﻿/*
 * ----------------------------------------------------------------------------
 * COMMON PRODUCT/BASKET FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */
 
/********************************************
 * Adds an Item to the basket through a BasketServices.AddItemToBasket web method.
 *******************************************/
function AddItemToBasket(pid, quantity, note, substitute) {

    var params = { 
        'UseAmendmentBasket': UseAmendmentBasket(), 
        'ProductID': pid, 
        'Quantity': quantity, 
        'Note': note, 
        'DoNotSubstitute': ParseBoolean(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);
        }
    });
}


/********************************************
 * Adds/removes a product from customer's favorites list via the FavoritesServices.SetFavorite web method.
 *******************************************/
function AddRemoveFavorite(pid, context) {

    var params = { 'ProductID': pid };

    var jsonString = "{JsonProductID: '" + JSON.stringify(params) + "'}";
    var serviceURL = resolveURL("WebServices/FavoritesServices.asmx/SetFavorite");
    $.ajax({
        type: "POST",
        url: serviceURL,
        data: jsonString,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(results) {
            var $product = $('#' + pid);
            var $details = $('#pnlDetails');
            if (context == "BASKET") {               
                if (results.d == "on") {
                    $product.find("A[ID$='btnFavorites']").addClass("selected");
                    $product.find("A[ID$='btnFavorites']").attr('style', 'background:url(../App_Themes/RocheBros_en/Images/icon_favorite_on.gif) no-repeat');
                }
                else {
                    $product.find("A[ID$='btnFavorites']").removeClass("selected");
                    $product.find("A[ID$='btnFavorites']").attr('style', 'background:url(../App_Themes/RocheBros_en/Images/icon_favorite.gif) no-repeat');
                }
            }
            else if (context == "DETAIL") {                
                if (results.d == "on") {
                    $details.find("A[ID$='lnkAddToFavorites']").addClass("selected");
                    $details.find("A[ID$='lnkAddToFavorites']").attr("style", 'background:url(../App_Themes/RocheBros_en/Images/icon_favorite_on.gif) no-repeat');
                    $details.find("*[ID$='lnkAddToFavorites']").html("<br>This Product is on your favorites list.");
                }
                else {
                    $details.find("A[ID$='lnkAddToFavorites']").removeClass("selected");
                    $details.find("A[ID$='lnkAddToFavorites']").attr("style", 'background:url(../App_Themes/RocheBros_en/Images/icon_favorite.gif) no-repeat');
                    $details.find("*[ID$='lnkAddToFavorites']").html("This items is not on your favorites list.<br/>To add this to your favorites list click here");
                }
            }
            else {
                if (results.d == "on") {
                    $product.find("A[ID$='btnFavorites']").addClass("selected");
                    $product.find("A[ID$='btnFavorites']").attr('style', 'background:url(../App_Themes/RocheBros_en/Images/icon_favorite_on.gif) no-repeat');
                }
                else {
                    $product.find("A[ID$='btnFavorites']").removeClass("selected");
                    $product.find("A[ID$='btnFavorites']").attr('style', 'background:url(../App_Themes/RocheBros_en/Images/icon_favorite.gif) no-repeat');
                }

                //$product.find("A[ID$='btnFavorites']").css("cursor", "pointer");
            }



        }
    });
}


/********************************************
 * Executes on successful completion of the BasketServices.AddItemToBasket web method.
 ********************************************/
function OnItemAddedSuccess(result, eventArgs) {
    //deserialize the JSON and use it to update the Mini Basket
    var basketServiceResult = JSON.parse(result.d);

    if (basketServiceResult == undefined) {
        return;
    }

    // update the mini basket
    AddUpdateItemInMiniCart(basketServiceResult);
    
    // update listing
    AddUpdateItemInProductListing(basketServiceResult);
    
    // update product details
    AddUpdateItemInProductDetails(basketServiceResult);
    
    // update referentials
    AddUpdateItemInReferentials(basketServiceResult);
}


/********************************************
 * Executes on successful completion of the BasketServices.RemoveItemFromBasket web method.
 ********************************************/
function OnItemRemovedSuccess(result, eventArgs) {
    //deserialize the JSON and use it to update the Mini Basket
    var basketServiceResult = JSON.parse(result.d);

    if (basketServiceResult == undefined) {
        return;
    }

    // remove the basket item from the mini cart
    RemoveItemFromMiniCart(basketServiceResult);
    
    // remove the basket item from the product listing
    RemoveItemFromProductListing(basketServiceResult);
    
    // remove item from product details
    RemoveItemFromProductDetails(basketServiceResult);

    // remove the basket item from referentials
    RemoveItemFromReferentials(basketServiceResult);
}


/******************************************
    Removes the item from the mini cart.
    RemoveItemFromBasket
*******************************************/
function RIFRB(pid) {
    var params = { 
        'UseAmendmentBasket': UseAmendmentBasket(), 
        'ProductID': pid, 
        'Quantity': 0, 
        'Note': "", 
        'DoNotSubstitute': false
    };

    var jsonString = "{json: '" + JSON.stringify(params) + "'}";
    var serviceURL = resolveURL("WebServices/BasketServices.asmx/RemoveItemFromBasket");
    $.ajax({
        type: "POST",
        url: serviceURL,
        data: jsonString,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnItemRemovedSuccess,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("There was an error trying to process the last operation."
            + "Error: " + errorThrown + "  TextStatus:  " + textStatus);
        }
    });
}


/********************************************
 * Updates a basket item's quantity via the BasketServices.UpdateItemQuantity web method.
 *******************************************/
