﻿String.prototype.trim = function() {
    return this.replace(/^\s*|\s*$/, "");
}
String.prototype.simplify = function() {
    return this.replace(/\s+/g, " ");
}

btnInitialPosition = 0;
// Create a cookie with the specified name and value.
function SetCookie(sName, sValue) {
    var d;
    date = new Date();
    if ('Panier,KPrix'.indexOf(sName) >= 0) {
        //date.setHours(date.getHours()+1);//Mr Schuler ne veut pas que le panier réside sur le pc du client plus longtemps que la session
        document.cookie = sName + "=" + escape(sValue) + "; path=/";
    }
    else {
        date.setDate(date.getDate() + 31);
        document.cookie = sName + "=" + escape(sValue) + "; expires=" + date.toGMTString() + "; path=/";
    }
}

// Retrieve the value of the cookie with the specified name.
function GetCookie(sName) {
    // cookies are separated by semicolons
    var aCookie = document.cookie.split(";");
    //a=lqsdjf.qsdjf.value;
    for (var i = 0; i < aCookie.length; i++) {
        // a name/value pair (a crumb) is separated by an equal sign
        var aCrumb = aCookie[i].split("=");
        if (aCrumb[0] != null) {
            //var nomChaine=aCrumb[0].replace(" ", "");
            var nomChaine = aCrumb[0];
            if (sName == nomChaine) {
                var chaine = aCookie[i].replace(sName + "=", "");
                return unescape(chaine);
            }

            if (" " + sName == nomChaine) {
                var chaine = aCookie[i].replace(" " + sName + "=", "");
                return unescape(chaine);
            }
        }
    }

    // a cookie with the requested name does not exist
    return null;
}


// Delete the cookie with the specified name.
function DelCookie(sName) {
    var sValue = "";
    document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}


function displayCGV() {
    var div = $$('.divCGVBackground')[0];
    div.style.display = 'block';
    var flash = $$('#flashContainer')[0];
    flash.style.display = 'none';
    scroll(0, 0);
}

function closeCGV() {
    var div = $$('.divCGVBackground')[0];
    div.style.display = 'none';
    var flash = $$('#flashContainer')[0];
    flash.style.display = 'block';
}
function btnColor(obj, contexte) {
    var color = "transparent";
    var onColor = "#A33400";
    //onColor = "#33FF33";
    var elts = obj.getElementsByTagName('b');
    //var elts = obj.getElementsBySelector('b');
    if (contexte == 'out') {
        for (var i = 1; i < elts.length; i++) {
            if (elts[i].className != 'niftycorners') {
                elts[i].style.backgroundColor = color;
            }
        }
        obj.style.backgroundColor = color;
    } else {
        for (var i = 1; i < elts.length; i++) {
            if (elts[i].className != 'niftycorners') {
                elts[i].style.backgroundColor = onColor;
            }
        }
        obj.style.backgroundColor = onColor;
    }

}

function getElementsByClassName(className, tag, elm) {
    var testClass = new RegExp("(^|s)" + className + "(s|$)");
    var tag = tag || "*";
    var elm = elm || document;
    var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
    var returnElements = [];
    var current;
    var length = elements.length;
    for (var i = 0; i < length; i++) {
        current = elements[i];
        if (testClass.test(current.className)) {
            returnElements.push(current);
        }
    }
    return returnElements;
}

function Replace(Chaine, Motif, Remplacement) {
    var tb;
    tb = Chaine.split(Motif);
    return tb.join(Remplacement);
}

function toMonnaie(Montant) {
    var sep;
    sep = (1 / 2).toString().substr(1, 1);
    Montant = "" + Montant;
    Montant = Montant.replace(",", sep);
    return Math.round(Montant * 100) / 100;
}

function formatMonnaie(chaine) {
    var c, sep;
    sep = (1 / 2).toString().substr(1, 1);
    c = chaine.toString().split(sep);
    if (c.length > 1) {
        if (c[1].length < 2) { c[1] += '0' }
        else {
            c[1] = c[1].substring(0, 2);
        }
        //return Math.round(c.join(sep)*100)/100;
        return c.join(sep);
    }
    else {
        chaine += sep + '00';
        //return Math.round(chaine*100)/100;
        return chaine;
    }
}
function formatDate(date) {
    var chaine = date.getDate() + '/' + parseInt(parseInt(date.getMonth()) + 1) + '/' + date.getFullYear();
    var tb = chaine.split('/');
    tb[0] = AjouteZeroGauche(tb[0], 2)
    tb[1] = AjouteZeroGauche(tb[1], 2)
    chaine = tb.join('/');
    return chaine;
}
function AjouteZeroGauche(chaine, longueur) {
    var Iteration, i;
    Iteration = longueur - chaine.length;
    for (i = 0; i < Iteration; i++) {
        chaine = '0' + chaine;
    }
    return chaine;
}


