// JavaScript Document
//here all method and function that control bill

var calcuproduct;
var totalprice;
var thegeneraldiscount;
var checkthepayed;
var thegeneralpayed;
var therestofdebt;
var addrow;
var getUnits;
var totalquantity;
var return_calcuproduct;
var return_totalprice;

var return_thegeneralpayed;
var return_therestofdebt;
var return_addrow;
var return_totalquantity;


jQuery(document).ready(function(){
		
		//here the varables in supplier method
		var supplierpagename = 'buyBillControllerAjax.php';
		var supplierid = 1;
		var productpricepagename = 'buyBillControllerAjax.php';
		//type determine if the bill is buy or return
		// 0 for buy , 1 for return
		var billtype = 0;
		
	////$('select').chosen();
	//to start the itration with default value // 1
	document.getElementById("hidden_itr").value = 1;
	
	//the common itration and the start // 2
	$aw_i = 2;
	
	//the tabindex to increment in dynmaic load
	$tabindexnum = 15;
	
	
	//add new row in bill 
	//on click the add button 
	/************************/
	$("#addpro").click(function() {

		addrow($aw_i,$tabindexnum);

		// fill the iltration filed with common iltration
		document.getElementById("hidden_itr").value = $aw_i ;
			
		// incrementaion of row number and tab index		
		$aw_i++
		$tabindexnum++ ;
				
		//reload the dropdownlist and jquery files	
		////$('select').chosen();
		return false;
	});
	/************************/

	
	//add new row in bill
	/**************************/
	addrow = function($aw_i,$tabindexnum)
	{
		var parcodeSetting = $("#parcodeSetting").val();
		var newProductSetting = $("#newProductSetting").val();
		var noteSetting = $("#noteSetting").val();
		var productDiscountSetting = $("#productDiscountSetting").val();
		var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();
		
		$addedRow = '<tr class="aw_td"  id="newProduct'+$aw_i+'">';
		
		if(newProductSetting == 0)
		{
			$addedRow += '<td><a onclick="javascript:showModalBox(this.name);" class="newLink"  id="new'+$aw_i+'"  name="'+$aw_i+'">جديد</a></td>';
		}
		
		if(parcodeSetting == 0)
		{
			$addedRow += '<td><input name="parcode'+$aw_i+'" type="text" id="parcode'+$aw_i+'"  size="3"  onkeypress="getproductbyParcode(event,this.value, '+$aw_i+');" size="10"  autocomplete="off"/></td>';
		}
	
		$addedRow += '<td>'
		+ '<div id="productdiv'+$aw_i+'" class="aw_width aw_mt5">'
		+ '<select id="product'+$aw_i+'" name="product'+$aw_i+'" data-placeholder="اختر" class="chzn-select aw_m1 chosenproduct" tabindex="'+$tabindexnum+'">'
		+ $("#addrowcreated").html()
		+ '</select></div></td>';
		
		if(noteSetting == 0)
		{
			$addedRow += ' <td>'
					+'    <input name="note'+$aw_i+'" id="note'+$aw_i+'" size="3"  type="text" />'
					+'    </td>';
		}
		
		$addedRow += '    <td>'
		+'  <div id="unitDiv'+$aw_i+'">'
        +'    <select name="unitId'+$aw_i+'" id="unitId'+$aw_i+'"  size="3"  onchange="getUnitPrice('+$aw_i+');"  data-placeholder="اختر" class="chzn-select aw_m1 chosenproduct" tabindex="122">>'
        +'    </select>'
        +'    </div>'
        +'    </td>'
		+ '<td><div id="propricechange'+$aw_i+'"><input name="proprice'+$aw_i+'" id="proprice'+$aw_i+'" value="0" size="3"  class="getprototal aw_m aw_mt aw_pp wd50  numberclic enteraction numberinput" type="text" tabindex="'+$tabindexnum+'" /></div></td>'
		+ '<td><input name="pronum'+$aw_i+'" id="pronum'+$aw_i+'" value="1" size="3"  class="getprototal aw_m aw_mt aw_pp wd50 numberclic enteraction numberinput" type="text" tabindex="'+$tabindexnum+'" /></td>';

		if(productDiscountSetting == 0)
		{
			$addedRow += '<td><input name="prodis'+$aw_i+'" id="prodis'+$aw_i+'" value="0"  size="3" class="getprototal aw_m aw_mt aw_in wd50 numberonly enteraction numberinput" type="text" tabindex="'+$tabindexnum+'" /></td>';
		}
	
		$addedRow += '<td class="aw_totalprice"><div id="prototal'+$aw_i+'" class="aw_mt">0</div></td>'
				+ '<input name="hidden_prototal'+$aw_i+'" id="hidden_prototal'+$aw_i+'" type="hidden" value="0" /> '
				+ '<td><p class="aw_mf"><a id="remove'+$aw_i+'" class="removeproduct"><img alt="" src="../views/default/images/close.png" /></p></a></td>'
				+ '</tr>';
		
		//add the new row with itration and with all propperties	
		$("#containerpros").append($addedRow);
			
		$(".numberinput").forceNumeric();
		
		// varaible to contains the common itration
		var n = $aw_i ;
		var tbindexn = $tabindexnum;
		
		//action in change of created dropdown list  to load the price		 
		$("#product"+n).chosen().change( function() {
			
			  //here  will get the price for every product
			  //the selected value in drop down list
			  var theselectedvalue = $(this).val();
			  //getProductPrice(theselectedvalue,n,0);
			  var returnBillFlag = 0; 
	 		
			 //using the load method to load the price
			  $("#propricechange"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
	
			  $('#unitDiv'+n).load('buyBillControllerAjax.php?do=units&&return='+returnBillFlag+'&itrs='+n+'&tabindex='+tbindexn+'&productid='+theselectedvalue+'',function() {
				   $("#productUnitsDiv").empty();
				   $("#unitDiv"+n+" option").clone().appendTo("#productUnitsDiv");
		 
				  $('#propricechange'+n).load(''+productpricepagename+'?itrs='+n+'&tabindex='+tbindexn+'&productid='+theselectedvalue+'',function() {
	
			
					  //here all code that will happend with loading contants
					  //the number of rows of products	
					  var noitr = document.getElementById("hidden_itr").value
					  
					  //to calculate the price and amount with discount
					  calcuproduct(n);
						
					  // get the total price of product
					  totalprice(noitr);
					  
					  totalquantity(noitr);
				  
					  //get the general discount
					  thegeneraldiscount();
					  checkthepayed();
					  //get the general payed
					  thegeneralpayed();
					  
					  // calculate the rest of debt 
					  therestofdebt();
			
					  //populate units
					  //getUnits(n);
					  
					  getUnitPrice(n);
	
					  //add another row if there is no any new rows
					  if($("#product"+noitr).val() != null && $("#product"+noitr).val() != '-1')
					  {
						 $("#addpro").trigger('click');
					  }
					  //load the jquery checker for number only
					 // $.getScript('../views/default/js/head_scripts.js');
					  
				  });	  
			  });
		});

		if(quantityOrParcodeSetting == 0)
		{
			var nold = Number(n)-1;
			$("#pronum"+nold).focus();
		}
		else
		{
			$("#parcode"+n).focus();
		}
	}
		
	
	/************************/
	// get product units
	/************************/
	getUnits = function($itrr)
	{
		$productid = $("#product"+$itrr).val();

		$('#unitDiv'+$itrr).load('buyBillControllerAjax.php?do=units&&itrs='+$itrr+'&productid='+$productid+'',function() {
			//reload the dropdownlist and jquery files	
			////$('select').chosen();
		});
	}

	
	/**************************/
	// the delete action that delete row of products
	/************************/
	$(document).on('click','.removeproduct', function() {
		
		// delete by partents  
		$(this).parent().parent().parent().remove();
		
		// get the itration from itration colum
		$remitr = document.getElementById("hidden_itr").value
		
		// get the total price of product
		totalprice($remitr);
		
		//get the general discount
		thegeneraldiscount();
		checkthepayed();
		//get the general payed
		thegeneralpayed();
		
		// calculate the rest of debt
		therestofdebt();
		
		document.getElementById("hidden_itr").value = Number($remitr) - 1;
		
		//reduce number of products //عدد القطع
//		$("#totalQty").html( Number($remitr) - 1);
		return false;
	});
	
	/************************/
	// calculating the product price
	// on keyup action
	/************************/
	$(document).on('keyup', ".getprototal",function(){
			
		//the id of selected row
		var currentId = $(this).attr('id');
		
		//get the num from this method
		var newword = currentId.slice(0,4);
		
		//the number of ilteration
		var thecolnmu = 0 ;
		
		//see what chase
		switch(newword)
		{
			case "prop":
			  thecolnmu = currentId.substr(8);
			  break;
			case "pron":
			 thecolnmu = currentId.substr(6);
			  break;
			case "prod":
			 thecolnmu = currentId.substr(6);
			  break;  
			default:
			  thecolnmu = 0;
		}

		// get the total of product
		calcuproduct(thecolnmu);

		// get the total price of product
		totalprice($aw_i);
		
		//calculate total quantity
		totalquantity($aw_i);
		
		//get the general discount
		thegeneraldiscount();
		checkthepayed();
		//get the general payed
		thegeneralpayed();
		
		// calculate the rest of debt
		therestofdebt();
			
	});
	/************************/
	
	// here the frist action on frist dropdownlist
	/************************/
	$("#product1").chosen().change( function() {

	  //here get the price of product from ajax
	  //the selected value of drop downlsit
	  var theselectedvalue = $(this).val();
	  var returnBillFlag = 0; 
		
	  //using the load method to load the price	
	  $("#propricechange1").html('<img src="../views/default/images/loader/6.gif" alt="">');		  
	
	  $('#unitDiv1').load('buyBillControllerAjax.php?do=units&&return='+returnBillFlag+'&itrs=1&tabindex=13&productid='+theselectedvalue+'',function() {
		   $("#productUnitsDiv").empty();
		   $("#unitDiv1 option").clone().appendTo("#productUnitsDiv");
		 
	  $('#propricechange1').load('buyBillControllerAjax.php?return='+returnBillFlag+'&itrs=1&tabindex=13&productid='+theselectedvalue+'',function() {
		  
		  //here all code that will happend with loading contants
		  //the number of rows of products
		  var noitr = document.getElementById("hidden_itr").value

		  // get the total of product
		  calcuproduct(1);

		  // get the total price of product
		  totalprice(noitr);

		  totalquantity(noitr);

		  //get the general discount
		  thegeneraldiscount();
			
			checkthepayed();

		  //get the general payed
		  thegeneralpayed();

		  // calculate the rest of debt
		  therestofdebt();

		  //populate units
		 // getUnits(1);
		getUnitPrice(1);
		
		  //add another row if there is no any new rows
		  if($("#product"+noitr).val() != null && $("#product"+noitr).val() != '-1')
		  {
			 $("#addpro").trigger('click');
		  }
		  //load the jquery checker for number only
		//$.getScript('../views/default/js/head_scripts.js');
	   }); 
	  });

	});

	/************************/
	// get the total price
	/************************/
	totalprice = function($ix)
	{
		// varaible that will carry total price
		var thealltotal = 0;
		var buyed_thealltotal ="";
		var returned_thealltotal ="";
		
		$round_numbers = $("#round_numbers").val();
		
		//loop to sum the all prices
		for($x=1;$x<=$ix;$x++)
		{
			var numco = $x;
			var inputname = "#hidden_prototal"+numco ;
			
			//to make sure that all input is created
			if ($("#hidden_prototal"+numco).length == 0)
			{
			  continue;
			}
			else
			{
			  // sum method
			  buyed_thealltotal = Number(buyed_thealltotal) +  Number(document.getElementById("hidden_prototal"+numco).value)
			}
		}
		
		$return_itr = document.getElementById("hidden_itr_re").value;
		
		//loop to sum the all prices
		for($x=1;$x<=$return_itr;$x++)
		{
			var numco = $x;
			var inputname = "#hidden_prototal_re"+numco ;
			
			//to make sure that all input is created
			if ($("#hidden_prototal_re"+numco).length == 0)
			{
			  continue;
			}
			else
			{
			  // sum method
			  returned_thealltotal = Number(returned_thealltotal) +  Number(document.getElementById("hidden_prototal_re"+numco).value)
			}
		}
		
		//total price
		thealltotal = buyed_thealltotal - returned_thealltotal;
		
			if($round_numbers == 0) //التقريب لأقرب عدد صحيح
			{
				thealltotal = Math.round(thealltotal);
			}
			else //التقريب لأقرب رقمين
			{
				thealltotal = Math.round(thealltotal*100)/100;
			}
	
		//insert the value in div
		$("#gentotal").html(thealltotal);
		document.getElementById("totalbeforediscount").value=thealltotal;
		
		document.getElementById("genpay").value=thealltotal;
	
		
	}
	
	
	/************************/
	// get the total quantity
	/************************/
	totalquantity = function($ixx)
	{
		// variable that will carry total quantity
		var totalQty ="";
		
		//loop to sum the all prices
		for($x=1;$x<=$ixx;$x++)
		{
			var numco = $x;
			var inputname = "pronum"+numco;
			//to make sure that all inputs are created
			if ($("#"+inputname).length == 0)
			{
			  continue;
			}
			else
			{
				if ($("#product"+$x).val() != '-1')
				{//to not calculate the last row's quantity if its empty
				  // sum method
				  totalQty = Number(totalQty) +  Number($("#"+inputname).val());
				}
			}
		}
		
//			//insert the value in div
			$("#totalQty").html(totalQty);
	}
	
	
	/************************/
	// method that calculate discount
	/************************/
	thegeneraldiscount = function()
	{
		//calculate the dicount
		var generalprice = Number($("#gentotal").html());
		var generaldiscount = Number(document.getElementById("gendis").value);
		
		$round_numbers = $("#round_numbers").val();

		//check discount type		
		var discountType = $("#discount_type").val();
		if(discountType == "0") //خصم مباشر
		{
//			if(generaldiscount != 0)//لا تسمح بالسالب في الخصم
//			{
//				if(generaldiscount > generalprice)
//				{//if قيمه الخصم > إجمالى الفاتوره
//					
//					document.getElementById("gendis").value = generalprice;// قيمة الخصم = إجمالى الفاتوره
//					var generaldiscount = document.getElementById("gendis").value;
//					var netprice = 0; // المبلغ بعد الخصم = 0
//				}
//				else
//				{//حساب الخصم
//					var netprice = Number(generalprice) - Number(generaldiscount);
//				}
//			}
//			else
//			{//حساب الخصم
				var netprice = Number(generalprice) - Number(generaldiscount);
//			}
		}
		else if(discountType == "1") // خصم بنسبة مئوية
		{
			if(generaldiscount > 100)
			{//حتى لا يتعدي 100% من إجمالي الفاتورة
				document.getElementById("gendis").value=100;
				var generaldiscount = document.getElementById("gendis").value;
			}
		
			var resultdiscountbefore = generaldiscount / 100;
			var resultdiscount = resultdiscountbefore * generalprice;
			var netprice = generalprice - resultdiscount;

		}
									
			if($round_numbers == 0) //التقريب لأقرب عدد صحيح
			{
				netprice = Math.round(netprice);
			}
			else //التقريب لأقرب رقمين
			{
				netprice = Math.round(netprice*100)/100;
			}
	
		$("#gen2total").html(netprice); // المبلغ بعد الخصم
		document.getElementById("totalafterdiscount").value=netprice;
	}
	/***************************/
	
	
	/************************/
	// method that calculate discount if user changed discount type after entering discount value
	/************************/
	$("#discount_type").chosen().change( function() {
			
			$("#gendis").trigger('keyup'); //trigger event
		});
	/***************************/
	
	
	/************************/
	// general pay , calaclution in key up
	/************************/
	$(document).on('keyup', "#genpay",function(){
		checkthepayed();
		//get the general payed		
		thegeneralpayed();
		
		// calculate the rest of debt
		therestofdebt();

		//checkthepayed();
	});
	/************************/


	/**********************/
	// calculate the general payed
	/************************/
	thegeneralpayed = function()
	{
		var netprice = $("#gen2total").html();
		var generalpayed = document.getElementById("genpay").value;
		var discountValue = Number(document.getElementById("gen2total").html);
		
		var resultpayed = netprice - generalpayed;
		
		$round_numbers = $("#round_numbers").val();
		if($round_numbers == 0) //التقريب لأقرب عدد صحيح
		{
			resultpayed = Math.round(resultpayed);
		}
		else //التقريب لأقرب رقمين
		{
			resultpayed = Math.round(resultpayed*100)/100;
		}
		
		$("#gen3total").html(resultpayed);
	}

	/*$(document).on("keyup","#genpay",function(){
		checkthepayed();
		thegeneralpayed();
		therestofdebt();	
	});*/
	/**********************/
	
	
	/************************/
	//calculate the rest of debt
	/************************/
	therestofdebt = function()
	{
		var generalpayed = document.getElementById("genpay").value;
		var debt = document.getElementById("hidden_debt").value;
		var resultpayed = $("#gen3total").html();
		var therestdebt = Number(debt) + Number(resultpayed) ;
		
		$round_numbers = $("#round_numbers").val();
		if($round_numbers == 0) //التقريب لأقرب عدد صحيح
		{
			therestdebt = Math.round(therestdebt);
		}
		else //التقريب لأقرب رقمين
		{
			therestdebt = Math.round(therestdebt*100)/100;
		}
		
		$("#gen4total").html(therestdebt);

		document.getElementById("supplierdebtafter").value=therestdebt;
	}
	/************************/
	
	
	/************************/
	// calculate general discount
	/***********************/
	$(document).on('keyup',"#gendis", function(){
				
		//get the general discount
		thegeneraldiscount();
		checkthepayed();
		//get the general payed
		thegeneralpayed();
		
		// calculate the rest of debt
		therestofdebt();
		
		checkthepayed();
	});
	/**********************/
	
	
	/**********************/
	//action of loading the dropdwonlist with new record
	/***********************/
	// the action will determine later
	$("#suppliernotuse").chosen().change( function() {
	
	  var couof = $aw_i ;
	  for($noof=1 ; $noof < couof ; $noof++)
	  {
		  $("#productdiv"+$noof).html('<img src="../views/default/images/loader/6.gif" alt="">');		  
		  $('#productdiv'+$noof).load('test.php?itrs='+$noof+'&id=15',function() {
			  ////$('select').chosen();
			  $("select").trigger("liszt:updated");
		  });
	  }
	  //document.getElementById("#product1").selected = 1;
	});
	/**********************/


	/**********************/
	// action of edit debt 
	/************************/
	$("#editdebt").click( function() {
			
	  //here the code
	  var theselectedvalue = document.getElementById("proprice1").value;
	  $("#debt").html('<img src="../views/default/images/loader/6.gif" alt="">');		  
	  $('#debt').load('test.php?itrs=1&id='+theselectedvalue+'',function() {
		  
		  $("#editdebt").css("display", "none");
	  }); 
	});
	/************************/
	
	
	/**********************/
	// the main method to calucalte products price
	/***************************/
	calcuproduct = function(thecolnmux)
	{
		var price = Number(document.getElementById("proprice"+thecolnmux).value);
		var amount = Number(document.getElementById("pronum"+thecolnmux).value);
		var productTotal = Number(document.getElementById("hidden_prototal"+thecolnmux).value);//إجمالي سعر المنتج

		var pricebefore = price * amount ;

		var discountbefore = Number(document.getElementById("prodis"+thecolnmux).value);

		//if(discountbefore > 100)
		if(discountbefore > productTotal)
		{
			//document.getElementById("prodis"+thecolnmux).value=100;
			document.getElementById("prodis"+thecolnmux).value = pricebefore;
			var discountbefore = document.getElementById("prodis"+thecolnmux).value;
			document.getElementById("hidden_prototal"+thecolnmux).value = 0;
			$("#prototal"+thecolnmux).html(0);
		}
		else
		{
			//var discountnum = discountbefore / 100 ;
			//var discount  = pricebefore * discountnum;
			//var totalprice = pricebefore - discount;
			var totalprice = pricebefore - discountbefore; //خصم مباشر
			$round_numbers = $("#round_numbers").val();
			if($round_numbers == 0) //التقريب لأقرب عدد صحيح
			{
				document.getElementById("hidden_prototal"+thecolnmux).value = Math.round(totalprice);
				totalprice = Math.round(totalprice);
			}
			else //التقريب لأقرب رقمين
			{
				document.getElementById("hidden_prototal"+thecolnmux).value = Math.round(totalprice*100)/100;
				totalprice = Math.round(totalprice*100)/100;
			}
			$("#prototal"+thecolnmux).html(totalprice);
		}
	}
	/***************************/
	
	
	/**********************/
	//use enter action do new row
	/*****************************/
	//$(document+ ":not(#product1_chzn a.chzn-single)").keypress(function(e) {
	$(document).on( 'keypress',".enteraction",function(e) {

		if(e.which == 13) {
			//add the new row with itration and with all propperties	
			addrow($aw_i,$tabindexnum);
			
			//here to make focus in dropdown list
			$('.chzn-single').focus(function(e){
				e.preventDefault();
			});
			$('#product'+$aw_i+'_chzn a.chzn-single').focus();
			
			// fill the iltration filed with common iltration
			document.getElementById("hidden_itr").value = $aw_i ;
				
			// incrementaion of row number and tab index		
			$aw_i++
			$tabindexnum++ ;
			
			//reload the dropdownlist and jquery files	
			////$('select').chosen();
			//$.getScript('../views/default/js/head_scripts.js');
			
			//here to make focus in dropdown list
			//$('.chzn-drop .chzn-search input[type="text"]').focus();
			//$('.chzn-container').addClass('chzn-container-active');

			return false;
		}
	});
	/*****************************/ 
	
	
	/**********************/
	//to use enter and click to submit the form 
	/*******************************/
	$("#billsure").keypress(function(e) {
		if(e.which == 13) {
			$('#billform').submit();
		}
	});
	/******************************/
	
	
	/**********************/
	// using esc to delete row
	/*****************************/
	$(document).keypress(function(e) {
		
		var code = (e.keyCode ? e.keyCode : e.which);
		//to stop the submit of the form
		if(e.which == 13) {
			
			e.preventDefault();
		}
		if(code == 114)
		{
			print_Custom('mycustomheader');
			this.print(false);
			return false; 
		}
		if(code == 27){
        
			$trno = $("#containerpros tr").length -1;
			//alert($trno);
			if($trno != 1)
			{
				// delete by partents  
				$('#containerpros tr:last').remove();
				
				// get the itration from itration colum
				$remitr = document.getElementById("hidden_itr").value
				
				// get the total price of product
				totalprice($remitr);
				
				//get the general discount
				thegeneraldiscount();
				checkthepayed();
				//get the general payed
				thegeneralpayed();
				
				// calculate the rest of debt
				therestofdebt();
				
			}
			return false;
        }
	});
	/*******************************/
	
	/**********************/
	//
	/**********************/
	checkthepayed=function(){
		
		var netpriceto = Math.abs($("#gen2total").html()); //المبلغ بعد الخصم
		var generalpayedto = Math.abs(document.getElementById("genpay").value); //المدفوع
		var generaldiscountto = Math.abs(document.getElementById("gendis").value); // قيمة الخصم
		var genetalpriceto = Math.abs($("#gentotal").html()); //إجمالي الفاتورة
		
		if(generaldiscountto > 0)
		{
			if(Number(generalpayedto) > Number(netpriceto))
			{
				document.getElementById("genpay").value=netpriceto;
			}
		}
		else
		{
			if( Number(generalpayedto) >  Number(genetalpriceto) && generaldiscountto != 0)
			{
				document.getElementById("genpay").value = genetalpriceto;
			}
			
		}
		
		 if(netpriceto == 0)
		{
			document.getElementById("genpay").value=0;
			$("#genpay").attr("readonly",true);	
			$("#gen3total").html(0);
			
			//calculate total debt
			therestofdebt();
			
		}
		else
		{
			$("#genpay").attr("readonly",false);	
		}
	}
	/*******************************/
	
	
	/**********************/
	//action of store dropdownlist
	/**********************/
/*	$("#storeId").chosen().change( function() {
			
		  var theselectedvalue = $(this).val();
		  $("#productdiv1").html('<img src="../views/default/images/loader/6.gif" alt="">');		  
		  $('#productdiv1').load(''+storepagename+'?storeid='+theselectedvalue+'',function() {
			  $("#addrowcreated").empty();
			  $("#productdiv1 option").clone().appendTo("#addrowcreated");
			  //$('select').chosen();
		  }); 
	});
*/


//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////

	//to start the itration with default value // 1
	document.getElementById("hidden_itr_re").value = 1;
	
	//the common itration and the start // 2
	$aw_i_re = 2;
	
	//the tabindex to increment in dynmaic load
	$tabindexnum_re = 15;
	
	
	//add new row in bill 
	//on click the add button 
	/************************/
	$("#addpro_re").click(function() {

		return_addrow($aw_i_re,$tabindexnum_re);

		// fill the iltration filed with common iltration
		document.getElementById("hidden_itr_re").value = $aw_i_re ;
			
		// incrementaion of row number and tab index		
		$aw_i_re++
		$tabindexnum_re++ ;
				
		//reload the dropdownlist and jquery files	
		//$('select').chosen();
		return false;
	});
	/************************/

	
	//add new row in bill
	/**************************/
	return_addrow = function($aw_i_re,$tabindexnum_re)
	{
		var parcodeSetting = $("#parcodeSetting").val();
		var noteSetting = $("#noteSetting").val();
		var productDiscountSetting = $("#productDiscountSetting").val();
		var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();
		
		$addedRow = '<tr class="aw_td">';

		if(parcodeSetting == 0)
		{
			$addedRow += ' <td><input name="parcode_re'+$aw_i_re+'" type="text" id="parcode_re'+$aw_i_re+'" size="3"  onkeypress="getreturnproductbyParcode(event,this.value, '+$aw_i_re+');" autocomplete="off"/></td>';
		}
	
		$addedRow +=  '<td>'
		+ '<div id="productdiv_re'+$aw_i_re+'" class="aw_width aw_mt5">'
		+ '<select id="product_re'+$aw_i_re+'" name="product_re'+$aw_i_re+'" data-placeholder="اختر" class="chzn-select aw_m1 chosenproduct" tabindex="'+$tabindexnum_re+'">'
		+ $("#addrowcreated").html()
		+ '</select></div></td>';
		
		if(noteSetting == 0)
		{
			$addedRow += ' <td>'
        +'    <input name="note_re'+$aw_i_re+'" id="note_re'+$aw_i_re+'" size="3"  type="text" />'
        +'    </td>' ;
		}
		
		$addedRow += '    <td>'
		+'  <div id="unitDiv_re'+$aw_i_re+'">'
        +'    <select name="unitId_re'+$aw_i_re+'" id="unitId_re'+$aw_i_re+'" onchange="return_getUnitPrice('+$aw_i_re+');"  data-placeholder="اختر" class="chzn-select aw_m1 chosenproduct" tabindex="122">>'
        +'    </select>'
        +'    </div>'
        +'    </td>'
        +'<td><div id="propricechange_re'+$aw_i_re+'"><input name="proprice_re'+$aw_i_re+'" id="proprice_re'+$aw_i_re+'" size="3"  value="0" class="return_getprototal aw_m aw_mt aw_pp wd50  numberclic enteraction numberinput" type="text" tabindex="'+$tabindexnum_re+'" /></div></td>'
		+ '<td><input name="pronum_re'+$aw_i_re+'" id="pronum_re'+$aw_i_re+'" value="1" size="3"  class="return_getprototal aw_m aw_mt aw_pp wd50 numberclic enteraction numberinput" type="text" tabindex="'+$tabindexnum_re+'" /></td>'
		;

		if(productDiscountSetting == 0)
		{
			$addedRow += '<td><input name="prodis_re'+$aw_i_re+'" id="prodis_re'+$aw_i_re+'" value="0" size="3"  class="return_getprototal aw_m aw_mt aw_i_ren wd50 numberonly enteraction numberinput" type="text" tabindex="'+$tabindexnum_re+'" /></td>';
		}
	
		$addedRow +='<td class="aw_totalprice"><div id="prototal_re'+$aw_i_re+'" class="aw_mt">0</div></td>'
		+ '<input name="hidden_prototal_re'+$aw_i_re+'" id="hidden_prototal_re'+$aw_i_re+'" type="hidden" value="0" /> '
		+ '<td><p class="aw_mf"><a id="remove_re'+$aw_i_re+'" class="removeproduct_re"><img alt="" src="../views/default/images/close.png" /></p></a></td>'
		+ '</tr>';
		
		//add the new row with itration and with all propperties	
		$("#containerpros_re").append($addedRow);
			
		$(".numberinput").forceNumeric();
		
		// varaible to contains the common itration
		var n = $aw_i_re ;
		var tbindexn_re = $tabindexnum_re;
		
		//action in change of created dropdown list  to load the price		 
		$("#product_re"+n).chosen().change( function() {
			
			  //here  will get the price for every product
			  //the selected value in drop down list
			  var theselectedvalue = $(this).val();
			  //getProductPrice(theselectedvalue,n,0);
			  	
	 		 //using the load method to load the price
			  $("#propricechange_re"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
	
			  $('#unitDiv_re'+n).load('buyBillControllerAjax.php?do=units&&return=1&itrs='+n+'&tabindex='+tbindexn_re+'&productid='+theselectedvalue+'',function() {
				   $("#productUnitsDiv").empty();
				   $("#unitDiv_re"+n+" option").clone().appendTo("#productUnitsDiv");
		 
			  $('#propricechange_re'+n).load(''+productpricepagename+'?return=1&itrs='+n+'&tabindex='+tbindexn_re+'&productid='+theselectedvalue+'',function() {

		
				  //here all code that will happend with loading contants
				  //the number of rows of products	
				  var return_itr = document.getElementById("hidden_itr_re").value
				 
						
				  // get the total of product
				  return_calcuproduct(n);
				  
				 $itr = document.getElementById("hidden_itr").value
				  // get the total price of product
				  totalprice($itr);
		
				  return_totalquantity(return_itr);
		
				  //get the general discount
				  thegeneraldiscount();
		
				  //get the general payed
				 // return_thegeneralpayed();
				 checkthepayed();
				thegeneralpayed();
				  // calculate the rest of debt
				 return_therestofdebt();
		
				  //populate units
				 // getUnits_re(n);
				  
				  return_getUnitPrice(n);
				  
				  //add another row if there is no any new rows
				  if($("#product_re"+return_itr).val() != null && $("#product_re"+return_itr).val() != '-1')
				  {
					 $("#addpro_re").trigger('click');
				  }
				  //load the jquery checker for number only
				 // $.getScript('../views/default/js/head_scripts.js');
				  
			})	
			  });
		});
		
		if(quantityOrParcodeSetting == 0)
		{
			var nold = Number(n)-1;
			$("#pronum_re"+nold).focus();
		}
		else
		{
			$("#parcode_re"+n).focus();
		}

	}
		
	
	/************************/
	// get product units
	/************************/
	var getUnits_re = function($itrr)
	{
		$productid = $("#product_re"+$itrr).val();

		$('#unitDiv_re'+$itrr).load('buyBillControllerAjax.php?do=units&return=1&itrs='+$itrr+'&productid='+$productid+'',function() {
			//reload the dropdownlist and jquery files	
			//$('select').chosen();
		});
	}

	
	/************************/
	// calculating the product price
	// on keyup action
	/************************/
	$(document).on('keyup', ".return_getprototal",function(){
			
			
		//the id of selected row
		var currentId_re = $(this).attr('id');

		//get the num from this method
		var newword = currentId_re.slice(0,4);

		//the number of ilteration
		var thecolnmu_re = 0 ;
		
		//see what chase
		switch(newword)
		{
			case "prop":
			  thecolnmu_re = currentId_re.substr(12);
			  break;
			case "pron":
			 thecolnmu_re = currentId_re.substr(9);
			  break;
			case "prod":
			 thecolnmu_re = currentId_re.substr(9);
			  break;  
			default:
			  thecolnmu_re = 0;
		}

		// get the total of product
		return_calcuproduct(thecolnmu_re);
		
		//get buyed products iteration
		 $itr = document.getElementById("hidden_itr").value
		// get the total price of product
		totalprice($itr);

		//calculate total quantity
		return_totalquantity($aw_i_re);

		//get the general discount
		thegeneraldiscount();
		checkthepayed();
		//get the general payed
		thegeneralpayed();
		
		// calculate the rest of debt
		//therestofdebt();
		return_therestofdebt();
		
		//checkthepayed();
		
		////////////////////////
			
	});
	/************************/
	
	// here the frist action on frist dropdownlist
	/************************/
	$("#product_re1").chosen().change( function() {
			 
	  //here get the price of product from ajax
	  //the selected value of drop downlsit
	  var theselectedvalue = $(this).val();
		
	  //using the load method to load the price	
	  $("#propricechange_re1").html('<img src="../views/default/images/loader/6.gif" alt="">');		  
	
	  $('#unitDiv_re1').load('buyBillControllerAjax.php?do=units&&return=1&itrs=1&tabindex=13&productid='+theselectedvalue+'',function() {
		   $("#productUnitsDiv").empty();
		   $("#unitDiv_re1 option").clone().appendTo("#productUnitsDiv");
	
	  $('#propricechange_re1').load(''+productpricepagename+'?return=1&itrs=1&tabindex=13&productid='+theselectedvalue+'',function() {
		  
		  //here all code that will happend with loading contants
		  //the number of rows of products
		  var return_itr = document.getElementById("hidden_itr_re").value
		  
		  // get the total of product
		  return_calcuproduct(1);
		  
		 $itr = document.getElementById("hidden_itr").value
		  // get the total price of product
		  totalprice($itr);

		  return_totalquantity(return_itr);

		  //get the general discount
		  thegeneraldiscount();

		  //get the general payed
		 // return_thegeneralpayed();
		 checkthepayed();
		thegeneralpayed();
		  // calculate the rest of debt
		 return_therestofdebt();

		  //populate units
		  //getUnits_re(1);

			return_getUnitPrice(1);

		  //add another row if there is no any new rows
		  if($("#product_re"+return_itr).val() != null && $("#product_re"+return_itr).val() != '-1')
		  {
			 $("#addpro_re").trigger('click');
		  }
		  //load the jquery checker for number only
		  //$.getScript('../views/default/js/head_scripts.js');
	   }); 
	  });
		  
	});
	
		
	/**************************/
	// the delete action that delete row of products
	/************************/
	$(document).on('click','.removeproduct_re', function() {
		
		// delete by partents  
		$(this).parent().parent().parent().remove();
		
		// get the itration from itration colum
		$remitr = document.getElementById("hidden_itr_re").value
		$itr = document.getElementById("hidden_itr").value
		// get the total price of product
		totalprice($itr);
		//return_totalprice($remitr);
		//get the general discount
		thegeneraldiscount();
	checkthepayed();
		//get the general payed
		return_thegeneralpayed();
		
		// calculate the rest of debt
		return_therestofdebt();
		
		document.getElementById("hidden_itr_re").value = Number($remitr) - 1;
		//reduce number of products //عدد القطع
//		$("#returnTotalQty").html( Number($remitr) - 1);
		return false;
	});
	

	/************************/
	//calculate the rest of debt
	/************************/
	return_therestofdebt = function()
	{
		//alert("else");
		var generalpayed = document.getElementById("genpay").value;//المدفوع
		var debt = document.getElementById("hidden_debt").value;//دين المورد
		//Number($("#debt").html()); //
		var resultpayed = $("#gen3total").html();//المتبقي
		
		var therestdebt = Number(debt) + Number(resultpayed) ;//إجمالي المديونية
		$round_numbers = $("#round_numbers").val();
		if($round_numbers == 0) //التقريب لأقرب عدد صحيح
		{
			therestdebt = Math.round(therestdebt);
		}
		else //التقريب لأقرب رقمين
		{
			therestdebt = Math.round(therestdebt*100)/100;
		}
		//alert("المدفوع: "+generalpayed+"   دين: "+debt +"  المتبقي: "+resultpayed);
		//alert("إجمالي المديونية: "+therestdebt);
		$("#gen4total").html(therestdebt);
		
		document.getElementById("supplierdebtafter").value=therestdebt;
	}
	/************************/

	
	/************************/
	// get the total quantity
	/************************/
	return_totalquantity = function($ixx)
	{
		// variable that will carry total quantity
		var totalQty ="";
		
		//loop to sum the all prices
		for($x=1;$x<=$ixx;$x++)
		{
			var numco = $x;
			var inputname = "pronum_re"+numco;
			//to make sure that all inputs are created
			if ($("#"+inputname).length == 0)
			{
			  continue;
			}
			else
			{
				if ($("#product_re"+$x).val() != '-1')
				{//to not calculate the last row's quantity if its empty
				  // sum method
				  totalQty = Number(totalQty) +  Number($("#"+inputname).val());
				}
			}
		}
		
//		//insert the value in div
		$("#returnTotalQty").html(totalQty);
	}
	

	/**********************/
	// the main method to calucalte products price
	/***************************/
	return_calcuproduct = function(thecolnmux)
	{
		var price = Number(document.getElementById("proprice_re"+thecolnmux).value);
		var amount = Number(document.getElementById("pronum_re"+thecolnmux).value);
		var productTotal = Number(document.getElementById("hidden_prototal_re"+thecolnmux).value);//إجمالي سعر المنتج
	
		var pricebefore = price * amount ;
		//alert("price: "+price+"  amount: "+amount+"  productTotal: "+productTotal+"   pricebefore: "+pricebefore);
		var discountbefore = Number(document.getElementById("prodis_re"+thecolnmux).value);

		if(discountbefore > productTotal)
		{
			document.getElementById("prodis_re"+thecolnmux).value = pricebefore;
			var discountbefore = document.getElementById("prodis_re"+thecolnmux).value;
			document.getElementById("hidden_prototal_re"+thecolnmux).value = 0;
			$("#prototal_re"+thecolnmux).html(0);
		}
		else
		{
			var return_totalprice = pricebefore - discountbefore; //خصم مباشر
			document.getElementById("hidden_prototal_re"+thecolnmux).value = return_totalprice;
			$round_numbers = $("#round_numbers").val();
			if($round_numbers == 0) //التقريب لأقرب عدد صحيح
			{
				return_totalprice = Math.round(return_totalprice);
			}
			else //التقريب لأقرب رقمين
			{
				return_totalprice = Math.round(return_totalprice*100)/100;
			}
			
			$("#prototal_re"+thecolnmux).html(return_totalprice);
		}
	}
	/***************************/
	
	 /**********************/
	 //
	/**********************/
	return_thegeneralpayed = function(){
		
		var netpriceto = $("#gen2total").html();
		var generalpayedto = document.getElementById("genpay").value;
		var generaldiscountto = document.getElementById("gendis").value;
		var genetalpriceto = $("#gentotal").html();
		
		if(generaldiscountto > 0)
		{
			if(Number(generalpayedto) > Number(netpriceto))
			{
				document.getElementById("genpay").value = netpriceto;
			}
		}
		else
		{
			if( Number(generalpayedto) >  Number(genetalpriceto))
			{
				//document.getElementById("genpay").value = genetalpriceto;
				document.getElementById("genpay").value = 0;
			}
		}
	}
	/*******************************/

 $("#supplier").chosen().change( function() {
        
            var filedvalue = document.getElementById("supplier").value;
           
			if(filedvalue == "-2")
			{
				$("#modalLink").click(); //invoke click event of the link
				$("#modalLink").cs
			}
	
			return false;
        
        });
		
		
		
	/////////////////////End////////////////
	});
	/**********************/

function submitSupplier()
{
	var sup_textDetails = document.getElementById("sup_textDetails").value;
	var sup_txtAddress = document.getElementById("sup_txtAddress").value;
	var sup_txtDebt = document.getElementById("sup_txtDebt").value;
	var sup_txtName = document.getElementById("sup_txtName").value;
	var sup_txtPhone = document.getElementById("sup_txtPhone").value;
	
	$("#preloader").html('<img src="{$path}/assets/pre-loader/Fading squares.gif">');
	$.post("cardAjaxController.php?do=add",{sup_txtAddress:sup_txtAddress, sup_textDetails:sup_textDetails, sup_txtDebt:sup_txtDebt, sup_txtName:sup_txtName,  sup_txtPhone:sup_txtPhone},function(result){
		//alert(result);												
		$("#supplier").html(result);
	});	
}


function return_getUnitPrice(n)
{
	  //here  will get the price for every product
	  //the selected value in drop down list
	  var productunitid = $("#unitId_re"+n).val();
	  //var buyPriceBeforeUnit =  $("#proprice"+n).val();
	  var productId =  $("#product_re"+n).val();
	  var tbindexn_re= document.getElementById("unitId_re"+n).getAttribute("tabindex");
			
	  //alert(''+productpricepagename+'?do=unitPrice&itrs='+n+'&qty='+productQty+'&productid='+productId);
	 if(productunitid != '-1')
	 {
	  //using the load method to load the price
	  $("#propricechange_re"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
	  $('#propricechange_re'+n).load(''+productpricepagename+'?do=unitPrice&return=1&itrs='+n+'&tabindex='+tbindexn_re+'&productunitid='+productunitid+'&productid='+productId,function() {

		  //here all code that will happend with loading contants
		  //the number of rows of products	
		  var noitr = document.getElementById("hidden_itr_re").value;
		//alert("return_getUnitPrice");
		//alert("n: "+n);
		  //to calculate the price and amount with discount
		  return_calcuproduct(n);

		  // get the total price of product
		  totalprice(noitr);

		  //get the general discount
		  thegeneraldiscount();
			checkthepayed();
		  thegeneralpayed();

		  // calculate the rest of debt 
		  return_therestofdebt();

	  })	
	 }
}


function supplierDebt(value)
{
	 var theselectedvalue = value;
	if(theselectedvalue != '-1' && theselectedvalue != '-2')
	{
	  $("#debt").html('<img src="../views/default/images/loader/6.gif" alt="">');		  
	  $('#debt').load('buyBillControllerAjax.php?supplierid='+theselectedvalue+'',function() {

			document.getElementById("hidden_debt").value = $('#debt').html();
			therestofdebt();
		  	//$("#editdebt").css("display", "block");
	  }); 
	  // calculate the rest of debt
		//therestofdebt();
		
		//	return_therestofdebt();	
	}
	else if(theselectedvalue == '-2')
	{
		showSupplierModalBox();	
	}
}

	/**********************/
	
function getUnitPrice(n)
{
	  //here  will get the price for every product
	  //the selected value in drop down list
	  var productunitid = $("#unitId"+n).val();
//alert(productunitid);
	if(productunitid != '-1')
	{
		  //var buyPriceBeforeUnit =  $("#proprice"+n).val();
		  var productId =  $("#product"+n).val();
		  var tbindexn= document.getElementById("unitId"+n).getAttribute("tabindex");
				
		  //alert(''+productpricepagename+'?do=unitPrice&itrs='+n+'&qty='+productQty+'&productid='+productId);
		 
		  //using the load method to load the price
		  $("#propricechange"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
		  $('#propricechange'+n).load(''+productpricepagename+'?do=unitPrice&itrs='+n+'&tabindex='+tbindexn+'&productunitid='+productunitid+'&productid='+productId,function() {
		
			  //here all code that will happend with loading contants
			  //the number of rows of products	
			  var noitr = document.getElementById("hidden_itr").value;

			  //to calculate the price and amount with discount
			  calcuproduct(n);
			
			  // get the total price of product
			  totalprice(noitr);
			
			  //get the general discount
			  thegeneraldiscount();
			  
			  checkthepayed();
			 
			  //get the general payed
			  thegeneralpayed();
			  
			  // calculate the rest of debt 
			  therestofdebt();

		  })	
	}
}
	
	//// load product by parcode ///////
	

function getproductbyParcode(e,value,n)
{
	var code = (e.keyCode ? e.keyCode : e.which);
		//to stop the submit of the form
		if(e.which == 13 && value != "")
		 {
			 
			  //here get the price of product from ajax
			  //the selected value of drop downlsit
			  var theselectedvalue = value;
				
				 $.ajax({
				  url: 'buyBillControllerAjax.php?do=parcode&parcode='+theselectedvalue+'',
				  type: "get",
				  success: function(data){
						$productId = data;
						if($productId != 0)//there is a product that is associated with this parcode
						{
		
							$("#product"+n).val($productId);
							$("#product"+n).trigger('liszt:updated');
							$("#product"+n).trigger("change");
						}
				  },
				  error:function(){
					  alert("لقد حدث خطأ أثناء إجراء العملية");
				  }   
				}); 
	
	

		 }
}
	
	
		
	//// load return product by parcode ///////
	

function getreturnproductbyParcode(e,value,n)
{
	var code = (e.keyCode ? e.keyCode : e.which);
		//to stop the submit of the form
		if(e.which == 13 && value != "")
		 {
			 
			  //here get the price of product from ajax
			  //the selected value of drop downlsit
			  var theselectedvalue = value;
				
				 $.ajax({
				  url: 'buyBillControllerAjax.php?do=parcode&parcode='+theselectedvalue+'',
				  type: "get",
				  success: function(data){
						$productId = data;
						if($productId != 0)//there is a product that is associated with this parcode
						{
		
							$("#product_re"+n).val($productId);
							$("#product_re"+n).trigger('liszt:updated');
							$("#product_re"+n).trigger("change");
						}
				  },
				  error:function(){
					  alert("لقد حدث خطأ أثناء إجراء العملية");
				  }   
				}); 
	
	

		 }
}
	
