 /** 
* @projectDescription France 2 & France 3, versions 2.0
* @author	[FTVI] Guyllaume Doyer
* JSLint validated http://www.jslint.com/
*/

/* !!! DO NOT MODIFY FUNCTIONS ORDER !! */
/* (required to pass jslint validation  */

/* submitVdoRelatedForm(),handleVideoLinks(),
 * iniContentsListeners(),iniContentsListenersSpecific(),initAjaxNewContentsHandlers(),
 * preload(),
 * fixDisappearingAdTop(),
 * fakeFunction(),kill(),
 * decodeHTMLChars(),
 * cleanAds(),cleanFlashLayers(),
 * handleVDOBlockScroller(),handleFlashNewsScroller(),
 * handleHiddenContents(),
 * rotateSpecialLastInfo(),handleSpecialLastInfo(),
 * deleteCookies(),getURLParamValue(),
 * addFavorite(),
 * searchengine(),handleTagCloudLinks(),
 * handleSmenuJtRegions(),
 * moveAd()
 */


// ----------------------------------------------------- \\
// This function submits the form related to the Video 
// Link whose id is given as the paramater
// ----------------------------------------------------- \\
function submitVdoRelatedForm(vdoID)
{
	var itemCtnr = $(".vdoItemsData[id=videoToCall_" + vdoID +"]");
	itemCtnr.children("form").attr("onsubmit","return false;").attr("target","myPopUp");
	
	var tmp = itemCtnr.children("form").attr("action");
	var url = (tmp.indexOf(VdoRelatedBaseURL)) ? VdoRelatedBaseURL + tmp : tmp; // VdoRelatedBaseURL is defined in conf.js
	itemCtnr.children("form").attr("action", url);
	itemCtnr.find("form input[name=courant]").attr("value", vdoID);
	
	window.open(url,'myPopUp','width=634,height=469,status=no,location=no,toolbar=no,scrollbars=auto,menubar=no,resizable=yes');
	itemCtnr.children("form").trigger("submit");
}



// ----------------------------------------------------- \\
// This function handles Video Links. Gets its id then
// call the function to submit the related form
// ----------------------------------------------------- \\
function handleVideoLinks()
{
	$(".handleVdoLnk").click(function()
	{
		var vdoID = $(this).attr("id");
		
		// Removes every no-numeric characters from the string
		vdoID = vdoID.replace(/\D/g,'');
		submitVdoRelatedForm(vdoID);
		return false;
	});
}



// ----------------------------------------------------- \\
// This function defines functions that have to be executed
// one an ajax block content is reloaded.
// It can/should be overloaded in pages secifics js files
// such as home_f2.js
// ----------------------------------------------------- \\
function iniContentsListeners(context)
{
	handleVideoLinks(context);
	handleTargetBlank(context);
	handleCustomPopup(context);
	finishDesign();
}


// ----------------------------------------------------- \\
// This function has to (and will) be overridden in the 
// page specific js files
// ----------------------------------------------------- \\
function iniContentsListenersSpecific()
{
	// none
}



// ----------------------------------------------------- \\
// This function MUSTN'T be called on page ready or load
// event.
// ----------------------------------------------------- \\
function initAjaxNewContentsHandlers(context)
{
	iniContentsListeners(context);
	iniContentsListenersSpecific(context);
}



// ----------------------------------------------------- \\
// This function allows you to preload the element whose
// src is given in parameter
// ----------------------------------------------------- \\
function preload(eltSRC)
{
	$("<img>").attr("src", eltSRC);	
	return eltSRC;
}



// ----------------------------------------------------- \\
// This function fix disappearing Top Ad (didn't worked
// with just css
// ----------------------------------------------------- \\
function fixDisappearingAdTop()
{
	/* If Browser is Internet Explorer
	if($.browser.msie)
	{
		$("#eAdBlkLargeBanner, #adSkyscrapper02").css("zoom","1");
	}
	*/
}



// Default Vars
var ajaxLoadingPixSRC = preload(ajaxLoadingPixPath);
var ajaxLoadingPix = '<img class="throbber" src="' + ajaxLoadingPixSRC + '" alt="Pictogramme : chargement en cours" />';
var ajaxLoadingMsg = '<span class="ajaxRequesting">' + ajaxLoadingPix + '<span> Chargement en cours</span></span>';

var isTopShowAnimRunning = false;
var isFlashNewsAnimRunning = false;

var posSMenuPrograms = (ftvi_portail == "france3" ) ? 68  : -6;
var posSMenuRegions = -9;

