﻿/* Helper Functions */
var helper = {
    idsMatch: function (id1, id2) {
        return (parseInt(id1, 10) === parseInt(id2, 10)); // Do IDs match
    },
    isEmpty: function (element) { // Is input element empty
        var trimmedEl = $.trim($(element).val());
        return $(element).length > 0 && $(element).val() !== "" ? trimmedEl === "" : true;
    },
    exists: function (element) { // Does element exist on page
        return $(element).length > 0;
    },
    asCurrency: function (amount) { // Formats an integer as currency
        return "$" + parseFloat(amount.toString()).toFixed(2);
    },
    debugEnabled: false,
    debug: function (obj) {
        if (window.console && console.log && helper.debugEnabled) {
            console.log(obj);
        }
    }
};

/* WhereYouNow / Delivery helper class */
var delivery = {
    init: function () {
        if (helper.exists("#Address_Postcode") && $("#Address_Postcode").val() === "0") { // Delete default postcode 0 value
            $("#Address_Postcode").val("");
        }
        $("#Address_IsCommercial").click(function () {
            if ($(this).is(":checked")) {
                $("#CommercialPropertyDisclaimer").show();
            } else {
                $("#CommercialPropertyDisclaimer").hide();
            }
        });
        $("#ChangeAddress a").click(function () {
            window.location.reload();
        });
        $("#CalculateDelivery").click(function () {
            delivery.calculate();
        });
    },
    calculate: function () {
        var formIsValid = $("form").validate().form(); // Validate form
        if (!formIsValid) {
            return; // Not all fields complete, don't calculate delivery
        }
        $("#DeliveryLoader").fadeIn();
        var streetNumber = $("#Address_StreetNumber").val(),
            streetName = $("#Address_StreetName").val(),
            suburb = $("#Address_Suburb").val(),
            postcode = $("#Address_Postcode").val(),
            locationId = $("#LocationID").val(),
            success = false;
        $.ajax({
            type: "GET",
            url: "/svc/GetDeliveryInfo",
            data: "streetNumber=" + streetNumber + "&streetName=" + streetName + "&suburb=" + suburb + "&postcode=" + postcode + "&locationId=" + locationId,
            success: function (response) {
                var html = "";
                switch (parseInt(response.DeliveryStatus, 10)) {
                case 0: // OK
                    html = "<h4>You are " + response.DistanceInMetres + " metres from misschu " + response.LocationName + "</h4>"
                        + "<p>Delivery will cost $" + parseFloat(response.Price).toFixed(2) + "</p>";
                    success = true;
                    break;
                case 1: // Invalid address
                    html = "<h4>Couldn't find your address</h4>"
                        + "<p>Please check and try again</p>";
                    break;
                case 2: // Address out of range
                    html = "<h4>You are " + response.DistanceInMetres + " metres from misschu " + response.LocationName + "</h4>"
                        + "<p>Max delivery distance is 3,500 metres sorry!</p>"
                        + "<p>Please enter a different address</p>"
                        + "<p>Or you can always <a href='/MeHungry/YouPickup/'>pickup your order</a></p>";
                    break;
                case 3: // API error
                    html = "<p>Something go really wrong sorry!</p>"
                        + "<p>Please try again or proceed onto the next page</p>"
                        + "<p>If you unhappy, please <a href='/Contact'>contact us</a> we fix for you</p>";
                    break;
                default:
                    break;
                }
                $("#DeliveryLoader").hide();
                if (success) {
                    $(".enterDetails #DeliveryInfoContainer").removeClass("error");
                    $(".enterDetails #DeliveryInfoContainer").addClass("success");
                    $("#orderSummary .calculateDelivery").hide();
                    $("#orderSummary .paymentButtons").show();
                } else {
                    $(".enterDetails #DeliveryInfoContainer").removeClass("success");
                    $(".enterDetails #DeliveryInfoContainer").addClass("error");
                }
                $(".enterDetails #DeliveryInfoContainer").html(html); // Update delivery info html and show
                $(".enterDetails #DeliveryInfoContainer").fadeIn();
                delivery.refreshPrice(response.Price); // Update cart summary info
                cart.refreshSummary();
            },
            error: function () {
                var html = "<p>Something go really wrong sorry!</p>"
                    + "<p>Please try again or proceed onto the next page.</p>"
                    + "<p>If you unhappy, please <a href='/Contact'>contact us</a> we fix for you.</p>";
                $(".enterDetails #DeliveryInfoContainer").html(html);
                $(".enterDetails #DeliveryInfoContainer").addClass("error");
                $(".enterDetails #DeliveryInfoContainer").fadeIn();
                $("#DeliveryLoader").fadeOut();
            }
        });
    },
    refreshPrice: function (price) {
        var deliveryPrice = (parseFloat(price)).toFixed(2);
        $("#deliveryPrice #d-amount").html("$" + deliveryPrice);
        $("#deliveryPrice #DeliveryCharge").val(deliveryPrice);
    },
    validateTime: function () {
        $("#date-invalid").remove();
	    if (helper.isEmpty("#PickupDeliveryTimeHour option:selected") || helper.isEmpty("#PickupDeliveryTimeMinute option:selected") || helper.isEmpty("#PickupDeliveryTimeAmPm option:selected")) {
		    var invalidHtml = "<span class='field-validation-error' id='date-invalid'>Please select a delivery time</span>";
		    $("#deliveryTimePicker").append(invalidHtml);
		    return false;
	    }
	    return true;
    },
    deliveryAmountValid: function (items) {
        $("#minDelivery span").hide();
        if ($("#OrderType").val().toLowerCase() !== "delivery") { // Only concerned with deliveries
            return true;
        }
        var total = 0;
        $(items).each(function (i, e) {
            total += (parseFloat(e.quantity) * parseFloat(e.price));
        });
        if (total >= 25) {
            return true;
        }
        $("#minDelivery span").show().css("display", "block");
        return false;
    }
};

