/**
* FICHIER JS pour la gestion de la mise en avant des produits
* author : KIG
* version : 1.0
* date : 20070504
* historique :
*    => [KIG] 20070504 : Creation
*/

var contenuDecouvrirPlus = "" ; //Le contenu html qui contiendra les produit à decouvrir
var contenuScript = "" ;
var nbProduitAAfficher = 2;
var nbProduitVraimentAAfficher = 2;


/** #########################################
* Permet de recuperer le sous rayon passes à 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 recuperer la famille passes à 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 recuperer la reference 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 generer la zone "Decouvrir plus"
*/                      
function getDecouvrirPlus(langue, sousRayon, referenceProduit, labelDecouvrez, labelEnSavoirPlus, nbFamilleSousRayon, arrayParamFamille,urlFamille,urlRayon){
    //Recuperation des ventes complementaires associees aux differents niveaux
     var urlVcToCheck = new Array();
    urlVcToCheck[0] = document.location.href;
    urlVcToCheck[1] = urlFamille;
    urlVcToCheck[2] = urlRayon;

    // permet de supprimer les eventuels ancres
    if(urlVcToCheck[0].lastIndexOf('/') != -1){ 
        urlVcToCheck[0] = urlVcToCheck[0].substring(0,urlVcToCheck[0].lastIndexOf('/')+1);
    }

    _indexUrlToCheck = 0 ;
    getVc(urlVcToCheck, langue, sousRayon, referenceProduit, labelDecouvrez, labelEnSavoirPlus, nbFamilleSousRayon, arrayParamFamille) ; //la VC par itool est desactive
}

/** #########################################
* 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, _labelEnSavoirPlus, _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, _labelEnSavoirPlus, _nbFamilleSousRayon, _arrayParamFamille) ;        
    }
}

/** #########################################
* Permet de recuperer les VC
*/     
function getVc(urlVcToCheck, langue, sousRayon, referenceProduit, labelDecouvrez, labelEnSavoirPlus, nbFamilleSousRayon, arrayParamFamille){
    _urlVcToCheck = urlVcToCheck ;
    _langue = langue ;
    _sousRayon = sousRayon ; 
    _referenceProduit = referenceProduit ;
    _labelDecouvrez = labelDecouvrez ;
    _labelEnSavoirPlus = labelEnSavoirPlus ;
    _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 ;
        var numPdtCurrent=0;
        //Pour chaque famille, on va recuperer le lien vers le depth.html de la famille
        //pour pouvoir recuperer un produit
        if(arrayParamFamille != ""){
            for(var i=0 ; i<arrayParamFamille.length() ; i++){
                var currentFamilleObj = arrayParamFamille.get(i)  ;
                
                if(currentFamilleObj != ""){
                    var currentUrlFamille = currentFamilleObj.getUrl() ;
                    numPdtCurrent++;
                    //Recuperation d'un modèle de cette famille
                    getAutreModele(langue, referenceProduit, currentUrlFamille, nbFamilleSousRayon, labelDecouvrez, labelEnSavoirPlus, numPdtCurrent) ;
                }
            }
        }
    }
}

