/** 
* @projectDescription France 2 & France 3, versions 2.0
*
* @author	Mururoa Project Team
* @version	0.1 
*/



// ----------------------------------------------------- \\
// This function listens for the click on "js_tn_scroller" 
// buttons then perfoms scrolling in the good direction
// ----------------------------------------------------- \\
function handleTopShowsScroller(contextSelector, rotationInterval, mode)
{
	
	var ts = 
	{
		// AjaxTopShowsDataURL: "/blocks/data/our_shows_caption_data.json";
		context: $(contextSelector),
		tnNb: $(".showCptPicsTn", this.context).length,
		tnSelector: contextSelector + " .showCptPicsTn",
		tnViewPics: 3,
		jsonLoadedData: "",
		alreadyLoadedData: false,
		rotationLoop: null,
		setReflects: false,
		thumbSetWidth: (mode == "simpleMode") ? 273 : 210,
		
		scrollListener: function()
		{
			$(".jsTnScrollerLeftLnk, .jsTnScrollerRightLnk", ts.context).click( function()
			{	
				// Stop rotation function
				if (rotationInterval) { ts.rotator.stop(); }
				
				// Set dir var depending of the clicked button
				var dir;
				if ( $(this).hasClass("jsTnScrollerLeftLnk") === true ) { dir = "dirRight"; }
				else { dir = "dirLeft"; }
				
				if(isTopShowAnimRunning !== true && ts.tnNb > 3) { isTopShowAnimRunning = true; ts.scroll(dir); }
			});
			
			return this;
		},


		scroll: function(dir)
		{
			var dest = $(".thumbsContent", ts.context);
			
			if(dir == "dirLeft")
			{
				var firstTumbsSet = $(".thumbsSet", ts.context).slice(0,1);
				firstTumbsSet.clone(true).appendTo(dest).end().animate({width:"0px"}, 800, "linear", function()
				{
					firstTumbsSet.remove();
					isTopShowAnimRunning = false;
					if (typeof(rotationInterval) != "undefined" && rotationInterval > 0) { ts.rotator.init(); }

				});
			}
			else
			{
				var lastTumbsSet = $(".thumbsSet", ts.context).slice(-1);
				lastTumbsSet.clone(true).prependTo(dest).width("0px").animate({width:ts.thumbSetWidth + "px"}, 800, "linear", function()
				{
					lastTumbsSet.remove();
					isTopShowAnimRunning = false;
					if (typeof(rotationInterval) != "undefined" && rotationInterval > 0) { ts.rotator.init(); }
				});
			}
			
			return this;
		},


		rotator:
		{
			
			init: function()
			{
				ts.rotator.selectFirst();
				return this;
			},
			


			selectFirst: function()
			{
				$("a.showCptPicsTn", ts.context).slice(0,1).trigger("click");
				return this;
			},

			
			
			goNext: function(current)
			{
				var curJqobj = ( typeof(current) === "undefined" ) ? $("a.showCptPicsTn.current", ts.context) : current;
				
				var currentSetThumbsNb = curJqobj.parents("div.thumbsSet", ts.context).find("a.showCptPicsTn").length;
				var curIndex = $("a.showCptPicsTn", ts.context).index(curJqobj[0]);
				
				ts.rotationLoop = setTimeout( function()
				{
					
					if ( (curIndex >= ts.tnViewPics-1 && currentSetThumbsNb == ts.tnViewPics) || curIndex >= currentSetThumbsNb-1)
					{
						$(".jsTnScrollerRightLnk", ts.context).trigger("click");
					}
					else
					{		
						// Trigger click on the next pics and adds "current" class on it
						$("a.showCptPicsTn", ts.context).slice(curIndex+1, curIndex+2).trigger("click", [true]);
					}

					
				}, rotationInterval);
				
				return this;
			},
			
			
			reset: function()
			{
				ts.rotator.stop();
				ts.rotator.init();
				
				return this;
			},
			
			stop: function()
			{
				clearTimeout(ts.rotationLoop);
				
				return this;
			}
			
		},
		

		showBigListener: function(doNotGoNext)
		{
			// Listens for the click on elements then changes main pics
			$(".showCptPicsTn", ts.context).attr("hidefocus","hidefocus").click( function(event, triggered)
			{
				if (!doNotGoNext)
				{	
					ts.rotator.stop($(this));
					
					// Remove "current" class on all the pics
					$(".showCptPicsTn", ts.context).removeClass("current");
					
					// Add "current" class on clicked item
					$(this).addClass("current");
					
					// Get the id of the clicked element and update data with ajax
					var clickedItemID = $(this).attr("id");
					if ( clickedItemID !== "" ) { ts.getData(clickedItemID); }
					
					// Launch timeout
					if (rotationInterval) { ts.rotator.goNext($(this));	}
				}
				
				return false;
			});
			
			return this;
		},
				

		preloadPics: function(data)
		{
			$.each(data, function(key, value)
			{
				var PicsSRCSize = value.imgSize;
				var picsSRC = value.img.replace(/()(.jpg)/i, '$1'+PicsSRCSize+'$2');
				
				preload(picsSRC);
			});
			
			return this;
		},
				
				
		getData: function(clickedItemID)
		{
			if (ts.alreadyLoadedData === false )
			{
	
				var req = $.ajax(
				{
					url: AjaxTopShowsDataURL,  // URL defined in conf.js
					dataType: "json",
					success: function(data)
					{
						// Set the already loaded data var to true
						ts.alreadyLoadedData = true;
						
						// Keep the data into a var
						ts.jsonLoadedData = data;
						
						// If the function has been called passing a clickedItemID param, we update data
						// else we lanch the function to preload pics
						if (typeof(clickedItemID)!= "undefined")
						{
							ts.updateData(data, clickedItemID);	
						}
						else
						{
							ts.preloadPics(data);
						}
			
			 		},
					error: function () { if (window.console && window.console.error){ console.error(arguments); } }
				});						
			}
			else
			{
				// Launch data update using existing data var
				ts.updateData(ts.jsonLoadedData, clickedItemID);
			}
			
			return this;
		},


		updateData: function(data, clickedItemID)
		{	
			$.each(data, function(key, value)
			{	
				if (key == clickedItemID)
				{	
					var newTitle = value.title;
					var newDate = value.date;
					var newSummary = value.description;
					var newHREF = value.link;
					var newBigPicsSRCSize = value.imgSize;
					var newBigPicsSRC = value.img.replace(/()(.jpg)/i, '$1'+newBigPicsSRCSize+'$2');
					
					$("#show_cpt_date_n_title_line .itemTitle", ts.context).empty().append(newTitle).attr("href",newHREF);
					$("#show_cpt_date_n_title_line .itemDate", ts.context).empty().append(newDate).attr("href",newHREF);
					$("#showCptTnNSummaryLine .itemSummary", ts.context).empty().append(newSummary);
					$("#topShowCaptionPxLnk", ts.context).attr("href",newHREF);
					$(".ctntBlk .pxBlk img", ts.context).attr("src",newBigPicsSRC);
					
					
					var tmp = OAS_sitepage.indexOf("programmes/series-et-fictions");
					
					// In the case we are in the "series & fictions" page and if there's a "related-links" element in the data
					if (tmp > -1 &&  value.relatedLinks )
					{	
						var opening = '<ul class="tabsLst">';
						var ending = '</ul>';
						var content = '';
						var count = 0;

						$.each(value.relatedLinks, function(subKey, subValue)
						{
							content += '<li class="tabIt"><a href="' + subValue.link + '" class="' + subValue.cssClass + '"><span class="left">&nbsp;</span><span class="label">' + subValue.label + '</span><span class="right">&nbsp;</span></a></li>';
							count++;
						});

						if (content !== '')
						{
							var newlinks = opening + content + ending;
							$("#showCptTnNSummaryLine .tabsBlk .tabsLst", ts.context).replaceWith( newlinks );
						}

						$("#showCptTnNSummaryLine #ts_relatedLink0", ts.context).attr("href", newHREF);


					}
				}
			});
			
			return this;
		},

				
		reflector: function()
		{
			if (ts.setReflects === true)
			{
				$(".showCptPicsTn img.ctntPx, .showCptPicsTn img.reflected", ts.context).slice(0,3).reflect({height: 0.3, opacity: 0.6});
			}
			
			return this;		
		}
							
	};


	// Initialisation functions
	ts.scrollListener().showBigListener().reflector();
	if ( rotationInterval && rotationInterval > 0) { ts.rotator.init(); }	


}