/* Me Hungry & Canapes Ordering */
var cart = {
    init: function () {
        if (!helper.isEmpty("#OrderJson")) {
            cart.order = $.parseJSON($("#OrderJson").val());
            cart.refreshSummary();
        }
        $(".menuItemControls a").live("click", function (e) { // Plus and minus button click binding
            e.preventDefault();
            cart.updateQuantity(this);
        });
        $(".menuItemControls > input").live("keyup", function () { // Binding for manually entering quantities
            cart.updateQuantity(this);
        });
        $(".menuItemControls .removeItem").live("click", function (e) { // Remove from order
            e.preventDefault();
            cart.removeItem(this);
        });
        if (helper.exists("#deliveryTime")) {
            $("#DeliverNow").click(function () { // Deliver now, hide time picker
                if ($(this).attr("checked")) {
                    $("#deliveryTimePicker").hide();
                    $("#ScheduleDelivery").val("false");
                }
            });
            $("#DeliverLater").click(function () { // Deliver later, show time picker
                if ($(this).is(":checked")) {
                    $("#deliveryTimePicker").show();
                    $("#ScheduleDelivery").val("true");
                }
            });
            if (helper.exists("#DeliveryTimeValid .field-validation-error")) { // If invalid delivery time selected
                $("#deliveryTimePicker").show();
                $("#ScheduleDelivery").val("true");
                $("#DeliverLater").attr("checked", "checked");
            }
        }
        $("#payCashD, #payCashP, #payCredit, input.continue").click(function (e) {
            var amountValid = delivery.deliveryAmountValid(cart.order.menuitems),
                timeValid = true;
            if (helper.exists("#deliveryTimePicker") && $("#ScheduleDelivery").val().toLowerCase() === "true") {
                timeValid = delivery.validateTime(); // Validate delivery time
            }
            $("#PaymentType").val($(this).attr("data-payment-type")); // Set payment type based on button clicked
            if (!timeValid || !amountValid) {
                e.preventDefault();
            }
        });
        $("#orderSummary .payNow").click(function (e) {
            if ($("#PaymentForm").valid()) {
                $("#orderSummary .payNow").hide();
                $(".pay-now-loading").show();
            }
            if (!delivery.deliveryAmountValid(cart.order.menuitems)) { // Validate delivery $ > 25
                $(".pay-now-loading").hide();
                $("#orderSummary .payNow").show();
                e.preventDefault();
            }
            cart.submitPayment(e);
        });
        cart.toggleOrderSummary(); // Toggle summary
    },
    order: {
        "menuitems": []
    },
    isEmpty: function () {
        return cart.order.menuitems.length === 0;
    },
    redirectIfEmpty: function () {
        if (!cart.isEmpty()) {
            return;
        }
        var pn = window.location.pathname.toLowerCase();
        if (pn.indexOf("delivery") === -1 && pn.indexOf("youpickup") === -1) { // If cart is empty and we're not on the first step of ordering process
            cart.clearCache(); // Clear cache
        }
    },
    clearCache: function () { // User has removed all items so clear cache to reflect this
        window.location = "/MeHungry/ClearCache/";
    },
    updateQuantity: function (el) {
        var elData = $(el).parent(),
            id = elData.attr("data-id"),
            name = elData.attr("data-name"),
            price = elData.attr("data-price"),
            type = elData.attr("data-type"),
            textBox = $(".menuItemControls[data-type='" + type + "'][data-id='" + id + "'] input.quantity"),
            quantity = parseInt(($("input.quantity", elData).val()), 10);
        switch ($(el).attr("class")) {
            case "plus": //  Plus button
                quantity = quantity + 1;
                textBox.val(quantity);
                cart.plusItem(id, name, price, quantity);
                break;
            case "minus": //  Minus button
                if (quantity > 0) {
                    quantity = quantity - 1;
                    textBox.val(quantity);
                    cart.minusItem(el);
                }
                break;
            default: //  Input field entry
                if (!quantity) {
                    cart.removeItem(el);
                } else {
                    textBox.val(quantity);
                    cart.plusItem(id, name, price, quantity);
                }
                break;
        }
        cart.refreshSummary();
    },
    plusItem: function (id, name, price, quantity) {
        var item = { "id": id, "name": name, "price": price, "quantity": quantity },
            exists = false;
        if (quantity > 0) {
            $(cart.order.menuitems).each(function (i, e) { // Iterate through menu items
                if (helper.idsMatch(e.id, id)) { // If item exists update quantity, if not add to list
                    e.quantity = parseInt(quantity, 10);
                    exists = true;
                }
            });
            if (!exists) {
                cart.order.menuitems.push(item);
            }
        }
    },
    minusItem: function (el) {
        var parent = $(el).parent(),
            id = parent.attr("data-id");
        $(cart.order.menuitems).each(function (i, e) {
            if (helper.idsMatch(e.id, id)) {
                var currQuantity = parseInt(e.quantity, 10);
                if (currQuantity === 1) {
                    cart.removeFromOrder(id); // If there's only 1 left, remove from order
                } else {
                    e.quantity = currQuantity - 1;
                }
            }
        });
    },
    removeItem: function (el) {
        var parent = $(el).parent(),
            id = parent.attr("data-id"),
            type = parent.attr("data-type"),
            textBox = $(".menuItemControls[data-type='" + type + "'][data-id='" + id + "'] input.quantity");
        textBox.val(0);
        cart.removeFromOrder(id);
        cart.refreshSummary();
        cart.redirectIfEmpty();
    },
    removeFromOrder: function (id) {
        var itemRemoveIndex = -1;
        $(cart.order.menuitems).each(function (i, e) {
            if (helper.idsMatch(e.id, id)) {
                itemRemoveIndex = i;
            }
        });
        if (itemRemoveIndex !== -1) { // Found item, remove from list
            cart.order.menuitems.splice(itemRemoveIndex, 1);
        }
        cart.redirectIfEmpty(); // If cart is empty, redirect to home page
    },
    refreshSummary: function () {
        var subTotal = 0,
            deliveryPrice = 0,
            creditCardSurcharge = 0,
            totalPrice = 0,
            totalPriceWithSurcharge = 0,
            menuItems = $("#orderSummary #menuItems");
        menuItems.html("");
        $(cart.order.menuitems).each(function (i, e) {
            $(".menuItemControls[data-type='food'][data-id='" + e.id + "'] input.quantity").val(parseInt(e.quantity, 10)); // Update quantity in both related input fields
            var appendHtml = "<li data-id='" + e.id + "' data-type='food'>"
                + "<div class='menuItemControls' data-id='" + e.id + "' data-name='" + e.name + "' data-price='" + e.price + "' data-type='food'><a class='removeItem' href='#'>Remove</a> "
                + "<a class='minus' href='#'>-</a> <a class='plus' href='#'>+</a> "
                + "<input class='quantity' value='" + e.quantity + "'></div>"
                + "<span class='itemName'>" + e.name + "</span> <span class='price'>$" + (parseFloat(e.price)).toFixed(2) + "</span></li>";
            menuItems.append(appendHtml);
            subTotal += (parseFloat(e.quantity) * parseFloat(e.price));
        });
        $("#subTotalDisplay span#s-amount").html(helper.asCurrency(subTotal)); // Sub total display
        $("#subTotalDisplay #SubTotal").val(parseFloat(subTotal)); // Sub total hidden
        if (helper.exists("#totalPrice")) {
            if (helper.exists("#deliveryPrice")) {
                deliveryPrice = parseFloat($("#deliveryPrice #DeliveryCharge").val());
            }
            totalPrice = parseFloat(subTotal + deliveryPrice), // Total price
            creditCardSurcharge = cart.calculateCreditCardSurcharge(totalPrice), // If paying by credit card, calculate surcharge
            totalPriceWithSurcharge = parseFloat(totalPrice + creditCardSurcharge); // Total price including surcharge
            $("#totalPrice span#t-amount").html(helper.asCurrency(totalPriceWithSurcharge)); // Total price displayed includes surcharge
            $("#totalPrice #TotalPrice").val(totalPrice); // Total price hidden does not include surcharge, this is calculated on the server
        }
        if ($("#OrderType").val().toLowerCase() === "delivery" && subTotal > 25) {
            $("#minDelivery span").hide(); // Hide invalid delivery amount if subtotal > $25
        }
        $("#OrderJson").val(JSON.stringify(cart.order)); // Update JSON passed back to server
        cart.toggleOrderSummary();
    },
    toggleOrderSummary: function () {
        if ((helper.exists("#menuItems > li"))) {
            $("#orderSummary:not(.selections) .orderDetail, #orderSummary:not(.selections) .orderSelection").show();
            $("#orderSummary:not(.selections) .noItems").hide();
        } else {
            $("#orderSummary:not(.selections) .orderDetail, #orderSummary:not(.selections) .orderSelection").hide();
            $("#orderSummary:not(.selections) .noItems").show();
        }
        var orderSummaryHeight = $("#orderSummary").height();
        $("#orderMenu").css("min-height", (orderSummaryHeight) + "px");
        $("article.enterDetails").css("min-height", orderSummaryHeight + "px");
    },
    calculateCreditCardSurcharge: function (totalPrice) {
        if (!helper.exists("#cardSurcharge")) {
            return 0;
        }
        var surcharge = (totalPrice / 100) * 1.5; // CC Surcharge = 1.5%
        $("#cardSurcharge #ccs-amount").html(helper.asCurrency(surcharge));
        return surcharge;
    },
    submitPayment: function () {
        $("#CreditCardInfo_Number").val($.trim($("#CreditCardInfo_Number").val())); // Trim whitespace from CC number
        $("#CreditCardInfo_CCV").val($.trim($("#CreditCardInfo_CCV").val())); // Trim whitespace from CCV
    }
};

