var positems = {};
var site = {
		base_url: "http://localhost/inventry_pos/",
		settings: {
			logo: "logo2.png",
			logo2: "logo3.png",
			site_name: "Stock Manager Advance",
			language: "english",
			default_warehouse: "1",
			accounting_method: "0",
			default_currency: "USD",
			default_tax_rate: "1",
			rows_per_page: "10",
			version: "3.0.1.20",
			default_tax_rate2: "1",
			dateformat: "5",
			sales_prefix: "SALE",
			quote_prefix: "QUOTE",
			purchase_prefix: "PO",
			transfer_prefix: "TR",
			delivery_prefix: "DO",
			payment_prefix: "IPAY",
			return_prefix: "RETURNSL",
			expense_prefix: null,
			item_addition: "0",
			theme: "default",
			product_serial: "1",
			default_discount: "1",
			product_discount: "1",
			discount_method: "1",
			tax1: "1",
			tax2: "1",
			overselling: "0",
			iwidth: "800",
			iheight: "800",
			twidth: "60",
			theight: "60",
			watermark: "0",
			smtp_host: "pop.gmail.com",
			bc_fix: "4",
			auto_detect_barcode: "1",
			captcha: "0",
			reference_format: "2",
			racks: "1",
			attributes: "1",
			product_expiry: "0",
			decimals: "2",
			decimals_sep: ".",
			thousands_sep: ",",
			invoice_view: "0",
			default_biller: null,
			rtl: "0",
			each_spent: null,
			ca_point: null,
			each_sale: null,
			sa_point: null,
			sac: "0",
			qty_decimals: "2",
			display_all_products: "0",
			printable: false
		},
		dateFormats: {
			js_sdate: "dd/mm/yyyy",
			php_sdate: "d/m/Y",
			mysq_sdate: "%d/%m/%Y",
			js_ldate: "dd/mm/yyyy hh:ii",
			php_ldate: "d/m/Y H:i",
			mysql_ldate: "%d/%m/%Y %H:%i"
		},
		product: ""
	},
	pos_settings = {
		pos_id: "1",
		cat_limit: "22",
		pro_limit: "20",
		default_category: "1",
		default_customer: "1",
		default_biller: "3",
		display_time: "1",
		cf_title1: "GST Reg",
		cf_title2: "VAT Reg",
		cf_value1: "123456789",
		cf_value2: "987654321",
		receipt_printer: "BIXOLON SRP-350II",
		cash_drawer_codes: "x1C",
		focus_add_item: "Ctrl+F3",
		add_manual_product: "Ctrl+Shift+M",
		customer_selection: "Ctrl+Shift+C",
		add_customer: "Ctrl+Shift+A",
		toggle_category_slider: "Ctrl+F11",
		toggle_subcategory_slider: "Ctrl+F12",
		cancel_sale: "F4",
		suspend_sale: "F7",
		print_items_list: "F9",
		finalize_sale: "F8",
		today_sale: "Ctrl+F1",
		open_hold_bills: "Ctrl+F2",
		close_register: "Ctrl+F10",
		keyboard: "1",
		pos_printers: "BIXOLON SRP-350II, BIXOLON SRP-350II",
		java_applet: "0",
		product_button_color: "default",
		tooltips: "1",
		paypal_pro: "0",
		stripe: "0",
		rounding: "0",
		char_per_line: "42",
		pin_code: null,
		extra_charges: 0
	};
var lang = {
	unexpected_value: "Unexpected value provided!",
	select_above: "Please select above first",
	r_u_sure: "Are you sure?"
};
var count = $("#count").val();
var rowCount = $("#posTable > tbody > tr").length;
setInterval(function() {
	$(".alert").hide("blind", {}, 500)
}, 15000);
setInterval(function() {
	if (typeof moment !== "undefined") {
		var a = new moment();
		$("#display_time").text(a.format((site.dateFormats.js_sdate).toUpperCase() + " HH:mm"));
		$("#sale_datetime").val(a.format(("Y-MM-D HH:mm:ss")))
	}
}, 1000);
$(document).ready(function() {
//	$(".auto").autoNumeric("init");
	$(".pos-tip").tooltip();
	/*$("#poswarehouse").select2({
		allowClear: true,
		minimumResultsForSearch: Infinity
	});*/
	$("#poscustomer").select2({
		allowClear: true
	}).change(function() {
		/*var data = $("#poscustomer").select2('data');*/
		//$('.bill_customer').text('Customer:' + (($("#poscustomer").select2('data')).text).split('-')[0].replace('-', ''));
		
		//if($("#poscustomer").select2('data')).text==)
		
	//	alert($("#poscustomer").select2('data'));
		
		
		$('.bill_customer').text('Customer:' + $("#poscustomer").select2('data').text);
	});
	$("#category").select2({
		allowClear: true
	});/*
	$('input[type="checkbox"].red, input[type="radio"].red').iCheck({
		checkboxClass: "icheckbox_minimal-red",
		radioClass: "iradio_minimal-red",
	});
	$('input[type="checkbox"].green, input[type="radio"].green').iCheck({
		checkboxClass: "icheckbox_minimal-green",
		radioClass: "iradio_minimal-green",
	});
	$('input[type="checkbox"].orange, input[type="radio"].orange').iCheck({

		checkboxClass: "icheckbox_minimal-orange",
		radioClass: "iradio_minimal-orange",
	});
	$('input[type="checkbox"].divi_1, input[type="radio"].divi_1').iCheck({
		checkboxClass: "icheckbox_minimal-orange",
		radioClass: "iradio_minimal-orange",
	});
	$('input[type="checkbox"].divi_2, input[type="radio"].divi_2').iCheck({
		checkboxClass: "icheckbox_minimal-orange",
		radioClass: "iradio_minimal-orange",
	});*/
	$("#table_id").select2({
		allowClear: true,
		minimumResultsForSearch: Infinity
	});
	//$(".bill_customer").text('Customer:' + (($("#poscustomer").select2('data')).text).split('-')[0].replace('-', ''));
	if($("#poscustomer").select2('data'))
	$(".bill_customer").text('Customer:' + (($("#poscustomer").select2('data')).text));
	
	//	alert($("#poscustomer").select2('data'));
	
	$("#add_item").focus();
	$("#modal-loading").hide();
	localStorage.clear();
	localStorage.setItem("reload", 1);
	$(window).resize();
	widthFunctions();
	/*$("#product-list").css("min-height", 90);*/
}).ajaxStart(function() {
	$("#modal-loading").show();
	$("#modal-loading").css("z-index", "9999");
}).ajaxStop(function() {
	$("#modal-loading").hide();
}).on("change", ".rquantity", function() {
	var b = $(this).closest("tr");
	if (!is_numeric($(this).val()) || parseFloat($(this).val()) == 0) {
		$(this).val(1);
		grand_total_cal();
		/*bootbox.alert(lang.unexpected_value);*/
		return
	} else {
		/*console.log('change');*/
		grand_total_cal();
	}
}).on("keypress", ".rquantity", function(b) {
	if (b.key == "Escape") {
		if ((b.target.id).indexOf("quantity") != -1) {
			var c = $(this).closest("tr");
			c.remove();
			$("#add_item").focus()
		}
	}
	if (b.key == "Enter") {
		$("#add_item").focus()
	} else {
		/*console.log('keypress');*/
		grand_total_cal();
	}
}).on("keypress", "#add_item", function(b) {
	if (b.key == "Enter") {
		$("#cash_en").focus()
	} else {
		/*console.log('keypress');*/
		grand_total_cal();
	}
}).on("keydown", "#cash_en", function(b) {
    console.log(b);
	if (b.key == "Enter") {
		$("#save").click()
	}else
	if (b.key == "Escape") {
	    b.preventDefault();
			$("#add_item").focus()
	}
	
}).on("keyup", ".rquantity", function() {
    grand_total_cal();
	/*if (!is_numeric($(this).val()) || $(this).val() < 0) {
		bootbox.alert(lang.unexpected_value);
		 $(this).val(1).focus().select();
		 return false;
		grand_total_cal();
	} else {*/
		/*console.log('keyup');
		grand_total_cal();
	}*/
}).on("change",".rdiscount", function() {
		grand_total_cal();
}).on("keyup", ".rdiscount", function() {
		grand_total_cal();
}).on("click", "#reset", function() {
	bootbox.confirm({
		size: "small",
		message: "Are you sure?",
		callback: function(a) {
			if (a == true) {
				$("#posTable tbody").empty();
				grand_total_cal(0);
				$("input#posdiscount").val(0);
				$("#tds").text(0);
				$("input#posshipping").val(0);
				$("#tship").text(0);
				localStorage.clear();
				form_clear();
				form_locate();
			}
		}
	});
	return false
}).bind("keyup", function(d) {
	if (d.target.classList[0] == "select2-input") {
		var b = d.target.value;
		if (!isNaN(b)) {
			$("#customer_mobile").val(d.target.value)
		}
	}
	if (d.key == "Enter") {
		if (d.target.classList[0] == "select2-input") {
			if ($(".select2-results > li").hasClass("select2-no-results")) {
				$("#modal_ajax_customers_btn").click();
				$("#select2-drop").slideUp("fast")
			}
		}
		var c = d.target.id;
		if (c.indexOf("c_pay_amount_") != -1) {
			set_as_paid(d.target.attributes["sale-id"].value)
		}
		if (d.target.id == "amount_1") {
			$("#pay_amount").val(remove_comma($("#amount_1").val()));
			$("#submit-sale").click()
		}
		if (d.target.id == "swipe_1") {
			if (d.target.value) {
				$("#pcc_no_1").focus()
			}
		}
		if (d.target.id == "pcc_no_1") {
			if (d.target.value) {
				$("#pay_amount").val(remove_comma($("#amount_1").val()))
			}
			$("#submit-sale").click()
		}
		if (d.target.id == "pcc_holder_1") {
			if (d.target.value) {
				$("#pay_amount").val(remove_comma($("#amount_1").val()))
			}
			$("#submit-sale").click()
		}
	}
}).keypress(function(event) {
	if (String.fromCharCode(event.which) == "'") {
		event.preventDefault();
		bootbox.alert("Character you typed is not allowed !!");
	}
});

