/*
SHOPPING CART Functions list
-------------------------------------
include(src)
getShopStockTest()
addProductToCart(item1,quantity)
getCartID()
getItemID(ProductID, DeliveryType)
paintcommonlines()
//getInfosShoppingCart(cartid)
deleteProduct(itemid)
deletecartitem(itemid)  
repaintline(itemid, qteP)
refreshEmptyPanier()
removeline(itemid)
addProductQuantity(itemid, quantity)
setProductQuantity(itemid, quantity)
refreshCart()
refreshPage(newurl)
changeDelivery(itemid,newdt)
doShowPanier()
doShowPanierVide()
startEffect2()
fermer()
showPopupShoppingCart(libele)
checkQteArtShoppingCart(action, object, eiid, stock)
addProductWithStock(dt,eiid, reflm, stock, quantity, pos)
storeStock(dt,eiid, reflm, stock, quantity, pos)
addShoppingCartProduct(dt,qte)
fcheckQtyShoppingCart(sValue, item, defaultValue)
validFormShoppingCart(CurrentForm)
encrypt(str, pwd)
decrypt(str, pwd)
paintLight()
removeCart()
-------------------------------------
 */


function include(src){ 
    var script=document.createElement('script');
    script.type='text/javascript';
    script.src=src;
    document.getElementsByTagName('head')[0].appendChild(script);
} 

include('/javascript/liste-produit/liste-produit.js');
include('/lmfr-vadlmorder/dwr/engine.js');
include('/lmfr-vadlmorder/dwr/util.js');
include('/lmfr-vadlmorder/dwr/interface/DWRShoppingCart.js');
include('/lmfr-vadlmorder/dwr/interface/DWRLMShoppingCart.js');
include('/lmfr-pickup-productinfo/dwr/interface/DWRProductInfoService.js');

include('/mpng2-front/listcourse-dwr/interface/ListCourseService.js');



// Provide a default path to dwr.engine
if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;

function getShopStock(ref) {
    // DWRContextualizer.getCurrentContext(function(data) {
    var data=getCurrentContext();
    var currentShop = data;
    //alert('2 getShopStock currentShop='+currentShop);
    //alert('3 getShopStock currentShop.save='+currentShop.save);
    //alert('4 getShopStock currentShop.shop='+currentShop.shop);
    // check if contextualized
    if (currentShop && currentShop.save =='true') {
        //alert('5 currentShop.shop='+currentShop.shop);
        var shopid = currentShop.shop;
        //shopid = 11; //shop ID for test
        //ref ='62637260'; //ref for test
            
        DWRProductInfoService.getProductDetails(ref,shopid, {
            callback:function(data2) {
                obj = data2;
                //alert('6 data2=> '+data2);
                var obj=data2;
                var stock = obj.stockEntity;
            // alert('7 stock=> '+stock);
            },
            timeout:5000,
            errorHandler:function(data2) {  //alert('getShopStock getProductDetails error=> '+data2);
            },
            exceptionHandler:function(data2) {
            //  alert('getShopStock getProductDetails exception=> '+data2);
            }
        });
            
    }
    else{
//alert('8 getShopStock false');
}
//  });
}

var reply0 = function(data) {
    //alert('data='+data);  
    if (data != null && typeof data == 'object') alert('stock='+data.stockEntity);
    else alert('data null'); 
}



function getShopStockTest(){
    var ref = "62637260";
    var shopid = 11;
    DWRProductInfoService.getProductDetails(ref,shopid, {
        callback:function(msg) { 
            obj = msg;
            //alert('SUCCES  ref ='+ ref +'  shopid'+shopid+'  obj=> '+obj);
            //alert('SUCCES  ref ='+ ref +'  shopid'+shopid+'  obj.stockEntity=> '+obj.stockEntity);
            var stock = obj.stockEntity;
        //alert('stock=> '+stock);
        },			
        timeout:5000, 
        errorHandler:function(msg) { // alert('getShopStockTest getProductDetails error=> '+msg); 
        },
        exceptionHandler:function(msg) { //alert('getShopStockTest getProductDetails exception=> '+msg); 
        } 		
    });
}

var showstockrem = false;
var launchstockrem = false;
var nbremcheck = 0;

function getShopStock2(ref,shopid,total){
    //test si le service est accessible
    if(typeof(DWRProductInfoService)=='undefined'){
        alert("le service d'interrogation du stock magasin est hors ligne, veuillez r\u00e9essayer dans quelques minutes.");
    }else{
        DWRProductInfoService.getProductDetails(ref[0],shopid, {
            callback:function(msg) {
                obj = msg;
                //alert('SUCCES  ref ='+ ref +'  shopid'+shopid+'  obj=> '+obj);
                // alert('SUCCES  ref ='+ ref +'  shopid'+shopid+'  obj.stockEntity=> '+obj.stockEntity);
                var qte = document.getElementById('qte_'+ref[1]).value;
            
                nbremcheck = nbremcheck +1;
                //alert(ref[0]+" | "+ qte +" | "+obj.stockEntity + " check="+nbremcheck+"/"+total);
                if( parseInt(qte) > obj.stockEntity ){
                    showstockrem =true;
                }
                if(showstockrem && !launchstockrem){
                    launchstockrem = true;
                    if(document.location && document.location.protocol)
                    {
                        protocole = 'http'+((document.location.protocol=='https:')?'s':'')+':';
                    }
                    else
                    {
                        protocole = 'http:';
                    }

                    if (protocole == 'https:')
                    {
                        popup('pre?zone=zoneimpressioncommande&todo=showstockrem','','630','650','yes');
                    }
                    else
                    {
                        popup('pre?zone=zonetest2print&todo=showstockrem','','630','650','yes');
                    }
                }
                if(nbremcheck==total && !showstockrem){
                    //cas : no product with qty > stock
                    //todo next step without popup showstockrem
                    //alert('showstockrem : no product with qty > stock');
                    document.formpanier.submit();
                }
            
            },
            timeout:5000,
            errorHandler:function(msg) {  //alert('getShopStockTest getProductDetails error=> '+msg);
            },
            exceptionHandler:function(msg) { //alert('getShopStockTest getProductDetails exception=> '+msg);
            }
        });
    }
}

function checkAllStocks(){

    showstockrem = false;
    launchstockrem = false;
    nbremcheck = 0;
    //DWRContextualizer.getCurrentContext(function(data) {
    var data=getCurrentContext();
    var currentShop = data;
    if (currentShop && currentShop.save =='true') {
        var shopid = currentShop.shop;
        //shopid = '11';
        if( aproductremref.length > 0){
            for (i=0; i<aproductremref.length; i++) {
                getShopStock2(aproductremref[i],shopid,aproductremref.length);
            }
        }else{
            //alert('showstockrem : not rem products');
            document.formpanier.submit();
        }
    }else{
        //cas : non contextualise
        //alert('showstockrem : not contextualized');
        document.formpanier.submit();
    }
//  });
}


