﻿/*
 * ----------------------------------------------------------------------------
 * PROMOTION POPUP FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */
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');
        }
    }

}


/********************************************
Executes on successful completion of the 
ItemAdded webservice
********************************************/
function OnItemAddedSuccessPopup(result, eventArgs) {

    var basketServiceResult = JSON.parse(result.d);

    if (basketServiceResult == undefined) {
        return;
    }
    //deserialize the JSON and use it to update the Mini Basket
    var miniBasketData = JSON.parse(result.d);

    if (miniBasketData == undefined) {
        return;
    }

   
    // 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");

    //display the In Basket Link
    $('#' + miniBasketData.ProductID).find("A[ID$='lnkInBasket']").css("display", "block");


    // 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) {
    sANP(miniBasketData.ProductID);
        return false;
    });

    // Remove the toolTip onmouseover for the addnote image
    $('#' + miniBasketData.ProductID).find("*[ID$='addNote']").removeAttr("onmouseover");

    

    AddUpdateItemInMiniCart(basketServiceResult);

    // update listing
    AddUpdateItemInProductListing(basketServiceResult);

    // update product details
    AddUpdateItemInProductDetails(basketServiceResult);

    // update referentials
    AddUpdateItemInReferentials(basketServiceResult);

    //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', '');



}




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 showPromoItems(promoid, productid) {
    var clientId = $("#pnlPromotionClientID").val();
    var popupContainer = $("#" + clientId);
    $('body').append(popupContainer);
     
    $("#" + clientId).jqm();

    $("#" + clientId).jqmShow();

 
        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
        });
    
}


function ShowPromoQualifiers(result, eventArgs) {
    if (document.getElementById("specialPromoProducts") != null) {
        document.getElementById("specialPromoProducts").innerHTML = result.d;
    }
}

function closePromoPopup() {
    var clientId = $("#pnlPromotionClientID").val();
    $("#" + clientId).jqmHide();
}



/*
 * ----------------------------------------------------------------------------
 * WEIGHTED ITEM POPUP FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */

/********************************************
 * Adds/updates a weighted item by getting all needed information from 
 * the weighted item popup and tehn calling the BasketServices.AddItemToBasket 
 * web method.  
 *******************************************/
function WeightItemPopupOnAddToBasketClickCallAddItemWebService(note,doNotsubstitute) {
    var clientId = $("#pnlChooseWeightClientID").val();

    var modalPopup = $("#" + clientId);

    if ((modalPopup != undefined) && (modalPopup != null)) {
        var pid, quantity, note, substitute;
    
        pid = modalPopup.find("*[ID$='hfProductId']").val();
        quantity = modalPopup.find("*[ID$='tbQuantityDouble']").val();
        quantity = parseFloat(quantity);
        if (quantity == 0) {
            alert("Please select a quantity");
            return;
        }
        
        
        WeightedItemPopupClose();

        AddItemToBasket(pid, quantity, note, doNotsubstitute);
    }
}


/********************************************
 * Updates a weighted item's quantity by getting all needed information from 
 * the weighted item popup and then calling BasketServices.AddItemToBasket 
 * web method.  
 *******************************************/
function WeightItemPopupOnAddToBasketClickCallUpdateQuantityWebService() {
    var clientId = $("#pnlChooseWeightClientID").val();
    var modalPopup = $("#" + clientId);

    if ((modalPopup != undefined) && (modalPopup != null)) {
        var pid, quantity, note, substitute;
    
        pid = modalPopup.find("*[ID$='hfProductId']").val();
        quantity = modalPopup.find("*[ID$='tbQuantityDouble']").val();
        quantity = parseFloat(quantity);
        
        WeightedItemPopupClose();
        
        UpdateItemQuantity(pid, quantity);
    }
}


/********************************************
 * Initializes and shows the weighted item popup.  The addToBasket click event
 * will be wired to call the BasketServices.AddItemToBasket web method to 
 * add/update the weighted item immediately.
 
 *******************************************/
function WeightedItemPopupShow(productId, productName, pricePerUnit, quantity, 
    note, doNotsubstitute, addToBasketClickHandler) {
    WeightedItemPopupShowBase(productId, productName, pricePerUnit, quantity,note,doNotsubstitute, 
        WeightItemPopupOnAddToBasketClickCallAddItemWebService);
}



/********************************************
 * Initializes and shows the weighted item popup.  The addToBasketClickHandler 
 * is the function to call once the user has clicked to add the weighted item 
 * to their basket.
 *******************************************/
