// 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 totalquantity;

jQuery(document).ready(function(){
	////$('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)
	{
		//add the new row with itration and with all propperties	
		$("#containerpros").append( '<tr class="aw_td">'
		+'<td><a onclick="javascript:showModalBox(this.id);" class="newLink"  id="new'+$aw_i+'">جديد</a></td>'
		+' <td><input name="parcode'+$aw_i+'" type="text" id="parcode'+$aw_i+'" size="10" onchange="getProductPrice(this.value,'+$aw_i+',1)" autocomplete="off"/></td>'
		+ '<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>'
		  
        +'    <td>'
		+'  <div id="unitDiv'+$aw_i+'">'
        +'    <select name="unitId'+$aw_i+'" id="unitId'+$aw_i+'" onchange="getUnitPrice('+$aw_i+');"  data-placeholder="اختر" class="chzn-select aw_m1 chosenproduct" tabindex="122">>'
        +'    </select>'
        +'    </div>'
        +'    </td>'
       
		+ '</div>'
		+ '</td>'
		+ '<td><div id="propricechange'+$aw_i+'"><input name="proprice'+$aw_i+'" id="proprice'+$aw_i+'" value="0" class="getprototal aw_m aw_mt aw_pp wd50  numberclic enteraction" type="text" tabindex="'+$tabindexnum+'" /></div></td>'
		+ '<td><input name="pronum'+$aw_i+'" id="pronum'+$aw_i+'" value="1" class="getprototal aw_m aw_mt aw_pp wd50 numberclic enteraction" type="text" tabindex="'+$tabindexnum+'" /></td>'
		+ '<td><input name="prodis'+$aw_i+'" id="prodis'+$aw_i+'" value="0" class="getprototal aw_m aw_mt aw_in wd50 numberonly enteraction" type="text" tabindex="'+$tabindexnum+'" /></td>'
		+ '<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>');
			
		
		// 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() {
			
                        alert(11);
			  //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"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
			  $('#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();
				  
				  //get the general payed
				  thegeneralpayed();
				  
				  // calculate the rest of debt 
				  therestofdebt();
		
				  //populate units
				  getUnits(n);
				  
				  var itr = document.getElementById("hidden_itr").value ;
				  //add another row if there is no any new rows
				  if($("#product"+itr).val() != null && $("#product"+itr).val() != '-1')
				  {
					 $("#addpro").trigger('click');
				  }
				  //load the jquery checker for number only
				 // $.getScript('../views/default/js/head_scripts.js');
				  
			})	  
		});


		//**************  product unit changed *************************//
				
		//action in change of created dropdown list  to load the price		 