// ----------------------------------------------------- \\
// This function hides by default each element of a menu
// and listens to the click on its items, then toggles
// ----------------------------------------------------- \\
function handleMenu(menu2Handle, submenu2handle)
{
	$(menu2Handle + " " + submenu2handle).hide();
		
	$("#eMenuItPrograms").hoverIntent(
	{
	 sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
	 interval: 10, // number = milliseconds for onMouseOver polling interval
	 over: handleSMenuPrograms, // function = onMouseOver callback (required)
	 timeout: 0, // number = milliseconds delay before onMouseOut
	 out: fakeFunction // function = onMouseOut callback (required)
	});
	
	$("#eMenuItPrograms").mouseout(function() { loadSMenuPrograms($(this),"abort"); $("#eSMenuPrograms").hide(); });
	$("#eSMenuPrograms").mouseover(function() { $(this).show(); }).mouseout(function() { $(this).hide(); });
	
}



// ----------------------------------------------------- \\
// This function calls the ajax request function for the
// SMenuPrograms if not already called, then
// display the menu
// ----------------------------------------------------- \\
function handleSMenuPrograms()
{
//	if (alreadyLoadedSMenuProg != true && loadingSMenuProg != true) { loadSMenuPrograms($(this),"load"); }
	$("#eSMenuPrograms").show().css("left",84).css({position: "absolute", top:"-4px"});
	handleSMenuProgramsCtntDimensions();
}