/* Me Hungry & Canapes Ordering */
var canapes = {
    init: function () {
        if (!helper.isEmpty("#OrderJson")) {
            canapes.order = $.parseJSON($("#OrderJson").val());
            canapes.refreshSummary();
        }
        $(".menuItemControls a").live("click", function (e) { // Plus and minus button click binding
            e.preventDefault();
            canapes.updateQuantity(this);
        });
        $(".menuItemControls > input").live("keyup", function () { // Binding for manually entering quantities
            canapes.updateQuantity(this);
        });
        $(".menuItemControls .removeItem").live("click", function (e) { // Remove from order
            e.preventDefault();
            canapes.removeItem(this);
        });
        canapes.toggleOrderSummary(); // Toggle summary
    },
    order: {
        "menuitems": []
    },
    isEmpty: function () {
        return canapes.order.menuitems.length === 0;
    },
    redirectIfEmpty: function () {
        if (!canapes.isEmpty()) {
            return;
        }
        var pn = window.location.pathname.toLowerCase();
        if (pn.indexOf("canapes") === -1) { // If cart is empty and we're not on the first step of ordering process
            window.location = "/"; // Redirect home
        }
    },
    updateQuantity: function (el) {
        var elData = $(el).parent(),
            id = elData.attr("data-id"),
            name = elData.attr("data-name"),
            price = elData.attr("data-price"),
            type = elData.attr("data-type"),
            textBox = $(".menuItemControls[data-type='" + type + "'][data-id='" + id + "'] input.quantity"),
            quantity = parseInt($("input.quantity", elData).val(), 10);
        switch ($(el).attr("class")) {
        case "plus": //  Plus button
            quantity = quantity === 0 ? 15 : quantity + 5;
            textBox.val(quantity);
            canapes.plusItem(id, name, price, quantity);
            break;
        case "minus": //  Minus button
            if (quantity > 0) {
                quantity = quantity === 15 ? 0 : quantity - 5;
                textBox.val(quantity);
                canapes.minusItem(el);
            }
            break;
        default: //  Input field entry
            if (!quantity) {
                canapes.removeItem(el);
            } else {
                textBox.val(quantity);
                canapes.plusItem(id, name, price, quantity);
            }
            break;
        }
        canapes.refreshSummary();
    },
    plusItem: function (id, name, price, quantity) {
        var item = { "id": id, "name": name, "price": price, "quantity": quantity },
            exists = false;
        if (quantity > 0) {
            $(canapes.order.menuitems).each(function (i, e) { // Iterate through menu items, if item exists update quantity, if not add to list
                if (helper.idsMatch(e.id, id)) {
                    e.quantity = parseInt(quantity, 10);
                    exists =  true;
                }
            });
            if (!exists) {
                canapes.order.menuitems.push(item);
            }
        }
    },
    minusItem: function (el) {
        var parent = $(el).parent(),
            id = parent.attr("data-id");
        $(canapes.order.menuitems).each(function (i, e) {
            if (helper.idsMatch(e.id, id)) {
                var currQuantity = parseInt(e.quantity, 10);
                if (currQuantity === 15) {
                    canapes.removeFromOrder(id); // If there's only 1 left, remove from order
                } else {
                    e.quantity = currQuantity - 5;
                }
            }
        });
    },
    removeItem: function (el) {
        var parent = $(el).parent(),
            id = parent.attr("data-id"),
            type = parent.attr("data-type"),
            textBox = $(".menuItemControls[data-type='" + type + "'][data-id='" + id + "'] input.quantity");
        textBox.val(0);
        canapes.removeFromOrder(id);
        canapes.redirectIfEmpty();
        canapes.refreshSummary();
    },
    removeFromOrder: function (id) {
        var itemRemoveIndex = -1;
        $(canapes.order.menuitems).each(function (i, e) {
            if (helper.idsMatch(e.id, id)) {
                itemRemoveIndex = i;
            }
        });
        if (itemRemoveIndex !== -1) { // Found item, remove from list
            canapes.order.menuitems.splice(itemRemoveIndex, 1);
        }
        canapes.redirectIfEmpty(); // If cart is empty, redirect to home page
    },
    refreshSummary: function () {
        var subTotal = 0,
            menuItems = $("#orderSummary #menuItems");
        menuItems.html("");
        $(canapes.order.menuitems).each(function (i, e) {
            $(".menuItemControls[data-type='food'][data-id='" + e.id + "'] input.quantity").val(parseInt(e.quantity, 10)); // Update quantity in both related input fields
            var html = "<li data-id='" + e.id + "' data-type='food'>"
                + "<div class='menuItemControls' data-id='" + e.id + "' data-name='" + e.name + "' data-price='" + e.price + "' data-type='food'><a class='removeItem' href='#'>Remove</a> "
                + "<a class='minus' href='#'>-</a> <a class='plus' href='#'>+</a> "
                + "<input class='quantity' value='" + e.quantity + "'></div>"
                + "<span class='itemName'>" + e.name + "</span> <span class='price'>$" + (parseFloat(e.price)).toFixed(2) + "</span></li>";
            menuItems.append(html);
            subTotal += (parseFloat(e.quantity) * parseFloat(e.price));
        });
        subTotal = parseFloat(subTotal).toFixed(2);
        $("#subTotalDisplay span#s-amount").html("$" + subTotal); // Sub total display
        $("#subTotalDisplay #SubTotal").val(subTotal); // Sub total hidden
        if (helper.exists("#totalPrice")) {
            var totalPrice = parseFloat(subTotal).toFixed(2);
            $("#totalPrice span#t-amount").html("$" + totalPrice); // Total price display
            $("#totalPrice #TotalPrice").val(totalPrice); // Total price hidden
        }
        $("#OrderJson").val(JSON.stringify(canapes.order)); // Update JSON passed back to server
        canapes.toggleOrderSummary();
    },
    toggleOrderSummary: function () {
        var orderSummaryHeight = $("#orderSummary").height();
        if ((helper.exists("#menuItems > li"))) {
            $("#orderSummary:not(.selections) .orderDetail, #orderSummary:not(.selections) .orderSelection").show();
            $("#orderSummary:not(.selections) .noItems").hide();
        } else {
            $("#orderSummary:not(.selections) .orderDetail, #orderSummary:not(.selections) .orderSelection").hide();
            $("#orderSummary:not(.selections) .noItems").show();
        }
        $("#orderMenu").css("min-height", (orderSummaryHeight) + "px");
        $("article.enterDetails").css("min-height", orderSummaryHeight + "px");
    }
};

