﻿/// <reference path="jquery-1.2.6-intellisense.js"/>
/// <reference path="json2.js" />


function chooseWeightFromProductListing(btnChooseWeightId, inBasket) {
    var pid = getProductIDFromListingRow(btnChooseWeightId)

    chooseWeightSetupAndShow(btnChooseWeightId, inBasket, pid);
}

function getProductIDFromListingRow(btnAddItem_ControlID) {

    var productRow = $('#' + btnAddItem_ControlID).parents(".product_info_container");
    var pid = parseInt(productRow.attr("id"));
    return pid;
    
}

function chooseWeightFromReferential(addLnkId, inBasket) {
    var referentialCell = $('#' + addLnkId).parents(".product_info_container");
    var pid = referentialCell.find("*[ID$='hfProductId']").val();

    chooseWeightSetupAndShow(addLnkId, inBasket, pid);
}


/*
*
*/
function addAllPromoPopupToBasket() {
    var idList = document.getElementById('promopopupidlist');       
    
    if (idList) {
        
        var productList = idList.value;
        var itemList = productList.split('_');
        for (i = 0; i < itemList.length; i++) {
        
            var pid = itemList[i];
     
            var quantityBox = document.getElementById('qty_promopopup_' + pid);
            if (quantityBox) {
                if (parseFloat(quantityBox.value) > 0) {
      
                    var quantity = quantityBox.value;
                    var note = '';
                    var substitute = 0;

                    var params = { 'UseAmendmentBasket': UseAmendmentBasket(), 'ProductID': pid, 'Quantity': quantity, 'Note': note, 'DoNotSubstitute': substitute };
              
                    var jsonString = "{json: '" + JSON.stringify(params) + "'}";
                    var serviceURL = resolveURL("WebServices/BasketServices.asmx/AddItemToBasket");
                    $.ajax({
                        type: "POST",
                        url: serviceURL,
                        data: jsonString,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: OnItemAddedSuccess,
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            alert("There was an error trying to process the last operation."
            + "Error: " + errorThrown + "  TextStatus:  " + textStatus);
                        }
                    });
                    
                }
            }
        }
    }
    closePromoPopup();
}
function addItemToBasketDetailsPopup(pid) {
    var quantityBox = document.getElementById('qty_promopopup_' + pid);
   
    if (quantityBox) {

        if (parseFloat(quantityBox.value) > 0) {

            var quantity = quantityBox.value;
            var note = '';
            var substitute = false;

            var params = { 'UseAmendmentBasket': UseAmendmentBasket(), 'ProductID': pid, 'Quantity': quantity, 'Note': note, 'DoNotSubstitute': substitute };

            var jsonString = "{json: '" + JSON.stringify(params) + "'}";
            var serviceURL = resolveURL("WebServices/BasketServices.asmx/AddItemToBasket");
    
            $.ajax({
                type: "POST",
                url: serviceURL,
                data: jsonString,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnItemAddedSuccessPopup,
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("There was an error trying to process the last operation."
            + "Error: " + errorThrown + "  TextStatus:  " + textStatus);
                }
            });

        }
        else {
            alert('Please enter a quantity');
        }
    }

}
/*********************************
*
**********************************/
function showPromoItems(promoid, productid) {
    var modalPopup = $find("modalPopupPromotionBehavior");
    if (modalPopup != null) {

        modalPopup.show();

        var params = { 'PromotionID': promoid, 'ProductID': productid };

        var jsonString = "{json: '" + JSON.stringify(params) + "'}";
        var serviceURL = resolveURL("WebServices/PromotionPopup.asmx/GetQualifierProducts");
        $.ajax({
            type: "POST",
            url: serviceURL,
            data: jsonString,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: ShowPromoQualifiers
        });
    }
}
/********************************************
Executes on successful completion of the 
ItemAdded webservice
********************************************/
function OnItemAddedSuccessPopup(result, eventArgs) {
 
    //deserialize the JSON and use it to update the Mini Basket
    var miniBasketData = JSON.parse(result.d);

    if (miniBasketData == undefined) {
        return;
    }

    UpdateMiniBasket(miniBasketData);
    // change the "Add" function to "Update" function.
    $('#' + miniBasketData.ProductID).find("A[ID$='btnAddToBasket']").unbind("click");
    $('#' + miniBasketData.ProductID).find("A[ID$='btnAddToBasket']").bind("click", function(eventObject) {
        addItemToBasket(miniBasketData.ProductID);
        return false;
    });

    $('#' + "addbasket_" + miniBasketData.ProductID).attr("class", "update");
    $('#' + miniBasketData.ProductID).find("IMG[ID$='imgBasket']").css("display", "block");
    $('#' + miniBasketData.ProductID).find("A[ID$='btnAddToBasket']").attr("class", "update");
    
    // write the quantity to the cell beside the Trolley icon
    var quantity = quantity = $('#' + "qty_promopopup_" + miniBasketData.ProductID).val();

    //get the name of the page
    var productRow;
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

    productRow = $('#' + miniBasketData.ProductID);
 
    productRow.find("*[ID$='tbQuantity']").val(quantity);
    productRow.find("*[ID$='lblItemSelectedQuantity']").text(" x " + quantity);

   
  
    $('#' + "imgBasketpopup_" + miniBasketData.ProductID).css("display", "block");
    $('#' + "lblItemSelectedQuantitypopup_" + miniBasketData.ProductID).css("display", "block").text(" x " + quantity);

    // when an item has been added to the basket, it is then possible to add a note to that Item.
    $('#' + miniBasketData.ProductID).find("*[ID$='addNote']").unbind("click");
    $('#' + miniBasketData.ProductID).find("*[ID$='addNote']").bind("click", function(eventObject) {
        showAddNotePopup(miniBasketData.ProductID);
        return false;
    });

    // Remove the toolTip onmouseover for the addnote image
    $('#' + miniBasketData.ProductID).find("*[ID$='addNote']").removeAttr("onmouseover");

    // ----- Update referentials on page ----
    var productReferentials = $(".product_referential input[value$='" + miniBasketData.ProductID + "'], .product_referential_wrap input[value$='" + miniBasketData.ProductID + "']");
    productReferentials.parents(".product_info_container").find("IMG[ID$='imgInBasket']").css("display", "inline");


    //this does not need to be called as the items are added to the basket automatically
    //ActivateUpdateBasketButton();
    //__doPostBack('ctl00_ctl00_ctl00_cphContent_cphMain_cphMain_upnlBasketContent', '');

    ActivateUpdateBasketButton();
    
}
function ShowPromoQualifiers(result, eventArgs) {
    if (document.getElementById("specialPromoProducts") != null) {
        document.getElementById("specialPromoProducts").innerHTML = result.d;
    }
}
/********************
Closes the popup
*********************/
function closePromoPopup() {
    var modalPopup = $find("modalPopupPromotionBehavior");
    if (modalPopup != null) {
        modalPopup.hide();
    }
}


