var iOS = ($.os.name == 'ipad' || $.os.name == 'iphone')
var oiOS = { iRotatorLimit: 2, iRotatorSpeed: 6, iHomeRotatorLimit: 7, iHomeRotatorSpeed: 4 };

/* faq */
$(document).ready(function() {
	$('ol#faq>li').each(function(i, o) { $(this).attr('id', 'faq-' + i); });
	$('ol#faq-contents li a').each(function(i, o) { $(this).attr('href', '#faq-' + i); });
});

/* read more */
$(document).ready(function() {
	$('a[rel="read-more"]').each(function(i, o) {
		var p = $(o).closest('div')
		if ($(p).attr('id') == '') { $(p).attr('id', 'less_' + i) }

		var h = $(p).find('div.hide');
		if ($(h).attr('id') == '') { $(h).attr('id', 'more_' + i) }

		$(o).attr('href', '#' + $(h).attr('id'));
		$(o).click(function() { $(this).blur(); $(h).slideDown(200); $(o).fadeTo(200, 0); return false; })

		var c = $(h).find('a[rel="read-less"]');
		$(c).attr('href', '#' + $(p).attr('id'))
		$(c).click(function() { $(this).blur(); $(h).slideUp(200); $(o).fadeTo(200, 1); return false; })
	});
});


/* scroll */
$(document).ready(function() {
	$.localScroll({ duration: 1000, lazy: false, easing: 'swing' });
});

/*fixtures*/
var oFixtures = {

	GetFixtures: function(sXML) {
		this.AddSpinner();
		this.AddControls();
		$.get('/' + sXML, function(xml) { oFixtures.BuildFixtures(xml) })
	},

	BuildFixtures: function(xml) {
		try {
			var aoFixtures = [];
			$(xml).find('fixture').each(
				function() {
					var fixture = $(this);
					var sTitle = $(this).find('title').text();
					var sInfo = ($(this).find('info').text()).replace(/\n/g, '<br/>');
					var sDate = $(this).find('date').text();
					aoFixtures[aoFixtures.length] = '<li><div class="date">' + sDate + '</div><h4>' + sTitle + '</h4><p>' + sInfo + '</p></li>';
				}
			);
			$('#fixtures').append('<ol>' + aoFixtures.join('\n') + '</ol>');
			this.ShowFixtures();
		} catch (e) {
			return;
		}
	},

	Spinner: function(bShow) { bShow ? $('#fixtures .spinner').fadeIn(100) : $('#fixtures .spinner').fadeOut(1200); },
	ShowFixtures: function() { this.Spinner(false); },
	AddSpinner: function() { $('#fixtures').append('<div class="spinner"></div>'); },
	AddControls: function() {
		$('#control-previous').click(function() { $(this).blur(); oFixtures.Move(false); return false; })
		$('#control-next').click(function() { $(this).blur(); oFixtures.Move(true); return false; })
	},
	Move: function(bNext) {
		var sSelector = bNext ? 'first-child' : 'last-child';
		var sMove = $('#fixtures ol li:' + sSelector).html();
		$('#fixtures ol')[(bNext ? 'ap' : 'pre') + 'pend']('<li' + (bNext ? '' : ' style="width: 0;"') + '>' + sMove + '</li>');
		var iWidth = bNext ? 0 : $('#fixtures ol li:last-child').width();
		if (bNext) {
			$('#fixtures ol li:' + sSelector).fadeTo(150, 0, function() {
				$('#fixtures ol li:' + sSelector).animate({ width: iWidth }, 250, function() {
					$('#fixtures ol li:' + sSelector).remove()
				})
			});
		} else {
			$('#fixtures ol li:first-child').fadeTo(1, 0, function() {
				$('#fixtures ol li:first-child').animate({ width: iWidth }, 250, function() {
					$('#fixtures ol li:first-child').fadeTo(250, 1, function() {
						$('#fixtures ol li:' + sSelector).remove()
					})
				});
			});
		}
	}
}

