$(document).ready(function () {
	initHeaderPopinEvents();
	resetHeaderPopinValues();
	
	initUniversPopinEvents(0);
	initWishListSize();
	initFavoriteFfmcenterName();
});

function initWishListSize() {
	if (getListItemSize)
		$("#wishListSize").html(getListItemSize("WISHLIST"));
}

function initFavoriteFfmcenterName() {
	if (getMag1) {
		var magId = getMag1();
		if (magId != null) {
			var AjaxCallURL = "/webapp/wcs/stores/servlet/AjaxFfmcenterNameView?storeId=10001&langId=-2&ffmcenterId="+magId;
			$("#favoriteFfmcenterName").load(AjaxCallURL);
		}
	}
}

/**
 * Returns true if the current browser is Chrome
 */  
$.browser.chrome = /chrome/.test(window.navigator.userAgent.toLowerCase());

/**
 * Initializes header popins events
 * @return
 */
function initHeaderPopinEvents() {
	// Replace clear input by password input when
	// the clear input is focused
	$('#loginPass-clear').focus(function() {
		showRealLoginPassInput();
		document.getElementById('loginPass').focus();
	});
	$('#loginMail').focus(function() {
		showRealLoginPassInput();
	});

	// Show/hide popin when the link is hovered
	$('#header .with-hover-menu').hover(
		function(event) {
			$(this).find('.hover-menu').show();
		}, function(event) {
			// Workaround for Chrome sometimes firing mouseout on internal div
			// @see http://bugs.jquery.com/ticket/8209
			if ($.browser.chrome && event.toElement != null && event.toElement.parentElement == null) {
				return;
			}
			// Get the element we mouse-hovered out *TO* (depending on IE/firefox)
			var mouseOverTarget = event.toElement != null ? event.toElement : event.relatedTarget;
			
			var eventTarget = event.target;
			if ($.browser.msie) 
				eventTarget = event.fromElement;
			
			// Do not hide if mouseout event comes from within the popin or from a form
			if ( $(mouseOverTarget).parents('.hover-menu').length != 0
					|| $(eventTarget).is('fieldset')
					|| $(eventTarget).is('select')
					|| $(eventTarget).is('option')
					|| $(eventTarget).is('input') ) {
				return;
			}
			// Else, hide popin
			$(this).find('.hover-menu').hide();
			//See if inputs reset is needed
			resetHeaderPopinValues();
		});
	// Hide when a link is clicked
	$('#header .with-hover-menu a').click(function() {
		$(this).parents('.hover-menu').hide();
	});
}

/**
 * Replace the password input with the fake clear one
 */
function showFakeLoginPassInput() {
	$('#loginPass').hide();
	$('#loginPass-clear').show();
}

/**
 * Replace the fake password input with the real one
 */
function showRealLoginPassInput() {
	$('#loginPass-clear').hide();
	$('#loginPass').show();
}

/**
 * Resets header popin forms
 * Called when document is ready for initialization and when
 * hovering out of a header popin
 */
var dumbReset = true;
var defaultLogonValue = null;
function resetHeaderPopinValues() {
	//Used to memorize initial value
	if (defaultLogonValue == null)
		defaultLogonValue = $('#loginMail').val();
	
	//Reset Compte form
	if(dumbReset ||($('#loginMail').val() != null && $('#loginMail').val().length == 0)
			|| $('#loginMail').val() == defaultLogonValue) {
		var form = document.getElementById('Logon');
		if (form != null) {
			//Reset
			form.reset();
			
			//Blur inputs
			var _blur = function(id) {
				var elem = document.getElementById(id);
				if(elem != null) {
					elem.blur();
				}
			};
			_blur('loginMail');
			_blur('loginPass');
			_blur('loginPass-clear');
			
			
			//Show fake loginPass input
			showFakeLoginPassInput();
		}
	}
	
	//Reset Magasin form
	if(dumbReset || ($('#zipCode').val() != null && $('#zipCode').val().length == 0)) {
		var form = document.getElementById('attachMag');
		if (form != null) {
			form.reset();
			$("select#citySelect").empty();
			addOptionPopin("Ville", "Ville", "citySelect");
		}
	}
}

/**
 * Initializes universes popins events
 * @return
 */
