var imgToResize = new Array();
                                    
/** #########################################
* Permet de redimensionner une image
*/
function redimImage(idImg, inMW, inMH)
{
  // Cette function recoit 3 parametres
  // inImg : Chemin relatif de l'image
  // inMW  : Largeur maximale
  // inMH   : Hauteur maximale
  var maxWidth = inMW;
  var maxHeight = inMH;
  // Récupération de l'élément image
  var oImg = new Image()
  var nImg = document.getElementById(idImg);
  oImg.src = nImg.src;

  // On recupere les tailles reelles
  var h = dH = oImg.height;
  var w = dW = oImg.width;
  // Si la largeur ou la hauteur depasse la taille maximale
  if ((h >= maxHeight) || (w >= maxWidth)) {
    // Si la largeur et la hauteur depasse la taille maximale
    if ((h >= maxHeight) && (w >= maxWidth)) {
      // On cherche la plus grande valeur
      if (h > w) {      
        dW = maxWidth 
        // On recalcule la taille proportionnellement
        dH = parseInt((h * dW) / w, 10);
        dW = parseInt((w * dH) / h, 10);
      } else {
        dH = maxHeight 
        // On recalcule la taille proportionnellement
        dW = parseInt((w * dH) / h, 10);        
        dH = parseInt((h * dW) / w, 10);
      }
    } else if ((h > maxHeight) && (w < maxWidth)) {
      // Si la hauteur depasse la taille maximale
      dH = maxHeight;
        // On recalcule la taille proportionnellement
      dW = parseInt((w * dH) / h, 10);
    } else if ((h < maxHeight) && (w > maxWidth)) {
      // Si la largeur depasse la taille maximale
      dW = maxWidth;
        // On recalcule la taille proportionnellement
      dH = parseInt((h * dW) / w, 10);
    }
  // On mets à jour les dimensions de l'image dans le document    
  nImg.height = dH
  nImg.width = dW
  }
}

/** #########################################
* Permet de redimensionner les images des BU
*/
function resizeAll(listImgToResize, inMW, inMH){    
    if(listImgToResize.length > 0){
        for(i=0;i<listImgToResize.length; i++){
            redimImage(listImgToResize[i], inMW, inMH);
        }
    }    
}


/** #########################################
* Permet d'ouvrir un zoom produit
*/
function ouvrirZoom(imageName){
    window.open(imageName , "", "top=screen.height,left=0,width=420, height=430, location=0, titlebar=0, status=0,menubar=0" );         
}

/** #########################################
* Permet d'initialiser l'image zoom en fonction de l'image principale
*/
function initZoom(idImage, idZoomImage){
    if(document.getElementById(idZoomImage)){
        document.getElementById(idZoomImage).onclick = document.getElementById(idImage).onclick;
    }
}

/** #########################################
* Permet d'ouvrir une popup
*/
function openPopup(url, largeur, hauteur){
    var timestamp = Math.floor((new Date()).getTime() / 1000) ;
    window.open(url, 'nw'+timestamp, 'top=screen.height,left=0,width='+largeur+',height='+hauteur+',menubar=no,toolbar=no, scrollbars=yes,location=no,resizable=yes') ;
}

/** #########################################
* Permet d'ouvrir une popup
* fonction 2
*/
function openPopup2(url){
    largeur=1000;
    hauteur=600;
    var timestamp = Math.floor((new Date()).getTime() / 1000) ;
    window.open(url, 'nw'+timestamp, 'top=screen.height,left=0,width='+largeur+',height='+hauteur+',menubar=no,toolbar=no, scrollbars=yes,location=no,resizable=yes') ;
}

/** #########################################
* Permet de rediriger l'internaute vers la page famille si le produit n'est plus dispo
*/
function redirectProduit(_urlPathFamille){
    if(_urlPathFamille != ""){
        document.location.href = _urlPathFamille + "?nondispo=true" ;        
    }    
}