function checkEmail(emailAddr) {
    // Cette fonction vérifie la bon format d'une adresse e-mail.
    // Comme :
    // user@domain.com ou user.perso@domain.com

    var i;

    // Recherche de @
    i = emailAddr.indexOf("@");
    if (i == -1) {
        return false;
    }

    // Séparation du nom de l'utilisateur et du nom de domaine.
    var username = emailAddr.substring(0, i);
    var domain = emailAddr.substring(i + 1, emailAddr.length)

    // Recherche des espaces au début du nom de l'utilisateur.
    i = 0;
    while ((username.substring(i, i + 1) == " ") && (i < username.length)) {
        i++;
    }
    // Les enlève s'il en trouve.
    if (i > 0) {
        username = username.substring(i, username.length);
    }

    // Recherche d'espaces à la fin du nom de domaine.
    i = domain.length - 1;
    while ((domain.substring(i, i + 1) == " ") && (i >= 0)) {
        i--;
    }
    // Les enlève s'il en trouve.
    if (i < (domain.length - 1)) {
        domain = domain.substring(0, i + 1);
    }

    // Vérifie que le nom de l'utilisateur et du domaine ne soit pas vide.
    if ((username == "") || (domain == "")) {
        return false;
    }

    // Vérifie s'il n'y a pas de caractères interdits dans le nom de l'utilisateur.
    var ch;
    for (i = 0; i < username.length; i++) {
        ch = (username.substring(i, i + 1)).toLowerCase();
        if (!(((ch >= "a") && (ch <= "z")) ||
			((ch >= "0") && (ch <= "9")) ||
			(ch == "_") || (ch == "-") || (ch == "."))) {
            return false;
        }
    }

    // Vérifie s'il n'y a pas de caractères interdits dans le nom de domaine
    for (i = 0; i < domain.length; i++) {
        ch = (domain.substring(i, i + 1)).toLowerCase();
        if (!(((ch >= "a") && (ch <= "z")) ||
			((ch >= "0") && (ch <= "9")) ||
			(ch == "_") || (ch == "-") || (ch == "."))) {
            return false;
        }
    }

    // Ajouter ci-dessous de nouveaux noms de domaine.

    //
    var aSuffix = new Array("com", "net", "int", "aero", "biz", "museum", "name", "info", "coop", "pro", "eu", "edu", "org", "gov", "gouv", "mil", "bj", "dz", "de", "ad", "be", "ca", "bf", "bi", "cm", "cf", "cg", "cd", "ci", "dj", "fr", "ga", "gp", "gf", "lu", "mg", "ml", "ma", "mq", "mr", "mc", "nc", "pf", "re", "pm", "sn", "ch", "td", "tf", "tn");
    var bFoundSuffix = false;
    i = 0;
    while (i < aSuffix.length) {
        if (("." + aSuffix[i]) == domain.substring(domain.length - aSuffix[i].length - 1, domain.length)) {
            return true;
        }
        i++;
    }
    // Si le nom de domaine est inconnu  : return false
    return false;

}

function emailOK(emailAddr) {
    if (!(checkEmail(emailAddr))) {
        alert("Merci de vérifier votre adresse e-mail. Elle n\'est pas dans le bon format.");
    }
}

var arrControlInError = new Array();

var controlAttributes = {
    obligatoire: false,
    valide: 0
}

function extendInput() {
    var maindoc = window.parent.mainFrame.document;
    var form = maindoc.getElementById('Form1');
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        var elt = inputs[i];
        if (elt.type.toLowerCase() == 'text') {
            //Object.extend(elt,controlAttributes);
            Object.prototype.obligatoire = false;
            Object.prototype.valide = "";
            if (elt.attributes["obligatoire"] != 'undefined') {
                //Object.extend(elt,controlAttributes);
                elt.obligatoire = elt.getAttribute("obligatoire") == 'true' ? true : false;
                elt.valide = elt.getAttribute("valide");
            }
        }
    }
}

function formAddressValidation() {
    var result = true;
    var maindoc = window.parent.mainFrame.document;
    var form = maindoc.getElementById('Form1');
    try {
        var phutil = $('phAdresseUtilisateur');
        var prefixeUtil = phutil.getAttribute("prefixe");
        var phLivr = $('phAdresseLivraison');
        var prefixeLivr = phLivr.getAttribute("prefixe");
    } catch (error) {

    }
    arrControlInError = new Array();
    for (var i = 0; i < form.elements.length; i++) {
        var elt = form.elements[i];
        try {
            if (elt.type == "text" && (elt.id.substring(0, 6) == (prefixeUtil + '_') || elt.id.substring(0, 6) == (prefixeLivr + '_'))) {
                if (elt.id.substring(6) == 'mail') {
                    if (!checkEmail(elt.value)) {
                        elt.valide = "1";
                        arrControlInError[arrControlInError.length] = elt;
                    }
                }
                if (elt.id.substring(6) == 'CodePostal') {
                    if (elt.value.length < 5) {
                        elt.valide = "1";
                        arrControlInError[arrControlInError.length] = elt;
                        result = false;

                    }
                }
                if (elt.obligatoire == true && elt.valide == "") {
                    if (elt.value.trim() == '') {
                        result = false;
                        arrControlInError[arrControlInError.length] = elt;
                    }
                    else {
                        elt.valide = "100";
                    }
                }
            }
        }
        catch (error) {
            continue;
        }
    }

    return result;
}


