﻿//Variable indiquant le nombre de requetes en cours
var numRequetes = 0;

function AddProduct(pProductID, pQtite, pPrice, pLibelle) {
    //On ne joue qu'une requete a la fois
    if (numRequetes > 3)
        return;
        
    if (isPositif(pQtite)) {
        pQtite = parseInt(pQtite);

        AddItemToServerCart("/Pages/VirtualStore.aspx?operation=ADD&code_produit=" + pProductID + "&quantite=" + pQtite);
        AddItemToPortlet(pProductID, pQtite, pPrice, pLibelle);
        $('#panier_infos').jScrollPane({ scrollbarWidth: 9 });
        TagAddProduct(pProductID);
    }
    else {
        alert("La valeur saisie est incorrecte.");
    }
}

function AddProductToFavorite(pProductID, pControl) {
    //On ne joue qu'une requete a la fois
    if (numRequetes > 3)
        return;
    AddProductToFavoriteAlert(pControl);
    AddItemToServerCart("/Pages/VirtualStore.aspx?operation=ADDFAV&code_produit=" + pProductID + "&quantite=1");
    TagFavoriteProduct(pProductID);
}

function AddProductToFavoriteAlert(pControl) {
    $('<div class="pop-in-ajout-favoris"><div class="pop-in-ajout-favoris-content"><a href="#"><span">Produit ajouté</span></a></div></div>')
        .insertAfter(pControl)
        .fadeIn('slow', function() {
            $(this).delay(500).fadeOut('slow', function() {
                $(this).remove();
            });
        });
}


function RemoveProduct(pProductID, pQtite, pPrice, pLibelle) {
    //On ne joue qu'une requete a la fois
    if (numRequetes > 3)
        return;
        
    if (isPositif(pQtite)) {
        pQtite = "-" + parseInt(pQtite);

        AddItemToServerCart("/Pages/VirtualStore.aspx?operation=ADD&code_produit=" + pProductID + "&quantite=" + pQtite);
        AddItemToPortlet(pProductID, pQtite, pPrice, pLibelle);
        $('#panier_infos').jScrollPane({ scrollbarWidth: 9 });
    }
    else {
        alert("La valeur saisie est incorrecte.");
    }
}

function CheckQuantityChange(inputObject, pProductID, pPrice, pLibelle) {

    var newQty = inputObject.value;
    var oldQty = inputObject.oldvalue;
    var pQtite = newQty - oldQty;

    if (!validateInteger(newQty) || parseInt(newQty) < 0)
    {
        alert("La valeur saisie est incorrecte.");
        inputObject.value = oldQty;
        return;
    }

    if (!validateInteger(oldQty)) {
        
        alert("La valeur est incorrecte.");
        return;
    }
    if (pQtite != 0) {
        AddItemToServerCart("/Pages/VirtualStore.aspx?operation=ADD&code_produit=" + pProductID + "&quantite=" + pQtite);
        UpdtateItemToPortlet(pProductID, pPrice, pLibelle);
        $('#panier_infos').jScrollPane({ scrollbarWidth: 9 });

        inputObject.oldvalue = inputObject.value;
    }
}

function AddItemToServerCart(pURL) {
    /*$.get(pURL, { noCache: (new Date()).getTime() });*/
    numRequetes++;
    jQuery.ajax({
        url: pURL,
        type: "GET",
        dataType: "html",
        data: { noCache: (new Date()).getTime() },
        complete: function(res, status) {
            numRequetes--;
        }
    });
}

