﻿/// <reference path="jquery-1.4.2-vsdoc.js"/>

// Cufon replacement calls
Cufon.replace('.strapline'/*, #header .btn-register a'*/, { fontFamily: 'advent', fontSize: '27.6px', textShadow: '#628521 1px 1px' });
Cufon.replace('#header .btn-login', { fontFamily: 'advent', fontWeight: '900', fontSize: '20px' });
Cufon.replace('.prize-breakdown .strapline', { fontFamily: 'advent' });
Cufon.replace('.panel:not(.prize-breakdown):not(.news-feature) h2', { fontFamily: 'advent' });
Cufon.replace('.prize-breakdown h2', { fontFamily: 'advent', textShadow: '#161614 1px 1px' });
Cufon.replace('.main-heading h1, .question-panel h2, .feature-button strong, .featured h2', { fontFamily: 'advent', fontWeight: '900', textShadow: '#628521 1px 1px', color: '-linear-gradient(#fff, 0.58=#fff, 0.59=#d3d3d3, 0.75=#fff' });

// IE6 'shim' to enable ABBR element support
document.createElement("abbr");

// document ready event
$(document).ready(function ()
{
	// auto postback
	$('[class*=postback-]').each(function (i)
	{
		$(this).data('postback', $(this).attr('class').replace(/^.*?postback-([a-zA-Z0-9_-]+)(\s|\b)?.*$/, '$1'))
		.find('input, select, textarea').andSelf().change(function (e)
		{
			var btn = $('[id$=' + $(this).data('postback') + ']');

			$('<input type="hidden" id="' + btn.attr('id') + '" name="' + btn.attr('name') + '" value="' + btn.val() + '" />').appendTo(btn.parents('form'));

			btn.parents('form').submit();
		});
	});

	// homepage news feature js switcher
	$('.news-feature .tabs a').live('click', function (e)
	{
		e.preventDefault();

		$(this).closest('.content').load($(this).attr('href') + ' .news-feature .content > *');
	});

	// let CSS know javascript is present
	$('#page').removeClass('no-js').addClass('has-js');

	// opens external links
	$('#page').ayoExternalLinks();

	// labelToValue
	$('.l2v').ayoLabelToValue();

	// panel borders, corners and dropshadows
	$('.panel:not(.dialog):not(.vanilla)').ayoAddBorders();

	// apply bigLink
	$('.featured-cause').ayoBigLink();

	// flash panel
	//$('.blink').ayoBlink(4, 300);

	// auto tabbing of multipart fields
	//$('.form-row input[class*=multipart-]').ayoAutoTab();

	// ShowHide based on checked inputs
	$('input:radio[class*=show-], [class*=show-] > input:radio, input:checkbox[class*=show-], [class*=show-] > input:checkbox').ayoShowHide();

	// Validate
	$('input:text[class*=ashx(]')
	.each(function (i)
	{
		var tmp = this.className.replace(/^.*?ashx\((.+)\).*$/, '$1').split(/\s*?,\s*/);
		var handler = tmp[0];
		var param = tmp[1];

		var ico_valid = $.ayo.assetsRoot() + '/css/icons/led24/accept.png';
		var ico_invalid = $.ayo.assetsRoot() + '/css/icons/led24/cross.png';

		$(this)
		.data('handler', handler)
		.data('param', param)
		.data('validate', function (field, delay)
		{
			if (field.val() == field.data('value'))
			{
				return;
			}

			field.stop().clearQueue().animate({ validation: 0 }, delay, function ()
			{
				var field = $(this);
				var suffix = field.find('+ .suffix, + .suffix');

				if (suffix.length)
				{
					suffix.find('+ img.valid, + img.invalid').remove();
				}
				else
				{
					field.find('+ img.valid, + img.invalid').remove();
				}

				$.ajax({
					url: $.ayo.siteRoot() + '/handlers/' + field.data('handler') + '.ashx?' + field.data('param') + '=' + field.val(),
					dataType: 'text',
					context: field,
					success: function (msg)
					{
						msg = msg.split('|');

						if (msg[0] && msg[0] == 'true')
						{
							$('<img class="valid" title="' + (msg[1] || 'This field is valid') + '" src="' + ico_valid + '" />').insertAfter(this.find('+ .suffix').add(this).last());
						}
						else
						{
							$('<img class="invalid" title="' + (msg[1] || 'This field is invalid') + '" src="' + ico_invalid + '" />').insertAfter(this.find('+ .suffix').add(this).last());
						}

						field.data('value', this.val());
					}
				});
			});
		})
		.blur(function (e) { $(this).data('validate')($(this), 0) })
		.keyup(function (e) { $(this).data('validate')($(this), 1500) });
	});

	// login slider
	$('#header .login').each(function (i)
	{
		function slider(e)
		{
			e.preventDefault();

			var login = $(this).parents('.login');

			login.animate({
				top: (login.css('top') == '0px') ? '-' + $(this).siblings('form').css('position', 'static').height() + 'px' : '0px'
			}, 150, function ()
			{
				$(this)
				//.find('.txt:eq(0)').focus().end()
				.find('.btn-login').one('click', slider);
			});

			login = null;
			delete login;
		}

		var form = $(this).find('form');

		if (form.length)
		{
			$(this).css('top', '-' + form.css('position', 'static').height() + 'px')
			.find('.btn-login')
			.click(function (e) { e.preventDefault() })
			.one('click', slider);
		}
	});

	// confirm action
	$('.confirm-action')
	.each(function (i)
	{
		var confirmbutton = $(this);

		confirmbutton.click(function (e)
		{
			e.stopPropagation();
			e.preventDefault();
		})
		.qtip({
			content: $('<div><p class="confirm">Are you sure?</p></div>')
					.append($('<a class="btn-confirm" href="#confirm">Yes</a>').click(function (e)
					{
						e.preventDefault();
						confirmbutton.unbind('click').click();
					}))
					.append($('<a class="btn-cancel" href="#cancel">No</a>').click(function (e)
					{
						e.preventDefault();
					})),
			position: {
				corner: {
					target: 'topRight',
					tooltip: 'bottomLeft'
				},
				adjust: {
					screen: false,
					y: -6
				},
				container: ($.browser.msie && $.browser.version < 8) ? $(this).closest('fieldset') : false
			},
			style: {
				name: 'blue',
				tip: {
					corner: 'bottomLeft', size: { x: 8, y: 8 }
				},
				border: {
					width: 5,
					radius: 5
				},
				textAlign: 'left',
				fontSize: ($.browser.msie && $.browser.version < 8) ? '1.2em' : '1.5em',
				fontWeight: 'bold'
			},
			show: { when: { target: false, event: 'click' }, delay: 0, solo: true },
			hide: { when: { target: $('body'), event: 'click'} }
		});
	});

	// qTip Tooltips
	$('.help-tip')
	.each(function (i)
	{
		var content = $(this).html().replace(/^\s*?\(?(.*?)\)?\s*$/, '$1');

		var tip = $('<img alt="Help" height="16" width="16" src="' + $.ayo.assetsRoot() + '/css/icons/led24/help.png" />')
		.css({ 'vertical-align': 'top', 'cursor': 'help', 'position': 'relative' })
		.click(function (e)
		{
			e.stopPropagation();
			e.preventDefault();
		})
		.qtip({
			content: content,
			position: {
				corner: {
					target: 'topMiddle',
					tooltip: 'bottomMiddle'
				},
				adjust: {
					screen: true,
					y: -6
				},
				container: ($.browser.msie && $.browser.version < 8) ? $(this).parent() : false
			},
			style: {
				name: 'blue',
				tip: {
					corner: 'bottomMiddle', size: { x: 8, y: 8 }
				},
				border: {
					width: 5,
					radius: 5
				},
				textAlign: 'left',
				fontSize: ($.browser.msie && $.browser.version < 8) ? '1em' : '1.2em',
				fontWeight: 'bold'
			},
			show: { when: { event: 'mouseover' }, delay: 0, solo: true },
			hide: { when: { event: 'mouseout' }, delay: 500, fixed: true }
			/*,
			show: { when: { target: false, event: 'click' }, delay: 0, solo: true },
			hide: { when: { target: $('body'), event: 'click' } }*/
		});

		$(this).replaceWith(tip)
	});

	/*
	// fix flash z-index problem in ie6/ie7
	if ($.browser.msie && $.browser.version < 8)
	{
	$('.main-feature .flash').each(function (i)
	{
	var flashoffset = $(this).offset();
	var formoffset = $(this).parents('form').offset();

	$(this).parents('form').append($(this).css({ position: 'absolute', top: (flashoffset.top - formoffset.top) + 'px', left: (flashoffset.left - formoffset.left) + 'px', zIndex: '100' }));

	delete flashoffset, formoffset;
	});
	}
	*/

	// fix dropdowns z-index problem in ie6/ie7
	if ($.browser.msie && $.browser.version < 8)
	{
		$('#header .content .nav > ul > li').each(function (i)
		{
			var li = $(this);

			li.find('ul').each(function (i)
			{
				var navoffset = $(this).css({ top: '100%' }).offset();

				var headeroffset = $(this).parents('#header').offset();

				$(this).parents('#header').append($(this).addClass('dropdown').css({ position: 'absolute', top: (navoffset.top - headeroffset.top) + 'px', left: (navoffset.left - headeroffset.left) + 'px', zIndex: '100' }));

				$(this).mouseenter(function (e)
				{
					$(this).stop().clearQueue().show();
				})
				.mouseleave(function (e)
				{
					$(this).stop().clearQueue().animate({ 'dropdown': 0 }, 200, function () { $(this).hide() });
				});

				li.data('dropdown', $(this).hide());

				delete navoffset, headeroffset;
			});

			li.mouseenter(function (e)
			{
				$(this).data('dropdown').stop().clearQueue().show();
			})
			.mouseleave(function (e)
			{
				$(this).data('dropdown').stop().clearQueue().animate({ 'dropdown': 0 }, 200, function () { $(this).hide() });
			});

			delete li;
		});
	}

	// accordian
	$('.accordian').each(function (i)
	{
		var link = $(this).find('dt a')

		link.click(function (e)
		{
			e.preventDefault();

			var speed = ($.browser.msie & $.browser.version < 7) ? 0 : 300;

			$(this).closest('dt')
			.find('+ dd')
			.animate({
				height: 'toggle'
			}, speed, function () { $(this).parents('.panel').ayoUpdateBorders() })
			.siblings('dd')
			.slideUp(speed, function () { $(this).parents('.panel').ayoUpdateBorders() });
		})
		.each(function (i)
		{
			$('a[href=' + $(this).attr('href') + ']').not(this)
			.data('accordian-link', $(this))
			.click(function (e)
			{
				e.preventDefault();

				$(this).data('accordian-link').click();
			});
		});

		delete link;
	});

	// Date Picker
	$.datepicker.setDefaults(
	{
		buttonImage: $.ayo.assetsRoot() + '/css/icons/silk/calendar_edit.png',
		buttonImageOnly: true,
		showOn: 'button',
		dateFormat: 'dd/mm/yy',
		defaultDate: '+0',
		//yearRange: '1900:2050',
		yearRange: '-10:+5', // from now until 5 years in the future
		minDate: '-10y',
		maxDate: '+5y',
		changeMonth: true,
		changeYear: true,
		duration: '', // show immediatley
		onChangeMonthYear: function (y, m, jq)
		{
			if (jq.currentDay)
			{
				$(this).datepicker('setDate', $.datepicker.parseDate('d/m/yy', jq.currentDay + '/' + m + '/' + y));
			}
		},
		onSelect: function (dateText, inst) { $(this).removeClass('l2v-added') }
	});

	//$('.short-date').datepicker({ showOn: 'focus' });
	$('.short-date').datepicker();

	// slideshow
	$('ul.slideshow').imageSlider(0, 7000, function (target)
	{
		if (target.is('.video'))
		{
			/*if (!!document.createElement('video').canPlayType)
			{
				var video = target.find('video');

				if (video.length)
				{
					video[0].play();
				}
			}*/
		}
		else
		{
			if (!!document.createElement('video').canPlayType)
			{
				var video = target.siblings('li').find('video');

				if (video.length && !video[0].paused)
				{
					video[0].pause();
					video[0].currentTime = 0;
				}
			}
		}
	});

	// lucky dip
	$('div.form-row.lucky-dip').each(function (i)
	{
		$(this).find('input:radio').click(function (e)
		{
			var selects = $(this).closest('fieldset').find('select');
			selects.siblings('strong.lucky-dip').remove();

			switch (this.value)
			{
				case 'True':
					selects.hide();
					$('<strong class="lucky-dip">Lucky Dip</strong>').insertAfter(selects);
					break;

				case 'False':
				default:
					selects.show();
					break;
			}

			selects = null;
			delete selects;
		})
		.filter('input:checked')
		.click();
	});
});

