/**
 * Momkai 
 * Copyright 2010 Momkai (www.momkai.com)
 * 
 * @author Theun de Bruijn (theun@momkai.com)
 * 
 * @version 1.0
 */
 

/** _______________________________________________________________________________________
* ___              ________________________________________________________________________
* ___|  on ready  |________________________________________________________________________
* _________________________________________________________________________________________
*/

$(document).ready(function()
{
	/* 
	 * catch undefined console
	 */
	
	try { console.log('console ready'); } catch(e) { console = { log: function() {} } }
	console.log("ready() called");

	
	/*
	 * embed Flash elements
	 * wmode is possible using SWFObject 2.2
	 */	
	
	//embedFlash("ctr360/HeaderStartup", "nike_flash_header", 1600, 188, "transparent", "nike_flash_header", "momkai/core/bin/ctr360/", "momkai/data/img/");
	//console.log("embedFlash() header called");
	
	// DISABLED THE HEADER EMBED: ADDED BG IMAGE
	$("#voetbalzone_header").css("background-image", "url('http://nikefootball.momkai.com/data/superfly/images/voetbalzone_nike_tab_default_header.jpg')");
	$("#voetbalzone_header").css("background-position", "0px 0px");
	$("#voetbalzone_header").css("cursor", "pointer");
	$("#voetbalzone_header").bind("click", function() {
		window.location = "http://www.voetbalzone.nl";
	});	
	
	embedFlash("Startup", "nike_flash_main", 976, 433, "transparent", "nike_flash_main");
	console.log("embedFlash() main called");
	
	
	
	/* 
	 * retrieve facebook data (JSONP Ajax call to their Graph API) 
	 */	
	 
	FB_getLikesNumber();
	FB_getLatestPost();
	
	console.log("Facebook data collected");
	
	
	/* 
	 * extend jQuery.easing with custom ease
	 */
	
	jQuery(function( $ ) 
	{
		$.easing.easeOutExpo = function (x, t, b, c, d) {
			return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
		};
	});	
	
	// check if flash element exists and if not, show the fallback correctly
	setTimeout("showFlashFallback()", 2500);
	
	/* 
	 * set the custom background-colors and image
	 * uses .attr because of the needed !important styles
	 */	
	
	$("#content").attr('style', 'background-color: #fff !important;');
	$("#main").attr('style', 'background-color: #000 !important; background-image: url("http://nikefootball.momkai.com/data/superfly/images/su11_background_tab.jpg") !important');

	$("body").css("background-image", "url('http://nikefootball.momkai.com/data/superfly/images/su11_background_tab.jpg')");
	
	/* 
	 * parse the dom to find the div to set the width of.
	 * no id or class name prestent
	 */	
	
	//console.log($("#main > div"));
	console.log($("#main > div")[2]);
	console.log($("#main > div")[2].getElementsByTagName("div")[0]);
	$("#main > div")[2].getElementsByTagName("div")[0].style.width = "976px";

});


/** _______________________________________________________________________________________
* ___                      			  _____________________________________________________
* ___|  Add Facebook like functions  |_____________________________________________________
* _________________________________________________________________________________________
*/

function addLikeButton(nMarginLeft, nMarginTop) {
	$('#main').append('<iframe id="likeButton" style="position: absolute; top: 0%; left: 50%; max-width: 150px; max-height: 30px; margin-top: '+ nMarginTop +'px; margin-left: '+ nMarginLeft +'px; display: none; z-index: 10;" src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fhome.php%23%21%2Fpages%2FNike-Football-Nederland%2F116614965038945&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=dark&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>');
	
}

function showLikeButton() {
	$('#likeButton').css("display", "block");
}

function hideLikeButton() {
	$('#likeButton').css("display", "none");
}


/** _______________________________________________________________________________________
* ___                       _______________________________________________________________
* ___|  General functions  |_______________________________________________________________
* _________________________________________________________________________________________
*/


/*
 * Generic SWF Embed function
 */