var alreadyLoadedAreaMap = false;

var userAcceptCookies = true;



// ----------------------------------------------------- \\
// This function does not do anything (but is used, 
// so DO NOT REMOVE !!)
// ----------------------------------------------------- \\
function fakeFunction()
{
	// none
}




// ----------------------------------------------------- \\
// This function removes the element whose selector is
// given in parameter
// ----------------------------------------------------- \\
function kill(selector)
{
	$(selector).remove();
}



// ----------------------------------------------------- \\
// This function removes unwanted elements in pub
// ----------------------------------------------------- \\
function decodeHTMLChars(chaine){
	var chars=new Array(
		'&#224;##à',
		'&#226;##â',
		'&#228;##ä',
		'&#230;##æ',
		'&#231;##ç',
		'&#233;##é',
		'&#232;##è',
		'&#234;##ê',
		'&#235;##ë',
		'&#238;##î',
		'&#239;##ï',
		'&#241;##ñ',
		'&#244;##ô',
		'&#246;##ö',
		'&#156;##oe',
		'&#249;##ù',
		'&#251;##û',
		'&#252;##ü',
		'&#171;##«',
		'&#187;##»',
		'&#180;##´',
		'&#39;##\'',
		'&#178;##²',
		'&#133;##...',
		'&#149;##-'
	);
	for(i=0;i<chars.length;i++){
		var couple=chars[i].split('##');
		var caractere=new RegExp(couple[0],'g');
		chaine=chaine.replace(caractere,couple[1]);
	}
	return chaine;
}



// ----------------------------------------------------- \\
// This function removes unwanted elements in pub
// ----------------------------------------------------- \\
function cleanAds()
{
	// If Browser is Internet Explorer & version < 7
	if($.browser.msie && jQuery.browser.version < 7)
	{
		$("#adVdoBlk").find("br").remove().end().find("img[src*=vide.gif]").remove().end().find("img[src*=pub.gif]").remove();
	}
}



// ----------------------------------------------------- \\
// This function clean the flash object that are not
// correctly formed to be fully cross-browser proof
// (Especialy on Firefox in which they could be not
// transparent when required
// ----------------------------------------------------- \\
function cleanFlashLayers(ctnrSelector)
{	
	var flashObjNb = $(ctnrSelector + " object").length;
	
	// Si on a au moins un Object
	if(flashObjNb >= 1)
	{
		$(ctnrSelector + " object param[name*=wmode]").attr("value","transparent"); // Fix no "transparent" value on wmode param
		
		// If Browser is not Internet Explorer
		if(!$.browser.msie)
		{
			// Remove "embed" tags since they prevent Flash elements
			// to be overlayed by absolute positioned elements
			var jqobj = $(".cmnBlk.adVdoBlk object embed");
			if (jqobj.length >= 1)
			{
			 var src = jqobj.attr("src");
			 var w = jqobj.attr("width");
			 var h = jqobj.attr("height");
			 var newobj = '<!--[if !IE]><--><object data="' + src + '" type="application/x-shockwave-flash" width="' + w + '" height="' + h + '"><param name="wmode" value="transparent" /></object><!--><![endif]-->';
			 jqobj.remove();
			 $(ctnrSelector + " object").append(newobj);
			}
		}
	}
}




// ----------------------------------------------------- \\
// This functions handle VideoBlocks and its content items
// changing behaviors
// ----------------------------------------------------- \\
function handleVDOBlockScroller(parentSelector)
{
	var dataSelector = parentSelector + " .vdoItemsData";
	
	$(parentSelector + " .jsJump2PreviousItem").click(function()
	{
		var firstItem = $(parentSelector + " .vdoItemsData:first");
		if ( firstItem.hasClass("current") === true ) // If the first item is the current one, the "previous" item must be the last one
		{
			firstItem.removeClass("current");
			$(dataSelector + ":last").addClass("current");
		}
		else
		{
			$(dataSelector + ".current").not(dataSelector + ":first").removeClass("current").prev().addClass("current");
		}
		updateCtntPix(parentSelector);
	});
	
	$(parentSelector + " .jsJump2NextItem").click(function()
	{
		var lastItem = $(parentSelector + " .vdoItemsData:last");
		if ( lastItem.hasClass("current") === true ) // If the last item is the current one, the "next" item must be the first one
		{
			lastItem.removeClass("current");
			$(dataSelector + ":first").addClass("current");
		}
		else
		{
			$(dataSelector + ".current").not(dataSelector + ":last").removeClass("current").next().addClass("current");
		}
		updateCtntPix(parentSelector);
	});
	
	function updateCtntPix(parentSelector)
	{
		var jqCtntPix = $(parentSelector + " .pxBlk img.ctntPx");
		jqCtntPix = jqCtntPix.attr("src",PixURL); // PixURL is defined in conf.js		
		var newPixSRC = $(parentSelector + " .vdoItemsData.current .itemSTitle").attr("title");

		var ext;
		if (newPixSRC.indexOf(".JPG") > -1){ ext = ".JPG"; }
		else { ext = ".jpg"; }

		// whitePixURL is defined in conf.js
		newPixSRC = (newPixSRC === undefined) ? whitePixURL : newPixSRC.substring(0,newPixSRC.indexOf(ext)) + "_" + "192_144" + ext;
		jqCtntPix.attr("src",newPixSRC);
		
		updateVdoLnk(parentSelector); // Then updates the video link
	}
	
	function updateVdoLnk(parentSelector)
	{
		var newVidHref = $(parentSelector + " .vdoItemsData.current a").attr("href");
		$(parentSelector + " .pxBlk .targBlank").attr("href", newVidHref);
	}
}