/* MissChu Selections */
var missChuSelections = {
    init : function () {
        missChuSelections.selections = $.parseJSON($("#SelectionsJson").val()); // Parse the selections from hidden field
        var budgetDisplay = $("#budget");
        budgetDisplay.text(helper.asCurrency(missChuSelections.selections[0].selection.budget));
        $(".selection").first().show(); // Show the first selection
        $("#ChosenSelectionID").val(missChuSelections.selections[0].selection.id);
        $(".selectionSlider").slider({ // MissChu Selections Slider
            value: 0, min: 0, max: $("#SelectionsCount").val(), step: 1,
            slide: function (event, ui) {
                $(".selection").hide();
                var active = missChuSelections.selections[ui.value].selection;
                budgetDisplay.html(helper.asCurrency(active.budget));
                $("#selection-" + active.id).show();
                $("#ChosenSelectionID").val(active.id);
            }
        });
        if (helper.exists("#deliveryTime")) {
            $("#DeliverNow").click(function () { // Deliver now, hide time picker
                if ($(this).attr("checked")) {
                    $("#deliveryTimePicker").hide();
                    $("#ScheduleDelivery").val("false");
                }
            });
            $("#DeliverLater").click(function () { // Deliver later, show time picker
                if ($(this).is(":checked")) {
                    $("#deliveryTimePicker").show();
                    $("#ScheduleDelivery").val("true");
                }
            });
            if (helper.exists("#DeliveryTimeValid .field-validation-error")) { // If invalid delivery time selected
                $("#deliveryTimePicker").show();
                $("#ScheduleDelivery").val("true");
                $("#DeliverLater").attr("checked", "checked");
            }
        }
        $("input.continue").click(function (e) {
            var timeValid = true,
                amountValid = missChuSelections.deliveryAmountValid();
            if ($("#ScheduleDelivery").val().toLowerCase() === "true") {
                timeValid = delivery.validateTime();
            }
            if (!timeValid || !amountValid) { // Ensure delivery time and amount valid
                e.preventDefault(); // Cancel form submission if invalid
            }
        });
    },
    selections : {
    },
    deliveryAmountValid: function () {
        $("#minDelivery span").hide();
        if ($("#OrderType").val().toLowerCase() !== "delivery") { // Only concerned with deliveries
            return true;
        }
        var amountValid;
        $(missChuSelections.selections).each(function (i, e) {
            if (helper.idsMatch(e.selection.id, $("#ChosenSelectionID").val()) && parseInt(e.selection.budget, 10) >= 25) { // Find chosen selection and validate budget
                amountValid = true;
            }
        });
        if (amountValid) {
            return true;
        }
        $("#minDelivery span").show().css("display", "block");
        return false;
    }
};