function UpdateItemQuantity(pid, quantity) {
    var params = { 
        'UseAmendmentBasket': UseAmendmentBasket(), 
        'ProductID': pid, 
        'Quantity': quantity, 
        'Note': "", 
        'DoNotSubstitute': false
    };

    var jsonString = "{json: '" + JSON.stringify(params) + "'}";
    var serviceURL = resolveURL("WebServices/BasketServices.asmx/UpdateItemQuantity");
    $.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);
        }
    });
    
}


/********************************************
 * Determines if the user is updating their amendment basket by looking at the 
 * hfUseAmendmentBasket hidden field.
 *******************************************/
function UseAmendmentBasket() {

    var useAmendmentBasket = document.getElementById('hfUseAmendmentBasket');

    if (useAmendmentBasket == null || (useAmendmentBasket != "false" & useAmendmentBasket != "true")) {
        useAmendmentBasket = "false";
    }
    
    return useAmendmentBasket;
}


/*
 * ----------------------------------------------------------------------------
 * PRODUCT LISTING FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */
 
/********************************************
 * Adds an each or weighted each item from the product listing by getting all 
 * needed information from the product's row and then calling 
 * BasketServices.AddItemToBasket web method.  
 *******************************************/
function AdEIFPL(pid)
{
    var productRow = $('#' + pid);

    if (productRow.length != 0)
    {
        var quantity, note, substitute;
        quantity = productRow.find("INPUT[NAME$='tbQuantity']").val();
        note = productRow.find("INPUT[NAME$='hfItemNote']").val();
        if (note == undefined) { note = "";  }
        substitute = productRow.find("*[ID$='hfDoNotSubstitute']").val();
        if (productRow.find("*[ID$='cbDoNotSubstitute']") != null) {
            
             substitute = productRow.find("*[ID$='cbDoNotSubstitute']").attr("checked");
            
        }
        if (substitute == undefined || substitute == "") {
            substitute = false;
        }

        AddItemToBasket(pid, quantity, note, substitute);
        productRow.find("*[ID$='hfQuantity']").val(quantity);
    }
    else {
        // alert error
    }
}


/********************************************
 * Adds/updates weighted item from the product listing by getting all needed 
 * information from the product's row and then calling weighted item popup.
 AddWeightedItemFromProductListing
 *******************************************/
function AWIFPL(pid) {
    var productRow = $('#' + pid);
    
    if (productRow.length != 0) {
        var productName, pricePerUnit, quantity, note, substitute;
    
        
        if (productRow.find("A[ID$='lnkProductName']") != null &&
             productRow.find("A[ID$='lnkProductName']") != undefined) {
            productName = productRow.find("A[ID$='lnkProductName']").text();
        }//for referential
        else if (row.find("*[ID$='lblProductTitle']") != null &&
                row.find("*[ID$='lblProductTitle']") != undefined)
        {
            productName = row.find("*[ID$='lblProductTitle']").text();
        }
        
        pricePerUnit = productRow.find("*[ID$='hfCurrentItemPrice']").val();

        quantity = productRow.find("*[ID$='lblItemSelectedQuantity']").text();
        
        if((quantity == undefined) || (quantity == "")) {
            quantity = 0;
        }
        else {
            quantity = quantity.substring(2, quantity.length);
            quantity = parseFloat(quantity);
        }
        
        note = productRow.find("INPUT[NAME$='hfItemNote']").val();
        if (note == undefined) {
            note = "";
        }

        doNotsubstitute = productRow.find("INPUT[NAME$='hfDoNotSubstitute']").val();
        if (doNotsubstitute == undefined || doNotsubstitute == "") {
            doNotsubstitute = false;
        }
        productRow.find("*[ID$='hfQuantity']").val(quantity);
        WeightedItemPopupShow(pid, productName, pricePerUnit, quantity, note, doNotsubstitute, WeightItemPopupOnAddToBasketClickCallUpdateQuantityWebService);
    }
    else {
        // alert error
    }
}



 
/********************************************
* Updates how the status of a basket item is displayed in the product listing
* by ensuring the cart image is shown, the view basket link is shown, button
* is the update button, the quantity of the item is correct, the add note
* tooltip is removed, and the event handlers for the update and note buttons
* are properly attached.
*******************************************/
function AddUpdateItemInProductListing(basketServiceResult) {
    var productRow = $('#' + basketServiceResult.ProductID);
    
    if (productRow.length != 0) {
        productRow.find("IMG[ID$='imgAddToBasket']").css("display", "none");
        productRow.find("IMG[ID$='imgUpdateBasket']").css("display", "block");

        productRow.find("A[ID$='lnkInBasket']").css("display", "block");
        productRow.find("IMG[ID$='imgBasket']").css("display", "block");

        var q = fnFormatNum(basketServiceResult.Quantity, 2);
        
        if (basketServiceResult.IsWeighted) {
            //this is used for product listing
            if (productRow.find("A[ID$='btnChooseWeight']") != null || productRow.find("A[ID$='btnChooseWeight']") != undefined) {
                productRow.find("A[ID$='btnChooseWeight']").attr("class", "changeWeight");
                productRow.find("A[ID$='btnChooseWeight']").attr("title", "Change Weight");
            }
            //this is used for product listing by category
            if (productRow.find("A[ID$='btnChooseWeightSmall']") != null || productRow.find("A[ID$='btnChooseWeightSmall']") != undefined) {
                productRow.find("A[ID$='btnChooseWeightSmall']").attr("class", "changeWeightSmall");
                productRow.find("A[ID$='btnChooseWeightSmall']").attr("title", "Change Weight");
            }
            
            if (q < 1) {
                productRow.find("*[ID$='lblGramEquivalent']").show().text(fnFormatNum(q * 16,2) + " oz");
                productRow.find("*[ID$='lblItemSelectedQuantity']").hide().text(" x " + q + " lb");
            }
            else {
                productRow.find("*[ID$='lblGramEquivalent']").hide();
                productRow.find("*[ID$='lblItemSelectedQuantity']").show().text(" x " + q + " lb");
            }
            productRow.find("*[ID$='tbQuantity']").val(parseFloat(q));
            productRow.find("*[ID$='hfQuantity']").val(parseFloat(q));
        }
        else {
            productRow.find("*[ID$='tbQuantity']").val(parseInt(q));
            productRow.find("*[ID$='lblItemSelectedQuantity']").text(" x " + q);
            productRow.find("A[ID$='btnAddToBasket']").attr("class", "update");
            productRow.find("A[ID$='btnAddToBasket']").attr("title", "Update");
            
            productRow.find("A[ID$='btnAddToBasket']").unbind("click");
            productRow.find("A[ID$='btnAddToBasket']").bind("click", function(eventObject) {
            AdEIFPL(basketServiceResult.ProductID);
                return false;
            });
        }

        
       
        if (productRow.find("*[ID$='lblTotalPriceValue']") != null || productRow.find("*[ID$='lblTotalPriceValue']") != undefined) {
            var totalprice = "$" + fnFormatNum(parseFloat(basketServiceResult.PricePerUnit) * parseFloat(basketServiceResult.Quantity), 2);
            productRow.find("*[ID$='lblTotalPriceValue']").text(totalprice);
        }
        
        productRow.find("A[ID$='addNote']").removeAttr("onmouseover");

        //productRow.find("*[ID$='addNote']").unbind("click");
        productRow.find("*[ID$='addNote']").unbind("mousemove");
        productRow.find("*[ID$='addNote']").attr("href", "javascript:sANP('" + basketServiceResult.ProductID + "')");

    }
}