$("#add_item").autocomplete({
	//source: base_url + 'pos/suggetions?t='+pos_price_type,
	source: function(request, response)
    {
        $.ajax({
            url: base_url+'pos/suggetions?t='+$('input[name="invoice_type"]:checked').val()+'&term='+$('#add_item').val(),
            dataType: "json",
            success: response
        });
    },
	minLength: 3,
	autoFocus: false,
	delay: 200,
	response: function(b, c) {
	    //console.log(c);console.log(b);
	    //console.log("---- 322 ----");
		/*console.log($(this).val().length);*/
		if ($(this).val().length >= 160 && c.content[0].id == 0) {
		    console.log("---- 325 ----");
			$(this).val("");
			$("#add_item").val("").removeClass("ui-autocomplete-loading")
		} else {
		    //console.log("---- 329 ----");
			if (c.content.length == 1 && c.content[0].id != 0) {
			    //console.log("---- c start ----");
				//  console.log(c);
			//	console.log("---- c end ----");
				add_invoice_item(c.content[0]);
				$(this).val("");
				//$(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', c);
			} else {
				if (c.content.length == 1 && c.content[0].id == 0) {
				    //console.log("---- 342 ----");
					$(this).val("");
					$("#add_item").val("").removeClass("ui-autocomplete-loading")
				}
			}
		}
	},
	select: function(b, c) {
	    console.log(c);
	    //console.log("---- 349 ----");
		b.preventDefault();
		if (c.item.id !== 0) {
			var d = add_invoice_item(c.item);
			if (d) {
				$(this).val("")
			}
			$("#add_item").val("").removeClass("ui-autocomplete-loading")
		} else {
			bootbox.alert("No matching result found! Product might be out of stock in the selected warehouse.")
		}
	}
});

$("#add_item").bind("keypress", function(b) {
	if (b.keyCode == 13) {
		b.preventDefault();
		var result = 1;
		$(this).autocomplete("search")
	}
});
$("input[type=text] select").focus(function() {
	if (this.id != "") {
		$("#id-name").val(this.id)
	}
});
$("#modal_ajax_customers_btn").click(function(b) {
	b.preventDefault();
	var a = $("#ajax-modal").modal();
	a.load(base_url + "customers/create_customers", "", function() {
		a.modal();
		setTimeout(function() {
			var c = $("#customer_mobile").val();
			$("#cus_phone").val(c);
			$("#nc").val(2);
			$("#cus_name").focus()
		}, 500)
	})
});
$(window).bind("resize", widthFunctions);

function widthFunctions(d) {
	var b = $(window).height(),
		c = $("#left-top").height(),
		a = $("#left-bottom").height();
	$("#item-list").css("height", b - 450);
	$("#item-list").css("min-height", 200);
	$("#left-middle").css("height", b - c - a - 102);
	$("#left-middle").css("min-height", 200);
	$("#product-list").css("height", b - c - a - 109);
	$("#product-list").css("min-height", 200);
	$(".select2-container").css("width", "100%");
	//$('#cal_container').css('top',$(window).height()-50);
	$("#myTab2").css("height",(parseInt($("#leftdiv").css("height"))-10)+"px");
	
	
}
var product_variant = 0,
	shipping = 0,
	p_page = 0,
	per_page = 0,
	tcp = "8",
	cat_id = "8",
	ocat_id = "1",
	sub_cat_id = 0,
	osub_cat_id
/*,
    DT = 1*/