var easyPicks = {
    init: function () {
        if (!helper.isEmpty("#OrderJson")) {
            easyPicks.selections = $.parseJSON($("#OrderJson").val()); // Populate order object from JSON
        }
        easyPicks.refreshSummary();
        $(".catering .easyPick").click(function (e) {
            e.preventDefault();
            var item = { id: $(this).attr("data-id"), name: $(this).attr("data-name"), price: $(this).attr("data-price") };
            if (!easyPicks.selectionsContainsItem(item.id)) {
                easyPicks.selections.push(item);
            }
            easyPicks.refreshSummary();
        });
        $(".menuItemControls .removeItem").live("click", function (e) { // Remove from order
            e.preventDefault();
            easyPicks.removeFromOrder($(this).parents("li").attr("data-id"));
            easyPicks.refreshSummary();
        });
        $("#subTotalDisplay").hide();
    },
    selections: [
    ],
    selectionsContainsItem: function (id) {
        var existing = false;
        $(easyPicks.selections).each(function (i, e) {
            if (helper.idsMatch(e.id, id)) {
                existing = true;
            }
        });
        return existing;
    },
    refreshSummary: function () {
        var subTotal = 0,
            easyPickItems = $("#orderSummary #menuItems"),
            html = "";
        easyPickItems.html("");
        $(easyPicks.selections).each(function (i, e) {
            html = "<li data-id='" + e.id + "' data-type='easy'>"
                + "<div class='menuItemControls' data-id='" + e.id + "' data-type='easy'><a class='removeItem' href='#'>Remove</a></div>"
                + "<span class='itemName'>" + e.name + "</span><span class='price'>$" + (parseFloat(e.price)).toFixed(2) + "</span></li>";
            easyPickItems.append(html);
            subTotal += (parseFloat(e.price));
        });
        $("#subTotalDisplay span#s-amount").html(helper.asCurrency(subTotal));
        $("#subTotalDisplay #SubTotal").val(subTotal);
        $("#OrderJson").val(JSON.stringify(easyPicks.selections)); // Update JSON passed back to server
        easyPicks.toggleOrderSummary();

    },
    toggleOrderSummary: function () {
        var orderSummaryHeight = $("#orderSummary").height();
        if (helper.exists("#menuItems > li")) {
            $("#orderSummary .orderDetail, #orderSummary .orderSelection").show();
            $("#orderSummary .noItems").hide();
        }
        else {
            $("#orderSummary .orderDetail, #orderSummary .orderSelection").hide();
            $("#orderSummary .noItems").show();
        }
        $("#orderMenu").css("min-height", (orderSummaryHeight) + "px");
        $("article.enterDetails").css("min-height", orderSummaryHeight + "px");
    },
    removeFromOrder: function (id) {
        var itemRemoveIndex = -1;
        $(easyPicks.selections).each(function (i, e) {
            if (helper.idsMatch(e.id, id)) {
                itemRemoveIndex = i;
            }
        });
        if (itemRemoveIndex != -1) {
            easyPicks.selections.splice(itemRemoveIndex, 1); // Remove from array
        }
    }
};