// ----------------------------------------------------- \\
// Image de la fonction handleVDOBlockScroller modifiée pour qu'elle fonctionne pour SPIP 
// (ne pas rajouter de _192_144 à la suite de l'URL de l'image pour la taille)
// -> A voir s'il ne serait pas plutôt préférable d'intégrer ça sous la forme d'un paramètre optionnel de la dite fonction
// ----------------------------------------------------- \\
function handleVDOBlockScrollerSPIP(parentSelector)
{
	var dataSelector = parentSelector + " .vdoItemsData";
	
	$(parentSelector + " .jsJump2PreviousItem").click(function()
	{
		var firstItem = $(parentSelector + " .vdoItemsData:first");
		if ( firstItem.hasClass("current") === true ) // If the first item is the current one, the "previous" item must be the last one
		{
			firstItem.removeClass("current");
			$(dataSelector + ":last").addClass("current");
		}
		else
		{
			$(dataSelector + ".current").not(dataSelector + ":first").removeClass("current").prev().addClass("current");
		}
		updateCtntPix(parentSelector);
	});
	
	$(parentSelector + " .jsJump2NextItem").click(function()
	{
		var lastItem = $(parentSelector + " .vdoItemsData:last");
		if ( lastItem.hasClass("current") === true ) // If the last item is the current one, the "next" item must be the first one
		{
			lastItem.removeClass("current");
			$(dataSelector + ":first").addClass("current");
		}
		else
		{
			$(dataSelector + ".current").not(dataSelector + ":last").removeClass("current").next().addClass("current");
		}
		updateCtntPix(parentSelector);
	});
	
	function updateCtntPix(parentSelector)
	{
		var jqCtntPix = $(parentSelector + " .pxBlk img.ctntPx");
		jqCtntPix = jqCtntPix.attr("src",PixURL); // PixURL is defined in conf.js		
		var newPixSRC = $(parentSelector + " .vdoItemsData.current .itemSTitle").attr("title");

		// whitePixURL is defined in conf.js
		newPixSRC = (newPixSRC === undefined) ? whitePixURL : newPixSRC;
		jqCtntPix.attr("src",newPixSRC);
		
		updateVdoLnk(parentSelector); // Then updates the video link
	}
	
	function updateVdoLnk(parentSelector)
	{
		var newVidHref = $(parentSelector + " .vdoItemsData.current a").attr("href");
		$(parentSelector + " .pxBlk .targBlank").attr("href", newVidHref);
	}
}



// ----------------------------------------------------- \\
// This function makes the Flash News to scroll
// infinitively.
// ----------------------------------------------------- \\
function handleFlashNewsScroller(ctnrSelector)
{
	var firstItem = $(ctnrSelector + " .newsLkIt:first");
	var w = "-" + firstItem.width() + "px";
	
	// Copy the first item at the end of the container
	firstItem.clone().appendTo(ctnrSelector);
	if (isFlashNewsAnimRunning !== true)
	{
		// makes the 1st item to disappear	
		$(ctnrSelector + " .newsLkIt:first").animate({marginLeft:w}, 10000, "linear", function(){ destroyFirstItem(); isFlashNewsAnimRunning = false; } );
	}
	
	function destroyFirstItem()
	{
		$(ctnrSelector + " .newsLkIt:first").remove();
	}
}



