$(document).ready(function() {

    $(".open-category").click(function() {

        $('#category-slider').toggle('slide', {

            direction: 'right'

        }, 700);

    });

    $(".open-subcategory").click(function() {

        $('#subcategory-slider').toggle('slide', {

            direction: 'right'

        }, 700);

    });



    $(document).on('click', function(e) {

        if (!$(e.target).is(".open-category, .cat-child") && !$(e.target).parents("#category-slider").size() && $('#category-slider').is(':visible')) {

            $('#category-slider').toggle('slide', {

                direction: 'right'

            }, 700);

        }

        if (!$(e.target).is(".open-subcategory, .cat-child") && !$(e.target).parents("#subcategory-slider").size() && $('#subcategory-slider').is(':visible')) {

            $('#subcategory-slider').toggle('slide', {

                direction: 'right'

            }, 700);

        }

    });

});



if (site.settings.auto_detect_barcode == 1) {

    $(document).ready(function() {

        var pressed = false;

        var chars = [];

        $(window).keypress(function(e) {

            if (e.key == '%') {

                pressed = true;

            }

            chars.push(String.fromCharCode(e.which));

            if (pressed == false) {

                setTimeout(function() {

                    if (chars.length >= 8) {

                        var barcode = chars.join("");

                        $("#add_item").focus().autocomplete("search", barcode);

                    }

                    chars = [];

                    pressed = false;

                }, 200);

            }

            pressed = true;

        });

    });

}







function getNumber(x) {

    return accounting.unformat(x);

}



function formatQuantity(x) {

    return (x != null) ? '<div class="text-center">' + formatNumber(x, site.settings.qty_decimals) + '</div>' : '';

}



function formatNumber(x, d) {

    if (!d && d != 0) {

        d = site.settings.decimals;

    }

    if (site.settings.sac == 1) {

        return formatSA(parseFloat(x).toFixed(d));

    }

    return accounting.formatNumber(x, d, site.settings.thousands_sep == 0 ? ' ' : site.settings.thousands_sep, site.settings.decimals_sep);

}



function formatMoney(x, symbol) {

    if (!symbol) {

        symbol = "";

    }

    if (site.settings.sac == 1) {

        return symbol + '' + formatSA(parseFloat(x).toFixed(site.settings.decimals));

    }

    return accounting.formatMoney(x, symbol, site.settings.decimals, site.settings.thousands_sep == 0 ? ' ' : site.settings.thousands_sep, site.settings.decimals_sep, "%s%v");

}



function formatDecimal(x) {

    return parseFloat(parseFloat(x).toFixed(site.settings.decimals));

}



function is_valid_discount(mixed_var) {

    return (is_numeric(mixed_var) || (/([0-9]%)/i.test(mixed_var))) ? true : false;

}



function is_numeric(mixed_var) {

    var whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";

    return (typeof mixed_var === 'number' || (typeof mixed_var === 'string' && whitespace.indexOf(mixed_var.slice(-1)) === -

        1)) && mixed_var !== '' && !isNaN(mixed_var);

}



function is_float(mixed_var) {

    return +mixed_var === mixed_var && (!isFinite(mixed_var) || !!(mixed_var % 1));

}



function currencyFormat(x) {

    if (x != null) {

        return formatMoney(x);

    } else {

        return '0';

    }

}



function formatSA(x) {

    x = x.toString();

    var afterPoint = '';

    if (x.indexOf('.') > 0)

        afterPoint = x.substring(x.indexOf('.'), x.length);

    x = Math.floor(x);

    x = x.toString();

    var lastThree = x.substring(x.length - 3);

    var otherNumbers = x.substring(0, x.length - 3);

    if (otherNumbers != '')

        lastThree = ',' + lastThree;

    var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;

    return res;

}





function add_invoice_item(item) {

    if (count == 1) {

        if ($('#poswarehouse').val() && $('#poscustomer').val()) {

            $('#poscustomer').select2("readonly", true);

            $('#poswarehouse').select2("readonly", true);

        } else {

            bootbox.alert(lang.select_above);

            item = null;

            return;

        }

    }

    if (item == null) {

        return;

    }



    loadItems(item);

}

if (typeof(Storage) === "undefined") {

    $(window).bind('beforeunload', function(e) {

        if (count > 1) {

            var message = "You will loss data!";

            return message;

        }

    });

}



