

// Set to true to see console output || false for no output
var debugMode = false;

/* ----------------------------------------
 * -- NAMESPACES --------------------------
 * ---------------------------------------- */

// Define the console object if not already there
if (console === undefined) {
	var console = {};
	console.log = console.warn
				= console.error
				= console.debug
				= console.info
				= console.trace
				= function () {};
}

// Define framework namespaces
var nf = nf || {};			// Nike Football
	nf.fw = nf.fw || {};	// Framework
	nf.gv = nf.gv || {};	// Global Variables

/* ----------------------------------------
 * -- GLOBAL VARIABLES --------------------
 * ---------------------------------------- */
 
// Could be used to set host information, currently blank so URLs should be /nikefootball/?
nf.gv.host = "";

// Has flash installed?
nf.gv.hasflash = swfobject.getFlashPlayerVersion();
if(nf.gv.hasflash.major === 0){
	nf.gv.hasflash = false;
} else {
	nf.gv.hasflash = true;
}

nf.gv.minipdp = null; // Used to store PDP information if applicable. Populated at ftl level

/* ----------------------------------------
 * -- TEMPORARY COMMERCE COOKIE CHECK -----
 * ---------------------------------------- */
if(!$.cookie('NIKE_COMMERCE_LANG_LOCALE') || !$.cookie('NIKE_COMMERCE_COUNTRY')){
	var modQuery = window.location.search;
	if(window.location.search.indexOf("&") != -1){
		var curLocale = modQuery.substring(modQuery.indexOf("locale"),modQuery.indexOf("&"));
		modQuery = modQuery.replace("?" + curLocale + "&", "?");
		modQuery = modQuery.replace("&" + curLocale, "");
	} else {
		var curLocale = modQuery.substring(modQuery.indexOf("locale"));
		modQuery = modQuery.replace("?" + curLocale, "");
	}
	window.location.href = "/nikeos/p/nikefootball/language_tunnel/?change&continueURL=" + window.location.pathname + encodeURIComponent(modQuery);
}

/* ----------------------------------------
 * -- FRAMEWORK ---------------------------
 * ---------------------------------------- */
nf.init = function(){

	// Configure content stub
	nf.fw.contentStub.init();
	
	// Configure video support
	nf.fw.videos.init();
	
	// Cufon
	nf.fw.cufon.init();
	
}
/* ----------------------------------------
 * -- TRACKING ----------------------------
 * ---------------------------------------- */
nf.fw.tracking = {
	
	tmp: null,
	
	init: function(){
	
		// Set up anchor tracking for swoosh lozenge, left navigation, login/out, and social links
		// tracker_obj.pageName taken from global variable set for dalewarth tracking script
		$("#p_lozenge a,#p_navigation a,#login a,#social a").click(function(){
		
			stringToTrack = tracker_obj.pageName + $(this).attr("data-tracking");
			
			// Set new props for this tracking call
			s.eVar13 = "Global navigation";
			s.prop3 = "Global navigation";
			s.s_objectID = stringToTrack;
			
			// Store old props with new temp object
			this.tmp = {};
			this.tmp.prop17 = s.prop17;
			this.tmp.prop18 = s.prop18;
			
			// Set new props for this tracking call
			s.prop17 = "nav";
			s.prop18 = "nav";
			
			// Call tracking object
			nf.fw.tracking.click(stringToTrack);
			
			// Reload old props & remove temp object
			s.prop17 = this.tmp.prop17;
			s.prop18 = this.tmp.prop18;
			this.tmp = null;
			
			// If link doesn't go anywhere abort
			if($(this).attr("href") == "#"){ return false; }
		
		});
		
		// Set up anchor tracking for commerce links
		// tracker_obj.pageName taken from global variable set for dalewarth tracking script
		$("div.commerceinner a").click(function(){
		
			stringToTrack = tracker_obj.pageName + ">" + $(this).attr("data-tracking");
			
			// Set new props for this tracking call
			s.eVar13 = "Global commerce";
			s.prop3 = "Global commerce";
			s.s_objectID = stringToTrack;
			
			// Call tracking object
			nf.fw.tracking.click(stringToTrack);
			
			// If link doesn't go anywhere abort
			if($(this).attr("href") == "#"){ return false; }
		
		});
		
		// Set up anchor tracking for footer links
		// tracker_obj.pageName taken from global variable set for dalewarth tracking script
		$("div.footercontainer a").click(function(){
		
			stringToTrack = tracker_obj.pageName + ">" + $(this).attr("data-tracking");
			
			// Set new props for this tracking call
			s.eVar13 = "Global footer";
			s.prop3 = "Global footer";
			s.s_objectID = stringToTrack;
			
			// Call tracking object
			nf.fw.tracking.click(stringToTrack);
			
			// If link doesn't go anywhere abort
			if($(this).attr("href") == "#"){ return false; }
		
		});
		
		
		if(debugMode){
			console.log("-- MSG -- Tracking initialised & framework anchors configured");
		}
		
	},
	
	// Fired on page loaded if required
	page: function(string){
		if(nf.gv.trackingEnabled == true){
			tracking.click(string);
		}
		
		if(debugMode){
			console.log("-- EVT ---- Tracking page event");
		}
		
	},

	// Fired on CTA clicks
	click: function(string){
		if(nf.gv.trackingEnabled == true){
			tracking.click(string);
		}
		
		if(debugMode){
			console.log("-- EVT ---- Tracking click event");
		}
		
	},

	// Fired when content is changed without reload of page i.e. ajax, tabs
	view: function(string){
		if(nf.gv.trackingEnabled == true){
			tracking.click(string);
		}
		
		if(debugMode){
			console.log("-- EVT ---- Tracking view event");
		}
		
	},

	// Fired when overlays are displayed
	overlay: function(string){
		if(nf.gv.trackingEnabled == true){
			tracking.click(string);
		}
		
		if(debugMode){
			console.log("-- EVT ---- Tracking overlay event");
		}
		
	}
	
}
/* ----------------------------------------
 * -- CONTENT STUB ------------------------
 * ---------------------------------------- */