// Add a product in cart
//item1 : object with elements of products 
//quantity : to put in cart
function addProductToCart(item1,quantity){
    
    
    //alert('1 addProductToCart : item1='+item1); 
    //alert('1 addProductToCart : item1.DeliveryType='+item1.DeliveryType); 
    //alert('1 addProductToCart : item1.ProductID='+item1.ProductID); 
    
    var result = getItemID(item1.ProductID, item1.DeliveryType);
    //alert("2 addProductToCart result : ["+result+"]");
    
    var tabresult = result.split(':');
    var cartId = tabresult[0];
    var itemId = tabresult[1];
    //alert ('itemId='+itemId+'  cartId='+cartId);
    
    if(itemId == 'null'){
        //alert("3 addProductToCart null");
        //first case : new product in cart
        DWRShoppingCart.addItem(cartId,item1,quantity, {
            callback:function(msg) { 
                itemId = msg;
                refreshLightBasket(); 
                //alert('success itemId=> '+itemId);
                if(document.getElementById("typeMQS") && document.getElementById("typeMQS").value == 'deco') {
                    showProductDeco(item1.ProductID,'panier');
                }
                else {
                    showPopupShoppingCart('panier',item1.ProductID);
                }
                
                
                
            },			
            timeout:5000, 
            errorHandler:function(msg) {  //alert('addProduct addItem error=> '+msg); 
            },
            exceptionHandler:function(msg) { //alert('addProduct addItem exception=> '+msg); 
            } 		
        });
    }else{
        //alert("4 addProductToCart not null");
        //second case : update cart quantity
        DWRShoppingCart.addItemQuantity(itemId,quantity, {
            callback:function(msg) { 
                //alert('success itemId=> '+itemId);
                refreshLightBasket(); 
                if(document.getElementById("typeMQS") && document.getElementById("typeMQS").value == 'deco') {
                    showProductDeco(item1.ProductID,'panier');
                }
                else {
                    
                    showPopupShoppingCart('panier',item1.ProductID);
                }
                
            },			
            timeout:5000, 
            errorHandler:function(msg) {  //alert('addProduct addItemQuantity error=> '+msg); 
            },
            exceptionHandler:function(msg) { //alert('addProduct addItemQuantity exception=> '+msg); 
            } 		
        });
        
    }
    
}