//change back to previous code in orde add favorite works on productlisting page
//AddRemoveFavoriteFromProductListing
function ARFFPL(pid) {
    
    AddRemoveFavorite(pid, 'LISTING');
}


/********************************************
 * Removes the product as being in the basket in a product listing by hiding 
 * the cart image is shown and view basket link is shown, changing button
 * to add button, hiding the quantity of the item, adding the tooltip onto the 
 * note icon, and attaching event handlers for the add and note buttons.
 *******************************************/
function RemoveItemFromProductListing(basketServiceResult) {
    var productRow = $('#' + basketServiceResult.ProductID);
    
    if (productRow.length != 0) {
        productRow.find("A[ID$='lnkInBasket']").css("display", "none");
        productRow.find("IMG[ID$='imgBasket']").css("display", "none");
        productRow.find("span[ID$='lblItemSelectedQuantity']").css("display", "none");
        productRow.find("IMG[ID$='imgAddToBasket']").css("display", "block");
        productRow.find("IMG[ID$='imgUpdateBasket']").css("display", "none");             
        if (basketServiceResult.IsWeighted) {
            if (productRow.find("A[ID$='btnChooseWeight']") != null || productRow.find("A[ID$='btnChooseWeight']") != undefined) {
                productRow.find("A[ID$='btnChooseWeight']").attr("class", "selectWeight");
                productRow.find("A[ID$='btnChooseWeight']").attr("title", "Select Weight");
                productRow.find("A[ID$='btnChooseWeightSmall']").attr("class", "selectWeightSmall");
                productRow.find("A[ID$='btnChooseWeightSmall']").attr("title", "Select Weight");
                productRow.find("*[ID$='lblGramEquivalent']").hide();
            }
        }
        else {
            productRow.find("A[ID$='btnAddToBasket']").attr("class", "add");
            productRow.find("A[ID$='btnAddToBasket']").attr("title", "Add");
        }

        productRow.find("*[ID$='tbQuantity']").val(1);
        productRow.find("*[ID$='hfItemNote']").val("");
        bqtyc(basketServiceResult.ProductID);
        productRow.find("LABEL[ID$='lblItemSelectedQuantity']").text("");

        productRow.find("*[ID$='hfQuantity']").val("");
        productRow.find("IMG[ID$='imgNoteAdded']").css("display", "none");
        productRow.find("A[ID$='addNote']").removeClass("selected");
        
        productRow.find("A[ID$='addNote']").unbind("click");        
        
        productRow.find("A[ID$='btnAddToBasket']").unbind("click");
        productRow.find("A[ID$='btnAddToBasket']").bind("click", function(eventObject) {
        AdEIFPL(basketServiceResult.ProductID);
            return false;
        });
    }
}


/*
 * ----------------------------------------------------------------------------
 * MINI BASKET FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */
 
