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

var return_calcuproduct;
var return_totalprice;
var thegeneraldiscount;
var return_thegeneralpayed;
var return_therestofdebt;
var return_addrow;
var return_totalquantity;

jQuery(document).ready(function () {
	//$('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) {
		//add the new row with itration and with all propperties	
		$("#containerpros_re").append('<tr class="aw_td">'
			+ ' <td><input name="parcode_re' + $aw_i_re + '" type="text" id="parcode_re' + $aw_i_re + '" size="10" onchange="getProductPrice(this.value,' + $aw_i_re + ',1)" autocomplete="off"/></td>'
			+ '<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>'

			+ '    <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>'

			+ '</div>'
			+ '</td>'
			+ '<td><div id="propricechange_re' + $aw_i_re + '"><input name="proprice_re' + $aw_i_re + '" id="proprice_re' + $aw_i_re + '" value="0" class="return_getprototal aw_m aw_mt aw_pp wd50  numberclic enteraction" type="text" tabindex="' + $tabindexnum_re + '" /></div></td>'
			+ '<td><input name="pronum_re' + $aw_i_re + '" id="pronum_re' + $aw_i_re + '" value="1" class="return_getprototal aw_m aw_mt aw_pp wd50 numberclic enteraction" type="text" tabindex="' + $tabindexnum_re + '" /></td>'
			+ '<td><input name="prodis_re' + $aw_i_re + '" id="prodis_re' + $aw_i_re + '" value="0" class="return_getprototal aw_m aw_mt aw_i_ren wd50 numberonly enteraction" type="text" tabindex="' + $tabindexnum_re + '" /></td>'
			+ '<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>');


		// varaible to contains the common itration
		var n = $aw_i_re;
		var tbindexn = $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="">');
			$('#propricechange_re' + 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_re").value

				//to calculate the price and amount with discount
				return_calcuproduct(n);

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

				return_totalquantity(noitr);

				//get the general discount
				thegeneraldiscount();

				//get the general payed
				return_thegeneralpayed();

				// calculate the rest of debt 
				return_therestofdebt();

				//populate units
				getUnits_re(n);

				var itr = document.getElementById("hidden_itr_re").value;
				//add another row if there is no any new rows
				if ($("#product_re" + itr).val() != null && $("#product_re" + itr).val() != '-1') {
					$("#addpro_re").trigger('click');
				}
				//load the jquery checker for number only
				// $.getScript('../views/default/js/head_scripts.js');

			})
		});

	}


	/************************/
	// get product units
	/************************/
	var getUnits_re = function ($itrr) {
		$productid = $("#product_re" + $itrr).val();
		var supplier = $('#supplier').val();
		$('#unitDiv_re' + $itrr).load('buyBillControllerAjax.php?do=units&&itrs=' + $itrr + '&productid=' + $productid + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val(), 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 = $(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":
				// if ($('#enablequantityfractions').val() != 1) {
				//     if ($(this).val() % 1 > 0)
				//         $(this).val(Math.round($(this).val())).keyup();
				// }
				thecolnmu = currentId.substr(6);
				break;
			case "prod":
				thecolnmu = currentId.substr(6);
				break;
			default:
				thecolnmu = 0;
		}

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

		// get the total price of product
		return_totalprice($aw_i_re);

		//calculate total quantity
		return_totalquantity($aw_i_re);

		//get the general discount
		thegeneraldiscount();

		//get the general payed
		return_thegeneralpayed();

		// calculate the rest of debt
		return_therestofdebt();

	});
	/************************/

	// 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="">');
		$('#propricechange_re1').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_re").value

			// get the total of product
			return_calcuproduct(1);
			alert(noitr);
			// get the total price of product
			return_totalprice(noitr);
			alert(noitr);
			return_totalquantity(noitr);
			alert(noitr);
			//get the general discount
			thegeneraldiscount();
			alert(noitr);
			//get the general payed
			return_thegeneralpayed();
			alert(noitr);
			// calculate the rest of debt
			return_therestofdebt();
			alert(noitr);
			//populate units
			getUnits_re(1);
			alert(noitr);
			var itr = document.getElementById("hidden_itr_re").value;
			//add another row if there is no any new rows
			if ($("#product_re" + itr).val() != null && $("#product_re" + 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

		// get the total price of product
		return_totalprice($remitr);

		//get the general discount
		thegeneraldiscount();

		//get the general payed
		return_thegeneralpayed();

		// calculate the rest of debt
		return_therestofdebt();

		return false;
	});


	/************************/
	//calculate the rest of debt
	/************************/
	return_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;
		}
	}
	/************************/


	/************************/
	// get the total price
	/************************/
	return_totalprice = function ($ix) {
		// varaible that will carry total price
		var thealltotal = 0;
		var total = 0;
		var return_total = 0;

		var rowCount = $('#containerpros tr').length;

		if (rowCount == 2) //فاتورة المبيعات ليست فيها أي منتجات
		{
			//loop to sum all prices
			for ($x = 1; $x <= $ix; $x++) {
				var numco = $x;

				//to make sure that all input is created
				if ($("#hidden_prototal_re" + numco).length == 0) {
					continue;
				}
				else {
					// sum method
					thealltotal = Number(thealltotal) + Number(document.getElementById("hidden_prototal_re" + numco).value)
					$("#gentotal").html(thealltotal);

					document.getElementById("totalbeforediscount").value = thealltotal;

				}
			}
			//insert the value in div
			$("#gentotal").html(thealltotal);

			document.getElementById("totalbeforediscount").value = thealltotal;
		}
		else {
			//loop to sum all prices
			for ($x = 1; $x <= $ix; $x++) {
				var numco = $x;

				//to make sure that all input is created
				if ($("#hidden_prototal" + numco).length == 0 && $("#hidden_prototal_re" + numco).length == 0) {
					continue;
				}
				else {
					// sum method
					total = Number(total) + Number(document.getElementById("hidden_prototal" + numco).value)
					return_total = Number(return_total) + Number(document.getElementById("hidden_prototal_re" + numco).value)
				}
			}
			thealltotal = total - return_total;
			//insert the value in div
			$("#gentotal").html(thealltotal);

			document.getElementById("totalbeforediscount").value = thealltotal;
		}
	}


	/************************/
	// 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) {
		alert(document.getElementById("proprice_re" + thecolnmux).value);
		var price = Number(document.getElementById("proprice_re" + thecolnmux).value);
		alert("price: " + price);
		var amount = Number(document.getElementById("pronum_re" + thecolnmux).value);
		alert("amount: " + amount);
		var productTotal = Number(document.getElementById("hidden_prototal_re" + thecolnmux).value);//إجمالي سعر المنتج

		var pricebefore = price * amount;
		alert("pricebefore: " + pricebefore);
		alert("productTotal: " + productTotal);
		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;
			$("#prototal_re" + thecolnmux).html(return_totalprice);
		}
	}
	/***************************/


	/**********************/
	// 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_re tr").length - 1;
			//alert($trno);
			if ($trno != 1) {
				// delete by partents  
				$('#containerpros_re tr:last').remove();

				// get the itration from itration colum
				$remitr = document.getElementById("hidden_itr_re").value

				// get the total price of product
				return_totalprice($remitr);

				//get the general discount
				thegeneraldiscount();


				//get the general payed
				return_thegeneralpayed();

				// calculate the rest of debt
				return_therestofdebt();

			}
			return false;
		}
	});
	/*******************************/

	/**********************/
	//
	/**********************/
	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;
			}
		}
	}
	/*******************************/

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

/**********************/

function return_getUnitPrice(n) {
	//here  will get the price for every product
	//the selected value in drop down list
	var productQty = $("#unitId_re" + n).val();
	//var buyPriceBeforeUnit =  $("#proprice"+n).val();
	var productId = $("#product_re" + n).val();
	var tbindexn = document.getElementById("unitId_re" + n).getAttribute("tabindex");

	//alert(''+productpricepagename+'?do=unitPrice&itrs='+n+'&qty='+productQty+'&productid='+productId);

	//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&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_re").value;
		// alert("itr:"+noitr);
		//to calculate the price and amount with discount
		return_calcuproduct(n);

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

		//get the general discount
		thegeneraldiscount();

		return_thegeneralpayed();

		//get the general payed
		return_thegeneralpayed();

		// calculate the rest of debt 
		return_therestofdebt();
	})

}