nf.fw.contentStub = {
	
	init: function(){
		this.moveStub();
	},
	
	moveStub: function(){
	
		$("#p_innerwrapperfooter").prepend($("#p_contentstub"));
		
		$.each($("div#p_contentstub>div"), function(index){

			var precontent = $(this).find(">*");
			if(precontent[0]){
				if(precontent[0].tagName.toUpperCase() == "P"){
					var postcontent = precontent.slice(0,precontent.length);
					
					var left = postcontent.slice(0,((postcontent.length/2)));
					var right = postcontent.slice(left.length, postcontent.length);
					
					var leftcount = 0;
					var rightcount = 0;
					
					$.each(left, function(){
						leftcount = parseInt(leftcount) + parseInt($(this).html().length);
					});
					$.each(right, function(){
						rightcount = parseInt(rightcount) + parseInt($(this).html().length);
					});
					
					if(leftcount < rightcount){
						left = postcontent.slice(0,((postcontent.length/2)+1));
						right = postcontent.slice(left.length, postcontent.length);
					}
				
					$(this).empty();
					$(this).append('<div class="leftcol"></div><div class="rightcol"></div>');
					
					for(i=0;i<left.length;i++){
						$(this).find("div.leftcol").append(left[i]);
					}
					for(i=0;i<right.length;i++){
						$(this).find("div.rightcol").append(right[i]);
					}
				}
			}
		});
		
		if(debugMode){
			console.log("-- MSG -- Content stub moved");
		}
		
		this.addTracking();
	
	},
	
	addTracking: function(){
		
		// Set up anchor tracking for content stub links
		// tracker_obj.pageName taken from global variable set for dalewarth tracking script
		$("#p_contentstub a").click(function(){
			
			// Set new props for this tracking call
			s.eVar13 = "Content stub";
			s.prop3 = "Content stub";
			
			// Call tracking object passing "content_stub" prefix, anchor text, converted to lower case and with spaces replaced by underscores
			nf.fw.tracking.click(tracker_obj.pageName + ">content_stub>" + $(this).text().toLowerCase().replace(" ","_"));
			
			// If link doesn't go anywhere abort
			if($(this).attr("href") == "#"){ return false; }
		
		});
		
		if(debugMode){
			console.log("-- MSG -- Tracking added to content stub anchors");
		}
		
	}
	
}
/* ----------------------------------------
 * -- HTML5 VIDEO WITH FLASH FALLBACK -----
 * ---------------------------------------- */
nf.fw.videos = {

	init: function(){
		
		this.supportsHTMLVideo();
		
		/*if((!nf.gv.supportsHTMLVideo)){
		// IE can not handle a request to get a non-supported tag, therefore we use the div wrapper instead
		$.each($(".videotagcontainer"), function(index, item){
			nf.fw.videos.setUpVideoPlaceHolder(item);
		});
		}*/
		
	},
	
	supportsHTMLVideo: function(){

		nf.gv.supportsHTMLVideo = false;
		
		/*
			var v = document.createElement("video");
			if((!v.play)){
				nf.gv.supportsHTMLVideo = false;
			} else {
				nf.gv.supportsHTMLVideo = true;
			}
		*/
		
		if(debugMode){
			console.log("-- MSG -- Video support determined");
		}
		
	},

	showVideoInOverlay: function(guid, options){
	
		// Add container for simple video overlays
		$("body").append('<div id="p_overlaycontainer"></div><div id="p_overlayvideo"><span id="p_video"></span><span id="p_closeoverlay" title="' + nf.gv.modals.global.close + '"></span></div>');
		$("#p_closeoverlay").click(function(evt){
			nf.fw.videos.hideVideoOverlay();
		});
		if($.browser.version.indexOf("6.") != -1){
			$("#p_overlaycontainer").addClass('close').click(function(evt){
				nf.fw.videos.hideVideoOverlay();
			});
		}
		$("#p_overlayvideo").hide();
		
		if (nf.gv.supportsHTMLVideo) {
			// embed HTML video
			this.injectHtmlVideo("p_video", guid);
		} else {
			// use flash video player
			if (options) {
				// Option to use the old Odaptor video player
				if (options.useOld) {
					this.injectFlashVideo("p_video", guid);
				}
				else {
					if (options.width && options.height) { 
						$("#p_video").videoplayer({guid: guid, locale: nf.gv.locale, width: options.width, height: options.height});						
						// test guid 74d32089-43d0-fa57-b00a-35ca690fa341
					}
				}
			}
			else { // Default to using Brightcove video player at full 908px width
				$("#p_video").videoplayer({guid: guid, locale: nf.gv.locale});
			}
		}
		
		this.placement();
		
		$("#p_overlaycontainer").fadeTo("slow", 0.6);
		$("#p_overlayvideo").fadeTo("slow", 1);
		
		
		//var info = $(container).find("span");
		//nf.fw.videos.injectFlashVideo(info[0].innerHTML,info[1].innerHTML);
		// TODO: inject HTML controls
		
		if(debugMode){
			console.log("-- EVT ---- Showing video in overlay");
		}
		
	},
	
	showBCVideoInOverlay: function(guid){
	
		// Add container for simple video overlays
		$("body").append('<div id="p_overlaycontainer"></div><div id="p_overlayvideo"><span id="p_video"></span><span id="p_closeoverlay" title="' + nf.gv.modals.global.close + '"></span></div>');
		$("#p_closeoverlay").click(function(evt){
			nf.fw.videos.hideVideoOverlay();
		});
		if($.browser.version.indexOf("6.") != -1){
			$("#p_overlaycontainer").addClass('close').click(function(evt){
				nf.fw.videos.hideVideoOverlay();
			});
		}
		$("#p_overlayvideo").hide();
		
		if (nf.gv.supportsHTMLVideo) {
			// embed HTML video
			this.injectHtmlVideo("p_video", guid);
		} else {
			// use flash video player
			$("#p_video").videoplayer({playerType: "homePlayer", guid: guid, locale: nf.gv.locale});
		}
		
		this.placement();
		
		$("#p_overlaycontainer").fadeTo("slow", 0.6);
		$("#p_overlayvideo").fadeTo("slow", 1);
		
		if(debugMode){
			console.log("-- EVT ---- Showing brightcove video in overlay");
		}
		
	},

	placement: function(){

		if($.browser.msie){
			if($.browser.version.indexOf("6.") != -1){
				$('html,body').animate({scrollTop: 0});
			}
		}
		$("#p_overlaycontainer").css({
			"height" : $("body").height()
		});
		$("#p_overlayvideo").css({
			"left" : ((($("body").width()-910)/2)+33)
		});
		
		if(debugMode){
			console.log("-- MSG -- Video placement adjusted");
		}
		
	},

	hideVideoOverlay: function(){
		$("#p_overlayvideo").fadeTo("fast", 0);
		$("#p_overlaycontainer").fadeTo("slow", 0, function(){
			$("#p_overlaycontainer").remove();
			$("#p_overlayvideo").remove();
		});
		
		if(debugMode){
			console.log("-- EVT ---- Video overlay closed");
		}
		
	},
	
	injectHtmlVideo: function(moduleElement, guid){
		$(moduleElement).load('/nikefootball/assets/framework/v1/html/snippet-video.html .videoplayer');
		if(debugMode){
			console.log("-- MSG -- HTML video player initialised");
		}
	},

	injectFlashVideo: function(moduleElement, guid){
		
		//console.log(moduleElement);
		//console.log(guid);
		
		var flashVars = {};
		var flashParams = {};
		var flashAttributes = {};

		flashVars.locale = nf.gv.locale;
		
		flashParams.wmode = ($.browser.msie)? "window": "opaque";
		flashParams.scale = "noscale";
		flashParams.allowScriptAccess = "always";
		flashParams.allowFullScreen = "true";
		flashParams.bgColor = "#000000";

		// Video module specific
		var moduleWidth = "908";
		var moduleHeight = "510";
		
		var moduleSWF = "http://www.nike.com/nikeos/global/modules/video/v1/swf/video_player_v2_0.swf";
		
		/**
			IE8-specific workaround: IE8 will not play the video more than
			once. The issue has been narrowed to a problem retrieving
			the video data from the browser cache. Adding random number
			parameter to the swf to prevent caching.
		*/
		if($.browser.msie){
			if($.browser.version.indexOf("8.") != -1){
				moduleSWF = moduleSWF + "?rand=" + Math.floor(Math.random()*100000);
			}
		}

		flashVars.guid = guid;
		
		// replace __ with _
		flashVars.locale = nf.gv.locale.replace(/__/,"_");
		
		flashVars.regionConfig = "http://www.nike.com/nikeos/global/modules/video/v1/xml/reg/reg_config_" + nf.gv.locale.replace(/__/,"_") + ".xml";
		flashVars.siteConfig = "http://www.nike.com/nikefootball/global/xml/videoSiteConfig.xml";
		
		flashVars.currentUrl = escape(location.href);

		flashAttributes.id = moduleElement;
		flashAttributes.name = moduleElement;

		swfobject.embedSWF(moduleSWF, moduleElement, moduleWidth, moduleHeight, "9", flashParams.bgColor, flashVars, flashParams, flashAttributes);
	
		if(debugMode){
			console.log("-- MSG -- Flash video player initialised");
		}
	
	}
	
}
/* ----------------------------------------
 * -- MINI PDP ----------------------------
 * ---------------------------------------- */