function loadItems(item) {



    var row_no =  Math.floor((Math.random() * 1000) + 1);

    var tr_html;

    var newTr = $('<tr id="row_'+row_no+'" class="row_'+row_no+'" data-item-id="'+row_no+'"></tr>');

        tr_html  = ' <td><input type="hidden" value="'+item.row.product_id+'" class="rid" name="product_id[]"><input type="hidden" value="'+item.row.product_code+'" class="rcode" name="product_code[]"><input type="hidden" value="'+item.row.product_name+'" class="rname" name="product_name[]">'+item.label+'</span></td>';

        tr_html += '<td class="text-right"><input type="hidden" value="'+item.row.product_price+'" id="price_'+row_no+'" name="net_price[]" class="rprice"><span class="text-right sprice" id="sprice_'+row_no+'">'+formatMoney(item.row.product_price)+'</span></td>';

        tr_html += '<td><input type="text" role="textbox" aria-haspopup="true" class="form-control kb-pad text-center rquantity ui-keyboard-input ui-widget-content ui-corner-all" name="quantity[]" value="1" data-id="1451881153671" data-item="'+row_no+'" id="quantity_'+row_no+'" onclick="this.select();"></td>';

        tr_html += ' <td class="text-right"><input type="hidden" value="'+item.row.product_price+'" id="ssubtotal_'+row_no+'" name="ssubtotal[]"><span class="text-right ssubtotal" id="subtotal_'+row_no+'">'+formatMoney(item.row.product_price)+'</span></td>'; 

        tr_html += '<td class="text-center"><i class="fa fa-times tip pointer posdel" id="1451881153671" title="Remove" style="cursor:pointer;"></i></td>';

    newTr.html(tr_html);

    newTr.prependTo("#posTable");

    grand_total();



 }





$(document).on("change", '.rquantity', function() {



    if (!is_numeric($(this).val()) || $(this).val() == 0) {

        bootbox.alert(lang.unexpected_value);

        return false;

    }



    var new_qty       = $(this).val();

    var item_id       = $(this).attr('data-item');

    var product_price = remove_comma($('#sprice_'+item_id+'').text()); 



    $('#subtotal_'+item_id+'').text(formatMoney(parseFloat(product_price) * parseFloat(new_qty)));

    $('#ssubtotal_'+item_id+'').val(parseFloat(product_price) * parseFloat(new_qty));

    grand_total();

});





var itemQty=0;

function grand_total (argument) {

    var to = 0;

    var order_discount = 0;



    $( ".ssubtotal" ).each(function( index ) {

        to += remove_comma($( this ).text());

        itemQty = index+1;

    });



    var ds = $("span#tds").text();

    if (ds.indexOf("%") !== -1) {

        var pds = ds.split("%");

        if (!isNaN(pds[0])) {

            order_discount = formatDecimal((to * parseFloat(pds[0])) / 100);

        } else {

            order_discount = formatDecimal(ds);

        }

    } else {

        order_discount = formatDecimal(ds);

    }



    $("span#total").text(formatMoney(to));



    $("input#amount_val_1").val(to - order_discount);

    $("input#posdiscount").val(order_discount);

    $("span#titems").text(itemQty);

    $("span#gtotal").text(formatMoney(to - order_discount));

    $("#grand_total").val(to - order_discount);

    //alert(order_discount);

}





function remove_comma(value) {

    return parseFloat(value.replace(/,/g, ''))

}





function is_numeric(mixed_var) {

    var whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";

    return (typeof mixed_var === 'number' || (typeof mixed_var === 'string' && whitespace.indexOf(mixed_var.slice(-1)) === -

        1)) && mixed_var !== '' && !isNaN(mixed_var);

}



function formatDecimal(x) {

    return parseFloat(parseFloat(x).toFixed(site.settings.decimals));

}





function formatMoney(x, symbol) {

    if (!symbol) {

        symbol = "";

    }

    if (site.settings.sac == 1) {

        return symbol + '' + formatSA(parseFloat(x).toFixed(site.settings.decimals));

    }

    return accounting.formatMoney(x, symbol, site.settings.decimals, site.settings.thousands_sep == 0 ? ' ' : site.settings.thousands_sep, site.settings.decimals_sep, "%s%v");

}



$("#ppdiscount").click(function(e) {

    e.preventDefault();

    //var dval = $('#posdiscount').val() ? $('#posdiscount').val() : '0';

    //$('#order_discount_input').val(dval);

    $('#dsModal').modal();

});





$('#dsModal').on('shown.bs.modal', function() {

    $(this).find('#order_discount_input').select().focus();

    $('input#order_discount_input').bind('keypress', function(e) {

        if (e.keyCode == 13) {

            e.preventDefault();

            var ds = $('#order_discount_input').val();

            if (is_valid_discount(ds)) {



            } else {

                bootbox.alert(lang.unexpected_value);

            }

            $('#dsModal').modal('hide');

        }

    });

});



$(document).on('click', '#updateOrderDiscount', function() {

    var ds = $('#order_discount_input').val() ? $('#order_discount_input').val() : '0';

    if (is_valid_discount(ds)) {

        $('#tds').text(ds);

        $('#posdiscount').val(ds);

        $('#pos_discount_input1').val(ds);

    } else {

        bootbox.alert(lang.unexpected_value);

    }

    $('#dsModal').modal('hide');

    grand_total();

});