;
var base_url = $("#base_url").val();
$(document).on("click", ".category", function() {
		if (cat_id != $(this).val()) {
			$("#modal-loading").show("fast");
			$("#open-category").click();
			cat_id = $(this).val();
			$.ajax({
				type: "get",
				url: base_url + "bar/ajaxcategorydata",
				data: {
					category_id: cat_id
				},
				dataType: "json",
				success: function(c) {
					$("#item-list").empty();
					var d = $('<div id="makeMeScrollable"></div>');
					d.html(c.products);
					d.appendTo("#item-list");
					$("#subcategory-list").empty();
					var b = $("<div></div>");
					b.html(c.subcategories);
					b.appendTo("#subcategory-list");
					tcp = c.tcp;
					/*scrollMe()*/
				}
			}).done(function() {
				p_page = "n";
				$("#category-" + cat_id).addClass("active");
				if (cat_id != ocat_id) {
					$("#category-" + ocat_id).removeAttr("style");
					$("#category-" + ocat_id).removeClass("active")
				}
				$(".active").css("background-color", "#999");
				ocat_id = cat_id;
				$("#modal-loading").hide();
				$(".pos-tip").tooltip()
			})
		}
	}).on("click", ".subcategory", function() {
		$("#modal-loading").show();
		if (sub_cat_id != $(this).val()) {
			$("#open-subcategory").click();
			sub_cat_id = $(this).val();
			$.ajax({
				type: "get",
				url: base_url + "pos/ajaxproducts",
				data: {
					category_id: cat_id,
					subcategory_id: sub_cat_id,
					per_page: p_page
				},
				dataType: "html",
				success: function(a) {
					$("#item-list").empty();
					var b = $('<div id="makeMeScrollable"></div>');
					b.html(a);
					b.appendTo("#item-list");
					/*scrollMe()*/
				}
			}).done(function() {
				p_page = "n";
				$("#subcategory-" + sub_cat_id).addClass("active");
				$("#subcategory-" + osub_cat_id).removeClass("active");
				osub_cat_id = sub_cat_id;
				$("#modal-loading").hide();
				$(".pos-tip").tooltip()
			})
		}
	}).on("click", ".product", function(a) {
		/*console.log(this);*/
		$("#modal-loading").show();
		/*product_id_sub = $(this).attr('product_id_sub');
		product_id = $(this).attr('product_id');*/
		product_code = $(this).attr('product_code');
		/*product_name = $(this).attr('product_name');
		product_price = $(this).attr('product_price');
		product_qty = $(this).attr('product_qty');
		product_cost	=	$(this).attr('product_cost');
		
		retail_credit	=	$(this).attr('retail_credit');
		retail_wholesale	=	$(this).attr('retail_wholesale');
		
		label = $(this).attr('label');
		value = $(this).attr('title');
		wh = $("#poswarehouse").val(), cu = $("#poscustomer").val();
		var product = {
			"product_id": product_id,
			"product_id_sub": product_id_sub,
			"qty": product_qty,
			"product_code": product_code,
			"product_name": product_name,
			"product_price": product_price,
			"product_cost":product_cost,
			"retail_credit":retail_credit,
			"retail_wholesale":retail_wholesale,
			"label": label,
			"value": value
		};*/
		/*console.log(product);*/
		
	//	$("#add_item").autocomplete('search', product_code);
		
		//add_invoice_item(product);
		
		
		//$("#modal-loading").hide()
		/**/
		$.ajax({
		    type: "get",
		    url: base_url + 'pos/suggetions',
		    data: {
		        term: product_code,
		        t: 1
		    },
		    dataType: "json",
		    success: function(b) {
		        a.preventDefault();
		        if (b !== null) {
		            //console.log(b);
		            
		            add_invoice_item(b[0]);
		            $("#modal-loading").hide()
		        } else {
		            bootbox.alert("No matching result found! Product might be out of stock in the selected warehouse.");
		            $("#modal-loading").hide()
		        }
		    }
		});
	}).on("click", ".posdel", function(b) {
		var c = $(this).closest("tr");
		c.remove();
		grand_total_cal();
	}).on("click", "#submit-sale", function() {
		$("#pay_amount").val(remove_comma($('#amount_1').val()))
		console.log('submit sale clicked...');
		var paid_by = $('#paid_by_1').val();
		if (paid_by == 'CC')
			if (!$('#swipe_1').val() || !$('#pcc_no_1').val() || !$('#pcc_holder_1').val()) bootbox.alert('Card detail fields are required !');
			else {
				site.settings.printable = true;
				$("#submit-sale").attr("disabled", true);
				$('#paymentModal').modal('hide');
				form_submit();
			}
		else {
			site.settings.printable = true;
			$("#submit-sale").attr("disabled", true);
			$('#paymentModal').modal('hide');
			form_submit();
		}
	}).on("click", "#save", function() {
		if ($("#posTable >tbody > tr").length > 0) {
			var a = $('.pt_list input[type="radio"]:checked:first').val();
			var shipping_address = $("#shipping_address").val();
			var shipping_charges = $("#posshipping").val();
			if (a != "retail_credit") {
				var cash_val = $('#cash_en').val();
			    if (cash_val <= 0 || cash_val == "") {
					bootbox.alert("Enter Paying Amount!");
					$('#cash_en').focus();
				}else {
					var result = 1;
    				site.settings.printable = true;
    				$("#submit-sale").attr("disabled", true);
    				form_submit();
    				$("#add_item").focus();
				}
			} else {
				var result = 1;
				site.settings.printable = true;
				$("#submit-sale").attr("disabled", true);
				form_submit();
				$("#add_item").focus();
			}
		} else {
			bootbox.alert("Please add product before payment. Thank you !! ",function(){
			    setTimeout(function(){
			        $("#add_item").focus();
			    },100);
			});
		}
	})
	.on("click", function(b) {
		if (!$(b.target).is(".open-category, .cat-child") && !$(b.target).parents("#category-slider").size() && $("#category-slider").is(":visible")) {
			$("#category-slider").toggle("slide", {
				direction: "right"
			}, 200)
		}
		if (!$(b.target).is(".open-subcategory, .cat-child") && !$(b.target).parents("#subcategory-slider").size() && $("#subcategory-slider").is(":visible")) {
			$("#subcategory-slider").toggle("slide", {
				direction: "right"
			}, 200)
		}
		if (!$(b.target).is(".open-keyboard")) {
			var a = document.activeElement;
			if (a.id != "") {
				$("#id-name").val(a.id)
			}
		}
	});
function add_invoice_item(c) {
    $("#qty_en_tot").val('');
	$("#dis_en_tot").val('');
	rowCount++;
	if (rowCount == 1) {
		if (! $("#poswarehouse").val() && $("#poscustomer").val()) {
	        bootbox.alert(lang.select_above);
			c = null;
			return false;
		} 
	}
	if (c == null) {
		return false;
	}
	if(c.bc==0){
	   bootbox.alert("not in stock");
	   return false;
	}
	if(c.bc > 1){
	    site.product = c;
	    select_product(c);
	}else{
	    $("#count").val(++count);
	    c.product_price = c.bdata[0]["product_price"];
	    c.bid = c.bdata[0]["batch_id"];
	    c.product_cost = c.bdata[0]["product_cost"];
	    c.batch_qty = c.bdata[0]["batch_qty"];
	    loadItems(c);
	}
	/*
	var b = "";
	if (rowCount) {
		b = isAddedProduct(c.product_id, c.product_id_sub, c.product_qty)
	}
	if (!b) {
		$("#count").val(++count);
		if (typeof c[0] !== "undefined") {
			loadItemsDef(c)
		} else {
			loadItems(c);
		}
	}
	*/
}

