﻿// Fichier JScript
var miniCartExpanded = false;
var tColorsInventory = new Array();

    //
    //  AFFICHE MINI PANIER EN LAYER
    //
    function DisplayMiniCart(nbItems)
    {
        if(nbItems>0)
        {
            var divMinicart = document.getElementById("divMiniCart");
            if(divMinicart)
                divMinicart.style.visibility = 'visible';
        }
    }
    
    //
    //  MASQUE MINI PANIER
    //    
    function HiddeMiniCart()
    {
        var divMinicart = document.getElementById("divMiniCart");
        if(divMinicart)
            divMinicart.style.visibility = 'hidden';
    }
    
    //
    //  CHANGE LA FONCTION SUR L'EVENEMENT ONCHANGE DE LA LISTE DES CATEGORIES 
    //  POUR EMPECHER LA REDIRECTION SUR LE MINI FORMULAIRE DE RECHERCHE PAR CATEGORIE
    //      
    function DesactiveScriptCat()
    {
        var f = document.getElementById("topsearchform");
        if(f)
        {        
            if(f.CategorySelectList)
            {
                f.CategorySelectList.onchange = ChangeCategoryTopSearch;
            }
        }
    }


    function centreVerticale() {
        var elementCentrageV = new Array("fils2", "fils3");
        for (var i = 0; i < elementCentrageV.length; i++) {
            var parent = document.getElementById(elementCentrageV[i]);
            parent.style.marginTop = "-" + (parent.clientHeight / 2) + "px";
        }
    } 
    
    
    
    function ChangeCategoryTopSearch()
    {
        var f = document.getElementById("topsearchform");
        if(f)
        {   
            f.CategoryID.value=document.getElementById('CategorySelectList')[document.getElementById('CategorySelectList').selectedIndex].value;
        }
    }
    
    //
    // ACCES AUX COOKIES
    //
    function getCookieVal(offset) 
    {
	    var endstr=document.cookie.indexOf (";", offset);
	    if (endstr==-1)
      		endstr=document.cookie.length;
	    return unescape(document.cookie.substring(offset, endstr));
	}

    function getElementsByTagElm(tag, elmt) {

        var tag = tag || "*";
	    var elm = document.getElementById(elmt) || document;
	    var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
	    var returnElements = [];
	    var current;
	    var length = elements.length;
	    for (var i = 0; i < length; i++) {
	        current = elements[i];
	       
	            returnElements.push(current);
	        
	    }
	    return returnElements;
	}


	function getElementsByClassName(className, tag, elm) {
	    var testClass = new RegExp("(^|s)" + className + "(s|$)");
	    var tag = tag || "*";
	    var elm = elm || document;
	    var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
	    var returnElements = [];
	    var current;
	    var length = elements.length;
	    for (var i = 0; i < length; i++) {
	        current = elements[i];
	        if (testClass.test(current.className)) {
	            returnElements.push(current);
	        }
	    }
	    return returnElements;
	}





       function getStyle(el,styleProp)

		{

		var x = document.getElementById(el);

		if (window.getComputedStyle)// Mozilla
		{

		    var y = window.getComputedStyle(x, null).getPropertyValue(styleProp);
		}
		else if (x.currentStyle)// Explorer 6
		{

		    if (styleProp != 'clip') {

		        while (styleProp.indexOf('-') != -1) {// clear '-' and  UpperCase  first next letters : background-color => backgroundColor

		            var letter = styleProp.charAt(styleProp.indexOf('-') + 1);

		            styleProp = styleProp.replace(/-\S{1}/, letter.toUpperCase());

		        }

		        var y = eval('x.currentStyle.' + styleProp);

		    }

		    else {// Return clip style  in mozilla format : rect(top,right,bottom,left)

		        ctop = x.currentStyle.clipTop;

		        cright = x.currentStyle.clipRight;

		        cbottom = x.currentStyle.clipBottom;

		        cleft = x.currentStyle.clipLeft;

		        y = 'rect(' + ctop + ',' + cright + ',' + cbottom + ',' + cleft + ')';

		    }

		}

		return y;

		}






    function hideProd(id,link) {

        var sender = document.getElementById(id);
        var parent = sender.parentNode;
        var button = document.getElementById(link);
        var prods = getElementsByTagElm("tr", "TableOrderForm");
        var buttons = getElementsByClassName("linkhide", "A");
        var i = 0;
        var len = prods.length;
        //var res = document.getElementById(prods[0].id);
//        prods[0].style.display = "none";
//        alert(prods[0].style);

//        var res = "";
//        
//        for (var elt in button.style) {
//            res += elt + " , ";
        //        }
        var listCb = document.getElementsByName('cbStamps');
        while (i<len) {

           

                if (prods[i].style.display != "none") {
                    if (prods[i].className != "") {
                        //alert(listCb.length);
                        prods[i].style.display = "none";
                        var cbox_all = document.getElementById("cbAddToCart_All");
                        if (cbox_all.checked) {
                            cbox_all.checked = false;
                            StampsTable_CheckAll(cbox_all);
                        }
                        
                        
                        
                    
                    button.style.backgroundImage = "url('Skins/Skin_1/images/icons/arrow_down.gif')";
                    }
                }
                else {
                    if (prods[i].className == id) {

                        var trVisible;

                        if (navigator.appName.indexOf("Microsoft") > -1)
                            trVisible = "block"
                        else
                            trVisible = "table-row"

                        prods[i].style.display = "";
                        //prods[i].style.display = "table-row";
                        button.style.backgroundImage = "url('Skins/Skin_1/images/icons/arrow_up.gif')";
                    }
                    else {
                        prods[i].style.display = "none";
                        
                        
                        //button.style.backgroundImage = "url('Skins/Skin_1/images/icons/arrow_down.gif')";
                    }

                }
         //   }
//            else {
//                prods[i].style.display = "none";
//                button.style.backgroundImage = "url('Skins/Skin_1/images/icons/arrow_down.gif')";
//            }
            i = i + 1;
        }
       var j = 0
       var len_ = buttons.length;
       while (j <= len_) {

           if (buttons[j] != null) {
               if (buttons[j].id != link) {
                   buttons[j].style.backgroundImage = "url('Skins/Skin_1/images/icons/arrow_down.gif')";
               }
           }
            j = j + 1;
        }




//        var cbox = document.getElementsByName("cbStamps");
//        var length = cbox.length;
//        var k = 0;
//        while (k <= length) {

//            if (cbox[k] != null) {
//                if (cbox[k].parentNode.parentNode.style.display!="none") {
//                    cbox[k].checked = false;
//                }
//            }
//            k = k + 1;
//        }
        
    }
    
    
    function GetCookie (name) 
    {
	    var arg=name+"=";
	    var alen=arg.length;
	    var clen=document.cookie.length;
	    var i=0;
	    while (i<clen) {
		    var j=i+alen;
		    if (document.cookie.substring(i, j)==arg)
                            return getCookieVal (j);
                    i=document.cookie.indexOf(" ",i)+1;
                            if (i==0) break;}
	    return null;
    }


    //fonction sleep    
    //
    // Ajout au panier et rafraichissement de la frame
    //


	function retarded() {
        RefreshNumItems(false);
        var expandButton = document.getElementById("CartSlidingButton");
        // On force le click sur le bouton pour afficher le contenu du panier
        //alert(expandButton);
        if (expandButton) {
            if (!miniCartExpanded)
            { expandButton.click(); }
        }        
    
    }
	
    //fonction sleep    
    //
    // Ajout au panier et rafraichissement de la frame
    //
	function _AddToCartBestSeller(ProductID, VariantID, quantity) {
        var color = document.getElementById("ColorBestSeller"+VariantID);
		var selected="";
		if (color!=null)
		{
			selected=color.options[color.options.selectedIndex].value;
		}
		//var selectedColorID=color.options[color.options.selectedIndex].value.split(',')[1];
        var oiFrame = document.getElementById('iFrameMiniCart');
		if (document.all)
		{
			oiFrame.onload=function(){retarded()};
		}
		else{
			
			oiFrame.setAttribute('onload','setTimeout("retarded();",1500)');
		}
			setTimeout(";",500);
			if (selected!="")
			{
			oiFrame.src = 'addtocart.aspx?productid=' + ProductID + '&variantid=' + VariantID + '&quantity=' + quantity + '&Color=' + selected + '&ReturnURL=_CartContent.aspx';
			}
			else
			{
				oiFrame.src = 'addtocart.aspx?productid=' + ProductID + '&variantid=' + VariantID + '&quantity=' + quantity + '&ReturnURL=_CartContent.aspx';
			}
        //setTimeout("retarded();", 3000);
    }
	
	
	function _AddToCartLink(ProductID, VariantID, quantity) {
        var color = document.getElementById("Color"+VariantID);
		var selected="";
		if (color!=null)
		{
			selected=color.options[color.options.selectedIndex].value;
		}
		//var selectedColorID=color.options[color.options.selectedIndex].value.split(',')[1];
        var linkCart = document.getElementById("LinkColor"+VariantID);
		if (selected!="")
		{
			linkCart.href=linkCart.href+"&Color="+selected;
		}
		else
		{
			return true;
		}
    }
	
	
    function _AddToCart(ProductID, VariantID, quantity) {
        var color = document.getElementById("Color"+VariantID);
		var selected="";
		if (color!=null)
		{
			selected=color.options[color.options.selectedIndex].value;
		}
		//var selectedColorID=color.options[color.options.selectedIndex].value.split(',')[1];
        var oiFrame = document.getElementById('iFrameMiniCart');
		if (document.all)
		{
			oiFrame.onload=function(){retarded()};
		}
		else{
			
			oiFrame.setAttribute('onload','setTimeout("retarded();",1500)');
		}
			setTimeout(";",500);
			if (selected!="")
			{
				oiFrame.src = 'addtocart.aspx?productid=' + ProductID + '&variantid=' + VariantID + '&quantity=' + quantity + '&Color=' + selected + '&ReturnURL=_CartContent.aspx';
			}
			else
			{
				oiFrame.src = 'addtocart.aspx?productid=' + ProductID + '&variantid=' + VariantID + '&quantity=' + quantity + '&ReturnURL=_CartContent.aspx';
			}
		//setTimeout("retarded();", 3000);
    }
	
	
	
	
	
	/*
    function retarded() {
        RefreshNumItems(false);
        //alert('tototototo');

        //RefreshNumItems(false);
        var expandButton = document.getElementById("CartSlidingButton");

        // On force le click sur le bouton pour afficher le contenu du panier
        //alert(expandButton);
        if (expandButton) {
            if (!miniCartExpanded)
            { expandButton.click(); }
        }

    }

    function _AddToCart(ProductID, VariantID, quantity) {
        var oiFrame = document.getElementById('iFrameMiniCart');
        oiFrame.src = 'addtocart.aspx?productid=' + ProductID + '&variantid=' + VariantID + '&quantity=' + quantity + '&ReturnURL=_CartContent.aspx';
        setTimeout("retarded();", 3000);
    }
*/    
    //
    // Suppression d'un produit du panier (depuis mini panier)
    //

    function remove_asynch() {
        
        RefreshNumItems(true)
       
                    //alert(oiFrame.src);
			//alert("test");
			
            //setTimeout("alert('test')",3000);
      
        
    }
    
    function _RemoveCartItem(ProductID, VariantID) {
        var oiFrame = window.parent.document.getElementById('iFrameMiniCart');
		if (document.all)
		{
			oiFrame.OnUnload=function(){remove_asynch()};
		}
		else {
		    oiFrame.OnUnload = function() { remove_asynch() };
			//oiFrame.setAttribute('onunload','remove_asynch();');
		}
		
		if (oiFrame) {
            var quantity = "-1";
        
            //oiFrame.src = 'addtocart.aspx?productid=' + ProductID + '&variantid=' + VariantID + '&quantity=' + quantity + '&ReturnURL=_CartContent.aspx';
			 //setTimeout("RefreshNumItems(true);",5000);
            oiFrame.src = 'addtocart.aspx?productid=' + ProductID + '&variantid=' + VariantID + '&quantity=' + quantity + '&ReturnURL=_CartContent.aspx';
            //RefreshNumItems(true)
			//alert(oiFrame.src);
        }
    }
    
    //
    // Recupère le VariantID depuis la liste déroulante (Package des timbres)
    //
    function GetVariantIDInList(ProductID)
    {
        
        var VariantID = 0;
        var o = document.getElementById("_Variants_"+ProductID);
        if(o)
        {
            if(o.options.selectedIndex>=0)
                {VariantID = o.options[o.options.selectedIndex].value;}
        }
        return VariantID;
    }
    
    //
    // Redimensionne  l'iframe du mini panier en fct du contenu
    //
    function iFrameHeight()
    {
        var h = 0;
        var maxH = 500;
        if ( !document.all ) {
            h = document.getElementById('iFrameMiniCart').contentDocument.height;
            if(h>maxH)
                {h=maxH;}
            document.getElementById('iFrameMiniCart').style.height = h + 'px';
        } else if( document.all ) {
            h = document.frames('iFrameMiniCart').document.body.scrollHeight;
            if(h>maxH)
                {h=maxH;}
            document.all.iFrameMiniCart.style.height = h + 'px';
        }
        //return false;

    }
    
    //
    // Initialisation Animation du mini panier
    //
    function InitCartAnimation()
    {

        if (typeof RadPanelbarCart == 'object') {

            var panelDomElement = RadPanelbarCart.DomElement;

            if (panelDomElement) {
                document.getElementById("HeaderSlidingDiv").style.visibility = "visible";
                SetUpAnimation(panelDomElement);
            }
        }
        else {
            //alert(document.getElementById("HeaderSlidingDiv").style.visibility);
            document.getElementById("HeaderSlidingDiv").style.display = "none";
        }
    }
    
     //
    // Configuration animation du mini panier
    //
    function SetUpAnimation(panelDomElement)
    {        
        panelDomElement.style.position = "relative";
 
        var config = {ExpandAnimation : {}, CollapseAnimation : {}};
        var listener = {};
     
        var ease = new RadControlsNamespace.Ease(
            panelDomElement,
            config,
            0,
            0,
            listener,
            false
            );


        ease.SetSide("top");
                  
        var slider = document.getElementById("CartSlidingButton");
        var expanded = false;
        var content = document.getElementById("MiniCart");
        var iFrameContent = document.getElementById("iFrameMiniCart");


        slider.onclick = function() {
            var urlIFrame = "_CartContent.aspx";
            panelDomElement.parentNode.style.visibility = "visible";

            if (!expanded) {
                // on recharge la frame contenant le descriptif du panier pour prendre en compte les modif
                iFrameContent.src = urlIFrame;
				setTimeout(';',700);
                RefreshNumItems();
                ease.In();
            }
            else {
                ease.Out();
            }
            expanded = !expanded;

            // On fait le swap de l'image selon l'état de l'animation
            var slider = document.getElementById("CartSlidingButton");
            if (slider) {
                if (expanded)
                { slider.src = slider.src.replace('plus.gif', 'minus.gif'); } ///skins/skin_(!SKINID!)/images/minus.gif';}
                else
                { slider.src = slider.src.replace('minus.gif', 'plus.gif'); } //'/skins/skin_(!SKINID!)/images/plus.gif';}
            }
            miniCartExpanded = expanded;
           
            DisplayHideMiniCartInfosPlus();
            return false;
        } 
        ease.Out();
      }
      
      //
      // Rafraichit le nombre d'éléments dans le panier
      //
      function RefreshNumItems(fromDeleted)
      {
        // On récupère dans la frame le nombre d'item du panier

          var NumCartItems;
          var totalCart;
          var totalCart_;
          totalCart_ = window.parent.document.getElementById("totalCart_");
          var oCart = document.getElementById("MiniCartInfosPlus");
          if (!oCart) {
              oCart = window.parent.document.getElementById("MiniCartInfosPlus");
          }
          
          
        if (fromDeleted) 
        {
            
            NumCartItems = document.getElementById("NumCartItemsFrame");
            if (NumCartItems != null) {
                totalCart = NumCartItems.ownerDocument.getElementById("totalCart");
                //            var totalCart = document.getElementById("totalCart");
                if (totalCart != null) {
                    totalCart_.innerHTML = totalCart.innerHTML;
                }
                else {
                    totalCart_.innerHTML = " ";
                    oCart.innerHTML = "";
                }
            }
            else 
            {
                totalCart_.innerHTML = " ";
                oCart.innerHTML = "";
            }
           
           //alert(totalCart.innerHTML);
        }
        else {
            var f;
            f = document.getElementById('iFrameMiniCart');



            //NumCartItems = f.ownerDocument.getElementById("NumCartItemsFrame");
            if (f) {
                NumCartItems = f.ownerDocument.getElementById("NumCartItemsFrame");
            }
        }

       
        if(NumCartItems)
        {
            var NumCartItemsText;
            var NumCartItemsInt;
            var cartText; 
            if (fromDeleted) {
                NumCartItemsText = window.parent.document.getElementById("NumCartItems");
                NumCartItemsInt = window.parent.document.getElementById("NumCartItemsInt");
                cartText = window.parent.document.getElementById("cartText"); 
            }
            else {
                NumCartItemsText = document.getElementById("NumCartItems");
                NumCartItemsInt = document.getElementById("NumCartItemsInt");
                cartText = document.getElementById("cartText");
            }

            var link = NumCartItemsInt.getElementsByTagName('A')
            var i = 0;
            
//            if(NumCartItemsText)
//            { NumCartItemsText.innerHTML = NumCartItems.innerText; }

            //test
            if (NumCartItemsText) {
                NumCartItemsText.innerHTML = NumCartItems.innerHTML;
                if (parseInt(NumCartItems.innerHTML) > 1) {
                    //alert(cartText.innerHTML);
                    if ((cartText.innerHTML.indexOf("articles")<1)&&((cartText.innerHTML+"s").indexOf("ss")<1))
                       
                       cartText.innerHTML = cartText.innerHTML + "s";
                }
                else {
                    var reg = new RegExp(".*s");
                
                    //alert(cartText.innerHTML.lastIndexOf("s",1));
                    if (cartText.innerHTML.match(reg))
                    {
                        //alert(cartText.innerHTML);
                       // cartText.innerHTML = cartText.innerHTML.substr(0, cartText.innerHTML.length - 1);
                    }
                }
                link[0].innerHTML = link[0].innerHTML.split('(')[0]+" ("+ NumCartItems.innerHTML+")";
            }
        }   
      }
      
      //
      // Affiche ou masque le panneau qui affiche les infos liées au contenu du panier (prochain palier cadeau par ex)
      //
      function DisplayHideMiniCartInfosPlus()
      {
          var o = document.getElementById("MiniCartInfosPlus");
         
        if(o) {
            
            o.style.visibility = (miniCartExpanded && o.innerHTML!='')?'visible':'hidden';
        }
      }
      
      //
      // Ajoute du texte dans le panneau des infos liées au contenu du panier
      //
      function WriteInMiniCartInfosPlus(s)
      {
        var o = document.getElementById("MiniCartInfosPlus");
        if(!o)
            {o = window.parent.document.getElementById("MiniCartInfosPlus");}
            
        if(o)
        {
//            if (o.innerText) {
//                o.innerText = s;
//            }
          
                o.innerHTML = s;
            
            
        }
        //alert(s);
      }
      
      
      //
      // Desactive la checkbox (après un ajout au panier)
      //
      function SwapCheckBox(o, srcImg)
      {
        if(o)
          {o.style.visibility = 'hidden';}
      }

      function AddAllToCartAction_(oBt) {

         
          setTimeout("AddToCartAll(oBT);", 500);
      }

      function AddAllStampsToCartAction(oBt) {
          var listBt = document.getElementsByName('cbStamps');
          var listBoutons = document.getElementsByName('AddToCart');
          for (i = 0; i <= listBt.length; i++) {
              if (listBt[i] != null) 
              {
                  var tr_elt = listBt[i];
				
                  if (tr_elt != null) 
                  {
                      
                      //var cbox = tr_elt.ownerdocument.getElementById("cbAddToCart_All");
                      var ProdId = listBoutons[i].id.split('_')[0];
                      var VariantID = listBoutons[i].id.split('_')[1];

                      if (tr_elt.checked) 
                      {
                          setTimeout(";", 700);
                          _AddToCart(ProdId, VariantID, 1);
                      }
                  }
              }
          }
      }

      function AddAllToCartAction(oBt) {
          var listBt = document.getElementsByName('AddToCart');
          for (i = 0; i <= listBt.length; i++) {
              if (listBt[i] != null) {
                  var tr_elt = listBt[i].parentNode.parentNode;
                  if (tr_elt != null) {
                      if (tr_elt.style.display != "none") {
                          var cbox = document.getElementById(listBt[i].id.split('_')[0] + "_cbStamps");
                          
                          var ProdId = listBt[i].id.split('_')[0];
                          var VariantID = listBt[i].id.split('_')[1];
                          //alert(ProdId + " " + VariantID);
                          if (cbox.checked) {
                              setTimeout(";", 700);
                              _AddToCart(ProdId, VariantID, 1);
                          }
                      }
                  }
              }
          }
          //document.forms[0].submit();   
      }

      function StampsTable_CheckAll_InRegroup(oCb) {
          var listCb = document.getElementsByName('cbStamps');
          for (i = 0; i < listCb.length; i++) {
              var tr_elt = listCb[i].parentNode.parentNode;
              if (tr_elt.style.display != "none") {
                  listCb[i].checked = oCb.checked;
              }
          }
      }
      
      function StampsTable_CheckAll(oCb)
      {
          var listCb = document.getElementsByName('cbStamps');
          for(i=0;i<listCb.length;i++)
          {
            listCb[i].checked = oCb.checked; 
          }
      }
      
      function StampsTable_onCheck(oCb)
      {
        var o = document.getElementByID('cbAddToCart_All');
        
      }
      
    // Ouvre le zoom de l'image dans un radwindow
    function PopupimgRadWindow(url,imgWidth, imgHeight, sName)
    {
        var o=GetRadWindowManager();//document.getElementById("RadWindowManager1_wrapper");;
        var f = o.Windows[0];
        var list = '';
//        for(var elt in f)
//            { list += elt + ', ';}
//          alert(list);
          
        o.Windows[0].Width = imgWidth;       
        o.Windows[0].Height = imgHeight;
       window.radopen('popup.aspx?src='+url+'&title='+sName, "LargerImage");
       return false;
    }
      
    // Ouvre le formulaire d'envoi de fiche produit à un ami dans un radwindow
    function PopupEmailToFriendRadWindow(oHref)
    {
        //alert(oHref.href);
        window.radopen(oHref.href, "EmailToFriend");
        oHref.href = '#';
        return false;
    }
    
    // Convertit la quantité saisie en unité d'achat (m2 par ex) en quantité (nb de bottes par ex)
    function ConvertUnitQtyToQty(o, oName, coeff)
    {
        if(oName)
        {        
            var no = document.getElementsByName(oName); // si on est dans le tableau
            
            if(no.length==0)
                no = document.getElementsByName('Quantity'); // si on est dans la description du produit
            
            if(no[0])
            {
                // Qté saisie en unité
                var i = o.value; 
                coeff = parseFloat(coeff.replace(',','.'));
                // Calcul de la quantité à commander
                if(i>0 && coeff>0)
                {
                    var qty = i/coeff;
                    // On passe à l'entier supérieur si résultat ne tombe pas sur un compte rond
                    if(qty>parseInt(qty))
                        qty = parseInt(qty)+1;       
                    
                    no[0].value = qty;                 
                }
                else
                {
                    if(i>0 && coeff==0)
                    {no[0].value = i; }
                }
            }
        }
    }

//    function GenerateInventoryByColorsArray() {
//        var oList = document.getElementById("Color");
//        if (oList) {
//            for (var i = 0; i < oList.options.length; i++) {
//                
//            }
//        }
//    }


    function RefreshStockState(oList) {
        
        if (tColorsInventory && oList) {
                var o = tColorsInventory[oList.selectedIndex];
                var oDivNo = document.getElementById("divNoStock");
                var oDivOk = document.getElementById("divStockOK");
                //alert(o);
            if (o == 0) {
                if (oDivNo && oDivOk) {
                    oDivNo.style.visibility = 'visible';
                    oDivOk.style.visibility = 'hidden';
                }
            }
            else {
                if (oDivNo && oDivOk) {
                    oDivNo.style.visibility = 'hidden';
                    oDivOk.style.visibility = 'visible';
                }

            }
        }
    }
    
 
    
    