function embedFlash(fileName, replaceDivId, nWidth, nHeight, windowMode, htmlClassName, sHeaderPath, sImagesPath) 
{
	
	var flashvars	= 
	{
		sHeaderPath : sHeaderPath,
		sImagesPath : sImagesPath
	};

	var params	  	= 
	{ 
		scale	: "noscale", 
		menu	: "false", 
		wmode	: windowMode,
		allowfullscreen		: "true" 
	}; 
	
	var attributes	=
	{
		'class'	: htmlClassName
	};
 
	
	swfobject.embedSWF("momkai/core/bin/" + fileName + ".swf", replaceDivId, nWidth, nHeight, "9", "false", flashvars, params, attributes);	
};


/*
 * Function that randomly sets a background (01-04)
 */

function setRandomCampaignBackground() {
	
	sLocation = "live";
	
	$.getJSON("http://nikefootball.momkai.com/data/" + sLocation + "/nikefootball_voetbalzone_backgrounds.php?jsoncallback=?", function( data ){ 
	
		// get number of keys in the json object
		var i = 0;
		for (var x in data)
			if (data.hasOwnProperty(x))
		i++;
		
		// pick a random number (incl. offset for 0)
		var nRand = Math.floor(Math.random()*i+1);
		
		//$("body").css("background-image", "url('http://nikefootball.momkai.com/data/" + sLocation + "/" + data['background_' + nRand] + "')");
		$("body").css("background-image", "url('http://nikefootball.momkai.com/data/ctr360/images/ctr360_background_tab.jpg')");
	});

}


/*
 * Generic Cufon text replace function
 */

function cufonReplace(sElement)
{
	Cufon.replace(sElement);
}


/*
 * Generic CSS update function
 */

function updateCSS(sElement, sStyle, sValue)
{
	$(sElement).css(sStyle, sValue)
}


/** _______________________________________________________________________________________
* ___                       _______________________________________________________________
* ___|  SWF Communication  |_______________________________________________________________
* _________________________________________________________________________________________
*/

/*
 * Event based call to other SWF 
 * oData object is included
 */

function callFlashObject(sDivId, sEvent, oData)
{
	document.getElementById("" + sDivId + "").call(sEvent, oData);
}


/*
 * Resize function for specific Flash object
 * Includes event call to that SWF 
 */

function resizeFlashObject(sDivId, nWidth, nHeight){

	/* resized the flash Object using a custom tween.
	 * 
	 * ie6 has some issues, so there we set the resize without
	 * tweening.
	 * 
	 * a check is implemented for the main element so it will 
	 * also resize the corresponing wrapper
	 *   
	 */
		
	if (sDivId === "nike_flash_main") {
		
		if (isIE6 = /msie|MSIE 6/.test(navigator.userAgent)) {
			
			$("#nike_flash_wrapper").css("width", nWidth);
			$("#nike_flash_wrapper").css("height", nHeight);
			
		} else {
			$("#nike_flash_wrapper").css("width", nWidth);
			$("#nike_flash_wrapper").animate({
				height: nHeight
			}, { "duration": 1000, "easing": "easeOutExpo" });
			
		}
	}

	$("#" + sDivId + "").css("marginLeft", 0);
	$("#" + sDivId + "").css("width", nWidth);
	$("#" + sDivId + "").css("height", nHeight);
	 
	
	oData = new Object();
	oData = {
		"width": nWidth,
		"height": nHeight
	};
	
	/*
 	* Event based call to other SWF 
 	* oData object is included
 	*/
	document.getElementById("" + sDivId + "").call("onResize", oData)

}

	
/** _______________________________________________________________________________________
* ___                  ____________________________________________________________________
* ___|  SWF Fallback  |____________________________________________________________________
* _________________________________________________________________________________________
*/

/*
 * This function is called onReady() and checks if the Flash 
 * elements are indeed embedded.
 *  
 * If not, it shows the correct fallback.
 */

