// ***********************************************************************************
// Declaration des variables globales
// ***********************************************************************************

// Utilisé par la page commande-rapid.html + le champ recherche sur les differentes pages
// pour l'animation du champ en attente du autocomplete ajax
var intervalAutoCompleteID = new Array(2);
intervalAutoCompleteID[0] = null;
intervalAutoCompleteID[1] = null;
intervalAutoCompleteID[2] = null;

var intervalAutoCompleteLayerID = new Array(2);
intervalAutoCompleteLayerID[0] = null;
intervalAutoCompleteLayerID[1] = null;
intervalAutoCompleteLayerID[2] = null;

var currentAutoCompleteTBox = new Array(2);
currentAutoCompleteTBox[0] = null;
currentAutoCompleteTBox[1] = null;
currentAutoCompleteTBox[2] = null;

var intervalParameters = new Array(2);
intervalParameters[0] = { layerClass: '.autoComplete', intervalIDIndex: 0, secondaryTextBoxFunction: 'setSecondaryTextBoxCommandeRapide' };
intervalParameters[1] = { layerClass: '.sousRecherche', intervalIDIndex: 1, secondaryTextBoxFunction: 'setSecondaryTextBox' };
intervalParameters[2] = { layerClass: '.autoComplete', intervalIDIndex: 2, secondaryTextBoxFunction: 'setSecondaryTextBoxAchatRapid' };
TimeoutID = null;

var textboxFocus = false;

var GlobalMenuIndex = null; 
var intervalGlobalMenuID = null;
var autoSuggestXHR = null; // Variable conteint un reference a le ajax XHR objet pour l'autosuggest d'articles

var urlCodeCourt = null;
var codeCourtTimeout = null;
var XHRObjectCodeCourt = null;

var callBackXHR = null; // xhr utilisé par achat rapide

function displayGlobalMenu()
{
	$("#entete .menuGlobal>ul>li").eq(GlobalMenuIndex).addClass('hover');	
}

$(document).ready(function() {	
    
    // footer
    heightUL = 0;
    $("#pied .main .right ul").each(function (i) { 
        
        if($(this).height() > heightUL)
            heightUL = $(this).height();
        
    });
    $("#pied .main .right ul").height(heightUL);
    
	$("#entete .menuGlobal>ul>li:lt(6)").not(":first").hover(function(){
		
		GlobalMenuIndex = $(this).index();
		if(intervalGlobalMenuID)
			window.clearTimeout(intervalGlobalMenuID);
		intervalGlobalMenuID = window.setTimeout(displayGlobalMenu, 500);
		
	},function(){
		
		if(intervalGlobalMenuID)
			window.clearTimeout(intervalGlobalMenuID);
		$(this).removeClass('hover');
		
	});	

	var wl=$(".menuGlobal ul li ul").height();
	var wf=$("ul.menuNav").height();
	var wk=$("ul li.simple ul").height();
	
	$(".menuGlobal ul>li>ul.firstNav>li>ul.sousMenu").each(function(){
		$(".menuGlobal ul>li>ul.firstNav>li>ul.sousMenu").height(wl);
	});
	
	/*$("ul li.simple ul.sousMenu").each(function(){
		$("ul li.simple ul.sousMenu").height(wk);
	});*/
	
	$("ul.menuNav ul.sousMenu").each(function(){
		$("ul.menuNav ul.sousMenu").height(wf);
	});
	
	$("a.panierM").click(function(){
	   
        if(!$(this).parent().parent().hasClass("panierActive"))
        {
    		$(this).parent().parent().toggleClass("panierActive");	
    		$("#cart_block").toggle("slow");
    		$("#compteBlock").hide("slow");
    		$("a.compteM").parent().parent().removeClass("compteActive");
        }
		return false;
	});
	
	$("a.compteM").click(function(){
	   
        if(!$(this).parent().parent().hasClass("compteActive"))
        {
    		$(this).parent().parent().toggleClass("compteActive");
    		$("#compteBlock").toggle("slow");
    		$("#cart_block").hide("slow");
    		$("a.panierM").parent().parent().removeClass("panierActive");
        }
		return false;
	});
	
	if($("#cart_block").attr("id") == "cart_block")
	{
		$("#cart_block").show();
		$("#compteBlock").hide();
	}
	
	$("#pikame").PikaChoose({carousel:true, transition:[5], autoPlay:true, hoverPause:true, speed: 7000 });
	
	// *************************************************************
	// Autocomplete sur la page 
	// *************************************************************
    jQuery("#sousRechercheTxt").keyup(function (event) {
        
		TimeoutID = 1;
		value = $(this).val();
        category = this.form.category.options[this.form.category.selectedIndex].value;
		autoCompleteRecherche(this, value, category, '.sousRecherche', '.sousRecherche .sousRechercheCont', 1, 'ajax_search.php?type=autocomplete_search');
        
                             }).keydown(function (event) {
                                
        if(event.which == 13)
            event.preventDefault();
        
                            }).keypress(function (event) {
        
        if(event.which == 13)
            event.preventDefault();                        
        
    })
    .blur(function () {
		
		if(intervalAutoCompleteLayerID[1])
			window.clearTimeout(intervalAutoCompleteLayerID[1]);
		TimeoutID = 1;
		intervalAutoCompleteLayerID[1] = window.setTimeout(undisplayAutoComplete, 200);
		
	}).focus(function () {
	   
        if(intervalAutoCompleteLayerID[1])
			window.clearTimeout(intervalAutoCompleteLayerID[1]);
       
		TimeoutID = 1;
        
	});
    
    jQuery(".sousRecherche .sousRechercheCont").scroll(function () {
		
		rechercheCancelUndisplay();
		
	});
    
    jQuery(".sousRecherche .sousRechercheCont, .sousRecherche").click(function (event) {
        
        rechercheCancelUndisplay();
        
        event.stopPropagation();
        
    });
    
    jQuery("#codeCourtTxt").keydown(function (event) {
        
       if(event.which == 13)
       {
            event.preventDefault();
            codeCourtClicked(this.form);
            this.focus();
            
            if(navigator.appVersion.indexOf("MSIE") >= 0)
                setCaretPos(jQuery("#codeCourtTxt")[0], jQuery("#codeCourtTxt").val().length);
       }
            
    }).keyup(function (event) {
        
       if(event.which == 13)
       {
            event.preventDefault();
            codeCourtClicked(this.form);
            this.focus();
            
            if(navigator.appVersion.indexOf("MSIE") >= 0)
                setCaretPos(jQuery("#codeCourtTxt")[0], jQuery("#codeCourtTxt").val().length);
       }
        
    }).keypress(function (event) {
    
       if(event.which == 13)
       {
            event.preventDefault();
            codeCourtClicked(this.form);
            this.focus();
            
            if(navigator.appVersion.indexOf("MSIE") >= 0)
                setCaretPos(jQuery("#codeCourtTxt")[0], jQuery("#codeCourtTxt").val().length);
       }
        
    });
    
    
    
	// **************************************************************************
	// le menu gauche sur les differentes pages
	// **************************************************************************
	/*
    jQuery(".MenuLeft ul li").each(function (i) {
		
		if(!$(this).hasClass("active"))
		{
			$(this).find("ul").hide();
		}
	});
	
	// Menu
	jQuery(".MenuLeft ul li a").click(function () {
		
											   // Find all primary li and remove active class 
										jQuery(".MenuLeft ul").find("li").removeClass("active")
											   // Find all secondary lists and set their visibility to none
											   .end().find("ul").hide();

											   // Find current li
										currentNode = $(this).parents("li")[0];
										$(this).parents().children("ul").show();
										
										while(currentNode.className != "mainMenu")
										{
											tagName = currentNode.tagName.toLowerCase();
											
											if(tagName == "li")
											{
												$(currentNode).addClass("active");	
											}
											else if(tagName == "ul")
											{
												$(currentNode).show();
											}
											
											currentNode = currentNode.parentNode;
										}
										
									  });
	*/
    
	// **************************************************************************
	// telecharger les images des popups (les bordures) pour une affichage plus liesse
	// **************************************************************************
	imageArray = new Array();
	imagesToDownload(imageArray, layerFolder + "bgd-layer-connect-cont.png", layerFolder + "bgd-layer-connect.png", 
								 layerFolder + "bgd-layer-dessins3D-cont.png", layerFolder + "bgd-layer-dessins3D.png",
								 layerFolder + "bgd-layer-foto.png", layerFolder + "bgd-layer-produit-cont.png",
								 layerFolder + "bgd-layer-produit.png", layerFolder + "bgd-layer-QuesProd.png",
								 layerFolder + "bgd-layer-QuestProd-cont.png", 
								 imagesFolder + "picto-dwnld.gif", imagesFolder + "button-links4.gif", 
								 imagesFolder + "loading.gif",
								 imagesFolder + "ico_mosaique.gif", imagesFolder + "ico_mosaique-active.gif",
								 imagesFolder + "ico_liste-active.gif", imagesFolder + "ico_liste.gif",
                                 imagesFolder + "loadingbar.gif", imagesFolder + "codecourt-loading.gif",
                                 imagesFolder + "bg-codecourt-success.png", imagesFolder + "codecourt-success.gif");
	
	// **************************************************************************
	// Page fiche-produit.html 
	// **************************************************************************
	$("#mainTabs .tabsCont:first").show();
	$("#mainTabs .tabsList li").click(function () {
		
		Index = $(this).index();
		
		// Display tabsList Active
		$("#mainTabs .tabsList li").not(this).removeClass("active");
		$(this).addClass("active");
		
		// Display tabsCont
		$("#mainTabs > .tabsCont").css("display", "none")
							                .eq(Index).css("display", "block");
		
	});
	
    /*
	$(".panierBtnImg").mouseover(function () { 
												Width = $(".infoBulle").width();
												Top = $(this).position().top - 37; 
												Left = $(this).position().left - (Width / 2) + 3;
												$(".infoBulle").css({ position:"absolute", display: "block", top: Top, left: Left });
											 })
					  .mouseout(function () { $(".infoBulle").css("display", "none"); });*/

    jQuery(".infobulleTable").delegate(".panierBtnImg", "mouseover", function () {
            
                                                if($(this).parents("tr").attr("ajoute") == "1")
                                                {
                                                    Width = $(".infoBulle").width();
    												Top = $(this).position().top - 37; 
    												Left = $(this).position().left - (Width / 2) + 3;
                                                    Left = leveragingIEInfoBulleLeftCoordinate(Left, $(this).parent());
    												$(".infoBulle").css({ position:"absolute", display: "block", top: Top, left: Left });
                                                }

                                              })
                             .delegate(".panierBtnImg", "mouseout", function () {
                                        
                                                if($(this).parents("tr").attr("ajoute") == "1")
                                                {
                                                    $(".infoBulle").css("display", "none");
                                                }
                                        
                                              });
    
    if(jQuery('.mycarousel').hasClass("mycarousel"))
    	jQuery('.mycarousel').jcarousel({ scroll: 1,
    									  initCallback: function() { },
    									  widthItem: 201
    								    });
	
	jQuery('.mycarousel .quickBuy').hide();
	jQuery('.mycarousel li').hover(
		function () {
			$(this).find(".quickBuy").show();
		}
	,
		function () {
			$(this).find(".quickBuy").hide();
		}
	);
	
    /*
	jQuery('.layerPhoto, .layerPhotoStretch').hover(
		function () {
			$(this).find("#closePopUpButton").show();
		}
	,
		function () {
			$(this).find("#closePopUpButton").hide();
		}
	);*/
	
	jQuery('.layerPhoto #closePhotoProduit').hide();
    
	// *************************************************************
	// Autocomplete sur la page commande-rapid.html
	// *************************************************************
	jQuery(".articleRef").keyup(function (event) {
		
		TimeoutID = 0;
		value = $(this).val();
        if(event.which == 8)
            autoComplete(this, value, '.autoComplete', '.autoComplete div', 0, 'ajax_get_articles.php', true);
        else
            autoComplete(this, value, '.autoComplete', '.autoComplete div', 0, 'ajax_get_articles.php', false);
        
	}).blur(function () {
		
		if(intervalAutoCompleteLayerID[0])
			window.clearTimeout(intervalAutoCompleteLayerID[0]);
		TimeoutID = 0;
		intervalAutoCompleteLayerID[0] = window.setTimeout(undisplayAutoComplete, 200);
        
	}).focus(function () {
		TimeoutID = 0;
	});	
	
    jQuery(".autoComplete div").scroll(function () {
		
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
		
	}).blur(function () { 
	
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
		intervalAutoCompleteLayerID[TimeoutID] = window.setTimeout(undisplayAutoComplete, 200);
		
	});
	
	jQuery(".autoComplete div ul").click(function (event) {
		
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
		intervalAutoCompleteLayerID[TimeoutID] = window.setTimeout(undisplayAutoComplete, 200);
		
	});
	
	jQuery(".autoComplete").parents().click(function () {
		
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
		intervalAutoCompleteLayerID[TimeoutID] = window.setTimeout(undisplayAutoComplete, 200);
	});
    
    /*
    jQuery(document).click(function (event) {
        
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
            
        intervalAutoCompleteLayerID[TimeoutID] = window.setTimeout(undisplayAutoComplete, 200);
		
	});*/
    
    /*
	jQuery(".autoComplete div, .sousRecherche .sousRechercheCont").scroll(function () {
		
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
		
	}).blur(function () { 
	
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
		intervalAutoCompleteLayerID[TimeoutID] = window.setTimeout(undisplayAutoComplete, 200);
		
	});
	
	jQuery(".autoComplete div ul, .sousRecherche .sousRechercheCont dl").click(function (event) {
		
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
		intervalAutoCompleteLayerID[TimeoutID] = window.setTimeout(undisplayAutoComplete, 200);
		
		event.stopPropagation();
		
	});
	
	jQuery(".autoComplete, .sousRecherche").parents().click(function () {
		
		if(intervalAutoCompleteLayerID[TimeoutID])
			window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
		intervalAutoCompleteLayerID[TimeoutID] = window.setTimeout(undisplayAutoComplete, 200);
	});*/
    
    jQuery("#commandeRapidePrixDisplay").attr("total", "0");
    
	// *************************************************************
	// Autocomplete sur la page panier.html
	// *************************************************************
	jQuery(".reference").keyup(function (event) {
		
		TimeoutID = 2;
		value = $(this).val();
        
		autoComplete(this, value, '.autoComplete', '.autoComplete div', 2, 'ajax_get_articles.php', true);
        
	}).blur(function () {
		
		if(intervalAutoCompleteLayerID[2])
			window.clearTimeout(intervalAutoCompleteLayerID[2]);
		TimeoutID = 2;
		intervalAutoCompleteLayerID[2] = window.setTimeout(undisplayAutoComplete, 200);
        
	}).focus(function () {
		TimeoutID = 2;
	});
	
	// *************************************************************
	// Le date picker sur la page livraison.html
	// *************************************************************
	Date.format = 'dd/mm/yyyy';

	if($('#dateLivraison').attr("id") == "dateLivraison")
	{
		$('#dateLivraison').datePicker({clickInput:true,createButton:false})
				  	   	   .dpSetOffset(24, 0);   
	}

    $(".disabledSubmit").keypress(function (event) {
       
       if (event.keyCode == 13) {
            event.preventDefault();
       }
        
    });
    
    // ************************************************************
    // Pour le code court
    // ************************************************************
    if(document.frmCodeCourt)
    {
        jQuery(document.frmCodeCourt.reference).bind("keypress", function () {
            
            if(jQuery("#errorMsgCodeCourt").css("display") == "block")
            {
                codeCourtErrorUndisplay();
            }

        });
        
        jQuery(".sbmRech", document.frmCodeCourt).unbind("click")
                                                 .bind("click", function () { codeCourtClicked(this.form); });
    }
    
});

