﻿$(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 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(),
        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() {
        //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++;
        }
        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() {

    // Create a string to hold the data
    var data = "mode=full&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 + ';';
    });

    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();
}