nf.fw.minipdp = {

	commerceCountries: "GB|US|DK|FI|GR|HU|IE|IT|LU|NL|PL|PT|SI|ES|SE|CZ|DE|AT|CH|ES|FR|BE|PT|PL",
	thisCountry: $.cookie("NIKE_COMMERCE_COUNTRY"),

	init: function(containers){
		if(!(($.browser.msie) && ($.browser.version.substr(0,1)<7))){
			this.requiresPDPs();
			
			if((nf.gv.requiresPDPs == true) && (nf.gv.hasflash == true)){
				
				if(nf.fw.minipdp.commerceCountries.indexOf(nf.fw.minipdp.thisCountry) != -1){
					this.addPDPmarkers(containers);
				}
				
			}
		}
	},

	requiresPDPs: function(){
		if(nf.gv.minipdp != null){
			nf.gv.requiresPDPs = true;

			if(debugMode){
				console.log("-- MSG -- Mini PDP data detected");
			}
			
		} else {
			nf.gv.requiresPDPs = false;
			
			if(debugMode){
				console.log("-- MSG -- No Mini PDP data detected");
			}
			
		}
	},

	addPDPmarkers: function(parentContainers){
		// parentContainers : array of containers to inject each array of PDP markers

		$.each(parentContainers, function(index, item){

			var pdp = nf.gv.minipdp.data;
			
			for(i=0; i<pdp.length;i++){
				if(pdp[i].carousel == index){
					var data = nf.gv.minipdp.data[i];
					$(item).prepend('<span class="miniPDPmarker" data-shopids="miniPDP' + i + '|' + data.catalogId + '|' + data.productGroupId + '|' + data.productId + '" style="position:absolute; top:' + pdp[i].yPosition + 'px; left:' + pdp[i].xPosition + 'px; cursor:pointer;"><img src="/nikefootball/assets/framework/images/pdp-hotspot.png" alt="" width="30" height="30" data-tracking="' + data.uniqueTrackingCode + '" /></span>');
				}
			}
			
		});
		
		$("span.miniPDPmarker").click(function(evt){

			if($(this).closest('div.slide').length > 0){
				// check if pdp is within a carousel
				$('#carouselnav a.on').click();
			}

			if($(".miniPDP").length > 0){
				$(".miniPDP").remove();
			}
			var shopidsArray = $(this).attr("data-shopids").split("|");
			
			$(this).parent().prepend('<span id="' + shopidsArray[0] + '" style="position:absolute; z-index:150; top:' + nf.fw.minipdp.containPDPinGrid("top", $(this).position().top) + 'px; left:' + nf.fw.minipdp.containPDPinGrid("left", $(this).position().left) + 'px; width:320px; height:260px; overflow:hidden;" class="miniPDP"><span id="' + shopidsArray[0] + 'inner"></span></span>');
			nf.fw.minipdp.injectFlashMiniPDP(shopidsArray[0] + "inner", shopidsArray[1], shopidsArray[2], shopidsArray[3]);
		});
		
		// Add NikeOS EventBridge listeners to enable closing of PDP i.e. remove it from the DOM
		var customObject = {};
		customObject.handleEvent = function(evt){
			if(evt.data.id == "close"){
				//console.log(evt);
				$(".miniPDP").remove();
				
				
				if(debugMode){
					console.log("-- EVT ---- Mini PDP closed");
				}
				
			}
		}
		EventBridge.addListener("minipdpEventType", customObject, "handleEvent");
		
		if(debugMode){
			console.log("-- MSG -- Mini PDP markers added successfully");
		}
		
	},
	
	containPDPinGrid: function(boundry, position){
	
		// Dimensions for home page with 10px gutter - will need to pull these out to app level for other implementations
		minLeft = 10;
		minTop = 10;
		maxLeft = 898;
		maxTop = 574;
		
		// PDP width 320, height 260
		// Flash object overspill 228 - need to adjust right boundry to cater for this otherwise horizontal scroll bar appears
		
		// Check position is good...
		var result = position;
		switch(boundry){
			case "top":
			
				var h1 = (position-130);
				if(h1 < minTop){
					result = minTop;
				}
				var h2 = (position+130);
				if(h2 > maxTop){
					result = (maxTop-260);
				}
				
				if(result == position){
					result = (position-130);
				}
			
			break;
			case "left":
			
				var w1 = (position-160);
				if(w1 < minLeft){
					result = minLeft;
				}
				var w2 = (position+160);
				if(w2 > maxLeft){
					result = (maxLeft-320);
				}
				
				if(result == position){
					result = (position-160);
				}
			
			break;
		}
		
		return result;
	},

	injectFlashMiniPDP: function(moduleElement, catalogId, productGroupId, productId){

		//console.log(moduleElement);
		//console.log(guid);
		
		var flashVars = {};
		var flashParams = {};
		var flashAttributes = {};
		
		flashVars.locale = nf.gv.locale;
		
		flashParams.wmode = "transparent";
		flashParams.salign = "tl";
		flashParams.quality = "high";
		flashParams.scale = "noscale ";
		flashParams.allowScriptAccess = "always";
		flashParams.allowFullScreen = "false";
		flashParams.bgColor = "";
		
		var moduleWidth = "548";
		var moduleHeight = "401";
		
		var moduleSWF = "http://modules.nike.com/nikestore/modules/web/miniPDP.swf";
		
		// replace __ with _
		flashVars.locale = nf.gv.locale.replace(/__/,"_");
		
		flashVars.siteId = "28";
		flashVars.catalogId = catalogId;
		flashVars.country = nf.fw.minipdp.thisCountry;
		flashVars.lang_locale = $.cookie("NIKE_COMMERCE_LANG_LOCALE");//nf.gv.locale.replace(/__/,"_");
		flashVars.productGroupId = productGroupId;
		flashVars.productId = productId;
		flashVars.FQDN = "http://modules.nike.com";
		flashVars.configPath = "/nikefootball/content/framework/v1/modules/minipdp_config.xml";
		
		flashAttributes.id = moduleElement;
		flashAttributes.name = moduleElement;
		
		swfobject.embedSWF(moduleSWF, moduleElement, moduleWidth, moduleHeight, "9", flashParams.bgColor, flashVars, flashParams, flashAttributes);
		
		if(debugMode){
			console.log("-- MSG -- Mini PDP injected");
		}
		
	}
}
/* ----------------------------------------
 * -- FRAMEWORK NAVIGATION ----------------
 * ---------------------------------------- */