/******************************************************************
 Fonctions multiples
 ******************************************************************/
function rechercheCategoryChanged(Element)
{
    value = Element.form.bandeau.value;
    
    if(!isEmpty(value) && Element.selectedIndex > 0)
    {
        TimeoutID = 1;
        category = Element.options[Element.selectedIndex].value;
        autoCompleteRecherche(Element.form.bandeau, value, category, '.sousRecherche', '.sousRecherche .sousRechercheCont', 1, 'ajax_search.php?type=autocomplete_search');
    }
}
 
function rechercheCancelTimeout()
{
    if(TimeoutID == 1)
        if(intervalAutoCompleteLayerID[TimeoutID])
            window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
    
}
 
function rechercheCancelUndisplay()
{
    if(intervalAutoCompleteLayerID[TimeoutID])
        window.clearTimeout(intervalAutoCompleteLayerID[TimeoutID]);
        
    rechercheFocus();
} 

function rechercheFocus()
{
    jQuery("#sousRechercheTxt").focus();
        
    if(navigator.appVersion.indexOf("MSIE") >= 0)
        setCaretPos(jQuery("#sousRechercheTxt")[0], jQuery("#sousRechercheTxt").val().length);
}

function codeCourtErrorDisplay()
{
    $("#errorMsgCodeCourt").css("display", "block");
    //jQuery("#labelCodeCourt").css("padding-top", "0px");
} 
 
function codeCourtErrorUndisplay()
{
    jQuery("#errorMsgCodeCourt").css("display", "none");
    //jQuery("#labelCodeCourt").css("padding-top", "6px");
} 
 
function codeCourtEnableTextFields(Form)
{
    jQuery(".sbmRech", Form).css("background", "#999999").val("OK")
                            .unbind("click")
                            .bind("click", function () { codeCourtClicked(this.form); });
    jQuery(Form.reference).removeAttr("disabled").focus();
}
 
function codeCourtSuccessAnimation()
{
    jQuery(".codeCourtSuccess").css("display", "block");
}
 
function cancelCodeCourt(Form)
{
    codeCourtErrorUndisplay();
    codeCourtEnableTextFields(Form);
    if(XHRObjectCodeCourt) XHRObjectCodeCourt.abort();
    
    jQuery(".sbmRech", Form).unbind("click")
                            .bind("click", function () { codeCourtClicked(this.form); });
}
 
function codeCourtClicked(Form)
{
        if(Form.reference.value.length != 3)
        {
            codeCourtErrorDisplay();
            return;
        }
        else
        {
            /*
            emptySpace = false;
            for(var i = 0, m = Form.reference.value.length; i < m; i++)
            {
                if(Form.reference.value.charAt(i) == " ")
                {
                    emptySpace = true;
                    break;   
                }
            }
    
            if(emptySpace)
            {
                codeCourtErrorDisplay();
                return;
            }
            else
            {*/
                codeCourtErrorUndisplay();
                jQuery(Form.reference).attr("disabled", "disabled");
                jQuery(".sbmRech", Form).css("background", "url(" + imagePathCodeCourtLoading + ") no-repeat").val("");
                
                if(XHRObjectCodeCourt) XHRObjectCodeCourt.abort();
                
                // Le jquery ajax
                XHRObjectCodeCourt = jQuery.ajax({
                        	       			url: "ajax_get_code_court.php",
                        					type: 'POST',
                        					dataType: 'json',
                        					data: "reference=" + encodeURI(Form.reference.value),
                        					success: function(data){
                                                
                                                // Erreur pas connecté
                                                if(data["status"] == "pas connecte")
                                                {
                                                    alert(MsgPasConnecte);
                                                    return false;
                                                }
                                                
                                                // appeler le callback fonction
                                                codeCourtCallBack(Form, data);
                                                
                                               
                                                
                        					},
                        					error: function (xhr, textStatus) {
                        					    
                                                if(textStatus != "abort")
                                                    alert(MsgErreurDeConnexion);
                        					}
                                   		});
                
                // jQuery(".sbmRech", Form)[0].onclick = function () { return false; };
                
                jQuery(".sbmRech", Form).unbind("click")
                                        .bind("click", function () { cancelCodeCourt(this.form); });
            //}
        }
} 

function codeCourtCallBack(Form, data)
{
    if(data["status"] == "ok")
    {
        productsId = parseInt(data["products_id"]);
        if(productsId > 0)
        {
            codeCourt = Form.reference.value;
            urlCodeCourt = "index.php?action=codecourt&products_id=" + productsId + "&code=" + codeCourt;
            
            if(codeCourtTimeout)
                clearTimeout(codeCourtTimeout);
            codeCourtTimeout = setTimeout(codeCourtLoadURL, 1050);
            codeCourtSuccessAnimation();
            
            jQuery(".sbmRech", Form).unbind("click");
        }
        else
        {
            codeCourtErrorDisplay();
            codeCourtEnableTextFields(Form);
        }
    }
    else
    {
        codeCourtErrorDisplay();
        codeCourtEnableTextFields(Form);
    }
}

function codeCourtLoadURL()
{
    location.replace(urlCodeCourt);
}

function leveragingIEInfoBulleLeftCoordinate(Left, ALink)
{
    if(navigator.appVersion.indexOf("MSIE 9") >= 0)
    {
        if($(ALink).siblings("form").size() == 0)
            Left = Left + 55;
    }
    
    if(navigator.userAgent.indexOf("Safari") >= 0 && navigator.userAgent.indexOf("Chrome") < 0)
    {
        if($(ALink).siblings("a").size() == 0)
        {
            if($(ALink).siblings("form").size() > 0)
            {
                // page liste-commande : bouton transformer en commande
                Left = Left + 37;
            }
            else
            {
                Left = Left + 57;
            }
        }
    }
    
    return Left;
}
 
function displayInfoBulle(ALink, BulleClass, InfoText)
{
    ImgElement = $(ALink).find("img");
    BulleElement = $(BulleClass);
    if(InfoText) BulleElement.html(InfoText);    
    Width = BulleElement.width();
    Top = ImgElement.position().top - 37; 
    Left = ImgElement.position().left - (Width / 2) + 3;
    Left = leveragingIEInfoBulleLeftCoordinate(Left, ALink);
    BulleElement.css({ position:"absolute", display: "block", top: Top, left: Left });
    setTimeout(undisplayInfoBulle, 3000);
} 

function undisplayInfoBulle()
{
    $(".infoBulle").css({ display: 'none' });
}

function check_qty_input(currentQuantity, condt, qmax, qmin)
{
    var cond = currentQuantity % condt;
    
    if(currentQuantity < qmin)
    {
        Message = new String(MessageMinimale).replace(/%qmin%/, qmin);
        alert(Message);
        return false;
    }
    else if(isNumber(currentQuantity) == false)
    {
        alert(MessageNumerique);
        return false;
    }
    else if((cond > 0)|| (currentQuantity==0))
    {
        Message = new String(MessageMultiple).replace(/%qty%/, currentQuantity)
                                             .replace(/%Condt%/, condt);
        alert(Message);
        return false;
    }
    else if(currentQuantity > qmax)
    {
        alert(MessageMax);
        return false;
    }
    else
    {
        return true;
    }
}
 