function AdresseSerialize() {
    var result = "";
    var maindoc = window.parent.mainFrame.document;
    var form = maindoc.getElementById('Form1');
    for (var i = 0; i < form.elements.length; i++) {
        var elt = form.elements[i];
        //        try{
        if (elt.type == "text" && (elt.id.substring(0, 6) == '_ctl0_' || elt.id.substring(0, 6) == '_ctl1_')) {
            var detail = elt.id.substring(6) + sepCol + elt.value;
            result += result == "" ? detail : sepRow + detail;
        }
        //        } catch(error) {
        //            continue;
        //        }
    }
    alert(result);
    return result;
}

function enregistreCommentaire() {
    var maindoc = window.parent.mainFrame.document;
    var form = maindoc.getElementById('Form1');
    for (var i = 0; i < form.elements.length; i++) {
        var elt = form.elements[i];

    }
}

function envoyer(typeEnvoi) {
    /*if(typeEnvoi=='Valider'){
    enregistreCommentaire();
    }*/
    var maindoc = window.parent.mainFrame.document;
    var etape = maindoc.getElementById('etape').value;
    var form = maindoc.getElementById('Form1');
    if (formAddressValidation()) {
        //    var adresse=AdresseSerialize();
        //    SetCookie('Coordonnees',adresse);
        form.action = '/VisuCommande.aspx?requestType=' + etape + '&typeEnvoi=' + typeEnvoi;
        form.submit();
    } else {
        showWhatsWrong();
    }
}

function showWhatsWrong() {
    for (var i = 0; i < arrControlInError.length; i++) {
        var elt = arrControlInError[i];
        if (elt.className != 'inError') {
            //si elt.className=='inError' alors on écraserait la sauvegarde faite auparavant
            //ça se produit quand par exemple, on signale le controle en erreur puis que l'utilisateur revalide quand même
            //après , quand il revient sur la zone, elle est constamment en erreur.
            elt.cssClass = elt.className; //Le fait de déclarer l'attribut cssClass ajoute cet attribut à l'objet
        }
        elt.className = 'inError';
        elt.onfocus = reset;
    }
}

function reset(e) {
    if (!e) var e = window.event;
    //var elt=e.originalTarget;
    var elt = e.srcElement;
    elt == null ? elt = e.originalTarget : elt = elt;
    elt.className = elt.cssClass;
    elt.valide = "";
}



function dupliquer() {
    var maindoc = window.parent.mainFrame.document;
    var form = maindoc.Form1;
    var phutil = $('phAdresseUtilisateur');
    var prefixeUtil = phutil.getAttribute("prefixe");
    var phLivr = $('phAdresseLivraison');
    var prefixeLivr = phLivr.getAttribute("prefixe");
    for (var i = 0; i < form.elements.length; i++) {
        var elt = form.elements[i];
        try {
            if (elt.type == "text" && (elt.id.substring(0, 6) == prefixeUtil + "_")) {
                var text = prefixeLivr + ':' + elt.id.substring(6);
                text = form.elements[text];
                text.value = elt.value;
            }
        } catch (error) {
            continue;
        }
    }
}