nf.fw.navigation = {
 	init: function(){
	
		// if not commerce mode, drop commerce nodes from the nav
		// duplicated from nikecommerce.js so we don't have to slow the page load
		if(nike_commerce.commerce_mode==0||nike_commerce.commerce_mode=='0'){
			$("#nav div[commerce_dependant='true']").remove();
			$("#nav div[id_dependant='true']").remove();
		}
		else if (nike_commerce.commerce_mode==3||nike_commerce.commerce_mode=='3') {
			$("#nav div[commerce_dependant='true']").remove();
		}
	
		var navXML = innerXHTML("nav",true);
		var siteXML = innerXHTML("site",true);
		
		/* Top Lock */
		var flashVars = {
			locale: nf.gv.locale,
			fontPath: "/nikeos/global/modules/nav/v1/font/fontlibrary.swf",
			currentUrl: location.href,
			stylePath: "/nikefootball/global/xml/style.xml",
			trackerObject: tracking.flash(nav_tracker_obj),
			siteXML: siteXML,
			id: "nav_module_top_swf"
		 };

		 var flashParams = {
			allowscriptaccess: "always",
			wmode: "transparent",
			scale: "noscale",
			salign: "tl",
			menu: "false",
			quality: "best",
			name: "nav-module-top_swf",
			id: "nav-module-top_swf",
			style: "width: 266px; height: 45px;"
		 };
		 var flashAttributes = {};

		swfobject.embedSWF("/nikeos/global/modules/nav/v1/swf/nav-module-top-1-2.swf", "nav-module-top_swf", "265", "61", "9", "#000000", flashVars, flashParams, flashAttributes);
		
		/* Left Navigation */
		var flashVars = {
			locale: nf.gv.locale,
			fontPath: "/nikeos/global/modules/nav/v1/font/fontlibrary.swf",
			currentUrl: location.href,
			stylePath: "/nikefootball/global/xml/style.xml",
			trackerObject: tracking.flash(nav_tracker_obj),
			siteXML: siteXML,
			currentNav: nf.gv.navigationItem,
			navXML: navXML,
			id: "nav_module_left_swf"
		 };

		 var flashParams = {
			allowscriptaccess: "always",
			wmode: "transparent",
			scale: "noscale",
			salign: "tl",
			menu: "false",
			quality: "best",
			name: "nav-module-left_swf",
			id: "nav-module-left_swf",
			style: "width: 102px; height: 677px;"
		 };
		 var flashAttributes = {};

		swfobject.embedSWF("/nikeos/global/modules/nav/v1/swf/nav-module-menu-1-2.swf", "nav-module-left_swf", "102", "650", "9", "#000000", flashVars, flashParams, flashAttributes);
		
	},
	
	init2: function(){
	
		/* SET UP COMPONENTS */
		$('#swoosh-flyout').hide();
		if(BrowserDetect.browser=='Firefox' && BrowserDetect.version < 3.6) $('#swoosh-flyout').css({'background-color': '#383838'});

		/* SWOOSH INTERACTIVITY */
		$("#swooshlozenge .swoosh a").click(function(){ nf.fw.navigation.openSwooshMenu(); });
		$("#swoosh-flyout a.close").click(function(){ nf.fw.navigation.closeSwooshMenu(); });
		$('#swoosh-flyout li.more a').click(function(){ nf.fw.navigation.openMoreMenu(); });
	
		/* SEARCH INTERACTIVITY */
		$("#leftnav a.search").click(function(){ nf.fw.navigation.openSearch(); });
		$("#leftnav .search-panel a.close").click(function(){ nf.fw.navigation.closeSearch(); });
		$("#leftnav #navsearch").submit(function(){ return nf.fw.navigation.submitSearch(); });

		/* SECOND LEVEL NAVIGATION */
		$('#leftnav > li > a:not(.nosubnav)').each(function(i, a){ nf.fw.navigation.configureSecondLevelMenuItem(a); });


		/* THIRD LEVEL NAVIGATION - FLYOUTS */
		$('#leftnav .second-level li a.has3rd').each(function(i, a){
			// collect the related third-level div in this fashion to avoid extra dom elements thrown in via cufon
			// perhaps we could keep live text for second-level links?

			var parentli = $(a).closest('li');
			if ($(parentli).length > 0) {
			
				var siblingthird = $(parentli).children('div.third-level')[0];
				/*var lastlink = $($(siblingthird)[0]).find('li:last a').focusout(function(){
					$(siblingthird).mouseleave();
				});*/
				
				$(a).mouseenter(function(){
					$(siblingthird).mouseenter();
				}).focus(function(){
					$(siblingthird).mouseenter();
				}).mouseleave(function(){
					$(siblingthird).mouseleave();
				});
				
				$(siblingthird).mouseenter(function(){
					$(a).addClass('on');
					$(this).show();
				}).mouseleave(function(){
					$(a).removeClass('on');
					$(this).hide();
				});
				
			}
			
		});
		
		/* PROFILE */
		$("#login .loggedinview").mouseenter(function(){ nf.fw.navigation.openProfile(); });
		$("#login .loggedinview").mouseleave(function(){ nf.fw.navigation.closeProfile(); });
		$("#userprofile a:last").click(function(){ nf.fw.navigation.logout(); return false; });
	},
	
	openSwooshMenu: function(){
		$("#swoosh-flyout").removeClass("hide");
		$("#swoosh-flyout").slideToggle();
		return false;
	},
	
	closeSwooshMenu: function(){
		$("#swoosh-flyout li.more a").fadeIn();
		$("#swoosh-flyout").slideToggle();
		$("#morelinks").hide();
		$("#swooshlozenge").removeClass("expanded");
	},
	
	openMoreMenu: function(){
		$("#swooshlozenge").addClass("expanded");
		$("#morelinks").slideToggle();
		$("#swoosh-flyout li.more a").fadeOut();
	},
	
	openSearch: function(){
		$('#leftnav .search-panel').show();
		$("#search-panel").focus();
		return false;
	},
	
	closeSearch: function(){
		$('#leftnav .search-panel').hide();
		return false;
	},
	
	submitSearch: function(){
		if($('#leftnav #navsearch').find("input[text]").val() != ""){
			return true;
		} else {
			return false;
		}
	},
	
	customSearch: function(text){
		$('#leftnav #navsearch').find("input[text]").val() = text;
		nf.fw.navigation.submitSearch();
	},
	
	configureSecondLevelMenuItem: function(a){
		var level2parent = $(a).closest('li'),
		level2 = $(a).siblings('div.second-level')[0];
		
		$(a).click(function(evt){ 
			// test href for a value of # - if present, this link won't trigger a page load
			if ($(this).attr('href') == '#'){
				
				if($(level2parent).is('.open')){
					// click will slide up
					nf.fw.navigation.closeMenuItem(level2, level2parent);
				} else {
					// click will slide down
					nf.fw.navigation.openMenuItem(level2, level2parent);
				}
				return false;
			}
		});
		
	},
	
	openMenuItem: function(level2, level2parent){
	
		if($("#leftnav li.open").length > 0){
			$.each($("#leftnav li.open > a"), function(i, a){
				var level2parent = $(a).closest('li'),
				level2 = $(a).siblings('div.second-level')[0];
				nf.fw.navigation.closeMenuItem(level2, level2parent);
			});
		}
	
		$(level2).slideDown();
		$(level2parent).addClass('open');
	},
	
	closeMenuItem: function(level2, level2parent){
		$(level2).slideUp(function(){
			$(level2parent).removeClass('open');
		});
	},
	
	flyOutMenu: function(){
		// not currently in use
	},
	
	setMenuItem: function(a){
		// when page is loaded open menu to correct place
		if($(a).parent().parent().attr("id") != "leftnav"){
			var level2parent = $(a).parent().parent().parent().parent(),
			level2 = $(a).parent().parent().parent();
			nf.fw.navigation.openMenuItem(level2, level2parent);
		} else if($(a).siblings('div.second-level').length > 0){
			var level2parent = $(a).closest('li'),
			level2 = $(a).siblings('div.second-level')[0];
			nf.fw.navigation.openMenuItem(level2, level2parent);
		}
		
		$(a).addClass("selected");
		
	},
	
	openProfile: function(){
		$("#userprofile").show();
	},
	
	closeProfile: function(){
		$("#userprofile").hide();
	},
	
	logout: function(){
		// delete cookies, function in global JS somewhere to copy or find service URL
		nf.fw.upmProfile.logOut();
		return false;
		
	}
 }
