/**
* FICHIER JS pour la gestion de la mise en avant des produits
* author : KIG
* version : 1.0
* date : 20070504
* historique :
*    => [KIG] 20070504 : Création
*/

var contenuDecouvrirPlus = "" ; //Le contenu html qui contiendra les produit à découvrir
var contenuScript = "" ;
var nbProduitAAfficher = 6 ;
var nbProduitVraimentAAfficher = 4 ;

/** #########################################
* Permet de récupérer le sous rayon passés à l'url
*/
function getSousRayon() {
    arrayUrl = new Array();
    arrayUrl = parent.document.location.href.split('/');
    //arrayUrl[7] correspond au sous rayon.
    if(arrayUrl[7]){
        return arrayUrl[7] ;
    }
}

/** #########################################
* Permet de récupérer la famille passés à l'url
*/
function getFamilleCourante() {
    arrayUrl = new Array();
    arrayUrl = parent.document.location.href.split('/');
    //arrayUrl[8] correspond à la famille
    if(arrayUrl[8]){
        return arrayUrl[8] ;
    }
}

/** #########################################
* Permet de récupérer la référence du produit
*/
function getIndexProduit() {
    arrayUrl = new Array();
    arrayUrl = parent.document.location.href.split('/');
    //arrayUrl[9] correspond au produit
    if(arrayUrl[9]){
        var productLabel = arrayUrl[9] ;
        productLabel = productLabel.split("_") ;
        if(productLabel[1]){
            return productLabel[1] ;
        }
        else{
            return "0" ;
        }
    }    
}

/** #########################################
* Permet de choisir au hasard une famille
*/
function randomizeFamille(nbTotalFamille){
   var randomNumber = Math.ceil(Math.random()*nbTotalFamille) ;
   return randomNumber ;
}

/** #########################################
* Permet de choisir au hasard un produit
*/           
function randomizeProduct(nbProduit){
   var randomProductId = Math.ceil(Math.random()*nbProduit) ;   
   
   return randomProductId ;               
} 
            
/** #########################################
* Permet de générer la zone "Découvrir plus"
*/                      
function getDecouvrirPlus(langue, sousRayon, referenceProduit, labelDecouvrez, nbFamilleSousRayon, arrayParamFamille, urlRayon, urlFamille, urlProduit){
    var urlVcToCheck = new Array() ;
    urlVcToCheck[0] = urlProduit ;
    urlVcToCheck[1] = urlFamille ;
    urlVcToCheck[2] = urlRayon;
    
    _indexUrlToCheck = 0 ;
    
    //Recuperation des ventes complementaires associees aux differents niveaux
    getVc(urlVcToCheck, langue, sousRayon, referenceProduit, labelDecouvrez, nbFamilleSousRayon, arrayParamFamille) ;
}

/** #########################################
* Permet de setter la VC ou de chercher la VC suivante
*/     
var POST_LOAD_VC_FUNCTION = function postGetVc(xmlHttp, httpStatus){
    //Si une VC repond, on va afficher l'iframe dans la bloc produit concerne 
    if(httpStatus == "200"){
        //Url de la VC qui a repondu
        var urlVc = _urlVcToCheck[_indexUrlToCheck];
        if(xmlHttp.responseText.indexOf('<body id="vc-body"')==-1){
             _indexUrlToCheck++ ;
            getVc(_urlVcToCheck, _langue, _sousRayon, _referenceProduit, _labelDecouvrez, _nbFamilleSousRayon, _arrayParamFamille) ;
        }else{
            var iframeVc = "<iframe id='iframe-vc' src='"+urlVc+"VC.html?refProduit="+_referenceProduit+"' scrolling='no' frameborder='0'></iframe>" ;
            setHtml("bloc-vc", iframeVc) ;
        }
    }
    //Sinon on va chercher la VC au niveau superieur
    else{
        _indexUrlToCheck++ ;
        getVc(_urlVcToCheck, _langue, _sousRayon, _referenceProduit, _labelDecouvrez, _nbFamilleSousRayon, _arrayParamFamille) ;        
    }
}