function readdClassFirstRowToTable()
{
    TRS = $(".hoverable tr");
    if(!TRS.eq(1).hasClass("firstRow"))
        TRS.eq(1).addClass("firstRow");
}
 
function ajouterAuPanier(initialqty,currentQuantity,Condt,i,qmax,prod,qmin,formName,fn,fname,URL,Link)
{ 
    var cond = currentQuantity % Condt;
            
    URL = URL + "&products_id="+prod;
    
    if(check_qty_input(currentQuantity, Condt, qmax, qmin))
    {
        if(fn) document.forms[formName].elements[fn].value = currentQuantity;
        PostQueryStr = $(document.forms[formName]).serializeArray();
        sendingAjax(URL, PostQueryStr, "ajouterAuPanierCallBack", null, Link);
    }
    else
    {
        if(fn) document.forms[formName].elements[fn].value = '';
        document.forms[formName].elements[fname].value = initialqty;
    }
    
}

function ajouterAuPanierCallBack(parameter, data)
{
    if(data["status"] == "ok")
    {
        // update panier
        setTotalTextePanier(data["produitTexte"], data["plancherMonCompte"]);
        alert(MessageArticleAjoute);
    }
    else if(data["status"] == "minimale not ok")
    {
        alert(MessageMinimale);
    }
    else if(data["status"] == "Quantite surprenante")
    {
        alert(MessageMax);
    }
    else if(data["status"] == "Condition vente not ok")
    {
        alert(MessageMultiple);
    }
    else if(data["status"] == "Product non trouve")
    {
        alert(MessageArticleNonTrouve);
    }
}
 
function displayPrice(number, symbol)
{
   return(new String(new Number(number).toFixed(2)).replace(/\./, ",") + symbol); 
} 
 
function toggleFavoris(Link, productid, URL, removeLinkRow)
{
    sendingAjax(URL, 'productid=' + encodeURI(productid), "toggleFavorisCallBack", [Link, removeLinkRow], Link);
}
        
function toggleFavorisCallBack(parameters, data)
{
    Link = parameters[0];
    removeLinkRow = parameters[1];
    
    if(removeLinkRow)
    {
        if(data["status"] == "deleted")
        {
            $(Link).parents("tr").remove();
        }
    }
    else
    {
        if(data["status"] == "added")
        {
            SRC = $(Link).find("img").attr("src");
            SRC = SRC.replace(/picto_favori.gif/, "picto_favori-active.gif");
                
            $(Link).find("img").attr("src", SRC);
        }
        else if(data["status"] == "deleted")
        {
            SRC = $(Link).find("img").attr("src");
            SRC = SRC.replace(/picto_favori-active.gif/, "picto_favori.gif");
                
            $(Link).find("img").attr("src", SRC);
        }
    }
}
    
function setTotalTextePanier(produitTexte, plancherTexte)
{
    $("#cartProduitTexte").html(produitTexte);
    $("#cartPlancherTexte").html(plancherTexte);
}
 
function supprimerArticle(Link, noRefReset)
{
    TR = $(Link).parents("tr");
    
    prixun = parseFloat(TR.attr("prix"));
    quantity = TR.find(".articleQuantity").val();
    
    if(prixun && quantity)
    {
        Element = $("#commandeRapidePrixDisplay");
        total = parseFloat(Element.attr("total")) - (prixun * quantity);
        totalstr = new String(total.toFixed(2)).replace(/\./, ",");
        Element.attr("total", total).html(totalstr + "&euro;");
    }
    
    if(!noRefReset)
    {
       TR.find(".articleRef").val(""); 
    }
    
    TR.removeAttr("prix")
      .removeAttr("total")
      .find(".articleType").val("")
      .end()
      .find(".articleQuantity").val("0")
      .end()
      .find(".uftxt").val("")
      .end()
      .find(".prixtxt").val("")
      .end()
      .find(".totaltxt").val("")
      .end()
      .find(".tdUf").html("&nbsp;")
      .end()
      .find(".tdPrix").html("&nbsp;")
      .end()
      .find(".tdTotal").html("&nbsp;")
      .end()
      .find(".delArticle").css({ visibility: 'hidden' });
      
    if(TR.next().hasClass("erreurRow"))
       TR.next().remove(); 
}

function updateTotalCommandeRapid(QuantityTBox)
{
    TR = $(QuantityTBox).parents("tr");
    
    if(new String(TR.find(".articleType").val()).length > 0)
    {
        prixun = parseFloat(TR.attr("prix"));
    
        valueEntered = $(QuantityTBox).val();
        condt = parseInt(TR.attr("condtv"));
        qmax = parseInt(TR.attr("qmax"));
        qmin = parseInt(TR.attr("qmin"));
     
        if(check_qty_input(valueEntered, condt, qmax, qmin))
        {
            previousSubTotal = parseFloat(TR.attr("total"));
            newSubTotal = parseInt(valueEntered) * prixun;
            
            // Set the total of the row
            TR.attr("total", newSubTotal)
            newSubTotalstr = new String(newSubTotal.toFixed(2)).replace(/\./, ",");
            TR.find(".tdTotal").html(newSubTotalstr + "&euro;");
            
            // set the overall total
            Element = $("#commandeRapidePrixDisplay");
            total = parseFloat(Element.attr("total")) - previousSubTotal + newSubTotal;
            totalstr = new String(total.toFixed(2)).replace(/\./, ",");
            Element.attr("total", total).html(totalstr + "&euro;");
        }
        else
        {
            $(QuantityTBox).val(qmin);
            valueEntered = qmin;
            
            previousSubTotal = parseFloat(TR.attr("total"));
            newSubTotal = parseInt(valueEntered) * prixun;
            
            // Set the total of the row
            TR.attr("total", newSubTotal)
            newSubTotalstr = new String(newSubTotal.toFixed(2)).replace(/\./, ",");
            TR.find(".tdTotal").html(newSubTotalstr + "&euro;");
            
            // set the overall total
            Element = $("#commandeRapidePrixDisplay");
            total = parseFloat(Element.attr("total")) - previousSubTotal + newSubTotal;
            totalstr = new String(total.toFixed(2)).replace(/\./, ",");
            Element.attr("total", total).html(totalstr + "&euro;");
        }
    }
    else
    {
        $(QuantityTBox).val(0);
    }
}

function toggleMosaiqueListe(thumbnailViewClass, listeClass, linkClicked)
{
	// interchanger la classe active sur les lien mosaique et liste
	Link = $(linkClicked);
	if(!Link.hasClass("active"))
	{
		Link.addClass("active")
			.parents("li").siblings("li").find("a").removeClass("active");
			
		if(Link.hasClass("mosaique"))
		{
			$("." + thumbnailViewClass).css("display", "block");
			$("." + listeClass).css("display", "none");
		}
		else if(Link.hasClass("liste"))
		{
			$("." + thumbnailViewClass).css("display", "none");
			$("." + listeClass).css("display", "block");
		}
	}
}
function CompterMots(chaine) {
	  result = 0;
	  var exp=new RegExp("[a-zA-Z0-9]+","g");
	  var tabNom=chaine.match(exp);
	  if (tabNom == null) {
		  result = 0;
	  } else {
		  result = tabNom.length;
	  }
	  return result;
}
function autoCompleteRecherche(textbox, value, category, layerClass, layerHTMLSelector, intervalIDIndex, URL, callbackFunction)
{
	currentAutoCompleteTBox[intervalIDIndex] = textbox;
	
	if(value.length >= 3)
	{
	    if(autoSuggestXHR)
            autoSuggestXHR.abort();
        
        /*
		if($(layerClass).css("display") != "block")
			intervalAutoCompleteID[intervalIDIndex] = window.setTimeout(setBorderTextBox, 10, textbox, intervalIDIndex);
    	*/
        
        $(textbox).css("background", "url(" + imagePathRechercheLoading + ") no-repeat 6px 5px #ffffff");

        var nbMots = CompterMots(value);
        
        if (nbMots == 1) {
    		var regexRefPattern = new RegExp("^([a-zA-Z][a-zA-Z][a-zA-Z])([0-9])([A-Z0-9]*)$");
        	var resultPattern = value.match(regexRefPattern);
        	
        	if (resultPattern != null) {
            	/*if (category == "KEYWORDS" || category == "REFERENCES") {*/
	        		// Forcer en Recherche References
            		category = "REFERENCES";
	        		document.getElementById('selectCategory').value = "REFERENCES";
            	//}
        	} else {
 	        		if (document.getElementById('selectCategory').value == "REFERENCES") {
 	        			// Il faut repasser en mots-cles
 	          			category = "KEYWORDS";
 	 	        		document.getElementById('selectCategory').value = "KEYWORDS";
 	        		}
        	}
        } else {
        	// il faut rebasculer en 
        	if (category == "REFERENCES") {
        		category = "KEYWORDS";
        		document.getElementById('selectCategory').value = "KEYWORDS";
        	}
        }
        
		autoSuggestXHR = jQuery.ajax({
            						url: URL,
            						type: 'POST',
            						dataType: 'html',
            						data: 'search_value=' + encodeURI(value) + "&category=" + encodeURI(category) + "&intervalIndex=" + encodeURI(intervalIDIndex),
            						success: function(data){
            
                                            autoSuggestXHR = null;
            
                                            jQuery(layerHTMLSelector).html("");
                                            jQuery(layerHTMLSelector).html(data);
                                                
                							// resetBorderTextBox(textbox, intervalIDIndex);
                							
                                            $(textbox).css("background", "url(" + imagePathRecherche + ") no-repeat 6px 5px #ffffff");
                                            
                							if($(layerClass).css("display") != "block")
                							{
                								TextBoxObj = $(textbox);
                								Top = TextBoxObj.position().top + TextBoxObj.height();
                								Left = TextBoxObj.position().left;
                
                								$(layerClass).css({ display: 'block', top: Top, left: Left });
                							}
                                            
                                            $(layerHTMLSelector).scrollTop(0);
                                            
                                            rechercheFocus();
            						},
            						error: function (jqXHR, textStatus) {
            							
                                        if(textStatus != "abort")
                                        {
                                            autoSuggestXHR = null;
                                            
                                            $(textbox).css("background", "url(" + imagePathRecherche + ") no-repeat 6px 5px #ffffff");
                							undisplayAutoComplete(layerClass, intervalIDIndex);
                                            
                                            // alert(MsgErreurDeConnexion);
                                        }
                                        
                                        
            						}
            		});
	}
	else
	{
	    $(textbox).css("background", "url(" + imagePathRecherche + ") no-repeat 6px 5px #ffffff");
		undisplayAutoComplete(layerClass, intervalIDIndex);
	}
}

