nikefootball.red.loaded = false;

$(document).ready(function() {
	
	var intervalKey = window.setInterval(function(){
		if(nikefootball.red.loaded){
			// clear interval
			window.clearInterval(intervalKey);
			$("#content-inner").css("visibility","visible");
		}
    }, 1000);
	
	//Animate the side touts on mouse over/out
	nikefootball.red.sidetoutsAnimate();
	//Hide the Buy Now button based on cookie and JS global var
	nikefootball.red.buyNowButtonHide();

	
	// 
	
	// Comments
	if (!$.browser.msie){
		nikefootball.red.comments();
	}else{
		//we'll do it on window.load for IE
	}

	// Media feed
	if (!$.browser.msie){
		nikefootball.red.embeddedVideos();
	}else{
		//we'll do it on window.load for IE
	}
	
	
	// Social
	nikefootball.red.socialLinks();
	
	// Use cufon
	var cufonDataRockwellBold = [
		{selector: 'div#blogfeedcontent h2'},
		{selector: 'div#media #comments h2'}
	];
	
	nikefootball.red.cufonise(cufonDataRockwellBold, 'RockwellBold', 'HelveticaNeueLTProMediumCondensed');
	
	var cufonDataHelveticaBoldCond = [
		{selector: '#p_innerwrapperfooter li.brand', options: {hover: !$.browser.msie}},
		{selector: 'ul#blogfeed li h3 a', options: {hover: !$.browser.msie}},
		{selector: 'div.tabcontentlink a', options: {hover: !$.browser.msie}},
		{selector: '.main-tout a:not(#content-inner.ru_ru .main-tout a)', options: {hover: !$.browser.msie}},
		{selector: '#content-inner.ru_ru .main-tout a span.text', options: {hover: !$.browser.msie}},		
		{selector: '.side-tout a', options: {hover: !$.browser.msie}},
		{selector: '#differenceWrapper h3'},
		{selector: '#differenceWrapper h4 a', options: {hover: !$.browser.msie}},
		{selector: '.gamechangers p span'},
		{selector: '.wear-laces h3'}
	];
	
	nikefootball.red.cufonise(cufonDataHelveticaBoldCond, 'HelveticaBoldCond', 'HelveticaNeueLTProBoldCondensed');
	
	var cufonTradeGothic = [
		{selector: '.subtitle h2'}
	];
	
	nikefootball.red.cufonise(cufonTradeGothic, 'TradeGothic', 'HelveticaNeueLTProBoldCondensed');	
	
	var cufonDataHelveticaNeueCondensed = [
		{selector: 'span.laces'},
		{selector: '.overlayinner h2'},
		{selector: '.overlayinner li span.number'},
		{selector: '.overlayinner li span.bullet'},
		{selector: '.overlayinner p'},
		{selector: '.gamechangers p a', options: {hover: !$.browser.msie}},
		{selector: '.wear-laces .buy-now a', options: {hover: !$.browser.msie}},
		{selector: '.wear-laces .find-store a', options: {hover: !$.browser.msie}},
		{selector: '.wear-laces .how-spent a', options: {hover: !$.browser.msie}}
		
	];
	
	nikefootball.red.cufonise(cufonDataHelveticaNeueCondensed, 'HelveticaNeueCondensed', 'HelveticaNeueLTProBoldCondensed');	

	/* Flash injection */
	var insertHeroFlash = new nikefootball.red.insertFlashModules("heroModule", "heroplaceholder");
	
	var redOverlay = nikefootball.red.overlay();

});

$(window).load(function() { //liquid canvas requires to be loaded on window.load

	nikefootball.red.loaded = true;

	setTimeout("nikefootball.red.tracking.templateTracking();",300);
	
	// Make the footer links open in new window - excludes language tunnel
	$("#footer_top_left a:gt(1)").attr("target","_blank");

	if ($.browser.msie){

		if ($("div.endpanel").is(':visible')){
		//	window.setTimeout(nikefootball.red.comments,25000);
			window.setTimeout(nikefootball.red.embeddedVideos,1000);
		}
	}

	
})

