jQuery(function($) {
    /* DRAG AND DROP PRODUCT */
    function fetchItem() {
        var fetchUrl = $('.cart-item-container').data('fetch-url');
        $('.ordered-list').load(fetchUrl);
    };
    fetchItem();
    (function() {
        var amountWrapper = $('.amount-wrapper');
        secondSign = amountWrapper.data('second-currency-sign');
        sign = $('.amount-wrapper').data('currency-sign');
        $('.loading').hide('fast');
        var proId = 0;
        $('.product-item').draggable({
            helper: 'clone',
            zIndex: 20,
            start: function() {
                proId = $(this).data('id');
                $('.sale-content').css('overflow-y', 'visible');
            },
            stop: function() {
                $('.sale-content').css('overflow-y', 'auto');
            }
        });
        $('.cart-item-container').droppable({
            drop: function(e, ui) {
                orderProduct(proId, "");
            }
        });
        $('.product-list .product-item').on('click', function(e) {
            e.preventDefault();
            orderProduct($(this).data('id'), "");
        });
        $(document).on('click', ".btn-add-cart", function () {
            console.log($(this));
            orderProduct($(this).data('id'), "");
        })

        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;
      }
        /**
         * Add Product To Cart
         * @param  {integer} productId
         * @param  {integer} sku
         * @return {void}
         */
        function orderProduct(productId, sku, amount, discount, price) {
            /* If Product ID is given */
            if (sku == "") {
                formData = "productId=" + productId;
            }
            /* If SKU is submitted */
            else {
                formData = "sku=" + sku;
            }
            if (!amount == "") {
                price = parseFloat(price);
                formData = formData.concat("&amount=" + amount + "&discount=" + discount + "&price=" + price);
            }
            if ($('#price_type').prop('checked')) {
                formData = formData.concat("&wholesale=true");
            }

            var storeProductUrl = $('.cart-item-container').data('store-product-url');
            var fetchUrl = $('.cart-item-container').data('fetch-url');
            $.ajax({
                type: "POST",
                url: storeProductUrl,
                data: formData,
                success: function(data) {
                    console.log(data);
                    $('.loading').hide('fast');
                    var returnData = data;
                    toastr.options = {
                        "progressBar": false,
                        "positionClass": "toast-bottom-left",
                        "hideMethod": "fadeOut"
                    }
                    if (returnData.error)
                        toastr.error(returnData.message);
                    else {
                        getTotalUpdate(returnData);
                    }
                }
            }, "json");
        }

        function removeItem(id) {
            /* If Product ID is given */
            productUrl = $('.cart-item-container').data('store-product-url');
            destroyProductUrl = productUrl + "/" + id;
            $.ajax({
                type: "DELETE",
                url: destroyProductUrl,
                success: function(data) {
                    $('.loading').hide('fast');
                    var returnData = data;
                    toastr.options = {
                        "progressBar": false,
                        "positionClass": "toast-bottom-left",
                        "hideMethod": "fadeOut"
                    }
                    if (returnData.error)
                        toastr.error(returnData.message);
                    else {
                         getTotalUpdate(returnData);
                    }
                }
            }, "json");
        }

        function getTotalUpdate(returnData) {
            var order = returnData.order;
            priceDollar = parseFloat(returnData.grand_total).toFixed(2);
            var grandTotal = (sign == "$") ? parseFloat(returnData.grand_total).toFixed(2) : moneyRiel(returnData.grand_total);
            var total = (sign == "$") ? fmoney(returnData.total, 2) : moneyRiel(returnData.total).format();
            var secondPrice = (secondSign == "$") ? fmoney(returnData.total_riel, 2) : moneyRiel(returnData.total_riel);
            $('.price').html(sign + " " + total);
            $('.amount-price').html(sign + " "+ total);
            if (returnData.tax)
                $('.tax').html(parseInt(returnData.tax) + "%");
            else
                $('.tax').html("%");
            var secondPriceDisplay = (secondSign == "$") ? fmoney(returnData.total_riel, 2) : moneyRiel(returnData.total_riel).format();
            $('.price-riel').html(secondSign + " " + secondPriceDisplay);
            $('.usd-price').val(grandTotal);
            $('.riel-price').val(secondPrice);
            $('#btn-charge-usd').attr('data-total-usd', grandTotal);
            $("#btn-charge-riel").attr('data-total-riel', secondPrice);
            fetchItem();
            toastr.success(returnData.message);
        }

        $('.submit_sku').on('submit', function(e) {
            e.preventDefault();
            sku = $(".product_sku_n").val();
            console.log(sku);
            orderProduct("", sku);
            $(".product_sku_n").val("");
        });
        $('.save-item').on('click', function(e) {
            e.preventDefault();
            var data = {
                "amount": $('.item-number input').val(),
                "price": $('#item-price').val(),
                "discount": $('#item-discount').val(),
                "productId": $('#product-id').val()
            };
            checkProductPriceIn(data);
        });
        $('.edit-sidebar-item-form').on('submit', function(e) {
            e.preventDefault();
           var data = {
                "amount": $('.item-number input').val(),
                "price": $('#item-price').val(),
                "discount": $('#item-discount').val(),
                "productId": $('#product-id').val()
            };
            checkProductPriceIn(data);
        });
        $('.remove-item').on('click', function(e) {
            e.preventDefault();
            orderId = $('#order-id').val();
            removeItem(orderId);
            $('.item-list-modal').modal('hide');
        });
        $('.search-product').on('select2:select', function(evt) {
            orderProduct($(this).val(), "");
            $(this).find('option').remove();
            $('#select2-search-product-container').html('');
        });

        $('.submit_sku_f4').on('submit', function(e) {
            e.preventDefault();
            var sku = $(".product_sku").val();
            console.log(sku);
            $.ajax({
                type: "POST",
                url : $(".product_sku").data('url'),
                data: {"sku": sku},
                success: function (data) {
                    toastr.options = {
                        "progressBar": false,
                        "positionClass": "toast-bottom-left",
                        "hideMethod": "fadeOut"
                    }
                    if (data.error) {
                        toastr.error(data.message); 
                        // if (data.pnf) {
                        //     $.alert({
                        //         title: data.message,
                        //         content: 'ERROR 404',
                        //         theme: 'supervan',
                        //         autoClose: 'okay|1000',
                        //         buttons: {
                        //             okay: function () {

                        //             }
                        //         }
                        //     });
                        // }
                    } else {
                        setValueFormOrder(data);
                        $(".form-new-order").show();
                        $(".p_price").focus();
                        $("#btn-confirm-order").prop('disabled', false);
                        $(".barcode-sku").hide();
                    }
                }
            });
        });
        function setValueFormOrder(data) {
            $(".p_price").val(data.obj.price);
            $(".p_amount").val(data.amount + 1);
            $(".p_id").val(data.obj.product_id);
            $(".p_sku").val(data.obj.sku);
            $(".order-title").text(data.p_name + " [ " + data.obj.sku + " ]");
        }
        $('#orderProductModal').on('show.bs.modal', function () {
          $(".product_sku").focus();
          $(".btn-confirm-order").prop('disabled', true);
          $(".form-new-order").hide();
        });

        $('#orderProductModal').on('shown.bs.modal', function () {
            $(".product_sku").val("").focus();
            $(".order-title").text("Order New Product");
        });
        $("#orderProductModal").on('hide.bs.modal', function () {
            $(".product_order_sku").text("");
            $(".barcode-sku").show();
        });
        /**
         * Form Data
         * @type {Object}
         */
        $("#form-add-new-order").submit( function(e) {
            var data = {
                'amount': $('.p_amount').val(),
                'price': $('.p_price').val(),
                'productId': $('.p_id').val(),
                'discount': 0

            };
            e.preventDefault();
            checkProductPriceIn(data);
            $(".product_sku_n").focus();

        });

        function checkProductPriceIn(data) {
            $.ajax({
                type: "POST",
                url: $("#form-add-new-order").attr('action'),
                data: data,
                success: function (data2) {
                    console.log(data2);
                    if (data2.error) {
                        toastr.options = {
                        "progressBar": false,
                        "positionClass": "toast-bottom-left",
                        "hideMethod": "fadeOut"
                        }
                        if (data2.lower_price) {
                           $.confirm({
                                title: data2.title,
                                content: data2.message,
                                
                                theme: 'supervan',
                                buttons: {
                                    confirm: function () {
                                        orderProduct(data2.productId, "",data2.amount, data2.discount, data2.price);
                                        $(".product_order_sku").text("");
                                        $(".barcode-sku").show();
                                        $('#orderProductModal').modal('hide');
                                        $('.item-list-modal').modal('hide');
                                        fetchItem();
                                    },
                                    cancel: function () {
                                        console.log("Cancel");
                                    }
                                }
                            });
                        } else {
                           toastr.error(data2.message); 
                        }
                     } else {
                        orderProduct(data2.productId, "",data2.amount, data2.discount, data2.price);
                        fetchItem();
                        $(".product_order_sku").text("");
                        $(".barcode-sku").show();
                        $('#orderProductModal').modal('hide');
                        $('.item-list-modal').modal('hide');
                    }
                }
            });
        }
    })();

    /**
     * Filter Products
     * @return {void}
     */
    +
    (function() {
        sign = $('.amount-wrapper').data('currency-sign');
        function formatProduct(product) {
            var tUrl = $('.search-product').data('product-thumbnail-url');
            var markup = "<div class='select2-result-product clearfix'>" +
                "<div class='select2-result-product-meta'>" +
                "<div class='select2-result-product-title'>" + product.name + "</div>";
            markup += "<div class='select2-result-product-detail'>" +
                "<div class='select2-result-product-price'>" + fmoney(product.price, 2) + " " + sign + "</div>" +
                "</div>" +
                "</div></div>";

            return markup;
        }

        function formatProductSelection(product) {
            return product.name || product.name_kh;
        }
        $('.search-product').select2({
            ajax: {
                url: $('.search-product').data('product-list-url'),
                dataType: 'json',
                delay: 250,
                type: "GET",

                data: function(params) {
                    return {
                        term: params.term, // search term
                    };
                },
                processResults: function(data, params) {
                    // parse the results into the format expected by Select2
                    // since we are using custom formatting functions we do not need to
                    // alter the remote JSON data, except to indicate that infinite
                    // scrolling can be used

                    return {
                        results: data.customers
                    };
                },
                cache: false
            },
            escapeMarkup: function(markup) { return markup; },
            minimumInputLength: 3,
            placeholder: 'Find Products',
            templateResult: formatProduct,
            templateSelection: formatProductSelection
        });

    })();
/**
     * Filter Customer
     * @return {void}
     */
    +
    (function() {
      $('.customer').select2({
            allowClear: true,
           ajax: {
             url: $(".customer").data('customer-list-url'),
             dataType: 'json',
             delay: 250,
             type: "GET",

             data: function (params) {
               return {
                 term: params.term, // search term
               };
             },
             processResults: function (data, page) {
                data = data.customers;
               return {
                 results: $.map(data, function (item) {
                     return {
                         text: item.first_name+" "+item.last_name,
                         id: item.id
                     }
                 })
                };
             },
             cache: false
           },
           initSelection: function(element, callback) {
                callback({ id: 10, text: "Hello World"});
                },
           minimumInputLength: 3,
           placeholder: 'ស្វែងរកអតិថិជន',
           formatResult: function (data, term) {
             return data;
            },
            formatSelection: function (data) {
                return data;
            },
            escapeMarkup: function (m) {
                return m;
            }
         });
         $('.customer').on('select2:unselect', function (evt) {
              $(this).trigger('change');
            });




        })();
    /**
     * Keycode Activation
     */
    +
    (function() {
        $(document).bind('keydown', function(e) {
            // console.log(e.keyCode);
            switch (e.keyCode) {
                case 117: //F6
                    $('.barcode-input input[type="text"]').focus();
                    return false;
                    break;
                case 118: //F7
                    $('#search-product').select2('open');
                    return false;
                    break;
                case 119: //F8
                    $('.currency-modal').modal('show');
                    return false;
                    break;
                case 114: //F3
                    $('.save-invoice').trigger('click');
                    return false;
                    break;
                case 115: // F4
                    $("#orderProductModal").modal({
                        backdrop: 'static',
                        keyboard: false
                    }).show();
                    $(".form-new-order").hide();
                    $("#btn-confirm-order").prop('disabled', true);
                    break;

            }
        });
        keyCodeConvert = {
            49: 0,
            50: 1,
            51: 2,
            52: 3,
            53: 4,
            54: 5,
            55: 6,
            56: 7,
            57: 8,
            58: 9,
        };
        $(document).bind('keydown', function(e) {
            productItem = $('.cart-item-container ul li');
            code = e.keyCode;
            if (e.ctrlKey) {
                productItem.eq(keyCodeConvert[code]).trigger('click');
            }
        });
        $(document).bind('keydown', function(e) {
            code = e.keyCode;
            if (code == 39 && e.shiftKey) {
                $('#order-tab').trigger('click');
            }
            if (code == 37 && e.shiftKey) {
                $('#product-tab').trigger('click');
            }
        });
        $('#input-dollar').keydown(function(e) {
            switch (e.keyCode) {
                case 9: //F6
                    $('#input-riel').focus();
                    return false;
                    break;
            }
        });
    })();
    /**
     * Application
     */
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-96392272-1', 'auto');
    ga('send', 'pageview');
    /**
     * Add new Customer
     */
     $("#form-add-customer").submit(function (e) {
        e.preventDefault();
        $.ajax({
            url: $("#form-add-customer").attr('action'),
            type: "POST",
            data: $("#form-add-customer").serialize(),
            success : function (data) {
                console.log(data);
                toastr.options = {
                  "progressBar": false,
                  "positionClass": "toast-bottom-left",
                  "hideMethod": "fadeOut"
                }
                if(data.error == true) {
                  toastr.error(data.msg);
                } else {
                  $('#customerModal').modal('hide');
                  location.reload();
                  toastr.success(data.msg);
                }
            }
        });
     });
});

/**
 * Formart money
 * @param  float amount of money
 * @param  int length of last two digit
 * @return string
 */
function fmoney(amount, length) {
    return parseFloat(amount).toFixed(length).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}