// ----------------------------------------------------- \\
// This function hides the "Plus de programmes" contents  
// then listens for a click on the button to show/hide it
// ----------------------------------------------------- \\
function handleHiddenContents(ctnrSelector)
{	
	// Hidden by default (once the page is loaded)
	$(ctnrSelector + " .jsHiddenContentsBlk").hide();
	
	// Toggle on click
	$(ctnrSelector + " .jsHiddenContentsToggleBtn a").click( function() 
	{
		$(this).toggleClass("less").parents(".cmnBlk").find(".jsHiddenContentsBlk").slice(0,1).slideToggle("normal");
		
		var label = $(this).find("span.label");
		
		if ( label.text() == "Plus de programmes" ) { label.text("Moins de programmes"); }
		else if ( label.text() == "Moins de programmes" ) { label.text("Plus de programmes"); }
		
		return false;
	});
}



// ----------------------------------------------------- \\
// This function handles the rotation of the contents of 
// its whose selector is given as first parameter
// ----------------------------------------------------- \\
function rotateSpecialLastInfo(parentSelector, rotationInterval)
{
	var zenbu = $(" .newsLkIt.captionNews", parentSelector);
	var itemsNb = zenbu.length;
	var curItem = $(" .newsLkIt.captionNews.current", parentSelector);
	var curItemIndex = zenbu.index(curItem[0]);
	var nextItemIndex = (curItemIndex == itemsNb - 1) ? 0 : curItemIndex + 1;
	
	curItem.removeClass("current");
	zenbu.slice(nextItemIndex, nextItemIndex+1).addClass("current");
	
	// Changes TabItems Status
	$(".tabsBlk.fullWidth .tabIt", parentSelector).removeClass("current").slice(nextItemIndex, nextItemIndex+1).addClass("current");
	
	// Makes the functio to loop
	setTimeout( function(){ rotateSpecialLastInfo(parentSelector, rotationInterval); }, rotationInterval);
}



// ----------------------------------------------------- \\
// This function handles Special LastInfo Block with
// big tabs that toggle the caption news
// ----------------------------------------------------- \\
function handleSpecialLastInfo(parentSelector, rotationInterval)
{
	// By default, hides every item except the current one
	$(" .newsLkIt.captionNews", parentSelector).not(".current");
	
	// If rotator is set to true, launch the function
	if (rotationInterval > 0) { setTimeout( function(){ rotateSpecialLastInfo(parentSelector, rotationInterval); }, rotationInterval); }
	
	// On click,
	$(" .tabsBlk.fullWidth .tabIt", parentSelector).click(function()
	{
		var jq_obj = $(this);
		// Gets the index of the clicked item
		var clickedItemNb = $(parentSelector + " .tabsBlk.fullWidth .tabIt").index( $(this)[0] );
		
		$(".newsLkIt.captionNews", parentSelector).removeClass("current").slice(clickedItemNb,clickedItemNb+1).addClass("current");

		// Changes TabItems Status
		$(".tabsBlk.fullWidth .current", parentSelector).removeClass("current");
		$(jq_obj).addClass("current");

		iniContentsListeners(); // Function handling listenig functions that concearn tabs contents

		return false;
	});
}



// ----------------------------------------------------- \\
// This function deletes cookies
// ----------------------------------------------------- \\
function deleteCookies()
{
	$("#resetMyPref").click( function()
	{
		$.cookie('ftvi_f2_showTooltipSortableBlocks', null);
		$.cookie('ftvi_myregion', null);
		
		return false;
	});
}



// ----------------------------------------------------- \\
// This function gets, in an URL, the value of the param
// given in the function call
// ----------------------------------------------------- \\
function getURLParamValue(requestedURL, requestedParamName)
{
	// Get start position of the param
	var pos = requestedURL.indexOf(requestedParamName);
	
	if (pos != -1 & requestedParamName !== "")
	{
		// Truncate the string from this position to its end
		var tmp = requestedURL.substr(pos);
		
		// Get the start position of the param value
		var start = pos + requestedParamName.length;
		
		// Get end position of the param value
		var end_pos;
		
			if (tmp.indexOf("&amp;") != -1) { end_pos = tmp.indexOf("&amp;"); } // case where there are others params after, separate by "&amp;"
			else if (tmp.indexOf("&") != -1 ) { end_pos = tmp.indexOf("&"); } // case where there are others params after, separate by "&"
			else if (tmp.indexOf("#") != -1 ) { end_pos = tmp.indexOf("#"); } // case where there are others params after, separate by "#"
			else { end_pos = tmp.length; } // case where there are no others params after
		
		var requestedParamValue = tmp.substring(requestedParamName.length + 1,end_pos); // truncates the string from 0 to end of the param value
		
		return requestedParamValue;
	}
	else
	{
		return false;
	}
}