nikefootball.red.cufonise = function (cufonData, fontFamilyBase, fontFamilyDegrade) {
	if (cufonData === undefined || !cufonData) {
		return;
	}
	fontFamilyBase = fontFamilyBase || 'Rhode-MediumCondensed';
	fontFamilyDegrade = fontFamilyDegrade || 'HelveticaNeueLTProBoldCondensed';
	if (nikefootball.GLOBAL_VARIABLES.textReplacementCyr) {
    fontFamilyDegrade = fontFamilyDegrade + 'Cyr';	
  }
  
  
	if (nikefootball.GLOBAL_VARIABLES.textReplacement) {
		if (nikefootball.GLOBAL_VARIABLES.fullTextReplacement) {
			//Cufon for all the buttons from the Button Factory
			//Use creative fonts
			Cufon.set('fontFamily', fontFamilyBase);
		} else { //use alternative font
			Cufon.set('fontFamily', fontFamilyDegrade);
		}
		$.each(cufonData, function (idx, datum) {
			var selector = datum.selector;
			if (selector === undefined || !selector) {
				return;
			}
			if (datum.options === undefined || !datum.options) {
				Cufon.replace(selector);
			} else {
				Cufon.replace(selector, datum.options);
			}
		});
	}
}

nikefootball.red.overlay = function(){

	$("p.how-spent a").click(function(){
		if(!$.browser.msie){
			$("div.overlaycontainer").fadeIn();
		} else {
			$("div.overlaycontainer").css("display","block");	
		}
		return false;
	});
	
	$("div.overlaycontainer span.close").click(function(){
		if(!$.browser.msie){
			$("div.overlaycontainer").fadeOut();
		} else {
			$("div.overlaycontainer").css("display","none");
		}
	});
	
}

