$(function() {

    /* CUSTOM SCROLLBAR */
    $(window).on("load", function() {

        $(".sidebar, .modal").mCustomScrollbar({
            theme: "dark-3"
        });

    });

    /* SWITCH SALE AND ORDER TAB*/
    $('#product-tab').click(function(e) {
        $('.product-list').show();
        $(this).addClass('active');
        $('#order-tab').removeClass('active');
        $('.order-list').hide();
    });
    $('#order-tab').click(function(e) {
        e.preventDefault();
        $('.order-list').show();
        $(this).addClass('active');
        $('#product-tab').removeClass('active');
        $('.product-list').hide();
    });



    $('.dropdown-toggle').dropdown();

    $('.barcode-input input[type="text"]').focus();

    /* HIDDEN SEARCH BUTTON */
    var searchText = "";//$(".top-navbar .search-box input[type='text']");
    $('.search-btn .ion-close-circled').hide();

    $('.search-btn .ion-ios-search').click(function() {
        searchText.show();
        $('.search-btn .ion-close-circled').show();
        //$(this).hide();
    });
    $('.search-btn .ion-close-circled').click(function() {
        if (searchText.val() != '') {
            searchText.val('');
            searchText.focus();
        } else {
            $(searchText).hide();
            $(this).hide();
            $('.search-btn .ion-ios-search').show();
        }
    });
    $(searchText).blur(
        function(event) {
            if ($(this).val() == '') {
                $(this).hide();
                $('.search-btn .ion-close-circled').hide();
                $('.search-btn .ion-ios-search').show();
            }
            //$(this).hide();
        }
    );



    /* SWITCH CASH AND EXTERNAL TERMINAL*/
    $('#cash-tab').click(function() {
        $('.switch-cash').show();
        $(this).addClass('btn-success').removeClass('btn-default');
        $('#terminal-tab').removeClass('btn-success').addClass('btn-default');
        $('.switch-terminal').hide();
    });
    $('#terminal-tab').click(function() {
        $('.switch-terminal').show();
        $(this).addClass('btn-success').removeClass('btn-default');
        $('#cash-tab').removeClass('btn-success').addClass('btn-default');
        $('.switch-cash').hide();
    });

    /* ADJUST NUMBER BUTTON*/
    $('.product-number .minus').click(function() {
        var currentNumber = $('.product-number .item-number').text();
        $('.item-number').text(parseInt(currentNumber) - 1);
    });
    $('.product-number .plus').click(function() {
        var currentNumber = $('.product-number .item-number').text();
        $('.item-number').text(parseInt(currentNumber) + 1);
    });

    $('.item-unit .minus').click(function() {
        var currentNumber = $('.item-unit .item-number input').val();
        if (currentNumber <= 1) {
            return;
        }
        $('.item-number input').val(parseInt(currentNumber) - 1);
    });
    $('.item-unit .plus').click(function() {
        var currentNumber = $('.item-unit .item-number input').val();
        $('.item-number input').val(parseInt(currentNumber) + 1);
    });

    /* DRAWER AND ACTIVITY LOG*/
    $('#btn-drawer').click(function() {
        $('.drawer-wrapper').show();
        $('.activity-log').hide();
        $(this).addClass('btn-success').removeClass('btn-default');
        $('#btn-activity').removeClass('btn-success').addClass('btn-default');
    });
    $('#btn-activity').click(function() {
        $('.activity-log').show();
        $('.drawer-wrapper').hide();
        $(this).addClass('btn-success').removeClass('btn-default');
        $('#btn-drawer').removeClass('btn-success').addClass('btn-default');
    });

    //$('.add-amount-modal').modal('show');
    //$('.no-conn-modal').modal('show');

    /* CALCULATOR */

    //percentages
    var decimalVal = function(num) {
        fixedNum = 2;
        return parseFloat(num).toFixed(fixedNum);
    }
    var percentageBtn = function(btn, val, resultBox) {
        $(btn).click(function(e) {
            e.preventDefault();
            $('.percentage-tab').addClass('btn-success').removeClass('btn-default');
            $('.dollar-tab').addClass('btn-default').removeClass('btn-success');
            $(this).addClass('btn-success').removeClass('btn-defualt');
            $(this).siblings('a').addClass('btn-default').removeClass('btn-success');
            var result = decimalVal(val);
            $(resultBox).val(result);
        });
    }
    var numberBtn = function(btn, val, resultBox) {
        $(btn).click(function(e) {

            e.preventDefault();
            $('.numeric-btn').find('a').addClass('btn-default').removeClass('btn-success');
            var result = val;
            result += $(resultBox).val().toString();
            $(resultBox).val(result);
        });
    }
    $('.dollar-tab').click(function(e) {
        e.preventDefault();
        $(this).addClass('btn-success').removeClass('btn-default');
        $('.percentage-tab').addClass('btn-default').removeClass('btn-success');
    });
    $('.percentage-tab').click(function(e) {
        e.preventDefault();
        $(this).addClass('btn-success').removeClass('btn-default');
        $('.dollar-tab').addClass('btn-default').removeClass('btn-success');
    });

    percentageBtn('#five-percent', 5, '#result-text');
    percentageBtn('#ten-percent', 10, '#result-text');
    percentageBtn('#twenty-percent', 20, '#result-text');
    percentageBtn('#thirty-percent', 30, '#result-text');
    percentageBtn('#fifty-percent', 50, '#result-text');
    percentageBtn('#clear-text', 0, '#result-text');

    numberBtn('#number-one', 1, '#result-text');
    numberBtn('#number-two', 2, '#result-text');
    numberBtn('#number-three', 3, '#result-text');
    numberBtn('#number-four', 4, '#result-text');
    numberBtn('#number-five', 5, '#result-text');
    numberBtn('#number-six', 6, '#result-text');
    numberBtn('#number-seven', 7, '#result-text');
    numberBtn('#number-eight', 8, '#result-text');
    numberBtn('#number-nine', 9, '#result-text');
    numberBtn('#number-enter', '', '#result-text');
    numberBtn('#number-dot', '.', '#result-text');
    numberBtn('#number-zero', 0, '#result-text');

    //numbers

    /* SIDEBAR ITEM LIST*/
    $('#edit-sidebar-item').on('show.bs.modal', function(e) {
        //get data-item-id value when show modal
        var itemId = $(e.relatedTarget).data('item-id'),
            //get selector from sidebar list item
            itemList = $('li[data-item-id="' + itemId + '"]'),
            //get the title from list item
            listTitle = itemList.find('.title').text(),
            //get item number from list item
            itemUnit = itemList.find('.badge').text(),
            //get price from list item
            listPrice = itemList.find('span.price-val').data('price'),
            listDiscount = itemList.find('.discount-val').val();
        $(e.currentTarget).find('h5').text(listTitle);
        $(e.currentTarget).find('#product-id').val($(e.relatedTarget).data('product-id'));
        $(e.currentTarget).find('#order-id').val($(e.relatedTarget).data('order-id'));
        $(e.currentTarget).find('.item-number input').val(parseInt(itemUnit)).focus();
        $(e.currentTarget).find('input[name="item-price"]').val(decimalVal(listPrice));
        $(e.currentTarget).find('input[name="item-discount"]').val(parseInt(listDiscount));
    });


    /*
    Trigger Sidebar
     */
    $('.trigger-sidebar').on('click', function() {
        $('.sale-container').toggleClass('sidebar-open');
        $('.sale-container').toggleClass('sidebar-collapse');
    });

    /* CURRENCY MODAL */
    // disable checkout button from submitting
    // $('#btn/-submit').prop('disabled', true).addClass('disabled btn-default').removeClass('btn-success');
    // if ($('.product-list > .row').data('customer-id')) {
    //     $('#btn-submit').prop('disabled', false).removeClass('disabled btn-default').addClass('btn-success');
    // }

    function moneyRiel(amount) {
        if (amount == 0) return 0;
        amount = parseInt(amount).toString();
        lt = amount.substring(amount.length - 2);
        if (amount.length <= 2 && lt < 50) return 0;
        lt = parseInt(lt);
        if (lt >= 50 ) {
              amount = (amount - lt) + 100;
        } else {
              amount = (amount - lt);
        }
        return amount;
      }



    $('.currency-modal').on('show.bs.modal', function(e) {
        var button = $(e.relatedTarget);
        var totalRiel = button.data('total-riel');
        var totalUsd  = button.data('total-usd');
        var amountWrapper = $('.amount-wrapper');
        var modalHeader = $('.currency-modal');
        var firstCurrencyInput = $('.usd-price').val();
        var secondCurrencyInput = $(".riel-price").val();
        var exchange = parseFloat($('.cart-item-container').data('currency'));
        if (totalRiel) {
             $('#input-riel').val(secondCurrencyInput).focus();
             $("#input-dollar").val(0);
        } else {
             $('#input-dollar').val(firstCurrencyInput).focus();
             $("#input-riel").val(0);
        }
       
        $('#input-dollar, #input-riel, #select-customer').trigger('change');
        sign = amountWrapper.data('currency-sign');
        secondSign = amountWrapper.data('second-currency-sign');
        totalFirst = (sign == "$") ? fmoney(firstCurrencyInput, 2) : moneyRiel(firstCurrencyInput).format();
        totalSecond = (secondSign == "$") ? fmoney(secondCurrencyInput, 2) : moneyRiel(secondCurrencyInput).format();
        modalHeader.find('.price-title-dollar').text(sign + " " + totalFirst);
        modalHeader.find('.price-title-riel').text(secondSign + " " + totalSecond);
        if (($('#input-dollar').val() != '0' && $('#input-dollar').val() != '') ||
            ($('#input-riel').val() != '0' && $('#input-riel').val() != '')) {
            var inputFirstCurrency = parseFloat($('#input-dollar').val());
            var inputSecondCurrency = (secondSign == "$") ? moneyRiel($("#input-riel").val() / exchange) : parseFloat($('#input-riel').val() / exchange);
            var inputTotal = parseFloat(inputFirstCurrency + inputSecondCurrency);
            var receivedTotal = parseFloat(inputTotal - parseFloat(firstCurrencyInput));
            var receivedTotalRiel = receivedTotal * exchange;
            var changedFirst = (sign == "$") ? fmoney(receivedTotal, 2) : moneyRiel(receivedTotal).format();
            var changedSecond = (secondSign == "$") ? fmoney(receivedTotalRiel, 2) : moneyRiel(receivedTotalRiel).format();
                $('#received-total').val(sign + " " + changedFirst + " | " + secondSign + " " + changedSecond);
            if (receivedTotal < 0) {
                $('#btn-submit').prop('disabled', true).addClass('disabled btn-default').removeClass('btn-success');
            } else {
                $('#btn-submit').prop('disabled', false).removeClass('disabled btn-default').addClass('btn-success');
            }
        }
        $('#input-dollar, #input-riel, #select-customer').bind("keyup change", function() {
            var selectedValue = $('#select-customer').val();
            if ($('#input-dollar, #input-riel').val() != "") {
                var inputFirstCurrency = parseFloat($('#input-dollar').val());
                var inputSecondCurrency = (secondSign == "$") ? moneyRiel($("#input-riel").val() / exchange) : parseFloat($('#input-riel').val() / exchange);
                var inputTotal = parseFloat(inputFirstCurrency + inputSecondCurrency);
                var receivedTotal = parseFloat(inputTotal - parseFloat(firstCurrencyInput));
                var receivedTotalRiel = receivedTotal * exchange;
                var changedFirst = (sign == "$") ? fmoney(receivedTotal, 2) : moneyRiel(receivedTotal).format();
                var changedSecond = (secondSign == "$") ? fmoney(receivedTotalRiel, 2) : moneyRiel(receivedTotalRiel).format();
                $('#received-total').val(sign + " " + changedFirst + " | " + secondSign + " " + changedSecond);

                if (selectedValue == '' || selectedValue == null && receivedTotal < 0) {
                    $('#btn-submit').prop('disabled', true).addClass('disabled btn-default').removeClass('btn-success');
                } else {
                    $('#btn-submit').prop('disabled', false).removeClass('disabled btn-default').addClass('btn-success');
                }

            } else {
                $('#received-total').val('0');
            }
        });
    });
    $('#numpadButton-btn').numpad({
        target: $('#numpadButton')
    });
    $('#usd-btn').numpad({
        target: $('#input-dollar'),
        onKeypadClose: function() {
            $('#usd-btn').trigger('change');
        }
    });
    $('#item-price-btn').numpad({
        target: $('#item-price'),
        onKeypadClose: function() {
            $('#usd-btn').trigger('change');
        }
    });
    $('#item-discount-btn').numpad({
        target: $('#item-discount'),
        onKeypadClose: function() {
            $('#usd-btn').trigger('change');
        }
    });
    $('#item-number-btn').numpad({
        target: $('#item-number'),
    });
    $('#riel-btn').numpad({
        target: $('#input-riel')
    });
    $('.currency-modal,.item-list-modal').on('hide.bs.modal', function(e) {
        $('.nmpd-wrapper').hide();
    });
    $('.currency-modal').on('shown.bs.modal', function(e) {
        var button = $(e.relatedTarget);
        var totalRiel = button.data('total-riel');
        var totalUsd  = button.data('total-usd');
        if (totalRiel) {
             $('#input-riel').focus();
        } else {
             $('#input-dollar').focus();
        }
    });

});

Number.prototype.format = function(n, x) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};
