/******indexOf fo Ie**************/
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}


/**********Pas de retour à la racine de catalogue***********/

function noRootCart (textCrumb) {
    if ( (OxCompName == "SCCatalog" && !OxCatID1 && !OxCatID2 && !OxCatID3) || ($('dontshow').length) ) {
        $('.sectiondata, .sectiontb').remove();
        window.location.replace("/");
    }

    $('.sccatalog #catbclevel0 a.PBBtnStd').html(textCrumb);
}


/******************cookie Manager*******************/
var localMode = false;

function getCookie(sName) {
    var oRegex = new RegExp("(?:; )?" + sName + "=([^;]*);?");

    if (oRegex.test(document.cookie)) {
        return unescape(RegExp["$1"]);
    } else {
        return null;
    }

}

function setCookie (sName, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = sName+"="+escape(value)+expires+"; path=/";
}

function eraseCookie(sName) {
    setCookie(sName,"",-1);
}


/************************Recupération ID catégorie****************************/
function getCatId () {
    var currentCatId=getCookie('currentCatId');

    if (!OxCatID1 && !OxCatID2 && !OxCatID3) {
        eraseCookie('currentCatId');
        return null;
    }

    if (!currentCatId) {
        if (OxCatID1) {
            setCookie ('currentCatId', OxCatID1);
            return OxCatID1;
        }
        if (OxCatID2) {
            setCookie ('currentCatId', OxCatID2);
            return OxCatID2;
        }
        if (OxCatID3) {
            setCookie ('currentCatId', OxCatID3);
            return OxCatID3;
        }
        return null;
    } else {
        switch (parseInt(currentCatId, 10)) {
            case parseInt(OxCatID1, 10):
                setCookie ('currentCatId', OxCatID1);
                return OxCatID1;
                break;
            case parseInt(OxCatID2, 10):
                setCookie ('currentCatId', OxCatID2);
                return OxCatID2;
                break;
            case parseInt(OxCatID3, 10):
                setCookie ('currentCatId', OxCatID3);
                return OxCatID3;
                break;
            default:
                if (OxCatID1) {
                    setCookie ('currentCatId', OxCatID1);
                    return OxCatID1;
                }
                if (OxCatID2) {
                    setCookie ('currentCatId', OxCatID2);
                    return OxCatID2;
                }
                if (OxCatID3) {
                    setCookie ('currentCatId', OxCatID3);
                    return OxCatID3;
                }
                break;
        }
        return null;
    }
}

function getCatTree (setting) {

    $('#bodycolumn2').hide();

    if (!setting.currentCatID) {
        $('#bodycolumn2').show();
        return;
    }

    if (!setting.ajaxCache)  setting.ajaxCache=true; // Cache des données en Ajax

    $.ajaxSetup({
        cache: setting.ajaxCache
    });

    // Premier appel Json
    $.getJSON('ws/wsGetCategories.asp?CatID='+setting.currentCatID+'&Mode=3&shopcart=1', function(data) {
        returnCatTree (data);
    });

}

/*Page Liste des idées sans prix ni bouton acheter */
function showIdea (setting) {
    $('.oxcell .PBItemPrice, .oxcell .PBItemStock, .oxcell PBItemEcoPart, .oxcell .btnaddtocart').remove();
}

