$(document).ready(function(){
		var mods 			=	$('#main_page').val();
		var types 			=	$('#main_type').val(); 
		var action 			=	$('#main_action').val();
 
		if(mods=="pricelist" && types=="pricelist" && (action=="edit" || action=="view")){
			load_pricelist();
		}

		$('#current_model').change(function(){
			getDefaultModelValues();
		})   
		
		//PRICELIST DETAIL TABLE
		$('#pricelist_detail_table_add').click(function(e){
			e.preventDefault();
				if(action=="create"){
					getDefaultModelTableValues();
				} 
				var random = Math.floor((Math.random() * 100) + 1);
				loadSelect('detail_terms','.select_random'+random);
//loadSelect('detail_terms','.select_random'+random,'select.select2');
			var htmlrow = ""; 
			htmlrow += '<tr><td><span onClick="removeCurrentRow(this);" class="btn btn-xs btn-danger glyphicon glyphicon-trash"></span></td><td><select onchange="computePF();" class="form-control text-left left pricelist_status" name="pricelist_status[]"><option value="PRE-SELLING">PRE-SELLING</option><option value="RFO">RFO</option><option value="ON-GOING">ON-GOING</option><option value="UP-COMING">UP-COMING</option></select></td><td><div class="div_detail_terms select_random'+random+'"></div></td><td><input maxlength="6" type="text" class="phase form-control text-right" name="phase[]"></td><td><input maxlength="10" type="text" class="form-control text-right block" name="block[]"></td><td><input maxlength="10" type="text" class="form-control text-right lot" name="lot[]"></td><td><select class="form-control text-left left" name="lot_type[]"><option value="">-</option><option value="INNER">Inner</option><option value="END">End</option></select></td><td><input maxlength="5" type="text" class="form-control text-right" name="lot_size[]" onkeypress="return isNumberKey(event)"></td> <td><input maxlength="5"  type="text" class="form-control text-right" name="floor_area[]" onkeypress="return isNumberKey(event)"></td><td><input maxlength="12"  type="text" class="form-control text-right pricelist_contract_price" name="contract_price[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"  onchange="computePF(); computeNetDiscountTCP();"></td><td><select class="form-control text-left left" name="discount_type[]"><option value="">-</option><option value="promo">Promo</option><option value="cash_equity">Cash Equity</option><option value="spot_cash">Spot Cash</option><option value="others">Others</option></select></td><td><input maxlength="12"  type="text" class="form-control text-right discount_amount" name="discount_amount[]" value="" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);computeNetDiscountTCP()" onchange="computeNetDiscountTCP()"></td><td><input maxlength="12"  type="text" class="form-control text-right discount_tcp" name="discount_tcp[]" value="" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td><td><input maxlength="12"  type="text" class="form-control text-right pricelist_loanable_amount" name="loanable_amount[]"  onchange="computePF()" onblur = "javascript:this.value=Comma(this.value);computePF()" onkeypress="return isNumberKey(event)"></td><td><input maxlength="12"  type="text" class="form-control text-right downpayment" name="downpayment[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);computePF()" onchange="computePF()"></td><td><input maxlength="12"  type="text" class="form-control text-right pricelist_pf_net" name="pf_net[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td><td><input maxlength="12" type="text" class="form-control text-right pf_payable" name="pf_payable[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td><td><input maxlength="12" type="text" class="form-control text-right required_gross" name="required_gross[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td><td><input maxlength="12" type="text" class="form-control text-right amortization" name="amortization[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td><td><input type="text" class="form-control text-right remarks" name="remarks[]"></td></tr>';
			
			 
			var rowCount = $('#pricelist_detail_table tr').length;
			 
			if(rowCount>60){
				bootbox.alert('You had reached the maximum limit of rows already.  Please create a new pricelist for continuation.');
			}else{
				$('#pricelist_detail_table').append(htmlrow); 
			}
		});
});
 