function select_product(c) {
    console.log("========= 645 =========");
    var bc = c.bc;
    var batch = "";
    
    if(bc > 1){
        var bdata = c.bdata;
        var checked = "checked";
        for(var i = 0;i < bdata.length; i++){
            //console.log(bdata[i]);
            batch += '<div class="form-check"><input '+checked+' class="form-check-input" type="radio" name="batch_price" id="bp_'+(i+1)+'" value="'+bdata[i]["batch_id"]+'"> <label class="form-check-label" for="bp_'+(i+1)+'">  <h1>'+bdata[i]["product_price"]+' <small>'+bdata[i]["batch_ref_number"]+': </small> <small> Stock '+bdata[i]["batch_qty"]+'</small> </h2></label></div>';
            checked = "";
        }
        
        $("#select_price_form").html(batch);
        $('.hover_bkgr_fricc').show();
        $("#bp_1").focus();
        site.product  = c;
        
        
        // $("#batch_model").on("hidden.bs.modal",function(){
        //     console.log("============ 676");
        //     var bid = $("#selected_batch").val();
        //     for(var i = 0;i < bdata.length; i++){
        //         if(bdata[i]["batch_id"] == bid){
        //             c.product_price = bdata[i]["product_price"];
        //             c.bid = bdata[i]["batch_id"];
        //             loadItems(c);
        //             break;
        //         }
        //     }
        //     $(this).data('bs.modal', null);
        // });
        
    }
}

$("#select_price_form").on("keypress", function(e){
    e.preventDefault();
    //console.log(e);
    var c = site.product;
    var bdata = c.bdata;
    if(e.key == "Enter"){
        //$("#selected_batch").val($(e.target).val());
        var bid = $(e.target).val();//$("#selected_batch").val();
        for(var i = 0;i < bdata.length; i++){
            if(bdata[i]["batch_id"] == bid){
                c.product_price = bdata[i]["product_price"];
                c.product_cost = bdata[i]["product_cost"];
                c.bid = bdata[i]["batch_id"];
                c.batch_qty = bdata[i]["batch_qty"];
                $(".hover_bkgr_fricc").hide();
                $("#count").val(++count);
                loadItems(c);
                break;
            }
        }
    }else if(e.key == "Escape"){
        $(".hover_bkgr_fricc").hide();
    }
});
$(".popupCloseButton").on("click",function(){
    $(".hover_bkgr_fricc").hide();
});
// $(".hover_bkgr_fricc").on("click",function(){
//     $(".hover_bkgr_fricc").hide();
// });



function isAddedProduct(pc, ps, qty) {
	for (c = 1; c <= $('#count').val(); c++) {		
		var a = $("#row_" + c).attr("data-item-id");
		if (a == pc)		
			if ($("#row_" + c).attr("product_id") == ps && a == pc) {
				var current_val = parseFloat($("#quantity_" + c).val());
				var new_qty = formatDecimal(current_val + parseFloat(qty));
				new_qty=1;
				$("#quantity_" + c).val(new_qty).focus().select();
				grand_total_cal();
				return 1;
			}
	}
}

function loadItems(e) {
    var qty_read_only="";
	var prod_price = e.product_price;
	var price_type = $("input[name='price_type']:checked").val();
	if(!price_type){alert("please select price type");return false;}

	var c = $("#count").val();
	var f;
	var btn_id = e.product_id;
	var qty = e.product_qty;
	

	
	if (qty == "") qty = 1;

    if(e.qty!=1){
        qty_read_only="readonly";
    }else{
        qty_read_only="";
    }
	
	var discount=e.discount; 
	var ch1,ch2,ch3;
	var alrady_added_batch_qty=getAddedBatchQty(e.bid);
	var expected_enter_qty=alrady_added_batch_qty+e.qty;
	if(e.batch_qty<expected_enter_qty){
	    bootbox.alert("<center>Out of stock <hr>You already added "+alrady_added_batch_qty+" number of qty. <br><br> Maximul limit in this batch is "+e.batch_qty+"</center>", function(){ 
                    console.log('This was logged in the callback!'); 
                    bootbox.hideAll();
                });
                
                return false;
	}
	if(e.wh == 4)ch1 = "checked";
	else if(e.wh == 5)ch2 = "checked";
	else if(e.wh == 6)ch3 = "checked";
	
	/*if(e)*/
	var a = $('<tr id="row_' + c + '" class="row_' + c + '" data-item-id="' + btn_id + '" product_id_sub = ' + e.product_id_sub + '></tr>');
	f =  '<td class="collapse"><label class="checkbox_for" for="dell' + c + '" ><input id="dell' + c + '" type="checkbox" '+ch1+' name="deliveryList[]" value="' + btn_id + '" row_id="' + c + '" pd_name="' + e.product_name + '" pd_qty="' + c+ '" ></label></td>';
	f += '<td class="collapse"><label class="checkbox_for" for="dell2' + c + '" ><input id="dell2' + c + '" type="checkbox" '+ch2+' name="deliveryList2[]" value="' + btn_id + '" row_id="' + c + '" pd_name="' + e.product_name + '" pd_qty="' + c+ '" ></label></td>';
	f += '<td class="collapse"><label class="checkbox_for" for="dell3' + c + '" ><input id="dell3' + c + '" type="checkbox" '+ch3+' name="deliveryList3[]" value="' + btn_id + '" row_id="' + c + '" pd_name="' + e.product_name + '" pd_qty="' + c+ '" ></label></td>';
	f += '<td><input type="hidden" value="' + btn_id + '" class="rid" name="product_id[]" id="product_id_' + btn_id + '" row_id="' + c + '"><input id="p_batch_id_' + c + '" type="hidden" value="' + e.bid + '" class="rcode" name="bid[]"><input readonly type="text" value="' + e.product_name + '" placeholder="' + e.product_code + '" class="rname table-row-input" name="product_name[]" onClick="this.select()"></td>';
	f += '<td class="text-right"><input ondblclick="enable_(this)" onclick="this.select" onblur="disable_(this)" class="table-row-input text-center  rprice" style="width: 50px" type="text" type="text" value="' + prod_price + '" id="sprice_' + c + '" name="net_price[]" onClick="this.select()" readonly> <input type="hidden" id="cost_' + c + '" name="cost[]"  value="' + e.product_cost + '"></input></td>"'; /* ondblclick="enable_(this)" onclick="this.select" onblur="disable_(this)" readonly*/
	f += '<td><input maxlength="8" type="number" role="textbox" tabIndex="' + c + '" aria-haspopup="true" class="form-control text-center rquantity '+e.bid+' " name="quantity[]" value="' + e.qty + '" data-item="' + c + '" id="quantity_' + c + '" onclick="this.select()" '+qty_read_only+' autocomplete="off">' + '<input type="hidden" value="' + e.product_id_sub + '" name="shot_type[]">' + '<span class="collapse" id="maxq_'+c+'"></span> <input type="hidden" value="' + e.batch_qty + '" name="batch_qty[]" id="batch_qty_' + c + '"> </td>';
	f += '<td><input type="text" role="textbox" tabIndex="' + c + '" aria-haspopup="true" class="form-control text-center rdiscount " name="discount_i[]" value="'+discount+'"  id="discount_' + c + '" readonly>' + '<input type="hidden" name="discount_val[]" value="'+""+'"  id="discount_val' + c + '">' + '</td>';
	
	f += '<td class="text-right"><input type="hidden" value="' + prod_price + '" id="ssubtotal_' + c + '" name="ssubtotal[]"><span class="text-right ssubtotal" id="subtotal_' + c + '">' + formatMoney(prod_price) + "</span></td>";
	f += '<td style="background-color:orange" class="text-center posdel" onClick="delRow(' + c + ')" ><i class="fa fa-times tip pointer " id="1451881153671" title="Remove" style="cursor:pointer;"></i></td>';
	a.html(f);
	a.prependTo("#posTable");
	create_bill(c, e.product_name, e.product_price);
	grand_total_cal();
	$("#quantity_" + c).focus().select();
}