/* ----------------------------------------
 * -- COMMERCE - UPDATE SHOP BASKET -------
 * ---------------------------------------- */
nf.fw.commerce = {
	
	init: function(){
		
		switch(nike_commerce.commerce_mode){
			case 1:
				nf.gv.commerceEnabled = true;
				nf.gv.nikeIdEnabled = true;
			break;
			case 2:
				nf.gv.commerceEnabled = true;
				nf.gv.nikeIdEnabled = true;
			break;
			case 3:
				nf.gv.commerceEnabled = false;
				nf.gv.nikeIdEnabled = true;
			break;
			default:
				nf.gv.commerceEnabled = false;
				nf.gv.nikeIdEnabled = false;
		}
		this.setUpCommerceNavigation();
		this.setUpCommerceLozenge();
		
	},
	
	getBasketCount: function(){
		// call basket service
		
		/*
		nf.fw.services.getOrderDetails({
			callback: function(data) {
				console.log(data);
			}
		});
		
		
		var intervalKey = window.setInterval(function(){	
			window.clearInterval(intervalKey);
			var qty = 3;
			nf.fw.commerce.updateBasketCount(qty);
		}, 2000);
		*/
	},
	
	updateBasketCount: function(qty){
		
		// Update DOM element with passed value
		$("#p_commerce li.cart span").text(qty);
		nf.fw.cufon.refresh();
		
	},
	
	setUpCommerceNavigation: function(){
		if(!(nf.gv.commerceEnabled)){
			$("#shop").parent().remove();
		}
		if(!(nf.gv.nikeIdEnabled)){
			$("#nikeid").parent().remove();
		}
	},
	
	setUpCommerceLozenge: function(){
		if((nf.gv.commerceEnabled)){
			$("#p_commerce .commerceinner").css("visibility", "visible");
			nf.fw.commerce.getBasketCount();
		} else {
			$("#p_commerce .commerceinner ul").remove();
			$("#p_commerce").addClass("fixheight");
		}
	}
	
}

/* ----------------------------------------
 * -- UPM PROFILE -------------------------
 * ---------------------------------------- */
nf.fw.upmProfile = {
	
	logOut: function(){
		// Log user out of UPM
		nf.fw.services.logOut({
			callback: function(data) {
				//console.log(data);
				location.href = location.href;
			}
		});
		
	}	
}
/* ----------------------------------------
 * -- CUFON -------------------------------
 * ---------------------------------------- */
nf.fw.cufon = {
	
	fwHeader: "",
	fwBody: "",
	fwBrand: "#p_innerwrapperfooter li.brand a",
	fwButtons: "",
	fwGlobal: "#swooshlozenge a, #p_commerce .commerceinner a, #leftnav > li > a, #leftnav > li label a, #p_navigation div.third-level li h2, #login > li > a, #p_navigation dd a",
	
	init: function(){
		$(nf.fw.cufon.fwHeader).addClass("cfHeader");
		//$(nf.fw.cufon.fwHeaderLinks).addClass("cfHeaderLinks");
		$(nf.fw.cufon.fwBody).addClass("cfBody");
		$(nf.fw.cufon.fwBrand).addClass("cfBrand"); // Brand mostly set in CMS with inline <em class="cfBrand"></em>
		$(nf.fw.cufon.fwButtons).addClass("cfButtons");
		$(nf.fw.cufon.fwGlobal).addClass("cfGlobal");
		
		nf.fw.cufon.replace("header", "cfHeader");
		//nf.fw.cufon.replace("header", "cfHeaderLinks", {hover:true});
		nf.fw.cufon.replace("body", "cfBody");
		nf.fw.cufon.replace("brand", "cfBrand");
		nf.fw.cufon.replace("buttons", "cfButtons");
		nf.fw.cufon.replace("global", "cfGlobal");
		
	},
	
	replace: function(cssFontFamily, cssClass, cfOptions){
		if(nf.gv.useFontNames == true){
			var mergedFamily = eval("nf.gv.fonts." + cssFontFamily);
			Cufon.set("fontFamily", mergedFamily);
		} else {
			Cufon.set("fontFamily", cssFontFamily);
		}
		if(cfOptions != null){
			Cufon.replace("a." + cssClass, cfOptions);
		} else {
			Cufon.replace("a." + cssClass, { hover: !($.browser.msie) });
			Cufon.replace("." + cssClass);
		}
	},
	
	refresh: function(){
		nf.fw.cufon.replace("header", "cfHeader");
		//nf.fw.cufon.replace("header", "cfHeaderLinks", {hover:true});
		nf.fw.cufon.replace("body", "cfBody");
		nf.fw.cufon.replace("brand", "cfBrand");
		nf.fw.cufon.replace("buttons", "cfButtons");
		nf.fw.cufon.replace("global", "cfGlobal");
	}
	
}
// ----------------------------------------
// ----------------------------------------
// -- LEGACY CUFON ------------------------
// ----------------------------------------
// ----------------------------------------