function autoComplete(textbox, value, layerClass, layerHTMLSelector, intervalIDIndex, URL, secondaryTextBox, jsonResult, callbackFunction)
{
	currentAutoCompleteTBox[intervalIDIndex] = textbox;
	if(secondaryTextBox)
    {
        eval(intervalParameters[intervalIDIndex].secondaryTextBoxFunction + "('', intervalIDIndex)");
    } 
	
	if(value.length >= 3)
	{
	    if(autoSuggestXHR)
            autoSuggestXHR.abort();
       
		if($(layerClass).css("display") != "block")
			intervalAutoCompleteID[intervalIDIndex] = window.setTimeout(setBorderTextBox, 10, textbox, intervalIDIndex);
        else
        {
            $(layerClass).find("div").html("<span><img src='" + imagesFolder + "telechargement1.gif' border='0' style='float:left;margin:3px;' /></span>");
        }
        
        if(jsonResult)
            datatype = 'json';
        else
            datatype = 'html';
    	
		autoSuggestXHR = jQuery.ajax({
            						url: URL,
            						type: 'POST',
            						dataType: datatype,
            						data: 'search=' + encodeURI(value) + "&intervalIndex=" + encodeURI(intervalIDIndex),
            						success: function(data){
            
                                            autoSuggestXHR = null;
            
                                            jQuery(layerHTMLSelector).html("");
                                            
                                            if(data == "Rafiner Requete")
                                                jQuery(layerHTMLSelector).html("<span>" + MsgAUTOSUGGESTRafinerRequete + "</span>");
                                            else if(data == "Pas de produits")
                                                jQuery(layerHTMLSelector).html("<span>" + MsgAUTOSUGGESTPasDeProduits + "</span>");
                                            else if(data == "Critere de recherche pas valide")
                                                jQuery(layerHTMLSelector).html("<span>" + MsgAUTOSUGGESTCritereRechercheNonValide + "</span>");
                                            else if(data == "Pas connecte")
                                                jQuery(layerHTMLSelector).html("<span>" + MsgAUTOSUGGESTPasConnecte + "</span>");
                                            else
                                                jQuery(layerHTMLSelector).html(data);
                                                
                							resetBorderTextBox(textbox, intervalIDIndex);
                							
                							if($(layerClass).css("display") != "block")
                							{
                								TextBoxObj = $(textbox);
                								Top = TextBoxObj.position().top + TextBoxObj.height();
                								Left = TextBoxObj.position().left;
                
                								$(layerClass).css({ display: 'block', top: Top, left: Left });
                							}
                                            
            						},
            						error: function (jqXHR, textStatus) {
            							
                                        if(textStatus != "abort")
                                        {
                                            autoSuggestXHR = null;
                                        
                                            resetBorderTextBox(textbox, intervalIDIndex);
            							    undisplayAutoComplete(layerClass, intervalIDIndex);
                                            
                                            alert(MsgErreurDeConnexion);
                                        }
                                        
            						}
            		});
              
	}
	else
	{
		resetBorderTextBox(textbox);
		undisplayAutoComplete(layerClass, intervalIDIndex);
	}
}

function setBorderTextBox(textbox, intervalIDIndex)
{
	if(!jQuery(textbox).hasClass("highlightTBox"))
		jQuery(textbox).addClass("highlightTBox");
	else
		jQuery(textbox).removeClass("highlightTBox");

	if(intervalAutoCompleteID[intervalIDIndex])
		window.clearTimeout(intervalAutoCompleteID[intervalIDIndex]);
	intervalAutoCompleteID[intervalIDIndex] = window.setTimeout(setBorderTextBox, 150, textbox, intervalIDIndex);
}

function resetBorderTextBox(textbox, intervalIDIndex)
{
	if(intervalAutoCompleteID[intervalIDIndex])
		window.clearTimeout(intervalAutoCompleteID[intervalIDIndex]);
	jQuery(textbox).removeClass("highlightTBox");
}

function setArticleRefInfo(articleRef, articleDesc, intervalIDIndex, quantite, uf, prixun, total, prixunnum, condtv, qmax, qmin)
{
	$(currentAutoCompleteTBox[intervalIDIndex]).val(articleRef);
    eval(intervalParameters[intervalIDIndex].secondaryTextBoxFunction + "(articleDesc, intervalIDIndex)");
    
    if(intervalIDIndex == 0)
    {
        // ********************
        // pour commande rapide
        // ********************
        $(currentAutoCompleteTBox[intervalIDIndex]).parents("tr").attr("prix", prixunnum)
                                                   .attr("total", prixunnum * parseInt(quantite))
                                                   .attr("condtv", condtv)
                                                   .attr("qmax", qmax)
                                                   .attr("qmin", qmin)
                                                   .find(".articleQuantity").val(quantite)
                                                   .end()
                                                   .find(".uftxt").val(uf)
                                                   .end()
                                                   .find(".prixtxt").val(prixun)
                                                   .end()
                                                   .find(".totaltxt").val(total)
                                                   .end().end()                                              
                                                   .parents("td")
                                                   .siblings(".tdUf").html(uf)
                                                   .end()
                                                   .siblings(".tdPrix").html(prixun)
                                                   .end()
                                                   .siblings(".tdTotal").html(total)
                                                   .end()
                                                   .siblings(".delArticle").css({ visibility: 'visible' });
                                                   
        Element = $("#commandeRapidePrixDisplay");
        total = parseFloat(Element.attr("total")) + (prixunnum * parseInt(quantite));
        totalstr = new String(total.toFixed(2)).replace(/\./, ",");
        Element.attr("total", total).html(totalstr + "&euro;");
    }
    else if(intervalIDIndex == 2)
    {
        // ********************
        // pour panier
        // ********************
        
        var context = { 
            condition : condtv,
            qmaxy : qmax,
            qmini : qmin,
            QtyElement : $(".achatRapid .qty")
        };
        
        $(".achatRapid .qty").val(quantite);
        $(".achatRapid .qty").unbind("change");
        $(".achatRapid .qty").bind("change", $.proxy(function () {
           
            currentQuantity = parseInt(this.QtyElement.val());
            
            if(!check_qty_input(currentQuantity, this.condition, this.qmaxy, this.qmini))
            {
                this.QtyElement.val(this.condition);
            }
            
        }, context));
                                                 
    }
    
}

function setSearchTextBoxInfo(textStr)
{
    $("#sousRechercheTxt").val(textStr);
}

function setSecondaryTextBox(articleDesc, intervalIDIndex)
{
	if($(currentAutoCompleteTBox[intervalIDIndex]).next()[0].tagName.toLowerCase() == "input")
		$(currentAutoCompleteTBox[intervalIDIndex]).next().val(articleDesc);
	else if($(currentAutoCompleteTBox[intervalIDIndex]).siblings("input")[0].tagName.toLowerCase() == "input")
		$(currentAutoCompleteTBox[intervalIDIndex]).siblings("input").val(articleDesc);
  
}

function setSecondaryTextBoxCommandeRapide(articleDesc, intervalIDIndex)
{
	$(currentAutoCompleteTBox[intervalIDIndex]).siblings("input").val(articleDesc);
    if(articleDesc == "")
        supprimerArticle(currentAutoCompleteTBox[intervalIDIndex], true);
}

function setSecondaryTextBoxAchatRapid(articleDesc, intervalIDIndex)
{
    $(currentAutoCompleteTBox[intervalIDIndex]).next().val(articleDesc);
    $(".achatRapid .qty").val(articleDesc);
    $(".achatRapid .qty").unbind("change");
}

function undisplayAutoComplete()
{
	if(TimeoutID != null)
	{
		layerClass = intervalParameters[TimeoutID].layerClass;
		intervalIDIndex = intervalParameters[TimeoutID].intervalIDIndex;
		
		if(intervalAutoCompleteLayerID[intervalIDIndex])
		{
			window.clearTimeout(intervalAutoCompleteLayerID[intervalIDIndex]);
			$(layerClass).css({ display: 'none' });
		}
	}
}