/******************************************
 * Updates the mini cart, either inserting a new basket item or updating an 
 * existing item.
*******************************************/
function AddUpdateItemInMiniCart(basketServiceResult) {

    // need to check if item in basket already -- if so delete
    // also need to take care of weighted items
    var divMiniCart = $("#divMiniCart");
    
    var itemDivID = basketServiceResult.ProductID + "_minibasketitem";
    var itemDiv = divMiniCart.find("#" + itemDivID);
    
    var itemInfoHTML = "<input id=\"hfItemNote\" type=\"hidden\" value=\"" + basketServiceResult.Note + "\"/> " +
                        "<input id=\"hfDoNotSubstitute\" type=\"hidden\" value=\"" + basketServiceResult.DoNotSubstitute + "\"/> ";

    if (basketServiceResult.IsWeighted) {
        var qtyText;
        if (basketServiceResult.Quantity < 1)
        {
            qtyText = "x " + (basketServiceResult.Quantity * 16) + " oz";
        }
        else
        {
            qtyText = "x " + basketServiceResult.Quantity + " lb";
        }
    
        itemInfoHTML += "<input id=\"hfProductName\" type=\"hidden\" value=\"" + basketServiceResult.ProductName + "\"/> " +
                        "<input id=\"hfPricePerUnit\" type=\"hidden\" value=\"" + basketServiceResult.PricePerUnit + "\"/> " +
                        "<input id=\"hfQuantity\" type=\"hidden\" value=\"" +fnFormatNum(basketServiceResult.Quantity,2) + "\"/> " +
                        "<span class=\"miniCartQty\">" + 
                            "<img src=\"" + resolveURL("App_Themes/RocheBros_en/Images/icon_small_weightedItem.gif") + "\" alt=\"Weighted Item\"/>" +
                        "</span>" +
                        "<span>" + basketServiceResult.ProductName + "</span>" +
                        "<span> " + qtyText + "</span>" +
                        "<span class=\"miniCartBtn\">" +
                            "<a href=\"javascript:UWIQFMC('" + basketServiceResult.ProductID + "')\">" +
                                "<img src=\"" + resolveURL("App_Themes/RocheBros_en/Images/btn_cart_changeWeight.gif") + "\" alt=\"Choose Weight\"/>" +
                            "</a>" +
                            "<a href=\"javascript:RIFRB('" + basketServiceResult.ProductID + "')\">" +
                                "<img src=\"" + resolveURL("App_Themes/RocheBros_en/Images/btn_small_XRemove.gif") + "\" alt=\"Remove\"/>" +
                            "</a>" +
                        "</span>";
    }
    else {
        itemInfoHTML +=  "<span class=\"miniCartQty\">" + basketServiceResult.Quantity + " x</span>" +
                        "<span>" + basketServiceResult.ProductTitle + "</span>" +
                        "<span class=\"miniCartBtn\">" +
                            "<a href=\"javascript:IEIQFMB('" + basketServiceResult.ProductID + "')\">" +
                                "<img height=\"12\" width=\"15\" src=\"" + resolveURL("App_Themes/RocheBros_en/Images/btn_Plus.gif") + "\" alt=\"Plus\"/>" +
                            "</a>" +
                            "<a href=\"javascript:DEIQFMB('" + basketServiceResult.ProductID + "')\">" +
                                "<img height=\"12\" width=\"15\" src=\"" + resolveURL("App_Themes/RocheBros_en/Images/btn_Minus.gif") + "\" alt=\"Minus\"/>" +
                            "</a>" +
                            "<a href=\"javascript:RIFRB('" + basketServiceResult.ProductID + "')\">" +
                                "<img src=\"" + resolveURL("App_Themes/RocheBros_en/Images/btn_XRemove.gif") + "\" alt=\"Remove\"/>" +
                            "</a>" +
                        "</span>";
    }
    
                        
    if (itemDiv.length == 0) {
        newItemString = "<div id=\"" + itemDivID + "\">" +
                            itemInfoHTML +
                        "</div>" +
                        "<div class=\"clear\"></div>" +
                        "<div class=\"separator_h\"></div>";

        divMiniCart.find(".cartContents").prepend(newItemString);

    }
    else {
        itemDiv.html(itemInfoHTML);
      
    }

    divMiniCart.find("*[ID$='lblSavings']").text("-$" + basketServiceResult.TotalSavings.toFixed(2));
    divMiniCart.find("*[ID$='lblEstimatedCost']").text("$" + basketServiceResult.TotalPrice.toFixed(2));

    //enable buttons on the cart
    var viewYourCartUrl = divMiniCart.find("input[ID$='hfViewCartButtonUrl']").val();
    var goToCheckoutUrl = divMiniCart.find("input[ID$='hfCheckoutUrl']").val()
    divMiniCart.find("*[ID$='btnViewYourCart']").attr("href", viewYourCartUrl);
    divMiniCart.find("*[ID$='btnGoToCheckout']").attr("href", goToCheckoutUrl);

}


/********************************************
 * Decreases the quantity of an each item in the mini basket by calling 
 * BasketServices.UpdateItemQuantity web method.
 DecreaseEachItemQuantityFromMiniBasket
 *******************************************/
function DEIQFMB(pid) {
    var itemDivID = pid + "_minibasketitem";
    var itemDiv = $("#" + itemDivID);
    var quantity = parseInt(itemDiv.find(".miniCartQty").text());
    
    if (quantity > 1) {
        UpdateItemQuantity(pid, quantity - 1);
    }
}


/********************************************
 * Increases the quantity of an each item in the mini basket by calling 
 * BasketServices.UpdateItemQuantity web method.
 IncreaseEachItemQuantityFromMiniBasket
 *******************************************/
function IEIQFMB (pid) {
    var itemDivID = pid + "_minibasketitem";
    var itemDiv = $("#" + itemDivID);
    var quantity = parseInt(itemDiv.find(".miniCartQty").text());

    UpdateItemQuantity(pid, quantity + 1);
}


/******************************************
    Removes the item from the mini cart.
*******************************************/
function RemoveItemFromMiniCart(basketServiceResult) {
    var itemDivID = basketServiceResult.ProductID + "_minibasketitem";
    var itemDiv = $("#" + itemDivID);
    
    // remove the clear and separator_h divs that follow the mini cart item
    itemDiv.next(".clear").remove();
    itemDiv.next(".separator_h").remove();
    
    itemDiv.remove();
    
    $("*[ID$='lblSavings']").text("-$" + basketServiceResult.TotalSavings.toFixed(2));
    $("*[ID$='lblEstimatedCost']").text("$" + basketServiceResult.TotalPrice.toFixed(2));

    //check if there is no basketitem left,disable the buttons
    if (basketServiceResult.TotalPrice.toFixed(2) <= 0) {
        $("*[ID$='btnViewYourCart']").removeAttr("href");
        $("*[ID$='btnGoToCheckout']").removeAttr("href");
    }
}