function create_bill(c, product_name, product_price) {
	/*------------------ADD TO BILL-TABLE			----------------*/
	a = $('<tr class="text-right bill_content	bill_tr_id' + c + '"></tr>');
	f = '<td class="text-center"></td>';
	f += '<td style="text-align:left"></td>';
	f += '<td class="text-center	bill_td_qty_' + c + '">1</td>';
	f += '<td class="text-right 	bill_td_price_' + c + '" id="">' + product_price + '</td>';
	f += '<td class="text-right 	bill_td_discount_' + c + '" id="">0</td>';
	f += '<td class="text-right		bill_td_amount_' + c + '">' + product_price + '</td>';
	a.html(f);
	a.prependTo("#bill_table");
	
	a = $('<tr class="text-right bill_content	bill_tr_id' + c + '"></tr>');
	f = '<td class="text-center">*</td>';
	f += '<td style="text-align:left" colspan="5">' + product_name + '</td>';
//	f += '<td class="text-center	bill_td_qty_' + c + '">1</td>';
//	f += '<td class="text-right 	bill_td_price_' + c + '" id="">' + product_price + '</td>';
//	f += '<td class="text-right 	bill_td_discount_' + c + '" id="">0</td>';
//	f += '<td class="text-right		bill_td_amount_' + c + '">' + product_price + '</td>';
	a.html(f);
	a.prependTo("#bill_table");
	
	a = $('<tr class="text-right 	bill_tr_id' + c + '"></tr>');
	f = '<td class="text-center">*</td>';
	f += '<td style="text-align:left">' + product_name + '</td>';
	f += '<td class="text-center	bill_td_qty_' + c + '">1</td>';
	a.html(f);
	a.prependTo("#kot_table");
	a.prependTo("#kot_table_print");
	/*---------------- END	--------------*/
}
function add_to_deli_list(c, product_name, product_qty) {
	
	a = $('<tr class="text-right"></tr>');
	f = '<td class="text-center">*</td>';
	f += '<td style="text-align:left">' + product_name + '</td>';
	f += '<td class="text-center">' + product_qty + '</td>';
	f += '<td class="text-center"><i class="fa fa-square-o"></i></td>';
	a.html(f);
	a.appendTo("#del_list");
}
function add_to_deli_list2(c, product_name, product_qty) {
	
	a = $('<tr class="text-right"></tr>');
	f = '<td class="text-center">*</td>';
	f += '<td style="text-align:left">' + product_name + '</td>';
	f += '<td class="text-center">' + product_qty + '</td>';
	f += '<td class="text-center"><i class="fa fa-square-o"></i></td>';
	a.html(f);
	a.appendTo("#del_list2");
}
function add_to_deli_list3(c, product_name, product_qty) {
	
	a = $('<tr class="text-right"></tr>');
	f = '<td class="text-center">*</td>';
	f += '<td style="text-align:left">' + product_name + '</td>';
	f += '<td class="text-center">' + product_qty + '</td>';
	f += '<td class="text-center"><i class="fa fa-square-o"></i></td>';
	a.html(f);
	a.appendTo("#del_list3");
}
function enable_(element) {
	$(element).removeAttr('readonly');
}

function disable_(element) {
	$(element).attr('readonly', true);
}

function delRow(a) {
	$(".bill_tr_id" + a).remove();
	delete positems[a];
	localStorage.setItem("positems", JSON.stringify(positems))
}
var itemQty = 0;



$("#cash_cus_name").on("change",function() {
    var cash_cus_name=$("#cash_cus_name").val();
	if(cash_cus_name=='Cash Customer Name') cash_cus_name='Cash Customer';
	 
	$(".bill_customer").html('Customer : '+ cash_cus_name);
});

