
/*=======================================================\
|                 Point of Sales Module                  |
|--------------------------------------------------------|
|   Creator: Phương                                      |
|   Date :   18-Dec-2017                                 |
|   Description: ERP Point of Sales Extension            |
|   Website: http://notrinos.com                         |
|                                                        |
\=======================================================*/

(function(){
	"use strict";

	var use_commission = 0;
	var use_amtbarcode = 0;
	var lowStock = 0;
	var salespeople = {};
	var commissions = {};

	var allowLowStock = function() {
		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'allow_negative_inventory'},
			dataType:'json'
		}).done(function(data){
			if(data != '') {
				lowStock = data;
			}
			// console.log(lowStock);
		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	};
	var checkUseCommission = function() {
		
		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'pos_using_commission'},
			dataType:'json'
		}).done(function(data){
			if(data != '') {
				use_commission = data;
				getSalesmanList();
				getComissionsList();
			}
			// console.log(use_commission);
		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	};
	var checkUseAmtBarcode = function() {
		
		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'use_amt_barcode'},
			dataType:'json'
		}).done(function(data){
			if(data != '') {
				use_amtbarcode = data;
			}
			// console.log(use_amtbarcode);
		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	};
	var getSalesmanList = function() {

		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'salesman_list'},
			dataType:'json'
		}).done(function(data){
			if(data != '')
				salespeople = data;

		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	};
	var getComissionsList = function() {

		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'commissions_list'},
			dataType:'json'
		}).done(function(data){
			if(data != '')
				commissions = data;

		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	};
	var itemsCart = {
		lineItem: {},
		customer: $('#customer_id').val()
	};
	var payItems = {};

	var updateCart = function() {
		itemsCart.lineItem = {};

		$('#pos_bill_table > tbody > tr:not(:first-child)').each(function(i){
			var itemId = $(this).attr('data');

			itemsCart.lineItem[i] = {
				item:itemId,
				desc:$(this).find('.line_item_desc').html(),
				qty:$(this).find('.item_qty').html(),
				price:price2number($(this).find('.bill_item_price').html()),
				dsc:($(this).find('.bill_item_disc').html())/100
			};

			if(use_commission == 1) {
				var thisSalesman = $(this).find('select.pos_salespeople_list').val();
				var thisCommission = $(this).find('select.pos_commissions_list').val();
				itemsCart.lineItem[i].salesman = thisSalesman;
				itemsCart.lineItem[i].commission = thisCommission;
			}
		});
	};
	var transferCart = function(data) {
		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'getCart',data:data},
			dataType:'json'
		}).done(function(){
			if($('#pos_from_table').length) {
				var transfer_items = $.parseJSON($('#pos_from_table').attr('data'));
				// console.log(transfer_items);
				// console.log(curTable);
				transferOldTable(transfer_items, curTable);
			}
			$('.pos_body_left').hide();
			$('.pos_body_right').hide();
			$('#payment_panel').show();
			var billTotal = $('#bill_total').html();
			$('#remain_amount').html(priceFormat(price2number(billTotal) - price2number(totalAlloc)));
			var old_table_kitchen = $('#print_kitchen_order').find('a').attr('href');
			var new_table_kitchen = (old_table_kitchen+'').replace(/PARAM_0=.+&/, "PARAM_0="+curTable+"&");
			var old_table_bill = $('#pos_bill_print_btn').find('a').attr('href');
			var new_table_bill = (old_table_bill+'').replace(/PARAM_0=.+&/, "PARAM_0="+curTable+"&");
			$('#print_kitchen_order').find('a').attr('href', new_table_kitchen);
			$('#pos_bill_print_btn').find('a').attr('href', new_table_bill);
		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	};
	var clearCart = function() {
		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'clearItems'},
			dataType:'json'
		}).done(function(){
			$('.pos_body_left').show();
			$('.pos_body_right').show();
			$('#payment_panel').hide();
			$("input[name=itemCode]").select();
			$("#process_order").siblings('center').remove();
			$("#process_order").show();
		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	};
	var transferAlloc = function(data, cash, orderType, table) {
		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'getAlloc',data:data,cash:cash,table:table,orderType:orderType},
			dataType:'json'
		}).done(function(){
			$('#process_payment').trigger('click');
		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	};
	var updateTotal = function() {
		var billTotal = 0;

		$('#pos_bill_table > tbody > tr:not(:first-child)').each(function(i){
			var thisAmount = $(this).find('.item_line_total').html();
			if(thisAmount != '')
				billTotal += price2number(thisAmount);
		});
		
		$('#bill_total').html(priceFormat(billTotal));
	};
	var updateStatus = function() {
		var canProcess = 1;
		if(price2number($('#bill_total').html()) == 0 || $('#bill_total').html() == '')
			canProcess = 0;
		$('#pos_bill_table > tbody > tr:not(:first-child)').each(function(i){
			var thisPrice = $(this).find('.bill_item_price').html();
			var thisQty = $(this).find('.item_qty').html();
			if(thisPrice == '' || price2number(thisPrice) == 0 || thisQty == '' || price2number(thisQty == 0))
				canProcess = 0;
		});
		// if($("select[name=table]").length && $("select[name=table]").val() == 0)
		//     canProcess = 0;
		// if($("select[name=order_type]").length && $("select[name=order_type]").val() == 0)
		//     canProcess = 0;

		if(canProcess == 1 && $('#process_order center').length == 0) {
			$('#process_order').append("<center>&#10004;</center>");
			$('#process_order').css({'background-color':'#6FCF9F','border': '2px solid #33cc00','color':'#FFF'});
		}
		else if(canProcess == 0) {
			$('#process_order center').remove();
			$('#process_order').css({'background-color':'#F0AD4E','border': '2px solid #EC971F','color':'#FFF'});
		}
	};

	var CancelTableOrder = function(table) {
		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'cancel_order',data:table},
			dataType:'json'
		}).done(function(msg){
			var notic = "<center id='cancel_order_notification'>"+msg+"</center>";
			$('.pos_body_left').find('#cancel_order_notification').remove();
			$('.pos_body_left').append(notic);
			setTimeout(function(){$('#cancel_order_notification').fadeOut(10000)}, 100);
			$('[table='+table+']').attr('data','');
			$('[table='+table+']').removeClass('pos_open_table');
		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	}

	var transferOldTable = function(data, toTable) {
		$.ajax({
			type: 'POST',
			url: '../data.php',
			data: {action:'update_transfered_table',data:data,toTable:toTable},
			dataType:'json'
		}).done(function(msg){
			var notic = "<center id='cancel_order_notification'>"+msg+"</center>";
			$('.pos_body_left').find('#cancel_order_notification').remove();
			$('.pos_body_left').append(notic);
			setTimeout(function(){$('#cancel_order_notification').fadeOut(10000)}, 100);
			$('#pos_from_table').remove();
			// $('[table='+table+']').removeClass('pos_open_table');
		}).fail(function(){
			alert('error sending data to server, check your internet conection and try again');
		});
	}

	var displayItems = function(cateData, currCate) {

		$('.pos_item_box').each(function(){
			var thisID = $(this).attr('data');

			if($.inArray(thisID, cateData) == -1 && currCate != 0)
				$(this).addClass('hide_menu');
			else
				$(this).removeClass('hide_menu');
		});
	};

	var round2 = function(n) {
		var dec = Math.pow(10, user.pdec);
		n = (Math.round(n*dec)/dec).toFixed(user.pdec);

		return parseFloat(n);
	}

	var priceFormat = function(number) {
		number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
		var n = !isFinite(+number) ? 0 : +number;
		var prec = !isFinite(+user.pdec) ? 0 : Math.abs(user.pdec);
		var sep = (typeof user.ts === 'undefined') ? ',' : user.ts;
		var dec = (typeof user.ds === 'undefined') ? '.' : user.ds;
		var s = '';
		var toFixedFix = function (n, prec) {
			var k = Math.pow(10, prec);
			return '' + Math.round(n * k) / k;
		};
		// Fix for IE parseFloat(0.55).toFixed(0) = 0;
		s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
		if (s[0].length > 3)
			s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
		if ((s[1] || '').length < prec) {
			s[1] = s[1] || '';
			s[1] += new Array(prec - s[1].length + 1).join('0');
		}
		return s.join(dec);
	}

	var price2number = function(n) {
		if(user.ts == ',')
			var num = (n + '').replace(/[^\d.]/g, '');
		else {
			var num = (n + '').replace(/[^\d,]/g, '');
			num = (num + '').replace(',', '.');
		}
		// console.log(num);

		return round2(num);
	}

	function openFullscreen() {
		var elem = document.documentElement;
		if (elem.requestFullscreen)
			elem.requestFullscreen();
		else if (elem.mozRequestFullScreen) /* Firefox */
			elem.mozRequestFullScreen();
		else if (elem.webkitRequestFullscreen) /* Chrome, Safari and Opera */
			elem.webkitRequestFullscreen();
		else if (elem.msRequestFullscreen) /* IE/Edge */
			elem.msRequestFullscreen();
	}

	function exitFullscreen() {
		var elem = document.documentElement;
		if (document.exitFullscreen)
			document.exitFullscreen();
		else if (document.mozCancelFullScreen) /* Firefox */
			document.mozCancelFullScreen();
		else if (document.webkitExitFullscreen) /* Chrome, Safari and Opera */
			document.webkitExitFullscreen();
		else if (document.msExitFullscreen) /* IE/Edge */
			document.msExitFullscreen();
	}

	//-------------------------------------------------------------------------------

	var countLine = 0;
	var currItem = 0;
	var calBtnVal = '';
	var calAmount = '';
	var totalAlloc = 0;
	var currCal = 'qty';
	var curPayMethod = $('#bank_name').length == 0 ? 'pt_cash' : 0;
	var curOrderType = 1; //1 - dine-in, 2 - take away, 3 - delivery
	var curTable = 0;
	var currPmtCal = 'p_amt';
	var dscAmount = '';
	var cash_tendered = 0;
	var cash_paid = 0;
	var restaurantMode = 0;

	$(document).ready(function() {

		if(sessionStorage.getItem('cateItems') == null)
			var cateItems = $('.selected_cat').attr('data').split('&');
		else
			var cateItems = sessionStorage.getItem('cateItems').split('&');
		if(sessionStorage.getItem('currCate') == null)
			var currCate = 0;
		else
			var currCate = sessionStorage.getItem('currCate');

		displayItems(cateItems, currCate);
		checkUseCommission();
		checkUseAmtBarcode();
		allowLowStock();

		$("td[btn='qty']").css({'background-color':'#D9534F', 'color':'#FFF'});
		$("div[btn='pt_cash']").css({'background-color':'#D9534F', 'color':'#FFF'});
		$("td[btn='p_amt']").css({'background-color':'#D9534F', 'color':'#FFF'});
		
		$('#payment_panel').hide();
		if($('#pos_table_list').length) {
			$('#retail_items_container').hide();
			restaurantMode = 1;
		}
		$('.pos_order_type_btn').each(function(){
			if(this.hasAttribute('default')) {
				curOrderType = $(this).attr('orderType');
				$(this).css({'background-color':'#D9534F', 'color':'#FFF'});

				if(curOrderType == 1) {
					$('#pos_table_seat').css({'background-color':'#D9534F', 'color':'#FFF'});
					$('#retail_items_container').hide();
					$('#pos_table_list').show();
				}
				else {
					$('#retail_items_container').show();
					$('#pos_table_list').hide();
					curTable = 0;
					$('#curTable').html('');
				}
			}
		});

		$('div#order_type_table').on('click', '.pos_order_type_btn', function() {
			
			$('#order_type_table').find('div').css({'background-color':'','color':''});
			$(this).css({'background-color':'#D9534F', 'color':'#FFF'});
			curOrderType = $(this).attr('orderType');

			if(curOrderType == 1) {
				$('#pos_table_seat').css({'background-color':'#D9534F', 'color':'#FFF'});
				$('#retail_items_container').hide();
				$('#pos_table_list').show();
			}
			else {
				$('#pos_table_seat').css({'background-color':'','color':''});
				$('#retail_items_container').show();
				$('#pos_table_list').hide();
				curTable = 0;
				$('#curTable').html('');
				$('.transfer_merge').removeClass('transfer_merge').addClass('transfer_merge_blur');
				$('.pos_select_item').replaceWith("<span class='pos_del_item'>X</span>");
				$('.pos_check_all').hide();
			}
		});
		$('div#order_type_table').on('click', '#pos_table_seat', function() {
			if(curOrderType == 1) {
				$('#pos_table_seat').css({'background-color':'#D9534F', 'color':'#FFF'});
				$('#retail_items_container').hide();
				$('#pos_table_list').show();
			}
		});
		$('div#pos_table_list').on('click', '.pos_table_box', function() {
			
			curTable = $(this).attr('table');
			$('#curTable').html(curTable);
			$('#retail_items_container').show();
			$('#pos_table_list').hide();
			$('#pos_table_seat').css({'background-color':'','color':''});

			$('.pos_item_row').addClass('pos_item_row_hidden').removeClass('pos_item_row').hide();

			var new_data = $(this).attr('data') ? $.parseJSON($(this).attr('data')) : [];

			$.each(new_data, function(i) {
				var itm_code = new_data[i].item_code;
				var itm_desc = new_data[i].item_description;
				var itm_unit = new_data[i].units;
				var itm_qty = new_data[i].quantity;
				var itm_price = new_data[i].std_price;
				var itm_dsc = new_data[i].discount_percent;
				var itm_price_full = new_data[i].price;

				var disc_box = "<span class='bill_item_disc item_price'></span>";

				if(itm_dsc != 0)
					disc_box = "<span class='bill_item_disc item_price'>"+itm_dsc*100+"</span><span class='item_price' id='dsc_txt'>&nbsp;% Discount</span>";

				var item_box = "<td><span class='pos_del_item'>X</span><span class='line_item_desc'>"+itm_desc+"</span><br><span class='bill_item_price item_price'>"+priceFormat(itm_price)+"</span><i>/</i><span class='item_unit item_price'>"+itm_unit+"</span>&nbsp;&nbsp;"+disc_box+"</td>";
				var qtyCell = "<td class='item_qty'>"+itm_qty+"</td>";
				var priceCell = "<td class='item_line_total'>"+priceFormat(itm_price_full*itm_qty)+"</td>";
			
				$('#pos_bill_table').find('tr').removeClass('pos_selected_line');

				if(countLine % 2 == 0)
					$('#pos_bill_table').append("<tr class='pos_item_row odd_line pos_selected_line' data='"+itm_code+"' price='"+itm_price_full+"'>"+item_box+qtyCell+priceCell+"</tr>");
				else
					$('#pos_bill_table').append("<tr class='pos_item_row even_line pos_selected_line' data='"+itm_code+"' price='"+itm_price_full+"'>"+item_box+qtyCell+priceCell+"</tr>");
				
				countLine++;
				
				currItem = itm_code;
				calBtnVal = '';
				$('.transfer_merge_blur').removeClass('transfer_merge_blur').addClass('transfer_merge');
			});

			if($('#cate_container').is(':hidden')) {
				$('.pos_item_row_hidden').each(function(){
					if($(this).find('input').is(':checked')) {

						if($('#'+$(this).attr('id')+'.pos_item_row').length > 0) {
							$('#'+$(this).attr('id')+'.pos_item_row').find('td.item_qty').html(price2number($('#'+$(this).attr('id')+'.pos_item_row').find('td.item_qty').html()) + price2number($(this).find('.item_qty').html()));
						}
						else {
							var from_itm_code = $(this).attr('data');
							var from_itm_desc = $(this).find('.line_item_desc').html();
							var from_itm_unit = $(this).find('.item_unit').html();
							var from_itm_qty = price2number($(this).find('.item_qty').html());
							var from_itm_price = price2number($(this).find('.bill_item_price').html());
							var from_itm_dsc = price2number($(this).find('.bill_item_disc').html());
							var from_itm_total = price2number($(this).find('.item_line_total').html());

							var from_item_box = "<td><span class='pos_del_item'>X</span><span class='line_item_desc'>"+from_itm_desc+"</span><br><span class='bill_item_price item_price'>"+priceFormat(from_itm_price)+"</span><i>/</i><span class='item_unit item_price'>"+from_itm_unit+"</span>&nbsp;&nbsp;<span class='bill_item_disc item_price'></span></td>";
							var from_qtyCell = "<td class='item_qty'>"+from_itm_qty+"</td>";
							var from_priceCell = "<td class='item_line_total'>"+priceFormat(from_itm_total)+"</td>";
			
							$('#pos_bill_table').find('tr').removeClass('pos_selected_line');

							if(countLine % 2 == 0)
								$('#pos_bill_table').append("<tr class='pos_item_row odd_line pos_selected_line' data='"+from_itm_code+"' price='"+from_itm_price+"'>"+from_item_box+from_qtyCell+from_priceCell+"</tr>");
							else
								$('#pos_bill_table').append("<tr class='pos_item_row even_line pos_selected_line' data='"+from_itm_code+"' price='"+from_itm_price+"'>"+from_item_box+from_qtyCell+from_priceCell+"</tr>");
				
							countLine++;
				
							currItem = from_itm_code;
							calBtnVal = '';
						}
					}
				});
			}

			$('#cate_container').show();
			$('.pos_body_left > center').show();
			$('.pos_order_type_btn').show();
			$('.pos_item_row_hidden').remove();
			updateCart();
			updateTotal();
			updateStatus();
			$("input[name=itemCode]").select();
			// console.log(itemsCart);
			// if($(this).attr('data'))
				// console.log($.parseJSON($(this).attr('data')));
		});
		$('div#retail_items_container').on('click', '.pos_item_box', function() {

			if($(this).hasClass('low_stock') && lowStock == 0) {
				alert('Low Stock!');
				return false;
			}

			var salespeople_list = "<select class='pos_salespeople_list'><option value = 0>No Salesman</option>";
			$.each(salespeople, function(id, name){
				salespeople_list += "<option value = "+id+">"+name+"</option>";
			});
			salespeople_list += "</select>";

			var commissions_list = "<select class='pos_commissions_list'><option value = 0>No Commission</option>";
			$.each(commissions, function(id, data){
				commissions_list += "<option value = "+id+">"+data['name']+" - "+data['comm']+"%"+"</option>";
			});
			commissions_list += "</select>";

			if(use_commission == 0) {
				salespeople_list = '';
				commissions_list = '';
			}

			var kit_code = $(this).attr('data');

			$(this).children('i').each(function () {
				var item_box = "<td><span class='pos_del_item'>X</span><span class='line_item_desc'>"+$(this).attr('desc')+"</span><br><span class='bill_item_price item_price'>"+priceFormat($(this).attr('std_price'))+"</span><i>/</i><span class='item_unit item_price'>"+$(this).attr('unit')+"</span>&nbsp;&nbsp;<span class='bill_item_disc item_price'></span>"+salespeople_list+commissions_list+"</td>";
				var qtyCell = "<td class='item_qty'>"+$(this).attr('quantity')+"</td>";
				var priceCell = "<td class='item_line_total'>"+priceFormat(Number($(this).attr('price') * price2number($(this).attr('quantity'))))+"</td>";
			
				$('#pos_bill_table').find('tr').removeClass('pos_selected_line');

				var line_itm = $("tr[data='"+$(this).attr('data')+"'][price='"+$(this).attr('price')+"']");

				var line_price = price2number($('#pos_bill_table').find(line_itm).find('.item_price').html());

				// console.log(line_price);

				if($('#pos_bill_table').find(line_itm).length && price2number(line_price) == price2number($(this).attr('std_price'))) {
					line_itm.addClass('pos_selected_line');
					var line_qty = line_itm.find('.item_qty').html();
					var line_disc = line_itm.find('.bill_item_disc').html();
					line_qty = price2number(line_qty);
					line_qty += price2number($(this).attr('quantity'));
					var price = $(this).attr('price') * (1 - line_disc/100);
					price *= line_qty;

					line_itm.find('.item_qty').html(line_qty);
					line_itm.find('.item_line_total').html(priceFormat(price));
				}
				else {
					if(countLine % 2 == 0)
						$('#pos_bill_table').append("<tr class='pos_item_row odd_line pos_selected_line' kit='"+kit_code+"' data='"+$(this).attr('data')+"' price='"+$(this).attr('price')+"'>"+item_box+qtyCell+priceCell+"</tr>");
					else
						$('#pos_bill_table').append("<tr class='pos_item_row even_line pos_selected_line' kit='"+kit_code+"' data='"+$(this).attr('data')+"' price='"+$(this).attr('price')+"'>"+item_box+qtyCell+priceCell+"</tr>");

					countLine++;
				}
				currItem = $(this).attr('data');
				calBtnVal = '';
				updateCart();
				updateTotal();
				updateStatus();
			});

			
		});
		$('#_page_body').on('change','#customer_id',function(){
			itemsCart.customer = $('#customer_id').val();
		});
		$('#process_order').on('click', function(){

			if($(this).find('center').length > 0) {
				$(this).hide();
				$(this).parent().append("<center><div><img src='../../../themes/default/images/ajax-loader2.gif' />Processing...</div></center>");
				updateCart();
				
				itemsCart.table = curTable === '' ? 0 : curTable;
				// console.log(itemsCart);

				var new_cart = [];

				$('#pos_bill_table > tbody > tr:not(:first-child)').each(function(i){
					var itemId = $(this).attr('data');
					var itemStdPrice = $(this).find('span.bill_item_price').html();
					var itemQty = ($(this).find('.item_qty').html());
					var itemTotal = ($(this).find('.item_line_total').html())

					new_cart[i] = {
						item_code:itemId,
						item_description:$(this).find('.line_item_desc').html(),
						units:$(this).find('span.item_unit').html(),
						quantity:price2number(itemQty),
						std_price:price2number(itemStdPrice),
						price:price2number(itemTotal)/price2number(itemQty),
						discount_percent:price2number($(this).find('span.bill_item_disc').html())
					};
				});
				$('[table='+curTable+']').attr('data', JSON.stringify(new_cart));
				$('[table='+curTable+']').addClass('pos_open_table');
				// console.log(new_cart);

				if($('#pos_from_table').length > 0) {

					var fromTableTransfer = $.parseJSON($('#pos_from_table').attr('data'));
					var fromTableData = $.parseJSON($('[table='+fromTableTransfer.table_id+']').attr('data'));

					// console.log(fromTableData);
					// console.log(fromTableTransfer.line_items);

					var tableDataRemain = [];

					$.each(fromTableData, function(i){
						var rowItem = fromTableData[i];

						tableDataRemain[i] = rowItem;

						$.each(fromTableTransfer.line_items, function(j){
							var remainItem = '';

							if(j == rowItem.item_code) {
								remainItem = rowItem.quantity - fromTableTransfer.line_items[j].quantity;
								if(remainItem > 0)
									tableDataRemain[i] = {
										item_code:rowItem.item_code,
										item_description:rowItem.item_description,
										units:rowItem.units,
										quantity:remainItem,
										price:rowItem.price,
										discount_percent:rowItem.discount_percent
									};
								else
									tableDataRemain.splice(i, 1);
							}					
						});
					});
					$.each(tableDataRemain, function(i){
						if(tableDataRemain[i] == null)
							tableDataRemain.splice(i, 1);
					});
					$('[table='+fromTableTransfer.table_id+']').attr('data', JSON.stringify(tableDataRemain));
					
					if(tableDataRemain.length == 0)
						$('[table='+fromTableTransfer.table_id+']').removeClass('pos_open_table');
					
					// console.log(tableDataRemain);
				}
				
				transferCart(itemsCart);
			}
			else {
				if(restaurantMode && Object.keys(itemsCart.lineItem).length == 0)
					CancelTableOrder(curTable);
			}
		});
		$('#processPayment').on('click', function(){

			var remainsAmount = $('#remain_amount').html();
			if(price2number(remainsAmount) == 0) {
				
				$(this).hide();
				$('#arrow_wrapper').append("<div><img src='../../../themes/default/images/ajax-loader2.gif' />Processing...</div>");
				var bill_cash = $('#pos_tendered').html();
				if(restaurantMode == 0)
					curOrderType = '';

				transferAlloc(payItems, price2number(bill_cash), curOrderType, curTable);
			}
		});
		$('#back_to_bill').on('click', function(){
			clearCart();
		});
		$('#pos_bill').on('click', '.pos_del_item', function() {
			$(this).parent().parent().remove();
			updateCart();
			updateTotal();
			updateStatus();
		});
		$('#pos_bill_table').on('click', 'tr', function() {
			currItem = $(this).attr('data');
			$('#pos_bill_table').find('tr').removeClass('pos_selected_line');
			$(this).addClass('pos_selected_line');
			calBtnVal = '';
		});
		$('#pos_calculator').on('click', '.pos_cal_btn', function() {
			var thisBtn = $(this).attr('btn');
			if(thisBtn == 'qty' || thisBtn == 'disc' || thisBtn == 'price') {
				$('#pos_calculator').find('td').css({'background-color':'','color':''});
				$(this).css({'background-color':'#D9534F', 'color':'#FFF'});
				currCal = thisBtn;
				calBtnVal = '';
			}
			else if(jQuery.inArray(thisBtn, ['00','0','1','2','3','4','5','6','7','8','9','.']) != -1) {
				if(calBtnVal.indexOf('.') == -1 || thisBtn != '.')
					calBtnVal += thisBtn;
				if(currCal == 'qty')
					$("tr.pos_selected_line[data='"+currItem+"']").find('.item_qty').html(round2(calBtnVal));
				else if(currCal == 'price') {
					$("tr.pos_selected_line[data='"+currItem+"']").find('.bill_item_price').html(price2number(calBtnVal));
					var thisTax = $("div#pos_item_"+currItem).find("i").attr('tax');
					$("div#pos_item_"+currItem).find("i").attr('price', price2number(calBtnVal)*(1+price2number(thisTax)));
				}
				else {
					$('tr.pos_selected_line[data='+currItem+']').find('.bill_item_disc').html(price2number(calBtnVal));
					if($("tr.pos_selected_line[data='"+currItem+"']").find('#dsc_txt').length == 0)
						$("tr.pos_selected_line[data='"+currItem+"']").find('.bill_item_disc').parent().append("<span class='item_price' id='dsc_txt'>&nbsp;% Discount</span>");
				}
			}
			else if(thisBtn == 'del') {
				if(currCal == 'qty') {
					calBtnVal = calBtnVal.slice(0,-1);
					$('tr.pos_selected_line[data='+currItem+']').find('.item_qty').html(round2(calBtnVal));
					if($('tr.pos_selected_line[data='+currItem+']').find('.item_qty').html() == '') {
						$('tr.pos_selected_line[data='+currItem+']').remove();
						currItem = $('#pos_bill_table tr:last').attr('data');
						$('tr.pos_selected_line[data='+currItem+']').addClass('pos_selected_line');
					}
				}
				else if(currCal == 'price') {
					$('tr.pos_selected_line[data='+currItem+']').find('.bill_item_price').html('0');
					calBtnVal = '';
				}
				else {
					$('tr.pos_selected_line[data='+currItem+']').find('.bill_item_disc').html('');
					$('tr.pos_selected_line[data='+currItem+']').find('.bill_item_disc').siblings("#dsc_txt").remove();
					calBtnVal = '';
				}
			}
			var line_qty = $('tr.pos_selected_line[data='+currItem+']').find('.item_qty').html();
			var line_total = $('tr.pos_selected_line[data='+currItem+']').find('.item_line_total').html();
			var disc = $('tr.pos_selected_line[data='+currItem+']').find('.bill_item_disc').html();
			var tax = price2number($('#pos_item_'+currItem).find('i:hidden').attr('tax'));
			if(disc == undefined)
				disc = 0;
			var price = $('tr.pos_selected_line[data='+currItem+']').find('.bill_item_price').html();
			// price = (price*line_qty);
			line_total = ((price2number(price)*price2number(line_qty)) * (1 + tax)) * (1 - disc/100);
			$('tr.pos_selected_line[data='+currItem+']').find('.item_qty').html(line_qty);
			$('tr.pos_selected_line[data='+currItem+']').find('.item_line_total').html(priceFormat(line_total));
			// console.log(tax);

			updateCart();
			updateTotal();
			updateStatus();
		});
		$('#payment_keyboard').on('click','.pos_cal_btn',function(){
			
			var thisPmtBtn = $(this).attr('btn');
			if(thisPmtBtn == 'p_amt' || thisPmtBtn == 'p_dsc') {
				$('#payment_keyboard').find('td').css({'background-color':'','color':''});
				$(this).css({'background-color':'#D9534F', 'color':'#FFF'});
				currPmtCal = thisPmtBtn;
			}
			else if(jQuery.inArray($(this).html(), ['0','1','2','3','4','5','6','7','8','9','.']) != -1) {

				if(currPmtCal == 'p_amt') {
					if(calAmount.indexOf('.') == -1 || $(this).html() != '.')
						calAmount += $(this).html();
				}
				if(currPmtCal == 'p_dsc') {
					if(dscAmount.indexOf('.') == -1 || $(this).html() != '.')
						dscAmount += $(this).html();
				}
			}
			else if($(this).attr('btn') == 'add10' || $(this).attr('btn') == 'add20' || $(this).attr('btn') == 'add50') {
				var addAmt = $(this).html().slice(1);
				if(calAmount == '')
					calAmount = 0;
				calAmount = price2number(calAmount) + price2number(addAmt);
				calAmount = calAmount.toString();
				// console.log(calAmount);
			}
			else if($(this).attr('btn') == 'import') {
				var remainAmt = $('#remain_amount').html();
				if(calAmount == '')
					calAmount = 0;
				calAmount = price2number(calAmount) + price2number(remainAmt);
				calAmount = calAmount.toString();
				// console.log(calAmount);
			}
			else if($(this).attr('btn') == 'del') {
				if(currPmtCal == 'p_amt')
					calAmount = calAmount.slice(0,-1);
				if(currPmtCal == 'p_dsc')
					dscAmount = dscAmount.slice(0,-1);
			}
			else if($(this).attr('btn') == 'c') {
				if(currPmtCal == 'p_amt')
					calAmount = '';
				if(currPmtCal == 'p_dsc')
					dscAmount = '';
			}
			$('#payment_amount_cell').html(priceFormat(calAmount));
			$('#pmt_dsc').val(dscAmount);
		});
		$('#transfer_table').on('click', '.transfer_merge', function(){
			var transferBtn = $(this).attr('id');

			if(transferBtn === 'btn_transfer_select') {
				$('.pos_del_item').replaceWith("<input type='checkbox' class='pos_select_item'>");
				$('#pos_select_all_items').show();
				$('#pos_uncheck_all_items').hide();
				$('#retail_items_container').hide();
			}
			else if(transferBtn === 'btn_cancel_select') {
				$('.pos_select_item').replaceWith("<span class='pos_del_item'>X</span>");
				$('.pos_check_all').hide();
				$('#cate_container').show();
				$('.pos_body_left > center').show();
				$('.pos_order_type_btn').show();
				$('#retail_items_container').show();
				$('.pos_table_box[table='+curTable+']').trigger('click');
			}
			else if(transferBtn === 'btn_to_table') {
				if(curOrderType == 1 && $('.pos_check_all').is(':visible')) {
					$('#pos_table_seat').css({'background-color':'#D9534F', 'color':'#FFF'});
					$('#retail_items_container').hide();
					$('#cate_container').hide();
					$('.pos_body_left > center').hide();
					$('.pos_order_type_btn').hide();
					$('#pos_table_list').show();
					$('.pos_check_all').hide();
					var from_table_data = {};
					from_table_data['table_id'] = curTable;
					from_table_data['line_items'] = {};
					$('.pos_item_row').each(function(i){
						if($(this).find('input').is(':checked')) {
							from_table_data['line_items'][$(this).attr('data')] = {
								description: $(this).find('.line_item_desc').html(), 
								units: $(this).find('.item_unit').html(), 
								quantity: price2number($(this).find('.item_qty').html()), 
								price: price2number($(this).find('.bill_item_price').html()), 
								discount_percent: price2number($(this).find('.bill_item_disc').html())
							};
						}
					});
					$('#order_type_table').append("<input type='hidden' id='pos_from_table' value='"+curTable+"' data='"+JSON.stringify(from_table_data)+"'>");
				}
			}

		});
		$('#pos_bill_table').on('click', '#pos_select_all_items', function(){
			$('.pos_select_item').prop('checked', true);
			$(this).hide();
			$('#pos_uncheck_all_items').show();
		});
		$('#pos_bill_table').on('click', '#pos_uncheck_all_items', function(){
			$('.pos_select_item').removeAttr('checked');
			$(this).hide();
			$('#pos_select_all_items').show();
		});
		$('#payment_add_bank').on('click', '.pos_payment_type_btn', function(){
			var thisMethod = $(this).attr('btn');
			$('#payment_add_bank').find('div').css({'background-color':'','color':''});
			$(this).css({'background-color':'#D9534F', 'color':'#FFF'});
			$('.pos_payment_type_btn').removeClass('selected_method');
			$(this).addClass('selected_method');
			curPayMethod = thisMethod;
		});
		$('#customer_select').on('click','#pos_menu_toggle',function(){
			$('.right-body').toggleClass('full_width');
			$('.quick_menu').toggleClass('hide_menu');
			$('#footer').toggleClass('hide_menu');
			$("#_page_body > center").toggleClass('hide_menu');
			$('.bottomBar2').toggleClass('hide_menu');
			$('.frontBarRight').toggleClass('hide_menu');
			$('.frontBar').toggleClass('hide_menu');
			$('#title').toggleClass('hide_menu');
			$('.main-menu').toggleClass('hide_menu');
			$('.page_header').toggleClass('hide_menu');
			
			if($('#footer').hasClass('hide_menu') && sessionStorage.getItem('fullScreen') != 1) {
				sessionStorage.setItem('fullScreen', 1);
				openFullscreen();
			}
			else {
				sessionStorage.setItem('fullScreen', 0);
				exitFullscreen();
			}
		});
		$('#add_payment_item').on('click', function(){
			var billTotal = price2number($('#bill_total').html());
			var bankAct = curPayMethod == 0 ? $('#bank_name').val() : $('.selected_method').attr('account');
			var bankName = curPayMethod == 0 ? $('#bank_name').find("option[value='"+bankAct+"']").html() : $('.selected_method').attr('acc_name');
			var remainAmount = $('#remain_amount').html();
			var lineDisc = $('#pmt_dsc').val();
			var DiscType = $('#total_disc_wrapper input[type=radio]:checked').val();
			var lineTotal = '';
			var dsc_element = '';
			var cash = price2number($('#payment_amount_cell').html());

			if(bankName == '' || bankAct == '')
				alert('Default bank account is not defined');
			else if(cash != '' && price2number(remainAmount) > 0) {
				if(price2number(calAmount) > price2number(remainAmount))
					calAmount = price2number(remainAmount);
				cash_tendered += cash;

				totalAlloc += price2number(calAmount);
				if(totalAlloc > price2number(billTotal))
					totalAlloc = price2number(billTotal);
				if(!lineDisc)
					lineDisc = 0;
				if(DiscType == '%') {
					lineTotal = calAmount - (calAmount * price2number(lineDisc)/100);
					if(lineDisc != 0)
						dsc_element = 'Discount: ' + lineDisc + '%';
				}
				else if(DiscType == 'amt') {
					lineTotal = calAmount - price2number(lineDisc);
					if(lineDisc != 0)
						dsc_element = 'Discount: ' + lineDisc;
				}

				cash_paid += price2number(lineTotal);

				var paymentRow = "<tr bank='"+bankAct+"' cash='"+cash+"' refund='"+(cash - lineTotal)+"'><td><span class='pos_del_item'>X</span>"+bankName+"<br><span class='pmt_dsc'>"+dsc_element+"</span></td><td class='bank_amt'>"+priceFormat(calAmount)+"</td><td class='pmt_line_total'>"+priceFormat(lineTotal)+"</td></tr>";
			
				$('#remain_amount').html(priceFormat(billTotal - totalAlloc));

				if($("#payment_items_table tr[bank='"+bankAct+"']").length > 0) {
					var thisLine = $("#payment_items_table tr[bank='"+bankAct+"']");
					var oldAmount = thisLine.find('td.bank_amt').html();
					var newAmount = price2number(oldAmount) + price2number(calAmount);
					var oldTottal = thisLine.find('td.pmt_line_total').html();
					var newTotal = '';
					if(DiscType == '%') {
						newTotal = newAmount - (newAmount * price2number(lineDisc)/100);
						dsc_element = 'Discount: ' + lineDisc + '%';
					}
					else if(DiscType == 'amt') {
						newTotal = newAmount - price2number(lineDisc);
						dsc_element = 'Discount: ' + lineDisc;
					}

					thisLine.find('td.bank_amt').html(priceFormat(newAmount));
					thisLine.find('td.pmt_line_total').html(priceFormat(newTotal));
					thisLine.find('span.pmt_dsc').html(dsc_element);
					thisLine.attr('cash', newTotal);
					payItems[bankAct] = {amount:newAmount, discount:newAmount - newTotal};
				}
				else {
					$('#payment_items_table').append(paymentRow);
					payItems[bankAct] = {amount:calAmount, discount:calAmount - lineTotal};
				}

				$('#pos_tendered').html(priceFormat(cash_tendered));
				$('#pos_refund').html(priceFormat(cash_tendered - cash_paid));

				calAmount = '';

				$('#payment_amount_cell').html(calAmount);
				// console.log(payItems);
				if(billTotal == totalAlloc)
					$('#processPayment').css({'background-color':'#6ec89b','border': '2px solid #33cc00'});
				else
					$('#processPayment').css({'background-color':'#AAA','border': '2px solid #AAA'});
			}
			$("td.pos_cal_btn[btn='p_amt']").trigger('click');
		});
		$('#payment_items_table').on('click','.pos_del_item',function(){
			var billTotal = price2number($('#bill_total').html());
			var thisBank = $(this).parent().parent().attr('bank');
			var thisValue = $(this).parent().parent().find('td.bank_amt').html();
			var thisCash = $(this).parent().parent().attr('cash');
			var totalCash = $('#pos_tendered').html();
			var thisRefund = $(this).parent().parent().attr('refund');
			var totalRefund = $('#pos_refund').html();

			$('#pos_tendered').html(price2number(totalCash) - price2number(thisCash));
			$('#pos_refund').html(price2number(totalRefund) - price2number(thisRefund));
			cash_tendered -= price2number(thisCash);
			cash_paid -= price2number(thisCash) - price2number(thisRefund);

			delete payItems[thisBank];
			totalAlloc -= price2number(thisValue);
			// console.log(billTotal);
			$('#remain_amount').html(priceFormat(billTotal - totalAlloc));
			$(this).parent().parent().remove();
			$('#processPayment').css({'background-color':'#AAA','border': '2px solid #AAA'});
		});
		if(sessionStorage.getItem('fullScreen') == 1){
			$('.quick_menu').addClass('hide_menu');
			$('#footer').addClass('hide_menu');
			$('.bottomBar2').addClass('hide_menu');
			$('.frontBarRight').addClass('hide_menu');
			$('.frontBar').addClass('hide_menu');
			$('#title').addClass('hide_menu');
			$('.main-menu').addClass('hide_menu');
			$('.page_header').addClass('hide_menu');
			$('.right-body').addClass('full_width');
			$("#_page_body > center").addClass('hide_menu');
			$('#pos_menu_toggle').attr('checked', true);
			openFullscreen();
		}
		$('.pos_body_left').find("input").on("keydown", function(e){

			if(e.keyCode === 13) {

				if(use_amtbarcode != 0) {

					var code = $(this).val(); //EAN 13

					var item_code = code.substr(0, 7);
					var amt_code = code.substr(7, 5);

					$('#pos_item_'+item_code).trigger('click');

					if($('#pos_item_'+item_code).attr('unit').toLowerCase() == 'kg')
						amt_code = price2number(amt_code)/1000;

					$('#'+currItem).find('.item_qty').html(amt_code);
					var line_qty = $('tr[data='+currItem+']').find('.item_qty').html();
					var price = $('tr[data='+currItem+']').find('.bill_item_price').html();
					var disc = $('tr[data='+currItem+']').find('.bill_item_disc').html();
					price = (price*line_qty);
					price = price - (price*disc/100);
					price = price2number(price);
					$('tr[data='+currItem+']').find('.item_qty').html(priceFormat(line_qty));
					$('tr[data='+currItem+']').find('.item_line_total').html(priceFormat(price));

					updateCart();
					updateTotal();
					updateStatus();
				}
				else if($('#pos_item_'+$(this).val()).is(':visible'))
					$('#pos_item_'+$(this).val()).trigger('click');

				$(this).select();
				// console.log(use_amtbarcode);
			}
		});
		setTimeout(function(){$('#code_input_hint').fadeOut(2000)}, 5000);
		setTimeout(function(){$('#cancel_order_notification').fadeOut(2000)}, 5000);
		
		$('.categories_link').on('click',function(){
			$('.categories_link').each(function(){
				$(this).removeClass('selectedCat');
			});
			currCate = $(this).attr('cat');
			sessionStorage.setItem('currCate', currCate);
			$(this).addClass('selectedCat');
			cateItems = $(this).attr('data').split('&');
			sessionStorage.setItem('cateItems', $(this).attr('data'));

			displayItems(cateItems, currCate);
		});
		$('.categories_link').each(function(){
			if(sessionStorage.getItem('currCate') == null)
				$('.selected_cat').addClass('selectedCat');
			else {
				if(currCate == 0)
					$('div[cat=0]').addClass('selectedCat');
				else {
					if($(this).attr('cat') == currCate)
						$(this).addClass('selectedCat');
					else
						$(this).removeClass('selectedCat');
				}
			}
		});
		$('#pos_loading_spinner img').on('click', function(){
			$('#pos_loading_spinner').hide();
		});
		$('#bank_name').change(function(){
			$("td.pos_cal_btn[btn='p_amt']").trigger('click');
		});
		$('#_page_body').on('change',"select[name=table]" ,function(){
			updateStatus();
		});
		$('#_page_body').on('change',"select[name=order_type]" ,function(){
			updateStatus();
		});
		// console.log(currCate);
		
		// $('body').on("keydown", function(e){
		// 	if(e.keyCode === 27)
		// 		$('#processPayment').trigger('click');			
		// });
	});

})();