/********************************************
 * Shows the weighted item popup from the minicart so that the user can make 
 * updates to weighted item.
 UpdateWeightedItemQuantityFromMiniCart
 *******************************************/
function UWIQFMC(pid) {
    var itemDivID = pid + "_minibasketitem";
    var itemDiv = $("#" + itemDivID);
    
    if (itemDiv.length != 0) {
        var productName, pricePerUnit, quantity, note, substitute;

        productName = itemDiv.find("INPUT[ID$='hfProductName']").val();
        
        pricePerUnit = itemDiv.find("INPUT[ID$='hfPricePerUnit']").val();
        pricePerUnit = parseFloat(pricePerUnit);
        note = itemDiv.find("INPUT[ID$='hfItemNote']").val();
        doNotSubstitute = itemDiv.find("INPUT[ID$='hfDoNotSubstitute']").val();

        quantity = itemDiv.find("INPUT[ID$='hfQuantity']").val();
        
        if((quantity == undefined) || (quantity == "")) {
            quantity = 0;
        }
        else {
            quantity = parseFloat(quantity);
        }
        
        WeightedItemPopupShow(pid, productName, pricePerUnit,quantity, note,
            doNotSubstitute, WeightItemPopupOnAddToBasketClickCallUpdateQuantityWebService);
    }
    else {
        // alert error
    }
}


/*
 * ----------------------------------------------------------------------------
 * PRODUCT DETAILS FUNCTIONS
 * ---------------------------------------------------------------------------- 
 */
 

/********************************************
 * Adds an item from the product details by getting all needed information from 
 * the product detail's panel and then calling BasketServices.AddItemToBasket web 
 * method.
 *******************************************/
function AddItemFromProductDetails(pid) {
    var productPnl = $('#pnlDetails');
    var selQuantity = productPnl.find("*[ID$='tbQuantity']").val();  
    var selWeight = productPnl.find("*[ID$='tbQuantityDouble']").val();
    var note = productPnl.find("*[ID$='tbItemNote']").val();
    
    var substitute = productPnl.find("*[ID$='cbDoNotSubstitute']").attr("checked");

    if (productPnl.length != 0) {
        var quantity;
        
        note = productPnl.find("*[ID$='tbItemNote']").val();
        if (note == undefined) {
            note = "";
        }
        else {
            //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 ");
           
        }
        
        
        if (substitute == undefined) {
            substitute = false;
        }

        if (selQuantity == undefined) {
            quantity = selWeight;
        }
        else if (selWeight == undefined) {
        quantity = selQuantity;
        }
        else {
            quantity = 0.00;
        }
        if (quantity <= 0) {
            alert("please select a quantity");
            return;
        }
        AddItemToBasket(pid, quantity, note, substitute);
    }
    else {
        // alert error
    }
}
    
 
/********************************************
 * Updates how the status of a basket item is displayed in the product details
 * by ensuring the cart image and view basket link are shown, button
 * is the update button, the quantity of the item is correct, the add note
 * tooltip is removed, and the event handlers for the update and note buttons
 * are properly attached.
 *******************************************/   
function AddUpdateItemInProductDetails(basketServiceResult) {
    var productPnl = $('#divProductDetails');
    
    if (productPnl.length != 0) {
        var currentProductDisplayed = productPnl.find("*[ID$='hfProductId']").val();
        
        if (currentProductDisplayed == basketServiceResult.ProductID) {

            //var imgBtn = $("#addProductContainer *[ID$='imgAddToBasket']");
            var imgBtn = productPnl.find("*[ID$='imgAddToBasket']");
            
            var imgPath = imgBtn.attr("src");
            var arrPath = imgPath.split('/');
            
            arrPath[arrPath.length - 1] = "btn_update.gif";
            imgBtn.removeAttr("style");
            imgBtn.attr("src", arrPath.join('/'));

            productPnl.find("A[ID$='lnkInBasket']").css("display", "block");
            productPnl.find("IMG[ID$='imgBasket']").css("display", "block");

            if (basketServiceResult.IsWeighted) {
                if (basketServiceResult.Quantity < 1) {
                    productPnl.find("*[ID$='lblGramEquivalent']").css("display", "block");
                }
                else {
                    productPnl.find("*[ID$='lblGramEquivalent']").css("display", "none");
                }

                productPnl.find("*[ID$='lblItemSelectedQuantity']").text(" x " + fnFormatNum(parseFloat(basketServiceResult.Quantity), 2) + " lb");
            }
            else {
                productPnl.find("*[ID$='lblItemSelectedQuantity']").text(" x " + fnFormatNum(parseFloat(basketServiceResult.Quantity), 2));
            }

            productPnl.find("*[ID$='tbQuantityDouble']").val(fnFormatNum(parseFloat(basketServiceResult.Quantity), 2));

            var pricePerUnit = productPnl.find("*[ID$='hfDiscountedPrice']").val();
            var total = fnFormatNum(parseFloat(pricePerUnit) * parseFloat(basketServiceResult.Quantity), 2);

            productPnl.find("*[ID$='lblTotalPrice']").text("$" + total);
            productPnl.find("*[ID$='tbItemNote']").val(basketServiceResult.Note);
        }
    }
}

function IncrementDetailsWeight(tdId, increment, price, priceLabel, oldPrice, oldPriceLabel) {
    fnWeightPlus(tdId, increment);
    UpdateWeightDetailsPriceLabel(tdId, increment, price, priceLabel, oldPrice, oldPriceLabel)
}
function DecrementDetailsWeight(tdId, increment, price, priceLabel, oldPrice, oldPriceLabel) {
    fnWeightMinus(tdId, increment);
    UpdateWeightDetailsPriceLabel(tdId, increment, price, priceLabel, oldPrice, oldPriceLabel)
}
function IncrementDetailsTotalPrice(tdId, price, priceLabel,oldPrice,oldPriceLabel) {
    fnpl(tdId);
    UpdateDetailsLabel(tdId, price, priceLabel, oldPrice, oldPriceLabel);
}
function DecrementDetailsTotalPrice(tdId, price, priceLabel, oldPrice, oldPriceLabel) {
    fnmi(tdId);
    UpdateDetailsLabel(tdId, price, priceLabel, oldPrice, oldPriceLabel);
}

