﻿/*Wraps a product in an order*/
function ProductOrder() {
    this.productGuid;
    this.quantity;
    this.bookingFee;
}

/*Enumerates the add to cart event status*/
function AddToCartStatusEnum() {
    this.ALL_OK = 0;
    this.PRODUCT_NO_LONGER_AVAILABLE = 1;
    this.UNKNOWN_ERROR = 2;
}
var AddToCartStatus = new AddToCartStatusEnum();


//--the total price of all items about to be added
var totalCurrentPrice = 0.0;


/*Converts the orderlist to JSON*/
function convertOrderToJSON(orderList) {
    var list = "{ list: [";

    for (i = 0; i < orderList.length; i++) {
        list += '{"productGuid":"' + orderList[i].productGuid + '", "quantity":' + orderList[i].quantity + '},';
    }
    list = list.substring(0, list.length - 1);
    list += "]}";

    return list;
}

/*Callback from the addtocart method, handle status codes here*/
function handleAddToCartResult(result) {

    switch (result.AddToCartStatus) {
        case AddToCartStatus.ALL_OK:
            //--item was added successfully, update UI by forcing the updatepanel to reload
            document.location.href = "/store/cart.aspx"; //--for now just redirect to cart
            break;
        case AddToCartStatus.PRODUCT_NO_LONGER_AVAILABLE:
            $("#cartLoading").hide();
            $("#btnAddToCart").show();
            //--the item is no longer available, inform user
            $("#ticketingErrors").html("The item you added is no longer available");
            //--disable the problem items
            for (i = 0; i < result.problemItems.length; i++) {
                document.getElementById("quantity_" + result.problemItems[i]).selectedIndex = 0;
                //--show the no longer available message and hide the select
                $("#nla_" + result.problemItems[i]).show();
                $("#quantity_" + result.problemItems[i]).hide();
                //--recalculate the total based on the reset
                recalculateTotals();
            }
            break;
        case AddToCartStatus.UNKNOWN_ERROR:
            $("#cartLoading").hide();
            $("#btnAddToCart").show();
            //--an unknown error occured, give a default error message.
            $("#ticketingErrors").html("There was a problem adding the item to your basket, please try again");
            break;
        default:
            $("#cartLoading").hide();
            $("#btnAddToCart").show();
            //--unknown return
            $("#ticketingErrors").html("There was a problem adding the item to your basket, please try again");
            break;
    }
}


function recalculateTotals() {
    //--re-zero the total
    totalCurrentPrice = 0.0;

    $(".selTicketQuantity").each(function() {
        if (parseInt($(this).val()) > 0) {
            var quantity = $(this).val();
            var fullId = $(this).attr('id');
            var productGuid = fullId.substring(fullId.indexOf("_") + 1, fullId.length);

            var retailPrice = $("#tdRetailPrice_" + productGuid).html();
            var bookingFee = 0;

            //--strip the pound symbols
            retailPrice = retailPrice.replace("£", "");

            //--strip any commas
            retailPrice = retailPrice.replace(",", "");


            //--multiply the retail price by the quantity and add the booking fee
            retailPrice = parseFloat(retailPrice) * quantity;
            totalCurrentPrice += (parseFloat(bookingFee) * quantity) + retailPrice;
        }
    });

    //--if the trailing 0 has been stripped by being a number re-add it
    var strTotal = totalCurrentPrice.toString();
    if (strTotal.indexOf(".") != -1) {
        if (strTotal.substring(strTotal.indexOf("."), strTotal.length).length == 2) strTotal = strTotal + "0";
    }
    $("#divTotalPrice").html("£" + strTotal);
}


$(document).ready(function() {


    //--onload set the total to zero
    recalculateTotals();

    /*dynamically calculate the current total price*/
    $("select.selTicketQuantity").change(function() {
        recalculateTotals();
    });

    /*This is the main add to cart handler */
    $("#btnAddToCart").click(function() {
        $("#cartLoading").show();
        $("#btnAddToCart").hide();

        $("#ticketingErrors").html("");
        var orderList = new Array();

        $(".selTicketQuantity").each(function() {
            if (parseInt($(this).val()) > 0) {
                var quantity = $(this).val();
                var fullId = $(this).attr('id');
                var productGuid = fullId.substring(fullId.indexOf("_") + 1, fullId.length);

                var order = new ProductOrder();
                order.productGuid = productGuid;
                order.quantity = quantity;
                orderList.push(order);
            }
        });

        if (orderList.length > 0) {
            //--add products to cart via webservice
            //--convert the order array to JSON
            var sendJson = $.toJSON({ list: eval(convertOrderToJSON(orderList)) });
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/CalzagheECommerceHelper.asmx/AddProductsToCart",
                data: sendJson,
                dataType: "json",
                success: function(msg) {
                    //--there wasn't a SOAP exception so read the result code
                    var resultCode = msg.d;
                    handleAddToCartResult(resultCode);
                },
                error: function() {
                    //--there was a SOAP exception, handle the error
                    $("#cartLoading").hide();
                    $("#btnAddToCart").show();
                    $("#ticketingErrors").html("There was a problem adding the item to your basket, please try again.");
                }
            });
        } else {
            //--nothing to add
            $("#cartLoading").hide();
            $("#btnAddToCart").show();
        }

    });
});