// Set font family count to support single font locales (ja_JP, zh_HK, zh_CN etc)
// Font count is increased within each font file
Cufon.fontCount = 0;

// Cufon replacement method
nf.fw.cufonise = function (cufonData, fontFamilyBase) {
	if (cufonData === undefined || !cufonData) {
		return;
	}
	
	// If single font family detected change all calls to use header font
	if(Cufon.fontCount == 1){
		fontFamilyBase = "header";
	}

	if (nf.gv.textReplacement) {
		Cufon.set('fontFamily', fontFamilyBase);
		$.each(cufonData, function (idx, ele) {
			var selector = ele.selector;
			if (selector === undefined || !selector) {
				return;
			}
			if (ele.options === undefined || !ele.options) {
				Cufon.replace(selector);
			} else {
				Cufon.replace(selector, ele.options);
			}
		});
	}
}
/* ----------------------------------------
 * -- DOM READY ---------------------------
 * ---------------------------------------- */
$(function() {
	
	/* ----------------------------------------
	 * -- ADD CSS FLAG FOR SCRIPT SUPPORT -----
	 * ---------------------------------------- */
	$("body").addClass("jsison");
	
	/* ----------------------------------------
	 * -- ADD CSS FLAG FOR FLASH SUPPORT ------
	 * ---------------------------------------- */
	if(nf.gv.hasflash){
		$("body").addClass("hasflash");
	}
	
	/* ----------------------------------------
	 * -- INITIALISE THE FRAMEWORK ------------
	 * ---------------------------------------- */
	nf.init();
});


/* ----------------------------------------
 * -- PAGE LOAD ---------------------------
 * ---------------------------------------- */
$(window).load(function() {
	
	/* ----------------------------------------
	 * -- REMOVE NOSCRIPT TAGS ----------------
	 * ---------------------------------------- */
	$("noscript").remove();
	
	/* ----------------------------------------
	 * -- SET UP NAVIGATION -------------------
	 * ---------------------------------------- */
	nf.fw.navigation.init();
	//nf.fw.navigation.setMenuItem($("#" + nf.gv.navigationItem));
	
	/* ----------------------------------------
	 * -- ADD COMMERCE SUPPORT ----------------
	 * ---------------------------------------- */
	nf.fw.commerce.init();
	
	/* ----------------------------------------
	 * -- SET UP TRACKING ---------------------
	 * ---------------------------------------- */
	nf.fw.tracking.init();
	
	/* ----------------------------------------
	 * -- LANGUAGE TUNNEL CONTINUE URL --------
	 * ---------------------------------------- */
	var modQuery = window.location.search;
	if(window.location.search.indexOf("&") != -1){
		modQuery = modQuery.replace("?locale=" + nf.gv.locale + "&", "?");
		modQuery = modQuery.replace("&locale=" + nf.gv.locale, "");
	} else {
		modQuery = modQuery.replace("?locale=" + nf.gv.locale, "");
	}
	$.each($("a.p_continueurl"), function(index, item){
		$(item).attr("href", $(item).attr("href") + "&continueURL=" + window.location.pathname + encodeURIComponent(modQuery));
	});
	
	// Check if mini PDPs are needed and pass through container - should be application based not framework, included here for reference
	// nf.fw.minipdp.init($("div#hero-section div.btn-region"));
	
	// Call get country list service
	/*nf.fw.services.getCountryList({
		callback: function(data) {
			console.log(data);
			
		}
	});*/
	
	// Call get shorty service
	/*nf.fw.services.getShorty({
		longUrl: "http://www.nike.com/nikefootball/home/?locale=" + nf.gv.locale,
		callback: function(data) {
			console.log(data);
			
		}
	});*/
	
	// Call get rss feed service
	/*nf.fw.services.getRssFeed({
		rssFeedUrl: "http://twitter.com/statuses/user_timeline/41147159.json",
		callback: function(data) {
			console.log(data.data[0]);
		}
	});*/
	
});

/* ----------------------------------------
 * -- BROWSER RE-SIZED --------------------
 * ---------------------------------------- */
//
/*
 *  Resize event was being fired multiple times in IE6, even if the window was not being resized.
 *  Nick added a logic that checks if the window dimensions really changed.
*/
var windowSize = [$(window).width(),$(window).height()];
$(window).resize(function() {

	/* ----------------------------------------
	 * -- ADJUST VIDEO OVERLAY POSITION -------
	 * ---------------------------------------- */
	
	var newWindowSize = [$(window).width(),$(window).height()];
	if (windowSize[0] != newWindowSize[0] || windowSize[1] != newWindowSize[1]) {
		nf.fw.videos.placement();
		windowSize = newWindowSize;
	}
	
});

/* ----------------------------------------
 * -- PAGE UNLOAD -------------------------
 * ---------------------------------------- */
$(window).unload(function() {
	$("*").unbind();
	nf = null;						// Nike Football Namespace
	$ = null;						// JQuery
	JQ = null;						// JQuery
	jQuery = null;					// JQuery
	swfobject = null;				// SWFOject 2
	deconcept = null;				// SWFObject 1.5 override
	tracking = null;				// Framework Tracking Object
	NIKEOS = null;					// NIKEOS Object
	BrowserDetect = null;			// PPK browser detection
	EventBridge = null;				// Flash Event Bridge
	Cufon = null;					// Cufon
	CallbackManager = null;			// Proxy callback manager
	DaleWarth = null;				// Nike Tracking Object
	nike_commerce = null;			// Nike Commerce Object
	NIKE_COMMERCE_CONFIG = null;	// Nike Commerce Config Object
	s = null						// Omniture Tracking Object
	site_data = null;				// Nike site_data
	XMLHttpRequest = null;			// Destroy any outstanding AJAX calls
});

// GLOBAL NIKEOS NAMESPACE
if (!window.NIKEOS) var NIKEOS = {};


/**
	Code drawn from NIKEOS.global.js
*/

