var g_invoice_prd=[];
var g_lastdiv=null;
var g_find_split="/";
var g_last_row=null;
var g_direct_print=false;
var g_input_quantity_selected=null;
var g_goods_category_id=0;
	function pageGoods(pageno)
	{
		ajaxGetUrl('?page=posgoods&pageno='+pageno+'&category_id='+g_goods_category_id,"posgoods",ajaxGetUrlReturn);
	}
	function pageGoodsReturn(goods_list)
	{
		var divgoodslist=document.getElementById("goods_list");
		divgoodslist.innerHTML=goods_list;
	}
	function pageGoodsCategory(pageno)
	{
		ajaxGetUrl('?page=posgoodscategory&pageno='+pageno,"posgoodscategory",ajaxGetUrlReturn);
	}
	function pageGoodsCategoryReturn(category_list)
	{
		var divcategory_list=document.getElementById("category_list");
		divcategory_list.innerHTML=category_list;
	}
	function invoiceGoodsCodeSearchReturn(retval)
	{
		if(retval.substring(0,2)!="ok")
		{
			alert("Không tìm thấy hàng!");
			return;
		}
		var goodsinfo=retval.substring(2,retval.length);
		var prds=goodsinfo.split(g_find_split);
		if(prds.length!=3)
		{
			alert("Dữ liệu bị lỗi. Hãy thử lại");
			return;
		}
		g_invoice_prd[g_invoice_prd.length]=prds[0]+g_find_split+prds[1]+g_find_split+"1"+g_find_split+prds[2];
		invoiceShow();	
	}
	function onGoodsCodePress(e)
	{
		if(e.keyCode === 13)
		{
			var prd_code=document.getElementById("prd_code");
			if(prd_code.length<1)
				return;
			goods_code=prd_code.value;
			prd_code.value="";
			ajaxGetUrl('?page=posgoodscodesearch&goods_code='+goods_code,"posgoodscodesearch",ajaxGetUrlReturn);
        }
        return false;
	}
	function invoiceQuantityInputToGoodsId(quantity_input)
	{
		if(quantity_input==null)
			return -1;
		if (typeof(quantity_input)== "undefined")	
			return -1;
		var id=quantity_input.id;
		if(id.substring(0,8)=="quantity")
		{
			goods_id=id.substring(8,id.length);
			return goods_id;
		}
		return -1;
	}
	function invoiceNew()
	{
		invoiceClear();
	}
	function invoiceGoodsQuantityFocus(inputid)
	{
		
		if ((typeof(g_input_quantity_selected)!= "undefined") &&(typeof(inputid)!= "undefined")&&(g_input_quantity_selected!=null))
		{
			if(g_input_quantity_selected.id==inputid.id)
				return;
			invoiceGoodsQuantityBlur(g_input_quantity_selected);
		}
		g_input_quantity_selected=inputid;
		//noi bat div co id item{goods_id}
		var goods_id=invoiceQuantityInputToGoodsId(g_input_quantity_selected);
		if(goods_id>=0)
		{
			var itemid="item"+goods_id;
			var divitem=document.getElementById(itemid);
			if(typeof(divitem)=="object");
			{
				divitem.style.background="lightgrey";
			}
		}
		g_input_quantity_selected.value="";
	}
	function invoiceGoodsQuantityBlur(inputid)
	{
		var id=inputid.id;
		var itemid="";
		if(id.substring(0,8)=="quantity")
		{
			goods_id=id.substring(8,id.length);
			itemid="item"+goods_id;
			var divitem=document.getElementById(itemid);
			if(typeof(divitem)=="object");
				divitem.style.background="white";
		}
	}
	function numpadPress(x)
	{
		if(g_input_quantity_selected==null)
			return;
		if (typeof(g_input_quantity_selected)== "undefined") 
			return;
		if(x>=0 && x<=9)
		{
			if(isNaN(g_input_quantity_selected.value))
				g_input_quantity_selected.value = 0;
			g_input_quantity_selected.value = (g_input_quantity_selected.value * 10)+x;
			
			invoiceGoodsChangeQuantityCurrent();
			
		}		
		if(x==10)
		{
			var num = g_input_quantity_selected.value;
			var num1 = num%10;
			num -= num1;
			num /= 10;
			g_input_quantity_selected.value = num;
			invoiceGoodsChangeQuantityCurrent();
		}
		if(x==11)
		{
			g_input_quantity_selected.value="";
			invoiceGoodsChangeQuantityCurrent();
		}
		if(x==12)
		{
		}
	}
	function formatNumber(x) 
	{
		return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
	}
	function invoiceSave()
	{
		if(g_invoice_prd.length<1)
		{
			alert("Phiếu chưa có mặt hàng nào. Không thể ghi!");
			return;
		}
		ajaxGetUrl('?page=possave&data='+invoiceGetRawData(),"possave",ajaxGetUrlReturn);
	}
	function invoiceSaveDone(ret)
	{
		if(ret=="ok")
		{
			var nRet=confirm("Đã ghi phiếu. Tạo ngay phiếu mới?");
			if(nRet==true)
				invoiceClear();
		}
		else
		{
			alert("Lỗi. Không ghi được phiếu!");
		}
	}
	function chonnhom(category_id)
	{
		g_goods_category_id=category_id;
		ajaxGetUrl('?page=goods&category_id='+category_id,"goods",ajaxGetUrlReturn);
	}
	function invoiceClear()
	{
		g_invoice_prd.length=0;
		invoiceShow();
	}
	function invoiceCancel()
	{
		invoiceClear();
	}
	function invoiceGetRawData()
	{
		var data="";
		for(i=0;i<g_invoice_prd.length;i++)
		{
			var prds=g_invoice_prd[i].split(g_find_split);
			if(prds.length!=4)
			{
				return 0;
			}
			data+=g_find_split+prds[0]+g_find_split+prds[2];
		}
		return data;
	}
	function invoiceGetSum()
	{
		var sum=0;
		for(i=0;i<g_invoice_prd.length;i++)
		{
			var prds=g_invoice_prd[i].split(g_find_split);
			if(prds.length!=4)
			{
				return 0;
			}
			sum+=prds[2]*prds[3];
		}
		return sum;
	}
	function invoiceShowSum()
	{
		var sum=invoiceGetSum();
		var invoice_sum=document.getElementById("invoice_sum");
		invoice_sum.innerHTML=formatNumber(sum);
		
		var invoice_total=document.getElementById("invoice_total");
		invoice_total.innerHTML=formatNumber(sum);
	}
	function invoiceGoodsRemove(goods_id)
	{
		var index=invoiceGoodsGetIndexFromId(goods_id);
		if(index<0)
		{
			alert("Lỗi. Không tìm thấy hàng");
			return;
		}
		g_invoice_prd.splice(index,1);
		invoiceShow();
	}
	function invoiceGoodsGetIndexFromId(goods_id)
	{
		for(i=0;i<g_invoice_prd.length;i++)
		{
			var prds=g_invoice_prd[i].split(g_find_split);
			if(prds.length!=4)
			{
				return -1;
			}
			if(goods_id==prds[0])
			{
				return i;
			}
		}
		return -1;
	}
	//Cap nhat hang dang duoc chon
	function invoiceGoodsChangeQuantityCurrent()
	{
		
		if(g_input_quantity_selected==null)
			return;
		if (typeof(g_input_quantity_selected)== "undefined") 
			return;	
			
		var goods_id=invoiceQuantityInputToGoodsId(g_input_quantity_selected);
		if(goods_id<0)
			return;
		var index=invoiceGoodsGetIndexFromId(goods_id);
		if(index<0)
			return;
			
		var prds=g_invoice_prd[index].split(g_find_split);
		var quantity=g_input_quantity_selected.value;
		
		if(prds.length!=4)
		{
			alert("LOI");
			return;
		}
		
		g_invoice_prd[index]=prds[0]+g_find_split+prds[1]+g_find_split+quantity+g_find_split+prds[3];
		
		var sutotalid="subtotal"+goods_id;
		var divsubtotal=document.getElementById(sutotalid);
		divsubtotal.innerHTML=prds[3]*quantity;
		invoiceShowSum();
	}
	function invoiceGoodsChangeQuantity(goods_id,export_price)
	{
		var sutotalid="subtotal"+goods_id;
		var quantityid="quantity"+goods_id;
		var divsubtotal=document.getElementById(sutotalid);
		var inputquantity=document.getElementById(quantityid);
		var quantity=inputquantity.value;
		divsubtotal.innerHTML=export_price*quantity;
		for(i=0;i<g_invoice_prd.length;i++)
		{
			var prds=g_invoice_prd[i].split(g_find_split);
			if(prds.length!=4)
			{
				alert("LOI");
				return;
			}
			if(goods_id==prds[0])
			{
				g_invoice_prd[i]=prds[0]+g_find_split+prds[1]+g_find_split+quantity+g_find_split+prds[3];
			}
		}
		invoiceShowSum();
	}
	function invoiceShow()
	{
		var item="";
		for(i=0;i<g_invoice_prd.length;i++)
		{
			var prds=g_invoice_prd[i].split(g_find_split);
			if(prds.length!=4)
			{
				alert("LOI");
				return;
			}
			item+="<div class=\"item\" id=\"item"+prds[0]+"\">";
			item+="<div class='goods_id'>"+prds[0]+"</div>";
			item+="<div class='goods_name'>"+prds[1]+"</div>";
			item+="<div class='export_price'>"+formatNumber(prds[3])+"</div>";
			
			item+="<div class='quantity'><input type='text' value='"+prds[2]+"' id=\"quantity"+prds[0]+"\"";
			item+=" onchange='javascirpt:invoiceGoodsChangeQuantity("+prds[0]+","+prds[3]+")' ";
			item+="onfocus='javascript:invoiceGoodsQuantityFocus(this)'></div>";
			
			item+="<div class='subtotal' id=\"subtotal"+prds[0]+"\">"+formatNumber(prds[3]*prds[2])+"</div>";
			item+="<a href='javascript:invoiceGoodsRemove("+prds[0]+")'><div class='remove'>-</div></a>";
			item+="</div>";
		}
		
		var invoice_prd=document.getElementById("invoice_prd");
		invoice_prd.innerHTML=item;
		////
		invoiceShowSum();
	}
	function chonhang(goods_id,goods_name,export_price)
	{
		g_invoice_prd[g_invoice_prd.length]=goods_id+g_find_split+goods_name+g_find_split+"1"+g_find_split+export_price;
		invoiceShow();
	}

	function clickDirectPrint()
	{
		var ddp=document.getElementById("div_direct_print");
		if(g_direct_print)
		{
			g_direct_print=false;
			ddp.style.background="#FF0000";
		}
		else
		{
			ddp.style.background="#00FF00";
			g_direct_print=true;
		}
	}
	function getCharPart(string)
	{
		ret="";
		for(i=0;i<string.length;i++)
		{
			if((string.charCodeAt(i)>=65)&&(string.charCodeAt(i)<=90))
				ret+=string.charAt(i);
			if((string.charCodeAt(i)>=97)&&(string.charCodeAt(i)<=122))
				ret+=string.charAt(i);
			if(string.charCodeAt(i)==32)
				ret+=string.charAt(i);
			if(string.charAt(i)=="/")
				ret+=string.charAt(i);
				
		}
		return ret;
	}
	function getNumberPart(string)
	{
		ret="";
		for(i=0;i<string.length;i++)
		{
			if((string.charCodeAt(i)>=48)&&(string.charCodeAt(i)<=57))
				ret+=string.charAt(i);
			if(string.charCodeAt(i)==32)
				ret+=string.charAt(i);
		}
		return ret;
	}

	function show()
	{
		var objid=document.getElementById("obj_id");
		
		//find('','dagoi');
	
		window.open('?man_id='+g_man_id+'&obj_id='+objid.value,'_self');
	}
	function expand_cat(div_id)
	{
		if(g_lastdiv)
		{
			g_lastdiv.innerHTML="";
			g_lastdiv.style.visibility="hidden";
		}
		var divid=document.getElementById(div_id);
		if(g_lastdiv==divid)
			return;
		divid.style.visibility="visible";
		divid.innerHTML=(strArray[div_id]);
		g_lastdiv=divid;
	}

	function find(goods_name,param)
	{
		var objid=document.getElementById("obj_id");
		if(objid.value<=0)
		{
			g_innerhtml_divcontent="";
			showContent();
			return;
		}
		var categoryid=document.getElementById("goods_category");
		if(param=="nhom")
			goods_name=categoryid.value;

		ajaxGetUrl('?page=res_find&goods_name='+goods_name+'&param='+param+'&obj_id='+objid.value+'&category_id='+categoryid.value,param,ajaxGetUrlReturn);
	}
	function add(goods_id,quantity)
	{
		var objid=document.getElementById("obj_id");
		ajaxGetUrl('?page=res_add&goods_id='+goods_id+'&obj_id='+objid.value+'&quantity='+quantity+'&print='+g_direct_print,"them",ajaxGetUrlReturn);		
	}
	function remove(order_id)
	{
		var objid=document.getElementById("obj_id");
		ajaxGetUrl('?page=res_add&order_id='+order_id+'&obj_id='+objid.value+"&param=loai"+'&print='+g_direct_print,"loai",ajaxGetUrlReturn);		
	}
	function showMarkGoodsAdded(goods_id)
	{
		var divname="divgoodsindex"+goods_id;
		var divindex=document.getElementById(divname);
		divindex.innerHTML="<B>OK</B>";
	}

	function submitUpdate(f)
	{
		f.man_id.value=g_man_id;
		
		f.submit();
		return TRUE;
	}
	
	function showContent()
	{
		var divcontent=document.getElementById("div_content");
		divcontent.innerHTML=(g_innerhtml_divcontent);
	}
	function getGoodsIdFromIndex(goods_index)
	{
		var divid="divgoodsindex";
		var alldivs=document.getElementsByTagName("div");
		var divcmd=document.getElementById("div_cmd");
		var goods_id=0;
		for(i=0;i<alldivs.length;i++)
		{
			if(alldivs[i].id.substr(0,divid.length)==divid)
			{
				goods_id=alldivs[i].id.substr(divid.length,alldivs[i].id.length-divid.length);
				if(alldivs[i].innerHTML==goods_index)
				{
					return goods_id;
				}
			}
		}
	}
	function selectRow(goods_id)
	{
		if(g_last_row!=null)
		{
			g_last_row.style.background="#FFFFFF";
			g_last_row=null;
		}
		var rowid=document.getElementById("tr"+goods_id);
		if(rowid==null)
			return;
		rowid.style.background="#FF00FF";
		g_last_row=rowid;
	}
	function addGoodsByEnter(goods_index,goods_quantity)
	{
		var goods_id=getGoodsIdFromIndex(goods_index);
		if(goods_id<=0)
			return;
		add(goods_id,goods_quantity);
	}
	function selObj(npart)
	{
		var objid=document.getElementById("obj_id");
		obj_id.selectedIndex=npart;
		show();
	}
	function findGoods(param,key_code)
	{
		if(param=="")
			return;

		if((key_code==13)&&(param.charAt(0)=="/"))
		{
			var cpart=getCharPart(param);
			var npart=getNumberPart(param);
			if((cpart=='/b')&&!isNaN(npart))
				selObj(npart);
			return;
		}
		var arvals=param.split(g_find_split);
		if(arvals.length<1)
			return;
			
		var goods_name=arvals[0];
		var goods_index=0;
		var goods_quantity=1;
		if(arvals.length>1)
			goods_index=arvals[1];
		if(arvals.length>2)
			goods_quantity=arvals[2];
		if(isNaN(goods_quantity))
			goods_quantity=1;
	
		if(goods_index>0)
		{
			goods_id=getGoodsIdFromIndex(goods_index);
			selectRow(goods_id);
		}
		//Enter
		if(key_code==13)
		{
			if(!isNaN(goods_index))
				addGoodsByEnter(goods_index,goods_quantity);
			return;
		}
		if(goods_name.substr(0,1)==" ")
			return;
		//neu den phan chon index thi khong tim hang nua
		if(goods_index==0)
			find(goods_name,'tim');
	}
	function keyboard(key)
	{
		var divcmd=document.getElementById("div_cmd");
		val=divcmd.innerHTML;
		if((key.length==1)&&(key!="/"))
		{
			val+=key;
			divcmd.innerHTML=val;
			//neu la lenh thi bo qua khong tim tru khi nhan phim enter - xu ly phia duoi
			if(val.substr(0,1)!="/")
				findGoods(val,key);
		}
		if(key=="db")
		{
			val=val.substr(0,val.length-1);
			divcmd.innerHTML=val;
			findGoods(val,key);
		}
		if(key=="sp")
		{
			divcmd.innerHTML=val+" ";
			findGoods(val,key);
		}
		if(key=="do")
		{
			divcmd.innerHTML=val+".";
			findGoods(val,key);
		}
		if(key=="bs")
		{
			divcmd.innerHTML=val+"/";
			findGoods(val,key);
		}
		if(key=="et")
		{
			findGoods(val,13);
			divcmd.innerHTML="";
		}
		if(key=="goithem")
		{
			find('','goithem');
		}
		if(key=="dagoi")
		{
			find('','dagoi');
		}
	}
	function ajaxGetUrl(url,dataExtra,functionHandler) 
	{
		if (window.XMLHttpRequest) 
		{ // Non-IE browsers & New IE
			req = new XMLHttpRequest();
			req.onreadystatechange = functionHandler;
			req.dataExtra=dataExtra;
			
			try 
			{
				req.open("GET", url, true);
			} 
			catch (e) 
			{
				alert(e);
			}
			req.send(null);
		} 
		else if (window.ActiveXObject) 
		{ // OLD IE
			req = new ActiveXObject("Microsoft.XMLHTTP");
			
			if (req) 
			{
				req.dataExtra=dataExtra;
				req.onreadystatechange = functionHandler;
				req.open("GET", url, true);
				req.send();
			}
		}
	}
	function ajaxGetUrlReturn()
	{
		if (req.readyState == 4) 
		{ // Complete
			if (req.status == 200) 
			{ // OK response
				if(req.dataExtra=="them")
				{
					alert(req.responseText);
					
					if(!isNaN(req.responseText))
					{
						showMarkGoodsAdded(Number(req.responseText));
						
					}
				}else if(req.dataExtra=="posgoodscodesearch")
				{
					invoiceGoodsCodeSearchReturn(req.responseText);
				}
				else if(req.dataExtra=="goods")
				{
					var divgoodslist=document.getElementById("goods_list");
					divgoodslist.innerHTML=(req.responseText);
				}
				else if(req.dataExtra=="possave")
				{
					invoiceSaveDone(req.responseText);
				}
				else if(req.dataExtra=="danhsach")
				{
					g_innerhtml_divcontent=req.responseText;
					
					showContent();
				} 	
				else if(req.dataExtra=="posgoodscategory")
				{
					pageGoodsCategoryReturn(req.responseText);
				}else if(req.dataExtra=="posgoods")
				{
					pageGoodsReturn(req.responseText);
				}
			}
			else 
			{
			}
		}
	}