/**
 * Fanta.com Global Javascript 
 * 
 * - To be included on every page on Fanta.com
 * 
 */
 
  /*
	Fanta Enhancement Release 0.5 - Loading functionality starts
	For perfomance issue.
*/
(function(){
	var backgorundDiv = $("body").prepend("<div class='background_div'></div>");
	$("body div.background_div").css({
		"background-image"		:	$("body").css("background-image"),
		"background-color"		:	$("body").css("background-color"),
		"background-position"	:	$("body").css("background-position"),
		"height" 				:	$(document).height()+"px",
	});
	$("#container").css("display", "block");
})();

$("#loading_site .loading_content span").html("loading...");

$(window).load(function () {
  stopLoading();
});

function stopLoading() {
	if($("#loading_site").length > 0) {
		$("#loading_site").css("display", "none");
		$("body div.background_div").fadeOut(300, function(){
			$("body div.background_div").remove();
		});
		$("#loading_site").fadeOut(300, function(){
			$("#loading_site").remove();
			load_callout_images();
			FANTA.Global();
			onHighlightNavigationClick();
		});
	}
}
 

 /*
	Fanta Enhancement Release 0.5 - Share functionality starts
	Here some varibales whcih are actually parameters to be passed to URL which will be opened when user clicks on any social media network
*/
var opennewwindow = "Vkontakte";
var OUR_SITE_URL = "http://test.fanta.com/content/default/pages/landing/index_gigya_test.html";
var OUR_SITE_TITLE = "Fanta %7C &#1044;&#1088;&#1098;&#1078;&#32;&#1089;&#1077;&#32;&#1077;&#1089;&#1090;&#1077;&#1089;&#1090;&#1074;&#1077;&#1085;&#1086;&#46; %7C Fanta.bg";
var OUR_SITE_BODY_TEXT ="Get your Fanta soda fix online, anytime. Visit Fanta.com to meet the Fanta Crew, watch TV spots, download the newest screensavers and get the latest information on your favorite Fanta soft drinks.";
var LOCALE_LANGUAGE = "en_US";

/*
	Variable social_medias contains key-value pair of social media networks name and the parameters to be passed in URL when user clicks on the respective social media network to share his comments.
	In order to add or remove any social media network then both key & value needs to be added or removed
	Example:
	If user wants to add any social media network in the list then following format needs to be followed:
	"Facebook"	:	"http://www.facebook.com/sharer.php?u=OUR_SITE_URL&bodytext=OUR_SITE_BODY_TEXT&locale=LOCALE_LANGUAGE",
*/

var social_medias = {
	"Facebook"			:	"http://www.facebook.com/sharer.php?u=OUR_SITE_URL&bodytext=OUR_SITE_BODY_TEXT&locale=LOCALE_LANGUAGE",
	"Twitter"			: 	"http://twitter.com/intent/tweet?text=OUR_SITE_TITLE&url=OUR_SITE_URL",
	
	
};

function opensocialnewwindow(obj) {
	window.open(obj.getAttribute("href"),'mywindow','width=600,left=250,top=100,screenX=250,screenY=100,resizable=yes');
	return false;
}

function allsocialscroll() {
	var HTML = "<ul>";
	
	OUR_SITE_URL = window.location;
	
	var opn = opennewwindow.split(",");
	
	for (var key in social_medias) {
		if(social_medias.hasOwnProperty(key)) {
			
			HTML = HTML + "<li><a target='_blank' href='" + social_medias[key] + "'>" + key + "</a></li>";
		
			HTML = HTML.replace("OUR_SITE_URL", OUR_SITE_URL).replace("OUR_SITE_TITLE", OUR_SITE_TITLE).replace("OUR_SITE_BODY_TEXT", OUR_SITE_BODY_TEXT).replace("LOCALE_LANGUAGE", LOCALE_LANGUAGE);
		}
	}
	
	$("#all_social_media").html(HTML + "</ul>");
	$("#all_social_media ul li:first-child").addClass("first");
	$("#all_social_media ul li:last-child").addClass("last");
	if($("#all_social_media ul li").length>12) {
		$("#all_social_media").scrollbar();	
	}
	$("#all_social_media ul li a").each(function(i){
		for(var i=0; i<opn.length; i++) {
			if($(this).html()==opn[i]) {
				$(this).attr("onClick", "javascript:return opensocialnewwindow(this)");
				break;
			}
		}
	});
}