//		$("#unitId"+n).chosen().change( function() {
//		});
		//********************** End product unit changed ********************************//

	}
		
	
	/************************/
	// get product units
	/************************/
	var getUnits = function($itrr)
	{
		$productid = $("#product"+$itrr).val();
                var supplier = $('#supplier').val();
		$('#unitDiv'+$itrr).load('buyBillControllerAjax.php?do=units&&itrs='+$itrr+'&productid='+$productid+ '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val(),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();

		
		//get the general payed
		thegeneralpayed();
		
		// calculate the rest of debt
		therestofdebt();
		
		
		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();
		
		//get the general payed
		thegeneralpayed();
		
		// calculate the rest of debt
		therestofdebt();
			
	});
	/************************/
	
	// here the frist action on frist dropdownlist
	/************************/
	$("#product1").live().change( function() {
		//alert(555);	  
	  //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	
	  $("#propricechange1").html('<img src="../views/default/images/loader/6.gif" alt="">');		  
	  $('#propricechange1').load(''+productpricepagename+'?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();
		  
		  //get the general payed
		  thegeneralpayed();
		  
		  // calculate the rest of debt
		  therestofdebt();
		  
		  //populate units
		  getUnits(1);
		  
    	  var itr = document.getElementById("hidden_itr").value ;
		  //add another row if there is no any new rows
		  if($("#product"+itr).val() != null && $("#product"+itr).val() != '-1')
		  {
			 $("#addpro").trigger('click');
		  }
		  //load the jquery checker for number only
		 // $.getScript('../views/default/js/head_scripts.js');
	   }); 
		  
	});

	
	/************************/
	
	// here the frist action on frist dropdownlist
	/************************/
	$("#parcode1").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	
	  $("#propricechange1").html('<img src="../views/default/images/loader/6.gif" alt="">');		  
	  $('#propricechange1').load('buyBillControllerAjax.php?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);
		
		  //get the general discount
		  thegeneraldiscount();
		  
		  //get the general payed
		  thegeneralpayed();
		  
		  // calculate the rest of debt
		  therestofdebt();
		  
		  //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 ="";
		
		//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
			  thealltotal = Number(thealltotal) +  Number(document.getElementById("hidden_prototal"+numco).value)
			  $("#gentotal").html(thealltotal);
			  
			  document.getElementById("totalbeforediscount").value=thealltotal;
			  
			}
		}
		//insert the value in div
		$("#gentotal").html(thealltotal);
		
		document.getElementById("totalbeforediscount").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);

		//check discount type		
		var discountType = $("#discount_type").val();
		if(discountType == "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 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;
		}
		
		$("#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(){
		
		//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 resultpayed = netprice - generalpayed;
		$("#gen3total").html(resultpayed);
	}

	$(document).on("keyup","#genpay",function(){
		
		thegeneralpayed();
		therestofdebt();	
	});
	/**********************/
	
	
	/************************/
	//calculate the rest of debt
	/************************/
	therestofdebt = function()
	{
		if(billtype == 0)
		{
			var generalpayed = document.getElementById("genpay").value;
			var debt = document.getElementById("hidden_debt").value;
			var resultpayed = $("#gen3total").html();
			var therestdebt = Number(debt) +Number(resultpayed) ;
			$("#gen4total").html(therestdebt);

			document.getElementById("supplierdebtafter").value=therestdebt;
		}
		else if(billtype == 1)
		{
			var generalpayed = document.getElementById("genpay").value;
			var debt = document.getElementById("hidden_debt").value;
			var resultpayed = $("#gen3total").html();
			var therestdebt = Number(debt) -Number(resultpayed) ;
			$("#gen4total").html(therestdebt);
			
			document.getElementById("supplierdebtafter").value=therestdebt;
		}
	}
	/************************/
	
	
	/************************/
	// calculate general discount
	/***********************/
	$(document).on('keyup',"#gendis", function(){
				
		//get the general discount
		thegeneraldiscount();
		
		//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 supplier dropdownlist
	/**********************/
	//$("#supplier").chosen().change( function() {
//		alert("ddd");
//	  var theselectedvalue = $(this).val();
//	  alert(theselectedvalue);
//	  //$("#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();
//
//	});
	/**********************/
	
	
	/**********************/
	// 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; //خصم مباشر
			document.getElementById("hidden_prototal"+thecolnmux).value = totalprice;
			$("#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();
				

				//get the general payed
				thegeneralpayed();
				
				// calculate the rest of debt
				therestofdebt();
				
			}
			return false;
        }
	});
	/*******************************/
	
	/**********************/
	//
	/**********************/
	checkthepayed=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;
			}
		}
	}
	/*******************************/
	
	
	/**********************/
	//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();
		  }); 
	});

	/////////////////////End////////////////
	});


function supplierDebt(value)
{
	 var theselectedvalue = value;

	  $("#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();	
}

	/**********************/
	
function getUnitPrice(n)
{
	  //here  will get the price for every product
	  //the selected value in drop down list
	  var productQty = $("#unitId"+n).val();
	  //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+'&qty='+productQty+'&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;
		 // alert("itr:"+noitr);
		  //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();
	  })	

}
	
////// Adding new product with modal box /////////////