function grand_total_cal(c) {
	
	/*var address_input=$('#address_input').val();
	if(address_input!=' '){
	$('.delivery_address_text').text("Delivery Address : "+address_input);
	$('.delivery_address_text').show();
	}else{
		$('.delivery_address_text').hide();
	}
	*/
	
	var invoice_type = $("input:radio[name='delivery_status']:checked").val();
	var ssubtotal = 0;
	var posdiscount = 0;
	var total_item_discount=0;
	var total_cost_value=0;
	/*-- get data and set sub totals in #postable --*/
	for (c = 0; c <= count; c++) {
	     //var check_qty = $('#quantity_' + c).val();
    	//if(check_qty>-0.111111 && check_qty<10000){	}else{
    	 //   $('#quantity_' + c).val(0);
        //	}
		var product_price = $('#sprice_' + c).val();
		var discount = 0;
		var discount_fld	= $('#discount_' + c);
		var cost_fld	= $('#cost_' + c);
		var cost= $(cost_fld).val();
			if($(discount_fld).length){
				discount = $(discount_fld).val();				
				var error=false;			
				if (discount.indexOf("%") !== -1) {
					var pds = discount.split("%");
					if (!isNaN(pds[0])) {
						discount = parseFloat( product_price* pds[0]/100 );
						discount = discount*$('#quantity_' + c ).val();
					}else{
						error=true;
					}
				}else{
					if (!isNaN(discount)) {
					    var qty = $('#quantity_' + c).val();
						discount	= parseFloat(discount * qty);
					}else{
						discount=0;
						error=true;
					}
				}				
			}else {
				discount=0;
			}
			
		focused = document.activeElement.id;
		if(!discount)discount=0;		
		total_item_discount+= parseFloat(discount);
		$('#discount_val' + c ).val(discount);
		$('#total_item_discount').val(total_item_discount);		
		if (product_price) {
		$('.bill_td_price_' + c).text(product_price);
		var btach_qty_value=parseFloat($('#batch_qty_' + c).val());
		var given_qty_value=parseFloat($('#quantity_' + c).val());
		var change_qty_batch_id=parseFloat($('#p_batch_id_' + c).val());
		var alrady_added_batch_qty=getAddedBatchQty(change_qty_batch_id);
		if(alrady_added_batch_qty>btach_qty_value){
		   var expected_qty=btach_qty_value-given_qty_value;
		   if(expected_qty<0){
		     expected_qty=given_qty_value+expected_qty; 
		   }else{
		       expected_qty=alrady_added_batch_qty-btach_qty_value;
		       if(expected_qty>=1){
		           expected_qty=1;
		       }else{
		          expected_qty=0.001; 
		       }
		   }
		 
		   $('#'+focused).val(parseFloat(expected_qty));
		   
		   bootbox.alert("Not enough quntity in hand for this batch. Maximum qty in this btach : "+btach_qty_value, function(){ 
                   
                    bootbox.hideAll();
                });
		}
		
		
		/*if(given_qty_value>btach_qty_value){
			if(btach_qty_value>1){
			  
			  
			    
			    
			    
			  $('#quantity_' + c).val(parseFloat(1));  
			}else{
			    $('#quantity_' + c).val(parseFloat(btach_qty_value));
			}
			 bootbox.alert("Not enough quntity in hand for this batch. Maximum qty in this btach : "+btach_qty_value, function(){ 
                    console.log('This was logged in the callback!'); 
                    bootbox.hideAll();
                });
			
		}*/
			
			
			
			
			
			
			var p_qty = $('#quantity_' + c).val();
			$('.bill_td_qty_' + c).html(p_qty);
			product_price = remove_comma(product_price);
			var p_sub_total = product_price * p_qty;
			ssubtotal += p_sub_total;
			$('#subtotal_' + c).text(formatMoney(p_sub_total-discount));
			$("#ssubtotal_" + c).val(parseFloat(p_sub_total));
			$(".bill_td_discount_" + c).text((formatMoney(discount)));			
			$('.bill_td_amount_' + c).text(formatMoney(p_sub_total-discount));
			if(isNaN(cost))
			{
				cost=0;
			}
			total_cost_value += parseFloat(cost)*p_qty;
			}
			
	}//end for	
	

	var tot_discount = $("span#tds").text();
	if (parseInt(tot_discount) > 0) {
		$('#td_order_discount').parent().removeClass('no-print');
		$('#td_order_discount').parent().css('display', '');
		$('#td_order_discount').text('(' + tot_discount + ')');
		if (tot_discount.indexOf("%") !== -1) {
			var e = tot_discount.split("%");
			if (!isNaN(e[0])) {
				posdiscount = formatDecimal((ssubtotal * parseFloat(e[0])) / 100)
			} else {
				posdiscount = formatDecimal(tot_discount)
			}
		} else {
			posdiscount = formatDecimal(tot_discount)
		}
	} else {
		$('#td_order_discount').parent().addClass('no-print');
		$('#td_order_discount').parent().css('display', 'none');
	}
	
		
	$("span#total").text(formatMoney(ssubtotal-total_item_discount));
	$(".td_sub_total").text(formatMoney(ssubtotal-total_item_discount));
	var extra_charges_amount = 0; /*console.log('dine type:'+invoice_type);*/
	$('#total_item_discount_fld').val(total_item_discount);	
	$('#extra_charges').val('');
	$('#extra_charges_amount').val();
	$('#sc_sp').css('visibility', 'hidden');
	$('#td_service_charges').parent().addClass('no-print');
	$('#td_service_charges').parent().css('display', 'none');
	itemQty = $("#posTable >tbody > tr").length;
	if (itemQty < 1) $('#sc_sp').css('visibility', 'hidden');
	ssubtotal += extra_charges_amount;	
	$("input#amount_val_1").val(ssubtotal - posdiscount);
	$("input#posdiscount").val(posdiscount);
	$("span#titems").text(itemQty)	
	
	var posshipping = $("#posshipping").val();
	if (!posshipping) posshipping = 0;
	$("span#tship").text(formatMoney(posshipping));
	$('#td_delivery_charges').parent().removeClass('no-print');
	$('#td_delivery_charges').text(formatMoney(posshipping));
	$('#td_delivery_charges').parent().css('display', '');
	$('.td_delivery_charges').text("Delivery Charges: "+formatMoney(posshipping));
	
	
	
	
	var g_total = ssubtotal - posdiscount + parseInt(posshipping);
	/*ccc*/
	var add_cc = $('input[name=add_cc]:checked').length;
	var paid_by_1 = $('#paid_by_1').val();
	if(paid_by_1 == "CC"){
		if(add_cc > 0){
			var cc = (g_total-total_item_discount)/100*2;
			g_total+=cc;console.log(cc);
			$("#td_cc_charges").text(formatMoney(cc)).parent().css('display', '');
			$('#cc_charges').val(cc);
			$('#cash_en').val(g_total-total_item_discount).attr('readonly');
		}else{
			$('#cash_en').val(g_total-total_item_discount).attr('readonly');
			$('#cc_charges').val(0);
			$("#td_cc_charges").text(formatMoney(0)).parent().css('display', 'none');
		}
		//$("#td_paying_amount").text(formatMoney($('#cash_en').val())).parent().css('display', '');
	}else{
		$('#cc_charges').val(0);
		$("#td_cc_charges").text(formatMoney(0)).parent().css('display', 'none');
	}
	/**/
	
	var cash_en = parseFloat($("#cash_en").val());
	var cash_balance = cash_en - (g_total-total_item_discount);
	$("span#gtotal").text(formatMoney(g_total-total_item_discount)); /*console.log('gtotal:'+(formatMoney(g_total)));*/
	$("#print_bill_total").text(formatMoney(g_total-total_item_discount));
	
	
	if (g_total == '0.00') {
		$("span#cash_balance").text(formatMoney(0));
		$(".cash_balance").text("Balance:"+formatMoney(0));
	} else if (g_total == 0) {
		$("span#cash_balance").text(formatMoney(0));
		$(".cash_balance").text("Balance:"+formatMoney(0));
	} else {
		$("span#cash_balance").text(formatMoney(cash_balance));
		$("#customer_balance").text(formatMoney(cash_balance));
		$(".cash_balance").text("Balance:"+formatMoney(cash_balance));
	}
	
	$(".id_total_amount").text(formatMoney(g_total));
	localStorage.setItem("gtotal", formatMoney(g_total));
	$("#grand_total").val(g_total-total_item_discount);
	$('#total_cost_val').val(total_cost_value);
	$('#td_balance_amount').text(formatMoney($('#cash_en').val()));
	
}
$("#ppdiscount").click(function(a) {
	a.preventDefault();
	$("#dsModal").modal()
});
function changecashen(){
	$("#td_paying_by").text($("#paid_by_1").val());
	var paid_by_1 = $('#paid_by_1').val();
	if(paid_by_1 == "CC"){
		/*var add_cc = $('input[name=add_cc]:checked').length;
		if(add_cc > 0){
		}else{
			$('#cash_en').val(0).removeAttr('readonly');	
		}*/
	}else{
		$('#cash_en').val(0).removeAttr('readonly');	
	}
}
/*Discount modal*/
$("#dsModal").on("shown.bs.modal", function() {
	$(this).find("#order_discount_input").select().focus();
	$("input#order_discount_input").bind("keypress", function(b) {
		if (b.keyCode == 13) {
			b.preventDefault();
			var a = $("#order_discount_input").val() ? $("#order_discount_input").val() : "0";
			if (is_valid_discount(a)) {
				if (is_valid_discount(a)) {
					$("#tds").text(formatMoney(a));
					$("#posdiscount").val(a);
					localStorage.removeItem("posdiscount");
					localStorage.setItem("posdiscount", a);
					$("#pos_discount_input1").val(a)
				} else {
					bootbox.alert(lang.unexpected_value);
				}
				$("#dsModal").modal("hide");
				grand_total_cal();
			} else {
				bootbox.alert(lang.unexpected_value);
			}
			$("#dsModal").modal("hide")
		}
	})
});
$(document).on("click", "#updateOrderDiscount", function() {
	var a = $("#order_discount_input").val() ? $("#order_discount_input").val() : "0";
	if (is_valid_discount(a)) {
		$("#tds").text(a);
		$("#posdiscount").val(a);
		localStorage.removeItem("posdiscount");
		localStorage.setItem("posdiscount", a);
		$("#pos_discount_input1").val(a)
	} else {
		bootbox.alert(lang.unexpected_value)
	}
	$("#dsModal").modal("hide");
	grand_total_cal();
});
$("#payment").click(function(b) {
	if (itemQty > 0) {
		//var a = $('.cb_list input[type="radio"]:checked:first').val();
		//var shipping_address = $("#shipping_address").val();
		//var shipping_charges = $("#posshipping").val();
		load_payment_grid();
	} else {
		bootbox.alert("Please add product before payment. Thank you !! ");
		$("#add_item").focus()
	}
});
$("#payment_no_bill").click(function(b) {
	if (itemQty > 0) {
		var a = $('.cb_list input[type="radio"]:checked:first').val();
		var shipping_address = $("#shipping_address").val();
		var shipping_charges = $("#posshipping").val();
		if (a == 3) {
			if (shipping_address == "") {
				$("#pshipping").click();
				bootbox.alert("Please confirm and update delivery details !!")
			} else if (shipping_charges == 0) {
				bootbox.confirm({
					size: "small",
					message: " Delivery charges : Rs. 0.00 /=. Continue ?",
					callback: function(a) {
						if (a == true) {
							load_payment_grid()
						} else $("#pshipping").click();
					}
				});
			} else {
				load_payment_grid();
			}
		} else {
			load_payment_grid();
		}
	} else {
		bootbox.alert("Please add product before payment. Thank you !! ");
		$("#add_item").focus()
	}
});

