﻿function AddToBasketForHome(productid, price)
{
    CheckDivCookie();
    //proceed only if add to basket button is enabled
    if (!$("#" + productid + "_addtobasket").attr("disabled"))
    {
        // Pass on quantity if present
        var qty = 1;
        if ($("#txtQty").length > 0) { qty = $("#txtQty").attr("value"); }

        $.ajax({
            type: "POST",
            url: "./WebService/Basket.asmx/AddToBasket",
            data: "{'ProductId':'" + productid + "','Price':'" + price + "','Quantity':'" + qty + "'}",
            success: function(data) {
                if (data.d[0] == "true") {
                    ShowSuccessImage(data, productid);
                    $("#ucCart_cartHeadTotal").html(data.d[1]);
                }
                else if (data.d[0] == "false") {
                    ShowAddToBasketFailImage(data, productid,qty);
                }
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(e, textStatus, errorThrown) {
                bReturn = false;
            }
        });

        
    }
}


function AddToBasketWithReturnIDs(productid, price)
{
    //document.write("dickie chikago");
    //debugger;
    //url: "http://" + document.domain + "/WebService/Basket.asmx/AddToBasket",

	CheckDivCookie();
    //proceed only if add to basket button is enabled
    if (!$("#" + productid + "_addtobasket").attr("disabled"))
    {
        // Pass on quantity if present
        var qty = 1;
        if ($("#txtQty").length > 0) { qty = $("#txtQty").attr("value"); }

        $.ajax({
            type: "POST",
            url: "http://" + document.domain + "/WebService/Basket.asmx/AddToBasket",
            data: "{'ProductId':'" + productid + "','Price':'" + price + "','Quantity':'" + qty + "'}",
            success: function(data) {
                if (data.d[0] == "true") {
                    ShowSuccessImage(data, productid);
                    $("#ctl00_ucCart_cartHeadTotal").html(data.d[1]);
                }
                else if (data.d[0] == "false") {
                    ShowAddToBasketFailImage(data, productid,qty);
                }
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(e, textStatus, errorThrown) {
                bReturn = false;
            }
        });
       
    }
}

function UpdateAccessories(productid, unitprice, quantity, containerDivId, ItemTotalID) {
    var elStyle;
    if ($("#iContent" + productid).length!=0) {
        elStyle = document.getElementById('iContent' + productid).style;
    }
    if (quantity == 0) {
        //delete product item
        DeleteProductItem('ItemRow_' + productid, 'GiftItemRow_' + productid);
    }
    else {
        $.ajax({
            type: "POST",
            url: "./ShoppingBasket.aspx/UpdateAccessoryQuantity",
            data: "{'ProductID':'" + productid + "','Quantity':'" + quantity + "'}",
            success: function(data) {
                if (data.d[0] == "true") {
                    $("#" + containerDivId).html(data.d[1]);
                    $("#ctl00_ucCart_cartHeadTotal").html(data.d[3]);
                    $("#ctl00_ContentPlaceHolder1_lblTotal").html(data.d[3]);
                    $("#ctl00_ContentPlaceHolder1_lblTotal2").html(data.d[3]);
                    //CalculateItemTotal(quantity, unitprice, ItemTotalID);
                     $("#ShowStockMessage_" + productid).html("");
                    $("#ShowStockMessage_" + productid).removeClass("stockMessage");
                    UpdateItemTotal(productid, data.d[2]);
                    GlowTotals();
                    //Keep gift accessories opened only if it is open
                    if ($("#iContent" + productid).length != 0) {
                        if (elStyle.display == 'block') {
                            ShowHide('iContent' + productid);
                        }
                    }
                }
                else {
                    SetRowToOutOfStock(data, productid, quantity)
                }
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(e, textStatus, errorThrown) {
                bReturn = false;
            }
        });

    }
    
return true;
}

function SetRowToOutOfStock(data, productid, quantity) {

    $("#ShowStockMessage_" + productid).addClass("stockMessage"); ;
    if (parseInt(data.d[1]) == 1) {
        $("#ShowStockMessage_" + productid).html("We currently have only <b>" + data.d[1] + "</b> bottle in stock.<br/>Please specify a quantity within the stock limit.");
    }
    else if (parseInt(data.d[1]) > 1) {
        $("#ShowStockMessage_" + productid).html("We currently have only <b>" + data.d[1] + "</b> bottles in stock.<br/>Please specify a quantity within the stock limit.");
    }
    else if (parseInt(data.d[1]) <= 0) {
    $("#ShowStockMessage_" + productid).html("We currently do not have the product in stock. Please remove the product from your basket.To find more products, you can use the search box at the top-right corner of this page.");
    }
}

function DeleteProductItem(productrowid,giftproductrowid) {

    arproductid = productrowid.split("_");

    $.ajax({
        type: "POST",
        url: "./ShoppingBasket.aspx/DeleteProductItem",
        data: "{'ProductID':'" + arproductid[1] + "'}",
        success: function(data) {
            if (data.d[0] == "true") {
                //remove table row
                //Update shopping basket totals
                DeleteProductItemRow(productrowid);
                DeleteProductItemRow(giftproductrowid);
                $("#dvGiftOptionItems").html(data.d[1]);
                $("#ctl00_ucCart_cartHeadTotal").html(data.d[2]);
                $("#ctl00_ContentPlaceHolder1_lblTotal").html(data.d[2]);
                $("#ctl00_ContentPlaceHolder1_lblTotal2").html(data.d[2]);
                if (data.d[2] == "£0.00") {
                    HideBasketGrid();
                }
                GlowTotals();
                checkIfOneItemInCart(productrowid);
            }
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(e, textStatus, errorThrown) {
            bReturn = false;
        }
    });

}

function checkIfOneItemInCart(productID) {
    //debugger;
    sRemoveProduct = productID.replace("ItemRow_", "").trim();
    var allProducts = document.getElementById('ctl00_ContentPlaceHolder1_hidNoOfProducts').value;
    if (allProducts.indexOf(sRemoveProduct + ",") > -1) {
        allProducts = allProducts.replace(sRemoveProduct + ",", "");
        document.getElementById('ctl00_ContentPlaceHolder1_hidNoOfProducts').value = allProducts;
    }
    if (allProducts.indexOf(",", allProducts.indexOf(",") + 1) == -1) {
        var iRowShow = 'iContent' + allProducts.replace(",", "").trim();
        ShowHide(iRowShow);
    }
    
 


}

function DeleteProductItemRow(productrowid) {
    $("#" + productrowid).remove();
}

function RefreshShoppingBasket() {
    // Pass on quantity if present
    if ($("#txtQty").length > 0) { qty = $("#txtQty").attr("value"); }
    
    $.ajax({
        type: "POST",
        url: "http://" + document.domain + "/WebService/Basket.asmx/GetBasketTotal",
        data: "{}",
        success: function(data) {
            if (data.d[0] == "true") {
                $("#ctl00_ucCart_cartHeadTotal").html(data.d[1]);
            }
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(e, textStatus, errorThrown) {
            bReturn = false;
        }
    });
    
}

function UpdateGiftOptions(chkBox) {
    // Pass on quantity if present
    $.ajax({
        type: "POST",
        url: "./ShoppingBasket.aspx/UpdateGiftOption",
        data: "{'chkBoxID':'" + chkBox + "'}",
        success: function(data) {
            if (data.d[0] == "true") {
                //$("#dvGiftOptionItems").html(data.d[1]);
                UpdateItemTotal(chkBox.split("_")[3],data.d[1]);
                $("#ctl00_ucCart_cartHeadTotal").html(data.d[2]);
                $("#ctl00_ContentPlaceHolder1_lblTotal").html(data.d[2]);
                $("#ctl00_ContentPlaceHolder1_lblTotal2").html(data.d[2]);
                GlowTotals();
            }
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(e, textStatus, errorThrown) {
            bReturn = false;
        }
    })
    
}



function AddGiftMessage(messageid) {
    // Pass on quantity if present
    message= (document.getElementById(messageid).value).replace(/>/g, "").replace(/</g, "").replace(/"/g, '&#34;');
    
    if(message.length>0)
    {
        armessage = $("#" + messageid).attr("id").split("_");
        
        $.ajax({
            type: "POST",
            url: "./ShoppingBasket.aspx/AddGiftMessage",
            data: '{"messageid":"' + armessage[1] + '","message":"' + message + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(e, textStatus, errorThrown) {
                bReturn = false;
            }
        });
        
    }
}


function cbRefreshOrderConfirmation() {
    __doPostBack('uppConfirmation', '');
    
}

function ShowAddToBasketFailImage(data, productid, quantity) {
    $("#StockMessage_" + productid).addClass("stockMessage");
    if (parseInt(data.d[1])==1) {
        
        $("#StockMessage_" + productid).html("Fiddlesticks. We’ve only got <b>" + data.d[1] + "</b> bottle of this left.<br/>If you need more, please <a href='http://www.masterofmalt.com/contact-us/'>drop us an e-mail</a>, and we’ll go a-hunting at the back of the warehouse...");
    }
    else if (parseInt(data.d[1]) > 1)
    {
        $("#StockMessage_" + productid).html("Fiddlesticks. We’ve only got <b>" + data.d[1] + "</b> bottles of this left.<br/>If you need more, please <a href='http://www.masterofmalt.com/contact-us/'>drop us an e-mail</a>, and we’ll go a-hunting at the back of the warehouse...");
    }
    else if (parseInt(data.d[1]) <=0 ) {
        $("#StockMessage_" + productid).html("Rats. We’ve sold out...<br/>You can <a href='http://www.masterofmalt.com/contact-us/'>e-mail us</a> and we’ll let you know when it will be back in?");
    }       
}

function ShowSuccessImage(data, productid) {
    $("#StockMessage_" + productid).removeClass("stockMessage");
    $("#StockMessage_" + productid).html(""); //if it is still showing, reset the stock message.
    switch (data.d[2]) {
        case "1":
            $("#" + productid + "_limited").show();
            $("#" + productid + "_added").show();
            break;
        case "0":
            $("#" + productid + "_addtobasket").attr("src", "/images/small-outofstock.gif");
            $("#" + productid + "_addtobasket").css("cursor", "default");
            $("#" + productid + "_addtobasket").attr("disabled", "true");
            break;
        case "2":
            $("#" + productid + "_added").show();
            break;
    }
}

//Method invokes JoinNewsletter webservice method
function AddToNewsletter()
{

CheckDivCookie();
    var emailInput = $("#newsletterInput").attr("value").trim();
    
    if (emailInput.length > 0)
    {
        if (!isValidEmail(emailInput))
        {
            $("#newsletterProblem").css("display", "block");
        }
        else
        {
            $.ajax({
                type: "POST",
                url: "./WebService/Newsletter.asmx/JoinNewsletter",
                //data: "{'CustomerId':'" + customerid + "','Email':'" + emailInput + "'}",
                data: "{'Email':'" + emailInput + "'}",
                success: function(data) {
                    if (data.d[0] == "true") {
                        $("#newsletterForm").css("display", "none");
                        $("#newsletterProblem").css("display", "none");
                        $("#newsletterThankYou").css("display", "block");
                    }
                },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function(e, textStatus, errorThrown) {
                    bReturn = false;
                }
            });
        }
        
    }
}


function AddToBasketWithDynamicReturnIDs(productid, price, addtobasketimageid, addedtobasketimageid, limitedtobasketimageid) {

CheckDivCookie();
    //proceed only if add to basket button is enabled
    if (!$("#" + productid + "_addtobasket").attr("disabled")) {
        // Pass on quantity if present
        var qty = 1;
        if ($("#txtQty").length > 0) { qty = $("#txtQty").attr("value"); }

        $.ajax({
            type: "POST",
            url: "http://" + document.domain + "/WebService/Basket.asmx/AddToBasket",
            data: "{'ProductId':'" + productid + "','Price':'" + price + "','Quantity':'" + qty + "'}",
            success: function(data) {
                if (data.d[0] == "true") {
                    ShowSuccessImageByIds(data, productid, addtobasketimageid, addedtobasketimageid, limitedtobasketimageid);
                    $("#ctl00_ucCart_cartHeadTotal").html(data.d[1]);
                }
                else if (data.d[0] == "false") {
                    ShowAddToBasketFailImage(data, productid, qty);
                }                
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(e, textStatus, errorThrown) {
                bReturn = false;
            }
        });
        
    }
}

function ShowSuccessImageByIds(data, productid, addtobasketimageid, addedtobasketimageid, limitedtobasketimageid) {
    switch (data.d[2]) {
        case "1":
            
            $("#" + limitedtobasketimageid).show();
            $("#" +  addedtobasketimageid).show();
            break;
        case "0":
            $("#" + addtobasketimageid).attr("src", "/images/small-outofstock.gif");
            $("#" + addtobasketimageid).css("cursor", "default");
            $("#" + addtobasketimageid).attr("disabled", "true");
            break;
        case "2":
            $("#" + addedtobasketimageid).show();
            break;
    }
}

function UpdateCustomerDataLog(CustomerInput) {
    $.ajax({
        type: "POST",
        url: "./CustomerDeliveryDetails.aspx/LogCustomerInput",
        data: "{'customerinput':'" + CustomerInput + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(e, textStatus, errorThrown) {
            bReturn = false;
        }
    });
}