/* Account */
var register = {
    init : function() {
        if (helper.exists("#defaultStore")) {
            if (helper.isEmpty("#LocationID")) {
                $("#LocationID").val("-1"); // Default LocationID value to -1 to trigger validation
            }
            else {
                var locationID = $("#LocationID").val();
                $("#defaultStore #" + locationID).attr("checked", "checked");
            }
            $("#defaultStore input").click(function () { // Update location ID when radio input checked
                if ($(this).is(":checked")) {
                    $("#LocationID").val($(this).val());
                    $("#defaultStore .field-validation-error").hide();
                }
            });
        }
        this.orderHistory();
    },
    orderHistory: function () {
        if (helper.exists(".orderHistory > table")) {
            var jsonRetrieve = {
                id: "1",
                sortBy: "date",
                sortDirection: "dsc",
                pageSize: 5,
                pageNumber: 0
            };
            var showMore = $("article.orderHistory a.showMore");
            var noOrdersFound = $("<tr><td colspan='6' class='noOrdersFound'>No orders were found. <a href='/MeHungry/Delivery'>You Hungry?</a></td></tr>");
            register.ajaxLoadAnim();
            // Set initial JSON URL
            var jsonURL = "/svc/GetCustomerOrderHistory?customerId=" + jsonRetrieve.id + "&sortBy=" + jsonRetrieve.sortBy + "&sortDirection=" + jsonRetrieve.sortDirection + "&pageSize=" + jsonRetrieve.pageSize + "&pageNumber=" + jsonRetrieve.pageNumber;
            register.showMoreBtn = function(btn, data) {
                if (jsonRetrieve.pageNumber == (data.TotalPages - 1)) {
                    btn.fadeOut(200);
                }
                else {
                    btn.fadeIn(200);
                }
            };
            $.getJSON(jsonURL, function (data) {
                if (data.ErrorMessage == null) {
                    // Initial data population
                    register.appendOrders(data);
                    register.showMoreBtn(showMore, data);
                    // Show more button
                    showMore.click(function() {
                        // Next page
                        jsonRetrieve.pageNumber++;
                        var showMoreUrl =  "/svc/GetCustomerOrderHistory?customerId=" + jsonRetrieve.id + "&sortBy=" + jsonRetrieve.sortBy + "&sortDirection=" + jsonRetrieve.sortDirection + "&pageSize=" + "5" + "&pageNumber=" + jsonRetrieve.pageNumber;
                        // Append next page orders
                        $.getJSON(showMoreUrl, function(newData) {
                            register.appendOrders(newData);
                        });
                        // Hide button if no more pages
                        register.showMoreBtn($(this), data);
                    });

                    // Sort by select box
                    $("#sortBy").change(function() {
                        // Reset page number
                        jsonRetrieve.pageNumber = 0;
                        // Set Sort By param
                        jsonRetrieve.sortBy = $(this).val();
                        var sortUrl = "/svc/GetCustomerOrderHistory?customerId=" + jsonRetrieve.id + "&sortBy=" + jsonRetrieve.sortBy + "&sortDirection=" + jsonRetrieve.sortDirection + "&pageSize=" + "5" + "&pageNumber=" + jsonRetrieve.pageNumber;
                        // Refresh content
                        $(".orderHistory > table > tbody *").fadeOut(200).parent().empty();
                        $.getJSON(sortUrl, function(newData) {
                            register.appendOrders(newData);
                        });
                        register.showMoreBtn($(this), data);
                    });
                    // Sort by order select box
                    $("#sortByOrder").change(function() {
                        jsonRetrieve.pageNumber = 0;
                        jsonRetrieve.sortDirection = $(this).val();
                        var sortUrl = "/svc/GetCustomerOrderHistory?customerId=" + jsonRetrieve.id + "&sortBy=" + jsonRetrieve.sortBy + "&sortDirection=" + jsonRetrieve.sortDirection + "&pageSize=" + "5" + "&pageNumber=" + jsonRetrieve.pageNumber;
                        $(".orderHistory > table > tbody *").fadeOut(200).parent().empty();
                        $.getJSON(sortUrl, function(newData) {
                            register.appendOrders(newData);
                        });
                        register.showMoreBtn($(this), data);
                    });
                    noOrdersFound.hide();
                }
                else if (((data.ErrorMessage).toLowerCase()).match("no orders found")) {
                    noOrdersFound.appendTo(".orderHistory > table > tbody");
                    $("article.orderHistory a.showMore").hide();
                }
                else {
                    $("article.orderHistory a.showMore").fadeOut(200);
                    noOrdersFound.hide();
                }
            });
        }
    },
    appendOrders: function (data) {    
         $.each(data.Orders, function(key, val) {
            var dateOrdered = val.DateTimeFormat;
            var customerName = val.Name;
            var orderId = val.OrderID;
            var orderType = (val.OrderType == 0) ? "Delivery" : "Pick Up";
            var totalPrice = val.TotalPrice;
            var menuitems = {
                food: val.OrderLight.menuitems
            };
            var rowData;
            var foodRowData;
            rowData = "<tr><td>" + orderId + "</td>";
            rowData += "<td>" + customerName + "</td>";
            rowData += "<td>" + dateOrdered + "</td>";
            /* Order details */
            rowData += "<td class='orderDetails'><a href='#'>View</a>";
            rowData += "<table><thead><tr><th>Name</th><th class='quantity'>Qty</th></tr></thead>";
            rowData += "<tbody>";
            if ((menuitems.food).length) {
                foodRowData = register.orderDetailsTable(menuitems.food);
                rowData += foodRowData;
            }
            rowData += "</tbody></table></td>";
            /* END Order details */
            rowData += "<td class='price'>$" + parseFloat(totalPrice).toFixed(2) + "</td>";
            rowData += "<td>" + orderType + "</td>";
            rowData += "</tr>";
            $(rowData).appendTo(".orderHistory > table > tbody").hide(0, function () {  $("article.orderHistory > table > tbody > tr:even, article.orderHistory > table > tbody > tr:even > td:odd").addClass("alt");}).fadeIn(200);
            register.orderDetailsToggle();
        });
    },
    orderDetailsTable: function (menuItemData) {
        var itemRowData = "";
        $(menuItemData).each(function (itemKey, item) {
            itemRowData += "<tr><td>" + item.name + "&nbsp;<strong>$" + parseFloat(item.price).toFixed(2) + "</strong></td><td class='quantity'>" + item.quantity +"</td></tr>";
        });
        return itemRowData;
    },
    orderDetailsToggle: function () {
        $(".orderHistory > table .orderDetails a").toggle(function() { // View Order Details toggle
            $(this).text("Hide").next().fadeIn(200);
        }, function () {
            $(this).text("View").next().fadeOut(200);
        });
    },
    ajaxLoadAnim: function () {
        $("<img src='/Content/Images/ajax-loader.gif' alt='loading'>").appendTo("article.orderHistory a.showMore").hide().ajaxStart(function () {
            $(this).show();
        }).ajaxComplete(function () {
            $(this).hide();
        });
    }
};