function WeightedItemPopupShowBase(productId, productName, pricePerUnit, quantity, note, doNotsubstitute,
     addToBasketClickHandler) {
    var clientId = $("#pnlChooseWeightClientID").val();
    var popupContainer = $("#" + clientId);

    if (popupContainer != null) {
        //var popupContainer = $("#" + modalPopup._PopupControlID);

        $('body').append(popupContainer);

        // initialize popup labels and fields
        popupContainer.find("*[ID$='productName']").text(productName);

        var pricePerUnitStr = "$" + fnFormatNum(parseFloat(pricePerUnit), 2) + " / lb";
        popupContainer.find("*[ID$='weightPricePerUnit']").text(pricePerUnitStr);

        // if the item is in the basket use change weight button
        var imgBtn = popupContainer.find('#imgAddBasket');
        var imgPath = imgBtn.attr("src");
        var arrPath = imgPath.split('/');
        
        if (quantity > 0) {
            
            arrPath[arrPath.length - 1] = "btn_changeWeight.gif";
            imgBtn.attr("src", arrPath.join('/'));
        }
        else {
            arrPath[arrPath.length - 1] = "btn_addToCart.gif";
            imgBtn.attr("src", arrPath.join('/'));
        }
        
        if (isNaN(quantity) || quantity == "") {
            quantity = "1.00";
            popupContainer.find("*[ID$='tbQuantityDouble']").val(quantity);
            popupContainer.find("SPAN[ID$='weightInGrammes']").text("1 Lb");
        }
        else {
            popupContainer.find("*[ID$='tbQuantityDouble']").val(quantity);
        }

        if (quantity >= 1) {
            popupContainer.find("SPAN[ID$='weightInGrammes']").hide();
        }
        else if (quantity > 0 && quantity < 1) {
        popupContainer.find("SPAN[ID$='weightInGrammes']").show().text((quantity * 16) + " Oz");
        }
        
        popupContainer.find("*[ID$='hfPopupPrice']").val(pricePerUnit);
        var totalprice = "$" + fnFormatNum(parseFloat(pricePerUnit) * parseFloat(quantity), 2);
        popupContainer.find("*[ID$='lblPopupTotalPrice']").text(totalprice);
        
        popupContainer.find("*[ID$='hfProductId']").val(productId);

        
        // wire up events
        popupContainer.find("*[ID$='tbQuantityDouble']").removeAttr("onblur");
        popupContainer.find("*[ID$='tbQuantityDouble']").attr("onchange", "javascript:WeightedItemPopupUpdatePrice(this);");

        popupContainer.find("A[ID$='btnAddToBasket']").unbind("click");
        // this will make sure event from shopping card is not evoke the webservice
        if (addToBasketClickHandler != "undefined" && addToBasketClickHandler != null) {

            popupContainer.find("A[ID$='btnAddToBasket']").attr("href", "javascript:WeightItemPopupOnAddToBasketClickCallAddItemWebService('" + note + "','" + doNotsubstitute + "')");
        }
        else {

            popupContainer.find("A[ID$='btnAddToBasket']").attr("href", "javascript:addItemToBasketWeightedFromBasket('" + note + "','" + doNotsubstitute  + "')");
        }

        popupContainer.jqm();
        popupContainer.jqmShow();
    }
}


/********************************************
 * Updates total price in weighted popup when selected weight is changed.
 *******************************************/
function WeightedItemPopupUpdatePrice(control) {
    var clientId = $("#pnlChooseWeightClientID").val();
    var popupContainer = $("#" + clientId);
    //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) + "Oz");
            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);
 }


/********************
 * Closes the chose weight popup
 **********************/
function WeightedItemPopupClose() {
    var clientId = $("#pnlChooseWeightClientID").val();
    var modalPopup = $("#" + clientId);
    if (modalPopup != null) {
        modalPopup.jqmHide();
    }
}


/*
 * ----------------------------------------------------------------------------
 * NOTE POPUP FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */

/******************************************
    Opens and Loads the AddNote popup with 
    data and sets the button functions
    showAddNotePopup
*******************************************/
function sANP(pid) {
    var row = $('#' + pid);
 
    var productname = row.find("*[ID$='lnkProductName']").text();
    var pricePerUnit = row.find("*[id$='lblpricePerUnit']").text();

    var doNotSubstitute = row.find("*[ID$='hfDoNotSubstitute']").val();
    var note = row.find("*[ID$='hfItemNote']").val();
    var quantity = row.find("*[ID$='tbQuantity']").val();
    if (quantity != undefined) {
        row.find("*[ID$='hfQuantity']").val(quantity);
    }

    // Deal with showing the ModalPopUp
    var clientId = $("#pnl_AddnoteClientId").val();
    var modalPopup = $("#" + clientId);
    if (modalPopup != null) {

        modalPopup.find("SPAN[ID$='lblproductName']").text(productname);
        modalPopup.find("*[ID$='lblPricePerUnitNote']").text(pricePerUnit);

        if (note == undefined) {
            note = "";
        }
        if (note != "") {
            modalPopup.find("IMG[ID$='imgAddBasket']").attr("src", "../App_Themes/RocheBros_en/Images/buttons/btn_editNote.gif");
        }
        else {
            modalPopup.find("IMG[ID$='imgAddBasket']").attr("src", "../App_Themes/RocheBros_en/Images/btn_addNote.gif");
        }
        // attach the click event handler

        modalPopup.find("*[ID$='btnAddToBasketNote']").attr("href", "javascript:addNoteToBasketItem(" + pid + ",'" + doNotSubstitute + "')");



        modalPopup.find("*[ID$='tbItemNote']").val(note);
       
        modalPopup.find("*[ID$='tbItemNote']").focus();
        //modalPopup.find("*[ID$='cbDoNotSubstitute']").attr("checked", ParseBoolean(doNotSubstitute));
        modalPopup.jqm();
        modalPopup.jqmShow();
    }
}