/*	Fanta Enhancement Release 0.5 - Share functionality ends */

var FANTA = FANTA || {};
/// for setting width according to layout

/**
 * modifications and startup for the 2bottom col.
 * @author Gaurav Saxena
 * 
 */
 
	 function strstr (haystack, needle, bool) {
		var pos = 0;
	
		haystack += '';
		pos = haystack.indexOf(needle);
		if (pos == -1) {
			return false;
		} else {
			if (bool) {
				return haystack.substr(0, pos);
			} else {
				return haystack.slice(pos);
			}
		}
	}
	
	$('nav ul a').mouseenter(function(){
		var img = $(this).find('.icon_img img');
		
		var orig_img = img.attr('src');
		
		var len = parseInt(orig_img.length);
		len = len-4;		
		
		var file_name_no_ext = orig_img.substr(0, len)
		
		var ext = (orig_img.substr(len));										 		
		var file_hover = file_name_no_ext + "_hover" + ext;
		
		img.data('origSrc',img.attr('src'));		
		img.attr('src',file_hover);
		
	}).mouseleave(function(){
		var img = $(this).find('img');
		img.attr('src',img.data('origSrc'));		
	});

	
	
	//var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	
	//if(!is_chrome){
		//$("img").load(function() {
			
		//});
	//}
	
	/*if(is_chrome) {
		$(function() {
			$("#twoWideCallouts div.callout:last-child").addClass("last");
			$("#twoWideCalloutsTop div.callout:last-child").addClass("last");
			$("#threeWideCallouts div.callout:last-child").addClass("last");
			$("#fourWideCallouts div.callout:last-child").addClass("last");
			
			if($('#threeWideCallouts div.callout').length != 0)
			{
				$len = $('#threeWideCallouts div.callout img.callout_img').length;
				
				for($i=0; $i<$len; $i++){
					$sgs = ($('#threeWideCallouts img.callout_img')[$i].width);
					
					if($sgs > 320){
						$('#threeWideCallouts div.callout').eq($i).addClass('threeDivMaxWidth');
					}
					else if($sgs < 300){
						$('#threeWideCallouts div.callout').eq($i).addClass('threeDivMinWidth');
					}
					else if($sgs > 720){
						$('#twoWideCalloutsTop div.callout').eq($i).addClass('threeDivMinWidth');
					}
					else if($sgs > 950){
						$('#twoWideCalloutsTop div.callout').eq($i).addClass('threeDivMaxWidth');
					}
				}
			}
			
		});
	}*/	
 	
	
		/*
			Enhancement Fanta Global 0.5 Release - 
			This change is made for RTL, 
			$sgs = ($('#twoWideCalloutsTop img.callout_img')[$i].width);
			
			given a class name (callout_img) for all contributable callout images to seperate from shadow image
			
			find the contributed callout images only, from the loop and take the width of the image 
			by leaving shadow images, 
			
		*/
	
		function load_callout_images(){
			
			if($('#twoWideCalloutsTop div.callout').length != 0)
			{
				$('#twoWideCalloutsTop div.callout img.callout_img').each(function(i){
					
					
					if (this.complete || this.readyState === 4) {
							$sgs = ($(this).width());
					
							if(470 < $sgs && $sgs < 700){
								$('#twoWideCalloutsTop div.callout').eq(i);
							}
							
							else if($sgs < 300){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('twoDivMinWidth');
							}
							
							else if($sgs > 700 && $sgs < 950){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('fourDivMinWidth');
							}
							else if($sgs > 950){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMaxWidth');
							}	
					} else {
						$(this).bind("load", function(){	
							$sgs = ($(this).width());
					
							if(470 < $sgs && $sgs < 700){
								$('#twoWideCalloutsTop div.callout').eq(i);
							}
							
							else if($sgs < 300){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('twoDivMinWidth');
							}
							
							else if($sgs > 700 && $sgs < 950){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('fourDivMinWidth');
							}
							else if($sgs > 950){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMaxWidth');
							}	
						});
					}
					
				});
			}
		
			if($('#twoWideCallouts div.callout').length != 0)
			{
				$('#twoWideCallouts div.callout img.callout_img').each(function(i){
					if (this.complete || this.readyState === 4) {
						$sgs = ($(this).width());
						if($sgs < 300){
							$('#twoWideCallouts div.callout').eq(i).addClass('twoDivMinWidth');
						}
						else if(470 < $sgs && $sgs < 700){
							$('#twoWideCallouts div.callout').eq(i);
						}
						else if($sgs > 700 && $sgs < 950){
							$('#twoWideCallouts div.callout').eq(i).addClass('fourDivMinWidth');
						}
						else if($sgs > 950){
							$('#twoWideCallouts div.callout').eq(i).addClass('threeDivMaxWidth');
						}
					}
					else {
						$(this).bind("load", function(){
							$sgs = ($(this).width());
							if($sgs < 300){
								$('#twoWideCallouts div.callout').eq(i).addClass('twoDivMinWidth');
							}
							else if(470 < $sgs && $sgs < 700){
								$('#twoWideCallouts div.callout').eq(i);
							}
							else if($sgs > 700 && $sgs < 950){
								$('#twoWideCallouts div.callout').eq(i).addClass('fourDivMinWidth');
							}
							else if($sgs > 950){
								$('#twoWideCallouts div.callout').eq(i).addClass('threeDivMaxWidth');
							}
						});
					}
					
				});
			}
		
			if($('#threeWideCallouts div.callout').length != 0)
			{
				$('#threeWideCallouts div.callout img.callout_img').each(function(i){
					if (this.complete || this.readyState === 4) {
						$sgs = ($(this).width());
						if($sgs > 320){
							$('#threeWideCallouts div.callout').eq(i).addClass('threeDivMaxWidth');
						}
						else if($sgs < 300){
							$('#threeWideCallouts div.callout').eq(i).addClass('threeDivMinWidth');
						}
						else if($sgs > 720){
							$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMinWidth');
						}
						else if($sgs > 950){
							$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMaxWidth');
						}
					}
					else {
						$(this).bind("load", function(){
							$sgs = ($(this).width());
							if($sgs > 320){
								$('#threeWideCallouts div.callout').eq(i).addClass('threeDivMaxWidth');
							}
							else if($sgs < 300){
								$('#threeWideCallouts div.callout').eq(i).addClass('threeDivMinWidth');
							}
							else if($sgs > 720){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMinWidth');
							}
							else if($sgs > 950){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMaxWidth');
							}
						});
					}
				});
			}
			
			if($('#threeWideCalloutsTop div.callout').length != 0)
			{
				$('#threeWideCalloutsTop div.callout img.callout_img').each(function(i){
					if (this.complete || this.readyState === 4) {
						$sgs = ($(this).width());
						if($sgs > 320){
							$('#threeWideCalloutsTop div.callout').eq(i).addClass('threeDivMaxWidth');
						}
						else if($sgs < 300){
							$('#threeWideCalloutsTop div.callout').eq(i).addClass('threeDivMinWidth');
						}
						else if($sgs > 720){
							$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMinWidth');
						}
						else if($sgs > 950){
							$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMaxWidth');
						}
					}
					else {
						$(this).bind("load", function(){
							$sgs = ($(this).width());
							if($sgs > 320){
								$('#threeWideCalloutsTop div.callout').eq(i).addClass('threeDivMaxWidth');
							}
							else if($sgs < 300){
								$('#threeWideCalloutsTop div.callout').eq(i).addClass('threeDivMinWidth');
							}
							else if($sgs > 720){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMinWidth');
							}
							else if($sgs > 950){
								$('#twoWideCalloutsTop div.callout').eq(i).addClass('threeDivMaxWidth');
							}
						});
					}
					
				});
			}
		
			/** for adding class=> last to all last divs **/
		
			if($('#twoWideCalloutsTop div.callout').length != 0)
			{	
				$len = ($('#twoWideCalloutsTop div.callout').length);
				$classNameExits = $('#twoWideCalloutsTop div.callout').eq($len-1).attr("class")
				$totalAddClass = $classNameExits + " last";
				$('#twoWideCalloutsTop div.callout').eq($len-1).addClass($totalAddClass);		//for section-3
				if($len == 2*2)
				$('#twoWideCalloutsTop div.callout').eq($len/2 - 1).addClass($totalAddClass); 	//for section-2
			}
		
			if($('#twoWideCallouts div.callout').length != 0)
			{	
				$len = ($('#twoWideCallouts div.callout').length);
				$classNameExits = $('#twoWideCallouts div.callout').eq($len-1).attr("class")
				$totalAddClass = $classNameExits + " last";
				$('#twoWideCallouts div.callout').eq($len-1).addClass($totalAddClass);		//for section-3
				if($len == 2*2)
				$('#twoWideCallouts div.callout').eq($len/2 - 1).addClass($totalAddClass); 	//for section-2
			}
		
			if($('#threeWideCallouts div.callout').length != 0)
			{	
				$len = ($('#threeWideCallouts div.callout').length);
				$classNameExits = $('#threeWideCallouts div.callout').eq($len-1).attr("class")
				$totalAddClass = $classNameExits + " last";
				$('#threeWideCallouts div.callout').eq($len-1).addClass($totalAddClass);
				if($len == 3*2)
				$('#threeWideCallouts div.callout').eq($len/2 - 1).addClass($totalAddClass);
			}
			
			if($('#threeWideCalloutsTop div.callout').length != 0)
			{	
			
				$len = ($('#threeWideCalloutsTop div.callout').length);
				$classNameExits = $('#threeWideCalloutsTop div.callout').eq($len-1).attr("class")
				$totalAddClass = $classNameExits + " last";
				$('#threeWideCalloutsTop div.callout').eq($len-1).addClass($totalAddClass);
				if($len == 3*2)
				$('#threeWideCalloutsTop div.callout').eq($len/2 - 1).addClass($totalAddClass);
			}
			
			if($('#fourWideCallouts div.callout').length != 0)
			{
				$len = ($('#fourWideCallouts div.callout').length);
				$classNameExits = $('#fourWideCallouts div.callout').eq($len-1).attr("class")
				$totalAddClass = $classNameExits + " last";
				$('#fourWideCallouts div.callout').eq($len-1).addClass($totalAddClass);
				if($len == 4*2)
				$('#fourWideCallouts div.callout').eq($len/2 - 1).addClass($totalAddClass);
			}
			
			if($('#fourWideCalloutsTop div.callout').length != 0)
			{
				$len = ($('#fourWideCalloutsTop div.callout').length);
				$classNameExits = $('#fourWideCalloutsTop div.callout').eq($len-1).attr("class")
				$totalAddClass = $classNameExits + " last";
				$('#fourWideCalloutsTop div.callout').eq($len-1).addClass($totalAddClass);
				if($len == 4*2)
				$('#fourWideCalloutsTop div.callout').eq($len/2 - 1).addClass($totalAddClass);
			}
			/** end adding class=> last **/			
		}