$.fn.imageSlider = function (select, delay, callback)
{
	var self = this;
	var delay = delay || 7000;

	self.each(function (i)
	{
		var self = $(this);
		var width = 0;
		var nav = $('<ul class="slider-nav"/>');
		var intv = setTimeout(resetSlideshow, 7000);

		function nextImage()
		{
			var next = nav.find('li.current').next('li:not(.next)');

			next.length ? next.click() : nav.find('li:eq(1)').click();
		}

		function prevImage()
		{
			var prev = nav.find('li.current').prev('li:not(.prev)');

			prev.length ? prev.click() : nav.find('li:last-child').prev('li').click();
		}

		function resetSlideshow()
		{
			clearInterval(intv);

			intv = setInterval(nextImage, delay);
		}

		self.find('li').each(function (i)
		{
			$(this).data('xOffset', width);

			width += $(this).width();

			nav.append($('<li class="' + ((i == 0) ? 'alpha current ' : '') + '"><span class="icon-' + (i % 4) + '">' + (i + 1) + '</span></li>')
			.click(function (e)
			{
				resetSlideshow();

				$(this).addClass('current').siblings('li').removeClass('current');

				var target = self.find('li:eq(' + i + ')');

				self.parent('.slider').animate(
                {
                	scrollLeft: target.length ? target.data('xOffset') : 0

                }, 300);

				if (callback) callback(target);
			}));
		}).end()
		.parent('.slider').css({ overflow: 'hidden', width: self.width() + 'px', height: self.height() + 'px' })
		.end()
		.width(width + 100); // the additional 'buffer' is for ie6 fix

		var next = $('<li class="next"><span>Next</span></li>').click(nextImage);
		var prev = $('<li class="prev"><span>Previous</span></li>').click(prevImage);

		self.closest('.content').append(nav.append(next).prepend(prev));

		if (select)
		{
			nav.find('li:eq(' + (select) + ')').click();
		}
	});
}

/*
jQuery.extend(jQuery.easing,
{
// t: current time, b: beginning value, c: change in value, d: duration
easeOutBounce: function (x, t, b, c, d)
{
if ((t /= d) < (1 / 2.75))
{
return c * (7.5625 * t * t) + b;
}
else if (t < (2 / 2.75))
{
return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
}
else if (t < (2.5 / 2.75))
{
return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
}
else
{
return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
}
}
});
*/