//SAVING PRICELIST
function save_pricelist(){
				var pricelist_detail_table  =  $('#pricelist_detail_table input, select').serialize();
				 
				var mods 					=	$('#main_page').val();
				var types 					=	$('#main_type').val(); 
				var action 					=	$('#main_action').val();
				var mainid					=	$('#main_id').val();
				
				var cash_discount			=	$('#pricelist_cash_discount').val();
				var terms					=	$('#pricelist_terms').val();
				var terms_discount			=	$('#pricelist_terms_discount').val(); 
				
				var project					=	$('#current_project').val();
				var model					=	$('#current_model').val();
				//var pricelist_remarks 		=	tinymce.get('pricelist_remarks').getContent();
				var pricelist_remarks 		=	$('#pricelist_remarks').val(); 
				var updated_date			=	$('#pricelist_updated_date').val();
				var reservation_fee			=	$('#pricelist_reservation_fee').val().replace(/,/g, "");
				var phase					=	$('.phase').val();
				var block					= 	$('.block').val();
				var lot						=	$('.lot').val();  
				 
				if(phase!="" && block!="" && lot!=""){ 
					var dataString = pricelist_detail_table+"&current_project="+encodeURIComponent(project)+"&current_model="+encodeURIComponent(model)+"&pricelist_remarks="+encodeURIComponent(pricelist_remarks)+"&pricelist_updated_date="+encodeURIComponent(updated_date)+"&pricelist_reservation_fee="+encodeURIComponent(reservation_fee)+"&action="+encodeURIComponent(action)+"&mainid="+encodeURIComponent(mainid)+"&cash_discount="+encodeURIComponent(cash_discount)+"&terms="+encodeURIComponent(terms)+"&terms_discount="+encodeURIComponent(terms_discount);
					$.post('./ajax/pricelist.php', dataString, function(msg){ 
												var obj	= $.parseJSON(msg); 
												if(obj.output==true){
													bootbox.alert("Successfully Saved ..."); 
													window.setTimeout(function() { window.location.href = 'index.php?pg='+mods+'&type='+types; }, 1000);
												}else{
													bootbox.alert("Failed in saving.");
												}
										});
					  /**/
						/*bootbox.dialog({
							message: "This is a confirmation everything is all correct. It can no longer be changed. Only Admin as authorizer to change any info in the pricelist",
							buttons: {								
								success: {
									label: 'Accept',
									className: 'btn-success'
								},danger: {
									label: 'Back',
									className: 'btn-danger'
								}
							},
							callback: function (result) { 
								alert(result);
								if(result==true){
										$.post('./ajax/pricelist.php', dataString, function(msg){ 
												var obj	= $.parseJSON(msg); 
												if(obj.output==true){
													bootbox.alert("Successfully Saved ..."); 
													window.setTimeout(function() { window.location.href = 'index.php?pg='+mods+'&type='+types; }, 1000);
												}else{
													bootbox.alert("Failed in saving.");
												}
										});
								}
							}
						});*/
						   
						
/*
 $.post('./ajax/pricelist.php', dataString, function(msg){ 
													var obj	= $.parseJSON(msg); 
													if(obj.output==true){
														bootbox.alert("Successfully Saved ..."); 
														//window.setTimeout(function() { window.location.href = 'index.php?pg='+mods+'&type='+types; }, 1000);
													}else{
														bootbox.alert("Failed in saving.");
													}
											});*/

						
						
				}else{
					bootbox.alert("Fields must not be blank");
				}
}