function initUniversPopinEvents(nbTry) {
	// Retry mechanism for IE firing "ready" event with DOM not completely loaded
	var nbElems = $('#header li.firstMenu').length;
	if ((nbTry == null || nbTry < 2) && nbElems == 0) {
		window.setTimeout(function() {
			initUniversPopinEvents(nbTry + 1);
			return false;
		}, 3000);
		return;
	}
	
	// Hover init
	var hoverTimeout = null;
	var hoverShowDelay = 400; //Delay before the popin is shown when the menu is hovered
	var hoverHideDelay = 100; //Delay before the hidden is shown when the menu no more hovered
	$('#header li.firstMenu').hover(
			function() {
				var hoveredElement = this;		

				window.clearTimeout(hoverTimeout); //Clear pending timeouts
				
				//Using a timeout to prevent popin show if the menu is just hovered briefly
				hoverTimeout = window.setTimeout(function() {
					showUniversPopin($(hoveredElement));
				}, hoverShowDelay);
			},
			function() {
				var hoveredElement = this;

				window.clearTimeout(hoverTimeout); //Clear pending timeouts
				
				//Using a timeout to prevent popin show if the menu is just hovered briefly
				hoverTimeout = window.setTimeout(function() {					
					hideUniversPopin();
				}, hoverHideDelay);
				
				
			});
	//Show popin immediately if the menu item is clicked
	$('#header li.firstMenu a').click(function(){
		window.clearTimeout(hoverTimeout);
		showUniversPopin($(this).parent());
		return false;
	});
}

function showUniversPopin(hoveredElement) {
	var layerPopinUnivers = getLayerPopinUnivers(hoveredElement);
	if (layerPopinUnivers == null)
		return;
	
	hideUniversPopin();
	$(hoveredElement).find('a.newLoadPopinNav').addClass('actif');
	$(layerPopinUnivers).show();
	
	$('#flashcontent').css('visibility', 'hidden'); 
}

function hideUniversPopin(hoveredElement) {
	if (hoveredElement == null) {
		hoveredElement = $('#header li.firstMenu');
	}
	
	$(hoveredElement).find('a.newLoadPopinNav').removeClass('actif'); //Hide popin if shown
	$(hoveredElement).find('.newNavTopPopin:visible').hide();
	
	$('#flashcontent').css('visibility', 'visible');
}



/**
 * Gets the universe popin to show.
 * If the div does not exist it's created and its content loaded
 * 
 * @param headerMenuItem
 * @return
 */
function getLayerPopinUnivers(headerMenuItem) {
	var noCacheArg = '';
	//Find popin div
	var layerPopinUnivers = $(headerMenuItem).find('.newNavTopPopin');
	if (layerPopinUnivers.length > 0) {
		if (layerPopinUnivers.html().length == 0) {
			// If popin is empty, force reload and bypass browser cache
			layerPopinUnivers.remove();
			noCacheArg = '&noCacheArg=' + (Math.random() * (Math.random() * 100000));
		} else {
		return layerPopinUnivers;
	}
	}
	// If div does not exist, create it
	$(headerMenuItem).append('<div class="newNavTopPopin" style="display: none;"></div>');
	layerPopinUnivers = $(headerMenuItem).find('.newNavTopPopin');
	// Get URL
	var universPopinURL = getUniversPopinURL($(headerMenuItem).find('a').href());
	universPopinURL += noCacheArg;
	// Load content
	$(layerPopinUnivers).load(universPopinURL, function() {
		//If empty, force reload immediately (only once)...
		if (layerPopinUnivers.html().length == 0 && noCacheArg.length == 0) {
			getLayerPopinUnivers(headerMenuItem);
			return;
		}
		
		// Bind click event of the close button
		var that = this;
		$(this).find('a.closePopin').click(function() {
			$(that).hide();
		});
	});
	
	$(headerMenuItem).find('a.newLoadPopinNav').click(function() {
		return false;
	});
	
	return layerPopinUnivers;
}

function getUniversPopinURL(href) {
	// considere que urlrewrite actif:
	var hrefArgs = href.split('_');
	
	var universPopinURL = "";
	if (href.indexOf("webapp") == -1) {
		var urlPage = window.location.href.split(':');
    	if(urlPage[0] != null && urlPage[0].indexOf('https') != -1) {
      		universPopinURL = "/webapp/wcs/preview/servlet/";    
    	}else{
		universPopinURL = "/webapp/wcs/stores/servlet/";
	}
	}
	universPopinURL += 
		"NavigationNewMenuView?storeId=" + hrefArgs[2]
		+ "&catalogId=" + hrefArgs[3]
		+ "&langId=" + hrefArgs[4]
		+ "&universeId=" + hrefArgs[5];
	return universPopinURL;
}

function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function showFooterNav(){
	if ($("#footerTabNav").attr("className")=="fermes") {
		$("#footerTabNav").removeClass("fermes");
		$("#footerTabNav").addClass("ouverts");
		$(".footerProduits #tableProduits").show();
		return false;
	}
	else {
		$("#footerTabNav").removeClass("ouverts");
		$("#footerTabNav").addClass("fermes");
		$(".footerProduits #tableProduits").hide();
		return false;
	}
}
