﻿var timer = null;
var timeoutTimer = null;
var onDeleteHandler = null;

$(document).ready(function () {

    $(document).trigger("page-load", { pageName: 'view cart', section: '' });

    // Error message if any
    if (errorMessage != '') {
        if (errorIsWarning) {
            showWarning(errorMessage);
        }
        else {
            showMessage(errorMessage);
        }
    }

    // Handle Begin Checkout
    $(document.body).on('click', '.begin-checkout', function () {
        BeginCheckout();
        return false;
    });

    // Handle item remove
    $(document.body).on('click', '.remove-item', function () {
        var element = $(this).closest('li');
        var id = $(element).data('id');
        var type = $(element).data('type');
        var name = $(element).find('h4').first().text();

        AskForDelete(name, function () {
            RemoveItem(type, id, element, name);
        });
        return false;
    });

    // Handle item quantity change
    $(document.body).on('paste keyup', '.package-quantity', function (event) {
        // cancel any previously-set timer
        if (timer) {
            clearTimeout(timer);
        }

        var id = $(this).data("id");
        var qty = $(this).val();

        if (qty == '') {
            qty = 0;
        }

        var element = $(this).closest('li');
        var type = $(element).data('type');

        timer = setTimeout(function () {
            UpdateItem(type, id, qty);
        }, 400);
    });

    // Handle remove processing fee
    $(document.body).on("click", '#remove-cc-fees', function () {
        var element = $(this).closest('li');
        var name = $(element).find('h4').first().text();

        AskForDelete(name, function () {
            RemoveProcessingFee();
        });
        return false;
    });

    // Handle Changes on processing fee
    $('#check-processing-fee').on('change', function () {
        var isChecked = $(this).is(':checked');
        if (isChecked) {
            IncludeProcessingFee();
        }
        return false;
    });

    // Handle changes on cash donations
    $(document.body).on('click', '.edit-cash-donation', function () {
        showLoader();
        $.get(
            $Url.resolve("~/Cart/EditCashDonationModal"),
            function (result) {
                $('form').find('.ajax-dynamic-content').html(result);
                $(document).trigger("html-changed");
                $('#modal-edit-donate').modal('show');
                hideLoader();
            })
            .fail(hideLoader);
        return false;
    });

    $(document.body).on('click', '.remove-cash-donation', function () {
        var donationName = $(this).closest('.list-details').find('h4').first().text();
        var element = $(this).closest('li');

        AskForDelete(donationName, function () {
            RemoveDonation(element);
        });
        return false;
    });

    // Handle changes on Coupons
    $(document.body).on('click', '#coupon-apply', function () {
        applyCoupon();
        return false;
    });

    $(document.body).on('click', '.coupon-remove', function () {
        var element = $(this).closest('li');
        var id = $(element).data('id');
        var type = $(element).data('type');
        var name = $(element).find('h4').first().text();

        AskForDelete(name, function () {
            DeleteCoupon(element, id);
        });
        return false;
    });
    
    // Clear onDelete handler
    $(document.body).on('hidden.bs.modal', '#modal-cart-remove', function () {
        onDeleteHandler = null;
    });

    // Clear onDelete handler
    $(document.body).on('hidden.bs.modal', '#modal-edit-donate', function () {
        refresh();
    });

});

function refresh() {
    showLoader();
    $.post(
        $Url.resolve("~/Cart/RefreshShoppingCartTotals"),
        function (result) {
            renderTotals(result);
            hideLoader();
        })
}

function renderTotals(totals) {
    $('#total').text(totals.total);
    $('label.tax').text(totals.tax);
    $('label.fee').text(totals.fee);
    $('span#fee-value').text(totals.feeValue);

    if (totals.itemId != '') {
        $('.subtotal.item-' + totals.id).text(totals.value);
    }

    if (totals.donationValue != '') {
        $('.donation-item-value').text(totals.donationValue);
    }

    $('.coupon').hide();
    totals.coupons.forEach(function (element, index, array) {
        if ($('.coupon[data-id="' + element.id + '"]').length) {
            $('.coupon[data-id="' + element.id + '"]').show();
            $('.coupon[data-id="' + element.id + '"]').find('.subtotal').first().text(element.value);
        }
        else {
            var coupon = $('<li data-type="8" data-id="' + element.id + '" data-packageid="' + element.id + '" class="coupon"><div class= "list-details"><div class="list-detail-heading"><h4>' + element.descr + '</h4><span class="list-detail-controls"><a href="#" class="coupon-remove">Remove</a></span></div></div><div class="list-control-group"><div class="list-control"><label class="subtotal">' + element.value + '</label></div></div></li>');
            $('li[data-id="' + element.id + '"].purchase').after(coupon);
        }
    });

    refreshCartItemsQuantity();
}

