/**
* 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 = 6 ;

var estPremierChoisit=false;

/** #########################################
* 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){
    //Recuperation des ventes complementaires associees aux differents niveaux
    //getVc(urlVcToCheck, langue, sousRayon, referenceProduit, labelDecouvrez, nbFamilleSousRayon, arrayParamFamille) ; //la VC par itool est desactive
    
    var randomIdFamille = 0 ;
    var numPdtCurrent=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 i=0 ; i<arrayParamFamille.length() ; i++){
       var currentFamilleObj = arrayParamFamille.get(i)  ;

       if(currentFamilleObj != ""){
           var currentUrlFamille = currentFamilleObj.getUrl() ;
           numPdtCurrent++;
           //Récupération d'un modèle de cette famille
           getAutreModele(langue, referenceProduit, currentUrlFamille, nbFamilleSousRayon, labelDecouvrez,numPdtCurrent) ;
       }
   }
}

/** #########################################
* 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];
        
        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{    
        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,numPdtCurrent) {
    var urlCeProduit = document.location.href ;
    urlFamille = langue+"/"+urlFamille + "depth.html" ; //Récupération de l'url depth.html
   
    
    var POST_LOAD_CONTENT_DEC_FUNC = function postILoadContentDecouvrir(xhr, httpstatus){        
        if(httpstatus == 200){
            var propertiesDivObjSr = document.getElementById("bloc-vc"); //le div qui va contenir les produits à mettre en avant
             
            
            var responseAjax = xhr.responseText ;
            var isPhotoNonDispo = "false" ;
            var aucunProduitAAffiche = "false" ;
            
            //Le bloc html qui contient tous les produits de la famille actuellement analyse
            var contenuDepthProduit = responseAjax.split('<div class="produits" id="produits" style="display:none;">')[1] ;            
                
            if(contenuDepthProduit){
                var informationsProduit = contenuDepthProduit.split('<div id="blocMiseEnAvant-') ; //on va recuperer le flux html de chaque produit dans un tableau
                var produitPossibleFamille = new Array ; //va contenir les produits possibles de la famille à mettre en avant
                var premierBloc=1;
                
                //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 ;
                    var maxDecouvrer=maxFamille;                   
                     if(maxDecouvrer == 1){
                         maxDecouvrer=informationsProduit.length-1;
                     }
                     if(maxDecouvrer>nbProduitAAfficher){
                        maxDecouvrer=nbProduitAAfficher;
                    }
                    //alert(numPdtCurrent + " " + maxFamille);
                    for(var p=1 ; p<informationsProduit.length ; p++){             
                        
                        
                        var infoProduit = informationsProduit[p].split('</li>')[0] ;

                        var refProduit = informationsProduit[p].split('id="vignetteproduit-')[1].split('">')[0] ;
                        var libelleProduit = infoProduit.split('<div class="produits-titre">')[1].split('">')[1].split("</a>")[0] ; //lien du produit avec le libelle                    
                        var imageProduit = infoProduit.split('<div class="produits-img">')[1].split('src="')[1].split('"')[0] ; //lien du produit avec l'image
                        var urlProduit = infoProduit.split('<a')[1].split('href="')[1].split('"')[0] ; //lien du produit avec l'image
                        
                        var funcVC = setLinkTag(tagProduit+"vc","");
                       
                        premierBloc=1;
                         if(refProduit!=referenceProduit){    
                             if(!estPremierChoisit && maxFamille == 1){
                                 premierBloc=numPdtCurrent;
                                 estPremierChoisit=true;
                             }
                           if(imageProduit != ''){
                                if(imageProduit.indexOf("mh-asset") > 0){                                
                                    isPhotoNonDispo = "false" ;
                                }
                                else if(imageProduit.indexOf("photo-non-dispo") > 0){
                                    isPhotoNonDispo = "true" ;
                                }
                                
                                imageProduit = '<a href="'+urlProduit+'" onclick="'+funcVC+'">'+ '<img src="' + imageProduit + '"/>' +'</a>';
                                libelleProduit = '<a href="'+urlProduit+'" onclick="'+funcVC+'">'+ libelleProduit +'</a>';

                                var display="style='display:none;'";
                                if(numPdtCurrent==premierBloc)display="style='display:block;'";
                                if(isPhotoNonDispo == "false"){
                                    var blocProduit = refProduit + '__' + 
                                    '<div class="boutique-menu-decouvre" id="bloc-decouvrer-'+numPdtCurrent+'"'+display+'>'+
                                        '<div class="boutique-menu-decouvre-left"><a href="javascript:decouvrerPrecedant('+numPdtCurrent+','+maxDecouvrer+');"></a></div>'+
                                        '<div class="boutique-menu-decouvre-titre">'+libelleProduit+'</div>'+
                                        '<div class="boutique-menu-decouvre-right"><a href="javascript:decouvrerSuivant('+numPdtCurrent+','+maxDecouvrer+');"></a></div>'+
                                        '<div class="boutique-menu-decouvre-img">'+imageProduit+'</div>'+
                                       ' </div>';
                                    
                                    produitPossibleFamille[indexProduitPossibleFamille] = blocProduit ;
    
                                    indexProduitPossibleFamille++;
                                }
                            }
                        }
                        if(maxFamille == 1){
                            numPdtCurrent++;
                        }
                    }
                    //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 ; 
                            }
                            
                            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 blocProduit = produitPossibleFamille[randomIdProduct-1] ;
                                        if(blocProduit){
                                            if(blocProduit.indexOf(urlCeProduit) == -1){ //Si le produit scanne est different du produit vue actuellement par l'internaute
                                                var nomModele = blocProduit.split("__")[0] ;
                                                var blocProduitHtml = blocProduit.split("__")[1] ;
                                                modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;
    
                                                nbProduitSelect++;
                                                contenuDecouvrirPlus = contenuDecouvrirPlus + blocProduitHtml ;
                                           }
                                        }
                                    }
                                }
                            }
                            else{ //Si la famille ne contient qu'un seul produit, ne pas afficher de mise en avant
                                contenuDecouvrirPlus = contenuDecouvrirPlus;
                                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 blocProduit = produitPossibleFamille[randomIdProduct-1] ;
                                if(blocProduit){
                                    if(blocProduit.indexOf(urlCeProduit) == -1){ //Si le produit scanne est different du produit vue actuellement par l'internaute
                                        var nomModele = blocProduit.split("__")[0] ;
                                        var blocProduitHtml = blocProduit.split("__")[1] ;
                                        modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;
                                        
                                        contenuDecouvrirPlus = contenuDecouvrirPlus + blocProduitHtml ;
                                    }
                                }
                        }
                        //************** 3- Cas particulier, si le nb de famille est strictement supérieur à 4  
                        else{
                            var randomIdProduct = randomizeProduct(produitPossibleFamille.length) ;
                            if(randomIdProduct){
                                var blocProduit = produitPossibleFamille[randomIdProduct-1] ;
                                if(blocProduit){
                                    if(blocProduit.indexOf(urlCeProduit) == -1){ //Si le produit scanne est different du produit vue actuellement par l'internaute
                                        var nomModele = blocProduit.split("__")[0] ;
                                        var blocProduitHtml = blocProduit.split("__")[1] ;
                                        modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;
                                        
                                        contenuDecouvrirPlus = contenuDecouvrirPlus +  blocProduitHtml 
                                            
                                    }
                                }
                            }
                        }                                    
                    }    
                    
                    //Traitement des id modèle pour supprimer les doublons
                    var arrayModelesADecouvrirTmp = modelesADecouvrir.split(";") ;
                    
                    if(contenuDecouvrirPlus && contenuDecouvrirPlus != ''){
                        if(aucunProduitAAffiche == "false"){
                            theInnerHTML = contenuDecouvrirPlus ;                        
                        }
                        else{
                            theInnerHTML = contenuDecouvrirPlus  ;
                            document.getElementById("bloc-vc").style.display = "none" ;
                        }
                        propertiesDivObjSr.innerHTML = theInnerHTML ;
                        displayProduct(referenceProduit, arrayModelesADecouvrirTmp) ;
                    }
                    else{
                        theInnerHTML = contenuDecouvrirPlus  ;
                        document.getElementById("bloc-vc").style.display = "none" ;
                    }
                }
            }
        }
    }
    
    var ajaxProc = new IAjaxProcess(urlFamille, POST_LOAD_CONTENT_DEC_FUNC) ;
    ajaxProc.run() ;
}


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" ;
                }
            }
        }
    }  
}