//LOADING PRICELIST
function load_pricelist(){ 
				var mods 			=	$('#main_page').val();
				var types 			=	$('#main_type').val(); 
				var action 			=	$('#main_action').val();
				var mainid			=	$('#main_id').val(); 
				var dataString		=	"action="+encodeURIComponent(action)+"&mainid="+encodeURIComponent(mainid);
						$.post('./ajax/load_pricelist.php', dataString, function(msg){
								var obj	= $.parseJSON(msg);
								var project				=	obj.data[0].project;
								var cash_discount		=	Comma(obj.data[0].cash_discount); 
								var terms				=	obj.data[0].terms; 
								var terms_discount		=	Comma(obj.data[0].terms_discount); 
								var models				=	obj.data[0].model; 
								var pricelist_date		=	obj.data[0].pricelist_date;
								var reservation_fee		=	obj.data[0].reservation_fee;
								var key_code			=	obj.data[0].key_code;
								var remarks2			=	obj.data[0].remarks;  
    							$('#pricelist_cash_discount').val(cash_discount); 
    							$('#pricelist_terms_discount').val(terms_discount); 
    							$('#pricelist_terms').val(terms); 
    							$('#pricelist_updated_date').val(pricelist_date); 
    							$('#pricelist_reservation_fee').val(reservation_fee);
    							$('#key_code').val(key_code);
								$('#pricelist_remarks').text(remarks2); 
								
							//	tinyMCE.get('pricelist_remarks'); 
								if(remarks2!=null || remarks2!=""){
    						//	tinyMCE.activeEditor.setContent(remarks2);
								}
								
								
								
								
    							 
								var detailTable	= "";  
								  
								var details	= $.parseJSON(obj.data[0].details); 

								for(var a=0; a<details.details.length; a++){
 
									var pricelist_status	=	details.details[a].pricelist_status;
									var detail_terms		=	details.details[a].detail_terms;
									var lot_type			=	details.details[a].lot_type;
									var phase				=	details.details[a].phase;
									var block				=	details.details[a].block;
									var lot					=	details.details[a].lot;

									var lot_size			=	details.details[a].lot_size; 
									var floor_area			=	details.details[a].floor_area; 
									//var contract_price		=	details.details[a].contract_price;
									var contract_price		=	Comma(parseFloat(details.details[a].contract_price.replace(/,/g, "")).toFixed(2));
									
									var loanable_amount		=	Comma(parseFloat(details.details[a].loanable_amount.replace(/,/g, "")).toFixed(2));


									var discount_type		=	details.details[a].discount_type;
									var discount_amount		=	Comma(parseFloat(details.details[a].discount_amount.replace(/,/g, "")).toFixed(2));
									var discount_tcp		=	Comma(parseFloat(details.details[a].discount_tcp.replace(/,/g, "")).toFixed(2));
 							  		
 							  		if(isNaN(discount_amount)) {
										var discount_amount = 0.00;
									}

									
 							  		if(isNaN(discount_tcp)) {
										var discount_tcp = 0.00;
									}

 							  		//var loanable_amount		=	details.details[a].loanable_amount;
 
									var loanable_amount		=	Comma(parseFloat(details.details[a].loanable_amount.replace(/,/g, "")).toFixed(2));
									/*if(isNaN(loanable_amount)) {
										var loanable_amount = 0.00;
									}
									*/
								 

									var downpayment			=	Comma(parseFloat(details.details[a].downpayment.replace(/,/g, "")).toFixed(2));
									/*if(isNaN(downpayment)) {
										var downpayment = 0.00;
									}*/
									

									var pf_net				= Comma(parseFloat(details.details[a].pf_net.replace(/,/g, "")).toFixed(2));
									/*if(isNaN(pf_net)) {
										var pf_net = 0.00;
									}*/

									//Comma(pf_payable.toFixed(2))
									var pf_payable			=	details.details[a].pf_payable;
									/*if(isNaN(pf_payable)) {
										var pf_payable = 0.00;
									}*/

									var remarks 			= 	details.details[a].remarks;
									//var required_gross		=	details.details[a].required_gross;
									var required_gross		=	Comma(parseFloat(details.details[a].required_gross.replace(/,/g, "")).toFixed(2));
									 
									/*if(isNaN(required_gross)) {
										var required_gross = 0.00;
									}*/

									//var amortization		=	details.details[a].amortization;
									var amortization		=	Comma(parseFloat(details.details[a].amortization.replace(/,/g, "")).toFixed(2));
									/*if(isNaN(amortization)) {
										var amortization = 0.00;
									}*/
									
									var sel7 = "";
									var sel1 = "";	var sel2 = "";	var sel3 = "";	var sel4 = "";	var sel5 = "";
									if(pricelist_status=="RFO"){
										sel1 = "selected";	
									}else if(pricelist_status=="ON-GOING"){ 
										sel2 = "selected";
									}else if(pricelist_status=="UP-COMING"){ 
										sel3 = "selected";
									}else if(pricelist_status=="PRE-SELLING"){ 
										sel7 = "selected";
									}

									if(lot_type=="INNER"){
										sel4 = "selected";
									}else if(lot_type=="END"){
										sel5 = "selected";
									}


									if(discount_type=="promo"){
										sel6 = "selected";
									}else if(lot_type=="cash_equity"){
										sel7 = "selected";
									}else if(lot_type=="spot_cash"){
										sel8 = "selected";
									}else if(lot_type=="others"){
										sel9 = "selected";
									}
 

							loadSelect('detail_terms2','.div_detail_terms'+a,'',detail_terms);							
							//loadSelect('detail_terms2','.div_detail_terms'+a,'select.select2',detail_terms);							
							detailTable += '<tr>';
							detailTable += '<td><span onClick="removeCurrentRow(this);" class="btn btn-xs btn-danger glyphicon glyphicon-trash"></span></td>';
							detailTable += '<td><select class="form-control text-left left pricelist_status" name="pricelist_status[]" onchange="computePF();"><option '+sel7+' value="PRE-SELLING">PRE-SELLING</option><option '+sel1+' value="RFO">RFO</option><option '+sel2+' value="ON-GOING">ON-GOING</option><option value="UP-COMING" '+sel3+'>UP-COMING</option></select></td>';
							detailTable += '<td style="width:200px"><div class="div_detail_terms'+a+'"></div></td>'; 
							detailTable += '<td><input maxlength="6" type="text" class="form-control text-right phase" name="phase[]" value="'+phase+'"></td>';
							detailTable += '<td><input maxlength="10" type="text" class="form-control text-right block" name="block[]"  value="'+block+'"></td>';
							detailTable += '<td><input maxlength="10" type="text" class="form-control text-right lot" name="lot[]" value="'+lot+'"></td>';
							detailTable += '<td><select class="form-control text-left left" name="lot_type[]"><option value="">-</option><option value="INNER" '+sel4+'>Inner</option><option '+sel5+' value="END">End</option></select></td>';
							detailTable += '<td><input maxlength="6" type="text" class="form-control text-right" name="lot_size[]" value="'+lot_size+'" onkeypress="return isNumberKey(event)"></td>';
							detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right" name="floor_area[]" value="'+floor_area+'" onkeypress="return isNumberKey(event)"></td>'; 
							detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right pricelist_contract_price" value="'+contract_price+'" name="contract_price[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"  onchange="computePF(); computeNetDiscountTCP();"></td>';
	 						  
							detailTable += '<td><select class="form-control text-left left" name="discount_type[]"><option value="">-</option><option '+sel6+' value="promo">Promo</option><option '+sel7+' value="cash_equity">Cash Equity</option><option '+sel8+' value="spot_cash">Spot Cash</option><option '+sel9+' value="others">Others</option></select></td>';
							detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right discount_amount" name="discount_amount[]" value="'+discount_amount+'" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);computeNetDiscountTCP()" onchange="computeNetDiscountTCP()"></td>';



							detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right discount_tcp" name="discount_tcp[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);" value="'+discount_tcp+'"></td>'; 

							//detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right discount_tcp" name="discount_tcp[]" value="'+discount_tcp+'" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);computePF()" onchange="computePF()"></td>';

							detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right pricelist_loanable_amount" name="loanable_amount[]" value="'+loanable_amount+'" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);computePF()" onchange="computePF()"></td>';
							

							//detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right downpayment" name="downpayment[]" value="'+downpayment+'" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);computePF()" onchange="computePF()"></td>';

							detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right downpayment" name="downpayment[]" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value); computePF()" onchange="computePF()"  value="'+downpayment+'"></td>';

							detailTable += '<td><input maxlength="12"  type="text" class="form-control text-right pricelist_pf_net" name="pf_net[]" value="'+pf_net+'" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td>';
							detailTable += '<td><input maxlength="12" type="text" class="form-control text-right pf_payable" name="pf_payable[]" value="'+pf_payable+'" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td>';
							detailTable += '<td><input maxlength="12" type="text" class="form-control text-right required_gross" name="required_gross[]" value="'+required_gross+'" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td>';
							detailTable += '<td><input maxlength="12" type="text" class="form-control text-right amortization" name="amortization[]" value="'+amortization+'" onkeypress="return isNumberKey(event)" onblur = "javascript:this.value=Comma(this.value);"></td>';
							detailTable += '<td><input type="text" value="'+remarks+'" class="form-control text-right remarks" name="remarks[]"></td>';
						detailTable += '</tr>';
								}
								
								$('#pricelist_detail_table tbody').html(detailTable); 
								
								if(action=="view"){
									$('input').attr("disabled", true);
									$('textarea').attr("disabled", true);
									$('select').attr("disabled", true);
									//$('#current_project').select2('disable');
									//$('#current_model').select2('disable');
									$('.glyphicon-trash').hide();
									$('.glyphicon-plus').hide();  
								}
								
						});
}


function delete_pricelist(id){
		var transaction		=	"pricelist";
		var mods 			=	$('#main_page').val();
		var types 			=	$('#main_type').val(); 
		var dataString		=	"mainid="+encodeURIComponent(id)+"&transaction="+encodeURIComponent(transaction);
						$.post('./ajax/delete_transaction.php', dataString, function(msg){
								var obj	= $.parseJSON(msg);
								if(obj.output==true){
									bootbox.alert("Successfully Deleted ..."); 
									window.setTimeout(function() { window.location.href = 'index.php?pg='+mods+'&type='+types; }, 1000);
								}else{
									bootbox.alert("Failed in Deleting ..."); 
									window.setTimeout(function() { window.location.href = 'index.php?pg='+mods+'&type='+types; }, 1000);
								}	
						});		
}

function getDefaultModelValues(){
	var cur_model 		=	$('#current_model').val(); 
	var dataString		=	"current_model="+cur_model;
	$.post('./ajax/load_default_model_values.php', dataString, function(msg){
			var obj	= $.parseJSON(msg); 
			var remarks				=	obj.data[0].remarks; 
			var reservation_fee		=	obj.data[0].reservation_fee;
			//tinyMCE.activeEditor.setContent(remarks);
			$('#pricelist_reservation_fee').val(reservation_fee); 
			$('#pricelist_remarks').val(remarks); 
	});
}

function getDefaultModelTableValues(){
	var cur_model 		=	$('#current_model').val(); 
	var dataString		=	"current_model="+cur_model;
	$.post('./ajax/load_default_model_values.php', dataString, function(msg){
			var obj	= $.parseJSON(msg);
			 
			var remarks				=	(obj.data[0].remarks!="" || obj.data[0].remarks!=null) ? obj.data[0].remarks : ''; 
			var reservation_fee		=	(obj.data[0].reservation_fee!='' || obj.data[0].reservation_fee!=null) ? obj.data[0].reservation_fee : 0;  
			//var pricelist_status	=	obj.data[0].status;
			//var loanable_price		=	obj.data[0].loanable_price;
			  
			//$('.required_gross').val(gross_income);
			//$('.amortization').val(amortization); 
			/*if(pricelist_status!=""){
				//$('.pricelist_status').val(pricelist_status);
			} 
			if(loanable_price!=""){
				//$('.pricelist_loanable_amount').val(loanable_price);
			}*/			
	});
}



//COMPUTE PROCESSING FEE
function computePF(){
 
    var sum = 0.0;
    $('#pricelist_detail_table > tbody  > tr').each(function() { 
        var detail_terms 	= $(this).find('.detail_terms option:selected').val(); 
        var contract_price 	= $(this).find('.pricelist_contract_price').val().replace(/,/g, "");
        var loanable_price 	= $(this).find('.pricelist_loanable_amount').val().replace(/,/g, ""); 

        //var downpayment 	= $(this).find('.downpayment').val(); 
        var downpayment 	= $(this).find('.downpayment').val().replace(/,/g, "");

		var reservation_fee = $('#pricelist_reservation_fee').val().replace(/,/g, "");
		if(contract_price==""){
			contract_price=0;
		} 
		
		var discount	 = 0;
		
		var pricelist_terms = $('#pricelist_terms').val(); 
		if(pricelist_terms==detail_terms){
			var discount	 = $('#pricelist_terms_discount').val().replace(/,/g, "");
		}
		
		
		
		if(detail_terms=="cash"){
			var discount	 	= $('#pricelist_cash_discount').val().replace(/,/g, "");
			var payable_months 	= 0;
		}else{
			var payable_months  = detail_terms;
		}
		
		if(!detail_terms){
		var payable_months 	= 0;
		}
		
		if(loanable_price==""){
			loanable_price=0;
		}

		if(downpayment==""){
			downpayment=0;
		}

         //var pf_net = (parseFloat(contract_price)-parseFloat(loanable_price))-reservation_fee-discount; 
           var pf_net = parseFloat(loanable_price) - parseFloat(downpayment); //29JUL23
        

		var pf_net_price	=	Comma(pf_net.toFixed(2));
        $(this).find('.pricelist_pf_net').val(pf_net_price); 
		var price_status = $(this).find('.pricelist_status option:selected').val(); 
		if(detail_terms=="cash"){
		var pf_payable = parseFloat(0);
		}else{
		var pf_payable = parseFloat(pf_net)/parseInt(payable_months); 
		}
		
		if(!detail_terms){
		var pf_payable = parseFloat(0);
		}
		$(this).find('.pf_payable').val(Comma(pf_payable.toFixed(2)));
    });
}
 


 //COMPUTE NET DISCOUNT TCP
function computeNetDiscountTCP(){
    var sum = 0.0;
    $('#pricelist_detail_table > tbody  > tr').each(function() { 
        
        var contract_price 	= $(this).find('.pricelist_contract_price').val().replace(/,/g, "");
        var discount_amount	= $(this).find('.discount_amount').val().replace(/,/g, ""); 
		

		if(contract_price==""){
			contract_price=0;
		} 

		if(discount_amount==""){
			discount_amount=0;
		} 
		  
		 
        var disc_pf_net = (parseFloat(contract_price)-parseFloat(discount_amount));
		var disc_pf_net_price	=	Comma(disc_pf_net.toFixed(2));
        $(this).find('.discount_tcp').val(disc_pf_net_price);  

    });
}