function RemoveItem(type, id, element, name) {
    $('#modal-cart-remove').modal('hide');
    showLoader();
    $.post(
        $Url.resolve("~/Cart/RemoveItem"),
        { "type": type, "packageId": id },
        function (result) {
            $(document).trigger("remove-cart-event", { products: { productId: id, productType: type, productName: name } });
            $(element).remove();
            renderTotals(result);
            hideLoader();
        })
}

function RemoveProcessingFee() {
    $('#modal-cart-remove').modal('hide');
    showLoader();
    $.post(
        $Url.resolve("~/Cart/RemoveProcessingFee"),
        function (result) {
            $('#cc-fees').hide();
            $('#cc-fees-restore').show();
            renderTotals(result);
            hideLoader();
        })
}

function RemoveDonation(element) {
    $('#modal-cart-remove').modal('hide');
    showLoader();
    $.post(
        $Url.resolve("~/Cart/RemoveCashDonation"),
        function (result) {
            $(element).remove();
            renderTotals(result);
            hideLoader();
        })
}

function IncludeProcessingFee() {
    showLoader();
    $.post(
        $Url.resolve("~/Cart/IncludeProcessingFee"),
        function (result) {
            $('#cc-fees').css('display', 'flex');
            $('#cc-fees-restore').hide();
            $('#check-processing-fee').attr('checked', false);
            renderTotals(result);
            hideLoader();
        })
}

function UpdateItem(type, id, qty) {
    showLoader();
    $.post(
        $Url.resolve("~/Cart/UpdateItemQuantity"),
        {
            "type": type, "packageId": id, 'quantity': qty
        },
        function (result) {
            renderTotals(result);
            hideLoader();

            if (result.message != '') {
                showMessage(result.message);
            }
        });
}

function AskForDelete(itemName, onYes) {
    onDeleteHandler = onYes;
    showLoader();
    $.get(
        $Url.resolve("~/Cart/AskBeforeRemoving?itemName=" + encodeURIComponent(itemName)),
        function (result) {
            $('form').find('.ajax-dynamic-content').html(result);
            $(document).trigger("html-changed");
            $('#modal-cart-remove').modal('show');
            hideLoader();
        }).fail(hideLoader);
    return false;
}

function applyCoupon() {
    var code = $('.coupon-code').val();
    $.post(
        $Url.resolve("~/Cart/AddCuponToCart"),
        { 'code': code },
        function (result) {
            refresh();
            renderCoupons(result);
            $('.coupon-code').val('');
        });
}

function DeleteCoupon(element, id) {
    $('#modal-cart-remove').modal('hide');
    showLoader();
    $.post(
        $Url.resolve("~/Cart/DeleteCoupon"),
        { "id": id },
        function (result) {
            $(element).remove();
            renderTotals(result);
            hideLoader();
        })
}

function BeginCheckout() {
    showLoader();
    $.post(
        $Url.resolve("~/Cart/CanBeginCheckout"),
        function (result) {
            if (result.canBegin == true) {
                window.location = $Url.resolve("~/Checkout");
            }
            else {
                if (result.available > 0) {
                    $('.checkout-validation-message').text('We’re sorry, but there are only ' + result.available + ' admissions available for the event.  Please adjust your cart to proceed.');
                }
                else {
                    $('.checkout-validation-message').text('We’re sorry, but the event has sold out. All packages containing admission tickets will be removed from your cart. ');
                }

                showCannotCheckout();
                hideLoader();
            }
           
        })
}

function showCannotCheckout() {
    $('#cannot-continue-modal').modal(
        {
            backdrop: 'static',
            keyboard: false
        });
}

function renderCoupons(result) {
    // Delete all
    $('li.coupon').remove();

    $(result).each(function (idx, el) {
        if ($(el).is('li')) {
            var packageId = $(this).data('packageid');
            $('li[data-id="' + packageId + '"].purchase').after(el);
        }
        else if ($(el).is('p')) {
            showMessage($(el).text());
        }
    }) 

}

function showLoader() {
    $('div.cart').loading({ theme: 'light' });
}

function hideLoader() {
    $('div.cart').loading('stop');
}