/*
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

/*  5/19/2011
		PikaChoose
	Jquery plugin for photo galleries
    Copyright (C) 2011 Jeremy Fry

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

// Added intervalCarouselID and backtonormalCarouselItem() for the animation of the plus sign
intervalCarouselID = null;
intervalImagePlusID = null;
currentImage = null;

function backtonormalCarouselItem()
{
	that = $("#pikame").data('pikachoose');
	image = currentImage;
	
	if(!$(image).hasClass("active")){
		$(image).stop(true,true).fadeTo(250,that.options.thumbOpacity);
	}
	
	$(image).parents(".jcarousel-item").find(".imageplus").remove();
	
}

function backtonormalAllCarouselItems(currentimage, that)
{
	currentli = $(currentimage).parents(".jcarousel-item");
	
	$(".jcarousel-item").not(currentli).each(function (i) {
		
		image = $(this).find("img");
		
		if(!image.hasClass("active")){
			image.stop(true,true).fadeTo(250,that.options.thumbOpacity);
		}
		$(this).find(".imageplus").remove();
		
	});

}

function renderImagePlusSign()
{
	$(".imageplus").css({ visibility: 'visible' });	
}

(function($) {
    /**
     * Creates a slideshow for all matched elements.
     *
     * @example $("#pikame").PikaChoose();
     * @input needed <ul id="pikame"><li><img src="first.jpg"><span>Caption</span></li><li><img src="second.jpg"><span>Caption</span></li></ul>
     *
     * @method PikaChoose
     * @return $
     * @param o {Hash|String} A set of key/value pairs to set as configuration properties or a method name to call on a formerly created instance.
     */
 	var defaults = {
		autoPlay: true,
		speed: 5000,
		text: { play: "", stop: "", previous: "Previous", next: "Next" },
		transition:[1],
		showCaption: true,
		IESafe: true,
		showTooltips: false,
		carousel: false,
		carouselVertical: false,
		animationFinished: null,
		buildFinished: null,
		startOn: 0,
		thumbOpacity: 0.4,
		hoverPause: false
	};
   
    $.fn.PikaChoose = function(o) {
		return this.each(function() {
			$(this).data('pikachoose', new $pc(this, o));
		});
	};
	
	/**
     * The PikaChoose object.
     *
     * @constructor
     * @class pikachoose
     * @param e {HTMLElement} The element to create the carousel for.
     * @param o {Object} A set of key/value pairs to set as configuration properties.
     * @cat Plugins/PikaChoose
     */
    $.PikaChoose = function(e, o) {
		this.options    = $.extend({}, defaults, o || {});
		this.list     	= null;
		this.image  	= null;
		this.anchor		= null;
		this.caption	= null;
		this.imgNav		= null;
		this.imgPlay 	= null;
		this.imgPrev	= null;
		this.imgNext 	= null;
		this.textNext	= null;
		this.textPrev	= null;
		this.previous  	= null;
		this.next 		= null;
		this.aniWrap	= null;
		this.aniDiv		= null;
		this.aniImg		= null;
		this.thumbs		= null;
		this.transition	= null;
		this.active		= null;
		this.tooltip	= null;
		this.animating	= false;
		this.stillOut 	= null;
		this.counter	= null;
		this.timeOut	= null;
		if(typeof(this.options.data) != "undefined"){
			//user passed a data source
			e = $("<ul></ul>").appendTo(e);
			$.each(this.options.data,function(){
				var tmp = $("<li><a href='"+this.link+"'><img src='"+this.image+"'></a></li>").appendTo(e);
				if(typeof(this.title) != "undefined"){ tmp.find('a').attr('title',this.title); }
				if(typeof(this.caption) != "undefined"){ tmp.append("<span>"+this.caption+"</span>"); }
				if(typeof(this.thumbnail) != "undefined"){ tmp.find('a').attr('ref',this.thumbnail); }
			});
		}
		if(e.nodeName == 'UL' || e.nodeName == 'OL' || e instanceof  jQuery) {
            this.list = $(e);
            this.build();
            this.bindEvents();
        }else{
        	return;
        }
		
		var y = 0;
		var x = 0;
		for(var t = 0; t<25;t++){
			var a = '<div col="'+y+'" row="'+x+'"></div>';
			this.aniDiv.append(a);
			y++;
			if(y == 5){
				x++;
				y=0;
			}
		}

		var Self = this;

		// Add on for the animation of the plus sign on a carousel item for the slideshow
		jQuery(".jcarousel-item").css({ position: 'relative' }).find(".clip").mouseover(function (event) {
			
			if(navigator.appVersion.indexOf("MSIE 6") >= 0)
			{
				if(!$(this).find(".imageplus").hasClass("imageplus") && !$(this).find("img").hasClass("active"))
				{
					$("<span>").attr("class", "imageplus")
							   .css({ top: 12, left: 89, visibility: 'hidden' })
							   .bind("click", {spanClicked:true,self:Self}, $("#pikame").data('pikachoose').imgClick)
							   .mouseover(function () { if(intervalCarouselID) window.clearTimeout(intervalCarouselID); })
							   .appendTo(this);
					
					window.setTimeout(renderImagePlusSign, 10);
					
				}
			}
			else
			{
				if(!$(this).find(".imageplus").hasClass("imageplus") && !$(this).find("img").hasClass("active"))
				{
					$("<span>").attr("class", "imageplus")
							   .css({ top: 12, left: 89 })
							   .bind("click", {spanClicked:true,self:Self}, $("#pikame").data('pikachoose').imgClick)
							   .mouseover(function () { if(intervalCarouselID) window.clearTimeout(intervalCarouselID); })
							   .appendTo(this);
							
				}
			}
					  
		});

    };//end PikaChoose function(e, o)
    
    var $pc = $.PikaChoose;
        $pc.fn = $pc.prototype = {
        pikachoose: '4.2.9'
    };
	
	$.fn.pikachoose = $.fn.PikaChoose;

    $pc.fn.extend = $pc.extend = $.extend;

    $pc.fn.extend({
        /**
         * Builds the gallery structure.
         *
         * @method build
         * @return undefined
         */
        build: function() {
            
        	this.step 		= 0; //transition step count
       	
            //create the structure for pikachoose
			this.wrap 		= $("<div class='pika-stage'></div>").insertBefore(this.list);
			this.image 		= $("<img>").appendTo(this.wrap);
			this.imgNav 	= $("<div class='pika-imgnav'></div>").insertAfter(this.image);
			this.imgPlay 	= $("<a></a>").appendTo(this.imgNav);
			this.counter 	= $("<span class='pika-counter'></span>").appendTo(this.imgNav);
			if(this.options.autoPlay){ this.imgPlay.addClass('pause'); }else{ this.imgPlay.addClass('play'); }
			this.imgPrev 	= $("<a class='previous'></a>").insertAfter(this.imgPlay);
			this.imgNext 	= $("<a class='next'></a>").insertAfter(this.imgPrev);
			this.caption 	= $("<div class='caption'></div>").insertAfter(this.imgNav).hide();
			this.tooltip 	= $("<div class='pika-tooltip'></div>").insertAfter(this.list).hide();
			this.aniWrap	= $("<div class='pika-aniwrap'></div>").insertAfter(this.caption);
			this.aniImg		= $("<img>").appendTo(this.aniWrap).hide();
			this.aniDiv		= $("<div class='pika-ani'></div>").appendTo(this.aniWrap);
			this.textNav 	= $("<div class='pika-textnav'></div>").insertAfter(this.aniWrap);
			this.textPrev 	= $("<a class='previous'>"+this.options.text.previous+"</a>").appendTo(this.textNav);
			this.textNext	= $("<a class='next'>"+this.options.text.next+"</a>").appendTo(this.textNav);
			this.list.addClass('pika-thumbs');
        	this.list.children('li').wrapInner("<div class='clip' />");
			this.thumbs = this.list.find('img');
			this.active		= this.thumbs.eq(this.options.startOn);
			
			//fill in info for first image
			this.finishAnimating({'source':this.active.attr('ref') || this.active.attr('src'),'caption':this.active.parents('li:first').find('span:first').html(), 'clickThrough':this.active.parent().attr('href') || "", 'clickThroughTitle':this.active.parent().attr('title') || ""});

			//process all the thumbnails
			var self = this;
			this.thumbs.each(function(){
				self.createThumb($(this),self);
			});
			
			if(this.options.carousel){
				this.list.jcarousel({vertical:this.options.carouselVertical, carouselSlideShow: true, initCallback: function(carousel){
					jQuery(carousel.list).find('div').click(function() {
						var clicked = parseInt(jQuery(this).parents('.jcarousel-item').attr('jcarouselindex'));
						var last = (jQuery(this).parents('ul').find('li:last').index() == clicked-1) ? true : false;
						if(!last){
							clicked = (clicked-2<=0) ? 0 : clicked-2;
						}
						clicked++;
						carousel.scroll(clicked);
					});
				}});
			}
			
			if(typeof(this.options.buildFinished) == 'function'){
	     		this.options.buildFinished(this);
	     	}
            
            $(".slideShowCont").css("visibility", "visible");
            
		}, //end setup
        /**
         * proccesses thumbnails
         *
         * @method createThumb
         * @return undefined
         */
        createThumb: function(ele) {
        	var self = ele;
			var that = this;
        	self.hide();
        	
			//store all the data with the image
        	$.data(ele[0],'clickThrough',self.parent('a').attr('href') || "");
        	$.data(ele[0],'clickThroughTitle',self.parent('a').attr('title') || "");
        	if(self.parent('a').length > 0){ self.unwrap(); }
        	$.data(ele[0],'caption',self.next('span').html() || "");
			self.next('span').remove();
        	$.data(ele[0],'source',self.attr('ref') || self.attr('src'));
			
			//gets each items index to iterate through them. Thanks to Tushar for the fix.
			$.data(ele[0],'order',self.closest('ul').find('li').index(self.parents('li')));
    		//pass data so it can enter the load scope
    		var data = $.data(ele[0]);
    		$('<img />').bind('load',{data:data},function(){
	    		if(typeof(that.options.buildThumbStart) == 'function'){
		     		that.options.buildThumbStart(that);
		     	}
    			//in this scope self refers to the image
				var img = $(this);
				var w = this.width;
				var h = this.height;
				if(w===0){w = img.attr("width");}
				if(h===0){h = img.attr("height");}
				//grab a ratio for image to user defined settings
				var rw = parseInt(self.parents('.clip').css('width').slice(0,-2))/w;
				var rh = parseInt(self.parents('.clip').css('height').slice(0,-2))/h;
				//determine which has the smallest ratio (thus needing
				//to be the side we use to scale so our whole thumb is filled)
				var ratio;
				if(rw<rh){
					//we'll use ratio later to scale and not distort
					ratio = rh;
					var left = ((w*ratio- parseInt(self.parents('.clip').css('width').slice(0,-2)))/2)*-1;
					left = Math.round(left);
					self.css({left:left});
				}else{
					ratio = rw;
					self.css({top:0});
				}
				//use those ratios to calculate scale
				var width = Math.round(w*ratio);
				var height = Math.round(h*ratio);
				self.css("position","relative");
				var imgcss={
					width: width+"px",
					height: height+"px"
				};
				self.css(imgcss);
				self.hover(
					function(e){
						
						backtonormalAllCarouselItems(this, that);
						
						window.clearTimeout(that.stillOut);
						$(this).stop(true,true).fadeTo(250,1);
						if(!that.options.showTooltips){ return; }
						that.tooltip.show().stop(true,true).html(data.caption).animate({top:$(this).parent().position().top, left:$(this).parent().position().left, opacity: 1.0},'fast');
						
					},
					function(e){
						
						currentImage = this;
						intervalCarouselID = window.setTimeout(backtonormalCarouselItem,100);
					}
				);

				if(data.order == that.options.startOn){
					self.fadeTo(250,1);
					self.addClass('active');
					self.parents('li').eq(0).addClass('active');
				}else{
					self.fadeTo(250,that.options.thumbOpacity);
				}
				if(typeof(that.options.buildThumbFinish) == 'function'){
		     		that.options.buildThumbFinish(that);
		     	}
    		}).attr('src',self.attr('src'));
        },//end createThumb
		/**
         * proccesses thumbnails
         *
         * @method bindEvents
         * @return undefined
         */
        bindEvents: function(e) {
        	this.thumbs.bind('click',{self:this},this.imgClick);
        	this.imgNext.bind('click',{self:this},this.nextClick);
        	this.textNext.bind('click',{self:this},this.nextClick);
        	this.imgPrev.bind('click',{self:this},this.prevClick);
        	this.textPrev.bind('click',{self:this},this.prevClick);
        	this.imgPlay.bind('click',{self:this},this.playClick);
        	
			// display the nav next and prev buttons
			this.imgNav.stop(true,true).fadeIn('slow');
			// clearTimeout(this.timeOut);
			
			this.wrap.bind('mouseenter',{self:this},function(e){
        		//e.data.self.imgNav.stop(true,true).fadeIn('slow');
				if(e.data.self.options.hoverPause == true){
					window.clearTimeout(e.data.self.timeOut);
				}
        	});
        	this.wrap.bind('mouseleave',{self:this},function(e){
        		//e.data.self.imgNav.stop(true,true).fadeOut('slow');
				
				if(e.data.self.options.autoPlay == true && e.data.self.options.hoverPause){
					
					if(e.data.self.timeOut)
						window.clearTimeout(e.data.self.timeOut);
						
					e.data.self.timeOut = window.setTimeout((function(self){
						return function(){  self.nextClick(); };
					})(e.data.self), e.data.self.options.speed);
				}
        	})
			
			this.tooltip.bind('mouseenter',{self:this},function(e){
				window.clearTimeout(e.data.self.stillOut);
			});
			this.tooltip.bind('mouseleave',{self:this},function(e){
				e.data.self.stillOut = window.setTimeout(e.data.self.hideTooltip,700);
			});
			
        },//end bind event
		/**
         * hides tooltip
         *
         * @method hideTooltip
         * @return undefined
         */
		hideTooltip: function (e){
			$(".pika-tooltip").animate({opacity:0.01});
		},
        /**
         * handles gallery after aclick occurs. and sets active classes
         *
         * @method imgClick
         * @return undefined
         */
	     imgClick: function(e,x) {
            
            rechercheCancelTimeout();
            
	        var self = e.data.self;
			var spanClicked = e.data.spanClicked;
			
			if(spanClicked)
				var data = $.data($(this).siblings("img")[0]);
			else
				var data = $.data(this);
			
	     	if(self.animating){return;}
     		if(typeof(x) == 'undefined' || x.how != "auto"){
	     		//arrive here if natural click
	     		if(self.options.autoPlay){
	     			self.imgPlay.trigger('click');
	     		}
			}else{
				if(self.options.autoPlay == false){
					return false;
				}
			}
		
			self.caption.fadeOut('slow');
	     	self.animating = true;
			if(spanClicked)
			{
				self.active.fadeTo(300,self.options.thumbOpacity).removeClass('active');
				self.active.parents('.active').eq(0).removeClass('active');
				self.active = $(this).siblings("img");
				self.active.addClass('active').fadeTo(200,1);
				self.active.parents('li').eq(0).addClass('active');
			}
			else
			{
				self.active.fadeTo(300,self.options.thumbOpacity).removeClass('active');
				self.active.parents('.active').eq(0).removeClass('active');
				self.active = $(this);
				self.active.addClass('active').fadeTo(200,1);
				self.active.parents('li').eq(0).addClass('active');
			}
	 		$('<img />').bind('load', {self:self,data:data}, function(){
				//in this scope self referes to the PikaChoose object
				self.aniDiv.css({height:self.image.height(),width:self.image.width()}).fadeIn('fast');
				self.aniDiv.children('div').css({'width':'20%','height':'20%','float':'left'});
		
				//decide our transition
				var n = 0;
				if(self.options.transition[0] == -1){	
					//random
					n = Math.floor(Math.random()*7)+1;
				}else{
					n = self.options.transition[self.step];
					self.step++;
					if(self.step >= self.options.transition.length){self.step=0;}
				}
				if(self.options.IESafe && $.browser.msie){ n = 1; }
				self.doAnimation(n,data);
				
			}).attr('src',data.source);//end image preload
	     },//end bindEvents
	     doAnimation: function(n,data){
	     		var self = this; //self in this scope refers to PikaChoose object. Needed for callbacks on animations
				self.image.stop(true,false);
				self.caption.stop().fadeOut();
				var aWidth = self.aniDiv.children('div').eq(0).width();
				var aHeight = self.aniDiv.children('div').eq(0).height();
				var img = new Image();
				$(img).attr('src',data.source);
				if(img.height != self.image.height() || img.width != self.image.width()){
					//Your images are not the same height? Well you get limited on transitions
					if(n != 0 && n != 1 && n != 7){
						n = 1;
					}
				}
				self.aniDiv.css({height:img.height,width:img.width});
				self.aniDiv.children().each(function(){
					//position myself absolutely
					var div = $(this);
					var xOffset = Math.floor(div.parent().width()/5)*div.attr('col');
					var yOffset = Math.floor(div.parent().height()/5)*div.attr('row');
					div.css({
						'background':'url('+data.source+') -'+xOffset+'px -'+yOffset+'px',
						'width':'0px',
						'height':'0px',
						'position':'absolute',
						'top':yOffset+'px',
						'left':xOffset+'px',
						'float':'none'
					});
				});//end ani_divs.children.each
				
                self.aniDiv.hide();
				self.aniImg.hide();
				
                
	     		switch(n){
					case 0:
						//fade out then in
						self.image.stop(true,true).fadeOut('slow',function(){
							self.image.attr('src',data.source).fadeIn('slow',function(){
								self.finishAnimating(data);
							});
						});
	
						break;
					case 1:
						//full frame fade
						self.aniDiv.hide();
						self.aniImg.height(self.image.height()).hide().attr('src',data.source);
						$.when(
							self.image.fadeOut('slow'),
							self.aniImg.eq(0).fadeIn('slow')).done(function(){
							self.finishAnimating(data);
						});
	
						break;
					case 2:
						self.aniDiv.show().children().hide().each(function(index){  
							//animate out as blocks 
							var delay = index*30;
							$(this).css({opacity: 0.1}).show().delay(delay).animate({opacity: 1,"width":aWidth,"height":aHeight},200,'linear',function(){
								if(self.aniDiv.find("div").index(this) == 24){
									self.finishAnimating(data);
								}
							});
						});
						break;
					case 3:
						self.aniDiv.show().children("div:lt(5)").hide().each(function(index){
							var delay = $(this).attr('col')*100;
							$(this).css({opacity:0.1,"width":aWidth}).show().delay(delay).animate({opacity:1,"height":self.image.height()},700,'linear',function(){
								if(self.aniDiv.find(" div").index(this) == 4){
									self.finishAnimating(data);
								}
							});
						});
						break;							
					case 4:
						self.aniDiv.show().children().hide().each(function(index){
							if(index>4){ return; }
							var delay = $(this).attr('col')*10;
							aHeight = self.gapper($(this), aHeight);
							$(this).css({opacity:0.1,"height":"100%"}).show().animate({opacity:1,"width":aWidth},500,'linear',function(){
								if(self.aniDiv.find(" div").index(this) == 4){
									self.finishAnimating(data);
								}
							});
						});
						break;
					case 5:
						self.aniDiv.show().children().show().each(function(index){
						  
							var delay = index*Math.floor(Math.random()*5)*7;
							aHeight = self.gapper($(this), aHeight);
							
							if($(".animation div").index(this) == 24){
								delay = 600;
							}
							$(this).css({"height":aHeight,"width":aWidth,"opacity":.01}).delay(delay).animate({"opacity":1},600,function(){
								if(self.aniDiv.find(" div").index(this) == 24){
									self.finishAnimating(data);
								}
							}); 

						});
						break;
					case 6:
						//full frame slide
						self.aniDiv.height(self.image.height()).hide().css({'background':'url('+data.source+') top left no-repeat'});
						self.aniDiv.children('div').hide();
						self.aniDiv.css({width:0}).show().animate({width:self.image.width()},'slow',function(){
							self.finishAnimating(data);
							self.aniDiv.css({'background':'transparent'});
						});
						break;
					case 7:
						//side in slide
						self.wrap.css({overflow:'hidden'});
						self.aniImg.height(self.image.height()).hide().attr('src',data.source);
						self.aniDiv.hide();
						self.image.css({position:'relative'}).animate({left:"-"+self.wrap.outerWidth()+"px"});
						self.aniImg.show();
						self.aniWrap.css({left:self.wrap.outerWidth()}).show().animate({left:"0px"},'slow',function(){
							self.finishAnimating(data);
						});
						break;
				}

	     },//end doAnimation
	     finishAnimating: function(data){
     		this.animating = false;
			this.image.attr('src',data.source);
			this.image.css({left:"0"});
			this.image.show();
			var self = this;
			$('<img />').bind('load',function(){
				self.aniImg.hide();
				self.aniDiv.hide();
			}).attr('src',data.source);
     		var cur = this.list.find('img').index(this.active);
     		cur++;
     		var total = this.list.find('img').length;
     		this.counter.html(cur+"/"+total);
			if(data.clickThrough != ""){
				if(this.anchor == null){
					this.anchor	= this.image.wrap("<a>").parent();
				}
				//this.anchor.attr('href','javascript:void(0);');
				//this.anchor.attr('title','');
				this.anchor.attr('href',data.clickThrough);
				this.anchor.attr('title',data.clickThroughTitle);
			}else{
	        	if(this.image.parent('a').length > 0){ this.image.unwrap(); }
				this.anchor = null;
			}
     		if(this.options.showCaption && data.caption != "" && data.caption != null){
     			this.caption.html(data.caption).fadeTo('slow',0.9);
     		}
			this.options.autoPlay = true;
     		if(this.options.autoPlay == true){
     			var self = this;
				if(this.timeOut)
					window.clearTimeout(this.timeOut);
     			this.timeOut = window.setTimeout((function(self){
					return function(){ self.nextClick(); };
				})(this), this.options.speed, this.timeOut);
     		}
     		
     		if(typeof(this.options.animationFinished) == 'function'){
	     		this.options.animationFinished(this);
	     	}
	     },//end finishedAnimating
		 gapper: function(ele, aHeight){
			if(ele.attr('row') == 9 && ele.attr('col') == 0){
				//last row, check the gap and fix it!
				var gap = ani_divs.height()-(aHeight*9);
				return gap;
			}
			return aHeight;
		 },
		 nextClick : function(e){
    
            rechercheCancelTimeout();
              
			var how = "natural";
		 	try{
				var self = e.data.self;
				if(typeof(e.data.self.options.next) == 'function'){
					e.data.self.options.next(this);
				}
			}catch(err){
				var self = this;
				how = "auto";
			}
			var next = self.active.parents('li:first').next().find('img');
			if(next.length == 0){next = self.list.find('img').eq(0);};
		 	next.trigger('click',{how:how});
		 },
		 prevClick : function(e){
		  
            rechercheCancelTimeout();
          
			if(typeof(e.data.self.options.previous) == 'function'){
	     		e.data.self.options.previous(this);
	     	}
			var self = e.data.self;
			var prev = self.active.parents('li:first').prev().find('img');
			if(prev.length == 0){prev = self.list.find('img:last');};
		 	prev.trigger('click');
		 },
		 playClick: function(e){
	  
		 	var self = e.data.self;
		 	self.options.autoPlay = !self.options.autoPlay;
			self.imgPlay.toggleClass('play').toggleClass('pause');
			if(self.options.autoPlay){ self.nextClick(); }
		 }
	}); //end extend

})(jQuery);