/* ARTICLE SHARE -- articleShare.js */
function articleShare(site, popUpUrl, title, description) {
    var repQ = /\?/;
    var encQ = '%3f';
    popUpUrl = popUpUrl.replace(repQ, encQ);

    switch (site) {
    case "digg":
        postPopUp('http://digg.com/remote-submit?phase=2&url=' + popUpUrl, 'digg', 'toolbar=0,status=0,height=450,width=650,scrollbars=yes,resizable=yes');
        break;
    case "delicious":
        postPopUp('http://del.icio.us/post?url=' + popUpUrl + '&title=' + title, 'delicious', 'toolbar=0,status=0,height=450,width=650,scrollbars=yes,resizable=yes');
        break;
    case "facebook":
        postPopUp('http://www.facebook.com/sharer.php?u=' + popUpUrl + '&t=' + title, 'facebook', 'toolbar=0,status=0,height=436,width=646,scrollbars=yes,resizable=yes');
        break;
    case "stumble":
        postPopUp('http://www.stumbleupon.com/submit?url=' + popUpUrl + '&title=' + title, 'stumble', 'toolbar=0,status=0,height=450,width=770,scrollbars=yes,resizable=yes');
        break;
    case "newsvine":
        postPopUp('http://www.newsvine.com/_tools/seed&save?u=' + popUpUrl + '&h=' + title, 'newsvine', 'toolbar=0,status=0,height=500,width=1000,scrollbars=yes,resizable=yes');
        break;
    };
};

/* ENABLEMENT -- enablement.js */

var enablementListener = {};
var http_request;

enablementListener.fileSave = function(event) {
    //window.open(event.data.url, event.data.target);
    window.open(event.data.url, "_self");
};

enablementListener.blogPrint = function(event) {
    //alert("opening print window");
    window.open(event.data.url, "_blank");
};

enablementListener.blogShare = function(event) {
    //alert("article enablement share: sn name: " + event.data.sn + ", url: " + event.data.url + ", title: " + event.data.title);
    articleShare(event.data.sn, event.data.url, event.data.title, event.data.title);
};

enablementListener.blogEmail = function(event) {
    //alert("blog email");
    http_request = null;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {}
        }
    }
    if (http_request != null) {
        var parameters = "?recipient=" + event.data.to + "&sender=" + event.data.from + "&message=" + event.data.message + "&language=" + event.data.language + "&country=" + event.data.country + "&link=" + event.data.link + "&title=" + event.data.title + "&brandName=" + event.data.brandName;
        var url = "http://cs.ny.rga.com/reboot/sendmailProxy.jsp";
        var urlParam = url + parameters;
        http_request.onreadystatechange = alertContents;
        http_request.open('GET', urlParam, true);
        http_request.send(null);
    } else {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
};

function alertContents() {
    if (xmlhttp.readyState == 4) {
        // 4 = "loaded"
        if (xmlhttp.status == 200) {
            // 200 = OK
            // ...our code here...
        }
    } else {
        alert("Problem retrieving XML data");
    }
}
EventBridge.addListener("blogprint", enablementListener, "blogPrint");
EventBridge.addListener("blogshare", enablementListener, "blogShare");
EventBridge.addListener("blogemail", enablementListener, "blogEmail");
EventBridge.addListener("filesave", enablementListener, "fileSave");

/* END ENABLEMENT */



function postPopUp(url, name, params) {
    var win = window.open(url, name, params);
};

/* END ARTICLE SHARE */

/**
	End of code drawn from NIKEOS.global.js
*/


/* INNER XHTML -- innerXHTML.js */
/*===================================================================*\
  innerXHTML

  Copyright (c) 2006 space150, LLC and released under the CPL license: 
		http://opensource.org/licenses/cpl1.0.php
\*===================================================================*/

function innerXHTML(obj, encode) {
  // It is an option to pass innerXHTML() a string indicating an id attribute
  if (typeof obj == "string") {
    obj = document.getElementById(obj);
  };
  

  
  var open = '';
  var content = '';
  var close = '';
  var tagname = obj.nodeName.toLowerCase();
  var emptytag = (obj.nodeName.match(/area|base|basefont|br|col|frame|hr|img|input|isindex|link|meta|param/i)) ? true : false; 

  // Write open tag
  open = '<'+tagname;
  for (var i=0; i<obj.attributes.length; i++) {
    if (obj.attributes[i].specified && obj.attributes[i].value != "null")
      open += ' '+obj.attributes[i].name.toLowerCase()+'="'+obj.attributes[i].value+'"';
  }
  open += (emptytag) ? ' />' : '>';

  if (!emptytag) {
    // Write tag content
    for (var i=0; i<obj.childNodes.length; i++) {
      var node = obj.childNodes[i];
      if (node.nodeType==3)
        content += node.data;
      else if (node.nodeType==1)
        content += innerXHTML(obj.childNodes[i], false);
      else
        content += " ";
    }

    // Write closing tag
    close = '</'+tagname+'>';
  }

	// URI encode the content if desired
  return (typeof(encode)=="undefined" || encode==true) ? encodeURIComponent(open+content+close) : open+content+close;
}


/* 
	NAVIGATION -- navigation.js 
	updated 10.09.08
*/
var navListener = new Object();
navListener.defaultSearchText = " ";
navListener.nullSearchText = "";

//console.log("check");

navListener.openURL = function(event){
	var target = "_self";
	if (event.data.target != "") {
		target = event.data.target;
	}
	window.open(event.data.href, target);
};


navListener.searchFocus = function(event) {
	navListener.navInput = document.getElementById('nav_input');

	setTimeout("navListener.navInput.focus()",25); 
	setTimeout("setCaretTo(navListener.navInput, 1000)");
};

navListener.searchOpen = function(event) {
	//console.log("search open");
	navListener.navInput = document.getElementById('nav_input');
	navListener.navForm = document.getElementById('nav_input_form');
	navListener.navForm.style.visibility='visible';
	navListener.navInput.style.visibility='visible';
	setTimeout("navListener.navInput.value = navListener.defaultSearchText",25); 
	setTimeout("navListener.navInput.select()",25); 
	setTimeout("navListener.navInput.value = navListener.nullSearchText",26); 
	setTimeout("setCaretTo(navListener.navInput, 1000)", 27);
};

navListener.searchClose = function(event) {
	//console.log("search close");
	setTimeout("navListener.navInput.value = navListener.nullSearchText",2); 
	setTimeout("navListener.navInput.blur()",3);
	setTimeout("navListener.navInput.style.visibility='hidden'",4); 
};

function search() {
	EventBridge.dispatchEvent({type:'moduleCall',data:encodeURIComponent(document.getElementById('nav_input').value)});
};

EventBridge.addListener("url", navListener, "openURL");
EventBridge.addListener("search", navListener, "openURL");
EventBridge.addListener("searchopen", navListener, "searchOpen");
EventBridge.addListener("searchclose", navListener, "searchClose");
EventBridge.addListener("searchfocus", navListener, "searchFocus");
EventBridge.addListener("callsearch", navListener, "callSearch");
EventBridge.addListener("lockup", navListener, "lockupActive");
EventBridge.addListener("nav", navListener, "navActive");

navListener.flashTest = function(event) { 
	alert("flash working");
};

navListener.lockupActive = function(event) {
	EventBridge.dispatchEvent({type:'navCall',data:'close'});
};