/** #########################################
* Permet de recuperer un autre modèle à afficher dans "Decouvrez egalement"
* 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 trouvee
*/
function getAutreModele(langue, referenceProduit, urlFamille, maxFamille, labelDecouvrez, labelEnSavoirPlus, numPdtCurrent) {
    var urlCeProduit = document.location.href ;
    urlFamille = langue+urlFamille + "depth.html" ; //Recuperation 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="zone-produits" id="produits" style="display:none;">')[1] ;         
            
            if(contenuDepthProduit){
                var informationsProduit = contenuDepthProduit.split('id="vignetteproduit') ; //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
                             
                //traitement sur la reponse ajax pour pouvoir recuperer 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;
                    }

                    for(var p=1 ; p<informationsProduit.length ; p++){
                        var infoProduit = informationsProduit[p].split('</li>')[0] ;

                        var refProduit = informationsProduit[p].split('-')[1].split('"')[0] ;
                        var libelleProduit = infoProduit.split('<h2')[1].split('</h2>')[0].split('>')[1];  //lien du produit avec le libelle      
                        var urlProduit = infoProduit.split('<a')[1].split('href="')[1].split('"')[0] ; //lien du produit avec l'image
                        var imageProduit = infoProduit.split('<img')[1].split('src="')[1].split('"')[0]; //lien du produit avec l'image
                        imageProduit=imageProduit.substring(imageProduit.indexOf("<"));

                        if(refProduit!=referenceProduit){
                            if(imageProduit != ''){
                                if(imageProduit.indexOf("mh-asset") > 0){
                                    isPhotoNonDispo = "false" ;
                                }
                                else if(imageProduit.indexOf("photo-non-dispo") > 0){
                                    isPhotoNonDispo = "true" ;
                                }
                                //imageProduit = imageProduit.replace('mh', 'pt');
                                
                                var display="style='display:none;'";
                                if (isPhotoNonDispo == "false") {
                                    //[TAG]Ajout du taggage Google analytics pour le texte
                                    var funcTag = setLinkTag(tagProduit+"vc", "") ;
        
                                    var blocProduit = refProduit + "__" +
                                    "<p class='pack-produit'>" +
                                    "<span class='vignette'>" +
                                    '<a href="'+urlProduit+'" onclick="'+funcTag+'">' +
                                    "<img alt='" + libelleProduit + "' src='" + imageProduit + "'/>" +
                                    "</a>" +
                                    "</span>" +
                                    "<span class='description'>" +
                                    libelleProduit +
                                    "</span></p>" +
                                    "<div class='pack-savoir-plus'><div class='ext'><span class='ext-g'>" +
                                    '<a class="ext-d" href="'+urlProduit+'" onclick="'+funcTag+'">' +
                                    labelEnSavoirPlus +
                                    "</a></span><span class='clear-both' /></div></div>" +
                                    "<span class='clear-both'></span>" +
                                    "<span class='pack-produit-separation'></span>" ;
                                    
                                    produitPossibleFamille[indexProduitPossibleFamille] = blocProduit ;
                                    indexProduitPossibleFamille++;
                                }
                            }
                        }
                    }
                }

                //On recupère pour la famille selectionne, 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 defaut, le nb de produit à afficher est de 4
                        if(produitPossibleFamille.length <= nbProduitAAfficher) { //On recalcule donc pour determiner 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 trouve est inferieur au nb de produit à afficher on continue de chercher des produits
                                var randomIdProduct = randomizeProduct(produitPossibleFamille.length) ; //on determine un produt au hasard dans cette famille mais dont l'index doit être different du produit courant
                                if(produitDejaSelect.indexOf(randomIdProduct) == -1){ //Si c ok et que le produit n'a pas encore ete 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 inferieur ou egal à 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 superieur à 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 (maxFamille < nbProduitVraimentAAfficher || (maxFamille >= nbProduitVraimentAAfficher && arrayModelesADecouvrirTmp.length == nbProduitAAfficher+1)) {
                    if(contenuDecouvrirPlus && contenuDecouvrirPlus != ''){
                        if(aucunProduitAAffiche == "false")
                        {
                            var chaine = "<span class='clear-both'></span><span class='pack-produit-separation'></span>";
                             if(contenuDecouvrirPlus.lastIndexOf(chaine) != -1){ 
                                    contenuDecouvrirPlus = contenuDecouvrirPlus.substring(0,contenuDecouvrirPlus.lastIndexOf(chaine));
                             }
                            contenuDecouvrirPlus = "<div class='bloc-passocies'><p class='titre-bloc'>" + labelDecouvrez + "</p>" + contenuDecouvrirPlus + "</div>";
                            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 verifier 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" ;
                }
            }
        }
    }  
}