/********************************************************************/
/* Les fonctions Ajax */ 
/********************************************************************/
function leveragingIELoadingLeftCoordinate(Left, LoadingRelativeLink, LoadingOnTheLeft)
{
    if(navigator.appVersion.indexOf("MSIE 9") >= 0)
    {
        if($(LoadingRelativeLink).siblings("form").size() > 0)
            Left = Left + 37;
        else
        {
            if($(LoadingRelativeLink).siblings("a").size() > 0)
            {
                Left = Left;
            }
            else
            {
                if($(LoadingRelativeLink).width() > 29)
                    Left = Left + ($(LoadingRelativeLink).width() - 29);
                else
                    Left = Left + 55;
            }
        }
    }
    else if(navigator.appVersion.indexOf("MSIE 7") >= 0)
    {
        if($(LoadingRelativeLink).siblings("a").size() > 0)
        {
            if(LoadingOnTheLeft)
                Left = Left;
        }        
        else
            Left = Left + 5;
    }
    
    if(navigator.userAgent.indexOf("Safari") >= 0 && navigator.userAgent.indexOf("Chrome") < 0)
    {
        if($(LoadingRelativeLink).siblings("a").size() == 0)
        {
            if($(LoadingRelativeLink).siblings("form").size() > 0)
                Left = Left + 37;
            else if($(LoadingRelativeLink).attr("title") == "Supprimer" && location.href.indexOf("liste_commande") >= 0)
                Left = Left + 18;
            else
                Left = Left + 57;
        }
    }
    
    
    return Left;
}