function showFlashFallback() {
	
	// check if main flash is embedded (a class is dynamically added on embed)
	if (!($("#nike_flash_main").hasClass("nike_flash_main"))) {
		
		console.log("main swf not embedded")	
		if(location.hash.match(/Take_Control/)) {
			$("#nike_flash_main_fallback").empty();
			$("#nike_flash_main_fallback").css("background", "url(http://nikefootball.momkai.com/data/ctr360/images/noflash_ctr360.jpg) 0 0 no-repeat");
			$("#nike_flash_wrapper").css("width", 976);
			$("#nike_flash_main").css("height", 1166);
			$("#nike_flash_main_fallback").css("height", 1166);
			$("#nike_flash_main_fallback").html(
				'<a href="http://get.adobe.com/flashplayer" target="_blank" style="position: absolute; left: 388px; top: 433px; width: 243px; height: 24px; text-indent: -9999px">Get Flash Player</a>'+
				'<a href="http://www.twitter.com/rafvdvaart" target="_blank" style="position: absolute; left: 388px; top: 471px; width: 264px; height: 24px; text-indent: -9999px">'+
				'<a href="http://www.facebook.com/#!/pages/Nike-Football-Nederland/116614965038945" target="_blank" style="position: absolute; left: 388px; top: 497px; width: 241px; height: 24px; text-indent: -9999px">Nike Footbal Nederland op Facebook</a>');
			$("#nike_flash_main_fallback").css("display", "block");
			$("#nike_flash_wrapper").animate({
				height: 1166
			}, { "duration": 1000, "easing": "easeOutExpo" });
		}
		else {
			// show fallback
			$("#nike_flash_main_fallback").css("display", "block");
			
			// position content
			$("#nike_flash_wrapper").animate({
				height: 315
			}, { "duration": 1000, "easing": "easeOutExpo" });
		}
		// hide corner element
		$("#menu_bg_extra").css("display", "none")
	}
	
	// check if header flash is embedded (a class is dynamically added on embed)
	if (!($("#nike_flash_header").hasClass("nike_flash_header"))) {
		
		console.log("header swf not embedded")	
		//$("#voetbalzone_header").css("background-image", "url('http://nikefootball.momkai.com/data/ctr360/images/fallback_header.jpg')");
		$("#voetbalzone_header").css("background-repeat", "no-repeat");
			
	}
}


/** _______________________________________________________________________________________
* ___              					  _____________________________________________________
* ___|  Facebook Ajax functionality  |_____________________________________________________
* _________________________________________________________________________________________
*/

/*
 * This function is used for the Facebook html section
 * on the Nike page. It queries the facebook graph API
 * for the relevant data and inserts it using Ajax in-
 * to the page.
 * 
 * For cross-domain ajax requests JSONP is used. 
 * More info: http://en.wikipedia.org/wiki/JSON#JSONP
 *  
 */

function FB_getLikesNumber()
{
	
	$.getJSON('https://graph.facebook.com/116614965038945?callback=?', function(response)
	{
		$(".fan_count").html(response.fan_count);
		
		cufonReplace(".likes");
	 	cufonReplace(".fan_count");
		
		console.log("Cufon replacements done");
		
	
	});	
}

