/***************************Panier dynamique V 4.1 *******************************/
function dynamicCart () {}
dynamicCart.prototype.smallCartTmpl=null;
dynamicCart.prototype.popupCartTmpl=null;
dynamicCart.prototype.cookieSaving=true;
dynamicCart.prototype.cartTemplateCookie=null;
dynamicCart.prototype.returnCartMainId = 'shopcartreturn';
dynamicCart.prototype.returnCartBodyId = 'shopcartbody';
dynamicCart.prototype.returnCartContainerId = 'shopcartcontainer';
dynamicCart.prototype.returnCartPreloadId = 'shopcartpreload';
dynamicCart.prototype.showCartContainerId = 'showCartContainer';
dynamicCart.prototype.mainTblSmallCart = '#dynamicCart';
dynamicCart.prototype.mainTblPopupCart = '#blockCart';
dynamicCart.prototype.returnButton = '#returnShopping';
dynamicCart.prototype.oldCartButton = '#btnviewcart span';
dynamicCart.prototype.mode = 'popup'; // autre valeur : 'animate''
dynamicCart.prototype.oldCartButtonExpRegModel = new RegExp('Votre\\s*?Panier(\\s*?:\\s*?\\<small\\>\\d*?\\s*?article\\(s\\)\\<\\/small\\>)',"gi");
dynamicCart.prototype.activate=  function (nProductID, strURLParams) {
   
    var me=this;
    if (this.mode == 'popup') var shopcartcontainer = this.addHTMLStructure ();
    var multiAjax = [];

    // Panier dynamqiue
    var getCart = new queryParameters();
    getCart.url = 'PBShoppingCart.asp?AjaxMode=1&'+strURLParams;
    var firstQuery = new queryDeclaration (getCart);
    multiAjax.push(firstQuery);

    // recup tmpl
    var getTmpl = null;
    if (this.popupCartTmpl) {
        getTmpl = new queryParameters();
        getTmpl.url = 'ws/wsGetWebBlock.asp?WBID='+this.popupCartTmpl;
        var secondQuery = new queryDeclaration (getTmpl);
        multiAjax.push(secondQuery);
    }

    // exécution simultanée des 2 requetes
    var doQuery = new chainProcessQueries (multiAjax);
    doQuery.toDo = function () {
        switch(me.mode) {

            case ('popup'):
                showCartPopup ();
                break;

            case ('animate'):
                showCartAnimate ();
                break;
                
            default :
                if (window.console) console.log ('unknow mode');
                break;
        }
    } ;
    doQuery.exec();

    //version animée
    function showCartAnimate () {

        var isThereImages = false;

        function spotImage (referer, element, only, defaultZone) {
            /* referer : la zone du produit
               element : l'image du produit - null ou classe à trouver
               only : ne doit pas s'appliquer si une image a déjà été trouvée - true ou false
               defaultZone : point de référence si le produit n'a pas d'image
               defaultImage : Url image de rempalcement
            */
            if (isThereImages && only) return;

            var localObject = "$(this)";
            if (element) localObject += ".find('"+element+"')";
            localObject +=".eq(0)";

            referer.each(function () {
                var imgRelated = new moveToCart(eval(localObject));
                imgRelated.domTarget = $(me.mainTblSmallCart);
                imgRelated.onDone = function () { me.showSmallCart(); }
 
                if ( imgRelated.moveInCart() ) {
                    isThereImages=true ;
                } else {
                    localObject = "$(this).find('"+defaultZone+"').eq(0)";
                    var btnRelated = new moveToCart( eval(localObject), me.defaultImg );
                    btnRelated.domTarget = $(me.mainTblSmallCart);
                    btnRelated.onDone = function () { me.showSmallCart(); }
                    if ( btnRelated.moveInCart() ) {
                        isThereImages=true ;
                    }
                }
            });
        }

        //image pincipale vue detail
        spotImage ($('.sectiondataarea').has('.itemdetail a.btnaddtocart[href*="AddToCart('+nProductID+'"]'), '.imgmain', true, '.btnmain');
        //images des articels cochés dans les ventes suggestives
        spotImage ($('.PBRelPdtTable table.PBLayoutTable').has('input[type=checkbox]:checked'), 'img', false, 'input[type=checkbox]');
        // image produit vue liste
        spotImage ($('.oxcell').has('a[href*="AddToCart('+nProductID+'"]'), 'img.imgthumbnail', true, '.btnaddtocart');
        // image produit vue liste
        spotImage ($('.PBOptImgTable td').has('a.btnoptaddtocart[href*="AddToCart('+nProductID+'"]'), '.PBOptImg img', true, '.PBOptBtn');

        // no image
        if (!isThereImages) {
            me.showSmallCart ();
        }
    }
    
    //version popup
    function showCartPopup () {

        if (!getCart.answer) {
            if (window.console) console.log ('Error : Can\'t send Items in Cart');
            me.returnToSite();
            return;
        }
                
        if (!getTmpl || !getTmpl.answer || getTmpl.answer.error) {
            if (window.console) console.log ('Error : Wrong popupCartTmpl ID');
            me.returnToSite();
            return;
        }

        var htmlModel=getTmpl.answer.htmlContent;
        if (!getCart.answer.cartsubtotalnet) getCart.answer.cartsubtotalnet = '0';
        var totalAmount=getCart.answer.currencies.mainFormat.replace ('#', numberToPrice (getCart.answer.cartsubtotalnet, getCart.answer.currencies.thousandsSep, getCart.answer.currencies.decSep) );
        var totalSubAmounnt = (getCart.answer.currencies.scndryFormat && getCart.answer.currencies.scndryRate)? getCart.answer.currencies.scndryFormat.replace ('#', numberToPrice ( Math.round ( parseFloat(getCart.answer.cartsubtotalnet) * parseFloat(getCart.answer.currencies.scndryRate) ), getCart.answer.currencies.thousandsSep, getCart.answer.currencies.decSep) ) : null;
        
        var pdtTitle = null;
        var pdtImg = null;
        var pdtPrice = null;
        var pdtScndryPrice = null;
        
        $.each(getCart.answer.products, function(key, val) {
            if (val.itemID != nProductID) return;
            pdtTitle = val.itemName;
            if (val.itemImgFile) pdtImg = '<img bordel=0 src="' + val.itemImgFile + '">';
            if (val.itemPriceNet) pdtPrice = getCart.answer.currencies.mainFormat.replace ('#', numberToPrice ( Math.ceil ( parseFloat(val.itemPriceNet) * 100 ), getCart.answer.currencies.thousandsSep, getCart.answer.currencies.decSep) );
            if (val.itemPriceNet && getCart.answer.currencies.scndryRate && getCart.answer.currencies.scndryFormat) pdtScndryPrice = getCart.answer.currencies.scndryFormat.replace ('#', numberToPrice ( Math.round ( parseFloat(val.itemPriceNet) * 100 * parseFloat(getCart.answer.currencies.scndryRate) ), getCart.answer.currencies.thousandsSep, getCart.answer.currencies.decSep) );
            return false;
        });
        
        me.showSmallCart ();
        
        htmlModel = me.replaceFromTemplate (htmlModel, '#ADDEDITEMS#', getCart.answer.result, true );
        htmlModel = me.replaceFromTemplate (htmlModel, '#TOTALITEMS#', getCart.answer.cartqtytotal, true );
        htmlModel = me.replaceFromTemplate (htmlModel, '#CARTAMOUNT#', totalAmount);
        htmlModel = me.replaceFromTemplate (htmlModel, '#SCNDRYCARTAMOUNT#', totalSubAmounnt);
        htmlModel = me.replaceFromTemplate (htmlModel, '#PDTTITLE#', pdtTitle);
        htmlModel = me.replaceFromTemplate (htmlModel, '#PDTPRICE#', pdtPrice);
        htmlModel = me.replaceFromTemplate (htmlModel, '#SCNDRYPDTPRICE#', pdtScndryPrice);
        htmlModel = me.replaceFromTemplate (htmlModel, '#PDTIMG#', pdtImg);
        shopcartcontainer.html(htmlModel);

        //clic sur bouton continuer
        $(me.returnButton).attr('href','#');
        $(me.returnButton).bind('click', function () {
            me.returnToSite();
        });
         
        $('#'+ me.returnCartContainerId).bind ('click', function () {
            me.returnToSite();        
        });

        $(me.mainTblPopupCart).bind ('click', function (e) {  
            e.stopPropagation();
        });
        
    } 
}