function sendingAjax(URL, PostDataQueryStr, callBackFunction, callBackParameters, LoadingRelativeLink, LoadingOnTheLeft)
{
    if($("#imgLoadingBarID").attr("id") == "imgLoadingBarID")
        $("#imgLoadingBarID").remove();
        
    // Afficher le telechargement
    if(LoadingRelativeLink)
    {
        LoadingAppendElementTo = null;
        
        if(LoadingRelativeLink.tagName.toLowerCase() == "a" && $(LoadingRelativeLink).find("img").size() > 0)
        {

            LoadingRelativeLinkElement = $(LoadingRelativeLink).find("img");          

            if(LoadingOnTheLeft == "left") 
                Left = LoadingRelativeLinkElement.position().left - 12;
            else
                Left = LoadingRelativeLinkElement.position().left + LoadingRelativeLinkElement.width() + 2;   
            
            Left = leveragingIELoadingLeftCoordinate(Left, LoadingRelativeLink, LoadingOnTheLeft);
                
            Top = LoadingRelativeLinkElement.position().top;
            srcLink = "images/new/loadingbar.gif";
        }  
        else if(LoadingRelativeLink.tagName.toLowerCase() == "input" && LoadingRelativeLink.type == "text") 
        {
            LoadingRelativeLinkElement = $(LoadingRelativeLink);
            Left = LoadingRelativeLinkElement.position().left + LoadingRelativeLinkElement.width() + 15;
            Top = LoadingRelativeLinkElement.position().top;
            srcLink = "images/new/loadingbar-text.gif";
            
            if(location.href.indexOf("devisExport.php") >= 0) LoadingAppendElementTo = LoadingRelativeLinkElement.parent();
        }
        else if((LoadingRelativeLink.tagName.toLowerCase() == "input" && LoadingRelativeLink.type == "button")) 
        {
            LoadingRelativeLinkElement = $(LoadingRelativeLink);
            Left = LoadingRelativeLinkElement.position().left + LoadingRelativeLinkElement.width() + 33;
            Top = LoadingRelativeLinkElement.position().top;
            srcLink = "images/new/loadingbar-button.gif";
        }
        else if((LoadingRelativeLink.tagName.toLowerCase() == "a" && $(LoadingRelativeLink).find("img").size() == 0))
        {
            LoadingRelativeLinkElement = $(LoadingRelativeLink);
            Left = LoadingRelativeLinkElement.position().left + LoadingRelativeLinkElement.width() + 58;
            Top = LoadingRelativeLinkElement.position().top + 13;
            srcLink = "images/new/loadingbar-button.gif";
        }
        
        LoadingAppendElementTo = LoadingAppendElementTo ? LoadingAppendElementTo : LoadingRelativeLinkElement.parent().parent();
        
        $("<img>").css({ position: 'absolute',
                         top: Top,
                         left: Left })
                  .attr("src", srcLink)
                  .attr("id", "imgLoadingBarID")
                  .appendTo(LoadingAppendElementTo);
    }
    
    // Le jquery ajax
    jQuery.ajax({
	       			url: URL,
					type: 'POST',
					dataType: 'json',
					data: PostDataQueryStr,
					success: function(data){
                        
                        // fait disparaitre le telechargement
                        if($("#imgLoadingBarID").attr("id") == "imgLoadingBarID")
                            $("#imgLoadingBarID").remove();
                        
                        // Erreur pas connecté
                        if(data["status"] == "pas connecte")
                        {
                            alert(MsgPasConnecte);
                            return false;
                        }
                        
                        // appeler le callback fonction
                        if(callBackFunction)
                            eval(callBackFunction + "(callBackParameters, data);");
                                
					},
					error: function () {
						alert(MsgErreurDeConnexion);
					}
           		});
                
}



/********************************************************************/
/* Les fonctions pour ouvrir les popups */
/********************************************************************/

/*============================================================*/
/* Set des fonctions pour les popups connection */
/*============================================================*/
function openPopUpConnection() { displayBackgroundPopUp("callBackConnection", null, true); }
function callBackConnection() { openPopUp(".layerConnexion"); }
function closePopUpConnection() { closePopUp(".layerConnexion"); }

function openPopUpConnectionNonDispo() { displayBackgroundPopUp("callBackConnectionNonDispo", null, true); }
function callBackConnectionNonDispo() { openPopUp(".layerConnectionNonDispo"); }
function closePopUpConnectionNonDispo() { closePopUp(".layerConnectionNonDispo"); }
/*============================================================*/
/* Fin - Set des fonctions pour les popups connection */
/*============================================================*/

/*==============================================================================*/
/* Set des fonctions pour le popup Dessins3D, Montage, Certificat de conformité */
/*==============================================================================*/
function openPopUpDocument(Selector) {
	
	// Call to displayBackgroundPopUp to load the grey background
	displayBackgroundPopUp("callBackDocument", Selector, false, true);
	
}

function callBackDocument(Selector) {
	
	// Undisplay telechargement
	undisplayTelechargement();
	
	// Call to openPopUp function 
	openPopUp(Selector);	

}

function closePopUpDocument(Selector) {
	
	// Call to closePopUp function 
	closePopUp(Selector);
	
}
/*============================================================*/
/* Fin - Set des fonctions pour le popup Dessins3D */
/*============================================================*/

/*============================================================*/
/* Set des fonctions pour le popup Aide */
/*============================================================*/
function openPopUpAide(Parameters) {
	
	// Call to displayBackgroundPopUp to load the grey background
	displayBackgroundPopUp("callBackAide", Parameters, false, true);
	
}

function callBackAide(Parameters) {
	
	// Faites le call ajax ici pour recuperer les informations depuis la base de données.
	
	// Undisplay telechargement
	undisplayTelechargement();
	
	// Call to openPopUp function 
	openPopUp(".layerAide");	

}

function closePopUpAide() {
	
	// Call to closePopUp function 
	closePopUp(".layerAide");
	
}
/*============================================================*/
/* Fin - Set des fonctions pour le popup Dessins3D */
/*============================================================*/

/*============================================================*/
/* Set des fonctions pour le popup QuestionProduit */
/*============================================================*/
function openPopUpQuestionProduit(Parameters) {
	
	// Call to displayBackgroundPopUp to load the grey background
	displayBackgroundPopUp("callBackQuestionProduit", Parameters, false, true);
	
}

function callBackQuestionProduit(Parameters) {
	
	// Faites le call ajax ici pour recuperer les informations depuis la base de données.
	
	// Undisplay telechargement
	undisplayTelechargement();
	
	// Call to openPopUp function 
	openPopUp(".layerQuesProd");	

}

function closePopUpQuestionProduit() {
	
	// Call to closePopUp function 
	closePopUp(".layerQuesProd");
	
}
/*============================================================*/
/* Fin - Set des fonctions pour le popup QuestionProduit */
/*============================================================*/
/*============================================================*/
/* Set des fonctions pour le popup Photo Stretch */
/*============================================================*/
function openPopUpPhotoStretch(Parameter) {

	// Call to displayBackgroundPopUp to load the grey background
	displayBackgroundPopUp("callBackPhotoStretch", Parameter, false, true);
	
}

function callBackPhotoStretch(Parameter) {
	
	// load Photo ici
	jQuery("#imgPhotoStretch").unbind("load")
						      .attr("src", "")
						      .load(function () {
		
		// Undisplay telechargement
		undisplayTelechargement();
		
        if(navigator.appVersion.indexOf("MSIE 7") >= 0)
        {
            var IMG = new Image();
            IMG.src = Parameter;
            
            imageWidth = IMG.width + 30;
            
            $("#layerPStretch").width(imageWidth);
        }
        
		// Call to openPopUp function 
		openPopUp("#layerPStretch");
		
	}).attr("src", Parameter);
	
}

function closePopUpPhotoStretch() {
	
	// Call to closePopUp function 
	closePopUp("#layerPStretch");
	
}
/*============================================================*/
/* Fin - Set des fonctions pour le popup Photo Stretch */
/*============================================================*/
/*============================================================*/
/* Set des fonctions pour le popup Video */
/*============================================================*/
function openPopUpVideo(product_name, product_id, annexe_id) {

	// Call to displayBackgroundPopUp to load the grey background
	displayBackgroundPopUp("callBackVideo", [product_name, product_id, annexe_id], false, true);
	
}

function callBackVideo(parameters) {
    
    if(new String($("#layerVideoIFrame").html()).length == 0)
    {
        URL = "displayvideo.php";
        
        product_name = parameters[0];
        product_id = parameters[1];
        annexe_id = parameters[2];
        
        // Faites le call ajax ici pour recuperer les informations depuis la base de données.
        callBackXHR = jQuery.ajax({
    	       			url: URL + "?products_id=" + encodeURI(product_id),
    					type: 'POST',
    					dataType: 'html',
    					data: null,
    					success: function(data){
                            
                            if(data == "Not Connected")
                            {
                                alert(MsgPasConnecte);
                                // Undisplay telechargement
                           	    undisplayTelechargement();
                                undisplayBackgroundPopUp();
                                return;
                            }
                            
                            if(data)
                            {
                                $("#layerVideoID #videoProduitID").html(product_name);
                                
                                HTMLElements = $(data);
                                
                                document.WidthOfVideoDiv = 0;
                                
                                if(HTMLElements.find("iframe").size() > 0)
                                {
                                    HTMLElements.find("iframe").each(function (i) { 
                                            
                                            if($(this)[0].tagName.toLowerCase() == "iframe")
                                            {
                                                NewWidth = parseInt($(this).attr("width").replace(/px/, ""));
                                                if(document.WidthOfVideoDiv < NewWidth)
                                                    document.WidthOfVideoDiv = NewWidth;
                                            }
    
                                        });
                                    
                                    $("#layerVideoID").width(document.WidthOfVideoDiv + 63);
                                }
                                else
                                {
                                    $("#layerVideoID").width(580);
                                }
                                
                                $("#layerVideoIFrame").html(data);
                                
                                titleId = "video" + annexe_id;
                                Top = 0;
                                Position = 0;
                                
                                $("#layerVideoIFrame h3").each(function (i) {
                                    
                                    if($(this).attr("id") == titleId && i > 0)
                                    {
                                        Top = $(this).position().top + 388;
                                        Position = i;
                                    }
                                });
    
                                HeightIFrames = 0;
    
                                if(HTMLElements.find("iframe").size() > 0)
                                {
                                    HTMLElements.find("iframe").each(function (i) { 
                                            
                                        if(i < Position)
                                        {
                                            if($(this)[0].tagName.toLowerCase() == "iframe")
                                            {
                                                HeightIFrame = parseInt($(this).attr("height").replace(/px/, ""));
                                                HeightIFrames = HeightIFrames + HeightIFrame;
                                            }
                                        }
    
                                    });
                                }
    
                                Top = Top + HeightIFrames;
    
                                // Undisplay telechargement
                           	    undisplayTelechargement();
                            	
                                functionOpenPopUpCallBack = '(function () { $("#layerVideoIFrame").scrollTop(' + Top + '); })();';
                                
                            	// Call to openPopUp function 
                            	openPopUp("#layerVideoID", functionOpenPopUpCallBack);
                            }
                            else
                            {
                                // Undisplay telechargement
                           	    undisplayTelechargement();
                                undisplayBackgroundPopUp();
                                alert(MsgVideoNexistePas);
                            }
                            	
                                    
    					},
    					error: function (XHR, textStatus) {
    					   if(textStatus != "abort")
    						  alert(MsgErreurDeConnexion);
    					}
               		});
    }
    else
    {
        functionOpenPopUpCallBack = '(function () { $("#layerVideoIFrame").scrollTop(0); })();';
        
        // Undisplay telechargement
        undisplayTelechargement();
        
       	// Call to openPopUp function 
       	openPopUp("#layerVideoID", functionOpenPopUpCallBack);
    }
}

function closePopUpVideo() {
	
    jQuery("#layerVideoIFrame").unbind("load");
    
	// Call to closePopUp function 
	closePopUp("#layerVideoID");
	
}
/*============================================================*/
/* Fin - Set des fonctions pour le popup Video                */
/*============================================================*/

/*============================================================*/
/* Set des fonctions pour le popup Content */
/*============================================================*/
function openPopUpContent(HTMLFilePath) {

	// Call to displayBackgroundPopUp to load the grey background
	displayBackgroundPopUp("callBackContent", HTMLFilePath, false, true);
	
}