// payment model section 



$("#payment").click(function(e) {

    if (itemQty>0) {

    $("span#twt").text($("span#gtotal").text());

    $("span#item_count").text($("span#titems").text());

    $('#paymentModal').modal();



    } else{

        bootbox.alert("Please add product before payment. Thank you!");

    };

});



$('#paymentModal').on('shown.bs.modal', function() {

    $("input.amount").focus();

});





$(document).on('change', '.paid_by', function () {

    var p_val = $(this).val(),

        id = $(this).attr('id'),

        pa_no = id.substr(id.length - 1);

    $('#rpaidby').val(p_val);

    if (p_val == 'cash' || p_val == 'other') {

        $('.pcheque_' + pa_no).hide();

        $('.pcc_' + pa_no).hide();

        $('.pcash_' + pa_no).show();

        $('#payment_note_' + pa_no).focus();

        $('#paid_by_val_1').val(p_val);



    } else if (p_val == 'CC' || p_val == 'stripe' || p_val == 'ppp') {

        $('.pcheque_' + pa_no).hide();

        $('.pcash_' + pa_no).hide();

        $('.pcc_' + pa_no).show();

        $('#swipe_' + pa_no).focus();

        $('#paid_by_val_1').val(p_val);

    } else if (p_val == 'Cheque') {

        $('.pcc_' + pa_no).hide();

        $('.pcash_' + pa_no).hide();

        $('.pcheque_' + pa_no).show();

        $('#cheque_no_' + pa_no).focus();

    } else {

        $('.pcheque_' + pa_no).hide();

        $('.pcc_' + pa_no).hide();

        $('.pcash_' + pa_no).hide();

    }

    if (p_val == 'gift_card') {

        $('.gc_' + pa_no).show();

        $('.ngc_' + pa_no).hide();

        $('#gift_card_no_' + pa_no).focus();

    } else {

        $('.ngc_' + pa_no).show();

        $('.gc_' + pa_no).hide();

        $('#gc_details_' + pa_no).html('');

    }

});



var pi = 'amount_1', pa = 2;

$(document).on('click', '.quick-cash', function () {

    var $quick_cash = $(this);

    var amt = $quick_cash.contents().filter(function () {

        return this.nodeType == 3;

    }).text();

    var th = ',';

    var $pi = $('#' + pi);

    amt = formatDecimal(amt.split(th).join("")) * 1 + $pi.val() * 1;

    $pi.val(formatDecimal(amt)).focus();

    var note_count = $quick_cash.find('span');

    if (note_count.length == 0) {

        $quick_cash.append('<span class="badge">1</span>');

    } else {

        note_count.text(parseInt(note_count.text()) + 1);

    }

});



$(document).on('click', '#clear-cash-notes', function () {

    $('.quick-cash').find('.badge').remove();

    $('#' + pi).val('0').focus();

});



$(document).on('focus', '.amount', function () {

    pi = $(this).attr('id');

    calculateTotals();

}).on('blur', '.amount', function () {

    calculateTotals();

});



function calculateTotals() {

    var total_paying = 0;

    var gtotal = remove_comma($("span#twt").text());

    var ia = $(".amount");

    $.each(ia, function (i) {

        total_paying += parseFloat($(this).val() ? $(this).val() : 0);

    });

    $('#total_paying').text(formatMoney(total_paying));

    $('#balance').text(formatMoney(total_paying - gtotal));

    $('#balance_' + pi).val(formatDecimal(total_paying - gtotal));

    total_paid = total_paying;

    grand_total = gtotal;

}



$(document).on('click', '#reset', function () {

    bootbox.confirm("Are you sure?", function (res) {

        if (res == true) {

            $("#posTable tbody").empty();

        }

    });

    return false;

});



//*********************************************





$('#paymentModal').on('change', '#amount_1', function (e) {

    $('#pay_amount').val($(this).val());

});



$('#paymentModal').on('blur', '#amount_1', function (e) {

    $('#pay_amount').val($(this).val());

});



$('#paymentModal').on('change', '#payment_note_1', function(e) {

    $('#pos_note').val($(this).val());

});



//$('#paymentModal').on('select2-close', '#paid_by_1', function (e) {

//    $('#paid_by_val_1').val($(this).val());

//});



$('#paymentModal').on('change', '#swipe_1', function (e) {

    $('#cc_name').val($(this).val());

});



$('#paymentModal').on('change', '.pcc_type', function (e) {

    $('#pcc_type').val($(this).val());

});



$('#paymentModal').on('change', '#pcc_holder_1', function (e) {

    $('#pcc_holder').val($(this).val());

});

$('#paymentModal').on('change', '#pcc_no_1', function (e) {

    $('#cc_no').val($(this).val());

});