function chooseWeightSetupAndShow(buttonClickedId, inBasket, pid) {
    var hiddenFieldContainer = $('#' + buttonClickedId).parents(".product_info_container");

    var productname = hiddenFieldContainer.find("*[ID$='lnkProductName']").text();
    var pricePerUnit = hiddenFieldContainer.find("*[id$='lblpricePerUnit']").text();
    var price = hiddenFieldContainer.find("*[ID$='hfCurrentItemPrice']").val();
    var quantity = hiddenFieldContainer.find("*[ID$='hfQuantity']").val();

    var modalPopup = $find("modalPopupChooseWeightNoteBehavior");
    var popupContainer = $("#" + modalPopup._PopupControlID);

    var control = popupContainer.find("*[ID$='tbQuantityDouble']");
    popupContainer.find("*[ID$='tbQuantityDouble']").removeAttr("onblur");
    popupContainer.find("*[ID$='tbQuantityDouble']").attr("onchange", "javascript:updatePriceWeight(this);");

    if (modalPopup != null) {

        if (inBasket) {
            var imgBtn = $('#' + modalPopup._PopupControlID).find('#imgAddBasket');
            var imgPath = imgBtn.attr("src");
            var arrPath = imgPath.split('/');
            arrPath[arrPath.length - 1] = "bttn_updatebasket.gif";
            imgBtn.attr("src", arrPath.join('/'));
        }

        popupContainer.find("*[ID$='hfProductId']").val(pid);
        popupContainer.find("*[ID$='productName']").text(productname);
        popupContainer.find("*[ID$='weightPricePerUnit']").text(pricePerUnit);
        popupContainer.find("A[ID$='btnAddToBasket']").unbind("click");
        popupContainer.find("A[ID$='btnAddToBasket']").bind("click", function(event) {
            addItemToBasketWeighted(buttonClickedId);
        });

        if (isNaN(quantity) || quantity == "") {
            quantity = "1.00";
            popupContainer.find("*[ID$='tbQuantityDouble']").val(quantity);
            popupContainer.find("SPAN[ID$='weightInGrammes']").text("1 Kg");
        }
        else {
            popupContainer.find("*[ID$='tbQuantityDouble']").val(quantity);
        }

        // set the price on the popup so the total price label can be updated.
        popupContainer.find("*[ID$='hfPopupPrice']").val(price);
        var totalprice = fnFormatNum(parseFloat(price) * parseFloat(quantity), 2);
        popupContainer.find("*[ID$='lblPopupTotalPrice']").text(totalprice);

        modalPopup.show();
    }
}