/** #########################################
* Permet d'ouvrir une vidéo
*/
function openPlayer(urlVideo, width, height){
    if(width == ''){
        width = "800" ;
    }
    if(height == ""){
        height = "600" ;
    }
    var target = "" ;
    if(urlVideo.indexOf(".flv") > -1){
        target = "_blank" ;
    }
    else if(urlVideo.indexOf(".wmv") > -1){
        target = "_top" ;
    }
    else{
        target = "_blank" ;
    }
    
    window.open(urlVideo, target, "width="+width+",height="+height+",location=no,toolbar=no,resizable=yes,menubar=no") ;
}

/** #########################################
* Permet d'ouvrir une vidéo
*/
function openPlayer2(){
    var timestamp = Math.floor((new Date()).getTime() / 1000) ;        
    window.open("infoPlus.html", 'player'+timestamp, "width=800,height=700,location=no,toolbar=no,resizable=yes,menubar=no") ;
}

/** #########################################
* Permet de récupérer le path du rayon
*/
function getPathRayon(genereDecouvrirPlus, rootPath, urlPathFamille, labelAccueil, libelleProduit, refProduit, libelleDecouvrez, multilingualRayon){
    var POST_LOAD_CONTENT_PRODUCT_FUNC = function postILoadContentProduct(xhr, httpstatus){    
        if(httpstatus == 200){
            var oXmlDoc = xhr.responseXML ;
   
             //Objet correspondant au Rayon et traitement de celui-ci
             var rayonObj = new RayonObj() ;
             var rayonTag = oXmlDoc.getElementsByTagName("Rayon")[0] ;
             
             for (i=0; i<rayonTag.childNodes.length; i++){
                if (rayonTag.childNodes[i].nodeName=="title"){
                
                    var name = rayonTag.childNodes[i].firstChild.nodeValue;
                    // tout en minuscules
                    name = name.toLowerCase();
                    // premiere lettre en majuscule
                    if (name.length > 0) {
                        name = name.charAt(0).toUpperCase()+name.substr(1).toLowerCase();
                    }
                    rayonObj.setName(name) ;                
                }
                if (rayonTag.childNodes[i].nodeName=="userTitle"){
                    rayonObj.setName(rayonTag.childNodes[i].firstChild.nodeValue) ;                
                }
                if (rayonTag.childNodes[i].nodeName=="url"){
                    rayonObj.setUrl(rootPath+rayonTag.childNodes[i].firstChild.nodeValue) ;                
                }
                if (rayonTag.childNodes[i].nodeName=="multilingualCategoryName"){
                    rayonObj.setMultiName(rayonTag.childNodes[i].firstChild.nodeValue) ;
                }            
                if (rayonTag.childNodes[i].nodeName=="name_image3"){
                    rayonObj.setNameImage3(rayonTag.childNodes[i].firstChild.nodeValue) ;
                }
                if (rayonTag.childNodes[i].nodeName=="id"){
                    rayonObj.setId(rayonTag.childNodes[i].firstChild.nodeValue) ;                
                }                
            }
            
            //Objet correspondant au Rayon et traitement de celui-ci
            var ssrayonObj = new SSRayonObj() ;
            var sousRayonTag = oXmlDoc.getElementsByTagName("SousRayon")[0] ;
            for (i=0; i<sousRayonTag.childNodes.length; i++){
                if (sousRayonTag.childNodes[i].nodeName=="title"){
                    ssrayonObj.setName(sousRayonTag.childNodes[i].firstChild.nodeValue) ;                
                }
                if (sousRayonTag.childNodes[i].nodeName=="userTitle"){
                    ssrayonObj.setName(sousRayonTag.childNodes[i].firstChild.nodeValue) ;                
                }                
                if (sousRayonTag.childNodes[i].nodeName=="url"){
                    ssrayonObj.setUrl(rootPath+sousRayonTag.childNodes[i].firstChild.nodeValue) ;                
                }
                if (sousRayonTag.childNodes[i].nodeName=="multilingualCategoryName"){
                    ssrayonObj.setMultiName(sousRayonTag.childNodes[i].firstChild.nodeValue) ;                
                }           
            }
               
            if(ssrayonObj && rayonObj)
            {
                //Initialisation du chemin de fer
                initCheminFer(rayonObj, ssrayonObj, familletitle, famillecouranteUrl, libelleProduit) ;
                
                initMenuGauche(rayonObj, famillecouranteUrl, ssrayonObj.getUrl()) ;
                
                initHeaderRayon(rayonObj) ;
                
                initMenuCourant(rayonObj.getId()) ;
            }
            var nbFamille = _mapNbFamilleParSSRayon.get(ssrayonObj.getMultiName()) ; //Nb de famille pour le sous rayon
            var arrayParamFamille = _mapListeFamilleParSSRayon.get(ssrayonObj.getMultiName()) ; //Liste des familles pour le sous rayon
            
            //Si on est dans le cas ou la liste des familles est une liste de selection
            if(typeof _listeFamillesRayonFictif != "undefined"){
                arrayParamFamille = _listeFamillesRayonFictif ;
                nbFamille = arrayParamFamille.length() ;
            }
            if(arrayParamFamille){
                getDecouvrirPlus(rootPath, ssrayonObj.getName(), refProduit, libelleDecouvrez, nbFamille, arrayParamFamille,famillecouranteUrl,rayonObj.getUrl());
            }
        }
    }
    
    var ajaxProc = new IAjaxProcess(urlPathFamille, POST_LOAD_CONTENT_PRODUCT_FUNC) ;
    ajaxProc.run() ;
}