function numberOfBox(obj) {
    //try {
        var PCObj = $$('input.hfPromoCadeau')[0];
        var jsonPC =null;
        if (PCObj.value!=''){
            jsonPC = PCObj.value.evalJSON();
        }
        var quantity = toMonnaie(obj.value);
        var articleObj = $$('input.hfArticle')[0];
        var jsonArticle = articleObj.value.evalJSON();
        var priceForBigQuantity = toMonnaie(jsonArticle.priceForBigQuantity);
        var bigQuantity = toMonnaie(jsonArticle.bigQuantity);
        var sellingCode = jsonArticle.sellUnitType;
        var montant = $$('input.amount')[0];
        var ecotaxIncluded = jsonArticle.ecotaxIncluded;
        var publicPrice = jsonArticle.publicPrice;
        var quantiteEntiere = 0;
        var quantiteRestante = 0;
        
        if (jsonArticle.ecotaxe != null) {
            if (ecotaxIncluded) {

            } else {
                publicPrice = publicPrice + jsonArticle.ecotaxe.prix;
            }
        }

        if (jsonPC != null && jsonPC.freeReference == jsonPC.Reference) {
        //cas: réduction de nombre sur une référence : XAchetes pour Y euros
            var quantiteTotale=jsonPC.quantity+jsonPC.freeQuantity; //Récupère le nombre donnant droit à réduction
            quantiteEntiere = parseInt(quantity / quantiteTotale); //Combien de multiples
            quantiteRestante = quantity - (quantiteEntiere*quantiteTotale);//Ce qui reste au prix public
            if (quantiteEntiere > 0) {
                var mtUnitaireReduit=0;
                if (jsonPC.discountAmount > 0) {
                    //C'est une remise en montant
                    mtUnitaireReduit=publicPrice-jsonPC.discountAmount; //prix unitaire de l'article à prix réduit
                } else {
                    //c'est une remise en %
                    var mtRemise=Math.round(Math.round((jsonPC.discountPercent/100*publicPrice)*100)/100*100)/100; //Calcul de la remise
                    mtUnitaireReduit = publicPrice - mtRemise; //prix unitaire de l'article à prix réduit
                }
                
                var mtPromoCadeau = (jsonPC.quantity * publicPrice + jsonPC.freeQuantity * mtUnitaireReduit) * quantiteEntiere; //montant des articles bénéficiant d'un prix global réduit
                var mtQteRestante = quantiteRestante * publicPrice;
                montant.value = formatMonnaie(mtPromoCadeau + mtQteRestante) + " €";
                return;
            }
        }
        
        
        
        var packValue = toMonnaie(jsonArticle.qtyForPackage1);
        if (packValue == 0) packValue = 1;
        var nbOfBox = quantity / packValue;
        nbOfBox = Math.ceil(nbOfBox);

        var qtyToSell = Math.round(1000 * nbOfBox * packValue) / 1000;

        if (sellingCode != 1) {
            var boxObj = $$('input.nbOfBox')[0];
            var packObj = $$('input.hfPackaging')[0];    
            if(boxObj!=null) boxObj.value = nbOfBox;
            
            var qtyToSellObj = $$('input.quantityToSell')[0];
            if (qtyToSellObj!=null) qtyToSellObj.value = qtyToSell;

            montant.value = formatMonnaie(Math.round(publicPrice * qtyToSell * 100) / 100) + " €";
            
            if (sellingCode == '2' && qtyToSell >= bigQuantity) {
                montant.value = formatMonnaie(Math.round(priceForBigQuantity * qtyToSell * 100) / 100) + " €";
            }
        } else if (sellingCode == '1') {

            var boxObj = $$('input.rangeNbOfBox')[0];
            var packObj = $$('input.hfRangePackaging')[0];

            boxObj.value = nbOfBox;

            var qtyToSellObj = $$('input.rangeQuantityToSell')[0];
            qtyToSellObj.value = qtyToSell;
        
            montant.value = formatMonnaie(Math.round(priceForBigQuantity * qtyToSell * 100) / 100) + " €";
            
        }
        
    //} catch (err) {

   // }
    }
    function clearAddressForm() {
        var form=document.forms[0];
        form.reset();
        for (var i = 0; i < form.elements.length; i++) {
            var elt = form.elements[i];
            if (elt.name == 'btnCreate') {
                var a;
                a = 1;
                
            }
            if ("Genre,Nom,Prenom,Societe,Rue,Complement,CodePostal,Ville,Tel,Fax".indexOf(elt.className,0)>=0 && elt.className!='')
                elt.value = "";
        }
        
        //var elt = getElementsByClassName('operation','input')[0].value='9';
    }

    function verifSaisie() {
        var tab = $$('.tarifTransport input');
        for (var i = 0; i < tab.length; i++) {
            if (tab[i].checked) return true;
        }
        alert("Vous n'avez pas choisi de Mode de Transport");
        return false;
     }

    function loadSlideShowDiv() {
        var url = racine + 'slideshow.htm';
        var pars = '';

        var myAjax = new Ajax.Request(
			url,
			{
			    method: 'get',
			    parameters: pars,
			    onComplete: slideShowDiv_CallBack
			});
    }
    function slideShowDiv_CallBack(request) {
        var response = request.responseText;
        $('slide-show').innerHTML = response;
        init();
    }

    function getLocalites(zipCode) {
        var pays = $$('select.Pays')[0];
        
        var span = $$('span#tournette')[0];
        span.style.visibility = 'visible';
        var url = '/localite.aspx';
        var pars = 'ZipCode=' + zipCode + '&Pays=' + pays.value;

        var myAjax = new Ajax.Request(
			url,
			{
			    method: 'get',
			    parameters: pars,
			    onComplete: localites_CallBack
			});
    }

function localites_CallBack(request) {
    var response = request.responseText;
    var selectObj = $$('select.Ville')[0];
    selectObj.options.length = 0;
    var villes = new Array();
    villes = response.split("#");
    for (var i = 0; i < villes.length; i++) {
        selectObj.options[i] = new Option(villes[i]);
    }

    var span = $$('span#tournette')[0];
    span.style.visibility = 'hidden';
}

function synchronizeZipCode(selectObj) {
try{
    var zipCodeObj = $$('input.CodePostal')[0];
    var selectObj = $$('select.Ville')[0];
    var selectedValue = selectObj.options[selectObj.selectedIndex].text;
    var zipCode = selectedValue.substring(0, selectedValue.indexOf(" "));
    zipCodeObj.value = zipCode;
} catch (error) {

    }
}