var map, marker, latLong;
var locations = {
    init: function () {
        var latitude = $("#Address_Latitude").val();
        var longitude = $("#Address_Longitude").val();
        latLong = new google.maps.LatLng(latitude, longitude);
        map = new google.maps.Map(document.getElementById('mapCanvas'), {
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: latLong,
            zoom: 14
        });
        locations.search();
    },
    search: function() {
        var geocoder = new google.maps.Geocoder();
        var address = $("#VenueAddress").val();
        geocoder.geocode({'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var found = results[0];
                map.setCenter(found.geometry.location);
                marker = new google.maps.Marker({
                    map: map,
                    position: found.geometry.location,
                    title: 'misschu - ' + found.formatted_address
                });
            }
            else {
                marker = new google.maps.Marker({
                    map: map,
                    position: latLong,
                    title: 'misschu'
                });
            }
            locations.toggleBounce(); // Animate marker
        });
    },
    toggleBounce: function() {
        if (marker.getAnimation() != null) { marker.setAnimation(null); }
        else { marker.setAnimation(google.maps.Animation.BOUNCE); }
    }
};


$(function () {
    if (helper.exists("#InitFlag")) { // Checks page for JS flag, if found, initializes correct object
        switch ($("#InitFlag").val()) {
            case "MeHungry":
                cart.init();
                break;
            case "Delivery":
                cart.init();
                delivery.init();
                break;
            case "CateringCanape":
                canapes.init();
                break;
            case "CateringEasyPick":
                easyPicks.init();
                break;
            case "MissChuSelections":
                missChuSelections.init();
                break;
            case "Account":
                register.init();
                break;
            case "Locations":
                locations.init();
                break;
            default:
                break;
        }
    }

    $("article#orderMenu table").each(function () {
        $("tbody tr.menuItemInfo:odd, tbody tr.menuItemImage:nth-child(4n)", this).addClass("odd"); // Add styling for alternating rows
    });

    // Selections jump menu hide/show toggle
    $(".jumpSelections h4 a").toggle(function (e) {
        e.preventDefault();
        $(this).addClass("show");
        $(".jumpSelections ul").slideUp(200);
    },
    function () {
        $(this).removeClass("show");
        $(".jumpSelections ul").slideDown(200);
    });

    // Menu images toggle
    $("td.showItemImage a").click(function (e) {
        e.preventDefault();
        if (!$(this).hasClass("active")) {
            $("tr.menuItemImage").hide();
            $(".showItemImage a").removeClass("active");
            $(this).addClass("active");
            var row = $(this).parent().parent().next(),
                imgLazy = row.find(".imgLazy");
            imgLazy.replaceWith("<img src='" + imgLazy.attr("data-src") + "' alt='" + imgLazy.attr("data-alt") + "' />");
            row.show();
        }
        else {
            $(this).removeClass("active").parent().parent().next().hide();
        }
    });

    // Anchor scrolling
    $("a[href*='#']").click(function (e) {
        if ($(this).attr("href").indexOf("http://") != -1) {
            return; // If it's a valid link with # in URL, ignore scrolling
        }
        e.preventDefault();
        var target = $(this).attr("href");
        if (target.length > 1) {
            e.preventDefault();
            var offset = $(target).offset();
            $("html, body").animate({ scrollTop: offset.top + "px" }, 400);
        }
    });

    if (helper.exists("#cvUpload")) {
        $("#cvUpload").change(function () {
            $("#WorkForUsSubmission_CvUrl").val($(this).val());
        });
    }
});