/*************************************
Add a product to the basket 
throught the AddNotePopup Control.
**************************************/
function addNoteToBasketItem(pid,doNotSustitute) {
    var quantity = "";
    var note = "";
    
    // get data from the popup control
    var clientId = $("#pnl_AddnoteClientId").val();
    var modalPopup = $("#" + clientId);
    if (modalPopup != null) {
        note = modalPopup.find("*[ID$='tbItemNote']").val();
        //replace special charater of \ ' " to empty string
        note = note.replace(/[\\ '''' "" ]/g, ' ');
        note = note.replace(/</g, " less than ");
        note = note.replace(/>/g, " greater than ");
        note = note.replace(/&/g, " and ");
    }

    // set hidden fields
    var row = $('#' + pid);

    quantity = row.find("*[ID$='hfQuantity']").val();

    if (quantity == 0) {
        quantity = 1.00;
    }
    if (quantity == undefined) {
        quantity = 1.00;
    }

    // set the hidden fields on the
    doNotSustitute = ParseBoolean(doNotSustitute);
    note = jQuery.trim(note);

    row.find("*[ID$='hfDoNotSubstitute']").val(doNotSustitute);
    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 != "" && note != undefined) {        
        row.find("A[ID$='addNote']").addClass("selected");
        row.find("IMG[ID$='imgNoteAdded']").css("display", "block");
    }
    else {
        row.find("A[ID$='addNote']").removeClass("selected");
        row.find("IMG[ID$='imgNoteAdded']").css("display", "none");
    }
 
    var params = { 'UseAmendmentBasket': UseAmendmentBasket(), 'ProductID': pid, 'Quantity': quantity, 'Note': note, 'DoNotSubstitute': doNotSustitute };

    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 basketServiceResult = JSON.parse(results.d);
    if (basketServiceResult == undefined) {
        return;
    }
    var clientId = $("#pnl_AddnoteClientId").val();
    var modalPopup = $("#" + clientId);
    if (modalPopup != null) {
        modalPopup.find("*[ID$='tbItemNote']").val("");
        modalPopup.find("*[ID$='cbDoNotSubstitute']").attr("checked", false);
        modalPopup.jqmHide();
    }

    // Update the Mini Basket
    AddUpdateItemInMiniCart(basketServiceResult);
}



/********************
Closes the popup
*********************/
function closeAddNotePopup() {
    var clientId = $("#pnl_AddnoteClientId").val();
    var modalPopup = $("#" + clientId);
    if (modalPopup != null) {
        modalPopup.jqmHide();
    }
}


/*
 * ----------------------------------------------------------------------------
 * OTHER MISCELLANEOUS POPUP FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */
 
function closeServiceFeePnl() {
    var clientId = $("#pnlServiceFeeClientID").val();
    $("#" + clientId).jqmHide();
}

function closeAddressChecker() {
    var modalclose = $find('modalPopupAddressChecker');
    if (modalclose != null) {
        modalclose.hide();
    }
}

function openAddressChecker() {
    var modalopen = $find('modalPopupAddressChecker');
    if (modalopen != null) {
        $('body').append(modalopen);
        modalopen.show();
    }
}
function closeAdressRemoveChecker() {
    var modalclose = $find('modalPopupRemoveAddressChecker');
    if (modalclose != null) {
        modalclose.hide();
    }
}
function openAdressRemoveChecker() {
    var modalopen = $find('modalPopupRemoveAddressChecker');
    if (modalopen != null) {
        $('body').append(modalopen);
        modalopen.show();
    }
}

/**************************************
Opens a generic content popup.  The div containing the generic content popup is
found by using the id of the div in the GenericContentPopup user control plus 
the modalPopupID set on the GenericContentPopUp user control.
**************************************/
function openGenericPopUp(modalPopupID) {
    var modalPopup = $("#GenericContentPopUp_" + modalPopupID);
    $('body').append(modalPopup);
    modalPopup.jqm();
    modalPopup.jqmShow();
}

/**************************************
Closes a generic content popup.  The div containing the generic content popup is
found by using the id of the div in the GenericContentPopup user control plus 
the modalPopupID set on the GenericContentPopUp user control.
**************************************/
function closeGenericPopUp(modalPopupID) {
    var modalclose = $("#GenericContentPopUp_" + modalPopupID);
    modalclose.jqmHide();
}


/**************************************
Open the Substitution policy Panel 
**************************************/
function openSubstitutionPolicyPnl() {
    var clientId = $("#pnlSubstitutionPolicyClientID").val();

    var popupContainer = $("#" + clientId);
    $('body').append(popupContainer);

    $("#" + clientId).jqm();
    $("#" + clientId).jqmShow();
}

/**************************************
Close the Substitution policy Panel
**************************************/
function closeSubstitutionPolicyPnl() {
    var clientId = $("#pnlSubstitutionPolicyClientID").val();
    $("#" + clientId).jqmHide();
}


function openServiceFeePnl() {
    var clientId = $("#pnlServiceFeeClientID").val();

    var popupContainer = $("#" + clientId);
    $('body').append(popupContainer);

    $("#" + clientId).jqm();
    $("#" + clientId).jqmShow();
}


/*
*   Updates the price label in a Choose Weight popup, 
*   whenever the weight quantity is manually inputed
*/
function updatePriceWeight(control) {
    var clientId = $("#pnlChooseWeightClientID").val();
    var modalPopup = $("#" + clientId);
    fnPopupValidateWeightBlur(control.id);

    var q = this.value;
    if (!isNaN(q) && q != undefined) {
        // do stuff

        if (q < 1) {
            $("#weightInGrammes").show().text((q * 1000) + "oz");
            $("#weightinlbs").show().text("(" + (fnFormatNum(q * 2.20462262, 2)) + " Lb)");
            modalPopup.find("*[ID$='currentSelectedWeight']").hide();
        }
        else {
            $("#weightInGrammes").hide();
            $("#weightinlbs").show().text("(" + (fnFormatNum(q * 2.20462262, 2)) + " Lb)");
            modalPopup.find("*[ID$='currentSelectedWeight']").show();
        }
    }

    var price = modalPopup.find("*[ID$='hfPopupPrice']").val();
    price = fnFormatNum(parseFloat(q) * parseFloat(price), 2);
    modalPopup.find("*[ID$='lblPopupTotalPrice']").html(price);
}


/**************************************
Credit Card Yes/No Popup
**************************************/
function openCreditCardPopup() {
    var clientId = $("#pnlAreYouSureCreditCard").val();

    var popupContainer = $("#" + clientId);
    $('body').append(popupContainer);

    $("#" + clientId).jqm();

    $("#" + clientId).jqmShow();
}

/**************************************

**************************************/
function closeCreditCardPopup() {
    var clientId = $("#pnlAreYouSureCreditCard").val();
    $("#" + clientId).jqmHide();

}


function closeAdressRemoveChecker() {
    var clientId = $("#pnlAreYouSureAddress").val();
    $("#" + clientId).jqmHide();
}
function openAdressRemoveChecker() {
    var clientId = $("#pnlAreYouSureAddress").val();
    var popupContainer = $("#" + clientId);
    $('body').append(popupContainer);
    
    $("#" + clientId).jqm();
    $("#" + clientId).jqmShow();
}


function GoToBasket() {
var siteUrl =   $("input[ID$='hfSiteUrl']").val();
    document.location.href = siteUrl +"shopping/basket.aspx";
}