function AddItemToPortlet(pProductId, pQuantity, pPrixUnitaire, pLibelle) {
    var divPanier = document.getElementById("panier_infos");
    if (!divPanier) {
        var divPan = document.getElementById("ctl00_PlaceHolderMain_ucEchPortlets_pnlCart");
        var div = getChild(divPan, "DIV", 1);
        var br = getChild(div, "BR", 1);

        var newDiv = document.createElement("div");
        newDiv.id = "panier_infos";
        newDiv.className = "panier_scrollpane";
        newDiv.style.overflow = "auto";
        newDiv.innerHTML = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody></tbody></table>";
        div.insertBefore(newDiv, br);

        divPanier = document.getElementById("panier_infos");
    }

    var table = getChild(divPanier, "TABLE", 1);
    for (var i = 0; i < table.rows.length; i++) {
        var tr = table.rows[i];
        if (tr.nodeName == "TR" && tr.className != "sep") {
            var tdId = getChild(tr, "TD", 5);
            var inputId = getChild(tdId, "INPUT", 1);
            if (pProductId == inputId.value) {
                var tdQtity = getChild(tr, "TD", 2);
                var inputQtity = getChild(tdQtity, "INPUT", 1);
                var oldQtity = inputQtity.value;  
                var newQtity = new Number(oldQtity) + new Number(pQuantity);
                if (newQtity >= 0) {
                    inputQtity.value = newQtity;
                    var varStrong = getChild(tdId, "STRONG", 1);
                    var strPrice = getChild(varStrong, "SPAN", 1).innerHTML;
                    var numPrice = new Number(strPrice.substring(0, strPrice.length - 2));

                    var newPrice;
                    if (oldQtity == "0") {
                        newPrice = Math.round((new Number(pPrixUnitaire) * new Number(pQuantity)) * 100) / 100;

                    } else {
                        newPrice = Math.round((numPrice + (new Number(pPrixUnitaire) * new Number(pQuantity))) * 100) / 100;
                    }
                    
                    getChild(varStrong, "SPAN", 1).innerHTML = newPrice + " &euro;";

                    RefreshTotaux(pQuantity, newPrice - numPrice);
                }
                return true;
            }
        }
    }

    var tbody = getChild(table, "TBODY", 1);

    var libelle2 = pLibelle.replace("'", "&rsquo;");

    var montant = (Math.round((new Number(pPrixUnitaire) * new Number(pQuantity)) * 100) / 100);

    // Ligne produit
    var tr = document.createElement("tr");
    var td1 = document.createElement("td");
    td1.innerHTML = "<img onclick=\"RemoveProduct('" + pProductId + "','1','" + pPrixUnitaire + "','" + libelle2 + "');\" style=\"cursor:pointer;\" class=\"btnC\" src=\"/Style Library/ECH/Images/portlet/panier-moins.gif\" title=\"Enlever un article\" id=\"imgMoins\">";
    tr.appendChild(td1);
    var td2 = document.createElement("td");
    td2.className = "td_saisie";

    td2.innerHTML = "<input id=\"Quantity\" type=\"text\" class=\"saisie identifiant\" style=\"width:20px;\" value='" + pQuantity + "' onchange=\"CheckQuantityChange(this,'" + pProductId + "','" + pPrixUnitaire + "','" + libelle2 + "');\" onfocus=\"this.oldvalue = this.value;\" />"
    tr.appendChild(td2);
    var td3 = document.createElement("td");
    td3.innerHTML = "<img onclick=\"AddProduct('" + pProductId + "','1','" + pPrixUnitaire + "','" + libelle2 + "');\" style=\"cursor:pointer;\" class=\"btnC\" src=\"/Style Library/ECH/Images/portlet/panier-plus.gif\" title=\"Ajouter un article\" id=\"imgMoins\">";
    tr.appendChild(td3);
    var td4 = document.createElement("td");
    td4.innerHTML = "<span title=\"" + pLibelle + "\">" + pLibelle.substring(0, 13) + "...</span>";
    tr.appendChild(td4);
    var td5 = document.createElement("td");
    td5.style.textAlign = "right";
    td5.innerHTML = "<strong class=\"btnB\"><span>" + montant + " &euro;</span></strong><input type=\"hidden\" value=\"" + pProductId + "\"/>";
    tr.appendChild(td5);
    tbody.insertBefore(tr, tbody.firstChild);

    // Ligne vierge       
    var td = document.createElement("td");
    td.innerHTML = " ";
    var tr = document.createElement("tr");
    tr.className = "sep";
    tr.appendChild(td);
    tbody.insertBefore(tr, tbody.firstChild);

    RefreshTotaux(pQuantity, montant);
}