function dupliquerLundi(){
    var tabH = $$('.HeureMinute');
    for (var i = 0; i < 4; i++) {
        for (var j = 4; j < 21; j+=4) {
            tabH[i + j].value = tabH[i].value;
        }
    }
}

function CGVAccepted(source, args) {
    args.IsValid = false;
    if (false) {
        var checkClass = 'checkCGV';
        var check = $$('.' + checkClass)[0].firstChild;
        if (check.checked) {
            args.IsValid = true;
            return;
        } else {
            args.IsValid = false;
            return;
        }
    }
}

function postForm(checkClass,action) {
    var customValidator = $$('.' + checkClass)[0].parentNode.childNodes[5];
    var check=$$('.' + checkClass)[0].firstChild;
    if (check.checked) {
        customValidator.style.color = 'transparent';
        document.aspnetForm.action = action;
        return true;
    } else {
        customValidator.style.color = '#FF0000';
        document.aspnetForm.action = "";
    }
}

function setOrderStatus(orderId) {
    var url = '/CMCIC_Ordered.aspx';
    var pars = 'orderId=' + orderId;

    var myAjax = new Ajax.Request(
			url,
			{   asynchronous:false,
			    method: 'get',
			    parameters: pars,
			    onComplete: orderStatus_CallBack
			});

    return true;
}

function orderStatus_CallBack(response) {

}

function sendComment(comment) {
    var url = '/orderComment.aspx';
    var pars = 'commentaire=' + comment;

    var myAjax = new Ajax.Request(
			url,
			{ asynchronous:true,
			    method: 'get',
			    parameters: pars,
			    onComplete: sendComment_CallBack
			});

    return true;
}

function sendComment_CallBack(response){
}


function redirectToSuccess(checkClass, recall) {
var check=$$('.' + checkClass)[0].firstChild;
if (check.checked) {
    if (recall!=null){
        document.location.href = '/commandeSuccess.aspx?recall=' + recall;
    }
    else{
        document.location.href = '/commandeSuccess.aspx?recall=0';
    }
}
}

function confirmAjoutArticle() {
    var hfConfirm = $$('input.hfConfirmAjoutArticle')[0];
    /*if (hfConfirm.value != "") {
        //alert(hfConfirm.value);
      }
    */
    var divContainer = $$('.rightDiv')[0].getElementsByClassName('boxContainer')[2];
    if (divContainer!=null){
        var divBody = divContainer.getElementsByClassName('boxContainer boxInnerContainer')[0];
        var scrollHeight = divBody.scrollHeight;
        
        divBody.style.height = (scrollHeight) * 1 + "px";
        divContainer.style.height = (scrollHeight + 50) * 1 + "px";
        divBody.style.overflow = "hidden";
        }

        if (hfConfirm.value != "") {
            //alert(hfConfirm.value);
            var divContainer = $$('.rightDiv')[0].getElementsByClassName('boxContainer')[2];
            //if (divContainer!=null){
            var divBody = divContainer.getElementsByClassName('boxContainer boxInnerContainer')[0];
            //new Effect.Pulsate(divBody.id, { pulses: 4, duration: 0.5 });
            //new Effect.Shrink(divBody.id);
            new Effect.Grow(divBody.id);
        }
    }

    
    function playEffect(btnClass, href) {
        setTimeout("new function() { document.location.href = '" + href + "'; }", 2000);
        var btn = $$('.' + btnClass)[0];
        var cell = btn.parentNode;
        var row = cell.parentNode;
        var firstCell = row.firstChild;
        var img = $$('.img' + btnClass)[0];
        goToBasket(img, 2.5);
    }

    function moveToBasket() {
        var img = $$('.article_RowImage')[0];
        goToBasket(img,0.8);

        
    }
    function goToBasket(img, duration) {
        var divContainer = $$('.rightDiv')[0].getElementsByClassName('boxContainer')[2];
        var divBody = divContainer.getElementsByClassName('boxContainer boxInnerContainer')[0];
        var scrollHeight = divBody.scrollHeight;
        var imgY = Position.cumulativeOffset(img)[1];
        var divBodyY = Position.cumulativeOffset(divBody)[1];
        var yCoord = divBodyY - imgY;
        var imgWidth = img.getWidth();
        var imgWidth2 = parseInt(imgWidth / 4);
        var imgHeight = img.getHeight();


        var styleTxt = 'width:' + imgWidth2 + 'px;' + 'height:' + imgHeight + 'px';
        var style2 = 'width:' + imgWidth + 'px;' + 'height:' + imgHeight + 'px';
        styleTxt = 'width:24px;';
        style2 = 'width:' + imgWidth + 'px;';
        //new Effect.Move(img.id, {x:650,y:yCoord,duration:0.35,mode:'relative'});
        //new Effect.Pulsate(img.id, { sync: true, pulses: 3 }),
        new Effect.Parallel([
            new Effect.Move(img.id, { sync: true, x: 650, y: yCoord, mode: 'relative' }),
            new Effect.Morph(img.id, { sync: true, style: styleTxt })
        ], {
            duration: duration
        });
    }

    function goTopOfPage() {
        posBtnTopOfPage();
        $$('#btnTopOfPage')[0].style.display = 'none';
        $$('#btnTopOfPage')[0].appear();
    }

    function posBtnTopOfPage() {
        var limiteY = $$('.footer')[0].cumulativeOffset()[1];
        var btn = $$('#btnTopOfPage')[0];
        var btnY = Position.cumulativeOffset(btn)[1];

        if (btnInitialPosition == 0) {
            btnInitialPosition = btnY + 100;
        }

        var pageHeight = document.viewport.getHeight();
        var scrollY = document.viewport.getScrollOffsets()[1];
        var btnTop = Math.max((pageHeight - parseInt(pageHeight / 2)) + scrollY, pageHeight);
        btnTop = Math.max((pageHeight - 150) + scrollY, pageHeight);
        btnTop = Math.max((pageHeight - parseInt(pageHeight / 2)) + scrollY, btnInitialPosition);
               
        if (scrollY + pageHeight / 2 < limiteY) {
            btn.style.top = btnTop + "px";
            btn.style.position = "absolute";
        } else {
            btn.style.top = limiteY + "px";
            btn.style.position = "absolute";
        }
        if (btnTop > limiteY) {
            //pour forcer la limite du top au footer : ne pas empiéter dans le footer
            btn.style.top = limiteY + "px";
            btn.style.position = "absolute";
        }
        
    }