/********************************************
 * Removes the product as being in the basket in product details by hiding 
 * the cart image and view basket link, changing button to add button, 
 * hiding the quantity of the item, and adding the tooltip onto the 
 * note icon.
 *******************************************/
function RemoveItemFromProductDetails(basketServiceResult) {
    var productPnl = $('#divProductDetails');
    
    if (productPnl.length != 0) {
        var currentProductDisplayed = productPnl.find("*[ID$='hfProductId']").val();
        
        if (currentProductDisplayed == basketServiceResult.ProductID) {

            var imgBtn = productPnl.find("IMG[ID$='imgAddToBasket']");
            var imgPath = imgBtn.attr("src");
            var arrPath = imgPath.split('/');
            arrPath[arrPath.length - 1] = "btn_addToCart.gif";
            imgBtn.removeAttr("style");
            imgBtn.attr("src", arrPath.join('/'));

            //There is no hfItemNote in the ProductDetails page,so this line is not needed,this will fix defect 16569
            //$("#addProductContainer A[ID$='hfItemNote]").val(""); //added to clear the note

            productPnl.find("A[ID$='lnkInBasket']").css("display", "none");
            productPnl.find("IMG[ID$='imgBasket']").css("display", "none");
            productPnl.find("*[ID$='lblGramEquivalent']").css("display", "none");

            productPnl.find("*[ID$='lblItemSelectedQuantity']").text("");
            productPnl.find("*[ID$='tbQuantity']").val(1);
            productPnl.find("*[ID$='tbQuantityDouble']").val(1.00);

            var pricePerUnit = productPnl.find("*[ID$='hfDiscountedPrice']").val();
            var total = fnFormatNum(parseFloat(pricePerUnit), 2);

            productPnl.find("*[ID$='lblTotalPrice']").text("$" + total);
            
            $("#pnlDetails *[ID$='tbItemNote']").val("");
        }
    }
}

function UpdateWeightOnChange(tdId, increment, price, priceLabel, oldPrice, oldPriceLabel) {

    UpdateWeightDetailsPriceLabel(tdId, increment, price, priceLabel, oldPrice, oldPriceLabel);
}

function UpdateDetailsLabel(tdId, price, priceLabel, oldPrice, oldPriceLabel) {
    fnValidateQuantityRange(tdId);
    var q = $("#" + tdId).val();
    var total = fnFormatNum(parseFloat(q) * parseFloat(price), 2);
    var oldtotal = fnFormatNum(parseFloat(q) * parseFloat(oldPrice), 2);
    $("#" + priceLabel).text("$" + total);
  
}

function UpdateWeightDetailsPriceLabel(tdId, increment, price, priceLabel, oldPrice, oldPriceLabel) {
    //var q = $("#" + tdId).val();
    var q = $get(tdId).value;
    q = fnFormatNum(parseFloat(q),2);
    var thePreviousSelectedQuantity = $(".productDetails *[ID$='lblItemSelectedQuantity']").text().trim().substring(1);

    if (isNaN(q) || parseFloat(q) <= 0 || q == "" || parseFloat(q) > 999) {
        q = "1.00";
        if (thePreviousSelectedQuantity != null && thePreviousSelectedQuantity != undefined && thePreviousSelectedQuantity != "") {
            q = parseFloat(thePreviousSelectedQuantity);
        }
        $("#" + tdId).val(q);
    }
    var dotPosition = q.toString().indexOf(".");

    
    if (q.toString().substring(dotPosition + 1, q.length).length > 2) {
        $("#" + tdId).val(fnFormatNum(q,2));
    }

    var total = fnFormatNum(parseFloat(q) * parseFloat(price), 2);
    var oldtotal = fnFormatNum(parseFloat(q) * parseFloat(oldPrice), 2);
    $("#" + priceLabel).text("$" + total);
    var $productDetails = $(".productDetails");
    if (q < 1) {
       $productDetails.find("*[ID$='lblGramEquivalent']").show();
       $productDetails.find("*[ID$='lblGramEquivalent']").text(fnFormatNum(q * 16, 2) + " oz");
       
    }
    else
        $productDetails.find("*[ID$='lblGramEquivalent']").hide();

    $productDetails.find("*[ID$='tbQuantityDouble']").val(q);  
}


function AddUpdateItemInReferentials(basketServiceResult) {

    var row = $('#' + basketServiceResult.ProductID);

   
    var q = fnFormatNum(basketServiceResult.Quantity, 2);
    if (basketServiceResult.IsWeighted) {
        if (row.find("A[ID$='btnChooseWeight']") != null || row.find("A[ID$='btnChooseWeight']") != undefined) {
            row.find("A[ID$='btnChooseWeight']").attr("class", "changeWeight");
            row.find("A[ID$='btnChooseWeight']").attr("title", "Change Weight");
        }
        if (q < 1) {
            row.find("*[ID$='lblGramEquivalent']").show().text(fnFormatNum(q * 16,2) + " oz");
            row.find("*[ID$='lblItemSelectedQuantity']").hide().text(" x " + q + " lb");
        }
        else {
            row.find("*[ID$='lblGramEquivalent']").hide();
            row.find("*[ID$='lblItemSelectedQuantity']").show().text(" x " + q + " lb");
        }
    }
    else {
        row.find("A[ID$='btnAddToBasket']").attr("class", "update");
        row.find("A[ID$='btnAddToBasket']").attr("title", "Update");
        row.find("*[ID$='lblItemSelectedQuantity']").text(" x " + q);
    }

    row.find("A[ID$='lnkInBasket']").css("display", "block");
    row.find("IMG[ID$='imgBasket']").css("display", "block");

    row.find("#tbTrolleyQuantity").show();

}
 