/** #########################################
* Permet de recuperer les VC
*/     
function getVc(urlVcToCheck, langue, sousRayon, referenceProduit, labelDecouvrez, nbFamilleSousRayon, arrayParamFamille){
    _urlVcToCheck = urlVcToCheck ;
    _langue = langue ;
    _sousRayon = sousRayon ; 
    _referenceProduit = referenceProduit ;
    _labelDecouvrez = labelDecouvrez ;
    _nbFamilleSousRayon = nbFamilleSousRayon ;
    _arrayParamFamille = arrayParamFamille ; 
    
    
    //Pour tous les niveaux (rayon, famille, produit) on va verifier si une VC y est associer
    if(_indexUrlToCheck < _urlVcToCheck.length){
        var urlVc = _urlVcToCheck[_indexUrlToCheck] ;
        
        if(urlVc && urlVc != ""){
             urlVc = urlVc + "VC.html"
            var oProcess = new IAjaxProcess(urlVc, POST_LOAD_VC_FUNCTION);
            oProcess.run();
        }
    }
    //sinon on va recuperer la VC propre au marque
    else{
    
    
        //KIG : 01/09/08 => Desactivation VC Itool
        var randomIdFamille = 0 ;   
    
       //Pour chaque famille, on va récupérer le lien vers le depth.html de la famille
       //pour pouvoir récupérer un produit                  
       for(var m=0 ; m<_arrayParamFamille.length ; m++){
           var currentParamFamille = _arrayParamFamille[m]  ;
    
           if(currentParamFamille != ""){
               var currentUrlFamille = currentParamFamille.split("___")[1] ;
               var nomFamille = currentParamFamille.split("___")[0] ;
               //Récupération d'un modèle de cette famille
               getAutreModele(_langue, _referenceProduit, currentUrlFamille, _nbFamilleSousRayon, _labelDecouvrez) ;
           }
       }
   }
}