function Rand_Tableau(tab_) {
    var i;
    var Num;
    var Nbr = tab_.length;
    var Tab = new Array();
    //-- Copie le contenu
    Tab = Tab.concat(tab_);
    //-- Lance la boucle
    while (Nbr > 0) {
        //-- Recup nombre aleatoire
        Num = Math.floor(Math.random() * Nbr);
        //-- 1 de moins a traiter
        Nbr--;
        //-- Stock l'element tire
        szTmp = Tab[Num];
        //-- Decalage les valeur du tableau
        for (i = Num; i < Nbr; i++)
            Tab[i] = Tab[i + 1]
        //-- Stock l'element tire en fin
        Tab[Nbr] = szTmp;
    }
    //-- On peut remettre dans l'ordre du tirage
    Tab.reverse();
    //-- Retourne resultat
    return (Tab);
}

function addQuantity(ctl) {
    var txtName = ctl.attributes['qtyName'];
    var form = document.forms['aspnetForm'];
    var txtBox = eval("document." + form.name + "." + txtName.value);
    var value = txtBox.value;
    value = parseFloat(value);
    value = value + 1;
    txtBox.value = value;
}

function minusQuantity(ctl) {
    var txtName = ctl.attributes['qtyName'];
    var form = document.forms['aspnetForm'];
    var txtBox = eval("document." + form.name + "." + txtName.value)
    var value = txtBox.value;
    value = parseFloat(value);
    value = value - 1;
    value = Math.max(value,1);
    txtBox.value = value;
}

function lotControl(total) {
    var form = document.forms['aspnetForm'];
    var subTotal = 0;
    for (var i = 0;i<form.elements.length; i++) {
        var elt = form.elements[i];
        
        if (elt.className!=null && elt.className == 'itemLot_Select') {
            subTotal += parseInt(elt.value);
        }
    }
    if (total != subTotal) {
        alert("Les quantités sélectionnées ne font pas " + total);
        return false;
    } else {
        return true;
    }
}

function popupPharmacist() {
    var codePharmacie = $$('input.compte_CodePharmacie')[0];
    initialPharmacist=codePharmacie.value;
    
    var popup = $$('div.popupPharmacist')[0];
    popup.style.display = 'block';
    var total = document.body.scrollHeight;
    popup.style.height = total + 'px';
    var flash = $$('#flashContainer')[0];
    flash.style.display = 'none';
    document.body.scrollIntoView(1);
    var div = $$('div.pharmacist_List')[0];
    div.innerHTML = "";
    //Nifty('div.pharmacist_Fond');
 }

 function closePopupPharmacist() {
     var flash = $$('#flashContainer')[0];
     flash.style.display = 'block';
     $$('div.popupPharmacist')[0].style.display = 'none';
 }

 function getPharmacists() {
     var objCodePostal = $$('input.pharmacist_codePostal')[0];
     var codePostal = objCodePostal.value;
     var url = '/ajaxPharmacists.aspx';
     var pars = 'dep=' + codePostal;
     var div = $$('div.pharmacist_List')[0];
     div.innerHTML = "";
     var myAjax = new Ajax.Request(
			url,
			{
			    method: 'get',
			    parameters: pars,
			    onComplete: pharmacists_CallBack
			});
}

