﻿/// <reference path="jquery-1.2.6-intellisense.js"/>

function basketQtyChanged(pid) {

    var row = $('#' + pid);
    var qty = row.find("*[ID$='tbQuantity']").val();

    //if it is a weighted item then the qty variable will be undefined
    if (typeof (qty) !== 'undefined') {


        var htmlToWrite = "";
        
        var priceEach = row.find("*[ID$='hfCurrentItemPrice']").val();
        priceEach = parseFloat(priceEach.replace(/^\D+/, ""));
        var totalPrice = priceEach * qty
        

        //if the item is on special offer then it will have something in the hidden field hfOrginalItemPrice
        //this tells us the orginal unit price of the item before the spical offer is applied and from this we can show the crossed out price
        var orginalPriceEach = row.find("*[ID$='hfOrginalItemPrice']").val();
        orginalPriceEach = parseFloat(orginalPriceEach.replace(/^\D+/, ""));
        if (!isNaN(orginalPriceEach)) {
            var totalOrginalPrice = orginalPriceEach * qty
            htmlToWrite = "<del> €" + totalOrginalPrice.toFixed(2) + "</del><BR />";
            htmlToWrite += "<span class=\"promotion\">€" + totalPrice.toFixed(2) + "</span>"
        }
        else {
            //add in the updated price
            htmlToWrite = "€" + totalPrice.toFixed(2)
            row.find("*[ID$='lblTotalPriceValue']").attr("style", "color: red");
        }

        row.find("*[ID$='lblTotalPriceValue']").html(htmlToWrite);
        
        
        ActivateUpdateBasketButton();

        //set the qty and price to red to indicate that they have changed
        row.find("*[ID$='tbQuantity']").attr("style", "color: red");
      
    } 

}



function ActivateUpdateBasketButton() {
    //TODO: check if the button is already active before going through the process again
    //get the site theme
    
    var hdnUrlPath = $("*[ID$='hfSiteUrlWithTheme']").val();

    $("#imgUpdateBasketBottom").attr("src", hdnUrlPath + "/images/buttons/bttn_updatebasket.gif");
    $("#imgUpdateBasketBottom").mouseover(function() {
    $(this).attr("src", hdnUrlPath + "/Images/buttons/bttn_updatebasket_on.gif");
    });

    $("#imgUpdateBasketBottom").mouseout(function() {
    $(this).attr("src", hdnUrlPath + "/Images/buttons/bttn_updatebasket.gif");
    });

    $("*[ID$='btnUpdateBasketBottom']").removeAttr("onclick");



    $("#imgUpdateBasketTop").attr("src", hdnUrlPath + "/images/buttons/bttn_updatebasket.gif");
    $("#imgUpdateBasketTop").mouseover(function() {
        $(this).attr("src", hdnUrlPath + "/Images/buttons/bttn_updatebasket_on.gif");
    });

    $("#imgUpdateBasketTop").mouseout(function() {
        $(this).attr("src", hdnUrlPath + "/Images/buttons/bttn_updatebasket.gif");
    });

    $("A[ID$='btnUpdateBasketTop']").removeAttr("onclick");
    
    $("DIV[ID$='divUpdateBasketMessageBotom']").attr("style", "display:block;");


    //disable the back button when the user tries to save the changes. This prevents the basket button from been pressed more than once.
    $("A[ID$='btnUpdateBasketTop']").click(function() {UnBindBasketSaveChanges('btnUpdateBasketTop');});
    $("A[ID$='btnUpdateBasketBottom']").click(function() {UnBindBasketSaveChanges('btnUpdateBasketBottom');});
                            
                            
    }


// Adds an Item to the basket through a WebService
function ToggleRemoveItem(pid) {

    var hrefQtyPlus;
    var hrefQtyMinus;
    
    // get product data from hidden fields
    var row = $('#' + pid);
    
    //get from the hidden field wheteher the item is removed already or not
    var itemRemoved = row.find("INPUT[ID$='hfItemRemoved']").val();

    //if the item is not currently removed then we cahnge the remove image 
   //and disable all the controls 
    if (itemRemoved == "false") {

        //the background colour here is to stop the text getting blury when the opacity is put over it
        var style = "opacity: 0.4; filter: alpha(opacity=40);z-index:1;background-color:white";
        row.find("*[ID$='td']").attr("style", style);
        
        
        
                         
        row.find("INPUT[ID$='hfItemRemoved']").val("true");
        row.find("INPUT[ID$='btnProductImage']").attr("disabled", true);
        row.find("A[ID$='btnFavourites']").attr("disabled", true);
        row.find("A[ID$='btnFavourites']").attr("class", "favouriteOff");
        row.find("A[ID$='addNote']").attr("disabled", true);
        row.find("A[ID$='addNote']").attr("class", "noteOff");
        
        //disable the qty box
        row.find("INPUT[ID$='tbQuantity']").attr("disabled", true);

        //do diable the hyperlinks we set the href to javascript:void(0);
        //we have to remember the href before we do this and save it to a hidden field
        //we need to get the value from this hidden field when they toggle the remove button again
        hrefQtyPlus = row.find("A[ID$='lnkQuantityPlus']").attr("href");
        row.find("INPUT[ID$='hfQtyPlusHref']").val(hrefQtyPlus);
        row.find("A[ID$='lnkQuantityPlus']").attr("href", "javascript:void(0);");
        hrefQtyMinus = row.find("A[ID$='lnkQuantityMinus']").attr("href");
        row.find("INPUT[ID$='hfQtyMinusHref']").val(hrefQtyMinus);
        row.find("A[ID$='lnkQuantityMinus']").attr("href", "javascript:void(0);");

        row.find("A[ID$='btnChooseWeight']").attr("class", "updateweightOff");
        row.find("A[ID$='btnChooseWeight']").attr("disabled", true);
               

        
        
        row.find("IMG[ID$='imgRemove']").attr("src", "../App_Themes/SuperQuinn_en/Images/buttons/bttn_basket_undelete.png");

        ActivateUpdateBasketButton()
        
        
    }
    else {

        row.find("*[ID$='td']").removeAttr("style");
        
        row.find("INPUT[ID$='hfItemRemoved']").val("false");
        row.find("INPUT[ID$='btnProductImage']").removeAttr("disabled");
        row.find("A[ID$='btnFavourites']").removeAttr("disabled");
        row.find("A[ID$='btnFavourites']").attr("class", "favourite");
        row.find("A[ID$='addNote']").removeAttr("disabled");
        row.find("A[ID$='addNote']").attr("class", "note");
        row.find("INPUT[ID$='tbQuantity']").removeAttr("disabled");
        
        hrefQtyPlus = row.find("INPUT[ID$='hfQtyPlusHref']").val();
        row.find("A[ID$='lnkQuantityPlus']").attr("href", hrefQtyPlus);

        hrefQtyMinus = row.find("INPUT[ID$='hfQtyMinusHref']").val();
        row.find("A[ID$='lnkQuantityMinus']").attr("href", hrefQtyMinus);
        row.find("A[ID$='btnChooseWeight']").removeAttr("disabled");
        row.find("A[ID$='btnChooseWeight']").attr("class", "updateweight");
        row.find("IMG[ID$='btnRemove']").attr("src", "../App_Themes/SuperQuinn_en/Images/buttons/bttn_basket_delete.png");
   
    }
    return false; //return false to stop postback
}