var globalcartID= null;
//Get ID of cart by XMLHttpRequest groovy 
function getCartID(){
    var cartID = null;
    var protocole;
    var carturl;
    if(document.location && document.location.protocol)
    {
        protocole = 'http'+((document.location.protocol=='https:')?'s':'')+':';
    }
    else
    {
        protocole = 'http:';
    }
	
    if (protocole == 'https:')
    {
        carturl = "pre?zone=zoneimpressioncommande&todo=getcartid";
    }
    else
    {
        carturl = "pre?zone=zonetest2print&todo=getcartid";
    }

	
    var xhr=null;
    
    try {
        xhr = new XMLHttpRequest(); 
    } catch(e) { 
        try { 
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e2) { 
            try { 
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {//alert('ERREUR');
            }
        }
    }
    xhr.open('GET', carturl , false); 
    xhr.send(null); 
    if(xhr.readyState == 4){
        var cartid = xhr.responseText;
        globalcartID = cartid;
        return globalcartID;
    }
}


//Get ID of item in cart by XMLHttpRequest groovy 
function getItemID(ProductID, DeliveryType){
    var cartID = null;
    //var carturl="pre?zone=zonetest2print&todo=getitemid&itemid="+ProductID+"&mode="+DeliveryType;
    var carturl;
    if(document.location && document.location.protocol)
    {
        protocole = 'http'+((document.location.protocol=='https:')?'s':'')+':';
    }
    else
    {
        protocole = 'http:';
    }

    if (protocole == 'https:')
    {
        carturl = "pre?zone=zoneimpressioncommande&todo=getitemid&itemid="+ProductID+"&mode="+DeliveryType;
    }
    else
    {
        carturl = "pre?zone=zonetest2print&todo=getitemid&itemid="+ProductID+"&mode="+DeliveryType;
    }

    var xhr=null;
    
    try {
        xhr = new XMLHttpRequest(); 
    } catch(e) { 
        try { 
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e2) { 
            try { 
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {}
        }
    }
    
    xhr.open('GET', carturl , false); 
    xhr.send(null); 
    if(xhr.readyState == 4){
        var itemid = xhr.responseText;
        return itemid;
    }
}


//display total values
function paintcommonlines(){
    //get all values by DWR
    var cartmgtid = document.getElementById('cartmgtid').innerHTML;
    var ALL = 'ALL';
    clearCookie();
    //DBG : PR 20091026
    var jsessionid = getCookie('JSESSIONID');

    // alert(cartmgtid+' , '+ALL);
    DWRLMShoppingCart.getShoppingCartInfo(cartmgtid,ALL, {
        callback:function(msg) { 
            tabInfos = msg;
            document.getElementById('total').innerHTML = (tabInfos.productSumWithTaxes).toFixed(2);
            document.getElementById('fraislivraison1').innerHTML = (tabInfos.deliveryCostWithTaxes).toFixed(2);
            document.getElementById('fraislivraison2').innerHTML = (tabInfos.deliveryCostWithTaxes).toFixed(2);
            document.getElementById('ttclivraison').innerHTML = (tabInfos.totalGlobal).toFixed(2);
            document.getElementById('ecotax').innerHTML = (tabInfos.ecoTaxSum).toFixed(2);
            var total = tabInfos.totalGlobal;
            var nombrearticles = tabInfos.cartItemCount;
	    //DBG : PR 20091026 : ajout de jsessionid au cookie
            var cookieval= ''+cartmgtid +'|'+ nombrearticles+'|'+ encrypt(total,"password")+'|'+jsessionid;
            //alert("paintcommonlines cookieval"+cookieval);
            //setCookie('cartmgt',cookieval);                
            refreshLightBasket(); 
        },			
        timeout:5000, 
        errorHandler:function(msg) {  //alert('getShoppingCartInfo error=> '+msg); 
        },
        exceptionHandler:function(msg) { //alert('getShoppingCartInfo exception=> '+msg); 
        } 		
    });
    
    
    
}





//launch DWR delete item function
function deleteProduct(itemid){
    DWRShoppingCart.deleteItem(itemid, {
        callback:function(msg) { 
            //alert('success DWR deleteItem');
            paintcommonlines();   
        },			
        timeout:5000, 
        errorHandler:function(msg) {  //alert('deleteItem error=> '+msg); 
        },
        exceptionHandler:function(msg) { //alert('deleteItem exception=> '+msg); 
        } 		
    });
}

//display confirm message before delete
function deletecartitem(itemid) { 
    if(confirm("Souhaitez-vous supprimer cet article de votre commande ?")) {
        removeline(itemid); 
        deleteProduct(itemid);
    }
}



//compute and display values for a product (qte and total)
function repaintline(itemid, qteP){
    document.formpanier.elements['qte_'+itemid].value = qteP;
    document.formpanier.elements['qteold_'+itemid].value = qteP;
    document.getElementById('total_'+itemid).innerHTML = 
    (qteP * document.formpanier.elements['price_'+itemid].value).toFixed(2) ;
//paintcommonlines();		
}


function refreshEmptyPanier(){
    var bocretraitvide = false;        
    var bocvadvide = false;        
    if(document.getElementById('blocSrc')){
        if( document.getElementById('blocSrc').childElements().size() ==1 &&
            document.getElementById('blocSrc').childElements()[0].id == 'noArticle'){
            bocretraitvide = true;
        }
    }else{
        bocretraitvide = true;
    }
    
    if( document.getElementById('blocDest').childElements().size() ==1 &&
        document.getElementById('blocDest').childElements()[0].id == 'noArticle'){
        bocvadvide = true;
    }
    
    if( bocvadvide && bocretraitvide ){
        doShowPanierVide();
    }   
}


function removeline(itemid){
    
    element = document.getElementById('test_'+itemid)
    new Effect.Fade(element, {
        duration: 1,
        afterFinish:
        function() {
            element.remove();
            if(document.getElementById('blocSrc')){ //for not contextualise case
                blocRetrait = document.getElementById('blocSrc');
                blocRetrait.childElements().size()
                if( blocRetrait.childElements().size() == 0) {
                    blocRetrait.update('<div id="noArticle" class="aucun_article">Aucun article</div>');
                }
            }
            
            blocVAD = document.getElementById('blocDest');
            if( blocVAD.childElements().size() == 0) {
                blocVAD.update('<div id="noArticle" class="aucun_article">Aucun article</div>');
            }
            refreshEmptyPanier();
        }.bind(this)
    });
//paintcommonlines();		
}



function addProductQuantity(itemid, quantity){
    DWRShoppingCart.addItemQuantity(itemid,quantity, {
        callback:function(msg) { 
            //refreshCart();
            //alert('success DWR addProductQuantity');
            paintcommonlines();
        },			
        timeout:5000, 
        errorHandler:function(msg) {  //alert('addProductQuantity error=> '+msg); 
        },
        exceptionHandler:function(msg) { //alert('addProductQuantity exception=> '+msg); 
        } 		
    });
}


function setProductQuantity(itemid, quantity){
    DWRShoppingCart.getItem(itemid, {
        callback:function(msg) {
            var item = msg;
            var qte = item.quantity;
            var qtetoset = quantity - qte; 
            
            DWRShoppingCart.addItemQuantity(itemid,qtetoset, {
                callback:function(msg) { 
                    //alert('success DWR setProductQuantity');
                    paintcommonlines();
                },			
                timeout:5000, 
                errorHandler:function(msg) {  //alert('setProductQuantity error=> '+msg); 
                },
                exceptionHandler:function(msg) { //alert('setProductQuantity exception=> '+msg); 
                } 		
            });
        },	
        timeout:5000,
        errorHandler:function(msg) { //alert('setProductQuantity error=> '+msg); 
        }	
    });
}


function setProductQuantity2(itemid, quantity){
    DWRShoppingCart.getItem(itemid, {
        callback:function(msg) {
            var item = msg;
            var qte = item.quantity;
            var qtetoset = quantity - qte; 
            var reflm = item.allItemProperties.RefProduct;
            //alert('setProductQuantity2  1. reflm='+reflm +'  qtetoset='+qtetoset+'  qte='+qte +'  Stock='+item.allItemProperties.Stock);
            
            DWRShoppingCart.addItemQuantity(itemid,qtetoset, {
                callback:function(msg) { 
                    
                    paintcommonlines();
                    
                    //DWRContextualizer.getCurrentContext(function(data) {
                    var data=getCurrentContext();
                    var currentShop = data;
                    if (currentShop && currentShop.save =='true') {
                        var shopid = currentShop.shop;
                            
                        //shopid = 11; //shop ID for test
                        //reflm ='62637260'; //ref for test
                        DWRProductInfoService.getProductDetails(reflm,shopid, {
                            callback:function(data2) {
                                    
                                var obj=data2;
                                var stock = obj.stockEntity;
                                //alert('setProductQuantity2  3. stock from DWR='+stock);
                                    
                                if( stock != item.allItemProperties.Stock ){
                                    //set stock and quantity
                                    var product  = item.allItemProperties;
                                        
                                    product.Stock = stock;
                                    //alert('setProductQuantity2  4. Stock='+product.Stock +'  reflm='+product.RefProduct );
                                        
                                        
                                    DWRShoppingCart.updateItem(itemid,product, {
                                        callback:function(msg) {
                                            //alert('success DWR updateItem');
                                            paintcommonlines();
                                        },
                                        timeout:5000,
                                        errorHandler:function(msg) { // alert('updateItem error=> '+msg);
                                        },
                                        exceptionHandler:function(msg) { //alert('updateItem exception=> '+msg);
                                        }
                                    });
                                }
                                    
                            },//callback
                            timeout:5000,
                            errorHandler:function(data2) {  //alert('getProductDetails error=> '+data2);
                            },
                            exceptionHandler:function(data2) {
                            //nothing to do
                            //alert('getProductDetails exception=> '+data2);
                            }
                                
                        });//DWRProductInfoService.getProductDetails
                            
                    }
                        
                //    });//DWRContextualizer.getCurrentContext
                    
                },			
                timeout:5000, 
                errorHandler:function(msg) { // alert('setProductQuantity error=> '+msg); 
                },
                exceptionHandler:function(msg) { //alert('setProductQuantity exception=> '+msg); 
                } 		
            });//DWRShoppingCart.addItemQuantity
            
            
        },	
        timeout:5000,
        errorHandler:function(msg) { //alert('setProductQuantity error=> '+msg); 
        }	
    });//DWRShoppingCart.getItem
}



function refreshCart(){
    //var refreshurl="pre?zone=zonetest2print&todo=refresh";
    var refreshurl;
    if(document.location && document.location.protocol)
    {
        protocole = 'http'+((document.location.protocol=='https:')?'s':'')+':';
    }
    else
    {
        protocole = 'http:';
    }

    if (protocole == 'https:')
    {
        refreshurl = "pre?zone=zoneimpressioncommande&todo=refresh";
    }
    else
    {
        refreshurl = "pre?zone=zonetest2print&todo=refresh";
    }
    refreshPage(refreshurl);
}

function refreshPage(newurl){
    var xhr=null;
    
    try {
        xhr = new XMLHttpRequest(); 
    } catch(e) { 
        //alert("Msxml2.XMLHTTP");
        try { 
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e2) { 
            try {
                alert("Microsoft.XMLHTTP");
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {}
        }
    }
    
    xhr.onreadystatechange = function() { 
        if(xhr.readyState == 4) {
            if(xhr.status == 200) { 
                
                var el = document.getElementById("maindiv");
                var htmlFrag = xhr.responseText;
                var browser=navigator.appName;
                var b_version=navigator.appVersion;
                var version=parseFloat(b_version);
                if (browser=="Netscape"){
                    el.innerHTML =""; 
                    window.location.reload();
                }
                else{                        
                    el.innerHTML =""; 
                    window.location.reload();
                //el.innerHTML = htmlFrag;
                //initDHTML();
                //executeJS();
                }
            } 
            else { 
        //alert("Error: returned status code " + xhr.status + " " + xhr.statusText);
        }
        } 
    }; 
    
    
    xhr.open('POST', newurl , true); 
    xhr.send(null); 
    
}
function dynamiccontentNS6(elementid,content){
    if (document.getElementById && !document.all){
        rng = document.createRange();
        el = document.getElementById(elementid);
        rng.setStartBefore(el);
        htmlFrag = rng.createContextualFragment(content);
        while (el.hasChildNodes())
            el.removeChild(el.lastChild);
        el.appendChild(htmlFrag);
    }
}


function changeDelivery(itemid,newdt){
    //use ajax refresh page
    //var urlrefresh ="pre?zone=zonetest2print&todo=refresh&todocart=changedelivery&itemid="+itemid+"&mode="+newdt;
    var urlrefresh;
    if(document.location && document.location.protocol)
    {
        protocole = 'http'+((document.location.protocol=='https:')?'s':'')+':';
    }
    else
    {
        protocole = 'http:';
    }

    if (protocole == 'https:')
    {
        urlrefresh = "pre?zone=zoneimpressioncommande&todo=refresh&todocart=changedelivery&itemid="+itemid+"&mode="+newdt;
    }
    else
    {
        urlrefresh = "pre?zone=zonetest2print&todo=refresh&todocart=changedelivery&itemid="+itemid+"&mode="+newdt;
    }
    refreshPage(urlrefresh);
    refreshLightBasket();
    
}


function doShowPanier() {
    obj = document.getElementById('validation-commande');
    obj.style.display = 'block';
    vide = document.getElementById('paniervide');
    vide.style.display = 'none';
}

function doShowPanierVide() {
    obj = document.getElementById('validation-commande');
    obj.style.display = 'none';
    vide = document.getElementById('paniervide');
    vide.style.display = 'block';
}


function startEffect2() {
    
    startTop   = $('masque').offsetTop;
    startLeft  = $('masque').offsetLeft; 
    $('masque').style.bgColor = '#000000';
    $('masque').style.opacity = 0.10;
    $('masque').style.visibility = "visible";	    
    new Rico.Effect.FadeTo( 'masque', 0.4, 10, 4 );
    document.getElementById('masque').style.zIndex = 1;
    
}


var _xlayer = 350; // position du bord gauche du layer relativement a la page
var _ylayer = 300; // position du bord haut du layer relativement a la page

// VARIABLES GLOBALES
var nn4 = (document.layers);
var dom = (document.getElementById);
var iex = (document.all);
var obj_layer = null;
var cache = true;

// creation de l'objet obj_layer en fonction du navigateur :
// affecte le layer et lui donne son emplacement vertical
/*function init_layer() {
    if (dom && (document.getElementById(_id_layer))) {
        obj_layer = document.getElementById(_id_layer).style;
        X = iex ?  "event.clientX": "e.clientX";
        Y = iex ?  "event.clientY" : "e.clientY";
        offsetX = (iex) ? "document.body.scrollLeft" : "pageXOffset";
        offsetY = (iex) ? "document.body.scrollTop" : "pageYOffset";
    }
    else if (iex && (_id_layer)) {
        obj_layer = _id_layer.style;
        X="event.clientX";
        Y="event.clientY";
        offsetX="document.body.scrollLeft";
        offsetY="document.body.scrollTop";
    }
    else if (nn4 && (document.layers[_id_layer])) {
        obj_layer = document.layers[_id_layer];
        X="e.pageX";
        Y="e.pageY";
        offsetX="pageXOffset";
        offsetY="pageYOffset";
        document.captureEvents(Event.MOUSEDOWN|Event.MOUSEMOVE|Event.MOUSEUP);
    }
    if (obj_layer) {
        
        obj_layer.left = _xlayer;
        obj_layer.top = _ylayer;
    }
}*/

function resetEffect2() {
    document.getElementById('masque').style.zIndex = -1;
    document.getElementById('masque').style.visibility = "hidden";	
}


function fermer() {
    if (!cache) {
        resetEffect2();
        obj_layer.innerHTML = '';
        obj_layer.visibility = "hidden";
        cache = true;
    }
}

function showPopupShoppingCart(libele,productid) {
    _id_layer = "popup";    
    init_layer_popup();
	
    if (obj_layer_popup) {
        cache_popup = false;

        startEffect2('masque');
        var ch_texte = '<div id="contentPopup" class="pop" >';

        if(libele=='panier'){
            if(document.getElementById('ap-'+productid)){
            //alert(document.getElementById('ap-'+productid).value);
            }
            else{
                ch_texte += '<h1 class="produits">L\'article a bien &eacute;t&eacute; ajout&eacute; au panier</h1><br>';
                ch_texte += '<div id="targetarea" class="arial_12_000000" style="margin-top: 5px; margin-bottom: 10px;">&nbsp;</div>';
                ch_texte += '<a href="pre?zone=zoneprocessachat&todo=show&pageid=111"><img src="/images/fiche-produit/accederAupanierVert.gif" border="0"></a><br>';
                ch_texte += '<a href="javascript:fermerpopup();"><img src="/images/fiche-produit/btnPoursuivreAchatsVert.gif" border="0"></a></div>';
            }
        }

        if(libele=='liste'){
            ch_texte += '<h1 class="produits">L\'article a bien &eacute;t&eacute; ajout&eacute; a ma liste</h1><br>';
            ch_texte += '<div id="targetarea" class="arial_12_000000" style="margin-top: 5px; margin-bottom: 10px;">&nbsp;</div>';
            ch_texte += '<a href="pre?zone=zoneprocessachat&todo=showlist&pageid=17"><img src="/images/fiche-produit/accederAmalisteVert.gif" border="0"></a><br>';
            ch_texte += '<a href="javascript:fermerpopup();"><img src="/images/fiche-produit/btnPoursuivreAchatsVert.gif" border="0"></a></div>';

        }

        contenu_layer_popup(ch_texte);
    //refreshLightBasket();
    }

}


function checkQteArtShoppingCart(action, object, eiid, stock, reflm){
    
    //alert('action='+action+'  object='+object+'  eiid='+eiid +'  stock='+stock);
    
    qte = parseInt(document.calcultotal['nop-0'].value);
    
    if (isNaN(qte)){
        alert("La valeur saisie est incorrecte");
        document.calcultotal['nop-0'].value = 1;			
        calcul();		
    }else if (qte < 0){
        alert("Vous ne pouvez pas saisir de quantit\u00e9 n\u00e9gative.");
        document.calcultotal['nop-0'].value = 1;			
        calcul();
    }else if (qte > 9999){
        alert("La quantit\u00e9 saisie ne doit pas d\u00e9passer 9999.");
        document.calcultotal['nop-0'].value = 9999;			
        calcul();
    }else if (qte == 0){
        alert("La quantit\u00e9 saisie doit \u00eatre sup\u00e9rieure a 0.");
        document.calcultotal['nop-0'].value = 1;			
        calcul();	
    }else{
        if (action == 'increment'){
            incrementPanier(1, object);
            calcul();
        }else if (action == 'decrement'){
            incrementPanier(-1, object);
            calcul();
        }else if (action == 'qte'){
            document.calcultotal['nop-0'].value = qte;	
            calcul();
        }else if (action == 'add'){
            //alert(document.getElementById("designation").value);
            //alert(document.getElementById("eprix").innerHTML);
            //addShoppingCartProduct('1',parseInt(document.calcultotal['nop-0'].value));
            addProductWithStock('1',eiid, reflm, parseInt(stock),parseInt(document.calcultotal['nop-0'].value),'','1');
        }else if (action == 'pickup'){ //TODO reprendre le stock reel dans le DWR
            
            addProductWithStock('2',eiid, reflm, parseInt(stock),parseInt(document.calcultotal['nop-0'].value),'','1');
        }
    }
    
}


/* Get real stock before to add a product
 * 
 */
function addProductWithStock(dt,eiid, reflm, stock, quantity, pos, toppickup){
    if (globalcartID == null){
        var Cookiecaddie = getCookie('cartmgt');
        if(Cookiecaddie != null) {
            var tabCookie=getContentCookieCaddie(Cookiecaddie);
            globalcartID = tabCookie[0];
        }
        if (globalcartID == null){
            getCartID();
        }
    }
	
    //on interroge le stock ssi le produit à la possibilité retrait en magasin
    var checkStock = true;
    if(toppickup==null || toppickup=='' || toppickup=='0'){
        checkStock = false;
    }
    //alert('  checkStock='+checkStock);
    //alert("addProductWithStock  dt="+dt +" quantity="+quantity +"  pos="+pos+"  reflm="+reflm+"  stock="+stock);
    
    if(checkStock){
        // DWRContextualizer.getCurrentContext(function(data) {
        var data=getCurrentContext();
        var currentShop = data;
        // check if contextualized
        //alert('currentShop.save=> '+currentShop.save);
        if (currentShop && currentShop.save =='true') {
            var shopid = currentShop.shop;
            
            //shopid = 11; //shop ID for test
            //reflm ='62637260'; //ref for test
            //alert('shopid=> '+shopid);
            
            //test si le service est accessible
            if(typeof(DWRProductInfoService)=='undefined'){
                //service non disponible
                if(dt == '2'){
                    //cas pickup servivce non disponible    
                    displayPanier();
                    alert("le service d'interrogation du stock magasin est hors ligne, veuillez r\u00e9essayer dans quelques minutes.");
                }else{
                    //cas vad ajout avec suppression des infos pickup si il y en a
                    storeStock(dt, eiid, reflm, stock, quantity,pos,true );
                }
            }else{
                //DWRProductInfoService exist
                DWRProductInfoService.getProductDetails(reflm,shopid, {
                    callback:function(data2) {
                        obj = data2;
                        var obj=data2;
                        stock = obj.stockEntity;
                        //alert('NB T16867 stock('+reflm+')=> '+stock);
                        //alert('addToPickup 1');
                        storeStock(dt, eiid, reflm, stock, quantity, pos, false );
                    },
                    timeout:5000,
                    errorHandler:function(data2) {
                    //alert('getShopStock getProductDetails error=> '+data2); 
                    },
                    exceptionHandler:function(data2) {
                        //alert('addProductWithStock getProductDetails exception=> '+data2);
                        if(dt == '2'){
                            //cas pickup servivce non disponible
                            displayPanier();
                            alert("le service d'interrogation du stock magasin est hors ligne, veuillez r\u00e9essayer dans quelques minutes");
                        }
                        else{
                            //cas vad
                            //ajout avec suppression des infos pickup si il y en a
                            storeStock(dt, eiid, reflm, stock, quantity,pos,true );
                        }
                    }
                });
            }
        }
        else{
            //alert('addToPickup 3');
            storeStock(dt, eiid, reflm, stock, quantity,pos,false );
        }
    //});
    }else{
        storeStock(dt, eiid, reflm, stock, quantity,pos,false );
    }
}

/* Set stock in page to add to cart after
 * value pos use from script-top.js 
 */
function storeStock(dt,eiid, reflm, stock, quantity, pos, removepickup){
    
    //alert("storeStock  dt="+dt +" quantity="+quantity +" pos="+pos+" stock="+stock );
    var posp = null;
    if(pos==null || pos==''){
        posp='';
    }else{
        posp=pos
        }
    
    //alert('stock='+stock);
    if(document.getElementById("Stock"+posp)){
        document.getElementById("Stock"+posp).innerHTML = stock;
    }
    //var newstock = document.getElementById("Stock"+posp).innerHTML; 
    //alert('stock='+stock+'  newstock='+newstock);
    
    if(dt == '1'){
        addShoppingCartProduct(dt,quantity,pos,stock,removepickup);
    }
    if(dt == '2'){
        if( stock >= quantity ){
            displayPanier();
            addShoppingCartProduct(dt,quantity,pos,stock,false);
        }
        else{ //stock < quantity nop
            //popup('pre?zone=zonecatalogue&idEIPub='+eiid+'&mdpid=1227883446&eipublicationtype=VELOCITY&zonetmp=zoneimpressionsl&pre-pos=','','600','350');
            //popup('pre?zone=zonecatalogue&idEIPub='+eiid+'&idMDPPub=1228743587&mdpid=127223170&eipublicationtype=VELOCITY&zonetmp=zoneimpressionsl&pre-stockreel='+stock+'&pre-pos='+posp,'','600','350','no');
            popup('pre?zone=zonecatalogue&idEIPub='+eiid+'&mdpid=1247223170&eipublicationtype=VELOCITY&zonetmp=zoneimpressionsl&pre-stockreel='+stock+'&pre-pos='+posp,'','600','350','no');
        }
    }
}

/*
function addToPickup( eiid, reflm, stock, qte ){
 
    //alert('PRE stock=>'+stock+'  reflm=>'+reflm+'   qte=>'+qte);
    DWRContextualizer.getCurrentContext(function(data) {
        var currentShop = data;
        // check if contextualized
        if (currentShop && currentShop.save =='true') {
            var shopid = currentShop.shop;
 
            //shopid = 11; //shop ID for test
            //reflm ='62637260'; //ref for test
            //alert('shopid=> '+shopid);
 
            DWRProductInfoService.getProductDetails(reflm,shopid,
            {
                callback:function(data2) { 
                        obj = data2;
                        var obj=data2;
                        stock = obj.stockEntity;
                        //alert('stock=> '+stock);
                        //alert('addToPickup 1');
                        loadPickupPage(eiid, stock, qte );
                 },			
                timeout:5000, 
                errorHandler:function(data2) {  alert('getShopStock getProductDetails error=> '+data2); },
                exceptionHandler:function(data2) { 
                    //alert('getShopStock getProductDetails exception=> '+data2); 
                    //alert('addToPickup 2');
                    loadPickupPage(eiid, stock, qte );
                } 		
            });
        }
        else{
            //alert('addToPickup 3');
            loadPickupPage(eiid, stock, qte );
        }
    });
 
}
 */
/*
function loadPickupPage(eiid, stock, qte ){
 
    if( stock >= qte ){
        addShoppingCartProduct('2',qte);
        }
    else{ //stock < qte nop
        popup('pre?zone=zonecatalogue&idEIPub='+eiid+'&mdpid=1227883446&eipublicationtype=VELOCITY&zonetmp=zoneimpressionsl&pre-pos=','','600','350');
    }
 
}
 */

function addShoppingCartProduct(dt,qte,pos,stockreel,removepickup){ 
    clearCookie();    
    
    
    if(pos==null || pos==''){
        pos='';
    }else{
        pos='_'+pos
        }
    
    var eiid = document.getElementById("eiid"+pos).innerHTML;
    var reflm = document.getElementById("reflm"+pos).innerHTML;
    var DescriptionOfProduct = document.getElementById("designation"+pos).value;
    var tva = document.getElementById("tva"+pos).innerHTML;
    var UnitPriceATA = document.getElementById("UnitPriceATA"+pos).innerHTML;
    var Weight = document.getElementById("Weight"+pos).innerHTML;
    var DeliveryDelay = document.getElementById("DeliveryDelay"+pos).innerHTML;
    var ModeVente = document.getElementById("ModeVente"+pos).innerHTML;
    
    var DescriptionOfProduct2 ='';
    if(document.getElementById("designation2"+pos)){
        DescriptionOfProduct2 = document.getElementById("designation2"+pos).innerHTML;
    }
    var DescriptionOfProduct2 = document.getElementById("designation2"+pos).value;
    var livraisonforfaitaire ='';
    if(document.getElementById("livraisonforfaitaire"+pos)){
        livraisonforfaitaire = document.getElementById("livraisonforfaitaire"+pos).innerHTML;
    }
    var td3e ='0';
    if(document.getElementById("td3e"+pos)){
        td3e = document.getElementById("td3e"+pos).innerHTML;
    }
    var vignette ='';
    if(document.getElementById("vignette"+pos)){
        vignette = document.getElementById("vignette"+pos).innerHTML;
    }
    var DiscountBeginDate ='';
    if(document.getElementById("DiscountBeginDate"+pos)){
        DiscountBeginDate = document.getElementById("DiscountBeginDate"+pos).innerHTML;
    }
    var DiscountAmountATA ='';
    if(document.getElementById("DiscountAmountATA"+pos)){
        DiscountAmountATA = document.getElementById("DiscountAmountATA"+pos).innerHTML;
    }
    var DiscountEndDate ='';
    if(document.getElementById("DiscountEndDate"+pos)){
        DiscountEndDate = document.getElementById("DiscountEndDate"+pos).innerHTML;
    }
    var TopPickup = 0;
    if(!removepickup){
        //ssi !removepickup, on a recupere les infos stock via le service
        TopPickup = document.getElementById("TopPickup"+pos).innerHTML;
    }
    var TopRestock ='';
    if(document.getElementById("TopRestock"+pos)){
        TopRestock = document.getElementById("TopRestock"+pos).innerHTML;
    }
    var currentDate ='';
    if(document.getElementById("currentDate"+pos)){
        currentDate = document.getElementById("currentDate"+pos).innerHTML;
    }
    var nextDeliveryDate ='';
    if(document.getElementById("nextDeliveryDate"+pos)){
        nextDeliveryDate = document.getElementById("nextDeliveryDate"+pos).innerHTML;
    }
    var Stock ='0';
    if(stockreel != null){
        Stock = stockreel;
    }else{    
        if(document.getElementById("Stock"+pos)){
            Stock = document.getElementById("Stock"+pos).innerHTML;
        }
    }
    var ProductType ='product';
    if(document.getElementById("ProductType"+pos)){
        ProductType = document.getElementById("ProductType"+pos).innerHTML;
    }
    var CodeBarre ='1213213213213';
    if(document.getElementById("CodeBarre"+pos)){
        CodeBarre = document.getElementById("CodeBarre"+pos).innerHTML;
    }
    var Editeur ='';
    if(document.getElementById("Editeur"+pos)){
        Editeur = document.getElementById("Editeur"+pos).innerHTML;
    }
    var RemiseID ='';
    if(document.getElementById("RemiseID"+pos)){
        RemiseID = document.getElementById("RemiseID"+pos).innerHTML;
    }
    
    
    //alert("  dt="+dt +"  eiid="+eiid +"  reflm="+reflm +"  tva="+tva +"  DescriptionOfProduct="+DescriptionOfProduct +"  DescriptionOfProduct2="+DescriptionOfProduct2 +"  UnitPriceATA="+ UnitPriceATA+"   Weight="+Weight +"  DeliveryDelay="+ DeliveryDelay+"  ModeVente="+ModeVente +"   vignette="+vignette +"  DiscountAmountATA=["+DiscountAmountATA+"]");
    
    var item = {
        'DeliveryType':dt,
        'ProductID':eiid, 
        'RefProduct':reflm,
        'tva':tva,
        'DescriptionOfProduct':DescriptionOfProduct,
        'DescriptionOfProduct2':DescriptionOfProduct2,
        'UnitPriceATA':UnitPriceATA,
        'Weight':Weight,
        'DeliveryDelay':DeliveryDelay, 
        'ModeVente':ModeVente,
        'td3e':td3e,
        'vignette':vignette,
        'DiscountBeginDate':DiscountBeginDate,
        'DiscountEndDate':DiscountEndDate,
        'Stock':Stock,
        'ProductType':ProductType
    };
    
    if(livraisonforfaitaire != ''){
        item.livraisonforfaitaire = livraisonforfaitaire;
    }
    if(DiscountAmountATA != ''){
        item.DiscountAmountATA = DiscountAmountATA;
    }
    if(currentDate != ''){
        item.currentDate = currentDate;
    }
    if(nextDeliveryDate != ''){
        item.nextDeliveryDate = nextDeliveryDate;
    }
    if(TopPickup != ''){
        item.TopPickup = TopPickup;
    }
    if(TopRestock != ''){
        item.TopRestock = TopRestock;
    }
    //alert('CodeBarre='+CodeBarre);
    if(CodeBarre != ''){
        item.CodeBarre = CodeBarre;
    }
    if(Editeur != ''){
        item.Editeur = Editeur;
    }
    if(RemiseID != ''){
        item.RemiseID = RemiseID;
    }
    
    
    addProductToCart(item,qte);
    
}


function fcheckQtyShoppingCart(sValue, item, defaultValue) {	
    qte = parseInt(sValue);
    if (qte > 9999){
        alert("La quantit\u00e9 saisie ne doit pas d\u00e9passer 9999.");
        item.value = defaultValue;
    }
}

function validFormShoppingCart(CurrentForm) {
    if(CurrentForm.cgvaccept.checked) {
        //CurrentForm.submit();
        checkAllStocks();
    } else {
        alert("Vous devez d\u00e9clarer avoir lu et accept\u00e9 les conditions g\u00e9n\u00e9rales de vente !");
        CurrentForm.cgvaccept.focus();
    }
}


function encrypt(str, pwd) {
    if(pwd == null || pwd.length <= 0) {
        alert("Please enter a password with which to encrypt the message.");
        return null;
    }
    var prand = "";
    for(var i=0; i<pwd.length; i++) {
        prand += pwd.charCodeAt(i).toString();
    }
    var sPos = Math.floor(prand.length / 5);
    var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
    var incr = Math.ceil(pwd.length / 2);
    var modu = Math.pow(2, 31) - 1;
    if(mult < 2) {
        alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
        return null;
    }
    var salt = Math.round(Math.random() * 1000000000) % 100000000;
    prand += salt;
    while(prand.length > 10) {
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
    }
    prand = (mult * prand + incr) % modu;
    var enc_chr = "";
    var enc_str = "";
    for(var i=0; i<str.length; i++) {
        enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
        if(enc_chr < 16) {
            enc_str += "0" + enc_chr.toString(16);
        } else enc_str += enc_chr.toString(16);
        prand = (mult * prand + incr) % modu;
    }
    salt = salt.toString(16);
    while(salt.length < 8)salt = "0" + salt;
    enc_str += salt;
    return enc_str;
}

function decrypt(str, pwd) {
    if(str == null || str.length < 8) {
        alert("Error str.length < 8 or null");
        return;
    }
    if(pwd == null || pwd.length <= 0) {
        alert("Please enter a password with which to decrypt the message.");
        return;
    }
    var prand = "";
    for(var i=0; i<pwd.length; i++) {
        prand += pwd.charCodeAt(i).toString();
    }
    var sPos = Math.floor(prand.length / 5);
    var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
    var incr = Math.round(pwd.length / 2);
    var modu = Math.pow(2, 31) - 1;
    var salt = parseInt(str.substring(str.length - 8, str.length), 16);
    str = str.substring(0, str.length - 8);
    prand += salt;
    while(prand.length > 10) {
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
    }
    prand = (mult * prand + incr) % modu;
    var enc_chr = "";
    var enc_str = "";
    for(var i=0; i<str.length; i+=2) {
        enc_chr = parseInt(parseInt(str.substring(i, i+2), 16) ^ Math.floor((prand / modu) * 255));
        enc_str += String.fromCharCode(enc_chr);
        prand = (mult * prand + incr) % modu;
    }
    return enc_str;
}


function paintLight(){
    var Cookiecaddie = getCookie('cartmgt');
    var doGetCaddie = false;
    if(Cookiecaddie != null) {
        doGetCaddie = true;
    }
     
    //alert(globalcartID + '    ' + doGetCaddie);
    if (globalcartID != null || doGetCaddie == true){

        //get all values by DWR
        //var Cookiecaddie = getCookie('cartmgt');
        //       alert('Cookiecaddie[' + Cookiecaddie+']');

        if(Cookiecaddie == null || Cookiecaddie == 'null'){
            createCookieCaddie();
        }
        else{
            refreshCookieCaddie(Cookiecaddie);
        }
    }else{
        lc ='Aucun article';
        if(document.getElementById('golightcaddie')){
            document.getElementById('golightcaddie').innerHTML =lc;
        }
    }
}


//remove cart by XMLHttpRequest groovy 
function removeCart(shopid){
    var cartID = null;
    //var carturl="pre?zone=zonetest2print&todo=removecart&shopid="+shopid;
    var carturl;
    if(document.location && document.location.protocol)
    {
        protocole = 'http'+((document.location.protocol=='https:')?'s':'')+':';
    }
    else
    {
        protocole = 'http:';
    }

    if (protocole == 'https:')
    {
        carturl = "pre?zone=zoneimpressioncommande&todo=removecart&shopid="+shopid;
    }
    else
    {
        carturl = "pre?zone=zonetest2print&todo=removecart&shopid="+shopid;
    }

    var xhr=null;
    try {
        xhr = new XMLHttpRequest(); 
    } catch(e) { 
        try { 
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e2) { 
            try { 
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {//alert('ERREUR');
            }
        }
    }
    
    xhr.open('GET', carturl , false); 
    xhr.send(null); 
    if(xhr.readyState == 4){
        var cartid = xhr.responseText;
        clearCookie();
        globalcartID = cartid;
        return globalcartID;
    }
}

// transfert liste course
function moveProductToListeCourse(CurrentForm){
    var cartmgtid = getCartID();
    var ALL = 'ALL';
    DWRShoppingCart.getAllItems(cartmgtid,['RefProduct'], {   
        callback:function(data) {
            var listProduct = data;
            
            for(i=0 ; i< listProduct.length; ++i) { 
                //alert("listProduct productid "+listProduct[i].allItemProperties.ProductID);   
                ListCourseService.addProduct( listProduct[i].allItemProperties.ProductID,
                    listProduct[i].quantity,
                    {
                        callback:function(data) {
                        }
                        });
            }            
            
            
        },			
        timeout:5000, 
        errorHandler:function(data) {  //alert('moveProductToListeCourse ipam error=> '+data); 
        },
        exceptionHandler:function(data) { 
        // alert("error dans moveProductToListeCourse");
            
        } 		
    });
    showPopupListeCourse();
}
function showPopupListeCourse(){
    init_layer_popup();
    if (obj_layer_popup) {	
        cache_popup = false;
        
        startEffect('masque');
        
        var ch_texte = '<div id="contentPopup">';
        
        ch_texte += '<h1 class="produits">Le contenu de mon panier a bien &eacute;t&eacute; ajout&eacute; &agrave; ma liste</h1><br>';
        ch_texte += '<div id="targetarea" class="arial_12_000000" style="margin-top: 5px; margin-bottom: 10px;">&nbsp;</div>';
        ch_texte += '<a href="/mpng2-front/pre?zone=zonelistecourse&srvname=srvlistecourse&action=showlistecourse&pageid=17"><img src="/images/produits/accederAmalisteVert.gif" border="0"></a><br>';
        ch_texte += '<a href="javascript:fermerpopup();"><img src="/images/produits/btnPoursuivreAchatsVert.gif" border="0"></a></div>';
        contenu_layer_popup(ch_texte);
        setTimeout('refreshLightBasket()',4000); 
    }
}
var maDate = new Date();    
var monJour = maDate.getDay();
var annee = maDate.getFullYear();
var H24 = 24*60*60*1000;

function getTheDate(strDate){
    // alert(strDate);
    day = parseInt(strDate.substring(0,2),10);
    month = parseInt(strDate.substring(3,5),10);
    year = parseInt(strDate.substring(6,10),10);
    d = new Date();
    d.setFullYear(year);
    d.setMonth(month-1,day);
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);
    return d;  
}
function getEaster() {
    
    var dateEaster = null;
    var b = annee - 1900;
    var c = annee % 19;
    var d = Math.floor((7*c+1)/19);
    var e = (11*c+4-d) % 29;
    var f = Math.floor(b/4);
    var g = (b+f+31-e) % 7; 
    var avril = 25-e-g;
    if (avril > 0) dateEaster = new Date(annee, 3, avril);
    else dateEaster = new Date(annee, 2, avril + 31);
    return dateEaster;
}
var aBankHolidays = new Array();
aBankHolidays.push(getTheDate('01/01/'+annee));
aBankHolidays.push(getTheDate('01/05/'+annee));
aBankHolidays.push(getTheDate('08/05/'+annee));
aBankHolidays.push(getTheDate('14/07/'+annee));
aBankHolidays.push(getTheDate('15/08/'+annee));
aBankHolidays.push(getTheDate('01/11/'+annee));
aBankHolidays.push(getTheDate('11/11/'+annee));
aBankHolidays.push(getTheDate('24/12/'+annee));
aBankHolidays.push(getTheDate('25/12/'+annee));
aBankHolidays.push(getTheDate('31/12/'+annee));
aBankHolidays.push(getTheDate('31/12/'+annee));
aBankHolidays.push(getTheDate('01/01/'+(annee+1)));
    
var iEaster = getEaster();
//aBankHolidays.push(iEaster);

var dateEaster1 = null;
dateEaster1 = iEaster;
dateEaster1.setDate(dateEaster1.getDate()+1);
var dateEaster38 = null;
dateEaster38 = iEaster;
dateEaster38.setDate(dateEaster38.getDate()+38);
    
aBankHolidays.push(dateEaster1);
aBankHolidays.push(dateEaster38);
        
    
function getNextShoppingDay(thisdate,index) {
    var sRetour ="";
    if(index==undefined) index="";    
    var finalDay = thisdate.getDate();   
    if(finalDay < 10){
        finalDay="0"+finalDay;
    }
    var finalMonth =thisdate.getMonth()+1; 
    if(finalMonth < 10){
        finalMonth="0"+finalMonth;
    }
    
    var tempDate = getTheDate(finalDay+"/"+finalMonth+"/"+thisdate.getFullYear());


    var ecrart = 0;
    var i = 1
    while(ecrart != 2) {
        tempDate=new Date(thisdate.getTime() +(H24*i));
        var stop = 0;
        for(var j=0 ; j< aBankHolidays.length; ++j) {
            if(tempDate.getMonth()==aBankHolidays[j].getMonth()
                &&tempDate.getDate()==aBankHolidays[j].getDate()
                &&tempDate.getFullYear()==aBankHolidays[j].getFullYear() && stop == 0 ){
                ecrart= ecrart-1;
                stop = 1;
            }else if(tempDate.getDay() == 0 && stop == 0 ){
                ecrart= ecrart-1;
                stop = 1;
            }
        }
        ecrart= ecrart+1;
        // alert("ecrart "+ecrart);
        i= i+1;  
        
    }
    var finalDay2 =tempDate.getDate();
    if(finalDay2 < 10){
        finalDay2="0"+finalDay2;
    }
    var finalMonth2 =tempDate.getMonth()+1 ;
    if(finalMonth2 < 10){
        finalMonth2="0"+finalMonth2;
    }
        
        
    sRetour =""+finalDay2+"/"+finalMonth2+"/"+tempDate.getFullYear();
    /* if(document.getElementById('promesse'+index)){
            document.getElementById('promesse'+index).innerHTML=sRetour;
    }*/
    if( document.getElementById('promessepickup'+index) ){
        document.getElementById('promessepickup'+index).innerHTML = sRetour;
    }
         
    //  alert("sRetour "+sRetour);
    return sRetour;
}
function getHours(index) {
    if(index==undefined) index="";    
    var sHours ="09";
    if(maDate.getHours() >= 14){
        sHours ="14";
    }
    if(document.getElementById('hours'+index)){
        document.getElementById('hours'+index).innerHTML=sHours;         
    }
    if(document.getElementById('hourspickup'+index)){
        document.getElementById('hourspickup'+index).innerHTML=sHours;         
    }
}
//Easter - donne la date de P�ques selon l�ann�e



//Retourne:
//   0 si date_1=date_2
//   1 si date_1>date_2
//  -1 si date_1<date_2	  
function compare(date_1, date_2){
    diff = date_1.getTime()-date_2.getTime();
    return (diff==0?diff:diff/Math.abs(diff));
}
//dayNumber - retourne 0 pour un lundi, 1 pour mardi... 6 pour dimanche
function dayNumber (thisdate) {
    //alert(thisdate);
    return thisdate.getDay() ? (thisdate.getDay()-1) : 6;
}

function executeJS(e) {
    // fix IE bug, e == null ?! message 'null' is null or not an object
    if(document.getElementById('maindiv')){
        e = document.getElementById('maindiv');
    }else if(document.getElementById('corps')){
        e = document.getElementById('corps');
    }
    var scripts = e.getElementsByTagName("script");
    for( var i =0 ; i < scripts.length; i++) {
        var ih = scripts[i].innerHTML;
        if(ih &&  ih.indexOf('document.write') == -1 ) {
            eval(ih);
        } else {
    //  alert("javascript contains document.write "+scripts[i].innerHTML);
    }
    }
}

//tomorrow - ajoute un jour � la date
function getTomorrow(theDate) {
    var datretour = new Date(theDate.getTime() + H24);
    return datretour;
}
function setTomorrow(theDate,index) {
    if(index==undefined) index="";         
    
    var tomo = getTomorrow(theDate);
     
    var finalDay =tomo.getDate();
    if(finalDay < 10){
        finalDay2="0"+finalDay;
    }
    var finalMonth =tomo.getMonth()+1 ;
    if(finalMonth < 10){
        finalMonth="0"+finalMonth;
    }
    var sRetour =""+finalDay+"/"+finalMonth+"/"+tomo.getFullYear();
    if(document.getElementById('promesse'+index)){
        document.getElementById('promesse'+index).innerHTML=sRetour;
    }
/*
     if( document.getElementById('promessepickup'+index) ){
         document.getElementById('promessepickup'+index).innerHTML = sRetour;
     }  */      
}


function refreshCookieCaddie(Cookiecaddie){
	
    var tabCookie=getContentCookieCaddie(Cookiecaddie);
    //alert(Cookiecaddie);
    //DBG : PR 20091026
    var jsessionid = getCookie('JSESSIONID');
    var jsessionidFromCookie = tabCookie[3];
    if(jsessionid != jsessionidFromCookie)
       {
         lc ='Aucun article';
         if(document.getElementById('golightcaddie')){
           document.getElementById('golightcaddie').innerHTML =lc;
         }
//       createCookieCaddie();
       return;
       }
    var total = decrypt(tabCookie[2],"password");
    var nombrearticles = tabCookie[1];

    //  alert('nombrearticles '+ nombrearticles+' total '+total);
    var lc ='';
    if(nombrearticles > 0) {
        lc += '<a onclick="makext_med(\'C\',\'zone_permanente::zone_header::panier\',\'N\');" href="pre?zone=zoneprocessachat&todo=show&pageid=111">&gt;';
        lc += '&nbsp;'+nombrearticles+'&nbsp;article';
        if(nombrearticles > 1){
            lc+='s';
        }
        lc += '&nbsp;<strong class="montant">'+total+'</strong> EUR';
        lc += '</a>';
    }
    else{
        lc ='Aucun article';
    }
    if(document.getElementById('golightcaddie')){
        document.getElementById('golightcaddie').innerHTML =lc;
    }
}

function getContentCookieCaddie(Cookiecaddie)
{
    var clen=Cookiecaddie.length;
    var i=0;
    var tabCookie=new Array();
    for(j=0;j<clen;j++) {
        if(Cookiecaddie.charAt(j)=="|") {
            var temp = Cookiecaddie.substring(i,j)
            //alert(temp);
            tabCookie.push(temp);
            i=j+1;
        //  alert(temp +' ' +i);
        }
    }
    tabCookie.push(Cookiecaddie.substring(i,clen));
    return tabCookie;
}

function createCookieCaddie(){
	
    var cartmgtid = globalcartID;
    if (cartmgtid == null){
        cartmgtid = getCartID();
    }
    var ALL = 'ALL';
    DWRLMShoppingCart.getShoppingCartInfo(cartmgtid,ALL, {
        callback:function(msg) {
            tabInfos = msg;
            var total = (tabInfos.totalGlobal).toFixed(2);
            var nombrearticles = tabInfos.cartItemCount;
            //  alert('nombrearticles '+ nombrearticles+' total '+total);
            var lc =''
            if(nombrearticles > 0) {
                lc += '<a onclick="makext_med(\'C\',\'zone_permanente::zone_header::panier\',\'N\');" href="pre?zone=zoneprocessachat&todo=show&pageid=111">&gt;';
                lc += '&nbsp;'+nombrearticles+'&nbsp;article';
                if(nombrearticles > 1){
                    lc+='s';
                }
                lc += '&nbsp;<strong class="montant">'+total+'</strong> EUR';
                lc += '</a>';
            }
            else{
                lc ='Aucun article';
            }
            if(document.getElementById('golightcaddie')){
                document.getElementById('golightcaddie').innerHTML =lc;
            }
	    //DBG : PR 20091026 ajout du jsessionid dans le cookie
	    var jsessionid = getCookie('JSESSIONID');
            var cookieval= ''+cartmgtid +'|'+ nombrearticles+'|'+ encrypt(total,"password")+'|'+jsessionid;
            setCookie('cartmgt',cookieval)
        },
        timeout:5000,
        errorHandler:function(msg) {
        //alert('getShoppingCartInfo ipam error=> '+msg);
        },
        exceptionHandler:function(msg) {
            var lc = 'Aucun article error';
            if(document.getElementById('golightcaddie')){
                document.getElementById('golightcaddie').innerHTML =lc;
            }
        //alert('getShoppingCartInfo exception=> '+msg);
        }
    });

}

function clearCookie(){
    setCookie('cartmgt',null);
}