function pharmacists_CallBack(response) {
    var list = response.responseText;

    var jsonList = list.evalJSON();

    var radioList="";
    var div = $$('div.pharmacist_List')[0];
    for (var i = 0; i < jsonList.length; i++) {
        var item = "<span class='pharmacist_itemRadio'><input type='radio' name='radioGroup' id='radioGroup' onClick='setPharmacist(this)' value='" + jsonList[i].identifiant + "'></span><span class='pharmacist_itemCodePostal'>" + jsonList[i].codePostal + "</span><span class='pharmacist_itemVille'>" + jsonList[i].ville + "</span><span class='pharmacist_itemOfficine'>" + jsonList[i].officine + "</span>";
        radioList+=radioList==""?item:"<br class='noFloat'/>" + item;
    }
    
    if (radioList == "") {
        div.innerHTML = "Aucun Résultat !";
    } else {
        div.innerHTML = radioList;
    }
}

function resetPharmacist() {
    var radioPharmacist = $$('input.radioPharmacist')[0];
    radioPharmacist.value = "";
    var codePharmacie = $$('input.compte_CodePharmacie')[0];
    codePharmacie.value = initialPharmacist;
    getPharmacist(codePharmacie);
    closePopupPharmacist();
}

function setPharmacist(radioBtn) {
    var radioPharmacist = $$('input.radioPharmacist')[0];
    if (radioBtn.checked){
        radioPharmacist.value = radioBtn.value;
    } else { radioPharmacist.value = "" };
    var codePharmacie = $$('input.compte_CodePharmacie')[0];
    codePharmacie.value = radioPharmacist.value;
    getPharmacist(codePharmacie);
}

function getPharmacist(obj) {
    var url = '/ajaxPharmacists.aspx';
    var pars = 'adherent=' + obj.value;

    var myAjax = new Ajax.Request(
			url,
			{
			    method: 'get',
			    parameters: pars,
			    onComplete: pharmacist_CallBack
			});
}

function pharmacist_CallBack(response) {
    var span = $$('span.compte_AdresseOfficine')[0];
    var adresse = "";
    adresse = response.responseText;
    span.innerHTML = adresse;
}

function filtreEnter(e) {
    return !isEnterKey(e);
}

function isEnterKey(e)  
 {  
    var evt = e || event;  
    return (evt.keyCode == 13);
}

function valideCoupon() {
    var doRequest=true;
    var textbox = $$('input.coupon_TextBox')[0];
    var url = '/valideCoupon.aspx';
    var pars = 'coupon=' + encodeURI(textbox.value);
    var div = $$('div.caddyContent_CouponMessage')[0];
    div.innerHTML = "";

    var hfJsonCoupon = $$('input.hfJsonCoupon')[0];
    var hfValue = hfJsonCoupon.value;
    if (hfValue != "") {
        jsonList = hfValue.evalJSON();
        for (var i = 0; i < jsonList.length; i++) {
            //var objCoupon = jsonList[i].evalJSON();
            var objCoupon = jsonList[i];
            if (objCoupon.identifiant.toLowerCase() == textbox.value.toLowerCase()) {
                doRequest = false;
                i = jsonList.length;
            }
        }
    }
    if (doRequest){
        var myAjax = new Ajax.Request(
			url,
			{
			    method: 'get',
			    parameters: pars,
			    onComplete: valideCoupon_CallBack
			});
    } else {textbox.value = "";}
}

function valideCoupon_CallBack(response) {
    if (response.responseText.indexOf("'statut':'OK'") >= 0) {
        var jsonResponse = response.responseText.evalJSON();
        var coupon = jsonResponse.coupon;
        var divCoupon = $$('div.couponList')[0];
        var textbox = $$('input.coupon_TextBox')[0];
        //addCoupon(textbox.value);
        addCoupon(coupon);
        displayCoupon();
        textbox.value = "";
    } else {
        var couponMessage = $$('div.caddyContent_CouponMessage')[0];
        couponMessage.innerHTML = response.responseText;
    }
}