function callBackContent(HTMLFilePath) {
    
    /*
    jQuery("#layerContentCont").load(HTMLFilePath + " > table", function () {
        
        titre = jQuery("#layerContentCont .TitreRouge").html();
        
        imgSrc = jQuery("#layerContentCont img").attr("src");
        
        if(imgSrc.indexOf("http://") >= 0)
            imgSrc = imgSrc.replace(/^http\:\/\/[\w\.]+\//, "");
        
        pos = HTMLFilePath.lastIndexOf("/");
        directoryPath = HTMLFilePath.substr("0", pos + 1);
        imgSrc = directoryPath + imgSrc;
        
        LayerCont = jQuery("#layerContentCont").html("");
        
        $("<h4>").attr("class", "headingAnnexe").appendTo(LayerCont).html(titre);
        $("<img>").attr("class", "headingImgAnnexe").appendTo(LayerCont).attr("src", imgSrc);
        
        // Undisplay telechargement
        undisplayTelechargement();  
                                
        // Call to openPopUp function 
        

    });
    */

    jQuery("#layerContentIFrame").unbind("load")
                                 .attr("src", "")
                                 .load(function () { 
                                
                                    // Undisplay telechargement
                                    undisplayTelechargement();  
                                
                                    // Call to openPopUp function 
                                    openPopUp("#layerContentID");
                                
                                  })
                                  .attr("src", HTMLFilePath);
    
}

function closePopUpContent() {
    
    jQuery("#layerContentIFrame").unbind("load").attr("src", "");
    
	// Call to closePopUp function 
	closePopUp("#layerContentID");
	
}

/*============================================================*/
/* Fin - Set des fonctions pour le popup Content */
/*============================================================*/

/*============================================================*/
/* Set des fonctions pour le popup PhotoProduit */
/*============================================================*/
function openPopUpPhotoProduit(Parameter) {

	// Call to displayBackgroundPopUp to load the grey background
	displayBackgroundPopUp("callBackPhotoProduit", Parameter, false, true);
	
}

function callBackPhotoProduit(Parameter) {
	
	// load Photo ici
	jQuery("#imgProduit").unbind("load")
						 .attr("src", "")
						 .load(function () {
		
		// Undisplay telechargement
		undisplayTelechargement();
		
		// Call to openPopUp function 
		openPopUp(".layerPhoto");
		
	}).attr("src", Parameter);
	
}

function closePopUpPhotoProduit() {
	
	// Call to closePopUp function 
	closePopUp(".layerPhoto");
	
}
/*============================================================*/
/* Fin - Set des fonctions pour le popup PhotoProduit */
/*============================================================*/

/*============================================================*/
/* Set des fonctions pour le popup AchatRapide */
/*============================================================*/
function openPopUpAchatRapide(productid, URL) {
	
	// Call to displayBackgroundPopUp to load the grey background
	displayBackgroundPopUp("callBackAchatRapide", [productid, URL], false, true);
	
}

function callBackAchatRapide(parameters) {
	
    productid = parameters[0];
    URL = parameters[1];
    
    // Faites le call ajax ici pour recuperer les informations depuis la base de données.
    callBackXHR = jQuery.ajax({
	       			url: URL + "?products_id=" + encodeURI(productid),
					type: 'POST',
					dataType: 'html',
					data: null,
					success: function(data){
                        
                        if(data == "Not Connected")
                        {
                            alert(MsgPasConnecte);
                            // Undisplay telechargement
                       	    undisplayTelechargement();
                            undisplayBackgroundPopUp();
                            return;
                        }
                        
                        if(data)
                        {
                            $(".layerProduit").html("");
                            $(".layerProduit").html(data);
                            
                            if(navigator.userAgent.indexOf("Firefox") >= 0 ||
                               navigator.userAgent.indexOf("Opera") >= 0)
                            {
                                numOfRows = 6; 
                            }
                            else
                            {
                                numOfRows = 5; 
                            }
                            
                            if($(".layerProduit .hoverableAchatRapide tr").size() > numOfRows)
                            {
                                $("#maskScroll").css("visibility", "hidden");
                            }
                            else
                            {
                                $("#maskScroll").css("visibility", "visible");
                            } 
                            
                            // Undisplay telechargement
                       	    undisplayTelechargement();
                        	
                        	// Call to openPopUp function 
                        	openPopUp(".layerProduit");
                        }
                        else
                        {
                            alert(MsgErreurAchatRapidePopUpVide);
                        }
                        	
                                
					},
					error: function (XHR, textStatus) {
					   if(textStatus != "abort")
						  alert(MsgErreurDeConnexion);
					}
           		});
    
}

function closePopUpAchatRapide() {
	
    undisplayInfoBulle();
    
	// Call to closePopUp function 
	closePopUp(".layerProduit");
	
}
/*============================================================*/
/* Fin - Set des fonctions pour le popup AchatRapide */
/*============================================================*/


// L'enchainement des actions pour ouvrir un popup est de suite:
// (1) Display Background noir / grisé (load le iframe) - displayBackgroundPopUp(CallBackFunction)
// (2) Quand le iframe est telechargé, scroll document to top of window
//	   + OpenPopUp Telechargement
//	   + appelle le callbackfunction pour telecharger les informations dynamiques du popup
// (3) Quand les informations du popup sont telechargées par ajax, faites les modifs HTML pour l'affichage du popup
//     + undisplayTelechargement()
//     + openPopUp() 

function undisplayTelechargement() {
	
	// close popup Telechargement
	closePopUp(".layerTelechargement", true);
	
}

function displayBackgroundPopUp(CallBackFunction, ParameterCallBackFunction, TelechargementNotNeeded, ScrollToTopNotNeeded) {
	
	Height = jQuery(document).height();
	
	// for chrome and safari
	loadDone = false;
	
	jQuery("<iframe>").load(function () { 
	
								if(!loadDone)
								{
									loadDone = true;
									
                                    /*
									if(!ScrollToTopNotNeeded) 
										jQuery(document).scrollTop(0);
									else
                                    {
                                        if(jQuery(document).scrollTop() > 150)
                                            jQuery(document).scrollTop(150);
                                    }*/
										
								
									if(!TelechargementNotNeeded) openPopUp(".layerTelechargement");
									if(CallBackFunction) eval(CallBackFunction + "(ParameterCallBackFunction)");
								}
								
					        })
                      .attr("frameborder", "0")
                      .attr("scrolling", "no")
                      .attr("id", "bgd_noir").css({ top: 0, 
												 	left: 0,
												 	width: '100%',
													height: Height,
												 	position: 'absolute',
												 	display: 'block',
                                                 	zIndex: 100,
                                                 	border: 0,
													opacity: 0.29
                                              	  }).appendTo("body")
												  	.attr("src", "background.html");
												  
	
	
}

function undisplayBackgroundPopUp() {
	jQuery("#bgd_noir").remove();
}

function openPopUp(LayerClass, functionCallBack) {

	// Open Popup
	LayerObj = jQuery(LayerClass);
	LayerWidth = LayerObj.width();
	LayerHeight = LayerObj.height();
	windowWidth = jQuery(window).width();
	windowHeight = jQuery(window).height();
	documentWidth = jQuery(document).width();
	documentHeight = jQuery(document).height();
	
	Left = (documentWidth / 2) - (LayerWidth / 2);
	//Top = (documentHeight / 2) - (LayerHeight / 2);
	Top = 170;
	
	LayerObj.css({ display: 'block', top: Top, left: Left });
	
    if(functionCallBack)
    {
        eval(functionCallBack);
    }
    
}

function closePopUp(LayerClass, notRemoveBackground) {
	
	// close popup
	LayerObj = jQuery(LayerClass);
	LayerObj.css({ display: 'none' });
	
	// remove any background iframe
	if(!notRemoveBackground) undisplayBackgroundPopUp();
}

function cancelTelechargement() {
	
	closePopUp(".layerTelechargement");
	
    if(callBackXHR)
        callBackXHR.abort();
        
    if(jQuery("#imgPhotoStretch").attr("id") == "imgPhotoStretch") jQuery("#imgPhotoStretch").unbind("load");
    if(jQuery("#layerVideoIFrame").attr("id") == "layerVideoIFrame") jQuery("#layerVideoIFrame").unbind("load");
    if(jQuery("#layerContentIFrame").attr("id") == "layerContentIFrame") jQuery("#layerContentIFrame").unbind("load");
	if(jQuery("#imgProduit").attr("id") == "imgProduit") jQuery("#imgProduit").unbind("load");
        
    
}

function toggleListeProduit(listype, viewtype)
{
    if(listype == 1)
        URL = 'ajax_get_product_listing_liste.php';
    else
        URL = 'ajax_get_product_listing_recently_viewed.php';
    
    if(jQuery("#mosaiqueView").hasClass("active") && viewtype == 'liste')
    {
            querystr = location.search;
            if(querystr.indexOf("list") >= 0)
            {
                querystr = querystr.replace(/list=[\w\d]*/, "list=0");
            }
            else
            {
                querystr = querystr + "&list=0";
            }
            
            jQuery.ajax({
                  		    url: URL + querystr,
                    		type:'GET',
                    		dataType:'html',
                    		data:  null,
                    		success: function(data){
    
                              jQuery(".thumbnailView").css("display", "none");
                              jQuery(".ListeArticle").html(data).css("display", "block");
                              jQuery("#mosaiqueView").removeClass("active");
                              jQuery("#listeView").addClass("active");
                              
                              $('.pagination > ul > li > a').each(function (i) {
                                
                                href = $(this).attr("href");
                                
                                if(href.indexOf("list=") >= 0)
                                {
                                    href = href.replace(/list=[\w\d]*/, "list=0");
                                    $(this).attr("href", href);
                                }
                                
                              });
                    		}
            	       });

    }
    else if(jQuery("#listeView").hasClass("active") && viewtype == 'mosaique')
    {
            querystr = location.search;
            if(querystr.indexOf("list") >= 0)
            {
                querystr = querystr.replace(/list=[\w\d]*/, "list=1");
            }
            else
            {
                querystr = querystr + "&list=1";
            }
            
            jQuery.ajax({
                  		    url: URL + querystr,
                    		type:'GET',
                    		dataType:'html',
                    		data:  null,
                    		success: function(data){
    
                              jQuery(".ListeArticle").css("display", "none");
                              jQuery(".thumbnailView").html(data).css("display", "block");
                              jQuery("#mosaiqueView").addClass("active");
                              jQuery("#listeView").removeClass("active");
                              
                              $('.pagination > ul > li > a').each(function (i) {
                                
                                href = $(this).attr("href");
                                
                                if(href.indexOf("list=") >= 0)
                                {
                                    href = href.replace(/list=[\w\d]*/, "list=1");
                                    $(this).attr("href", href);
                                }
                                
                              });
                              
                    		}
            	       });
    }
        
}

// *****************************************************************
// Fonctions Utiles
// *****************************************************************
function setCaretPos(Element, pos) {

	if (Element.setSelectionRange) {
      Element.setSelectionRange(pos, pos);
    } else if (Element.createTextRange) {
      var range = Element.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
	
}

function imagesToDownload(imageArray)
{
	for(var i = 1, m = arguments.length; i < m; i++)
	{
		imageArray[i-1] = new Image();
		imageArray[i-1].onload = function () {  };
		imageArray[i-1].src = arguments[i];
	}
}

/**
 * Retourne vrai si c'est une nombre plus qu'un
 */
function isNumber(str)
{
	var regexp1 = /^[1-9]{1}\d*$/;
	var result = new String(str).search(regexp1);
    
	if(str.length == 0 || str == null || result == -1)
		return false;
	else
		return true;	
}

/**
 * Retourne vrai si le texte est vide ou contient juste des blank spaces.
 */
function isEmpty(str)
{
	var regexp1 = /^\s+$/;
	var result = new String(str).search(regexp1);
	if(str.length == 0 || str == null || result != -1)
		return true;
	else
		return false;	
}

// ----------------------------------------------------------------------
// 
// ----------------------------------------------------------------------