/* 
the following code has been duplicated from the other listing controls. 
These should to be refactored back into addNoteToBasketItem & OnPopupNoteAddedSuccess so all the listing use the same functions.
Not enough time before release to do this.
*/

/******************************************
Opens and Loads the AddNote popup with 
data and sets the button functions - ViewBasket Screen
*******************************************/
function showAddNotePopupFromBasket(pid) {
    var row = $('#' + pid);

    var itemRemoved = row.find("*[ID$='hfItemRemoved']").val();

    //check if the item is removed and if it is do not show the weight popup
    //this used by firefox
    if (itemRemoved == "false") {
        var productname = row.find("*[ID$='lnkProductName']").text();
        var substitute = row.find("*[ID$='hfDoNotSubstitute']").val();
        var note = row.find("*[ID$='hfItemNote']").val();
        var quantity = row.find("*[ID$='tbQuantity']").val();

        var pricePerUnit = row.find("*[id$='lblpricePerUnit']").text();


        // 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) {
                addNoteToBasketItemFromBasket(pid);
                return false;
            });

            $('#' + modalPopup._PopupControlID).find("*[ID$='tbItemNote']").val(note);

            if (substitute.toUpperCase() == "FALSE") {
                $('#' + modalPopup._PopupControlID).find("*[ID$='cbDoNotSubstitute']").attr("checked", false);
            }
            else {
                $('#' + modalPopup._PopupControlID).find("*[ID$='cbDoNotSubstitute']").attr("checked", true);
            }
            
            modalPopup.show();
        }
    }
}


function addNoteToBasketItemFromBasket(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);

    var modalPopup = $find("modalPopupAddNoteBehavior");
    if (modalPopup != null) {
        $('#' + modalPopup._PopupControlID).find("*[ID$='tbItemNote']").val("");
        $('#' + modalPopup._PopupControlID).find("*[ID$='cbDoNotSubstitute']").attr("checked", false);
        modalPopup.hide();
    }

    // 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");
    }

    //activate the update button so the user can save their changes
    ActivateUpdateBasketButton();
}

// this one shows the choose weght popup
function chooseWeightSetupAndShowInBasket(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$='hfWeightedQuantity']").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) {
            // add the product to the basket
            addItemToBasketWeightedFromBasket(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();
    }
}


/****************************************
Add a weighted product to the 
basket from the ChooseWeightPopup
****************************************/
function addItemToBasketWeightedFromBasket(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();
    }

    var row = $("#"+pid);

    row.find("*[ID$='hfWeightedQuantity']").val(quantity);
    row.find("*[ID$='lblTotalPriceValue']").text('€' + (parseFloat(quantity) * parseFloat(price)).toFixed(2));


    //hiddenFieldContainer.find("*[ID$='hfQuantity']").val(quantity);
    $('#' + buttonClickedId).attr("class", "updateweight");


    // write the quantity to the cell beside the Trolley icon
    quantity = parseFloat(quantity).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)))

    row.find("*[ID$='lblItemSelectedQuantity']").text(displayText);
    // 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();
    }

    // show the trolley Icon on the Listing.
    row.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.
    row.find("*[ID$='addNote']").unbind("click");
    row.find("*[ID$='addNote']").bind("click", function(eventObject) {
        showAddNotePopupFromBasket(pid);
        return false;
    });
    // Remove the toolTip onmouseover for the addnote image
    row.find("*[ID$='addNote']").removeAttr("onmouseover");

    var addButton = row.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$='" + pid + "'], .product_referential_wrap input[value$='" + pid + "']");
    productReferentials.parents(".product_info_container").find("IMG[ID$='imgInBasket']").css("display", "inline");


    //activate the update button so the user can save their changes
    ActivateUpdateBasketButton();    
}