function showModalBox(newLinkId)
{
	$("#productForm").css("display","block");	
	$("#newLinkCurrentId").val(newLinkId);
	
	//extract the number from id. Example: get 1 from new1
	var newLinkCurrentId = $("#newLinkCurrentId").val(); //example: new2
	var st = newLinkCurrentId.substr(3,newLinkCurrentId.length - 1);
	var itr = st;
	//alert(newLinkId);
	//get new product parcode
	var parcode = $("#parcode"+itr).val();
	//check if this operation is editing or adding
	if(parcode != null && parcode != "")
	{
		//alert("in if");
		//get data from producttemp_tbl table
		$.ajax({
			type: 'POST',
			url: 'getProductsFromTempTableAJAX.php?itr='+itr+'&parcode='+parcode,
			data: $("#productInfo").serialize(),
			success: function(data) {
					//alert(data);
					//alert("success");
					//load this exact new product data in the modal box.
					//$("#productForm").fadeIn("fast", function(){
						//$(this).before("<strong>Success! :)</strong>");
					//	setTimeout("$.fancybox.open()", 1000);
						$("#productInfo").html(data);
					//});
			}
        });
	}
	else
	{
		$("#productInfo").html('<table width="60%" border="0" align="center" cellpadding="0" cellspacing="2">'
+'      <tr>'
+'        <td colspan="2" align="center"><strong>إضافة منتج </strong></td>'
+'      </tr>'
+'      <tr>'
+'        <td colspan="2" align="right">&nbsp;</td>'
+'      </tr>'
+'      <tr>'
+'        <td width="74%" align="right"><span id="spryselect1">'
+'          <select name="cat_id" id="cat_id" dir="rtl" style="width:250px">'
+'            <option>-- اختر المنتج الرئيسي--</option>'
+''+        $("#productSelect").html()
  +'        </select>'
    +'      <span class="selectRequiredMsg">*</span></span></td>'
      +'  <td align="right"><strong>المنتج الرئيسي</strong></td>'
    +'  </tr>'
     +' <tr>'
+'        <td align="right"><input name="name" type="text" id="name" size="50"  dir="rtl"/></td>'
+'        <td width="26%" align="right"><strong>الإسم</strong></td>'
+'      </tr>'
+'      <tr>'
+'        <td align="right"><input name="buyprice" type="text" id="buyprice" size="50"  dir="rtl"/></td>'
+'        <td align="right"><strong>سعر الشراء</strong></td>'
+'      </tr>'
+'      <tr>'
+'        <td align="right"><input name="sellPrice" type="text" id="sellPrice" size="50"  dir="rtl"/></td>'
+'        <td align="right"><strong>سعر بيع</strong></td>'
+'      </tr>'
+'      <tr>'
+'        <td align="right"><input name="amount" type="text" id="amount"  dir="rtl" value="1" size="50"/></td>'
+'        <td align="right"><strong>الكميه</strong></td>'
+'      </tr>'
+'      <tr> </tr>'
+'      <tr>'
+'      <input name="newLinkCurrentId" id="newLinkCurrentId" type="hidden" value="" />'
+'      <input type="button" id="cancel" onclick="closeProductForm();" value="إلغاء" />'
+'        <input type="submit" id="insert" onclick="insertIntoTemp();" value="إضافة" />'
+'      </tr>'
+'    </table>');	
		$("#newLinkCurrentId").val(newLinkId);
	}
}


function insertIntoTemp()
{
    
	var newLinkCurrentId = $("#newLinkCurrentId").val(); //example: new2
	var st = newLinkCurrentId.substr(3,newLinkCurrentId.length - 1);
	var itr = st;
	//alert(newLinkCurrentId);
	//document.getElementById('itr').value;
	var totalQuantity = $("#totalquantity").val();
        //alert($('#productInfo').validate().form())
      //   if ($('#productInfo').validate().form())
        {
	//alert("itr:"+itr);
	$.ajax({
			type: 'POST',
			url: 'insertProductsInTempTableAJAX.php?itr='+itr,
			data: $("#productInfo").serialize(),
			success: function(data) {
					//alert(data);
					$("#productForm").fadeOut("fast", function(){
						//$(this).before("<strong>Success! :)</strong>");
						setTimeout("$.fancybox.close()", 1000);
						$("#divnew"+itr).html(data);
						//alert("before before");
						//add new product quantity to tatal quantity
						$("#totalquantity").val(Number(totalQuantity) + Number($("#Qty"+itr).val()));
						//alert("before");
						calRow(itr);	
						//alert("itr: "+itr);
						//empty modal box's inputs' values
						$("#name").val("");
						$("#buyprice").val("");
						$("#sellPrice").val("");
						$("#amount").val("");
						$("#newLinkCurrentId").val("");
						//
						//alert("ddddddd");
					});
			}
        });
    }
}

function UpdateTemp()
{
	//alert("update");
	var newLinkCurrentId = $("#newLinkCurrentId").val(); //product temp id in table
	
	var itr = $("#tempItr").val();
	//document.getElementById('itr').value;
	var totalQuantity = $("#totalquantity").val();
	//alert("itr:"+itr);
	$.ajax({
			type: 'POST',
			url: 'updateProductsInTempTableAJAX.php?itr='+itr+'&id='+newLinkCurrentId,
			data: $("#productInfo").serialize(),
			success: function(data) {
					////alert(data);
					$("#productForm").fadeOut("fast", function(){
						//$(this).before("<strong>Success! :)</strong>");
						setTimeout("$.fancybox.close()", 1000);
						$("#divnew"+itr).html(data);
						////alert("before before");
						//add new product quantity to tatal quantity
						$("#totalquantity").val(Number(totalQuantity) + Number($("#Qty"+itr).val()));
						////alert("before");
						calRow(itr);	
						////alert("itr: "+itr);
						//empty modal box's inputs' values
						$("#name").val("");
						$("#buyprice").val("");
						$("#sellPrice").val("");
						$("#amount").val("");
						$("#newLinkCurrentId").val("");
						//
						////alert("ddddddd");
					});
			}
        });
}

function closeProductForm()
{
	$("#productForm").fadeOut("fast", function(){
		setTimeout("$.fancybox.close()", 1000);
	});
}
////////////////// End adding new product /////////////////////////////////