function load_payment_grid() {
	//$("span#twt").text($("span#gtotal").text());
	//$("span#item_count").text($("span#titems").text());
	$("#paymentModal").modal();
}
$("#paymentModal").on("shown.bs.modal", function() {
	//$('#paid_by_1').val('cash').trigger('change');
	//$("input.amount").focus().select();
}).on("hidden.bs.modal", function(e) {
	$('#add_item').focus();
});
$(document).on("change", ".paid_by", function() {
	var a = $(this).val(),
		c = $(this).attr("id"),
		b = c.substr(c.length - 1);
	$("#rpaidby").val(a);
	if (a == "cash" || a == "other") {
		$(".pcheque_" + b).hide();
		$(".pcc_" + b).hide();
		$(".pcash_" + b).show();
		$("#payment_note_" + b).focus();
		$("#paid_by_val_1").val(a)
	} else {
		if (a == "CC" || a == "stripe" || a == "ppp") {
			$(".pcheque_" + b).hide();
			$(".pcash_" + b).hide();
			$(".pcc_" + b).show();
			$("#swipe_" + b).focus();
			$("#paid_by_val_1").val(a)
		} else {
			if (a == "Cheque") {
				$(".pcc_" + b).hide();
				$(".pcash_" + b).hide();
				$(".pcheque_" + b).show();
				$("#cheque_no_" + b).focus()
			} else {
				$(".pcheque_" + b).hide();
				$(".pcc_" + b).hide();
				$(".pcash_" + b).hide()
			}
		}
	}
	if (a == "gift_card") {
		$(".gc_" + b).show();
		$(".ngc_" + b).hide();
		$("#gift_card_no_" + b).focus()
	} else {
		$(".ngc_" + b).show();
		$(".gc_" + b).hide();
		$("#gc_details_" + b).html("")
	}
	calculateTotals();
}).on("click", ".quick-cash", function() {
	var a = $(this);
	var e = a.contents().filter(function() {
		return this.nodeType == 3
	}).text();
	var c = ",";
	var d = $("#amount_1");
	e = formatDecimal(e.split(c).join("")) * 1 + remove_comma(d.val()) * 1;
	d.val(formatDecimal(e)).focus().change();
	var b = a.find("span");
	if (b.length == 0) {
		a.append('<span class="badge">1</span>')
	} else {
		b.text(parseInt(b.text()) + 1)
	}
}).on("click", "#clear-cash-notes", function() {
	$(".quick-cash").find(".badge").remove();
	//$("#" + pi).val("0").focus()
}).on("focus", ".amount", function() {
	pi = $(this).attr("id");
	calculateTotals()
}).on("blur", ".amount", function() {
	calculateTotals()
}).on("keyup", ".amount", function() {
	calculateTotals()
});
//$('input[name=add_cc]:checked').val();

function calculateTotals() {
	/* alert(33);
	console.log('calculateTotals....');*/
	/*var c = 0;
	var b = remove_comma($("span#twt").text());
	var a = $(".amount");
	
	$.each(a, function(e) {
		var d = remove_comma($(this).val());
		c += parseFloat(d ? d : 0)
	});
	
	$("#total_paying").text(formatMoney(c));
	$("#td_paying_amount").text(formatMoney(c)).parent().css('display', '');
	$("#td_paying_by").text($("#paid_by_1").val());
	$("#balance").text(formatMoney(c - b));
	if ((c - b) >= 0) {
		$("#td_balance_amount").text(formatMoney(c - b)).parent().parent().css('display', '');
	}*/
	/*$("#balance_" + pi).val(formatDecimal(c - b));*/
	/*total_paid = c;
	grand_total = b;*/
}
$("#pshipping").click(function(a) {
	a.preventDefault();
	shipping = $("#posshipping").val() ? $("#posshipping").val() : shipping;
	$("#shipping_input").val(shipping);
	shippingAddr = $("#shipping_address").val() ? $("#shipping_address").val() : "";
	if (shippingAddr) {
		$("#address_input").val(shippingAddr);
		$("#sModal").modal()
	} else {
		getAddressByCusId(1)
	}
});

$(document.body).on("change","#poscustomer",function(){
 getAddressByCusId()
});