function UpdtateItemToPortlet(pProductId, pPrixUnitaire, pLibelle) {
    var divPanier = document.getElementById("panier_infos");
    if (!divPanier) {
        var divPan = document.getElementById("ctl00_PlaceHolderMain_ucEchPortlets_pnlCart");
        var div = getChild(divPan, "DIV", 1);
        var br = getChild(div, "BR", 1);

        var newDiv = document.createElement("div");
        newDiv.id = "panier_infos";
        newDiv.className = "panier_scrollpane";
        newDiv.style.overflow = "auto";
        newDiv.innerHTML = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody></tbody></table>";
        div.insertBefore(newDiv, br);

        divPanier = document.getElementById("panier_infos");
    }

    var table = getChild(divPanier, "TABLE", 1);
    for (var i = 0; i < table.rows.length; i++) {
        var tr = table.rows[i];
        if (tr.nodeName == "TR" && tr.className != "sep") {
            var tdId = getChild(tr, "TD", 5);

            var inputId = getChild(tdId, "INPUT", 1);
            if (pProductId == inputId.value) {
                var tdQtity = getChild(tr, "TD", 2);
                var inputQtity = getChild(tdQtity, "INPUT", 1);
                var oldQtity = new Number(inputQtity.oldvalue);  
                var newQtity = new Number(inputQtity.value);
                if (newQtity >= 0) {
                    inputQtity.oldvalue = inputQtity.value;
                    inputQtity.value = newQtity;
                    var varStrong = getChild(tdId, "STRONG", 1);
                    var strPrice = getChild(varStrong, "SPAN", 1).innerHTML;
                    var numPrice = new Number(strPrice.substring(0, strPrice.length - 2));

                    var newPrice = Math.round((new Number(pPrixUnitaire) * new Number(newQtity)) * 100) / 100;
                    getChild(varStrong, "SPAN", 1).innerHTML = newPrice + " &euro;";

                    RefreshTotaux(newQtity - oldQtity, newPrice - numPrice);
                }
                return true;
            }
        }
    }

    var tbody = getChild(table, "TBODY", 1);

    var libelle2 = pLibelle.replace("'", "&rsquo;");

    var montant = (Math.round((new Number(pPrixUnitaire) * new Number(newQtity)) * 100) / 100);

    // Ligne produit
    var tr = document.createElement("tr");
    var td1 = document.createElement("td");
    td1.innerHTML = "<img onclick=\"RemoveProduct('" + pProductId + "','1','" + pPrixUnitaire + "','" + libelle2 + "');\" style=\"cursor:pointer;\" class=\"btnC\" src=\"/Style Library/ECH/Images/portlet/panier-moins.gif\" title=\"Enlever un article\" id=\"imgMoins\">";
    tr.appendChild(td1);
    var td2 = document.createElement("td");
    td2.className = "td_saisie";

    td2.innerHTML = "<input id=\"Quantity\" type=\"text\" class=\"saisie identifiant\" style=\"width:20px;\" value='" + newQtity + "' onchange=\"CheckQuantityChange(this,'" + pProductId + "','" + pPrixUnitaire + "','" + libelle2 + "');\" onfocus=\"this.oldvalue = this.value;\" />"
    tr.appendChild(td2);
    var td3 = document.createElement("td");
    td3.innerHTML = "<img onclick=\"AddProduct('" + pProductId + "','1','" + pPrixUnitaire + "','" + libelle2 + "');\" style=\"cursor:pointer;\" class=\"btnC\" src=\"/Style Library/ECH/Images/portlet/panier-plus.gif\" title=\"Ajouter un article\" id=\"imgMoins\">";
    tr.appendChild(td3);
    var td4 = document.createElement("td");
    td4.innerHTML = "<span title=\"" + pLibelle + "\">" + pLibelle.substring(0, 13) + "...</span>";
    tr.appendChild(td4);
    var td5 = document.createElement("td");
    td5.innerHTML = "<strong class=\"btnB\"><span>" + montant + " &euro;</span></strong><input type=\"hidden\" value=\"" + pProductId + "\"/>";
    tr.appendChild(td5);
    tbody.insertBefore(tr, tbody.firstChild);

    // Ligne vierge       
    var td = document.createElement("td");
    td.innerHTML = " ";
    var tr = document.createElement("tr");
    tr.className = "sep";
    tr.appendChild(td);
    tbody.insertBefore(tr, tbody.firstChild);

    RefreshTotaux(newQtity, montant);
}