function updatePriceWeight(control) {
    var modalPopup = $find("modalPopupChooseWeightNoteBehavior");
    var popupContainer = $("#" + modalPopup._PopupControlID);
    fnPopupValidateWeightBlur(control.id);

    var q = this.value;
    if (!isNaN(q) && q != undefined ) {
        // do stuff
        if (q < 1) {
            popupContainer.find("#weightInGrammes").show().text((q * 1000) + "g");
            popupContainer.find("*[ID$='currentSelectedWeight']").hide();
        }
        else {
            popupContainer.find("#weightInGrammes").hide();
            popupContainer.find("*[ID$='currentSelectedWeight']").show();
        }
    }

    var price = popupContainer.find("*[ID$='hfPopupPrice']").val();
    price = fnFormatNum(parseFloat(q) * parseFloat(price), 2);
    price = popupContainer.find("*[ID$='hfPopupPrice']").val(price);
    popupContainer.find("*[ID$='lblPopupTotalPrice']").text(price);
 }




/******************************************
    Opens and Loads the AddNote popup with 
    data and sets the button functions
*******************************************/
function showAddNotePopup(pid) {
    var row = $('#' + pid);

    var productname = row.find("*[ID$='lnkProductName']").text();
    var pricePerUnit = row.find("*[id$='lblpricePerUnit']").text();

    var substitute = row.find("*[ID$='hfDoNotSubstitute']").val();
    var note = row.find("*[ID$='hfItemNote']").val();
    var quantity = row.find("*[ID$='tbQuantity']").val();
    row.find("*[ID$='hfQuantity']").val(quantity);
    
    
    // Deal with showing the ModalPopUp
    var modalPopup = $find("modalPopupAddNoteBehavior");
    if (modalPopup != null) {
        $('#' + modalPopup._PopupControlID).find("SPAN[ID$='lblproductName']").text(productname);
        $('#' + modalPopup._PopupControlID).find("SPAN[ID$='lblPricePerUnit']").text(pricePerUnit);

        // attach the click event handler
        $('#' + modalPopup._PopupControlID).find("*[ID$='btnAddToBasketNote']").unbind("click");
        $('#' + modalPopup._PopupControlID).find("*[ID$='btnAddToBasketNote']").bind("click", function(eventObject) {
            addNoteToBasketItem(pid);
            return false;
        });
        
        $('#' + modalPopup._PopupControlID).find("*[ID$='tbItemNote']").val(note);
        $('#' + modalPopup._PopupControlID).find("*[ID$='cbDoNotSubstitute']").attr("checked", ParseBoolean(substitute));
        modalPopup.show();
    }
}