/***************************Menu Horizontal CATALOGUE**********************************/
function showCarrousel (setting) {
    if (!setting.currentCatID || !setting.targetCatID || !setting.data) return;
       
    //Variables Initialisation
    if (!setting.imgWidth) setting.imgWidth=140; // Taille image avant zoom
    if (!setting.maxElements) setting.maxElements=6; // Nombre d'élement du carrousel si un seul niveau
    if (!setting.imgWidthLv2) setting.imgWidthLv2=90; // Taille image avant zoom
    if (!setting.maxElementsLv2) setting.maxElementsLv2=8; // Nombre d'élement du carrousel si un seul niveau
    if (!setting.fontOffset) setting.fontOffset=0; // zoom des texte
    if (!setting.arrowSize) setting.arrowSize=30; // largeur des élements fleche
    if (!setting.CSSMargin)  setting.CSSMargin=0; // Marge css appliquée à hmenuListMainContainer
    if (!setting.levelTwoThreshold)  setting.levelTwoThreshold=null; // profondeur de catalogue pour affichage du deuxième menu
    if (!setting.ajaxCache)  setting.ajaxCache=true; // Cache des données en Ajax

    $.ajaxSetup({
        cache: setting.ajaxCache
    });
        
    var firstParentLevel, secondParentLevel;

    firstParentLevel = (setting.data.categorypath.levelcount>1) ? setting.data.categorypath.hierarchy[setting.data.categorypath.levelcount-2] : null;
    secondParentLevel = (setting.data.categorypath.levelcount>2 && setting.data.categorypath.levelcount>=setting.levelTwoThreshold ) ? setting.data.categorypath.hierarchy[setting.data.categorypath.levelcount-3] : null;

    if ((setting.currentCatID != setting.targetCatID) && (secondParentLevel != setting.targetCatID) && (firstParentLevel != setting.targetCatID)) {
        $('#bodycolumn2').show();
        return;
    }

    //Suppression/déplacement des élements générés par Oxatis
    var itemlist = $('.itemlist'),
    oxcell = $('.oxcell');

    if (itemlist.length>0 && oxcell.length<1) {
        $('tr:has(.sectiondata)').not(':has(.sectioncatheader)').remove();
        // suppression du <br>
        $('.sectioncatheader br:first').remove();
    }

    var navbar = $('.navbar').first().html();
    $('.sectionsubcatlist').remove();
    $('.sectiontbarea').remove();
    $('.sectioncatheader .PBSTitle').remove();

    var nbCols = $('.datatbl tr:first > td').length;
    if (window.console) console.log ('nbCols', nbCols);
    $('.viewtbl td:has(.sectiontb):first').attr('colspan',nbCols);
    var navNumbers = $('.viewtbl tr:has(.sectiontb):first').detach();
    $('.datatbl').prepend(navNumbers);

    if (navbar && oxcell.length>1) {
        $('<div/>', {
            'class': 'navbar',
            html: navbar
        }).appendTo('.sectiontb');
        $('.sectiontb').css('float','right');
    } else {
        $('.sectiontb').parentsUntil('tbody').remove();
    }

    var colorZone='#E6E6E6;',
    testColorZone;

    if (setting.data.categories.length<1 && firstParentLevel) {

        // Si pas de sous catégorie : deuxième appel Json puis construction du menu
        $.getJSON('ws/wsGetCategories.asp?CatID='+firstParentLevel+'&Mode=1&shopcart=1&sort=name&sortdir=1', function(data2) {
            buildMainHmenu (data2, 'levelTwo', setting.imgWidthLv2, setting.maxElementsLv2);
            nextStepLevel ();
        });

    } else if (setting.data.categories.length>0) {
        // sinon lancement direct de la construction du menu
        if (firstParentLevel>=setting.levelTwoThreshold) secondParentLevel=firstParentLevel;
        buildMainHmenu (setting.data, 'levelTwo', setting.imgWidthLv2, setting.maxElementsLv2);
        nextStepLevel ();
    }

    function nextStepLevel () {
        if (secondParentLevel) {
            $.getJSON('ws/wsGetCategories.asp?CatID='+secondParentLevel+'&Mode=1&shopcart=1&sort=position&sortdir=1', function(data3) {
                testColorZone = buildMainHmenu (data3, 'levelOne', setting.imgWidth, setting.maxElements);
                //  ( couleur si catégorie correspondante )
                if (testColorZone) colorZone=testColorZone;
                $('#levelTwoListContainer').css({ 
                    'border-top-color': colorZone
                });

                // (focus si page correspondante)
                $('#levelTwo'+setting.currentCatID).css({
                    'background-color':'white'
                });
            });

        }
    }

    $('#bodycolumn2').show();

    //correction des padding du design CSS
    $('.view').css({
        'padding' : 0
    });
    
    $('.sectiondata .sectioncatheader').css ({
        'padding' : 0
    })

    // clic sur image -> Animation
    $('.sectioncatheader img').bind('click', function() {
        if (oxcell.length) {
            var targetOffset = oxcell.eq(0).offset().top;
            $('html,body')
            .animate({
                scrollTop: targetOffset
            }, 1000);
        }
    });

    function buildMainHmenu (data, zoneId, imgWidth, maxElements) {

        //initialisation
        var items = [],
        numberOfItems = data.categories.length,
        containerZoneWidth=$('#bodyarea').width()-setting.CSSMargin,
                
        slideWidth=Math.round((containerZoneWidth-(setting.arrowSize*2))/maxElements),
        ulWidth = numberOfItems * slideWidth,
        currentPosition=0,
        animateFirst=false,
        catIndex=0,
        zoneWidth=maxElements*slideWidth,
        colorZone=null;

        //Création de l'HTML
        $.each(data.categories, function(key, val) {
            if (!val.imgfilename) val.imgfilename='Files/0/OxTransparent.gif';
            catIndex++;
            if ((val.id == setting.currentCatID) || (val.id == firstParentLevel)) {
                //catName=val.name;
                 
                if (catIndex>maxElements) {
                    currentPosition =catIndex-maxElements;
                    animateFirst=true;
                }
         
                if (val.description) {
                var expregDesc=new RegExp('#?[0-9A-Fa-f]{6}',"g"),
                testDesc = val.description.match(expregDesc);

                if (testDesc) colorZone = val.description;
                }
    
            }
            items.push('<li class="'+zoneId+'ListElements" id="'+zoneId
                + val.id + '"><a class="'+zoneId+'Link" href="' + val.url + '"><img src="' + val.imgfilename + '"/><span class="mainTxt">'
                + val.name + '</span></a></li>');
        });

        $('<div/>', {
            'id': zoneId+'ListMainContainer'
        }).prependTo('#bodycolumn2')
        .append('<div id="'+zoneId+'ListContainer"></div>');

        $('#'+zoneId+'ListContainer')
        .append('<div class="'+zoneId+'control" id="'+zoneId+'leftControl"></div>')
        .append ('<div id="'+zoneId+'ListSubContainer"></div>')
        .append('<div class="'+zoneId+'control" id="'+zoneId+'rightControl"></div>');

        $('<ul/>', {
            'id': zoneId+'ListZone',
            html: items.join('')
        }).css({
            'width':ulWidth
        }).appendTo('#'+zoneId+'ListSubContainer');

        // Mise en forme CSS
        $('#'+zoneId+'ListContainer').css({
            'width':containerZoneWidth
        });


        $('#'+zoneId+'ListSubContainer').css({
            'width':zoneWidth,
            'left':setting.arrowSize
        });

        $('.'+zoneId+'ListElements, .'+zoneId+'Link').css({
            'width':slideWidth
        });

        $('.'+zoneId+'Link img').css({
            'width':imgWidth
        });

        // alignement au centre si peu d'éléments
        if (numberOfItems<maxElements) {
            $('#'+zoneId+'ListZone').css({
                'margin' : '0 auto'
            });
        }

        //Cursors droite/Gauche et scrolling
        $('.'+zoneId+'control')
        .bind('click', function(){

            var maxOffset=numberOfItems-maxElements-currentPosition,
            rightOffset = (maxElements<maxOffset) ? maxElements : maxOffset,
            leftOffset = (maxElements<currentPosition) ? maxElements : currentPosition;

            currentPosition = ($(this).attr('id')==zoneId+'rightControl') ? currentPosition+rightOffset : currentPosition-leftOffset;

            animateControl(currentPosition);
            positionControl(currentPosition);
        })
        .bind('mouseover', function(){

            $(this).css('opacity',0.5);
        })
        .bind('mouseout', function(){

            $(this).css('opacity',1);
        });

        // déplacement des éléments
        function animateControl (pos) {

            $('#'+zoneId+'ListZone').animate({
                'marginLeft' : (slideWidth)*(-pos)
            });
        }
            
        //affichage des curseurs droite et/ou gauche
        function positionControl (pos) {
      
            (pos==0)? $('#'+zoneId+'leftControl').hide() : $('#'+zoneId+'leftControl').show();
            (pos>=(numberOfItems-maxElements))? $('#'+zoneId+'rightControl').hide() : $('#'+zoneId+'rightControl').show();
        }

        // offset initial
        function firstAnim () {
            if (animateFirst)  {
                animateControl (currentPosition);
                positionControl(currentPosition);
            } else {
                positionControl(0);
            }
        }

        firstAnim();

        var positionImgOffset=-Math.round((slideWidth-imgWidth)/4),
        textSize=parseInt($('.'+zoneId+'Link .mainTxt').css('fontSize')),
        textSizeZoom=textSize+setting.fontOffset,
        positionTxtOffset=-Math.round(setting.fontOffset/2);

        return colorZone;
    }

}

