﻿$(document).ready(function() {
    // When the user chooses a country, go get the delivery options from the server for that country
    $(".selectCountry").change(function() {
        var countryId = $(this).val();
        if (countryId == "-1") {
            $(".selectDelivery").val("-1").attr("disabled", "disabled");
        }
        else {
            strData = "country=" + countryId + "&emailonly=" + emailOnly;
            $.ajax({
                type: "GET",
                url: "/GetDeliveryOptionsByCountry.aspx",
                dataType: "xml",
                data: strData,
                success: function(xml) {
                    updateDeliveryOptions(xml);
                }
            });
        }
    });

    $(".selectDelivery").change(function() {
        updateCart();
    });

    $(".cartQuantity").change(function() {
        updateCart();
    });

    // When the Update Cart button is clicked, check that the form is valid
    // If it is valid, then go to the server with the details and update the form
    // with the xml that's returned from the server
    $(".updatecart").click(function(event) {
        updateCart();
        event.preventDefault();
    });
    //updateCart();
});

function addToCart(productId, quantity) {
    //alert("add to cart");
    //alert("/Recalculate.aspx?id=" + productId + "&q=" + quantity + "&" + getData("add", productId, quantity));
    $.ajax({
        type: "GET",
        url: "/Recalculate.aspx",
        dataType: "xml",
        data: "id=" + productId + "&q=" + quantity + "&" + getData("add", productId, quantity),
        success: function(xml) {
            updateForm(xml);
        }
    });
    return false;
}

function updateCart() {
    var invalid = false;
    $(".required").each(function() {
        var myobj = $(this);
        // if it's empty or -1, then it's invalid (-1 means no choice in a dropdown)
        if (myobj.val() == '' || myobj.val() == '-1') {
            //alert("adding invalid!");
            myobj.addClass("invalid");
            invalid = true;
        }
        else {
            //alert("removing invalid!");
            myobj.removeClass("invalid");
        }
    });

    //if (invalid != true) {
    //alert("calling server with " + getData());
    $.ajax({
        type: "GET",
        url: "/Recalculate.aspx",
        dataType: "xml",
        data: getData("full", -1, -1),
        success: function(xml) {
            updateForm(xml);
        }
    });
    //}
    return false;
}