/** find the value of glp from url to open or close the div of global landing page **/
function gup( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+name+"=([^&#]*)";  
	var regex = new RegExp( regexS );  
	var results = regex.exec( window.location.href ); 
	if( results == null )   return "";  
	else    return results[1];
}


/**
 * Kick starts global methods.
 * 
 * @author Karl Stanton
 * @since 0.1
 */
FANTA.Global = function () {
	
	FANTA.Global.BindEvents();
	$('#regionPulldown').prependTo('body');
	var glp = gup( 'glp' );
	if(glp == 1)
	$('#handlePulldown').click();
};

/**
 * Binds methods to global (site wide) assets and objects
 * 
 * @author Karl Stanton
 * @since 0.1
 */
FANTA.Global.BindEvents = function () {
	
	// Region
	FANTA.Global.RegionSelector();
	
	// Share / Facebook
	FANTA.Global.Share();
	
};

/**
 * All events and code for the Pull Down Region Selector
 * 
 * @author Karl Stanton
 * @since 0.1
 */
FANTA.Global.RegionSelector = function () {
	
	var ANIMATION_SPEED = 150,
		PULLDOWN_HEIGHT = 735,
		iAnchorHeight	= $('a:first', '#regionIndex').outerWidth(),
		oRegionMarker	= '';
	
	// Bind the pulldown trigger
	$('#handlePulldown').click(function () {
		
		onRegionPulldownClick();
		return false;
		
	});
	
	/**
	 * Brings the region selector into view by adjusting the
	 * height (defaulted in CSS to 0px);
	 * 
 	 * @author Karl Stanton
 	 * @since 0.1
	 */
	function onRegionPulldownClick () {
		
		var pulldown = $('#regionPulldown');
		if( parseFloat( pulldown.css('height') ) > 0 ){
			pulldown.animate({
				 height: '0'
			});
		} else {
			pulldown.animate({
				 height: PULLDOWN_HEIGHT
			});
		}
	}
	
	// Build the selected marker and append it to the DOM	
	oRegionMarker = $('<div id="regionMarker"></div>');
	
	
	if($("#regionPulldown").length>0){
		$.ajax({
			url: "/content/shared/glp.html",
			cache: false,
			success: function(data){
				$("#regionPulldown").html(data);
				replaceTranslatedText();
				$('#regionSelector').append(oRegionMarker);
				
				// Click event for region selection
				$('a', '#regionIndex').click(function () {
					onRegionIndexClick($(this));
					return false;
					
				});
		  }
		});
	}
	
	
	/**
	 * When user clicks the region title in the region index
	 * the ordered list of the same index is to be shown
	 * 
 	 * @author Karl Stanton
 	 * @since 0.1
	 */
	function onRegionIndexClick (oAnchor) {
		
		var iIndex	= oAnchor.parent().index(),
			iTop	= oAnchor.position().top;
		
		// Remove all selected classes
		$('#regionList').find('.selected').removeClass('selected');
		$('#regionIndex').find('.selected').removeClass('selected');
		
		// Now add it back to the new selection
		$('li.region' + iIndex, '#regionList').addClass('selected');
		// Moving forward or backward
		// True  === Moving backward
		// False === Moving forward
		iDirection	= (iTop < oRegionMarker.position().top);
		
		// Move the marker to the selected region
		oRegionMarker.animate({
			top: iTop
		}, {
			duration: ANIMATION_SPEED,
			step: function (iPosition) {
				
				// Timing is everything to make the class switch to active
				if (iDirection && iPosition <= (iTop + (iAnchorHeight / 2))) {
					oAnchor.addClass('selected');
				}
				else if(!iDirection && iPosition >= (iTop - (iAnchorHeight / 2))) {
					oAnchor.addClass('selected');
				}
				
			}
		});
		
	}
	
	
	// Click event for country click
		


	/**
	 * When user clicks the country name within the region
	 * the pulldown closes and the lang in the toolbar is updated
	 * 
 	 * @author Erik Kallevig
 	 * @since 0.1
	 */
	function onCountryClick (oAnchor) {
		
		$('li.region span', '#toolbar').text( '(' + oAnchor.text() + ')' );
		$('#regionPulldown').animate({
			height: '0'
		});		
		
	}

	
	
};