navListener.navActive = function(event) {
	EventBridge.dispatchEvent({type:'lockupCall',data:'close'});
};

navListener.flashAlert = function(event) {
	alert(event.data);
};

navListener.callSearch = function(event) {
	if (document.getElementById('nav_input').value != "") {
		search();
	}
};

function setMenuArea(id, width, height) {
	//console.log('id:' + id + ', width:'+width+'px, height:'+height+'px');
	
	if(id == "nav-module-top_swf"){
		$("#p_lozenge").css("width", width);
		$("#p_lozenge").css("height", height);
	}
	/*if(id == "nav-module-left_swf"){
		$("#p_navigation").css("width", width);
		$("#p_navigation").css("height", height);
	}*/
	
	$("#" + id).width(width+'px');
	$("#" + id).height(height+'px');
}


function setCaretTo(obj, pos) {
    if(obj.createTextRange) { 
        var range = obj.createTextRange(); 
        range.move("character", pos); 
        range.select(); 
    } else if(obj.selectionStart) { 
        obj.focus(); 
        obj.setSelectionRange(pos, pos); 
    } 
}; 

/*For Login Update*/
EventBridge.addListener("updateNavProfile", navListener, "updateNavProfile");
EventBridge.addListener("logoutCookies", navListener, "logoutCookies");
EventBridge.addListener("logoutSocial", navListener, "logoutSocial");

var navProfileObj;
var navProfileCalled = false;

function setNavProfile(obj) {
	navListener.navProfileObj = obj;
	navListener.navProfileCalled = true;
	EventBridge.dispatchEvent({type:'setNavProfile', data: obj});
};

navListener.updateNavProfile = function(event) {
	if ((navProfileCalled == false) && (navProfileObj != undefined)) {
		setNavProfile(navListener.navProfileObj);
	}
}

navListener.logoutCookies = function(event) {
	NIKEOS.ME.clearSocialCookies();
	if(typeof nikeplus != "undefined")
		nikeplus.user.logout();
}

//Logout for social-enabled sites (add type="logoutSocial" to nav.xml)
//Clears social cookies, logs user out of UPM and refreshes page.
navListener.logoutSocial = function(event){
	if(typeof(NIKEOS.AC)=='undefined'){
		NIKEOS.AC = new AjaxController({});
	}
	NIKEOS.ME.clearSocialCookies();
	var profileServiceUrl = '/services/profileService';
	if(typeof(NIKEOS.YP=='object')){
		profileServiceUrl = NIKEOS.YP.profileService;
	}
	var request = { url:profileServiceUrl, method:'POST', post_data:'action=logout' };
	var callback = function(data){
		location.reload(true);
	}
	NIKEOS.AC.request(request,callback);
}
/*End Login Update*/

/* END NAVIGATION */


/* me.nike.com COOKIE */

if (!NIKEOS.ME) NIKEOS.ME = {};

/**
 * setCookie
 * sets the "me.nike.com" cookie
 * @param {object} obj : hash of profile name/values
 */
NIKEOS.ME.setCookie = function(obj){
	var str = '';
	var counter = 0;
	for(i in obj){
		if(counter!=0){ str += '&'; } else { counter++; }
		str += i + '=' + obj[i];
	}
	NIKEOS.ME.data = obj;
	var date = new Date();
	date.setTime(date.getTime() + (5 * 60 * 1000));
	JQ.cookie('me.nike.com',Base64.encode(str),{path:'/',expires:date});
}

/** getCookie
 * gets hash from "me.nike.com" cookie
 * @return {object} obj : hash of profile name/values
 */
NIKEOS.ME.getCookie = function(){
	if(JQ.cookie('me.nike.com')){
		var str = Base64.decode(JQ.cookie('me.nike.com'));
		var arr = str.split('&');
		var obj = {};
		for(var i = 0;i<arr.length;i++){
			obj[arr[i].split('=')[0]] = arr[i].split('=')[1];
		}
		return obj;
	} else { return false; }
}

/** addToCookie
 * add hash to "me.nike.com" cookie (OVERWRITES)
 * @param {object} params : hash of name/values to add
 * @return {object} obj : hash of profile name/values
 */
NIKEOS.ME.addToCookie = function(params){
	if(JQ.cookie('me.nike.com')){
		var str = Base64.decode(JQ.cookie('me.nike.com'));
		var arr = str.split('&');
		var obj = {};
		for(var i = 0;i<arr.length;i++){
			obj[arr[i].split('=')[0]] = arr[i].split('=')[1];
		}
		for(var j in params){
			obj[j] = params[j];
		}
		NIKEOS.ME.setCookie(obj);
		return obj;
	} else { NIKEOS.ME.setCookie(params); }
}

/** removeFromCookie
 * remove array of keys from "me.nike.com" cookie
 * @param {array} params : array of keys to delete
 * @return {object} obj : hash of profile name/values
 */
NIKEOS.ME.removeFromCookie = function(toDelete){
	if(JQ.cookie('me.nike.com')){
		var str = Base64.decode(JQ.cookie('me.nike.com'));
		var arr = str.split('&');
		var obj = {};
		for(var i = 0;i<arr.length;i++){
			obj[arr[i].split('=')[0]] = arr[i].split('=')[1];
		}
		for(var j = 0;j<toDelete.length;j++){
			delete obj[toDelete[j]];
		}
		NIKEOS.ME.setCookie(obj);
		return obj;
	} else { return false; }	
}

/** clearSocialCookies
 * remove me.nike.com and st.nike.com cookies on logout.
 */
NIKEOS.ME.clearSocialCookies = function(){
	if(JQ.cookie){
		JQ.cookie('me.nike.com', null, {path:'/'});
		JQ.cookie('st.nike.com', null, {path:'/'});
	} else {
		NIKEOS.log('JQ.cookie not available');
	}
}
/** verifyCookie
 * make sure that id.nike.com matches me.nike.com
 * if it doesn't, clearSocialCookies
 */
NIKEOS.ME.verifyCookie = function(){
	if(JQ.cookie){
		if(JQ.cookie('me.nike.com') && JQ.cookie('id.nike.com')){
			var id_id = Base64.decode(JQ.cookie('id.nike.com')).split(':')[0];
			var me_id = NIKEOS.ME.getCookie().id;
			if (id_id != me_id){
				NIKEOS.ME.clearSocialCookies();
				return false;
			} else {
				return true;
			}
		} return false;
	}
	NIKEOS.log('JQ.cookie not available');
}

/** updateNav
 * set nav profile tab to have updated screenName, profileImage, messageCount
 */
NIKEOS.ME.setMessageCount = function(){
	if(JQ.cookie){
		if(JQ.cookie('me.nike.com')){
			var messageCount = NIKEOS.ME.getCookie().messageCount;
			if(typeof(messageCount)!='undefined'){
				setNavProfile({'messageCount':messageCount});
			}
		}
	}
}
/* END me.nike.com COOKIE */

/* BASE 64 Encoding/Decoding */

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
};

/* END BASE 64 Encoding/Decoding */