// Création structure HTML
dynamicCart.prototype.addHTMLStructure = function () {
    var testCartArea= $('#'+this.returnCartMainId);

    if (testCartArea.length<1) {
        $('body').eq(0).prepend('<div id="'+this.returnCartMainId+'"><div id="'+this.returnCartBodyId+'"></div><div id="'+this.returnCartContainerId+'"></div></div>');
    }
    $('#'+this.returnCartBodyId).css('height',$(document).height());

    var shopcartcontainer=$('#'+this.returnCartContainerId);
    $('#'+this.returnCartMainId).show();

    shopcartcontainer.append('<div id="'+this.returnCartPreloadId+'"></div>').css('top',$(window).scrollTop());
    return shopcartcontainer;
}

// affichage du mini-panier
dynamicCart.prototype.showSmallCart = function () {

    if (!this.testInit) return;

    var localCookie = getCookie('cartTemplateCookie');
    var cookieCal = getCookie('cartCalculationCookie');
    if (this.cookieSaving) this.cartTemplateCookie = localCookie;
   
    if (!this.cartTemplateCookie || !cookieCal) {
                
        var ajaxQueries = [];
        // Panier
        var getSmallCart = new queryParameters();
        getSmallCart.url = 'ws/wsGetInfo.asp';
        var firstQuery = new queryDeclaration (getSmallCart);
        ajaxQueries.push(firstQuery);

        // recup tmpl
        var getSmallTmpl = new queryParameters();
        getSmallTmpl.url = 'ws/wsGetWebBlock.asp?WBID='+this.smallCartTmpl;
        var secondQuery = new queryDeclaration (getSmallTmpl);
        ajaxQueries.push(secondQuery);

        // exécution simultanée des 2 requetes
        var doQueries = new chainProcessQueries (ajaxQueries);
        doQueries.toDo = function () {
            createTemplate();
        }
        doQueries.exec();    
        
        var me=this;
        function createTemplate () {
           
            if (!getSmallTmpl.answer || getSmallTmpl.answer.error) {
                if (window.console) console.log ('Error : Wrong smallCartTmpl ID');
                me.returnToSite();
                return;
            }
      
            var htmlModel = getSmallTmpl.answer.htmlContent ;
            var mainFormat = (getSmallCart.answer.currencies.mainFormat)? getSmallCart.answer.currencies.mainFormat.replace ('#', '#CARTAMOUNT#'): '#CARTAMOUNT#';
            var scndryFormat = (getSmallCart.answer.currencies.scndryFormat && getSmallCart.answer.currencies.scndryRate)? getSmallCart.answer.currencies.scndryFormat.replace ('#', '#SCNDRYCARTAMOUNT#'): null;
       
            htmlModel = me.replaceFromTemplate (htmlModel, '#CARTAMOUNT#', mainFormat);
            htmlModel = me.replaceFromTemplate (htmlModel, '#SCNDRYCARTAMOUNT#', scndryFormat);
       
            var rate = '{ sr : ' + getSmallCart.answer.currencies.scndryRate +', d : "' + getSmallCart.answer.currencies.decSep + '", t : "' + getSmallCart.answer.currencies.thousandsSep + '"}';
       
            me.cartTemplateCookie = htmlModel;
            if (me.cookieSaving)  setCookie ('cartTemplateCookie', me.cartTemplateCookie);
            setCookie ('cartCalculationCookie',rate);
            me.showCartInDocument (); 
        }  
    } else {
        this.showCartInDocument ();
    }
}