/**
 * Downloads link handlers
 * 
 * @author Erik Kallevig
 * @since 1.0
 */
$('.downloadsRow .link').mouseenter(function(){
	$(this).find('a').show();
}).mouseleave(function(){
	$(this).find('a').hide();
}).find('a').hide();


/**
 * Callout link hover handlers
 * 
 * @author Erik Kallevig
 * @since 1.0
 */
 
 /* Enhancement Fanta Global 0.5 Release - Revert shadow*/
$('.callout a').mouseenter(function(){
	var img = $(this).find('img');

	
	img.data('origSrc',img.attr('src'));
	img.eq(0).attr('src',img.attr('data-hoverImg'));
}).mouseleave(function(){
	var img = $(this).find('img');
	img.eq(0).attr('src',img.data('origSrc'));

});


/**
 * All events for the Facebook share component
 * 
 * @author Karl Stanton
 * @since 1.0
 */
FANTA.Global.Share = function () {
	
	var bShoutsLoaded = false;
	
	// Launches the share popup
	$('#shareLaunch').click(function () {
		onShareLaunchClick();
		return false;
	});

	// Toggle from Share on Sites to Facebook
	$('.btnShout', '#shareFooter').click(function () {
		onToggleShoutShareClick('shout');
		return false;
	});

	// Toggle from Facebook to Share on Sites
	$('.btnShare', '#shareFooter').click(function () {
		onToggleShoutShareClick('share');
		/* Fanta Enhancement Release 0.5 - Share functionality, Function allsocialscroll() called to make the list of social media networks that are contributed in Share list.
		 */
		allsocialscroll(); 
		return false;
	});
	
	// Hide the make comment post, and show the view comments list
	$('a.btnPostComment', '#shareViewPosts').click(function () {
		showPostComment();
		return false;
	});
	
	// Hide the make comment post, and show the view comments list
	$('a.btnViewComments').click(function () {
		$('#shareMakeComment').hide();
		$('#shareViewPosts').show();
		return false;
	});
	
	// Post to Facebook - added 3/4/11
	$('a.btnPostToFacebook', '#facebookComment').click(function () {
		postFantaFacebookFeed();
		$('#shareMakeComment').hide();
		$('#shareViewPosts').show();
		//need setTimeout otherwise new msg probably won't show up
		loadFantaFacebookFeed();
		loadFantaFacebookFeed();
		setTimeout(loadFantaFacebookFeed,1000);
		return false;
	});
	
	// Share using Gigya - added 3/17/11, removed 3/21/11
	/*
	$('a.btnShareWithFacebook', '#share').click(function () {
		//alert("now here");
		shareWithGigya("facebook");
		return false;
	});
	$('a.btnShareWithTwitter', '#share').click(function () {
		//alert("now here");
		shareWithGigya("twitter");
		return false;
	});
	*/
	
	// Close panels
	$('a.btnClose', '#share').click(function () {
		hideSharePopup();
		return false;
	});
	
	// Close panels on document click
	$(document).click(function () { 
		hideSharePopup();
	});
	
	// Stops the closure of the panel
	$('#share').click(function (event) {
		event.stopPropagation();
	});
	
	/**
	 * Toggles between the Shout and Share panels
	 * 
	 * @author Karl Stanto
	 * @since 1.0
	 * 
	 * @param {String} sSwitch
	 */
	function onToggleShoutShareClick (sSwitch) {
		switch (sSwitch) {	
			case 'shout':	
				// Style buttons
				$('.btnShout').addClass('btnShoutOn');
				$('.btnShare').removeClass('btnShareOn');
				// Show / Hide
				$('#sharePopupFacebook').show();
				$('#sharePopupSites').hide();
				// Update footer
				$('#shareFooter').attr('class', 'shout');
				break;
			case 'share':
				// Style buttons
				$('.btnShare').addClass('btnShareOn');
				$('.btnShoutOn').removeClass('btnShoutOn');
				// Show / Hide
				$('#sharePopupFacebook').hide();
				$('#sharePopupSites').show();
				// Update footer
				$('#shareFooter').attr('class', 'share');
				break;
		}
	}
	
	/**
	 * Launches the share popup and gets the Fanta feed
	 * from Facebook
	 * 
 	 * @author Karl Stanton
 	 * @since 1.0
	 */
	function onShareLaunchClick () {
		
		var oSharePopupFacebook = $('#sharePopupFacebook');
		
		if (oSharePopupFacebook.is(':visible') || $('#sharePopupSites').is(':visible')) {
			oSharePopupFacebook.hide();
			$('#sharePopupSites').hide();
			$('#shareFooter').hide();
		}
		// Show it!
		else {
			if (!bShoutsLoaded) {
				loadFantaFacebookFeed();
			}
			$('#sharePopupSites').hide();
			$('#shareFooter').attr('class', 'shout');
			oSharePopupFacebook.show();
			$('#shareFooter').show();
		}
	}
	
	/**
	 * Loads in the Fanta Feed from Facebook via AJAX using JSON
	 * as the data model. Once we have retried the data we then
	 * cycle through it and push everything out to the DOM 
	 * 
 	 * @author Karl Stanton
 	 * @since 1.0
	 */
	function loadFantaFacebookFeed () {
		var sURL = 'https://graph.facebook.com/fanta/feed/?access_token=165876006808188|d4a83efdabbf5b9a542f9c7c.1-100002464471577|0Ms5QOa9d629DVALgDjm1AyPYpw&limit=20&callback=?'; 
		$.getJSON(sURL, function (sJSON) {
			bShoutsLoaded = true;
			buildFacebookWallPosts(sJSON.data);
		});
	}
	
	/**
	 * Posts to the fanta wall
	 * 
	 */
	function postFantaFacebookFeed () {
		//  this gives a pop up that you have to hit submit
        //  FB.ui({ method: 'feed', 
		//	  to: '23550666633',
        //    message: 'red!!!'});

		// user must be logged in and must like brand. brand id: fanta or 23550666633
		var body = $('textarea[name=postText]').val();
		//console.log(body);
		if (body.length > 0){
			FB.api('/fanta/feed', 'post', { message: body }, function(response) {
				if (!response || response.error) {
					//console.log('Error occured');
				} else {
					//console.log('Post ID: ' + response.id);
				}
			});		
			//if checkbox is checked, post to users wall too
			if ($('input[name=post_wall]').attr('checked')) {
				FB.api('/me/feed', 'post', { message: body }, function(response) {
					if (!response || response.error) {
						//console.log('Error occured (to me)');
					} else {
						//console.log('Post ID (to me): ' + response.id);
					}
				});
			}
		} else {
			alert("Message text is empty.");
		}
	}
	
	function showPostComment(){	
		$('#shareMakeComment').show();
		$('#shareViewPosts').hide();
		$('textarea[name=postText]').val('');
	}
	
	function shareWithGigya(socialSite){
		var conf = { 
			APIKey: "2_LZM_wtKh0JdBcISAZkFDY7nPsV528OGJJrc3qr9tfZCXYqJRbLz2tXI_kQSsQmcT",
			enabledProviders: "facebook,twitter"
		};
		
		var act = new gigya.services.socialize.UserAction(); 
		act.setUserMessage("This is the user message"); 

        var params = {
           //callback: onConnectionAdded,
           //provider: socialSite
		   userAction: act,
		   cid:'',
		   operationMode: "simpleShare"
        };   
        //gigya.services.socialize.addConnection(conf, params);
		gigya.services.socialize.showShareUI(conf,params); 
	}
	
	/**
	 * Loop through this object and build out the wall
	 * posts
	 * 
 	 * @author Karl Stanton
 	 * @since 1.0
	 * 
	 * @param {Object} oData
	 */
	function buildFacebookWallPosts (oData) {
		
		try {
			var sHTML = '<ul>',
				i, oMessage, sClass;
			
			for (i = 0; i < oData.length; i++) {
				
				oMessage = oData[i];
				
				// Set our first or last class depending on position of iterator
				sClass = (i === 0) ? ' class="first"' : '';
				sClass = (i === (oData.length - 1)) ? ' class="last"' : sClass;
				
				sHTML += '<li' + sClass + '>' + oMessage.message;
				sHTML += '<span class="nameDate">' + oMessage.from.name + ' ' + prettyDate(oMessage.created_time) + '</span></li>';
				
			}
			
			// Append the list to the Facebook div
			//console.log('replacing posts now');
			$('#facebookPosts').html(sHTML + '</ul>');
			
			// Build the scrollbar
			$('#facebookPosts').scrollbar();
		}
		catch(err) {}
	}
	
	/**
	 * Simply closes the share popup
	 * 
 	 * @author Karl Stanton
 	 * @since 1.0
	 */
	function hideSharePopup () {
		
		$('#sharePopupFacebook').hide();
		$('#sharePopupSites').hide();
		$('#shareFooter').hide();
		
	}
	
};

