(function(window, $, undef) {
	(function(dep) {
		for(var i in dep) {
			if(dep[i] === undef || dep[i] === false) {
				throw 'Dépendence non satisfaite : '+i;
			}
		}
	})({
		jQuery							: $
		,jQueryScrollingResizedMenu		: $.fn.scrollingResizedMenu
	});
	$(function() {
		
		// ------------------------------------ \\
		// ********** Menu Principal ********** \\
		
		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;
			}
		}

		
		var getCacheAjaxPath = '/appftv/dfusion/getCache.php',
			forcerCache = '&forcerCache=1',
			debutURLPortail = getCacheAjaxPath + '?bloc=' + ftvi_portail + '.fr:'
			loadSMenuProgramsURL = debutURLPortail + 'common:submenu_programmes_block' + forcerCache,
			SMenuProgramsTabsURL = debutURLPortail + 'common:submenu_programmes_block_tabs' + forcerCache,
			
			SMenuRegionsCache = '/layoutftv/arches/france32/modeles/submenu_regions.php',
			
			posSMenuPrograms = (ftvi_portail == "france3" ) ? 75  : -6,
			posSMenuRegions = -5,
			
			portailCSSPath = '/layoutftv/arches/' + ftvi_portail + '/stylesheets',
			ajaxLoadingPixPath = portailCSSPath + '/img/cursors/loading_02.gif',
			
			ajaxLoadingPix = '<img class="throbber" src="' + ajaxLoadingPixPath + '" alt="Pictogramme : chargement en cours" />',
			ajaxLoadingMsg = '<span class="ajaxRequesting">' + ajaxLoadingPix + '<span> Chargement en cours</span></span>';
		
		var HandleMenu = function() {
		
			var progMenu = "#eSMenuPrograms";
			var progMenuActivator = "#eMenuItPrograms";
			var regMenu = "#eSMenuRegions";
			var regMenuActivator = "#eMenuItRegions";

			var menu = {
				
				reqSMenuProg: null,
				loadedSMenuProg: false,
				loadingSMenuProg: false,
				
				reqSMenuReg : null,
				loadedSMenuReg: false,
				loadingSMenuReg: false,


				init: function(menuSelector, menuActivationSelector)
				{
					$(menuActivationSelector).
						mouseover( function() { menu.over(menuSelector); } ).
						focus( function() { menu.over(menuSelector); } ).
						mouseout( function() { menu.out(menuSelector); } ).
						blur( function() { menu.out(menuSelector); } );
					
					return this;
				},


				over: function(menuSelector)
				{
					// Case of the "Programmes" Submenu
					if ( menuSelector === progMenu )
					{
						if (!menu.loadedSMenuProg && !menu.loadingSMenuProg) { menu.loadingSMenuProg = true; menu.loadSMenuProg(menuSelector, "load"); }
						else { menu.show(menuSelector); }	
					}
					else if ( menuSelector === regMenu )
					{					
						if (!menu.loadedSMenuReg && !menu.loadingSMenuReg) { menu.loadingSMenuReg = true; menu.loadSMenuReg(menuSelector, "load"); }
						else { menu.show(menuSelector); }
					}
					else
					{
						menu.show(menuSelector);
						$(menuSelector).
							mouseover( function() { $(this).show(); } ).
							mouseout( function() { $(this).hide(); } ).
							focus( function() { $(this).show(); } ).
							blur( function() { $(this).hide(); } );
					}
					
					return this;
				},


				out: function(menuSelector)
				{
					// Case of the "Programmes" Submenu
					if ( menuSelector === progMenu )
					{
						menu.loadSMenuProg(progMenu, "abort");
						menu.hide(progMenu);
					}
					else if ( menuSelector === regMenu )
					{
						menu.hide(menuSelector);
					}
					
					return this;
				},


				loadSMenuProg: function(menuSelector, action)
				{
					// If called action is "load", we do the request
					if (action == "load")
					{
						menu.reqSMenuProg = $.ajax(
						{
							// URL defined in conf.js
							url: loadSMenuProgramsURL,
							dataType: "html",
							//beforeSend: function()
							//{
							//	if ( $("#supportNav .ajaxRequesting").length < 1 ) { $("#supportNav").append(ajaxLoadingMsg); }
							//},
							success: function(data)
							{
								menu.loadedSMenuProg = true;

								// Remove throbber
								//$("#supportNav .ajaxRequesting").remove();
								
								// Insert data
								$(menuSelector).html(data).
									mouseover( function() { $(this).show(); } ).
									mouseout( function() { $(this).hide(); } ).
									focus( function() { $(this).show(); } ).
									blur( function() { $(this).hide(); } );

								// Display the menu
								menu.show(menuSelector);
								
								// Ad a trobber
								$("#eLettresAlpha").append(ajaxLoadingMsg);
								
								
								// Launch Submenu Tabs request function then launch listener function
								menu.loadSMenuProgTabs().handleSMenuProgTabs();
							},
							error: function () { if (window.console && window.console.error){ console.error(arguments); } }
						});
					}
					// Else the request is aborted
					else
					{
						if ( menu.reqSMenuProg )
						{
							// Abort Request (if not too late)
							menu.reqSMenuProg.abort();
							
							menu.loadingSMenuProg = false;
							
							// Remove throbber
							//$("#supportNav .ajaxRequesting").remove();
						}
					}
					
					return this;
				},


				loadSMenuProgTabs: function(Params)
				{
					menu.reqSMenuProgTabs = $.ajax(
					{
						// URL defined in conf.js
						url: (Params) ? (SMenuProgramsTabsURL + ((SMenuProgramsTabsURL.indexOf('?') > -1)?'&':'?') + Params) : SMenuProgramsTabsURL,
						dataType: "html",
						success: function(data)
						{
							$("#eLettresAlpha").empty().append(data);
							
							menu.setSMenuProg3Cols();
						},
						error: function () { if (window.console && window.console.error){ console.error(arguments); } }
					});
					
					return this;
				},


				handleSMenuProgTabs: function()
				{
					$("#eOngletsLettres li a.ajaxTabCtnt").click(function()
					{
						// Get param
						var ParamValue = getURLParamValue( $(this).attr("href"), "b_ProgSubMenuTab" );
						
						$('#eOngletsLettres li')
							.removeClass('current');
						$(this)
							.parent()
								.addClass('current');
								
						menu.loadSMenuProgTabs("b_ProgSubMenuTab=" + ParamValue);
						
						return false;
					});

					return this;
				},
				
				
				setSMenuProg3Cols: function()
				{	
					var nbDTDD = $("#eSMenuPrograms dl dt").length + $("#eSMenuPrograms dl dd").length;

					var cutAfter = Math.ceil(nbDTDD / 3);
					var colCloser = '<dl class="eLFloated"></dl>';
				
					var tmp = $("#eSMenuPrograms dl").clone();
					var tmp2 = $("#eSMenuPrograms dl").clone();
					tmp.appendTo("#eLettresAlpha");
					tmp2.appendTo("#eLettresAlpha");
					$("#eSMenuPrograms dl:eq(0)").children("*").slice(cutAfter,nbDTDD).remove();
					$("#eSMenuPrograms dl:eq(1)").children("*").slice(0,cutAfter).remove();
					$("#eSMenuPrograms dl:eq(1)").children("*").slice(cutAfter+1, nbDTDD).remove();
					$("#eSMenuPrograms dl:eq(2)").children("*").slice(0,cutAfter*2+1).remove();

					// If the last child of a DL is a DT, we move it to the top of the next DL
					$("#eSMenuPrograms dl").not(":last").each(function()
					{
						if( $(this).children("*:last").is("DT"))
						{
							$(this).children("*:last").remove().prependTo( $(this).next("DL") );
							$(this).next("DL").not(":last").children("*:last").remove().prependTo( $(this).next("DL").next("DL") );
						}
					});
					
					// Add "lastone" class on the last DL
					$("#eSMenuPrograms dl:last").addClass("lastone");
					
					// If the first child of a dl is a DT, we remove its padding-top
					$("#eSMenuPrograms dl").each(function() { if( $(this).children("*:first").is("DT") ) { $(this).children("*:first").css("padding-top","0"); } });
					
					// Get the higher height of the 3 DL and applies it to the others
					var widthTable = [];
					$("#eSMenuPrograms dl").each(function() { widthTable.push( parseInt( $(this).height(), 10 ) ); });
					widthTable.sort().reverse();
					$("#eSMenuPrograms dl").height(widthTable[0]);
					
					menu.sizeSMenuProg();
					
					return this;
				},
				
				
				sizeSMenuProg: function()
				{			
					// Get submenu content dimensions then updates shadow pics dimensions to fit
					var sMenuCtnt = $("#eSMenuCtnt");
					var tmp_h = sMenuCtnt.height();
					var tmp_w = sMenuCtnt.width();
					$("#eSMenuL, #eSMenuR").height(tmp_h);
					$("#eSMenuBM").width(tmp_w-10);
					$("#eSMenuTM").width(tmp_w+2);
					
					// Set equal heights for the lists
					var lettresAlpha = $("#eLettresAlpha");
					lettresAlpha.height(tmp_h - parseInt( lettresAlpha.css("padding-top"), 10 ) - parseInt( lettresAlpha.css("padding-bottom"), 10 ));
					
					return this;
				},
				
				
				loadSMenuReg: function(menuSelector, action)
				{
					// If called action is "load", we do the request
					if (action == "load")
					{
						menu.reqSMenuReg = $.ajax(
						{
							// URL defined in conf.js
							url: SMenuRegionsCache,
							dataType: "html",
							success: function(data)
							{
								menu.loadedSMenuReg = true;
								
								$(menuSelector).append(data);
								
								$(menuSelector + " *").not("#eSMenuRegLabelAside").
									mouseover( function() { $(menuSelector).show(); } );
								$(menuSelector).
									mouseout( function() { $(menuSelector).hide(); } );

								// Display the menu
								menu.show(menuSelector);
								
								menu.sizeSMenuReg(menuSelector);
							},
							error: function () { if (window.console && window.console.error){ console.error(arguments); } }
						});
					}
					// Else the request is aborted
					else
					{
						if ( menu.reqSMenuProg )
						{
							// Abort Request (if not too late)
							menu.reqSMenuProg.abort();
							
							menu.loadingSMenuProg = false;
							
							// Remove throbber
							//$("#supportNav .ajaxRequesting").remove();
						}
					}
					
					return this;
				},

				sizeSMenuReg: function(menuSelector)
				{
					// Get submenu content dimensions then updates shadow pics dimensions to fit
					var tmp_h = $("#eSMenuCtntReg").height();
					var tmp_w = $("#eSMenuCtntReg").width();
					$("#eSMenuRegL, #eSMenuRegR").height(tmp_h);
					$("#eSMenuRegBM").width(tmp_w-10);
					$("#eSMenuRegTM").width(tmp_w+2);
					
					// Makes the menu to hide when going at the right
					$("#eSMenuRegLabelAside").width( $(menuSelector).width() - $("#eSMenuCtntRegLabel").width() ).height( $("#eSMenuCtntRegLabel").height() );
					
					return this;
				},


				show: function(menuSelector)
				{
					// Specific case for the Programs Submenu
					if (menuSelector === progMenu) { $(menuSelector).show().css("left",posSMenuPrograms).css({position: "absolute", top:"-4px"}); }
					else if (menuSelector === regMenu) { $(menuSelector).show().css("left","4px").css({position: "absolute", top:"-4px"}); }
					
					// Default case for common menus
					else { $(menuSelector).show(); }
					
					return this;
				},


				hide: function(menuSelector)
				{
					$(menuSelector).hide();
					
					return this;
				}
				
			};


			menu.init(progMenu, progMenuActivator);
			if( ftvi_portail === "france3" ){ 
			menu.init(regMenu, regMenuActivator); 
			}
		};
		
		new HandleMenu();
		// ------------------------------------ //
		
		// ------------------------------------ \\
		// ********** Menu Secondaire ********** \\ (nécessite inclusion de jquery.scrollingResizedMenu.js)
		
		
		$('ul#archeMenu_secondaire, #archeMenu_secondaire > ul')
			.scrollingResizedMenu(); // plugin jquery scrollingResizedMenu
			
		if($('body.info #archeMenu_secondaire,body.regions #archeMenu_secondaire').length > 0)
		{
			/* Gestion de la recherche */
			var form_recherche 	 =	'<div id="rechercheMenu">';
			form_recherche 		+= 		'<form title="Effectuer une recherche" id="rechercheMenuForm" method="get" action="http://recherche.'+ftvi_portail+'.fr">';
			form_recherche 		+= 			'<fieldset>';
			form_recherche 		+= 				'<legend>Recherche</legend>';
			form_recherche 		+= 				'<label for="q">Votre recherche</label>';
			form_recherche 		+= 				'<input type="text" id="q" name="q" />';
			form_recherche 		+= 				'<input type="submit" value="ok" title="Lancer la recherche" />';
			
			var urlcourante = document.domain;
			var urlsource = new Array();
			urlsource['alsace.france3.fr'] = 'a_alsace';
			urlsource['aquitaine.france3.fr'] =  'a_aquitaine';
			urlsource['corse.france3.fr'] =  'a_corse';
			urlsource['alpes.france3.fr'] =  'a_alpes';
			urlsource['auvergne.france3.fr'] =  'a_auvergne';
			urlsource['basse-normandie.france3.fr'] =  'a_basse_normandie';
			urlsource['bourgogne.france3.fr'] =  'a_bourgogne';
			urlsource['bretagne.france3.fr'] =  'a_bretagne';
			urlsource['centre.france3.fr'] =  'a_centre';
			urlsource['champagne-ardenne.france3.fr'] =  'a_champagne_ardenne';
			urlsource['cote-d-azur.france3.fr'] =  'a_cote_dazur';
			urlsource['franche-comte.france3.fr'] =  'a_franche_comte';
			urlsource['haute-normandie.france3.fr'] =  'a_haute_normandie';
			urlsource['languedoc-roussillon.france3.fr'] =  'a_languedoc_roussillon';
			urlsource['limousin.france3.fr'] =  'a_limousin';
			urlsource['lorraine.france3.fr'] =  'a_lorraine';
			urlsource['midi-pyrenees.france3.fr'] =  'a_midi_pyrenees';
			urlsource['nord-pas-de-calais.france3.fr'] =  'a_nord_pas_de_calais';
			urlsource['paris-ile-de-france.france3.fr'] =  'a_paris_ile_de_france ';
			urlsource['pays-de-la-loire.france3.fr'] =  'a_pays_de_la_loire';
			urlsource['picardie.france3.fr'] =  'a_picardie';
			urlsource['poitou-charentes.france3.fr'] =  'a_poitou_charentes';
			urlsource['provence-alpes.france3.fr'] =  'a_provence_alpes';
			urlsource['rhone-alpes.france3.fr'] =  'a_rhone_alpes';

			if (urlsource[urlcourante] != "" || urlsource[urlcourante] != "undefined")
			{
				form_recherche 		+= 				'<input type="hidden" name="filtre" value="'+urlsource[urlcourante]+'" />';
			}

			form_recherche 		+= 			'</fieldset>';
			form_recherche 		+= 		'</form>';
			form_recherche 		+= 	'</div>';
			
			$('#archeMenu_secondaire')
				.append( form_recherche );
		}	
		// -------------------------------------- //
	});

})(this, this.jQuery);
