<script type="text/javascript">
    $(document).ready(function () {
        initateCartOnDocumentReady();
        $('.category-tab').on('click', function () {
            var tabContentId = $(this).attr('id') + 'Content';
            zamanDesign.scrollPosition(tabContentId);
        });
        $('.order-changer').on('change', function () {
            if ($("input[name='onlineOrderType']").is(':checked')) {
                if ($(this).val() === 'delivery') {
                    $('.loader-order-type').show();
                    setCustomerDeliveryArea();
                } else {
                    $.ajax({
                        url: '<?php echo site_url('cart/setCollectionType') ?>',
                        type: 'POST',
                        dataType: 'json',
                        data: {'type': $(this).val()},
                        beforeSend: function () {
                            $('.loader-order-type').show();
                        },
                        success: function (response) {
                            if (response.status) {
                                if (response.onlineOrderType === 'collection') {
                                    window.location.reload();
                                }
                            }
                        }
                    });
                }
            }
        });
        $('#promoBlockChanger').on('change', function () {
            if ($(this).is(':checked')) {
                $('#promoBlock').show('slow');
            } else {
                $('#promoBlock').hide('slow');
            }
        });
        $('#noteBlockChanger').on('change', function () {
            if ($(this).is(':checked')) {
                $('#noteBlock').show('slow');
            } else {
                $('#noteBlock').hide('slow');
            }
        });
        $('.getmetocart').on('click', function () {
            var item = $(this);
            getMeToCart(item[0].dataset);
        });
        $('#addressBook').on('change', function () {
            var addressType = $(this).val();
            if (addressType === 'addnew') {
                setCustomerDeliveryArea();
            } else {
                $.ajax({
                    url: '<?php echo site_url('cart/presetPostcode') ?>',
                    type: 'POST',
                    dataType: 'json',
                    data: {'type': addressType},
                    beforeSend: function () {
                        $('.loader-order-type').show();
                    },
                    success: function (response) {
                        if (response.status) {
                            window.location.reload();
                        } else {
                            $('#addressTypeError').text(response.message);
                        }
                    }
                });
            }
        });
    });
    function getMeToCart(dataset) {
        $('.loader').hide();
        $('.loader' + dataset.c + '_' + dataset.m + '_' + dataset.s).show();
        if (dataset.dealtype !== '2' && dataset.hastop === '0' && dataset.hasmod === '0') {
            addToCart(dataset.c, dataset.m, dataset.s);
        } else {
            itemAttributesPopupController(dataset.c, dataset.m, dataset.s);
        }
    }

    function showThisCategoryContent(cat) {
        if ($('#iconId-' + cat + '.icon').hasClass('icon-up-open-big')) {
            $('#iconId-' + cat + '.icon').removeClass('icon-up-open-big');
            $('#iconId-' + cat + '.icon').addClass('icon-down-open-big');
        } else {
            $('#iconId-' + cat + '.icon').removeClass('icon-down-open-big');
            $('#iconId-' + cat + '.icon').addClass('icon-up-open-big');
        }
        $('#categoryBlock-' + cat).toggle();

    }
    function addToCart(c, m, s) {
        $.ajax({
            url: '<?php echo site_url('cart/addToCart') ?>',
            type: 'POST',
            dataType: 'json',
            data: {c: c, m: m, s: s},
            beforeSend: function () {
                $('.loader').hide();
                $('.loader' + c + '_' + m + '_' + s).show();
            },
            success: function (data, textStatus, jqXHR) {
                if (textStatus === 'success') {
                    loadCart(data);
                    manageCartItemListAreaScroll();
                    closePopup();
                }
                $('.loader' + c + '_' + m + '_' + s).hide();
            }
        });
    }
    function plus(line) {
        $.ajax({
            url: '<?php echo site_url('cart/plus') ?>',
            type: 'POST',
            dataType: 'json',
            data: {line: line},
            beforeSend: function (xhr) {
                $('.loader-' + line).show();
            },
            success: function (data) {
                if (!jQuery.isEmptyObject(data)) {
                    loadCart(data);
                }
            }
        });
    }
    function minus(line) {
        $.ajax({
            url: '<?php echo site_url('cart/minus') ?>',
            type: 'POST',
            dataType: 'json',
            data: {line: line},
            beforeSend: function (xhr) {
                $('.loader-' + line).show();
            },
            success: function (data) {
                if (!jQuery.isEmptyObject(data)) {
                    loadCart(data);
                }
            }
        });

    }
    function remove(line) {
        $.ajax({
            url: '<?php echo site_url('cart/remove') ?>',
            type: 'POST',
            dataType: 'json',
            data: {line: line},
            beforeSend: function (xhr) {
                $('.loader-' + line).show();
            },
            success: function (data) {
                if (!jQuery.isEmptyObject(data)) {
                    loadCart(data);
                }
            }
        });
    }
    function clearCart() {
        $.ajax({
            url: '<?php echo site_url('cart/clear') ?>',
            type: 'POST',
            dataType: 'json',
            success: function (data) {
                if (!jQuery.isEmptyObject(data)) {
                    loadCart(data);
                }
            }
        });
    }
    function initateCartOnDocumentReady() {
        $.ajax({
            url: '<?php echo site_url('cart') ?>',
            type: 'POST',
            dataType: 'json',
            success: function (data) {
                if (!jQuery.isEmptyObject(data)) {
                    loadCart(data);
                    manageCartItemListAreaScroll();
                }
            }
        });
    }
    function loadCart(data) {
        $('#cartActiveLine').val(data.line);
        setOrderType(data.orderType);
        renderCartItems(data.cart);
        cartTax(data.tax);
        cartDeliveryFee(data.orderType, data.deliveryFee, data.subtotal, data.deliveryMinOrderAmount);
        if (Number(data.serviceCharge) > 0) {
            cartServiceCharge(data.serviceCharge, data.subtotal);
        }
        cartSubtotal(data.subtotal);
        cartDiscount(data.discount);
        cartPromoDisocunt(data.promoDisocunt);
        cartMultiDiscount(data.multiDiscount);
        cartTotal(data.total);
        $('.cart-item-line').removeClass('cart-active-line');
        $('.line-' + $('#cartActiveLine').val()).addClass('cart-active-line');


    }
    function setOrderType(orderType) {
        if (orderType === 'collection') {
            $('#onlineOrderTypeCollection').not(':checked').prop("checked", true);
        }
        if (orderType === 'delivery') {
            $('#onlineOrderTypeDelivery').not(':checked').prop("checked", true);
        }
    }
    function renderCartItems(cart) {
        var cartHtml = '';
        for (var index in cart) {
            cartHtml += '<div class="cart-item-line line-' + index + '">';
            var itemTitle = '';
            if ($.trim(cart[index].selectionTitle)) {
                itemTitle += cart[index].selectionTitle + ' - ' + cart[index].menuTitle;
            } else {
                itemTitle += cart[index].menuTitle;
            }
            cartHtml += '<div class="cart-item-info row">';
            cartHtml += '<div class="cart-item-name-string"><span class="price">' + cart[index].qty + '&nbsp;</span>' + itemTitle + '</div>';
            cartHtml += '<div class="cart-item-price-string price">' + toCurrency(cart[index].total) + '</div>';
            cartHtml += '</div>';
            if (cart[index].isFree === 'no') {
                cartHtml += '<div class="cart-item-action row">';
                cartHtml += '<div class="cart-item-name-string">';
                cartHtml += '<a href="javascript:void(0)" class="icon icon-plus" onclick="plus(\'' + index + '\')"></a><div class="loader loader-' + index + '" style="display:none; float:right"></div>';
                if (cart[index].Topping.length > 0 || cart[index].modifier.length > 0 || cart[index].setItem.length > 0) {
                    cartHtml += '&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)"  class="icon icon icon-down-open-big" onclick="showCartItemAttributes(\'' + index + '\')"></a>';
                }
                cartHtml += '</div>';
                cartHtml += '<div class="cart-item-price-string">';
                cartHtml += '<a href="javascript:void(0)" class="icon icon-minus" onclick="minus(\'' + index + '\')"></a>';
                if (cart[index].menuTitle !== "Bag") {
                    cartHtml += '&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)" class="icon icon-trash" onclick="remove(\'' + index + '\')"></a>';
                }
                cartHtml += '</div>';
                cartHtml += '</div>';
            }
            if (cart[index].Topping.length > 0 || cart[index].modifier.length > 0 || cart[index].setItem.length > 0) {
                cartHtml += '<div class="cart-item-action row cart-item-additional-info" id="CartItemAttributes' + index + '">';
                if (cart[index].setItem.length > 0) {
                    cartHtml += "<div><strong>Item : </strong></div>";
                    cart[index].setItem.forEach(function (anItem) {
                        cartHtml += '<div>' + anItem.qty + ' ' + anItem.title + '</div>';
                    });
                }
                if (cart[index].Topping.length > 0) {
                    cartHtml += "<div><strong>With : </strong></div>";
                    cart[index].Topping.forEach(function (aTop) {
                        if (Number(aTop.total) > 0) {
                            cartHtml += '<div>' + aTop.qty + ' ' + aTop.title + ' ' + toCurrency(aTop.total) + '&nbsp;&nbsp;<span class="icon icon-plus" onclick="plusItemAttribute(\'' + index + '\',\'' + aTop.category + '\',\'' + aTop.id + '\')"></span></div>';
                        } else {
                            cartHtml += '<div>' + aTop.title + '</div>';
                        }
                    });
                }
                if (cart[index].modifier.length > 0) {
                    cartHtml += '<div>2&nbsp;vindi vagi</div>';
                }
                if ($.trim(cart[index].comment)) {
                    cartHtml += '<div style="width:90%"><span><b>comment:</b>&nbsp;' + cart[index].comment + '</span></div>';
                }

                cartHtml += '</div>';
            }
            cartHtml += '</div>';
        }
        $('#cartItemListArea').html(cartHtml);
    }
    function cartSubtotal(subtotal) {
        $('#cartSubtotal').text(toCurrency(subtotal));
    }
    function cartTax(tax) {
        if (Number(tax) > 0) {
            $('#cartTaxBlock').show();
            $('#cartTax').text(toCurrency(tax));
        } else {
            $('#cartTaxBlock').hide();
        }
    }
    function cartDeliveryFee(orderType, fee, subtotal, minOrderAmount) {
        if (orderType === 'delivery') {
            if (Number(subtotal) > 0) {
                $('#cartDeliveryFeeBlock').show();
                if (Number(fee) > 0) {
                    $('#cartDeliveryFee').text(toCurrency(fee));
                } else {
                    $('#cartDeliveryFee').text('Free');
                }
                if (Number(minOrderAmount) > Number(subtotal)) {
                    window.location.href = "<?php echo site_url('online-order') ?>";
                }
            } else {
                $('#cartDeliveryFeeBlock').hide();
                window.location.href = "<?php echo site_url('online-order') ?>";
            }
        } else {
            if (Number(subtotal) <= 0) {
                window.location.href = "<?php echo site_url('online-order') ?>";
            }
            $('#cartDeliveryFeeBlock').hide();
        }
    }
    function cartDiscount(discount) {
        if (Number(discount) > 0) {
            $('#cartDiscountBlock').show();
            $('#cartDiscount').text(toCurrency(discount));
        } else {
            $('#cartDiscountBlock').hide();
        }
    }
    function cartPromoDisocunt(discount) {
        if (Number(discount) > 0) {
            $('#cartPromoDiscountBlock').show();
            $('#cartPromoDiscount').text(toCurrency(discount));
        } else {
            $('#cartPromoDiscountBlock').hide();
        }
    }
    function cartMultiDiscount(multiDiscount) {
        if (Number(multiDiscount) > 0) {
            $('#cartMultiDiscountBlock').show();
            $('#cartMultiDiscount').text(toCurrency(multiDiscount));
        } else {
            $('#cartMultiDiscountBlock').hide();
        }
    }
    function cartServiceCharge(serviceCharge, subtotal) {
        if (Number(subtotal) > 0) {
            $('#cartServiceChargeBlock').show();
            $('#cartServiceCharge').text(toCurrency(serviceCharge));
        } else {
            $('#cartServiceChargeBlock').hide();
        }
    }
    function cartTotal(total) {
        $('#cartTotal').text(toCurrency(total));
    }
    function showCartItemAttributes(index) {
        $('#CartItemAttributes' + index).toggle();
    }
    function plusItemAttribute(line, category, id) {
        $.ajax({
            url: '<?php echo site_url('cart/plusItemAttribute') ?>',
            type: 'post',
            dataType: 'json',
            data: {line: line, category: category, id: id},
            success: function (data) {
                if (!jQuery.isEmptyObject(data)) {
                    loadCart(data);
                }
            }
        });
    }
</script>