// ----------------------------------------------------- \\
// This function helps disabled persons to place a bookmark 
// of the currentPage ITA
// ----------------------------------------------------- \\
function addFavorite(){
	$('a.addBookmark').click(function(){
		var lnk=$(this).attr('href');
		var lnkTxt=$(this).attr('rel');
		if(window.sidebar){
			window.sidebar.addPanel(lnkTxt,lnk,"");
		}
		else if($.browser.msie){
			window.external.AddFavorite(lnk,lnkTxt);
		}
		else{
			return true;
		}
		return false;
	});
}

// ----------------------------------------------------- \\
// This function launches the search engine
// ----------------------------------------------------- \\
function searchengine()
{
}



// ----------------------------------------------------- \\
// This function handles TagClouds links. Gets the word
// clicked then submit the search form with this keyword
// as the search field val input
// ----------------------------------------------------- \\
function handleTagCloudLinks()
{
	$("#tagcloudBlk .tagcloudLst a").not(".letLive").click(function()
	{
		var word = $(this).text();
		$("form#searchform input#q").val(word);
		$("form#searchform").trigger("submit");
		return false;
	});
}



// ----------------------------------------------------- \\
// This function handles JT submenus
// ----------------------------------------------------- \\
function handleSmenuJtRegions()
{	
	var jtReg =
	{
		idCurrent: "",

		init: function()
		{
			$("#jtListe .titleBtnsLst .titleBlk").
				mouseover( function() { jtReg.over($(this)); } ).
				focus( function() { jtReg.over($(this)); } ).
				mouseout( function() { jtReg.out($(this)); } ).
				blur( function() { jtReg.out($(this)); } );
			
			
			$("#jtRegions").
				mouseover( function() { $(this).show(); } ).
				focus( function() { $(this).show(); } ).
				mouseout( function() { $(this).hide(); } ).
				blur( function() { $(this).show(); } );
			
			return this;
		},
		
		over: function(jqOjb)
		{
			// Get the related submenu id of the hovered item
			jtReg.idCurrent = $("h3", jqOjb).attr("id");
			
			// Hide every submenu
			$(".eListeJtSMenu").hide();

			// Show the related to the hovered item
			$("#jtRegions").show().find("#eListe" + jtReg.idCurrent).show();
			var hauteurCols=$("#jtRegions").show().find("#eListe" + jtReg.idCurrent).height();
			hauteurCols+=parseInt($("#jtRegions").show().find("#eListe" + jtReg.idCurrent).css('padding-top'));
			hauteurCols+=parseInt($("#jtRegions").show().find("#eListe" + jtReg.idCurrent).css('padding-bottom'));
			$('#jtRegions #eSMenuJtL, #jtRegions #eSMenuJtR').height(hauteurCols);
			return this;
		},
		
		out: function()
		{
			$("#jtRegions").hide();
			
			return this;
		}
		
	};

	jtReg.init();
	
}



// ----------------------------------------------------- \\
// This function moves ads after they've been called (in
// order to load them at the end of the page to avoid
// conflicts between badly coded ad scripts and our 
// clean non obtrusive javascript
// ----------------------------------------------------- \\
function moveAd(adContentSelector, adMove2Selector)
{
	var jqobj = $(adContentSelector);
	var jqobj2 = $(adMove2Selector);

	if (jqobj.length > 0 && jqobj2.length > 0)
	{

		// Moves the loaded ad to its "normal" container
		var tmp = jqobj.contents().not("script").appendTo(adMove2Selector);
		
		// If the browser is Internet Explore, fixes disappearing element
		if($.browser.msie){
			$(adMove2Selector).css("visibility", "visible");
			$("#eAdBlkLargeBanner, #adSkyscrapper01, #adSkyscrapper02").css("zoom","1");
			}

		// Removes contents juste moved to avoid having ads twice
		jqobj.contents().not("script").remove();

	}	
}

// ----------------------------------------------------- \\
// This function handles thumbsets that cycle
// ----------------------------------------------------- \\
function handleCycleScroll(speed)
{
	$('.thumbsContent').cycle({
		fx: 'scrollHorz',
		speed: speed,
		timeout: 0,
		next: '.jsTnScrollerLeftLnk',
		prev: '.jsTnScrollerRightLnk'
	});
}