$(document).ready(function() {
	if ($('#fixtures').length) {
		($('#three-d').length) ? oFixtures.GetFixtures('fixtures-3d.xml') : oFixtures.GetFixtures('fixtures.xml');
	}
});



/* FLASH THINGS */
$(document).ready(function() {
	if (!iOS) {
		oiOS.flashloading = true;
		/* Package movies */

		if ($('#package-movie').length && !$('#package-movie').hasClass('no-flash')) {
			swfobject.embedSWF('/graphics/content/package-movies/' + $('#placeholder').attr('title'), 'placeholder', "719", "274", "9.0.0", '', {}, { wmode: "opaque" });
		};

		/* HD movies */
		if ($('#hd-movie').length) {
			swfobject.embedSWF('/graphics/content/flash/' + $('#placeholder').attr('title'), 'placeholder', $('#placeholder img').width().toString(), $('#placeholder img').height().toString(), "9.0.0", '', {}, { wmode: "opaque" });
		};

		/* Home movie */
		if ($('#home #features').length) {
			swfobject.embedSWF('/graphics/content/flash/' + $('#placeholder').attr('title'), 'placeholder', $('#placeholder img').width().toString(), $('#placeholder img').height().toString(), "9.0.0", '', {}, { wmode: "opaque" });
		};
		
		/* Non-flash package movies */
		if ($('#package-movie.no-flash').length) {
			var o = $('#package-movie.no-flash');
			oiOS.keepLooking = null;
			
			$('#placeholder').addClass('absolute');
			
			$('#placeholder img').attr('data-order', 0);
			$('#placeholder img').attr('data-order-set', 0);
			
			var i = 0;
			
			while (i < 20) {
				i = i + 1;
				var oP = $('#placeholder img:first-child').clone()
				oP.removeAttr('data-order-set');
				oP.attr('src', oP.attr('src').replace(/[\d]*\.jpg$/i, i + '.jpg'));
				oP.attr('data-order', i);
				oP.load(function() {
					$(this).attr('data-order-set', $(this).attr('data-order'));
					oiOS.iLoaded++; oiOS.fRotate(oiOS.iLoaded == oiOS.iTotal);

					// The idea is that this shouldn't execute until they're all loaded because an incoming image will cancel this
					clearTimeout(oiOS.keepLooking);
					oiOS.keepLooking = setTimeout(function() { o.find('img[data-order]:not([data-order-set])').remove(); }, 3000);
					
				});
				$('#placeholder').prepend(oP);
			}
			
			oiOS.fRotate(true);
		}
	};
});

/* FLASH SUBSTITUTE */
$(document).ready(function() {
	if (oiOS.flashloading != true) {
		/* Package movies *//* HD movies *//* Home movie */
		// if it's the home-page, override the Rotator settings so we're only using one set of code
		/*if ($('#home #features').length) { oiOS.iRotatorLimit = oiOS.iHomeRotatorLimit; oiOS.iRotatorSpeed = oiOS.iHomeRotatorSpeed; }
		if ($('#package-movie').length || $('#hd-movie').length || $('#home #features').length) {*/
		if ($('#package-movie').length || $('#hd-movie').length) {
			oiOS.iLoaded = 0;
			$('#placeholder').addClass('absolute');
			for (var i = 1; i < oiOS.iRotatorLimit; i++) {
				var oP = $('#placeholder img:first-child').clone()
				oP.attr('src', oP.attr('src').replace(/[\d]?\.jpg$/i, (i + 1) + '.jpg'));
				//check for image loaded before setting interval
				oP.load(function() { oiOS.iLoaded++; oiOS.fRotate(oiOS.iLoaded == oiOS.iTotal); })
				$('#placeholder').prepend(oP);
			}
			oiOS.iTotal = $('#placeholder img').length - 1;
		};
	}
});