function getAddressByCusId(open) {
	var b = "";
	var a = $("#poscustomer").val();
	$.ajax({
		type: "get",
		url: base_url + "pos/get_customers",
		data: {
			srh_customer_id: a
		},
		dataType: "json",
		success: function(c) {
			if (c !== null) {
				b = c[0].cus_address;
				$("#address_input").val(b);
				
					if(b!=''){
                	    $('.delivery_address_text').text("Delivery Address : "+b).show();
                	}else{
                		$('.delivery_address_text').hide();
                	}
				
				if(open)
				$("#sModal").modal();
				return b
			} else {
				bootbox.alert("No result found!")
			}
		}
	})
}
/*$("#sModal").on("shown.bs.modal", function() {
    $(this).find("#shipping_input").select().focus()
});*/
$("#sModal").on("shown.bs.modal", function() {
	$(this).find("#shipping_input").select().focus();
	$("input#shipping_input").bind("keypress", function(b) {
		if (b.keyCode == 13) {
			b.preventDefault();
			var a = parseFloat($("#shipping_input").val() ? $("#shipping_input").val() : "0");
			if (is_numeric(a)) {
				$("#posshipping").val(a);
				localStorage.setItem("posshipping", a);
				grand_total_cal();
				$("#sModal").modal("hide")
			} else {
				bootbox.alert(lang.unexpected_value)
			}
		}
	})
});
$(document).on("click", "#updateShipping", function() {
	var b = parseFloat($("#shipping_input").val() ? $("#shipping_input").val() : "0");
	var a = $("#address_input").val();
	$("#shipping_address").val(a);
	if (is_numeric(b)) {
		$("#posshipping").val(b);
		/*localStorage.setItem("posshipping", b);*/
		grand_total_cal();
		$("#sModal").modal("hide")
	} else {
		bootbox.alert(lang.unexpected_value)
	}
});
$("#paymentModal").on("change", "#amount_1", function(a) {
	$("#pay_amount").val(remove_comma($(this).val()))
}).on("blur", "#amount_1", function(a) {
	$("#pay_amount").val(remove_comma($(this).val()))
}).on("change", "#payment_note_1", function(b) {
	$("#pos_note").val($(this).val());
	var a = $("#pos_note").val();
	localStorage.setItem("posnote", a);
}).on("change", "#swipe_1", function(a) {
	$("#cc_name").val($(this).val())
}).on("change", ".pcc_type", function(a) {
	$("#pcc_type").val($(this).val())
}).on("change", "#pcc_holder_1", function(a) {
	$("#pcc_holder").val($(this).val())
}).on("change", "#pcc_no_1", function(a) {
	$("#cc_no").val($(this).val())
});

function printElem(b) {
	var c = document.getElementById(b).innerHTML;
	var a = window.open("", "Print", "height=1,width=1");
	a.document.close();
	a.focus();
	a.print();
	a.close();
	return true
};

function remove_comma(a) {
	return parseFloat(a.replace(/,/g, ""))
}

function formatDecimal(a) {
	return parseFloat(parseFloat(a).toFixed(site.settings.decimals))
}

function formatMoney(a, b) {
	if (!b) {
		b = ""
	}
	if (site.settings.sac == 1) {
		return b + "" + formatSA(parseFloat(a).toFixed(site.settings.decimals))
	}
	return accounting.formatMoney(a, b, site.settings.decimals, site.settings.thousands_sep == 0 ? " " : site.settings.thousands_sep, site.settings.decimals_sep, "%s%v")
}

function getNumber(a) {
	return accounting.unformat(a)
}

function formatQuantity(a) {
	return (a != null) ? '<div class="text-center">' + formatNumber(a, site.settings.qty_decimals) + "</div>" : ""
}

function formatNumber(a, b) {
	if (!b && b != 0) {
		b = site.settings.decimals
	}
	if (site.settings.sac == 1) {
		return formatSA(parseFloat(a).toFixed(b))
	}
	return accounting.formatNumber(a, b, site.settings.thousands_sep == 0 ? " " : site.settings.thousands_sep, site.settings.decimals_sep)
}

function formatMoney(a, b) {
	if (!b) {
		b = ""
	}
	if (site.settings.sac == 1) {
		return b + "" + formatSA(parseFloat(a).toFixed(site.settings.decimals))
	}
	return accounting.formatMoney(a, b, site.settings.decimals, site.settings.thousands_sep == 0 ? " " : site.settings.thousands_sep, site.settings.decimals_sep, "%s%v")
}

function formatDecimal(a) {
	return parseFloat(parseFloat(a).toFixed(site.settings.decimals))
}

function is_valid_discount(a) {
	return (is_numeric(a) || (/([0-9]%)/i.test(a))) ? true : false
}

function is_numeric(b) {
	var a = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
	return (typeof b === "number" || (typeof b === "string" && a.indexOf(b.slice(-1)) === -1)) && b !== "" && !isNaN(b)
}

function is_float(a) {
	return +a === a && (!isFinite(a) || !!(a % 1))
}

function currencyFormat(a) {
	if (a != null) {
		return formatMoney(a)
	} else {
		return "0"
	}
}

function formatSA(b) {
	b = b.toString();
	var d = "";
	if (b.indexOf(".") > 0) {
		d = b.substring(b.indexOf("."), b.length)
	}
	b = Math.floor(b);
	b = b.toString();
	var c = b.substring(b.length - 3);
	var a = b.substring(0, b.length - 3);
	if (a != "") {
		c = "," + c
	}
	var e = a.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + c + d;
	return e
}
$('.panel-refresh').click(function(e) {
	e.preventDefault();
	if (e.target.id == 'delivery-panel-refresh') loadDelivery();
	else if (e.target.id == 'takeaway-panel-refresh') loadTakeaway();
	else if (e.target.id == 'dine_in-panel-refresh') loadDineIn();
});
$('input').on('ifChecked', function(event) {
	/*console.log(event);*/
	if (event.target.value == 1) {
		$('#content').css('background-color', '#d9534f');
		$('.hide_me').css('visibility', 'hidden');
		grand_total_cal();
	}
	if (event.target.value == 2) {
		$('#content').css('background-color', '#5cb85c');
		$('.hide_me').css('visibility', 'hidden');
		grand_total_cal();
	}
	if (event.target.value == 3) {
		$('#content').css('background-color', '#eea236');
		$('.hide_me').css('visibility', 'visible');
		grand_total_cal();
	}
});
$('input').on('ifUnchecked', function(event) {
	$('#delivary_status').val(0);
	$('#content').css('background-color', '#FFF');
	/*var cur_status = $('#delivary_status').val();
	alert(cur_status );*/
});
$('#div_1 , #div_1_2').on('click', function() {
	$('#cb_1').iCheck("check");
	grand_total_cal();
});
$('#div_2 , #div_2_2').on('click', function() {
	$('#cb_2').iCheck("check");
	grand_total_cal();
});
$('#div_3 , #div_3_2').on('click', function() {
	$('#cb_3').iCheck("check");
	grand_total_cal();
});
$('#poss_1 , #poss_1_2').on('click', function() {
	$('#divi_1').iCheck("check");
	/* grand_total_cal();*/
});
$('#poss_2 , #poss_2_2').on('click', function() {
	$('#divi_2').iCheck("check");
	/* grand_total_cal();*/
});
$("#view_bill").click(function(b) {
	b.preventDefault();
	$("#view_bill_modal").modal();
});


var old_row_qty;
$(document).on("focus", '.rquantity', function() {
    old_row_qty = $(this).val();
}).on("change", '.rquantity', function() {
    var row = $(this).closest('tr');
    if (!is_numeric($(this).val())) {
        $(this).val(old_row_qty);
        bootbox.alert("unexpected value !");
        return;
    }
     var new_qty = parseFloat($(this).val());
     if(new_qty.toString().length>9){
       $(this).val(old_row_qty);  
       grand_total_cal();
     }
});

//batch product all count check and validate
function getAddedBatchQty(batch_id){
    var total_batch_count=0;
    $('.'+batch_id).each(function(){
    total_batch_count+=parseFloat($(this).val());
});
   return total_batch_count;
}