function RefreshTotaux(pQuantity, pPriceDelta) {
    var divTotaux = document.getElementById("ctl00_PlaceHolderMain_ucEchPortlets_pnlCart");
    var div = getChild(divTotaux, "DIV", 1);
    var p = getChild(div, "P", 1);

    // Votre panier contient :
    var spane = getChild(p, "SPAN", 1);
    spane.innerHTML = "Votre panier contient";

    // NbArticles
    var span = getChild(p, "SPAN", 2);
    var strong = getChild(span, "STRONG", 1);
    var spanNbArticles = getChild(strong, "SPAN", 1);
    var len = spanNbArticles.innerHTML.indexOf(" ", 0);
    var res = spanNbArticles.innerHTML.substring(spanNbArticles.innerHTML, len);
    var intRes = new Number(res) + new Number(pQuantity);
    if (intRes == "1") {
        spanNbArticles.innerHTML = intRes + " article";
    } else {
        spanNbArticles.innerHTML = intRes + " articles";
    }

    // Montant Total
    var span = getChild(p, "SPAN", 3);
    var strong = getChild(span, "STRONG", 1);
    var spanMontant = getChild(strong, "SPAN", 1);
    var strMontant = spanMontant.innerHTML.substring(0, spanMontant.innerHTML.length - 2).replace(",", ".");
    var newMontant = Math.round((new Number(strMontant) + new Number(pPriceDelta)) * 100) / 100;
    spanMontant.innerHTML = newMontant + " &euro;";

    //Dernier articles
    //var lblDernierArt = document.getElementById("ctl00_PlaceHolderMain_ucEchPortlets_ucEchPortletsPanier_lblDernierArt");
    var span = getChild(p, "SPAN", 4);
    var strong = getChild(span, "STRONG", 1);
    var lblDernierArt = getChild(strong, "SPAN", 1);
    lblDernierArt.style.display = "block";
}

function getChild(pSource, pBalise, pRang) {
    var resultat = null;
    if (pSource != null) {
        var i = 0;
        var rang = 0;
        while (rang < pRang && i < pSource.childNodes.length) {
            resultat = pSource.childNodes[i];
            if (resultat.nodeName == pBalise) {
                rang++;
            }
            i++;
        }
    }
    return resultat;
}

function TheQuantity(productID) {
    var val = $("#" + productID).val();
    var currentQte = parseInt(val);
    if (!validateInteger(val) || isNaN(currentQte) || currentQte < 1) {
        $("#" + productID).val(1);
    }
    return val;
}

function validateInteger(strValue) {
    var objRegExp = /(^-?\d\d*$)/;
    //check for integer characters
    return objRegExp.test(strValue);
}

function HandleBasketQtyEnter(inField, e, pProductID, pPrice, pLibelle) {
    var charCode;
    if (e && e.which) {
        charCode = e.which;
    }
    else if (window.event) {
        e = window.event; charCode = e.keyCode;
    }
    if (charCode == 13) {
        CheckQuantityChange(inField, pProductID, pPrice, pLibelle);
    }
}