// ----------------------------------------------------- \\
// This function loads (with ajax) the "Programs" SMenu
// Contents
// ----------------------------------------------------- \\
function loadSMenuPrograms(jq_ob, action)
{
	// If called action is "load", the request is done
	if (action == "load")
	{
		loadingSMenuProg = true;
		
		var reqSMenuPrograms = $.ajax(
		{
			// URL defined in conf.js
			url: loadSMenuProgramsURL,
			dataType: "html",
			success: function()
			{
				var dataSMenuPrograms = reqSMenuPrograms.responseText;
				
				alreadyLoadedSMenuProg = true;
				$(".ajaxRequesting").remove();
				$(".eSMenu#eSMenuPrograms").html(dataSMenuPrograms);
				
				handleSMenuProgramsTabs();
				handleSMenuProgram3cols();
	 		},
			error: function () { if (window.console && window.console.error){ console.error(arguments); } }
		});
		
		ajaxRequestinghelper = ajaxLoadingMsg;
		$("#supportNav .ajaxRequesting").remove();
		$("#supportNav").append(ajaxRequestinghelper);
		
		reqLoadingSMenuProg = reqSMenuPrograms;
	}
	
	// Else the request is aborted
	else
	{
		if ( reqLoadingSMenuProg ) { reqLoadingSMenuProg.abort(); $("#supportNav .ajaxRequesting").remove(); loadingSMenuProg = false; }
	}
	
	// If Browser is Internet Explorer & version < 7
	// we have to emulate :hover on <li>
	if($.browser.msie && jQuery.browser.version < 7)
	{
		$("#eSMenuPrograms ul#eOngletsLettres li").mouseover( function()
		{
			$("#eOngletsLettres li").removeClass("iehover"); // Instead of mouseout behavior, we remove classes iehover from here
			$(this).addClass("iehover");
		});
		//$("#eSMenuPrograms ul#eOngletsLettres li").mouseout( function() { $(this).removeClass("iehover"); }); // Creates a bug (flickering)
	}
}



// ----------------------------------------------------- \\
// This function handles SubMenu Program Contents Dimensions
// ----------------------------------------------------- \\
function handleSMenuProgramsCtntDimensions()
{
	// Gets submenu content dimensions then updates shadow pics dimensions to fit
	var tmp_h = $("#eHead #eSMenuCtnt").height();
	var tmp_w = $("#eHead #eSMenuCtnt").width();
	$("#eSMenuL, #eSMenuR").height(tmp_h);
	$("#eSMenuBM").width(tmp_w-10);
	$("#eSMenuTM").width(tmp_w+2);
	
	// Sets equal heights for the lists
	var topPad = $("#eHead #eLettresAlpha").css("padding-top");
	var botPad = $("#eHead #eLettresAlpha").css("padding-bottom");
	$("#eHead #eLettresAlpha").height(tmp_h - parseInt(topPad) - parseInt(botPad));

}




function handleCloseBtns()
{
	$(".btnFermer").click(function() { window.close(); });
}