/*************************************
Add a product to the basket 
throught the AddNotePopup Control.
**************************************/
function addNoteToBasketItem(pid) {
    var quantity = "";
    var note = "";
    var substitute = false;

    // get data from the popup control    
    var modalPopup = $find("modalPopupAddNoteBehavior");
    if (modalPopup != null) {
        note = $('#' + modalPopup._PopupControlID).find("*[ID$='tbItemNote']").val();
        //remove any special characters
        note = note.replace(/[^a-zA-Z 0-9]+/g, '');
        substitute = $('#' + modalPopup._PopupControlID).find("*[ID$='cbDoNotSubstitute']").attr("checked");
    }

    // set hidden fields
    var row = $('#' + pid);
    quantity = row.find("*[ID$='hfQuantity']").val();

    if (quantity == 0) {
        quantity = 1.00;
    }

    // set the hidden fields on the
    substitute = ParseBoolean(substitute);
    note = jQuery.trim(note);
    
    row.find("*[ID$='hfDoNotSubstitute']").val(substitute);
    row.find("*[ID$='hfItemNote']").val(note);
    // change the button to "Update"
    row.find("IMG[ID$='imgChooseWeight']").css("display", "none");
    row.find("IMG[ID$='imgUpdateWeight']").css("display", "block");

    // Switch Images if necessary
    if ((note != "") || (substitute == true)) {
        row.find("A[ID$='addNote']").removeAttr("class");
        row.find("A[ID$='addNote']").attr("class", "noteOn");
        row.find("IMG[ID$='imgNoteAdded']").css("display", "block");
    }
    else {
        row.find("A[ID$='addNote']").removeAttr("class");
        row.find("A[ID$='addNote']").attr("class", "note");
        row.find("IMG[ID$='imgNoteAdded']").css("display", "none");
    }

    var params = { 'UseAmendmentBasket': UseAmendmentBasket(), 'ProductID': pid, 'Quantity': quantity, 'Note': note, 'DoNotSubstitute': substitute };

    var jsonString = "{json: '" + JSON.stringify(params) + "'}";

    $.ajax({
        type: "POST",
        url: resolveURL("WebServices/BasketServices.asmx/AddItemToBasket"),
        data: jsonString,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnPopupNoteAddedSuccess,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("there was a problem saving you note. error:" + XMLHttpRequest.ResponseText);
        }
    });
}




/*******************************
OnSuccess function 
for the AddNote Popup.
********************************/
function OnPopupNoteAddedSuccess(results, eventArgs) {
    var miniBasketData = JSON.parse(results.d);
    if (miniBasketData == undefined) {
        return;
    }
    var modalPopup = $find("modalPopupAddNoteBehavior");
    if (modalPopup != null) {
        $('#' + modalPopup._PopupControlID).find("*[ID$='tbItemNote']").val("");
        $('#' + modalPopup._PopupControlID).find("*[ID$='cbDoNotSubstitute']").attr("checked", false);
        modalPopup.hide();
    }
       
    // Update the Mini Basket
    UpdateMiniBasket(miniBasketData);    
}