oiOS.fRotate = function(bGo) {
	if (!bGo) { return; }
	oiOS.imagerotator = setInterval(function() {
		$($('#placeholder img')[$('#placeholder img').length - 1]).fadeOut(2000, function() {
			$('#placeholder').prepend($($('#placeholder img')[$('#placeholder img').length - 1]))
			$($('#placeholder img')[0]).show();
		});
	}, oiOS.iRotatorSpeed * 1000);
};


/* FORM VALIDATION */
var ValidateForm = function(oForm) {
	var bValid = true;
	$(oForm).find('input.mandatory, select.mandatory, textarea.mandatory').each(function(i, o) {
		if ($(o).val() == '') { bValid = false; $('#error').html('Please complete all mandatory fields before continuing.'); return false; }
		if ($(o).attr('id').toLowerCase() == 'email') { if (!bValidEmail($(o).val())) { bValid = false; $('#error').html('The email address you supplied is invalid.'); return false; } }
	});
	return bValid;
}

var bValidEmail = function(sEmail) {
	var sMatch = sEmail.match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/)
	return (sMatch !== null);
}

$(document).ready(function() {
	$('form').each(function(i, o) {
		$(o).submit(function() { Skip(); return ValidateForm($(o)); })
		$(o).find('a.button[rel="submit"]').click(function() { $(o).submit(); return false; }); ;
	});
});

/* BDE */
var Skip = function() {
	var sCondition = 'BDE123';
	var sLocation = '/BDEDownloads';
	$('input[type="text"]').each(function(i, o) { if ($(o).val() == sCondition) { window.location = sLocation; } });
}

/* FORM REJECTION */
var ShowRejection = function(sReason) {
	switch (sReason) {
		case 'invalid-email':
			$('#error').html('The email address you supplied was invalid.');
			break;
		default:
			break;
	}
	return;
}

var RepopulateForm = function(sFields, sValues) {
	var asFields = sFields.split(',');
	var asValues = sValues.split(',');
	for (var i = 0; i < asFields.length; i++) {
		$('#' + asFields[i]).val(asValues[i]);
	}
}

$(document).ready(function() {
	if ($.query.get('reason') != '') {
		ShowRejection($.query.get('reason'));
		RepopulateForm($.query.get('fields'), $.query.get('values'));
	}
});

/* REFERENCE NUMBER */
$(document).ready(function() {
	if ($.query.get('reference') != '') {
		var sReferenceID = String($.query.get('reference'));
		while (sReferenceID.length < 9) { sReferenceID = '0' + sReferenceID; }
		$('#reference-number').append(sReferenceID);
	}
});

var oTrackPage = {
	'a[href="/Promos/MagicOfSky"]': 'Magic of Sky',
	'a[href="/Calculator"]': 'Calculator',
	'a[href="/graphics/content/flash/videos/august-on-sky.flv"': 'Season/August promo video'
}

$(document).ready(function() {
	var asLocation = String(window.location).split('http://').pop().split('/');
	asLocation.shift();
	var sLocation = '/' + asLocation.join('/');
	for (sTrack in oTrackPage) {
		$(sTrack).attr('track-event', oTrackPage[sTrack])
		$(sTrack).click(function() { pageTracker._trackEvent($(this).attr('track-event'), 'click', sLocation) });
	}
});

/* PRETTY PHOTO */
$(document).ready(function() {
	if (iOS) { $("a[href$='.flv']").each(function(i, o) { $(o).attr('href', $(o).attr('href').replace(/\.flv/, '.mp4')) }); }
	$("a[href$='.flv']").each(function(i, o) { $(o).attr('rel', 'prettyPhoto'); });
	$("a[rel^='prettyPhoto']").prettyPhoto();
});

$(document).ready(function() {
	$('#show_me').click(function() {
		$('.hide').show('slow');
	});
	$('#hide_me').click(function() {
		$('.hide').hide('slow');
	});
});

/* EXTERNAL LINKS */
$(document).ready(function() {
	
	$('a[href$=".pdf"]').attr('rel','external');
	
	$('a[rel="external"]').click(function(e){
		e.preventDefault();
		window.open($(this).attr('href'));
	});
});