/**
 * Fonction permettant d'initialiser le chemin de fer
 */
function initCheminFer(rayonObj, ssrayonObj, famille, familleUrl, produit){

    var cheminRayonObj = getElement("fa-rayon", true, "") ;
     var cheminSSRayonFamilleObj = getElement("fa-sousrayonfamille", true, "") ;
    var cheminProduitObj = getElement("fa-produit", true, "") ;
    var funcFam =  setLinkTag(tagProduit + tagPath + "family", "");
    var funcRay =  setLinkTag(tagProduit + tagPath + "dpt", "");
    
    if(cheminRayonObj) {
        //Cas de plusieurs rayons
        if(cheminRayonObj.innerHTML == ""){
            cheminRayonObj.href = rayonObj.getUrl();
            cheminRayonObj.innerHTML = rayonObj.getName();
        }
        else {
            cheminRayonObj.innerHTML = '&gt;&nbsp;'+cheminRayonObj.innerHTML ;
        }
    }
     if(cheminSSRayonFamilleObj){
        cheminSSRayonFamilleObj.innerHTML = '&gt;&nbsp;<a href="'+familleUrl+'" onclick="'+funcFam+'">'+ssrayonObj.getName()+' : '+famille+'</a>' ;
    }
    if(cheminProduitObj){
        cheminProduitObj.innerHTML = "&gt;&nbsp;"+produit ;
    }
}


/**
 * Fontion permettant d'initialiser le menu gauche
 */
function initMenuGauche(_rayonObj, _familleCouranteUrl, _ssrayonUrl){
    var menuObj = getElement("menurayon", true, "") ;
    if(menuObj){
        var urlRayonTree = _rayonObj.getUrl() ;

        var iframeMenuGauche = "<iframe id='iframe-menugauche' name='iframe-menugauche' src='"+urlRayonTree+"tree.html?lienFamille=" + _familleCouranteUrl + "&lienSousRayon=" + _ssrayonUrl + "' scrolling='no' frameborder='0' allowtransparency='true'></iframe>" ;
        setHtml("menurayon", iframeMenuGauche) ;
    }
}

/**
 * Fontion permettant d'initialiser le header propre au rayon
 */
function initHeaderRayon(_rayonObj){
    var headerRayon = getElement("header-rayon", true, "") ;
    if(headerRayon){
            headerRayon.style.backgroundImage = "url(/" + _language+"/"+ "images/assets/" +_rayonObj.getNameImage3()+")" ;            
            headerRayon.innerHTML = "<span class=\"hide\">" + _rayonObj.getName() + "</span>";
    }
}