/****************************************
Add a weighted product to the 
basket from the ChooseWeightPopup
****************************************/
function addItemToBasketWeighted(buttonClickedId) {
    var quantity = "";
    var pid = "";
    var price = "";
    
    // get data from the popup control    
    var modalPopup = $find("modalPopupChooseWeightNoteBehavior");
    if (modalPopup != null) {
        quantity = $('#' + modalPopup._PopupControlID).find("*[ID$='tbQuantityDouble']").val();
        pid = $('#' + modalPopup._PopupControlID).find("*[ID$='hfProductId']").val();
        price = $('#' + modalPopup._PopupControlID).find("*[ID$='hfPopupPrice']").val();
    }

    // set hidden fields and ensure class of weighted item button is update
    var hiddenFieldContainer = $('#' + buttonClickedId).parents(".product_info_container");
    hiddenFieldContainer.find("*[ID$='hfQuantity']").val(quantity);

    hiddenFieldContainer.find("*[ID$='lblTotalPriceValue']").text('€' + (parseFloat(quantity) * parseFloat(price)).toFixed(2));
    
    
    //hiddenFieldContainer.find("*[ID$='hfQuantity']").val(quantity);
    $('#' + buttonClickedId).attr("class", "updateweight");


    var params = { 'UseAmendmentBasket': UseAmendmentBasket(), 'ProductID': pid, 'Quantity': quantity };
    var jsonString = "{json: '" + JSON.stringify(params) + "'}";
    var serviceURL = resolveURL("WebServices/BasketServices.asmx/AddItemToBasket");
    $.ajax({
        type: "POST",
        url: serviceURL,
        data: jsonString,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnPopupItemAddedSuccess
    });
}

/****************************************************
    OnSuccess function 
    for the ChooseWeight Popup.
*****************************************************/
function OnPopupItemAddedSuccess(results, eventArgs) {
    var miniBasketData = JSON.parse(results.d);
    if (miniBasketData == undefined) {
        return;
    }
    var modalPopup = $find("modalPopupChooseWeightNoteBehavior");

    // write the quantity to the cell beside the Trolley icon
    var quantity = parseFloat($('#' + modalPopup._PopupControlID).find("*[ID$='tbQuantityDouble']").val()).toFixed(2);
    var displayText = "";
    if (quantity < 1) {
        displayText = " x " + (quantity * 1000) + "g";
    }
    else {
        displayText = " x " + quantity + "Kg";
    }

    //$('#' + miniBasketData.ProductID).find("*[ID$='lblTotalPriceValue']").Text(("€" + miniBasketData.TotalPrice.toFixed(2)))

    $('#' + miniBasketData.ProductID).find("*[ID$='lblItemSelectedQuantity']").text(displayText);
    $('#' + miniBasketData.ProductID).find("A[ID$='lnkInBasket']").css("display", "block");
    
    // reset default values. must be reset as each row in the product listing uses the same control.
    if (modalPopup != null) {
        $('#' + modalPopup._PopupControlID).find("*[ID$='tbItemNote']").val("");
        $('#' + modalPopup._PopupControlID).find("*[ID$='tbQuantityDouble']").val(1.00);
        $('#' + modalPopup._PopupControlID).find("*[ID$='cbDoNotSubstitute']").attr("checked", false);
        modalPopup.hide();
    }

    // Update the Mini Basket
    UpdateMiniBasket(miniBasketData);
    // show the trolley Icon on the Listing.
    $('#' + miniBasketData.ProductID).find("IMG[ID$='imgBasket']").css("display", "block");
    // when an item has been added to the basket, it is then possible to add a note to that Item.
    $('#' + miniBasketData.ProductID).find("*[ID$='addNote']").unbind("click");
    $('#' + miniBasketData.ProductID).find("*[ID$='addNote']").bind("click", function(eventObject) {
        showAddNotePopup(miniBasketData.ProductID);
        return false;
    });
    // Remove the toolTip onmouseover for the addnote image
    $('#' + miniBasketData.ProductID).find("*[ID$='addNote']").removeAttr("onmouseover");

    var addButton = $('#' + miniBasketData.ProductID).find("A[ID$='btnChooseWeight']");
    // Switch the addToBasket class 
    addButton.attr("height", "30");
    addButton.attr("width", "93");
    addButton.attr("class", "updateweight");

    var productReferentials = $(".product_referential input[value$='" + miniBasketData.ProductID + "'], .product_referential_wrap input[value$='" + miniBasketData.ProductID + "']");
    productReferentials.parents(".product_info_container").find("IMG[ID$='imgInBasket']").css("display", "inline");
}