function FB_getLatestPost()
{
	
	$.getJSON('https://graph.facebook.com/116614965038945/posts?callback=?', function(response)
	{
		// check if facebook returns data
		if (response.data) {
			
			//console.log(response.data);
			
			/*
			 * loops trough the JSON data for the first post
			 * containing a message longer than 49 characters
			 */
			var data = response.data;
			var prop = "message";
			
			for (var i = 0; i < data.length; i++) {
				
				
				
				if (!data[i].hasOwnProperty(prop)) {
					continue;
				}
				
				if (data[i].message.length < 50) {
					continue;
					
				}
				else {
									
					break;
				}
			}
			
			/*
			 * Note:
			 *
			 * If you need it, the "data[prop]" object
			 * now contains the found post and all it's
			 * properties & data.
			 *
			 * console.log(data[prop]);
			 *
			 */
			/*
			 * Get the latest post dates and inject them
			 * into the html
			 */
			postDate = data[i].updated_time;
			
			
			/*
			 * rewrite month to text
			 */
			var month;
			
			switch (postDate.substring(5, 7)) {
			
				case "01":
					month = "januari";
					break;
				case "02":
					month = "februari";
					break;
				case "03":
					month = "maart";
					break;
				case "04":
					month = "april";
					break;
				case "05":
					month = "mei";
					break;
				case "06":
					month = "juni";
					break;
				case "07":
					month = "juli";
					break;
				case "08":
					month = "augustus";
					break;
				case "09":
					month = "september";
					break;
				case "10":
					month = "oktober";
					break;
				case "11":
					month = "november";
					break;
				case "12":
					month = "december";
					break;
			}
			
			/*
			 * compensate for timezone (+3 hours)
			 */
			var hour = parseFloat(postDate.substring(11, 13)) + 3;
			
			$("#nike_facebook > .functions > .date > .day").html(postDate.substring(8, 10));
			$("#nike_facebook > .functions > .date > .month").html(month);
			$("#nike_facebook > .functions > .date > .hour").html(hour);
			$("#nike_facebook > .functions > .date > .minute").html(postDate.substring(14, 16));
			
			
			/*
			 * Loop trough the content data and inject
			 * the split data into the html
			 */
			var message = "";
			var line_1 = "";
			var line_2 = "";
			var line_3 = "";
			var line_4 = "";
			var line_5 = "";
			
			message = (data[i].message);
			
			message = message.split(" ");
			
			for (key in message) {
				if (line_1.length < 25) {
					line_1 = line_1 + " " + message[key];
					delete message[key];
					continue;
				}
				break;
			};
			
			for (key in message) {
				if (line_2.length < 25) {
					line_2 = line_2 + " " + message[key];
					delete message[key];
					continue;
				}
				break;
			};
			
			for (key in message) {
				if (line_3.length < 18) {
					line_3 = line_3 + " " + message[key];
					delete message[key];
					continue;
				}
				break;
			};
			
			for (key in message) {
				if (line_4.length < 13) {
					line_4 = line_4 + " " + message[key];
					delete message[key];
					continue;
				}
				break;
			};
			
			for (key in message) {
				if (line_5.length < 10) {
					line_5 = line_5 + " " + message[key];
					delete message[key];
					continue;
				}
				break;
			};
			
			$("#nike_facebook > .latest_post > .line_1").html(line_1);
			$("#nike_facebook > .latest_post > .line_2").html(line_2);
			$("#nike_facebook > .latest_post > .line_3").html(line_3);
			$("#nike_facebook > .latest_post > .line_4").html(line_4);
			
			/*
			 * Check if the last line ends a sentence or not
			 *
			 */
			if ((data[i].message).charAt((data[i].message).length) === ".") {
				$("#nike_facebook > .latest_post > .line_5").html(line_5)
			}
			else {
				$("#nike_facebook > .latest_post > .line_5").html(line_5 + " ...");
			}
			
			/*
			 * Only show the Facebook functions if 
			 * Facebook actually returns data
			 */			
			updateCSS(".functions", "display", "block");
			
		} else {
			
			/*
			 * If Facebook doesn't return data
			 * fail gracefully
			 */
			updateCSS(".latest_post", "padding-top", "128px");
			$("#nike_facebook > .latest_post > .line_1").html("Facebook is even niet bereikbaar.");
			$("#nike_facebook > .latest_post > .line_2").html("Onze excuses hiervoor.");
		}
		
		/*
		 * Show the elements after everything has been rendered
		 * (overrides the css 'display : none' style
		 */		
		updateCSS(".likes", "display", "block");
		updateCSS(".fixed_txt", "display", "block");
		updateCSS(".btn", "display", "block");
	});	
}

/**
 * ScrollTo include
 */
(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement

					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

function scrollToTop() {
	$(window).scrollTo(188, 200);
}

function scrollToPrizes() {
	$(window).scrollTo(874, 200);
}

function showProCombat() {
    
    console.log("showProCombat() called");
    
    // gives the flash some breathing room
    $("#nike_flash_wrapper").css("width", "100%");
    $("#nike_flash_main").css("width", "100%");
	$("#nike_flash_wrapper").css("height", "1110px");
    $("#nike_flash_main").css("height", "1110px");
	
}

function hideProCombat() {
    
    console.log("hideProCombat() called");
    
    // let's close it up again
    $("#nike_flash_wrapper").css("width", "976px");
    $("#nike_flash_main").css("width", "976px");
}

function initFacebookLikeButton() {
	
};

function showFacebookLikeButton() {
	
};

function hideFacebookLikeButton() {
	
};

function alignFacebookLikeButton() {
	
};