/** #########################################
* Permet de vérifier si le rayon existe bien
*/
function verifRayonPublie(urlRayon){
    var xhr = getXhr();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            return true ;
        }
        else if(xhr.readyState == 4 && xhr.status == 404){
            document.location.href="../index.shtml" ;
            return false ;
        }
    }
    xhr.open("GET", urlRayon, true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send(null);
}


/** #########################################
* Permet de charger l'image principale dans la popup photoplus
*/
function chargeMainPicture(idImage, urlImage){
    var currentPhoto = document.getElementById(idImage).src ;
    
    if(currentPhoto.indexOf(urlImage) == -1){
        document.getElementById(idImage).src = urlImage ;        
    }
}


/** #########################################
* Permet de charger l'image principale dans la popup photoplus ainsi que sa vue HD
*/
function chargeMainPictureHD(idImage, idImageZoomHD, urlImage){
    var currentPhotoObj = document.getElementById(idImage) ;
    if(currentPhotoObj){
        var currentPhoto = currentPhotoObj.style.backgroundImage ;

        //est ce que l'image a change ???
        if(currentPhoto.indexOf(urlImage) == -1){
            //si oui alors on met a jour l'image droite
            currentPhotoObj.style.backgroundImage = "url("+urlImage+")" ;            
            
            //on met ensuite a jour l'image hd via le tableau mapPhotoHd
            var urlImageHd = mapPhotoHd.get(urlImage) ;
            var currentPhotoHdObj = getElement(idImageZoomHD, true, "") ;
            var imageNonDispoObj = getElement("imageNonDispo", true, "") ;
            var blocZoomObj = getElement("bloczoom", true, "") ;
            if(currentPhotoHdObj && imageNonDispoObj && blocZoomObj){
                if(urlImageHd && urlImageHd != ""){          
                    currentPhotoHdObj.style.backgroundImage = "url("+urlImageHd+")" ;
                    hideBloc(imageNonDispoObj) ;
                    displayBloc(blocZoomObj) ;
                }
                else{                
                    hideBloc(blocZoomObj) ;
                    displayBloc(imageNonDispoObj) ;                
                }
            }
        }
    }
}


/** #########################################
* Permet de charger une image directe dans la popup photoplus
* @params :
*    - idImage : l'id du bloc de destination pour l'image SD
*    - idImageZoomHD : l'id du bloc de destination pour l'image HD
*    - isPhotoHD : true/false image HD ou non
*/
function chargeDirectPhoto(idImage, idImageZoomHD, isPhotoHD){
    var params = getParameters() ;
    var currentImageSrc = "" ;
    if(parent && parent.document.getElementById("main-picture")){
        currentImageSrc = parent.document.getElementById("main-picture").src ;
        
        //on va faire un traitement pour eliminer l'url du site
        var currentImageSrcTab = currentImageSrc.split('/') ;
        if(currentImageSrcTab.length == 5){
            currentImageSrc = "/"+currentImageSrcTab[3] + "/" + currentImageSrcTab[4] ;
        }
    }
    
    if(params && params[0][0] && params[0][0].indexOf("urlphoto") > -1){
        if(params[0][1]){
            currentImageSrc = params[0][1] ;
        }
    }
    
    if(currentImageSrc){
        if(isPhotoHD){
            chargeMainPictureHD(idImage, idImageZoomHD, currentImageSrc) ;
        }
        else{
            chargeMainPicture(idImage, currentImageSrc) ;
        }
    }
}