/********************
Closes the popup
*********************/
function closeChooseWeightPopup() {
    var modalPopup = $find("modalPopupChooseWeightNoteBehavior");
    if (modalPopup != null) {
        modalPopup.hide();
    }
}

/********************
Closes the popup
*********************/
function closeAddNotePopup() {
    var modalPopup = $find("modalPopupAddNoteBehavior");
    if (modalPopup != null) {
        modalPopup.hide();
    }
}

/**************************************
    Open the Substitution policy Panel 
**************************************/
function openSubstitutionPolicyPnl() {
    var modalPopup = $find('modalPopupSubstitutionPolicyPopup');

    if (modalPopup != null) {
       modalPopup.show();
    }
}

/**************************************
    Close the Substitution policy Panel
**************************************/
function closeSubstitutionPolicyPnl() {
    var modalclose = $find('modalPopupSubstitutionPolicyPopup');
    if (modalclose != null) {
        modalclose.hide();
    }
}


/**************************************
Open the Substitution policy Panel 
**************************************/
function openGenericPopUp(modalPopupID) {
    var modalPopup = $find(modalPopupID);

    if (modalPopup != null) {
        modalPopup.show();
    }
}

/**************************************
Close the Substitution policy Panel
**************************************/
function closeGenericPopUp(modalPopupID) {
    var modalclose = $find(modalPopupID);
    if (modalclose != null) {
        modalclose.hide();
    }
}


/**************************************
Open the Service Fee policy Panel 
**************************************/
function openServiceFeePnl() {
    var modalPopup = $find('modalPopupServiceFeePopup');

    if (modalPopup != null) {
        modalPopup.show();
    }
}

/**************************************
Close the Service Fee policy Panel
**************************************/
function closeServiceFeePnl() {
    var modalclose = $find('modalPopupServiceFeePopup');
    if (modalclose != null) {
        modalclose.hide();
    }
}

/********************

*********************/
function openAnonStartShoppingpnl() {
    var modalclose = $find('modalPopupAnonShoppingPopUp');
    if (modalclose != null) {
        modalclose.show();
    } 
}
function closeAnonStartShoppingpnl() {
    var modalclose = $find('modalPopupAnonShoppingPopUp');
    if (modalclose != null) {
        modalclose.hide();
    }
}

function closeAddressChecker() {
    var modalclose = $find('modalPopupAddressChecker');
    if (modalclose != null) {
        modalclose.hide();
    }
}

function openAddressChecker() {
    var modalopen = $find('modalPopupAddressChecker');
    //var pos =
    if (modalopen != null) {
        modalopen.show();
    }
}
function closeAdressRemoveChecker() {
    var modalclose = $find('modalPopupRemoveAddressChecker');
    if (modalclose != null) {
        modalclose.hide();
    }
}
function openAdressRemoveChecker() {
    var modalopen = $find('modalPopupRemoveAddressChecker');
    //var pos =
    if (modalopen != null) {
        modalopen.show();
    }
}

//Show SignUpWithRewardCardPopUp
function openSignUpWithRewardCardpnl() {

    var modalopen = $find('modalSignUpWithRewardCardPopUp');
    
    if (modalopen != null) {

        $("#" + modalopen._PopupControlID).find("#pnlSignUpWithRewardCardPopUp").css("display", "block");
       
        modalopen.show();
    }
}

//Hide SignUpWithRewardCardPopUp
function closeSignUpWithRewardCardpnl() {

    var modalclose = $find('modalSignUpWithRewardCardPopUp');
    if (modalclose != null) {
        modalclose.hide();
    }
}