function addCoupon(coupon) {
    var hfJsonCoupon = $$('input.hfJsonCoupon')[0];
    var hfValue = hfJsonCoupon.value;
    var jsonList = new Array;
    if (hfValue != "") {
        jsonList = hfValue.evalJSON();
    }
    jsonList[jsonList.length] = coupon;
    hfJsonCoupon.value = jsonList.toJSON();
}
/*
function addCouponOld(coupon) {

    var hfJsonCoupon = $$('input.hfJsonCoupon')[0];
    var hfValue = hfJsonCoupon.value;
    var jsonList=new Array;
    if (hfValue != "") {
        jsonList = hfValue.evalJSON();
     }
    jsonList[jsonList.length]='{"identifiant":'+ '"' + coupon + '"}';
    hfJsonCoupon.value = jsonList.toJSON();
}
*/
function displayCoupon() {
    var hfJsonCoupon = $$('input.hfJsonCoupon')[0];
    var hfValue = hfJsonCoupon.value;
    var jsonList = new Array;
    if (hfValue != "") {
        jsonList = hfValue.evalJSON();
    }

    var radioList = "";
    for (var i = 0; i < jsonList.length; i++) {
        var item = "";
        //var objCoupon = jsonList[i].evalJSON();
        var objCoupon=jsonList[i];
        item += "<div class='couponRow'>";
        item += "<div class='couponId'><span class='couponIdentifiant'>" + objCoupon.identifiant + "</span><span class='couponSummary'>" + objCoupon.Libelle.substring(0,25) + "...<img src='/image/info.png' width='22' title='" + objCoupon.Libelle.replace("'","&rsquo;") + "' /></span></div>";
        item += "<span class='coupon_item'>";
        var param = '"' + objCoupon.identifiant + '"';
        param = '"' + i + '"';
        item += "<img src='/image/Poubelle.png' id='checkGroup" + objCoupon.identifiant + "' onClick='deleteCoupon(" + param + ")' value='" + objCoupon.identifiant + "' class='couponDeleteImg couponDeleteImg" + objCoupon.identifiant + "'>";
        item += "</span>";
        item += "</div>";
        radioList += radioList == "" ? item : "<br class='noFloat'/>" + item;
    }
    var couponList = $$('div.couponList')[0];
    if (jsonList.length>0){
        couponList.style.display= "block";
    } else {
        couponList.style.display = "none";
    }
    couponList.innerHTML = radioList;
    return true;
}

function deleteCoupon(indiceCoupon) {
    var hfJsonCoupon = $$('input.hfJsonCoupon')[0];
    var hfValue = hfJsonCoupon.value;
    var jsonList = hfValue.evalJSON();
    jsonList[indiceCoupon] = null;
    jsonList = jsonList.compact();
    hfJsonCoupon.value = jsonList.toJSON();
    displayCoupon();
    if (hfJsonCoupon.value==""){
        var couponList = $$('div.couponList')[0];
        couponList.style.display = "none";
    }
}

function changeAddressDisplay(objPays) {
//Dans le cas d'adresses hors du territoire Français(qui inclut les dom-tom), il y a une saisie libre des 
    var typeOfDisplay = $$('input.hfTypeOfDisplay')[0];
    var submittedForDisplay = $$('input.submittedForDisplay')[0];

    var codePostal = $$('input.CodePostal')[0];
    codePostal.value = "";
    var objAttributes = codePostal.attributes["onchange"];
    var ville = $$('.Ville')[0];
    if (ville.tagName.toLowerCase() == 'select') {
        ville.options.length=0;
    }
    var parentVille = ville.parentNode;
    var parent = codePostal.parentNode;
    var typePays = "GF,GP,MQ,NC,PF,PM,RE,TF,WF,YT,FR".indexOf(objPays.value)<0?0:1;

    if (typePays==1 && typeOfDisplay.value != 'FR') {
        objAttributes.value = 'getLocalites(this.value)';
        changeNode(typePays, ville, parentVille, typeOfDisplay, "select");
    }
    if (typePays==0 && typeOfDisplay.value == 'FR') {
        objAttributes.value = '';
        changeNode(typePays, ville, parentVille, typeOfDisplay, "input");
    }
}

function changeNode(typePays,ville,parentVille,typeOfDisplay,typeOfNode) {
    parentVille.removeChild(ville);
    typeOfDisplay.value = typePays == 1 ? 'FR' : 'EX';
    var node = document.createElement(typeOfNode);
    /*var classAttribute = document.createAttribute("class");
    classAttribute.nodeValue = "Ville";
    node.setAttributeNode(classAttribute);*/
    node.setAttribute("class", "Ville");
    node.setAttribute("id", ville.id);
    node.setAttribute("name", ville.name);
    if (typePays == 1) {
        node.setAttribute('onblur', 'this.style.width="185px";synchronizeZipCode(this)');
        node.setAttribute('onchange', 'this.style.width="185px";synchronizeZipCode(this)');
        node.setAttribute('onclick', 'this.style.width="auto"');
    }
    var lastChild = parentVille.childNodes[parentVille.childNodes.length - 1];
    parentVille.insertBefore(node, lastChild);

}

function parrainageVerification() {
    var textbox = $$('.parrainage_area')[0];
    var valide = true;
    var arrMails = textbox.value.split('\n');
    for (var i = 0; i < arrMails.length; i++) {
        arrMails[i] = arrMails[i].simplify();
        arrMails[i] = arrMails[i].trim();
        if (arrMails[i] == "") {
            arrMails[i] = null;
        } else {
            if (!checkEmail(arrMails[i])) {
                alert("L'adresse ligne " + (i + 1) + " n'est pas valide !");
                valide = false;
            }
        }
    }
    arrMails=arrMails.compact();
    textbox.value = arrMails.join("\n");
    return valide;
    //for(var i=0;i<textbox)
}

function submitSearchForm() {
    $$('input.searchBox_btnSearch')[0].click();
}