/***************************Panier dynamique*******************************/
function ajaxCartSubmiter (nProductID, strURLParams, showCartTemplate) {

    var shopCart=null;

    $.ajaxSetup({
        cache: false
    });

    $.getJSON('PBShoppingCart.asp?AjaxMode=1&'+strURLParams, function(data) {
        shopCart=data;
        showCart ();
    });

    function showCart () {

        moveToCart.prototype.htmlTemplate= showCartTemplate;

        var isThereImages = false;

        function spotImage (referer, element, only, defaultZone, defaultImage) {
            /* 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));
            
            if (imgRelated.moveInCart()) {
                isThereImages=true ;
            } else {
                localObject = "$(this).find('"+defaultZone+"').eq(0)";
                var btnRelated = new moveToCart(eval(localObject), defaultImage);

                if (btnRelated.moveInCart()) {
                    isThereImages=true ;
                }

            }
            });
            
        }
        //image de rempalcement
        var defaultImg = "Files/15269/addToCart/no-product.png";

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

        // no image

        if (!isThereImages) {
                          setDynamicCart (showCartTemplate);
        }
    }

}

function moveToCart (origin, url) {
    this.origin=origin;
    this.url=(!url)? null : url;
}

moveToCart.prototype.target= '#showCartBox';
moveToCart.prototype.moveInCart= function () {

    var domOrigin = $(this.origin),
        domTarget = $(this.target),
        isImage;

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

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

    if (!domOrigin.length || !domTarget.length || !isImage || isImage=="none")  return false;
        
    var offsetOrigin=domOrigin.offset(),
    offsetTarget=domTarget.offset();

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

    return true;
}

// affichage du mini-panier
function setDynamicCart (htmlTemplate) {

    if (!$('#maincontainer').length) return;

    function setCartCookie (Data) {

        var answer = cleanHtmlTags (Data);
        setCookie ('cartTemplateCookie', answer);
        cartTemplateCookie = answer;
        showCartInDocument ();
    }

    var cartTemplateCookie = getCookie('cartTemplateCookie');

    if (!cartTemplateCookie) {
        $.ajax({
            url: htmlTemplate,
            success: function(Data) {
                setCartCookie (Data);
            }
        });
    } else {
        showCartInDocument ();
    }

    function showCartInDocument () {

        var reg=new RegExp("QTYTotal=(\\d*)","g"),
        regAmount=new RegExp("SubTotalNet=(\\d*)","g"),
        chaine=getCookie('PCart'),
        nbItems=reg.exec(chaine),
        amount=regAmount.exec(chaine),
        items=0,
        totalCart=0;

        if (nbItems && nbItems.length>=1 && amount && amount.length>1) {
            items=parseInt(nbItems[1]);
            totalCart=convertToPrixe(amount[1], decimalType);
        }

        cartTemplateCookie = replaceFromTemplate (cartTemplateCookie, 'nbItems', items , true );
        cartTemplateCookie = replaceFromTemplate (cartTemplateCookie, 'cartAmount', totalCart , false );

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

// bouton continuer
function returnToSite() {
    $("#shopcartreturn").hide();
}

//*********************** nettoyage des balises inutiles ans un template*************************/
function cleanHtmlTags (htmlModel){

    var cleanHTML = {
        lineBreaks:new RegExp('\\r?\n|\\r',"g"),
        doctype:new RegExp('<!DOCTYPE[^>]*>',"gi"),
        head:new RegExp('<head[^>]*>(.*)</head>',"gi"),
        body:new RegExp('</?body[^>]*>',"gi"),
        html:new RegExp('</?html[^>]*>',"gi"),
        script:new RegExp('<\\s*script.*?>(.*?)<\\/\\s*?script[^>\\w]*?>',"gi"),
        noscript:new RegExp('<\\s*noscript.*?>(.*?)<\\/\\s*?noscript[^>\\w]*?>',"gi")
    }

    htmlModel=htmlModel.replace(cleanHTML.lineBreaks, "");
    htmlModel=htmlModel.replace(cleanHTML.doctype, "");
    htmlModel=htmlModel.replace(cleanHTML.head, "");
    htmlModel=htmlModel.replace(cleanHTML.body, "");
    htmlModel=htmlModel.replace(cleanHTML.html, "");
    htmlModel=htmlModel.replace(cleanHTML.script, "");
    htmlModel=htmlModel.replace(cleanHTML.noscript, "");

    return htmlModel;
}

/***************gestion des zeros dans les prix****************/
function convertToPrixe (price, decimal) {

    if (!decimal) decimal=',';
    var amount = parseFloat(price)/100;
    amount = amount.toString();
    amount =  (decimal==',')?  amount.replace('.', ',') : amount;

    var expregTest=new RegExp(decimal+'\\d\\d',"g"),
    expregTest2=new RegExp(decimal,"g"),
    test = amount.match(expregTest),
    test2 = amount.match(expregTest2);

    if  (!test && test2) {
        amount += '0';
    }

    return amount;
}

/******************gestionnaire de template*************************/
function replaceFromTemplate (htmlModel, tag, value, recursive) {
    var reg = {};

    if (recursive) {

        reg = {
            expression:new RegExp("\\{"+tag+"\\s*\\[([^\\}|\\]]*)\\]\\s*\\[([^\\}|\\]]*)\\]\\s*\\[([^\\}|\\]]*)\\]\\}", "g"),
            tagValue:new RegExp("#"+tag, "g")
        }

        htmlModel=htmlModel.replace(reg.tagValue, value);
        var doResult=reg.expression.exec(htmlModel);
        if (value>2) value=2;
        htmlModel=htmlModel.replace(reg.expression,doResult[value+1]);

    } else {

        reg = {
            tagValue:new RegExp("{"+tag+"}", "g")
        }
        htmlModel=htmlModel.replace(reg.tagValue,value);
    }

    return htmlModel;
}


/****************************idées********************************/
function customItem () {
    $('.sectiondata').css('visibility','hidden');
    if ($('#customTags').length)  customTags ();
    if ($('.itemdetail #idees').length)  showIdeas ();
    $('.sectiondata').css('visibility','visible');

    // récupération des produits associés.
    function showIdeas () {

         // si "idéee", on supprime prix, bouton acheter, etc...
        $('.PBItemPrice').closest('tr').remove();
        $('.PBRelPdtTable').closest('.sectiondata').remove();
        $('.PBUpsellTable').closest('.sectiondata').remove();
        $('table:has(.stock1):last').remove();

        /*/ On replace le titre
        $('.sectiondataarea .PBLongTxt').eq(0).prepend('<span class="PBMainTxt">'+OxPdtName+'</span>');
        */
    
        var PdtID = $('input[name="HVProductID"]').val();

        if (!PdtID) return;
        // Lancement des cross sales
        $.getJSON('ws/wsGetRelatedProducts.asp?PdtID='+PdtID+'&RelType=3&shopcart=1', function(data2) {
            buildCrassSalesVmenu (data2);
        });

        //Construction de la liste des cross sales dans un onglet.
        function buildCrassSalesVmenu (data) {
            //initialisation
            if (!data.crosssell && !data.upsell) return;
            var items = [],
            i=0;

            //Création de l'HTML
            function createItem (val) {

                var item='<li class="relatedProducts"><a class="relatedLink" href="javascript:AddToCart(' +
                val.id + ')" style="background-image:url('+val.smallimg+')"><span class="relatedAddTo">Ajouter</span></a><span class="relatedText">'
                +val.name+'</span><a href="'+val.url+'" class="relatedInfo"><span class="relatedMoreInfos">Plus d\'infos</span></a><span class="relatedPrice PBItemPrice">'+convertToPrixe (parseFloat(val.price)*100)
                +'&nbsp;EUR</span></li>';

                return item;
            }
            
            if (data.crosssell) {

                $.each(data.crosssell, function(key, val) {
                    if (val.buybtn) {
                        items.push( createItem (val) );
                        i++;
                    }
                });
            }

            if (data.upsell) {

                $.each(data.upsell, function(key, val) {
                    
                        items.push( createItem (val) );
                        i++;
                    
                });
            }

            $('<ul/>', {
                'id': 'crossListZone',
                html: items.join('')
            }).appendTo('#idees');

            // Mise en forme CSS

            $('.imgcontainer').css({
                'float': 'none',
                'position':'absolute',
                'right':22,
                'top':100
            });


        }
    }


    //Création des onglets
    function customTags () {

        if (!$('#customTags').length) return;
        var myTabs = new customCarrousel ();
        myTabs.target = '#customTags';
        myTabs.autoSlide = false;
        myTabs.crossTransition = false;
        myTabs.htmlTemplate = '<tbody><tr><td><list/></td></tr><tr><td><zone/></td></tr></tbody>';
        myTabs.carrousel(); //lancement de la fonction.
    }
}



function customCarrousel () { }

// définition des valeurs par défaut
customCarrousel.prototype.target = '#carrousel';
customCarrousel.prototype.urlParam = 'tab';
customCarrousel.prototype.autoSlide = true;
customCarrousel.prototype.crossTransition = true;
customCarrousel.prototype.autoHeight = false;
customCarrousel.prototype.autoWidth = false;
customCarrousel.prototype.timeToSlide = 3000;
customCarrousel.prototype.slideSpeed = 500;
customCarrousel.prototype.stopAfterFirstClick = false;
customCarrousel.prototype.htmlTemplate = '<tbody><tr><td class="leftColumn"><zone/></td><td class="rightColumn"><list/></td></tr></tbody>';
customCarrousel.prototype.order = ['tab', 'zone'];
customCarrousel.prototype.tabContainer = 'ul';
customCarrousel.prototype.tabLister = 'li';
customCarrousel.prototype.zIndex = 10;
customCarrousel.prototype.carrousel = function () {

    if (!$(this.target).length) return;
    var tags =[],
    zone=[],
    x=0,
    y=0,
    i=1,
    me=this;

    $(this.target).css({
        'position':'relative'
    });

    // récupération des élemetns du webBlock
    $(this.target+ ' > tbody > tr').each(function () {
        var thisElement = $(' > td', this);

        var thisTag = thisElement.eq(me.order.indexOf("tab")).html(),
            thisZone = thisElement.eq(me.order.indexOf("zone"));

        if (me.autoWidth) x = Math.max (thisZone.width(), x);
         if (me.autoHeight) y = Math.max (thisZone.height(), y);

        tags.push('<'+me.tabLister+' class="tagListElements" ><a class="tagLinks tagLink'+i+'">'+thisTag + '</a></'+me.tabLister+'>');

        var tempZone = thisZone.wrapInner('<div class="tagsZone tagZone'+i+'" />'),
            tempZoneChild = tempZone.children().detach();
        zone.push(tempZoneChild);
        i++;
    });

    // Position initiale diaporama
    var numberOfItems = tags.length,
    timeOut,
    uriCourant = document.location.href,
    reg= new RegExp ("[&\\?]"+this.urlParam+"=(\\d+)", "g"),
    infosInUrl = reg.exec(uriCourant);

    var current = null,
    next = (infosInUrl && infosInUrl.length>0 && parseInt(infosInUrl[1])>0 && parseInt(infosInUrl[1])<=numberOfItems )? parseInt(infosInUrl[1]) : 1;

    //création HTML
    $(this.target).html(this.htmlTemplate);

    $(this.target+' zone:first').replaceWith('<div class="tagsListZone" style="position:relative;"></div>');
    $(this.target+' list:first').replaceWith('<'+this.tabContainer+' class="tagsList">'+tags.join('')+'</'+this.tabContainer+'>');
    for (var j=0; j<numberOfItems; j++) {
        $(me.target+' .tagsListZone:first').append(zone[j]);
    }


    $(this.target+' .tagsListZone:first .tagsZone')
    .css({
        'opacity': 0,
        'left':0,
        'top':0,
        'position':'absolute'
    })
    .hide();

    if (this.autoHeight) $(this.target+' .tagsListZone:first .tagsZone').height(y);
    if (this.autoWidth) $(this.target+' .tagsListZone:first .tagsZone').width(x);


    shadeIt (1);
    // fonction de transition fondu/enchainé :
    function shadeIt (speed) {

        if (current==next) return;
        if(current) {
            var currentZone = $(me.target+' .tagsListZone:first > .tagZone'+current);

            if (me.crossTransition) {
                currentZone.css({
                    'position':'absolute'
                });
            }

            currentZone.animate({
                'opacity': 0,
                'z-index':0
            }, {
                queue: !me.crossTransition,
                duration : speed,
                complete : function () {
                    $(this)
                    .css({
                    'position':'absolute'
                    })
                    .hide();
                    if (!me.crossTransition) showNext ();
                }
            });

            $(me.target+' .tagsList:first > .tagListElements > .tagLink'+current).removeClass('taghighlighted');
        }

        $(me.target+' .tagsList:first > .tagListElements > .tagLink'+next).addClass('taghighlighted');

        if (me.crossTransition || !current) showNext ();

        function showNext () {
            $(me.target+' .tagsListZone:first > .tagZone'+next)
            .show()
            .css({
                'z-index':1,
                'position':'relative'
            })
            .animate({
                'opacity': 1,
                'z-index':me.zIndex
            }, speed);
        }

        current=next;
    }


    // affichage zone correspondante lors du clic sur un élement du carousel
    $(document).delegate(this.target+' .tagsList:first .tagLinks','click', function(){
        var meAgain = $(this).attr('class'),
        reg = new RegExp ('tagLink(\\d+)', 'g');
        next = parseInt(reg.exec(meAgain)[1], 10);

        if (me.autoSlide) {
            clearTimeout (timeOut);
        }
        if (me.autoSlide && !me.stopAfterFirstClick)  {
            autoscroll();
        }
        shadeIt (me.slideSpeed);
    });

    //auto défilement
    function autoscroll () {
        timeOut = setTimeout (function () {
            next = (next<numberOfItems) ? next+1 : 1;
            shadeIt (me.slideSpeed);
            autoscroll();
        }, me.timeToSlide);
    }

    if (this.autoSlide) autoscroll ();
}


// récupération ID des boutons "Catalogue" et "Idées""
function getIdFromButton (id) {
    var url = $(id).attr('href');
    if (!url) return null;
    var reg=new RegExp("CatID=(\\d*)","g"),
    idInUrl=reg.exec(url);
    if (idInUrl.length>1) {
        return idInUrl[1];
    }
    else return null;
}

/*********Ajout de la classe scorderform à la page d'identification (Step2 sur toutes les pages du tunnel)************/

function addClassToUserLogin () {

    if (!OxPageName) return;
    if (OxPageName == "Identification") $('#maincontainer').addClass('scorderform');

}

///*********************Ajout nom de domaine dans Instructions spéciales********************/

function addClassToUserLogin () {
    var uriCourant = document.location.href,
    reg= new RegExp ("http://([^/]*)/", "g"),
    url = reg.exec(uriCourant)[1],
    specialInstructions = $('.scorderform textarea[name="SpecialInstructions"]');
    if (!specialInstructions.length) return;
    specialInstructions.html(url);
    specialInstructions.closest('td').hide();
}

/* Inversement de l'ordre des articles dans le panier */

function shopCartOrder () {
    if (!$('.scshopcart').length || !$('.cartline').length) return;
    
    var shopCartTable = $('.scshopcart .shopcarttable');
    shopCartTable.hide();

    var liCart = $('.scshopcart .shopcarttable .cartline').get(),
    licarthead = $('.scshopcart .shopcarttable .carthead'),
    cartsubtotal = $('.scshopcart .shopcarttable .cartsubtotal');
    liCart.reverse();

    shopCartTable.html("");
    shopCartTable.append(licarthead);
    $.each(liCart, function(){
        shopCartTable.append(this);
    });
    shopCartTable.append(cartsubtotal);
    shopCartTable.show(); 
}


/*********Ajout de la classe scorderform à la page d'identification (Step2 sur toutes les pages du tunnel)************/
function addClassToUserLogin () {

if (!OxPageName) return;
if (OxPageName == "Identification") $('#maincontainer').addClass('scorderform');

}

/* commande par ref*/

function fastInput () {

    if (!'#cmdbtn'.length) return;
    
    var fastInputState=getCookie('fastInput'),
        initialText=$('#cmdbtn').html(),
        newText = "Masquer l'interface de commande directe";

    $(document).delegate('#cmdbtn','click', function(){
        fastInputState=getCookie('fastInput');
        fastInputToggle (fastInputState);
    });
    
    $('#fastInput .QuickSKU').blur(function(){
        $('this').val('');
    });

    function fastInputToggle (fastInputState) {

        if (fastInputState=="enabled") {
            $('#cmdbtn').animate({'opacity': 0}, function () {
                       $(this).html(initialText).animate({'opacity': 1});
                   });
            $('#fastInput')
            .animate({'opacity': 0}, function() {
                   $(this).hide();
                   $('.catalogButton, .ideaButton, .accountButton').animate ({'top':'-64px'});
            });
           
            setCookie ('fastInput', "disabled");

        } else {
            $('#fastInput').css({'opacity': 0}).show();
             $('#cmdbtn').animate({'opacity': 0}, function () {
                    $(this).html(newText).animate({'opacity': 1});
                });
            $('.catalogButton, .ideaButton, .accountButton')
            .animate ({'top':'-39px'}, function() {
                $('#fastInput').animate({'opacity': 1});  
            });
            
            setCookie ('fastInput', "enabled");
        }
    }

    if (fastInputState=="enabled") {

        $('#cmdbtn').html(newText);
        $('#fastInput').show();
        $('.catalogButton, .ideaButton, .accountButton').css ({'top':'-39px'});
    }

}

// déplacmeent des block raccourcis dans homepage.
function moveContent (ActiveSite) {

    if (!($('.webblock').length &&  $('.blockcontainer').length)) return;

   
    $('#blockcoupon').appendTo($('#' + ActiveSite + 'Coupon'));
    $('#blockuserlogin').appendTo($('#' + ActiveSite + 'Login'));
    $('#blockuserlogout').appendTo($('#' + ActiveSite + 'Login'));
    $('#blocknewsletter').appendTo ($('#' + ActiveSite + 'News'));

    $('.blockcontainer').remove();

}


// suppression zone "information complémentaires"

function hideComplementaryZone () {
var uriCourant = document.location.pathname;

if (uriCourant!="/PBSCShippingForm.asp")  return;
$('div.sectiondata:has(textarea[name="ShipInstruction"]):last').hide();

}

// prix de la commande en haut des pages de confirmation.

function movePriceUp () {
    if (!($('.scpaymentform').length || $('.scconfirmform').length ) || !$('.carttotal').length ) return;
    
    var cartTotal= $('.carttotal').html();
    $('#btncheckout, #btncontinue').eq(0).after('<table class="shopcarttable upShopcartTable"><tbody><tr class="carttotal">' + cartTotal + '</tr></toby></table>');
    
}