function AddItemFromReferential(pid) {
    // Get all needed information from referential
    // Call AddItemToBasket
    
}

function RemoveItemFromReferentials(basketServiceResult) {

    var row = $('#' + basketServiceResult.ProductID);
    row.find("A[ID$='lnkInBasket']").css("display", "none");
    row.find("IMG[ID$='imgBasket']").css("display", "none");
    
}

function bqtycpl(pid) {
    var productRow = $('#' + pid);
    var tb = productRow.find("*[ID$='tbQuantity']");
    fnpl(tb.attr('id'));
    bqtyc(pid);
}
function bqtycmi(pid) {
    var productRow = $('#' + pid);
    var tb = productRow.find("*[ID$='tbQuantity']");
    fnmi(tb.attr('id'));
    bqtyc(pid);
}
/*
 * ----------------------------------------------------------------------------
 * BASKET LISTING FUNCTIONS
 * ---------------------------------------------------------------------------- 
 basketQtyChanged
 */

function bqtyc(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 priceEach = row.find("*[ID$='hfCurrentItemPrice']").val();
        priceEach = parseFloat(priceEach.replace(/^\D+/, ""));
        var totalPrice = priceEach * qty
        row.find("*[ID$='lblTotalPriceValue']").text("$" + totalPrice.toFixed(2));

        ActivateUpdateBasketButton();

        //set the qty and price to red to indicate that they have changed
        row.find("*[ID$='tbQuantity']").attr("style", "color: red");
        row.find("*[ID$='lblTotalPriceValue']").attr("style", "color: red");
    }


}



function ActivateUpdateBasketButton() {

    
    var hdnUrlPath = $("*[ID$='hfSiteUrlWithTheme']").val();

    $("#imgUpdateBasketBottom").attr("src", hdnUrlPath + "/images/buttons/btn_confirmChanges.gif");
    $("#imgUpdateBasketBottom").attr("title", "Confirm Changes");
    $("*[ID$='btnUpdateBasketBottom']").removeAttr("onclick");
    $("#imgUpdateBasketTop").attr("src", hdnUrlPath + "/images/buttons/btn_confirmChanges.gif");
    
    $("#imgUpdateBasketTop").attr("title", "Confirm Changes");
    
    $("*[ID$='btnUpdateBasketTop']").removeAttr("onclick");

    $("*[ID$='divUpdateBasketMessageTop']").attr("style", "display:inline;");
   
    $("*[ID$='divUpdateBasketMessageBotom']").attr("style", "display:inline;");


                            
                            
    }





function toggleProductImagesOnViewBasket() {

    //check the visibility of the div that the image is contained in
    //then toggle the visibility of this
    var row = $(".listing_view");
    var visibility
    var strVisibleState = row.find("*[ID$='divProductImages']").attr("style");
    
    if (strVisibleState.search(/hidden/) != -1) {
        visibility = "visible";
    }
    else {
        visibility = "hidden";
        row.find("*[ID$='lblTurnOffImagesHeading']").text("Turn Images On");
    }

    row.find("*[ID$='divProductImages']").css("visibility", visibility);

}