dynamicCart.prototype.showCartInDocument = function () {
    //suppresions du nb d'articles dans l'ancien bouton
    var oldBuyButton = $(this.oldCartButton);
    if (oldBuyButton.length) {
        var htmlContent = oldBuyButton.html(),
        doResult=this.oldCartButtonExpRegModel.exec(htmlContent);
        if (doResult && doResult.length>0) {
            oldBuyButton.html(htmlContent.replace(doResult[1], ''));
        }
    }

    //affichage du mini panier
    var reg=new RegExp("QTYTotal=(\\d*)","g");
    var regAmount=new RegExp("SubTotalNet=(\\d*)","g");
    var PCart=getCookie('PCart');
    var cartCalculation = eval('('+ getCookie('cartCalculationCookie') +')');
    var nbItems=reg.exec(PCart);
    var amount=regAmount.exec(PCart);
    var totalCart = (amount && amount.length>1 && amount[1]!="")? numberToPrice (amount[1], cartCalculation.t, cartCalculation.d) : '0';
    var scndryTotalCart = (amount && amount.length>1 && amount[1]!="" && cartCalculation.sr )? numberToPrice ( Math.round( parseFloat(amount[1]) * parseFloat(cartCalculation.sr) ), cartCalculation.t, cartCalculation.d) : '0';
    var items = (nbItems && nbItems.length>1 && nbItems[1]!="")?  nbItems[1] : '0';
    var cartModel = this.cartTemplateCookie;
    
    cartModel = this.replaceFromTemplate (cartModel, '#NBITEMS#', items , true );
    cartModel = this.replaceFromTemplate (cartModel, '#CARTAMOUNT#', totalCart);
    cartModel = this.replaceFromTemplate (cartModel, '#SCNDRYCARTAMOUNT#', scndryTotalCart);

    var btncontainer = $('#'+this.showCartContainerId);
    if (btncontainer.length<1) {
        $('<div/>', {
            'id': this.showCartContainerId,
            html: cartModel
        }).prependTo('body');
    } else {
        btncontainer.html(cartModel);
    }

}