/** #########################################
 * Permet d'afficher les produits precedent et suivant
 * @param :
 *    - _modeleCourant : le modele courant pour lequel il faut recuperer le produit precedent et le produit suivant
*/
function displayPrevNextProduct(_modeleCourant){          

    if(_modeleCourant && typeof _modeleCourant == "string"){
    
        var indexModeleCourant = enableModelList.contains(_modeleCourant) ;

        if(indexModeleCourant != -1){
            //on recupere le modele precedant
            var modelePrev = getPrevProduct(indexModeleCourant, indexModeleCourant-1) ;

            //si le modele precedent existe et que l'index du modele courant n'est pas 0, c'est a dire ce n'est pas le premier modele de la liste
            if(modelePrev != "" && indexModeleCourant > 0){
                var produitPrevObj = getElement("vignetteproduit-"+modelePrev , true, "") ; //alors on recupere le bloc html correspondant au modele precedent
                
                if(produitPrevObj){ //si ce bloc html est ok alors on affiche ce bloc
                    var destBlocHtmlPrev = getElement("blocnavigationinterne-prev", true, "") ;
                    if(!destBlocHtmlPrev){
                        destBlocHtmlPrev = parent.document.getElementById("blocnavigationinterne-prev") ;
                    }
                    
                    if(destBlocHtmlPrev){
                        var libProduitNextObj = getElement("libProduitNext"+modelePrev, true, "") ;
                        if(!libProduitNextObj){
                            libProduitNextObj = parent.document.getElementById("libProduitNext"+modelePrev) ;
                        }
                    
                        hideBloc(libProduitNextObj) ;
                        
                        destBlocHtmlPrev.innerHTML = produitPrevObj.innerHTML ;
                    }                
                }
            }
            
            //on recupere le modele precedant
            var modeleNext = getNextProduct(indexModeleCourant, indexModeleCourant+1) ;
            //si le modele suivant existe et que l'index du modele courant n'est le dernier modele de la liste
            if(modeleNext != "" && indexModeleCourant < modelList.length()){
                var produitNextObj = getElement("vignetteproduit-"+modeleNext , true, "") ; //alors on recupere le bloc html correspondant au modele suivant
                if(produitNextObj){ //si ce bloc html est ok alors on affiche ce bloc
                    var destBlocHtmlNext = getElement("blocnavigationinterne-next", true, "") ;
                    if(!destBlocHtmlNext){
                        destBlocHtmlNext = parent.document.getElementById("blocnavigationinterne-next") ;
                    }
                    
                    if(destBlocHtmlNext){
                        var libProduitPrevObj = getElement("libProduitPrev"+modeleNext, true, "") ;
                        if(!libProduitPrevObj){
                            libProduitPrevObj = parent.document.getElementById("libProduitPrev-next"+modeleNext) ;
                        }
                        
                        hideBloc(libProduitPrevObj) ;
                        
                        destBlocHtmlNext.innerHTML = produitNextObj.innerHTML ;
                    }
                }
            }
        }        
    }
}


/** #########################################
 * Permet de recuperer le produit precedent
 * @param :
 *    - _modeleCourant : le modele courant pour lequel il faut recuperer le produit precedent et le produit suivant
 *    - _indexModelePrev : l'index du modele precedent
*/
function getPrevProduct(_indexModeleCourant, _indexModelePrev){
    //recuperation du modele precedent
    var modelePrev = "" ;
    if(_indexModeleCourant > 0){
        modelePrev = enableModelList.get(_indexModelePrev) ;
    }
    return modelePrev ;
}


/** #########################################
 * Permet de recuperer le produit suivant
 * @param :
 *    - _modeleCourant : le modele courant pour lequel il faut recuperer le produit precedent et le produit suivant
 *    - _indexModeleNext : l'index du modele suivant
*/
function getNextProduct(_indexModeleCourant, _indexModeleNext){
    //recuperation du modele suivant
    var modeleNext = "" ;
    if(_indexModeleCourant < enableModelList.length()){
        modeleNext = enableModelList.get(_indexModeleNext) ;
    }
    return modeleNext ;
}


/** #########################################
 * Permet de changer de famille
 * @param :
 *    - obj : la liste de selection contenant les familles
*/
function changeFamille(obj){
    var url = obj.value ;
    if(url != "" && url != "-1"){
        document.location.href = url ;
    }
}

/** #########################################
 * Permet de calculer la taille du bloc ou se trouve les pictos
 * @param :
 *    - bloc : id du bloc ou se trouve les pictos
*/
function calculeTailleBloc(bloc) {
    document.getElementById(bloc).style.width = document.getElementById(bloc).offsetWidth +10 + 'px';
    document.getElementById(bloc).className = 'float-center';
}