// 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("*[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("*[ID$='hfItemRemoved']").val("true");
        row.find("*[ID$='btnProductImage']").attr("disabled", true);
        row.find("*[ID$='btnFavorites']").attr("disabled", true);
        row.find("*[ID$='btnFavorites']").attr("class", "favorite");
        row.find("*[ID$='addNote']").attr("disabled", true);
        row.find("*[ID$='addNote']").removeClass("selected");
        
        //disable the qty box
        row.find("*[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("*[ID$='lnkQuantityPlus']").attr("href");
        row.find("*[ID$='hfQtyPlusHref']").val(hrefQtyPlus);
        row.find("*[ID$='lnkQuantityPlus']").attr("href", "javascript:void(0);");
        hrefQtyMinus = row.find("*[ID$='lnkQuantityMinus']").attr("href");
        row.find("*[ID$='hfQtyMinusHref']").val(hrefQtyMinus);
        row.find("*[ID$='lnkQuantityMinus']").attr("href", "javascript:void(0);");

        if (row.find("A[ID$='btnChooseWeight']") != null || row.find("A[ID$='btnChooseWeight']") != undefined) {
            row.find("*[ID$='btnChooseWeight']").attr("class", "changeWeightSmall");
            row.find("*[ID$='btnChooseWeight']").attr("title", "Change Weight");
            row.find("*[ID$='btnChooseWeight']").attr("disabled", true);
        }

            
        if (row.find("A[ID$='btnChooseWeightSmall']") != null || row.find("A[ID$='btnChooseWeightSmall']") != undefined) {
                 row.find("*[ID$='btnChooseWeightSmall']").attr("class", "changeWeightSmall");
                 row.find("*[ID$='btnChooseWeightSmall']").attr("disabled", true);
                 row.find("*[ID$='btnChooseWeightSmall']").attr("title", "Change Weight");
            }
        
        row.find("*[ID$='imgRemove']").attr("src", "../App_Themes/RocheBros_en/Images/buttons/bttn_basket_undelete.gif");

        ActivateUpdateBasketButton()
        
        
    }
    else {

        row.find("*[ID$='td']").removeAttr("style");
        
        row.find("*[ID$='hfItemRemoved']").val("false");
        row.find("*[ID$='btnProductImage']").removeAttr("disabled");
        row.find("*[ID$='btnFavorites']").removeAttr("disabled");
        row.find("*[ID$='btnFavorites']").attr("class", "favorite");
        row.find("*[ID$='addNote']").removeAttr("disabled");
        row.find("*[ID$='addNote']").removeClass("selected");
        row.find("*[ID$='tbQuantity']").removeAttr("disabled");
        hrefQtyPlus = row.find("*[ID$='hfQtyPlusHref']").val();
        row.find("*[ID$='lnkQuantityPlus']").attr("href", hrefQtyPlus);

        hrefQtyMinus = row.find("*[ID$='hfQtyMinusHref']").val();
        row.find("*[ID$='lnkQuantityMinus']").attr("href", hrefQtyMinus);

        if (row.find("A[ID$='btnChooseWeight']") != null || row.find("A[ID$='btnChooseWeight']") != undefined) {
            row.find("*[ID$='btnChooseWeight']").removeAttr("disabled");
            row.find("*[ID$='btnChooseWeight']").attr("class", "changeWeightSmall");
            row.find("*[ID$='btnChooseWeight']").attr("title", "Change Weight");
        }

        if (row.find("A[ID$='btnChooseWeightSmall']") != null || row.find("A[ID$='btnChooseWeightSmall']") != undefined) {
            row.find("*[ID$='btnChooseWeightSmall']").removeAttr("disabled");
            row.find("*[ID$='btnChooseWeightSmall']").attr("class", "changeWeightSmall");
            row.find("*[ID$='btnChooseWeightSmall']").attr("title", "Change Weight");
        }
        row.find("*[ID$='imgRemove']").attr("src", "../App_Themes/RocheBros_en/Images/buttons/bttn_basket_delete.gif");
   
    }
    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 clientId = $("#pnl_AddnoteClientId").val();
        var modalPopup = $("#" + clientId);
        if (modalPopup != null) {

            $('body').append(modalPopup);

            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");
            
            }
             modalPopup.find("SPAN[ID$='lblproductName']").text(productname);
             modalPopup.find("SPAN[ID$='lblPricePerUnit']").text(pricePerUnit);



            modalPopup.find("*[ID$='btnAddToBasketNote']").attr("href", "javascript:addNoteToBasketItem(" + pid + ")");
          
           
           modalPopup.find("*[ID$='tbItemNote']").val(note);

           modalPopup.jqm();
           modalPopup.jqmShow();
        }
    }
    
   
}






/****************************************
Add a weighted product to the 
basket from the ChooseWeightPopup
****************************************/
function addItemToBasketWeightedFromBasket(note,doNotsubstitute) {
    var quantity = "";
    var pid = "";
    var price = "";

    // get data from the popup control
    var clientId = $("#pnlChooseWeightClientID").val();
    var modalPopup = $("#" + clientId);
    
    if (modalPopup != null) {
        quantity = modalPopup.find("*[ID$='tbQuantityDouble']").val();
        pid = modalPopup.find("*[ID$='hfProductId']").val();
        price = modalPopup.find("*[ID$='hfPopupPrice']").val();

        if (quantity <= 0) {
            alert("please select a quantity");
            return;
        }
    }

    var row = $("#"+pid);

    row.find("*[ID$='hfWeightedQuantity']").val(quantity);
    row.find("*[ID$='hfQuantity']").val(quantity);
    row.find("*[ID$='hfItemNote']").val(note);
    row.find("*[ID$='hfDoNotSubstitute']").val(doNotsubstitute);
    row.find("*[ID$='lblTotalPriceValue']").text('$' + (parseFloat(quantity) * parseFloat(price)).toFixed(2));
    // Switch the changeweight class 
    row.find("A[ID$='btnChooseWeight']").attr("class", "changeWeightSmall");
    row.find("A[ID$='btnChooseWeight']").attr("title", "Change Weight");


    // write the quantity to the cell beside the Trolley icon
    quantity = parseFloat(quantity).toFixed(2);
    var displayText = "";
    if (quantity < 1) {
        displayText = "<br />x " + (quantity * 16) + " oz";
    }
    else {
        displayText = "<br />x " + quantity + " lb";
    }

    row.find("*[ID$='lblWeightedQty']").html(displayText);
    row.find("*[ID$='lblItemSelectedQuantity']").html(displayText);
    // reset default values. must be reset as each row in the product listing uses the same control.
    if (modalPopup != null) {
        modalPopup.find("*[ID$='tbItemNote']").val("");
        modalPopup.find("*[ID$='tbQuantityDouble']").val(1.00);
        modalPopup.find("*[ID$='cbDoNotSubstitute']").attr("checked", false);
        modalPopup.jqmHide();
    }

    // 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']");


    //activate the update button so the user can save their changes
    ActivateUpdateBasketButton();    
}



function CheckBasketSave() {

    var clientId = $("#pnlChooseWeightClientID").val();

    var modalPopup = $("#" + clientId);

    modalPopup.jqm();
    modalPopup.jqmShow();


}
/* change sub policy */
function chsb(pid) {
    var row = $('#' + pid).parent();
    var donotsub = 1;
    if (row.find("INPUT[ID$='cbSubstitute']").attr("checked") == false) {
        donotsub = 0;
    }
    var serviceURL = resolveURL("WebServices/BasketServices.asmx/SetSubstitutionPolicy");
    $.ajax({
        type: "POST",
        url: serviceURL,
        data: "{'ProductID': '" + pid + "','donotSub': '" + donotsub + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("There was an error trying to process the last operation."
            + "Error: " + errorThrown + "  TextStatus:  " + textStatus);
        }
    });
}