nikefootball.red.socialLinks = function(){
	
	// Generate & populate link hrefs for twitter and fb sharing
	var fbLinkOut = "http://www.facebook.com/sharer.php?u=";
	var fbLinks = $("div[id='media'] li.facebook a");
	var fbLinksSide = $("div.side-tout-3 h3 a.facebook");
	if (nikefootball.GLOBAL_VARIABLES.locale=="zh_CN") {
		var fbLinksSide = $("div.side-tout-3 h3 a.renren");
	}
	var twitterLinks = $("div[id='media'] li.twitter a"); 
	
	fbLinks.each(function(i,link){
		$(link).click(function() {
			var u = $(this).attr('rel');
			var t = "";
			window.open(fbLinkOut + encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
			//tracking.click(trackerString + "media_feed>facebook");
			return false;
		});						
	});
	
	fbLinksSide.each(function(i,link){
		$(link).click(function() {
			
			//special zh_CN script exception, requested by CN team;			   
			if (nikefootball.GLOBAL_VARIABLES.locale=="zh_CN") {
				//insert & execute the zh_CN provided script
				if(/xiaonei\.com/.test(document.location))return false;
				var f='http://share.renren.com/share/buttonshare.do?link=',u=document.location,l=document.title,p=[encodeURIComponent(u),'&title=',encodeURIComponent(l)].join('');
				function a(){
					if(!window.open([f,p].join(''),'xnshare',['toolbar=0,status=0,resizable=1,width=626,height=436,left=',(screen.width-626)/2,',top=',(screen.height-436)/2].join('')))u.href=[f,p].join('');
				};
				if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);
				else a();
				
				return false;
			}
			
			//else do the other locales as usual
			var u = $(this).attr('rel');
			var t = "";
			window.open(fbLinkOut + location.protocol + encodeURIComponent('//') + location.host + encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
			//tracking.click(trackerString + "media_feed>facebook");
			return false;
		});						
	});	
	
	twitterLinks.each(function(i,link){
		$(link).click(function() {
			//tracking.click(trackerString + "media_feed>twitter");
			return true;
		});
	});
	
}

nikefootball.red.embeddedVideos = function(){
    
	// Store clicked media image for use later
	var mediaParent = '';
	var mediaPlaying = '';
	// Click event to load latest media video
	$('#blogfeed li .video a').live('click', function() {
		
		if(mediaPlaying != ''){
			mediaParent.find('object').replaceWith(mediaPlaying);
		}
		mediaParent = $(this).parent();
		mediaPlaying = $(this).parent().html();
	
		var flashVars = {};
		var flashParams = {};
		var flashAttributes = {};
		
		var guid = $(this).attr('rel');
		
		// Global
		flashVars.locale = nikefootball.GLOBAL_VARIABLES.locale.replace(/__/,"_");
		
		flashVars.guid = $(this).attr("rel");
		flashVars.currentUrl = escape(location.href);
		flashVars.autoPlay = "true";
	
		flashVars.regionConfig = "http://www.nike.com/nikeos/global/modules/video/v1/xml/reg/reg_config_" + nikefootball.GLOBAL_VARIABLES.locale.replace(/__/,"_") + ".xml";
		flashVars.siteConfig = "http://www.nike.com/nikefootball/global/xml/videoSiteConfig.xml";
		
		flashVars.trackerObj = tracker_obj;
		
		flashParams.wmode = "opaque";
		flashParams.scale = "noscale";
		flashParams.allowScriptAccess = "always";
		flashParams.allowFullScreen = "true";
		flashParams.bgColor = "#ebebeb";

		var moduleWidth = "384";
		var moduleHeight = "216";
		var moduleElement = "vid_" + flashVars.guid;
		var moduleSWF = "http://www.nike.com/nikeos/global/modules/video/v1/swf/video_player_v2_0.swf";
	
		//swfobject.embedSWF(moduleSWF, moduleElement, moduleWidth, moduleHeight, "9", flashParams.bgColor, flashVars, flashParams, flashAttributes);
		$("#vid_" + guid).videoplayer({guid: guid, width: "384", height: "216", locale: flashVars.locale});
			
		return false;
	});

}

nikefootball.red.comments = function(){

	var commentData = $("ul#commentsfeed li");
	var index = 0;
		
	function displayComments(commentData) {
					
		$("ul#commentsfeed").empty();
		
		//index = commentData.length-6;
		for (i = 0; i < 5; i++) {
			var item = commentData[i];
			$('ul#commentsfeed').prepend(item);
		}
		
		$("ul#commentsfeed li:first").addClass("highlight");
		//highlightComment($('ul#commentsfeed li:first'));
		
		index--;
	}

	function refresh() {
		
		if (index >= 0) {
			var item = commentData[index];
			
			$('ul#commentsfeed').prepend(item);
			
			/* Animate old content out */
			$('ul#commentsfeed li:last').fadeOut(1200, function() { $(this).remove(); });
								
			/* Animate new comment in */
			var height = $('ul#commentsfeed li:first').height();
			$('ul#commentsfeed li:first').css({
				marginTop: '-' + height + 'px', 
				'visibility': 'visible',
				'opacity': '0'
			}).animate({
				marginTop: '0px',
				'opacity': '1'
			}, 1200, function() {
				//highlightComment($('ul#commentsfeed li:first'));
			});
			
			index--;
		}
	}
		
	function highlightComment(targetComment){
		var oldHighlight = $('.highlight:eq(0)');
		
		if(targetComment.hasClass("highlight")){
			return;
		}
		
		if(oldHighlight[0] != undefined){
			oldHighlight.animate({opacity:0.3}, {queue:true, duration:500});
			oldHighlight.find("div.body").slideToggle(500, function(){ 
				oldHighlight.removeClass("highlight");
				oldHighlight.find("div.body").slideToggle(400, function(){ 
					oldHighlight.animate({opacity:1}, {queue:true, duration:500}); });
			});
			animateNewHighlight(targetComment);
			
		} else {
			animateNewHighlight(targetComment);
		}
		
	}
	
	function animateNewHighlight(newHighlight){
		newHighlight.animate({opacity:0.3}, {queue:true, duration:400});
		newHighlight.find("div.body").slideToggle(400, function(){ 
			newHighlight.addClass("highlight");
			newHighlight.find("div.body").slideToggle(400, function(){ 
				newHighlight.animate({opacity:1}, {queue:true, duration:400}); });
		});

	}
	
	$('ul#commentsfeed li').live("click", function() {
		highlightComment($(this));
	});
	
	$('ul#commentsfeed li').live("mouseover", function() {
		$(this).addClass('itemhighlight');
	});
	$('ul#commentsfeed li').live("mouseout", function() {
		$(this).removeClass('itemhighlight');
	});
	
	if(commentData.length < 5){
		$("ul#commentsfeed li:first").addClass("highlight");
		return;
	}
	
	displayComments(commentData);

}

/* Flash module/component management */
nikefootball.red.insertFlashModules = function(flashModule, moduleElement, guid, componentLabel) {

	var isRecognised = false; // Used for debugging

	var flashVars = {};
	var flashParams = {};
	var flashAttributes = {};

	// Global
	flashVars.locale = nikefootball.GLOBAL_VARIABLES.locale;
	flashVars.trackPageName = ">" + nikefootball.GLOBAL_VARIABLES.view.replace("/nikefootball/","").replace(/\//g,">");

	flashParams.wmode = "opaque";
	flashParams.scale = "scale";
	flashParams.allowScriptAccess = "always";
	flashParams.allowFullScreen = "true";
	flashParams.bgColor = "#333333";

	switch (flashModule) {
		case "heroModule":
			// Hero module specific
			var moduleWidth = "910";
			var moduleHeight = "600";
			var moduleElement = "heroplaceholder";
			var pagesrc = document.location.pathname.split("/");
			var pagepath = document.location.pathname.replace("nikefootball/gamechangers", "gamechangers/pages");
			var pageid = pagepath + "/" + pagesrc[pagesrc.length - 1];
			//console.log(pageid);
			var moduleSWF = "/nikefootball/global/swf/modules/contentpage/application/v1_0_0/BootroomContentPage.swf";

			flashVars.pageid = pageid;
			
			flashVars.application = "gamechangers";
			flashVars.pageType = "modules/heroflash/home";
			flashVars.pageName = "home";
			
			flashVars.trackerObj = tracker_obj;

			flashParams.base = "/nikefootball/global/swf/modules/contentpage/application/v1_0_0/";
			flashAttributes.id = moduleElement;
			flashAttributes.name = moduleElement;
			if ($("#" + moduleElement).length > 0) {
				isRecognised = true;
			}
			break;
		default:
			isRecognised = false;
	}

	if (isRecognised) {
		swfobject.embedSWF(moduleSWF, moduleElement, moduleWidth, moduleHeight, "9", flashParams.bgColor, flashVars, flashParams, flashAttributes);
		//console.info("- Flash module: " + flashModule + " : injected.");
	} else {
		//console.warn("- Flash module: " + flashModule + " : not recognised.");
	}
	
	
}

nikefootball.red.tracking = {
	
	// Initialise the tracker string prefix : nav_tracker_obj passed from nikeos shell
	nikeosView: nav_tracker_obj.prefix,
	currentView: nav_tracker_obj.prefix + nikefootball.GLOBAL_VARIABLES.view.replace("/nikefootball/","").replace(/\//g,">"),
	
	templateTracking: function(){
		var trackerString = nikefootball.red.tracking.currentView + '>';
		
		// Community - Comments RSS
		$('#comments h2 a').click(function() {
			tracking.click(trackerString + 'community>rss');
		});
		// Community - View Comment link 
		$('#comments #commentsfeed li .head a').click(function() {
			tracking.click(trackerString + 'community>comment');
//			tracking.click(trackerString + 'community>click>' + $(this).text());
		});
		$('#comments #commentsfeed li .body .timestamp a').click(function() {
			tracking.click(trackerString + 'community>comment');
//			tracking.click(trackerString + 'community>view_comment>' + $(this).text());
		});
		
		// Latest Media RSS
		$('#media .leftcol h2 a').click(function() {
			tracking.click(trackerString + 'media_feed>rss');
		});
		
		// Latest Media Facebook & Twitter links
		// See function generateShareLinks
		
		// Latest media video play
		$('#blogfeed li .video a').click(function() {
//			tracking.click(trackerString + 'media_feed>play>' + $(this).closest('li.blog').find('.post h3 a').text());
			tracking.click(trackerString + 'media_feed>play');
		});

		// Latest media article link out
		$('#blogfeed .blog .asset:not(.video) a').click(function() {
//			tracking.click(trackerString + 'media_feed>click>' + $(this).closest('li.blog').find('.post h3 a').text());
			tracking.click(trackerString + 'media_feed>click');
		});
		$('#blogfeed .blog h3 a').click(function() {
//			tracking.click(trackerString + 'media_feed>click>' + $(this).text());
			tracking.click(trackerString + 'media_feed>click');
		});
		
		// Latest media article view/post comments
		$('#blogfeed .blog .post .links li.viewcomment a').click(function(){	
//			tracking.click(trackerString + 'media_feed>view_comments>' + $(this).closest('div.post').find('h3').text());
			tracking.click(trackerString + 'media_feed>view_comments');
		});
		$('#blogfeed .blog .post .links li.postcomment a').click(function(){	
//			tracking.click(trackerString + 'media_feed>post_comments>' + $(this).closest('div.post').find('h3').text());
			tracking.click(trackerString + 'media_feed>post_comments');
		});
		
		// Generate & populate link hrefs for twitter and fb sharing
		$("div[id='media'] li.facebook a").click(function() {
			tracking.click(trackerString + "media_feed>facebook");
		});						
		
		$("div[id='media'] li.twitter a").click(function() {
			tracking.click(trackerString + "media_feed>twitter");
		});
		//Share button click
		$("div.side-tout-1 a").click(function() {
			tracking.click(trackerString + "link>share");
		});		
		//Show button click		
		$("div.side-tout-2 a").click(function() {
			tracking.click(trackerString + "link>show");
		});		
		//Tell button click
		$("div.side-tout-3 a").click(function() {
			tracking.click(trackerString + "link>tell");
		});		
		
		//buy button click
		$("div.buy-now a").click(function() {
			tracking.click(trackerString + "link>buy");
		});			
		//read the latest news click
		$("div.main-tout a").click(function() {
			tracking.click(trackerString + "link>read");
		});
		//find a store button click
		$("div.find-store a").click(function() {
			tracking.click(trackerString + "link>find_store");
		});		
		//gamechangers button click
		$("div.gamechangers p a").click(function() {
			tracking.click(trackerString + "link>gamechangers");
		});	
		//see the diff - medicate button click
		$("#seeTheDifference .medicate h4 a").click(function() {
			tracking.click(trackerString + "link>medicate");
		});	
		//see the diff - educate button click
		$("#seeTheDifference .educate h4 a").click(function() {
			tracking.click(trackerString + "link>educate");
		});	
		//get the story button click
		$("#getTheStory h4 a").click(function() {
			tracking.click(trackerString + "link>get_the_story");
		});	
		
		//how are funds used click
		$("p.how-spent a").click(function() {
			tracking.click(trackerString + "link>how_are_funds_used");
		});			
						
		

	}
	
}

nikefootball.red.buyNowButtonHide = function(){
	//grab the cookie value of NIKE_COMMERCE_COUNTRY
	if ((commerce_cookie = $.cookie('NIKE_COMMERCE_COUNTRY')) && $.cookie('NIKE_COMMERCE_COUNTRY')!= ""){
		//alert($.cookie('NIKE_COMMERCE_COUNTRY'));
		//now check the commerce global var coming from FTL to JS
		if ((commerce_glovar = eval("COMMERCE_REGION_GLOBAL_VARIABLES." + commerce_cookie)) || $.cookie('NIKE_COMMERCE_COUNTRY').toLowerCase()=='us'){ 
			//if the cookie exists and if the global commerce var says that we have commerce on, we keep the Buy Now button
			//otherwise we hide
			//alert(commerce_glovar);
			if (commerce_glovar == 1 || commerce_glovar == 2 || $.cookie('NIKE_COMMERCE_COUNTRY').toLowerCase()=='us'){
				$('.storeWrap div.buy-now').show();
			}else{
				$('.storeWrap div.buy-now').hide();
			}
		}
	}

}

nikefootball.red.sidetoutsAnimate = function(){

$('div.side-tout h3 a img.tout-flash').each(function() {

if ($.browser.msie) {
	$(this).attr('src',$(this).attr('src').replace('.png','.gif'));
}
													 
	var sidetoutImage = $(this);
	var zoomWidth = parseInt(sidetoutImage.css('width')) * 0.25;
	var zoomHeight = parseInt(sidetoutImage.css('height')) * 0.25 ;
	
	//make the default state smaller size
	sidetoutImage.css('left', '120px');	
	sidetoutImage.css('top', '20px');
	sidetoutImage.css('width', parseInt(sidetoutImage.css('width')) * 0.75);
	sidetoutImage.css('height', parseInt(sidetoutImage.css('height')) * 0.75);


	sidetoutImage.parent().hover(
      function () {
        sidetoutImage.animate({
			width: "+=" + zoomWidth,
			height: "+=" + zoomHeight,
			left: "-=" + parseInt(zoomWidth/2),
			top: "-=" + parseInt(zoomHeight/3)
		}, 300);
      }, 
      function () {
        sidetoutImage.animate({
			width: "-=" + zoomWidth,
			height: "-=" + zoomHeight,
			left: "+=" + parseInt(zoomWidth/2),
			top: "+=" + parseInt(zoomHeight/3)
		}, 300);
      }
    );

});
/*

	
	
	// Event handlers
	toutBox.mouseenter( 
		function() {
			if ($(this).css('background-image').match(/\.png/i) !== null || $(this).css('background-image').match(/\.gif/i) !== null || $(this).css('background-image').match(/\.jpg/i) !== null ) {
				alert('@');
					$(this).animate({
						width: "-=" + zoomWidth,
						height: "-=" + zoomHeight,
						left: "+=" + parseInt(zoomWidth/2),
						top: "+=" + parseInt(zoomHeight/3)
					}, 1500);	
			}
		}
	);
	toutBox.mouseleave(
		function() {
			
		}
	);
*/	
}


/**
	Reusable Animation Functions 
**/

// Zoom in and "white flash" effect
nikefootball.red.zoomIn = function(toutImg, zoomWidth, zoomHeight, opac) {
	var flashOpacity;
	if (opac != undefined) {
		flashOpacity = opac;
	}
	else {
		flashOpacity = 0.7;
	}
	if (!noZoom) {
		toutImg.animate({
			width: "+=" + zoomWidth,
			height: "+=" + zoomHeight,
			left: "-=" + parseInt(zoomWidth/2),
			top: "-=" + parseInt(zoomHeight/3)
		}, 300).parent().parent().find('span.toutflash').animate({ 
			opacity: flashOpacity
		}, 200, function() {
			$(this).animate({ 
				opacity: 0
			}, 500);
		});
	}
	else {
		toutImg.parent().parent().find('span.toutflash').animate({ 
			opacity: flashOpacity
		}, 200, function() {
			$(this).animate({ 
				opacity: 0
			}, 500);
		});
	}
}

// Zoom out effect
nikefootball.red.zoomOut = function(toutImg, zoomWidth, zoomHeight) {
	if (!noZoom) {
		toutImg.animate({
			width: "-=" + zoomWidth,
			height: "-=" + zoomHeight,
			left: "+=" + parseInt(zoomWidth/2),
			top: "+=" + parseInt(zoomHeight/3)
		}, 300);
	}
}