/**
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 * Takes an ISO time and returns a string representing how
 * long ago the date represents.
 */
function prettyDate (time) {

	var time		= time.split(/\+0000/);
		time		= time[0];
		time		= new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," "));
		
	var sGMTOffset = (time.getTimezoneOffset() / 60) * 3600; 
		
	time	= time.getTime() + sGMTOffset;
	var date		= new Date(time),
		diff		= (((new Date()).getTime() - date.getTime()) / 1000) + sGMTOffset,
		day_diff	= Math.floor(diff / 86400);
		/*hardfix to correct 25 seconds error */
		if(diff<26)
		{
			
			return 'just now';
		}
		/*hard fix ends*/
		
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return 'just now';

	return day_diff == 0 && (
		//diff < 60 && "just now" ||
		diff < 60 &&  Math.floor(diff) + ' seconds ago' ||
		diff < 120 && "1 minute ago" ||
		diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
		diff < 7200 && "1 hour ago" ||
		diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
		
}




// Kick start Fanta after the DOM is ready
$(document).ready(function () {
	
	//FANTA.Global();
	//onHighlightNavigationClick();
	
});

	



function setCookie(l_name,l_value,r_name,r_value,c_name,c_value,exdays, path, domain, secure)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var l_value=escape(l_value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=l_name + "=" + l_value + ";path=/";
var r_value=escape(r_value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=r_name + "=" + r_value + ";path=/";
var c_value=escape(c_value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value + ";path=/"
		+ (domain ? "; domain=" + domain : "")
		+ (secure ? "; secure" : "");
return true;
}

function getCookie(region)
{
var i,region_name,region_value,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  region_name=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  region_value=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  region_name=region_name.replace(/^\s+|\s+$/g,"");
  if (region_name==region)
    {
    return unescape(region_value);
    }
  }
}

function setRegion(region)
{
	var listitems = $('#regionIndex > li');
  $('#regionIndex > li').each(function() {
	if($(this).text() == region) {
		$(this).find("a").click();
	}
  });
  
  /// Only for Google Chrome
  //$("img").load(function() {
//	load_callout_images();					
 // });

  
}

function onHighlightNavigationClick() {

	var url = window.location.href;
	var page_name_index = url.lastIndexOf("/");
	var url_length = url.length;
	var pageName_org = url.substring(page_name_index,url_length);
	var pageName = pageName_org.toLowerCase();
	var pageName_last = pageName.replace("/","");
// All page names should be entered in lowercase eg. ScreenSavers.html should be entered as screensavers.html.
	
	/*
	Enhancement Fanta Global 0.5 Release - Highlight Logic :It fetches the page name from browser and match it with all link to secondary navigation and highlight that sub-navigation item where link matches. 
	*/
	
	if($("h1.downloads").length != 0) {
		var mainlink = $("h1.downloads a").attr("href");
		var mainlink_last = mainlink.replace("./", "");
		
		if(mainlink_last == pageName_last) {
			$("h1.downloads a").addClass('active');
		}
		else {
			$('li.List_Nav_1 a:first').addClass('active');
			$('li.List_Nav_1 a').each(function() {
				var tmp = $(this).attr('href');
				var tmp_last=tmp.replace('./', '');
				if(tmp_last == pageName_last)
				{
					$('li.List_Nav_1 a').removeClass('active');
					$(this).addClass('active');
				}
			});
		}
	}
	

	/* Code for Enhancement Fanta Global 0.5 Release - Highlight Logic ends*/
	
	/* Code for <h1> tags */
	if(pageName=="/index.html" || pageName=="/index.html?glp=1"){
			$('#container header').append('<h1>Fanta!</h1>');
			$('#container header p a').removeAttr("href");
			}
	else if(pageName=="/photos.html"){
			$('#container header').append('<h1 class="hide">Photos</h1>');
			}
	else if(pageName=="/videos.html"){
			$('#container header').append('<h1 class="hide">Videos</h1>');
			}
	else if(pageName=="/flavors.html"){
			$('#container header').append('<h1 class="hide">Flavors</h1>');
			}
	else if(pageName=="/screensavers.html" || pageName=="/downloads.html" || pageName=="/wallpapers.html" || pageName=="/other.html"|| pageName=="/ringtones.html" || pageName=="/the_fanta_crew.html" || pageName=="/privacy.html" || pageName=="/terms.html"){
	
	}
	else{
		$('#container header').append('<h1>Fanta!</h1>');
	}

}

// Prevent logging errors and redirect write method
window.log = function(){
  log.history = log.history || [];   
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};
(function(doc){
  var write = doc.write;
  doc.write = function(q){ 
    log('document.write(): ',arguments); 
    if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);  
  };
})(document);

//This logic is added to play mp3 file from downloads page
var my_window;
	
	function playMp3(obj) {
		if(my_window) {
			my_window.close();
		}
		
		var html = '<embed src="' + obj.getAttribute("href") + '" type="audio/mpeg" />';
		//var html = '<embed type="application/x-shockwave-flash" flashvars="audioUrl=' + obj.getAttribute("href") + '" src="http://www.google.com/reader/ui/3523697345-audio-player.swf" width="400" height="27" quality="best"  wmode="opaque"></embed>';		
		my_window = window.open("", "mywindow1", "status=0,menubar=0,resizable=0,width=415,height=210");
		//my_window.document.write('<h1>Ravinder</h1>');
    	my_window.document.write(html);
		
		
		return false;
	}

