$(document).ready(function() {
	if (Academy.pageType == "team")
		Academy.initTeam();
	if (Academy.pageType == "home") 
		Academy.initHome();
	
	Academy.Navigation.apply();
	Academy.topLockFlash();
});


var Academy = new function() {

	// private vars
	var path = "/nikefootball/assets/academy/";
	var defaultDate = "(DD/MM/YYYY)";
	
	// public vars
	var pageType = this.pageType = "";

	/**
	* Initialise Home page
	*/
	var initHome = this.initHome = function() {
		
		$('a.btnSignUp').click(function() { 
			var modalSettings = { 
				type: "register",
				url: $(this).attr("href")
			};
			createModal(this, modalSettings);
			return false;
		});
		
		/*$('#btnRegister').live("click", function() { 
			$("#formRegister").submit();
			return false;
		});*/
		
		$('#tags li.hide').hide();
		$('a.tagsMore').toggle(
			function() {
				$('#tags li.hide').fadeIn();
				$(this).removeClass('arrowDown').addClass('arrowUp').text('LESS');
				return false;
			},
			function() {
				$('#tags li.hide').hide();
				$(this).removeClass('arrowUp').addClass('arrowDown').text('MORE');
				return false;
			}
		);
	};
	
	/**
	* Initialise Team page
	*/
	var initTeam = this.initTeam = function() {
		$('a.viewProfile').addClass("hideViewProfile");
		
		embedFlash('/nikefootball/global/swf/campaigns/academy/hero/', 'AcademyHero.swf');
		
		// Hover popout effect
		$("ul#team li").hover(
			function () {
				// Only create & append html popup on first load
				var objLi = $(this);
				if (objLi.find("span.popout img").length == 0) {
					var htmlStr = "<span class='popout'>"
									+ "<img src='" + objLi.children("img").attr("src") + "' width='147' height='164' />"
									+ "<p><strong>" + objLi.find("strong").text() + "</strong></p>"
									+ "<p><a href='" + objLi.find("a.viewProfile").attr("href") + "' class='modalProfile iconProfile'>" 
									+ objLi.find("a.viewProfile").text() + "</a></p>"
									+ "</span>";
					objLi.find("a.viewProfile").replaceWith(htmlStr).hide();
					
					// View profile modal 
					objLi.find("span.popout").click(function() { 
						var modalSettings = { 
							type: "team",
							url: $(this).find("a.modalProfile").attr("href")
						};
						createModal(this, modalSettings);
					});
					objLi.find("a.modalProfile").click(function() {
						objLi.find("span.popout").click();
						return false;
					});
				}
				
				// Browser specific conditional comments - IE or other browsers (source: see http://javascriptkit.com/javatutors/conditionalcompile.shtml)
				/*@cc_on
					/*@if (@_jscript_version >= 5)
						objLi.removeClass("zindexOff").addClass("zindexOn");
						//objLi.find("span.popout").addClass("popoutIE").fadeIn("fast", function() { $(this).removeClass("popoutIE"); } );
						objLi.find("span.popout").show();
					@else @*/
						objLi.find("span.popout").fadeIn("fast");
					/*@end
				@*/
			}, 
			function () {
				var objLi = $(this);
				/*@cc_on
					/*@if (@_jscript_version >= 5)
						objLi.removeClass("zindexOn").removeClass("zindexOn").addClass("zindexOff");
						//objLi.find("span.popout").addClass("popoutIE").fadeOut("fast",function() { $(this).removeClass("popoutIE"); } );
						objLi.find("span.popout").hide();
					@else @*/
						objLi.find("span.popout").fadeOut();
					/*@end
				@*/
			}
		);		
	};
	
	var embedFlash = this.embedFlash = function(path, swfFile) {
		var search = window.location.search;
		var locale = "";
		var deepLink = "";
		if( search.indexOf( "locale=" ) > -1 ) {
			var locale = search.substring( search.indexOf( "locale=" ) + "locale=".length, search.length );
	
			if( locale.indexOf( "&" ) > -1 )
				locale = locale.split( "&" )[ 0 ];
		}
		
		if( search.indexOf( "deepLink=" ) > -1 )
		{
			deepLink = search.substring( search.indexOf( "deepLink=" ) + "deepLink=".length, search.length );
	
			if( deepLink.indexOf( "&" ) > -1 )
				deepLink = deepLink.split( "&" )[ 0 ];
		}
		
		if( locale == "" ) {
			locale = "en_GB";
		}
		var flashvars = {
			locale: locale,
			deepLink: deepLink,
			debug: "true"
		};
		var params = {
			base: path,
			wmode: "transparent"
		};
		var attributes = {
		  id: "academyHero",
		  name: "academyHero"
		};
		
		swfobject.embedSWF(path + swfFile, "flash", "910", "550", "9.0.0","expressInstall.swf", flashvars, params, attributes);

	};
	
	/*
	* Create modal window function (for both register and profile pages)
	 */ 
	var createModal = this.createModal = function(obj, settings) {
		// Call external interface to stop flash animation if on team page
		if (Academy.pageType == "team") {
			var flashHero = getFlash("academyHero");
			//flashHero.sendToActionscript("stop");
		}
		
		// Create html and append to document
		$('body').append(
			'<div id="modalOverlay"></div>' + 
			'<div id="modalContainer"><div id="modalOuter">' + 
			'<div id="modalTop"></div>' +
			'<div id="modalInner"><a id="modalClose" href="#close">Close</a>' + '</div>' +
			'<div id="modalBase"></div>' + 
			'</div></div>');
		
		// Do ajax request to get relevant page
		/*$.ajax({
			type: "GET",
			url: settings.url,
			success: function(html) {
				$("#modalInner").append($("#modalInner", html));
				$('#modalClose').show();
				if (settings.type == "register") {
					// Initialise register form fields
					initForm();
					
					// Handle the form submit
					bindRegister();
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$("#modalInner").append(textStatus);
			}
		});*/
		
		// TEMPORARY STATIC SOLUTION
		var htmlModalContent = "";
		var playerid = getQuerystring("id", settings.url);
		htmlModalContent = $("#p"+playerid).html();
		$("#modalInner").append(htmlModalContent);
		//$("#modalClose").show();
		
		// Initialise modal overlay and positioning
		initModal();
		
		// If window was resized, calculate the new overlay dimensions
		$(window).resize(function() {
			initModal();
		});
		
		// Show modal
		$('#modalOverlay').fadeIn( function() {
			$('#modalContainer').slideDown();
		});
		
		// Capture close modal click events
		$('#modalOverlay').click(function() {
			$('#modalClose').click();
		});
		$('#modalContainer').click(function() {
			$('#modalClose').click();
		});
		$('#modalOuter').click(function() {
			return false;
		});
		$('#modalInner').click(function() {
			return true;
		});
		
		setTimeout(function() {
			$("#modalInner #modalClose").click(function() {
				_closeModal();
				return false;
			});
		}, 500);
		
		$('#privacy').click(function() {
			window.open($(this).attr("href"));
			return false;
		});
	};
	
	/**
	 * Initialise register form
	 */
	var initForm = function() {
		var inputDob = $("#formRegister input#dob");
		$(inputDob).data("defaultValue", defaultDate);
					
		/* Remove prepopulated value from input field on focus */
		$("#formRegister input#dob").focus(function(){
			$(this).removeClass("default");
			if ($(this).attr("value") == defaultDate) {
				$(this).attr("value", "");
			}
			else {
				this.select();
			}
		});

		/* Reset input field with prepopulated value on blur */
		$("#formRegister input#dob").blur(function(){
			if ($(this).attr("value") == "") {
				$(this).attr("value", defaultDate);
				$(this).addClass("default");
			}
		});
	}
	
	/**
	 * Bind register form
	 */
	var bindRegister = function() {
		$("#formRegister").submit(function() {
			var validFields = false;
			var postAction = $(this).attr("action");
			var txtEmail = $("#email:input").attr("value");
			var txtDob = $("#dob:input").attr("value");
			var errEmail = $("#errEmail");
			var errDob = $("#errDob");
			errEmail.empty();
			errDob.empty();
			
			if (txtEmail == "") {
				errEmail.append("<span class='error'>Missing email</span>");
			}
			else if (!isEmail(txtEmail)) {
				errEmail.html("<span class='error'>Invalid email</span>");
			}
			else if ($("#dob:input").data("defaultValue") == $("#dob:input").attr("value")) {
				errDob.append("<span class='error'>Missing date of birth</span>");
			}
			else if (!isDob(txtDob)) {
				errDob.append("<span class='error'>Invalid date of birth</span>");
			}
			else {
				validFields = true;
			}
			
			if (validFields) {
				$.ajax({
					type: "POST",
					url: postAction,
					data: "email=" + txtEmail + "&dateOfBirth=" + txtDob,
					success: function(html) {
						$("#modalInner").html($("#modalInner", html));
						initForm();
						bindRegister();
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						$("#modalInner").html(textStatus);
					}
				});
			}
			else {
				bindRegister();
			}
			return false;
		});
	};
	
	/**
	  * Email validation regex 
	  */
	var isEmail = function(text) {
		return /[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,4}/.test(text);
	};
	
	var isDob = function(text) {
		return /[0-3]\d\/[01]\d\/(19|20)\d\d/.test(text);
	};
	
	/**
	 * Remove modal markup
	 */
	var _closeModal = function(pageType) {
		$('#modalContainer').fadeOut( function() { $(this).remove(); });
		$('#modalOverlay').fadeOut( function() { $(this).remove(); });
		
		// Restart flash animation if on team page
		if (Academy.pageType == "team") {
			var flashHero = getFlash("academyHero");
			//flashHero.sendToActionscript("start");
			//alert(flashHero);
		}
	};

	/**
	 * Initialise modal overlay and window position 
	 */
	var initModal = function() {
		// Get page size & set modal overlay size
		var arrPageSizes = _getPageSize();
		$('#modalOverlay').css({
			width:		arrPageSizes[0],
			height:		arrPageSizes[1]
		});
		
		// Get page scroll & set modal position
		var arrPageScroll = _getPageScroll();
		
		// Calculate top and left offset for the modal div object and show it
		$('#modalContainer').css({
			top:	arrPageScroll[1] + (arrPageSizes[3] / 5),
			left:	arrPageScroll[0]
		});
	};
	
	/**
	 * getPageSize() by quirksmode.com
	 *
	 * @return Array Return an array with page width, height and window width, height
	 */
	var _getPageSize = function() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};
	
	/**
	 * getPageScroll() by quirksmode.com
	 *
	 * @return Array Return an array with x,y page scroll values.
	 */
	var	_getPageScroll = function() {
		var xScroll, yScroll;
		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;	
		}
		arrayPageScroll = new Array(xScroll,yScroll);
		return arrayPageScroll;
	};
	
	// Function to get querystring parameter in passed url 
	var getQuerystring = function(key, url) {
		//if (default_==null) default_="";
		//	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
		var qs = regex.exec(url);

		if(qs == null)
			return false;
		else
			return qs[1];
	} 
	
	/**
	 * FLASH EXTERNAL INTERFACE FUNCTIONS
	 */
	var openPlayerModal = this.openPlayerModal = function(id) {
		var modalSettings = { 
			type: "team",
			url: "viewPlayer?id=" + id
		};
		createModal(this, modalSettings);
	};
	
	var getFlash = this.getFlash = function(movieName) {
		// Grab flash obj for external interface communication
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return window[movieName];
		}
		else {
			return document[movieName];
		}
	};
	
	/**
	 * TRACKING
	 */
	var Tracking = this.Tracking = new function() {
        this.apply = function() {
			
        }
    };
	
	/**
	 * NIKEOS NAVIGATION
	 */
	var Navigation = this.Navigation = new function() {
		this.apply = function() {
			var minimumFlashVersion = 9;
			if(typeof(swfobject) != 'undefined' && swfobject.getFlashPlayerVersion().major >= minimumFlashVersion && location.search.indexOf('noFlash=true') == -1) {
				if (typeof(GLOBAL_VARIABLES) != 'undefined') {
					var flashVars = {
						id: 'site',
						stylePath: '/nikefootball/global/xml/style.xml',
						fontPath: '/nikeos/global/modules/nav/v1/font/fontlibrary.swf',
						configPath: GLOBAL_VARIABLES.site_path,
						siteHost: GLOBAL_VARIABLES.siteHost,
						lang_locale: GLOBAL_VARIABLES.locale,
						current_url: escape(location.href)
						//trackerObject: tracking.flash(nav_tracker_obj)
					};
					
					var flashParams = {
						quality: 'best',
						wmode: 'transparent',
						scale: 'noscale',
						menu: 'false',
						allowScriptAccess: 'always',
						salign: 'tl',
						name: 'site'
					};

					var flashAttributes = {};
					swfobject.embedSWF('/nikeos/global/modules/nav/v1/swf/nav-module-top-1-2.swf', 'site', '300', '65', '9', '', flashVars, flashParams, flashAttributes);	     
					
					var currentUrl = window.location.href;
					var currentUrlArr = currentUrl.split("/");
					var currentNav = currentUrlArr[currentUrlArr.length - 1];
					flashVars = {
						id: 'nav',
						trackerObject: '',
						stylePath: '/nikefootball/global/xml/style.xml',
						fontPath: '/nikeos/global/modules/nav/v1/font/fontlibrary.swf',
						configPath: GLOBAL_VARIABLES.nav_path,
						navXML: innerXHTML('nav', true),
                        currentUrl: escape(document.location.href),
						currentNav: currentNav
					};
					
					flashParams = {
						quality: 'best',
						wmode: 'transparent',
						scale: 'noscale',
						salign: 'tl',
						menu: 'false',
						allowScriptAccess: 'always',
						name: 'nav'
					};
					
					flashAttributes = {};
					swfobject.embedSWF("/nikeos/global/modules/nav/v1/swf/nav-module-menu-1-2.swf", "nav", "102", "616", "9", "", flashVars, flashParams, flashAttributes);
				}
			} else {
				//Re align the nav and remove the search
				$('#navigation').attr({'style': 'left: -91px; top: 96px;'});
				$('#search').attr({'style': 'display: none'});
				
				//Add a shadow to the first element of every second level nav item.
				var primary_buttons = $('.primaryButton');
				for(var i=0; i<primary_buttons.length; i++) {
					if(typeof($('.secondaryButton', primary_buttons[i])[0]) != 'undefined'){
						secondaryLinkLength = jQuery($('.secondaryButton', primary_buttons[i])).length;
						jQuery($('.secondaryButton', primary_buttons[i])[0]).addClass('first');
						jQuery($('.secondaryButton', primary_buttons[i])[secondaryLinkLength-1]).addClass('last');
					}
				}
				
				//Display the navigation
				$('#nav').attr({'style': 'visibility: visible;'});
				$('#topLock').attr({'style': 'visibility: visible;'});
			}	
		}
	};
	
	// TEMPORARY STATIC SOLUTION
	var topLockFlash = this.topLockFlash = function() {
		
		var deeplink = document.location.hash;
	    if (deeplink) {
	    		deeplink = deeplink.substr(1);
	    } else {
	    		deeplink = document.location.search;
	    		if (deeplink) deeplink = deeplink.substr(6);
	    }
	        
	    var flashVars = {
			id: "topLockNav",
			stylePath: "/nikefootball/global/xml/style.xml",
			fontPath: "/nikeos/global/modules/nav/v1/font/fontlibrary.swf",
			configPath: "/nikefootball/" + GLOBAL_VARIABLES.localeDir + "/xml/site.xml",
			siteHost: GLOBAL_VARIABLES.siteHost,
			lang_locale: GLOBAL_VARIABLES.locale,
			current_url: escape(location.href),
			trackerObject: tracking.flash(nav_tracker_obj),
			link: deeplink
		};
		
		var flashParams = {
			quality: "best",
			wmode: "transparent",
			scale: "noscale",
			menu: 'false',
			allowScriptAccess: "always",
			salign: "tl",
			name: "topLockNav"
		};
		
		var flashAttributes = {};
		swfobject.embedSWF("/nikeos/global/modules/nav/v1/swf/nav-module-top-1-2.swf", "topLockNav", "300", "65", "9", "", flashVars, flashParams, flashAttributes);	 
	};
};

function setMenuArea(id, width, height) {
	$("#" + id).width(width+'px').height(height+'px');
}