//gestionnaire de template
dynamicCart.prototype.replaceFromTemplate = function (htmlModel, tag, value, recursive) {

    if (recursive) {
        
        if (!value) value = 0;
        value = parseInt(value);
        var reg = {
            expression:new RegExp(tag+"\\s*\\{\\s*\\[([^\\}|\\]]*)\\]\\s*\\[([^\\}|\\]]*)\\]\\s*\\[([^\\}|\\]]*)\\]\\}", "g"),
            tagValue:new RegExp("#VALUE#", "g")
        }
        var doResult=reg.expression.exec(htmlModel);
        if (!doResult) return null;

        var idValue = (value>2)? 3 : value+1,
        newHTML=doResult[idValue].replace(reg.tagValue, value);
        htmlModel=htmlModel.replace(reg.expression,newHTML);
        
    } else {
        
        var tagValue = new RegExp(tag, "g");
        if (!value) value='';
        htmlModel=htmlModel.replace(tagValue, value);
        
    }

    return htmlModel;
}

//bouton continuer
dynamicCart.prototype.returnToSite = function () {
    $('#'+this.returnCartMainId).remove();
}

dynamicCart.prototype.testInit = function () {
    if (typeof jQuery == 'undefined') {
        if (window.console) console.log ('Error : Jquery must be activated');
        return false;
    }

    if (!this.smallCartTmpl)  {
        if (window.console) console.log ('Error : no smallCartTmpl ID');
        return false;
    }

    if (typeof queryParameters == 'undefined') {
        if (window.console) console.log ('missing file : ajaxScheduler.js');
        return false;
    }
    
    if ( typeof getCookie == 'undefined' ) {
        if (window.console) console.log ('missing file : cookieManager.js');
        return false;
    }
    
    if ( typeof numberToPrice == 'undefined' ) {
        if (window.console) console.log ('missing file : priceConverter.js');
        return false;
    }
    
    return true;
}

function moveToCart (origin, url) {
    this.domOrigin=origin;
    this.url=(!url)? null : url;
}
moveToCart.prototype.domTarget = null;
moveToCart.prototype.height = 100;
moveToCart.prototype.width = 100;
moveToCart.prototype.onDone = null;
moveToCart.prototype.moveInCart= function () {

    var isImage;
    var me=this;

    // récupération image
    if (this.url) {
        isImage = this.url;
    } else {
        // récupr src
        isImage = this.domOrigin.attr('src');
        this.height = this.domOrigin.outerHeight();
        this.width = this.domOrigin.outerWidth();
    }

    // si pas de src, on pcherche une eventuelle bg-image
    if (!isImage) {
        var pattern = /url\(|\)|"|'/g,
        getUrl = this.domOrigin.css('backgroundImage');
        if (getUrl) {
            isImage= getUrl.replace(pattern,"");
            this.height = this.domOrigin.outerHeight();
            this.width = this.domOrigin.outerWidth();
        }
    }

    if (this.height<1) this.height = 1;
    var coef= this.width/this.height;
        
    if (!this.domOrigin.length || !this.domTarget.length || !isImage || isImage=="none")  return false;

    var offsetOrigin=this.domOrigin.offset(),
    offsetTarget=this.domTarget.offset();

    $('<img/>', {
        'src':isImage
    }).prependTo('body').css ({
        'z-index':3000,
        'position':'absolute',
        'top':offsetOrigin.top,
        'left':offsetOrigin.left,
        'height':this.height,
        'width': Math.ceil(this.height*coef)
    }).animate ({
        'height':this.domTarget.outerHeight(),
        'width': Math.ceil(this.domTarget.outerHeight()*coef),
        'top':offsetTarget.top,
        'left':offsetTarget.left+(Math.round(this.domTarget.outerWidth()/2))
    }, 1500).animate ({
        'opacity':0
    }, 500, function(){
        if (me.onDone) me.onDone();            
        $(this).remove();
    });

    return true;
}