/** #########################################
* Permet de récupérer un autre modèle à afficher dans "Découvrez également"
* params :
*    => indexFamille : l'index de la famille à traiter
*    => urlFamille : l'url de la famille à traiter
*    => currentModele : le modèle courant de la page
*    => familleModele : le nom R3 de la famille à traiter
*    => maxFamille : le nombre de famille trouvée
*/
function getAutreModele(langue, referenceProduit, urlFamille, maxFamille, labelDecouvrez) {
    var urlCeProduit = document.location.href ;
    var xhr = getXhr();
    urlFamille = urlFamille + "depth.html" ; //Récupération de l'url depth.html
    
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){                        
            var propertiesDivObjSr = document.getElementById("product-decouvrirplus"); //le div qui va contenir les produits à mettre en avant
            var responseAjax = xhr.responseText ;
            var isPhotoNonDispo = "false" ;
            var aucunProduitAAffiche = "false" ;
            
            var contenuDepthProduit = responseAjax.split('<div id="products">')[1] ;
            if(contenuDepthProduit){
                var informationsProduit = contenuDepthProduit.split(' class="bloc-product"') ;                
                var produitPossibleFamille = new Array ; //va contenir les produits possibles de la famille à mettre en avant
    
                //traitement sur la réponse ajax pour pouvoir récupérer l'url, le nom et l'image des produits possibles à mettre en avant
                if(informationsProduit.length > 1){
                    var indexProduitPossibleFamille = 0 ;
                    for(var p=1 ; p<informationsProduit.length ; p++){
                        var infoProduit = informationsProduit[p].split(' class="bloc-product">')[0] ;
                        
                        var libelleProduit = infoProduit.split('<a id="product')[1] ;                    
                        var imageProduit = infoProduit.split(' src="/products-pictures')[1] ;
                        
                        var hrefCourant = libelleProduit.split(">")[0] ;
                        hrefCourant = '<a id="product'+hrefCourant+'>' ;                                        
                        
                        var hrefCompletCourant = libelleProduit.split("</a>")[0] ;
                        hrefCompletCourant = '<a id="product'+hrefCompletCourant ;
                        
                        var imageProduitCourant = "" ;
                        if(imageProduit != "undefined" && imageProduit){                        
                            imageProduitCourant = imageProduit.split("</a>")[0] ;
                            imageProduitCourant = imageProduitCourant.split("onmouseover")[0] ;
                            imageProduitCourant = imageProduitCourant.split("onmouseout")[0] ;
                        }
                        
                        if(imageProduitCourant != ''){
                            if(imageProduitCourant.indexOf("my-asset") > 0){
                                imageProduitCourant = imageProduitCourant.replace("my-asset","pt-asset") ;
                                isPhotoNonDispo = "false" ;
                            }
                            else if(imageProduitCourant.indexOf("photo-non-dispo") > 0){
                                isPhotoNonDispo = "true" ;
                            }
    
                            if(isPhotoNonDispo == "false"){
                                produitPossibleFamille[indexProduitPossibleFamille] = hrefCourant+'<img class="img-decouvrirPlus" align="absmiddle" src="/products-pictures'+imageProduitCourant+'</a>&nbsp;<div id="lien-decouvrir">'+hrefCompletCourant+"</div>" ;
                                indexProduitPossibleFamille++;
                            }
                        }
                    }
                    
                    //On récupère pour la famille sélectionné, la liste des produits potentiellement affichable
                    //Pour chacun de ces produits on en prend un au hasard et on le met dans la liste final à proposer à l'internaute                       
                    if(produitPossibleFamille){
                        //************** 1- Cas particulier d'une seule famille
                        if(maxFamille == 1){
                            var produitDejaSelect = "" ;
                            var nbProduitSelect = 0 ;
                            var nbProduitToDisplay = nbProduitAAfficher ; //Par défaut, le nb de produit à afficher est de 4
                            if(produitPossibleFamille.length <= nbProduitAAfficher){ //On recalcule donc pour déterminer si il ne faut pas en afficher moins car la famille peut contenir moins de 4 produits
                                nbProduitToDisplay = produitPossibleFamille.length - 1 ; //on enlève un produit qui correspond au produit courant
                            }
                            
                            if(nbProduitToDisplay > 0){ //Si la famille possède au moins un produit, on va afficher au maxi 4 produits à mettre en avant
                                while(nbProduitSelect != nbProduitToDisplay){ //Tant que le nb de produit trouvé est inférieur au nb de produit à afficher on continue de chercher des produits
                                    var randomIdProduct = randomizeProduct(produitPossibleFamille.length) ; //on détermine un produt au hasard dans cette famille mais dont l'index doit être différent du produit courant
                                    if(produitDejaSelect.indexOf(randomIdProduct) == -1){ //Si c ok et que le produit n'a pas encore été choisi, on va former le contenu html et le fichier script pour le js price
                                        produitDejaSelect = produitDejaSelect + ";" + randomIdProduct ;
                                        
                                        var hrefProduit = produitPossibleFamille[randomIdProduct-1] ;
                                        if(hrefProduit){
                                            var urlModele = (hrefProduit.substring(hrefProduit.lastIndexOf("href")+5)).split('"')[1] ;
                                            
                                            if(urlCeProduit.indexOf(urlModele) == -1){
                                                var nomModele = urlModele.split('/')[2] ;
                                                modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;
    
                                                nbProduitSelect++;
                                                contenuDecouvrirPlus = contenuDecouvrirPlus +
                                                    "<li class='image-decouvrirplus' id='"+nomModele+"'>" + 
                                                    hrefProduit +
                                                    "</li>" ;
                                           }
                                        }
                                    }
                                }
                            }
                            else{ //Si la famille ne contient qu'un seul produit, ne pas afficher de mise en avant
                                contenuDecouvrirPlus = contenuDecouvrirPlus +
                                    "<li class='image-decouvrirplus'></li>" ;
                                aucunProduitAAffiche = "true" ;                            
                            }
                        }
                        //************** 2- Cas particulier, si le nb de famille est inférieur ou égal à 4  
                        else if(maxFamille <= nbProduitVraimentAAfficher){                                                         
                            
                                var randomIdProduct = randomizeProduct(produitPossibleFamille.length) ;
                                var hrefProduit = produitPossibleFamille[randomIdProduct-1] ;
                                if(hrefProduit){
                                    var urlModele = (hrefProduit.substring(hrefProduit.lastIndexOf("href")+5)).split('"')[1] ;
                                    
                                    if(urlCeProduit.indexOf(urlModele) == -1){
                                        var nomModele = urlModele.split('/')[2] ;
                                        modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;
                                        
                                        contenuDecouvrirPlus = contenuDecouvrirPlus +
                                            "<li class='image-decouvrirplus' id='"+nomModele+"'>" + 
                                            hrefProduit +
                                            "</li>" ;
                                    }
                                }
                        }
                        //************** 3- Cas particulier, si le nb de famille est strictement supérieur à 4  
                        else{
                            var randomIdProduct = randomizeProduct(produitPossibleFamille.length) ;
                            if(randomIdProduct){
                                var hrefProduit = produitPossibleFamille[randomIdProduct-1] ;
                                if(hrefProduit){
                                    var urlModele = (hrefProduit.substring(hrefProduit.lastIndexOf("href")+5)).split('"')[1] ;
                                    
                                    if(urlCeProduit.indexOf(urlModele) == -1){
                                        var nomModele = urlModele.split('/')[2] ;
                                        modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;
                                        
                                        contenuDecouvrirPlus = contenuDecouvrirPlus +
                                            "<li class='image-decouvrirplus' id='"+nomModele+"'>" + 
                                            hrefProduit +
                                            "</li>" ;
                                    }
                                }
                            }
                        }                                    
                    }    
                    
                    //Traitement des id modèle pour supprimer les doublons
                    var arrayModelesADecouvrirTmp = modelesADecouvrir.split(";") ;
                    
                    if(contenuDecouvrirPlus && contenuDecouvrirPlus != ''){
                        if(aucunProduitAAffiche == "false"){
                            theInnerHTML = "<img src='../images/static/070718-picto-fleche-decouvrir.gif' align='absmiddle' alt='"+labelDecouvrez+"'>&nbsp;<span id='title-decouvrirplus'>"+labelDecouvrez+"</span><ul>" + contenuDecouvrirPlus+"</ul>"  ;                        
                        }
                        else{
                            theInnerHTML = contenuDecouvrirPlus  ;
                            document.getElementById("bloc-decouvrirplus").style.display = "none" ;
                        }
                        propertiesDivObjSr.innerHTML = theInnerHTML ;
                        displayProduct(referenceProduit, arrayModelesADecouvrirTmp) ;
                    }
                    else{
                        theInnerHTML = contenuDecouvrirPlus  ;
                        document.getElementById("bloc-decouvrirplus").style.display = "none" ;
                    }
                }
            }
        }	
    }
    xhr.open("GET", urlFamille, true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send(null);
}


function displayProduct(referenceProduitCourant, arrayModelesADecouvrir){
    var nbProduitTrouve = 0 ;

    //on va vérifier si il ne faut pas cacher le produit
    for(var q=0 ; q<arrayModelesADecouvrir.length ; q++){
        if(arrayModelesADecouvrir[q]){                 
            var modeleCourant = arrayModelesADecouvrir[q] ;

            if(modeleCourant != referenceProduitCourant){
                if(arrayModelesADecouvrir.length >= nbProduitVraimentAAfficher){                    
                    if(nbProduitTrouve < nbProduitVraimentAAfficher && document.getElementById(modeleCourant)){
                        document.getElementById(modeleCourant).style.display = "block" ;
                        nbProduitTrouve++ ;                        
                    }
                    else{
                        if(document.getElementById(modeleCourant)){
                            document.getElementById(modeleCourant).style.display = "none" ;
                        }
                    }
                }
                else{
                    if(document.getElementById(modeleCourant)){
                        document.getElementById(modeleCourant).style.display = "block" ;
                    }                        
                }                
            }
            else{
                if(document.getElementById(modeleCourant)){
                    document.getElementById(modeleCourant).style.display = "none" ;
                }
            }
        }
    }  
}