// Takes the xml back from the Recalculate.aspx page and populates the form with the correct values
function updateForm(xml) {
    var index = 0;
    var countProducts = 0;
    var emptyCart = true;

    // Loop over the products and update the linetotal and subtotal for each
    $(xml).find("product").each(function() {
        // count the existing rows in the table
        var rowCount = $('#cartContents tr').length;

        //alert("updating running total: " + $(this).find("subtotal").text());
        if ($(this).find("subtotal").text() == "0.00") {
            $(".productline:eq(" + index + ")").hide();
        }
        else {
            $(".linetotal:eq(" + index + ")").text("£" + $(this).find("linetotal").text());
            $(".runningtotal:eq(" + index + ")").text($(this).find("subtotal").text());
            emptyCart = false;
            countProducts++;
        }

//        // If there are more products coming back from the server than there are rows in the table, 
//        // then add new rows for each
//        if (index >= rowCount - 1) {
//            var strNewRow = "<tr class=\"productline\">";
//            strNewRow += "    <td><a>Charity Item for Bowmore</a></td>";
//            //                   <td>&pound;<span id=\"ctl00_ctl00_ctl00_ContentPlaceHolderDefault_MasterContentPlaceHolder_ShoppingCart_7_repCart_ctl02_lblPrice\">1.50</span></td>
//            //                   <td class=\"quantity quantityrow\"><input type=\"hidden\" name=\"ctl00$ctl00$ctl00$ContentPlaceHolderDefault$MasterContentPlaceHolder$ShoppingCart_7$repCart$ctl02$hidProductId\" id=\"ctl00_ctl00_ctl00_ContentPlaceHolderDefault_MasterContentPlaceHolder_ShoppingCart_7_repCart_ctl02_hidProductId\" value=\"1584\" /><select name=\"ctl00$ctl00$ctl00$ContentPlaceHolderDefault$MasterContentPlaceHolder$ShoppingCart_7$repCart$ctl02$ddlQuantity\" id=\"ctl00_ctl00_ctl00_ContentPlaceHolderDefault_MasterContentPlaceHolder_ShoppingCart_7_repCart_ctl02_ddlQuantity\" class=\"quantity cartQuantity\">
//            //		                <option selected=\"selected\" value=\"0\">0</option>
//            //		                    <option value=\"1\">1</option>
//            //		                    <option value=\"2\">2</option>
//            //		                    <option value=\"3\">3</option>
//            //		                    <option value=\"4\">4</option>
//            //		                    <option value=\"5\">5</option>
//            //		                    <option value=\"6\">6</option>
//            //		                    <option value=\"7\">7</option>
//            //		                    <option value=\"8\">8</option>
//            //		                    <option value=\"9\">9</option>
//            //		                    <option value=\"10\">10</option>
//            //	                    </select></td>
//            //                   <td class=\"linetotal\">&pound;<span id=\"ctl00_ctl00_ctl00_ContentPlaceHolderDefault_MasterContentPlaceHolder_ShoppingCart_7_repCart_ctl02_lblLineTotal\">1.50</span></td>

//            //                   <td class=\"subtotal\"><div id=\"top\"><a>£<span id=\"ctl00_ctl00_ctl00_ContentPlaceHolderDefault_MasterContentPlaceHolder_ShoppingCart_7_repCart_ctl02_lblSubTotal\" class=\"runningtotal\">45.70</span></a></div></td>
//            strNewRow += "</tr>";
//            $('#myTable tr:last').after();
//        }

        index++;
    });

    // If a list of countries is sent back from the server, then we need to update
    // the country select list to include those options
    $(xml).find("countries").each(function() {

        var chosenCountry = $(".selectCountry")[0].value;

        $(".selectCountry").removeOption(/./);
        $(".selectCountry").addOption("-1", "Please Choose", false);

        // loop over the xml and ad the new options
        $(this).find('country').each(function() {
            var value = $(this).find('id').text();
            var text = $(this).find('name').text();
            $(".selectCountry").addOption(value, text, false);
        });
        $(".selectCountry").removeClass("invalid");
        $(".selectCountry")[0].value = chosenCountry;
    });

    // If a list of deliveryoptions is sent back from the server, then we need to update
    // the delivery option select list to include those options
    $(xml).find("deliveryoptions").each(function() {

        var chosenDeliveryOption = $(".selectDelivery")[0].value;

        $(".selectDelivery").removeOption(/./);
        $(".selectDelivery").addOption("-1", "Please Choose", false);

        // loop over the xml and ad the new options
        $(this).find('deliveryoption').each(function() {
            var value = $(this).find('id').text();
            var text = $(this).find('label').text();
            $(".selectDelivery").addOption(value, text, false);
        });
        $(".selectDelivery").removeClass("invalid");
        $(".selectDelivery")[0].value = chosenDeliveryOption;
    });

    // show/hide the message about liquid items depending on 
    // if the cart contains any or not
    if ($(xml).find("hasLiquid").text() == "True") {
        $(".countryfiltered").show();
        //alert("has liquid");
    }
    else {
        //alert("no liquids");
        $(".countryfiltered").hide();
    }

    if (!emptyCart) {
        // update the delivery amount
        $(".deliveryamount").text("£" + $(xml).find("deliveryamount").text());

        // update the delivery line total
        $(".deliverylinetotal").text("£" + $(xml).find("deliverylinetotal").text());

        // update the discount
        $(".discountamount").text("-£" + $(xml).find("discountamount").text());

        // update the discount line total
        $(".discountlinetotal").text("£" + $(xml).find("discountlinetotal").text());

        // update the total cost
        $(".carttotal").text("£" + $(xml).find("carttotal").text());

        //alert(countProducts);
        // update the Shopping Cart link so that it shows the correct number of products in the cart
        $(".cartlink").text("Shopping Cart (" + countProducts + ")");

        // Re-do the cufon for the cartlink after the text has been changed
        Cufon.replace(".cartlink", {
            hover: true
        });
    }
    else {
        $(".pnlcart").hide();
        //alert($(".emptycart").text());
        $(".emptycart").show();

        // update the Shopping Cart link so that it shows that the cart is empty
        $(".cartlink").text("Shopping Cart (-)");

        // Re-do the cufon for the cartlink after the text has been changed
        Cufon.replace(".cartlink", {
            hover: true
        });
    }
}

// Gets the data from the current state of the form to send to the server
function getData(mode, productId, quantity) {

    // Create a string to hold the data
    var data = "mode=" + mode + "&products=";

    // for each row in the cart, get the id and the quantity
    $(".quantityrow").each(function() {
        data += $(this).children()[0].value + ',' + $(this).children()[1].value + ';';
    });

    if (mode == 'add') {
        data += productId + ',' + quantity + ';';
    }

    data += "&country=" + $(".selectCountry")[0].value;
    data += "&delivery=" + $(".selectDelivery")[0].value;
    data += "&discount=" + $(".selectDiscount")[0].value;

    return data;
}

// Takes the xml that contains the delivery options for the chosen country
// and updates the delivery dropdownlist with the new options
function updateDeliveryOptions(xml) {
    // record selected value - if it exists after the update then can re-select it
    var chosenDeliveryOption = $(".selectDelivery")[0].value;

    // remove all options first
    $(".selectDelivery").removeOption(/./);
    $(".selectDelivery").addOption("-1", "Please Choose", false);

    // loop over the xml and ad the new options
    $(xml).find('option').each(function() {
        var value = $(this).find('id').text();
        var text = $(this).find('title').text();
        $(".selectDelivery").addOption(value, text, false);
    });
    $(".selectDelivery").removeClass("invalid");
    $(".selectDelivery").removeAttr("disabled");

    $(".selectDelivery")[0].value = chosenDeliveryOption;

    updateCart();
}
