<?php 

// exit;

session_start();
require_once("../../includes/display_internal_user_dryout.inc.php");
require_once("../../includes/functions_internal_user_dryout.inc.php");
$obj = new data();
$connect = $obj->funConnect();
$display = new display();
$display->logout_iu();

$idd = $_REQUEST['id'];
$id        = explode(",",$_REQUEST['id']);
$comid     = $id[0];
$vendorid  = $id[2];
$fcaid     = $id[1];
$cargoid   = $id[6];
$randomid  = $id[9];
$slaveids  = $id[10];


$name      = $_REQUEST['name'];
$page      = $_REQUEST['page'];
$invtype   = $_REQUEST['invtype'];

if($invtype=='Interim')
{
    $creatorsarr = $obj->getUsersWithAuthority('INI_FREIGHT_CHK_CRETR');
	$approverarr1 = $obj->getUsersWithAuthority('INI_FREIGHT_CHK_APP_1');
	$approverarr2 = $obj->getUsersWithAuthority('INI_FREIGHT_CHK_APP_2');
	
	$creator = $obj->getUserAuthority($_SESSION['uid'], 'INI_FREIGHT_CHK_CRETR');
	$approver1 = $obj->getUserAuthority($_SESSION['uid'], 'INI_FREIGHT_CHK_APP_1');
	$approver2 = $obj->getUserAuthority($_SESSION['uid'], 'INI_FREIGHT_CHK_APP_2');
}else
{
    $creatorsarr = $obj->getUsersWithAuthority('FINL_FREIGHT_CHK_CRETR');
	$approverarr1 = $obj->getUsersWithAuthority('FINL_FREIGHT_CHK_APP_1');
	$approverarr2 = $obj->getUsersWithAuthority('FINL_FREIGHT_CHK_APP_2');
	
	$creator = $obj->getUserAuthority($_SESSION['uid'], 'FINL_FREIGHT_CHK_CRETR');
	$approver1 = $obj->getUserAuthority($_SESSION['uid'], 'FINL_FREIGHT_CHK_APP_1');
	$approver2 = $obj->getUserAuthority($_SESSION['uid'], 'FINL_FREIGHT_CHK_APP_2');
}

if($page == 1){$page_link = "payment_grid.php"; $page_bar="In Ops at a glance";$nav=5;$subtitle = 'VC';}else if($page == 2){$page_link = "payment_grid.php"; $page_bar="Vessels in Post Ops";$nav=5;$subtitle = 'VC';}else if($page == 3){$page_link = "payment_grid.php"; $page_bar="Vessels in History";$nav=5;$subtitle = 'VC';}else if($page == 4){$page_link = "payment_gridcoa.php"; $page_bar="In Ops at a glance - COA";$nav=16;$subtitle = 'COA';}else if($page == 5){$page_link = "payment_gridcoa.php"; $page_bar="In Post Ops at a glance - COA";$nav=16;$subtitle = 'COA';}else if($page == 6){$page_link = "payment_gridcoa.php"; $page_bar="Vessels in History - COA";$nav=16;$subtitle = 'COA';}else{$page_link = "payment_grid.php"; $page_bar="Historical Data - VC";$nav=23;$subtitle = 'VC';}

if(@$_REQUEST['action'] == 'submit')
{
	$msg = $obj->insertFreightInvoiceDetails();
	$msg = explode(",",$msg);
	header('Location:./invoice.php?msg='.$msg[0].'&comid='.$msg[1].'&page='.$page.'&id='.$_REQUEST['id'].'&name='.$_REQUEST['name']."&cargoid=".$cargoid."&randomid=".$randomid."&invtype=".$invtype);
}

if (@$_REQUEST['action2'] == 'submit1')
{
	$msg = $obj->insertFreightPaymentReceivedDetails();
	$msg = explode("_",$msg);
	header('Location:./invoice.php?msg='.$msg[0].'&comid='.$msg[1].'&page='.$page.'&id='.$_REQUEST['id'].'&name='.$_REQUEST['name']."&cargoid=".$cargoid."&randomid=".$randomid."&invtype=".$invtype);
}

if (@$_REQUEST['action1'] == 'submit2')
{
	$msg = $obj->deletefreightInvoiceRecords();
	$msg = explode(",",$msg);
	header('Location:./invoice.php?msg='.$msg[0].'&comid='.$msg[1].'&page='.$page.'&id='.$_REQUEST['id'].'&name='.$_REQUEST['name']."&cargoid=".$cargoid."&randomid=".$randomid."&invtype=".$invtype);
}

$fcaid = $obj->getLatestCostSheetID($comid);
$obj->viewFreightCostEstimationTempleteRecordsNew($fcaid);

if (isset($_POST['invoice_id'])) {
	$sql_ufim = mysql_query("update freight_invoice_master set STATUS=0 where INVOICEID='".$_POST['invoice_id']."'");
	echo true;
	
}
$add_qty_less_perc=$obj->getFun54() - ($obj->getFun54()*$obj->getFun243()/100);


if($add_qty_less_perc>0)
{
	$add_qty_less_perc_total=$obj->getFun66() + $add_qty_less_perc*$obj->getFun49();
}else{
	$add_qty_less_perc_total = $id[3];

}

$arr       = $obj->getLoadPortAndDischargePortArrBasedOnCommidAndProcessWithoutTBN($comid,$fcaid);

$lp_name = array(); 
$dp_name = array();
$discharge_port = "";

for($j=0;$j<count($arr);$j++)
{   
    $arr_explode = explode('@@',$arr[$j]);
	if($arr_explode[0] == "LP" && $arr_explode[8]==''){$lp_name[]= $obj->shortPortNameWithCountry($obj->getPortNameBasedOnID($arr_explode[1]));}
	if($arr_explode[0] == "DP" && $arr_explode[8]==''){$dp_name[]= $obj->shortPortNameWithCountry($obj->getPortNameBasedOnID($arr_explode[1]));}
}


$lp_name  = implode(', ',$lp_name);
$dp_name  = implode(', ',$dp_name);
$pagename = basename($_SERVER['PHP_SELF'])."?comid=".$comid."&name=".$name."&page=".$page."&id=".$idd."&cargoid=".$cargoid."&randomid=".$randomid."&invtype=".$invtype;

$uid	  = $_SESSION['uid'];
$moduleid = $_SESSION['moduleid'];

if($obj->getFun158() == 2)
{ 
    $currency = 'USD';
    $res11 = mysql_query("select * from freight_cost_estimete_slave10 where FCAID='".$obj->getFun1()."' and SHIPPER_CHARTER='".$vendorid."' and FCA_SLAVE10ID!='".$slaveids."' and CARGOID!=''");
	while($row11 = mysql_fetch_assoc($res11))
	{
		$clubcharterer[] = array('charterer'=>$row11['SHIPPER_CHARTER'], 'charterer_name'=>$obj->getVendorListNewBasedOnID($row11['SHIPPER_CHARTER']), 'cargoid'=>$row11['CARGOID'], 'cargo_name'=>$obj->getCargoNameListForMultipleNamemultiple($row11['CARGOID']), 'amount'=>$row11['AMOUNT_USD'], 'randomid'=>$row11['RANDOMID']);
	}
}
if($obj->getFun158() == 3)
{
	if($obj->getFun155()==2)
	{
		$sqlcoa = "select * from coa_master where COAID='".$obj->getFun175()."'";
		$resultcoa = mysql_query($sqlcoa) or die($sqlcoa);
		$rowscoa   = mysql_fetch_assoc($resultcoa);
		$currency = $rowscoa['CURRENCY'];
		$clubcharterer = array();
		$res11 = mysql_query("select * from freight_cost_estimete_slave7 where FCAID='".$obj->getFun1()."' and QTY_VENDORID='".$vendorid."' and FCA_SLAVE7ID!='".$slaveids."' and CARGO!=''");
		while($row11 = mysql_fetch_assoc($res11))
		{
			$clubcharterer[] = array('charterer'=>$row11['QTY_VENDORID'], 'charterer_name'=>$obj->getVendorListNewBasedOnID($row11['QTY_VENDORID']), 'cargoid'=>$row11['CARGO'], 'cargo_name'=>$obj->getCargoNameListForMultipleNamemultiple($row11['CARGO']), 'amount'=>$row11['NET_FREIGHT'], 'randomid'=>$row11['RANDOMID']);
		}
	}else
	{
		$currency = 'USD';
	}
}
$rights = $obj->getUserRights($uid,$moduleid,$linkid);
?>
<?php
$sql = "SELECT * from freight_invoice_master where COMID='".$comid."' and MODULEID='".$_SESSION['moduleid']."' and MCOMPANYID='".$_SESSION['company']."' and VENDOR='".$vendorid."' and P_TYPE='".$name."' and CARGOID='".$cargoid."' and RANDOMID='".$randomid."' and I_TYPE='".$invtype."' and STATUS < 5 LIMIT 1";

$res 	= mysql_query($sql);
$rec 	= mysql_num_rows($res);
$rows 	= mysql_fetch_assoc($res); 



?>	
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php $display->title(); ?></title>
<?php $display->favicon(); ?>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<?php $display->css(); ?>
<?php $display->js(); ?>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
  <script src="../js/html5shiv.js"></script>
  <script src="../js/respond.min.js"></script>
<![endif]-->
<link href="../../css/jquery.alerts.css" rel="stylesheet" type="text/css" />
<script src='../../js/jquery.autosize.js'></script>
<script language="JavaScript" type="text/javascript" src="../../js/jquery.alerts.js"></script>
<script src="../../js/timer.js" type="text/javascript"></script>
<link href="../../css/datepicker/datepicker.css" rel="stylesheet" type="text/css" />
<script src="../../js/bootstrap-datepicker.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript" src="../../js/jquery.numeric.js"></script>
<script language="JavaScript" type="text/javascript" src="../../js/jquery.calculation-min.js"></script>
<link type="text/css" href="../../css/chosen.css" rel="stylesheet" />
<script src="../../js/chosen.jquery.js" type="text/javascript"></script>
<link href="../../css/datetimepicker/bootstrap-datetimepicker.css" rel="stylesheet" type="text/css" />
<script src="../../js/plugins/datetimepicker/bootstrap-datetimepicker.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){ 
	$(".autosize").autosize({append: "\n"});
	$("#selApprovers").chosen();

	
	$("#frm1").validate({
		rules: {
	    selFromOwner: {required: true},
		selIType: {required: true},
		txtDNote: {required: true},
		txtDate: {required: true},
		txtExchangeRate:{required: true},
		selExchangeCurrency:{required: true},
		txtPaymentTerms:{required: true},
		selNOB:{required: true},
		txtDesc:{required: true}
		},
	messages: {
		selIType: {required: "*"},
		txtDNote: {required: true},
		txtDate: {required: true},
		txtExchangeRate:{required: "*"},
		selExchangeCurrency:{required: "*"},
		txtPaymentTerms:{required: "*"},
		selNOB:{required: "*"}
		},

		
	submitHandler: function(form)  {

		console.log($('#gridCount').val());


		// con/s
		if(parseInt($('#gridCount').val())!=0){

			console.log('dpk is great devs33333');
		for(var i=0 ; i < parseInt($('#gridCount').val()); i++){


			console.log($('#CancelledInv_'+i).val())
			if($('#selIType').val()==$('#gridInvType_'+i).val() && $('#txtDNote').val()==$('#gridInvNo_'+i).val() && $('#CancelledInv_'+i).val()=='undefined'){
			console.log('dpk is great devs007');
			jAlert('Invoice already exists');

			return;


		}
		else{

			console.log('dpk is great devs2222');
			if($('#txtStatus').val() == 0)
		{
			jAlert('<b style="font-size:25px;">Please wait . . .</b><br><br><img src="../../img/loading.gif"  />', 'Alert');
			$("#popup_container").css({"background": "rgba(255,255,255,0.1)","border": "10px solid rgba(255,255,255,0.1)","width": "100%"});
			$("#popup_content").css({"background":"none","text-align":"center"});
			$("#popup_ok,#popup_title").hide();  
			form.submit();
		}
		else
		{
			jConfirm('Are you sure you want to Submit ?', 'Confirmation', function(r) {
				if(r)
				{
					jAlert('<b style="font-size:25px;">Please wait . . .</b><br><br><img src="../../img/loading.gif"  />', 'Alert');
					$("#popup_container").css({"background": "rgba(255,255,255,0.1)","border": "10px solid rgba(255,255,255,0.1)","width": "100%"});
					$("#popup_content").css({"background":"none","text-align":"center"});
					$("#popup_ok,#popup_title").hide();  
					form.submit();
				}
			});
		}

		}
		}
	}else{


		if($('#txtStatus').val() == 0)
		{
			jAlert('<b style="font-size:25px;">Please wait . . .</b><br><br><img src="../../img/loading.gif"  />', 'Alert');
			$("#popup_container").css({"background": "rgba(255,255,255,0.1)","border": "10px solid rgba(255,255,255,0.1)","width": "100%"});
			$("#popup_content").css({"background":"none","text-align":"center"});
			$("#popup_ok,#popup_title").hide();  
			form.submit();
		}
		else
		{
			jConfirm('Are you sure you want to Submit ?', 'Confirmation', function(r) {
				if(r)
				{
					jAlert('<b style="font-size:25px;">Please wait . . .</b><br><br><img src="../../img/loading.gif"  />', 'Alert');
					$("#popup_container").css({"background": "rgba(255,255,255,0.1)","border": "10px solid rgba(255,255,255,0.1)","width": "100%"});
					$("#popup_content").css({"background":"none","text-align":"center"});
					$("#popup_ok,#popup_title").hide();  
					form.submit();
				}
			});
		}
	}



		
		
		}
	});
$("#txtTO,[id^=txtAddDesAmt_],[id^=txtSubDesAmt_],#txtAddComm,#txtExchangeRate,#txtBrokerage").numeric();
$(".numeric").numeric();

$('#txtRemarks').autosize({append: "\n"});

$('#txtDate,#txtDueDate,#txtExchangeDate').datepicker({
	format: 'dd-mm-yyyy',
	autoclose:true
});

$('[id^=chkClubFreight_]').on('ifChecked', function () { 

	

   var amount = parseFloat($("#txtClubFreight_"+$(this).val()).val());if(isNaN(amount)){amount = 0;}else{amount = amount.toFixed(2);};
   var frtamt = parseFloat($("#txtGrossFreight").val());if(isNaN(frtamt)){frtamt = 0;};
   var newamt = parseFloat(frtamt) + parseFloat(amount);


   $("#txtGrossFreight").val(newamt.toFixed(2));
   getAmountThereOff();
});

$('[id^=chkClubFreight_]').on('ifUnchecked', function () { 
	
   var amount = parseFloat($("#txtClubFreight_"+$(this).val()).val());if(isNaN(amount)){amount = 0;}else{amount = amount.toFixed(2);};
   var frtamt = parseFloat($("#txtGrossFreight").val());if(isNaN(frtamt)){frtamt = 0;};
   var newamt = parseFloat(frtamt) - parseFloat(amount);
   $("#txtGrossFreight").val(newamt.toFixed(2));
   getAmountThereOff();
});



$('#chkProRate').on('ifChecked', function () { 

// alert();

var $txtDemDisID  = $('#txtDemDisID').val();

for(var $i=1;$i<=$txtDemDisID;$i++){


	if($('#IS_SHOW_DDCLP_CHECK_'+$i).val()==1){

		var dem_des_cost =  parseFloat($('#DDCLP_NETCOST_CHECK_'+$i).val())*parseFloat($('#id5_'+$i).val())/parseFloat($('#ttlQuantity_'+$i).val());

		$('#txtDemDisAmt_'+$i).val(dem_des_cost.toFixed(2));

	}else{

		var dem_des_cost_des =  parseFloat($('#DDCDP_NETCOST_CHECK_'+$i).val())*parseFloat($('#id5_'+$i).val())/parseFloat($('#ttlQuantity_'+$i).val());

		$('#txtDemDisAmt_'+$i).val(dem_des_cost_des.toFixed(2));

	}

}

$('#setProRate').val(1);
});



$('#chkProRate').on('ifUnchecked', function () { 


var $txtDemDisID  = $('#txtDemDisID').val();

for(var $i=1;$i<=$txtDemDisID;$i++){


	if($('#IS_SHOW_DDCLP_CHECK_'+$i).val()==1){

		var dem_des_cost =  parseFloat($('#DDCLP_NETCOST_CHECK_'+$i).val());

		$('#txtDemDisAmt_'+$i).val(dem_des_cost.toFixed(2));

	}else{

		var dem_des_cost_des =  parseFloat($('#DDCDP_NETCOST_CHECK_'+$i).val());

		$('#txtDemDisAmt_'+$i).val(dem_des_cost_des.toFixed(2));

	}

}

$('#setProRate').val(0);
});



$('[id^=chkDemDis_]').on('ifChecked', function () { 
   getAmountThereOff();
});

$('[id^=chkDemDis_]').on('ifUnchecked', function () { 
   getAmountThereOff();
});


$('#rdoTaxApplicable1').on('ifChecked', function () { 
    $(this).attr('checked', true);showhidetaxDiv();
});

$('#rdoTaxApplicable2').on('ifChecked', function () { 
   $(this).attr('checked', true);showhidetaxDiv();
});

//-----------------------------------------------------------------
$('#rdoGSTVAT1').on('ifChecked', function () { 
   $(this).attr('checked', true);showhidetaxDiv();
});

$('#rdoGSTVAT2').on('ifChecked', function () { 
   $(this).attr('checked', true);showhidetaxDiv();
});

readonlytextbox();
showhidetaxDiv();
getCalculateFreight();
getBankingDetailsData();
getAmountThereOff();
});

function readonlytextbox()
{
    if($("#txtIGST").val()>0)
	{
	    $("#txtSGST,#txtCGST").attr('readonly',true);
		$("#txtSGST,#txtCGST").val(0);
	}
	else
	{
	    $("#txtSGST,#txtCGST").attr('readonly',false);
	}
	
	if($("#txtSGST").val()>0 || $("#txtCGST").val()>0)
	{
	    $("#txtIGST").attr('readonly',true);
		$("#txtIGST").val(0);
	}
	else
	{
	    $("#txtIGST").attr('readonly',false);
	}
	getAmountThereOff();
}

function showhidetaxDiv()
{
    if($("#rdoTaxApplicable1").is(":checked"))
	{
	    $("#taxRadioDiv,#taxtDiv_1,#taxtDiv_2,#taxtDiv_3,#taxtDiv_4").show();
		if($("#rdoGSTVAT1").is(":checked"))
	    {
			$("#taxtDiv_1,#taxtDiv_2,#taxtDiv_3").show();
            $("#taxtDiv_4").hide();
		}
		else
		{
		    $("#taxtDiv_1,#taxtDiv_2,#taxtDiv_3").hide();
            $("#taxtDiv_4").show();
		}
	}
	else
	{
	    $("#taxRadioDiv,#taxtDiv_1,#taxtDiv_2,#taxtDiv_3,#taxtDiv_4").hide();
	}
	getAmountThereOff();
}

function getCalculateFreight()
{
	var sum2 = parseFloat('<?php echo $add_qty_less_perc_total;?>');
	
	
	var sum1 = 0;
	for(var i = 1;i<=$("#hddnClubcount").val();i++)
	{   
		if($("#chkClubFreight_"+i).is(":checked"))
		{
			var txtClubFreight = parseFloat($("#txtClubFreight_"+i).val());if(isNaN(txtClubFreight)){txtClubFreight = 0;}
			sum1 = parseFloat(sum1.toFixed(2)) + parseFloat(txtClubFreight.toFixed(2));
		}
	}
	if(isNaN(sum1)){sum1 = 0;}
	var sum3  = parseFloat(sum2.toFixed(2)) + parseFloat(sum1.toFixed(2));
	$("#txtGrossFreight").val(parseFloat(sum3.toFixed(2)));
	
}


function AddNewAddRow()
{
	var id = $("#txtAddID").val();
	if($("#txtAddDes_"+id).val() != "" && $("#txtAddDesAmt_"+id).val() != "")
	{
		id = (id - 1) + 2;
		$('<tr id="add_Row_'+id+'"><td align="center"><a href="#pr1" onClick="removeAddRow(1);"><i class="fa fa-times" style="color:red;"></i></a></td><td><textarea class="form-control areasize" name="txtAddDes_'+id+'" id="txtAddDes_'+id+'" rows="2" placeholder="Description..."></textarea></td><td><input type="text" name="txtAddDesAmt_'+id+'" id="txtAddDesAmt_'+id+'" class="form-control"  placeholder="Amount" autocomplete="off" value="" onKeyUp="getAmountThereOff();"/></td></tr>').appendTo("#tblAdd");
		$("#txtAddID").val(id);
		$("[id^=txtAddDesAmt_]").numeric();	
	}
}


function removeAddRow(var1)
{
		jConfirm('Are you sure you want to remove this entry permanently ?', 'Confirmation', function(r) {
			if(r){
					$("#add_Row_"+var1).remove();
					getAmountThereOff();
				 }
			else{return false;}
			});
}



function SubNewSubRow()
{
	var id = $("#txtSubID").val();
	if($("#txtSubDes_"+id).val() != "" && $("#txtSubDesAmt_"+id).val() != "")
	{
		id = (id - 1) + 2;
		$('<tr id="Sub_Row_'+id+'"><td align="center"><a href="#pr1" onClick="removeSubRow(1);"><i class="fa fa-times" style="color:red;"></i></a></td><td><textarea class="form-control areasize" name="txtSubDes_'+id+'" id="txtSubDes_'+id+'" rows="2" placeholder="Description..."></textarea></td><td><input type="text" name="txtSubDesAmt_'+id+'" id="txtSubDesAmt_'+id+'" class="form-control"  placeholder="Amount" autocomplete="off" value="" onKeyUp="getAmountThereOff();"/></td></tr>').appendTo("#tblSub");
		$("#txtSubID").val(id);
		$("[id^=txtSubDesAmt_]").numeric();	
	}
}


function removeSubRow(var1)
{
	jConfirm('Are you sure you want to remove this entry permanently ?', 'Confirmation', function(r) {
		if(r){
				$("#Sub_Row_"+var1).remove();
				getAmountThereOff();
			 }
		else{return false;}
		});
}

function getBankingDetailsData()
{   
    var1 = $('#selNOB').val();
	if($("#selNOB").val()!="")
	{
		$.post("options.php?id=43",{selNOB:""+$("#selNOB").val()+""}, function(html) {
			if(html!="")
			{
				$("#bankingrow").show();
				var res = html.split("@@@@");
				$('#span_1_0').text(res[0]);
				$('#span_1_1').text(res[1]);
				$('#span_1_2').text(res[2]);
				$('#span_1_3').text(res[3]);
				$('#span_1_4').text(res[4]);
				$('#span_1_5').text(res[5]);
				$('#span_1_6').text(res[6]);
				$('#span_1_7').text(res[7]);
				$('#span_1_8').text(res[8]);
				$('#span_1_9').text(res[9]);
				$('#span_1_10').text(res[10]);
				$('#span_1_11').text(res[11]);
			}
		});
	}
	else
	{
	    $("#bankingrow").hide();	
		$('#span_1_0').text("");
	    $('#span_1_1').text("");
		$('#span_1_2').text("");
		$('#span_1_3').text("");
		$('#span_1_4').text("");
		$('#span_1_5').text("");
		$('#span_1_6').text("");
		$('#span_1_7').text("");
		$('#span_1_8').text("");
		$('#span_1_9').text("");
		$('#span_1_10').text("");
		$('#span_1_11').text("");
	}
}




function getAmountThereOff()
{ 
    if($('#txtFinlGrossFreight').val()=="" || isNaN($('#txtFinlGrossFreight').val())){var final_freight = 0;}else{var final_freight = $("#txtFinlGrossFreight").val();}
	if($('#txtGrossFreight').val()=="" || isNaN($('#txtGrossFreight').val())){var final_freight1 = 0;}else{var final_freight1 = $("#txtGrossFreight").val();}
	
	
	if($('#txtTO').val()=="" || isNaN($('#txtTO').val())){var var1 = 0;}else{var var1 = $("#txtTO").val();}
	var var3 = (parseFloat(parseFloat(parseFloat(final_freight1)*parseFloat(var1))/100)).toFixed(2);
	if(isNaN(var3)){var3 = 0;}
	
	$('#txtNet').val(parseFloat(var3).toFixed(2));
	
    var add1 = parseFloat($("[id^=txtAddDesAmt_]").sum());
	if(isNaN(add1)){add1 = 0;}
	var sub1 = parseFloat($("[id^=txtSubDesAmt_]").sum());
	if(isNaN(sub1)){sub1 = 0;}
		
	var addcomdem = 0;
	var brocommdem = 0;
	var addcom = parseFloat($("#txtAddComm").val());if(isNaN(addcom)){addcom = 0;}
	var brocomm = parseFloat($("#txtBrokerage").val());if(isNaN(brocomm)){brocomm = 0;}
	var gst_on_brok_perc = parseFloat($("#gst_on_brokage_perc").val());if(isNaN(gst_on_brok_perc)){gst_on_brok_perc = 0;}
	for(var i = 1;i<=$("#txtDemDisID").val();i++)
	{
		if($("#chkDemDis_"+i).is(":checked"))
		{
			var txtDemDisAmt = parseFloat($("#txtDemDisAmt_"+i).val());if(isNaN(txtDemDisAmt)){txtDemDisAmt = 0.00;}
			add1 = parseFloat(add1) + parseFloat(txtDemDisAmt);
			
			if(txtDemDisAmt > 0)
			{
			    var addcomdem1 = parseFloat(parseFloat(txtDemDisAmt)*parseFloat(addcom))/100;if(isNaN(addcomdem1)){addcomdem1 = 0.00;}
				var brocommdem1 = parseFloat(parseFloat(txtDemDisAmt)*parseFloat(brocomm))/100;if(isNaN(brocommdem1)){brocommdem1 = 0.00;}
				addcomdem = parseFloat(addcomdem) + parseFloat(addcomdem1);
				brocommdem = parseFloat(brocommdem) + parseFloat(brocommdem1);
			}
		}
	}
	
	if($('#txtTO').val() > 0)
	{
		var brokerage = (parseFloat(parseFloat(parseFloat(final_freight1)*parseFloat(brocomm))/100)).toFixed(2);
		if(isNaN(brokerage)){brokerage = 0;}
		
		if($('#txtAddComm').val()=="" || isNaN($('#txtAddComm').val())){var addcom = addcom_amt = 0;}
		else{var addcom = $("#txtAddComm").val(); addcom_amt = parseFloat(parseFloat(final_freight1)*parseFloat(addcom))/100;}
		
	}else{
	    var addcom_amt = 0;
		var brokerage = 0;
	}
	
	var brokerage_amt = parseFloat(brokerage) + parseFloat(brocommdem);

	var gst_on_brok=(gst_on_brok_perc*brokerage_amt)/100;
	$('#gst_on_brokage').val(parseFloat(gst_on_brok).toFixed(2));


	
	$('#txtBrokerageAmt').val(parseFloat(brokerage_amt).toFixed(2));

	addcom_amt = parseFloat(parseFloat(addcom_amt) + parseFloat(addcomdem));
	$('#txtAddCommAmt').val(parseFloat(addcom_amt).toFixed(2));


	
	
	var var2 = parseFloat(var3) + parseFloat(add1) - parseFloat(sub1) - parseFloat(addcom_amt) - parseFloat(brokerage_amt)-parseFloat(gst_on_brok);
	
	if(isNaN(var2)){var2 = 0;}
	$('#txtNetAmtPayable').val(parseFloat(var2).toFixed(2));
	
	var txtSGST = parseFloat($("#txtSGST").val());if(isNaN(txtSGST)){txtSGST = 0;}
	var txtCGST = parseFloat($("#txtCGST").val());if(isNaN(txtCGST)){txtCGST = 0;}
	var txtIGST = parseFloat($("#txtIGST").val());if(isNaN(txtIGST)){txtIGST = 0;}
	var txtVAT = parseFloat($("#txtVAT").val());if(isNaN(txtVAT)){txtVAT = 0;}
	
	var txtSGST_Amount = parseFloat(parseFloat(var2)*parseFloat(txtSGST))/100;if(isNaN(txtSGST_Amount)){txtSGST_Amount = 0;}
	var txtCGST_Amount = parseFloat(parseFloat(var2)*parseFloat(txtCGST))/100;if(isNaN(txtCGST_Amount)){txtCGST_Amount = 0;}
	var txtIGST_Amount = parseFloat(parseFloat(var2)*parseFloat(txtIGST))/100;if(isNaN(txtIGST_Amount)){txtIGST_Amount = 0;}
	var txtVAT_Amount = parseFloat(parseFloat(var2)*parseFloat(txtVAT))/100;if(isNaN(txtVAT_Amount)){txtVAT_Amount = 0;}
	
	$("#txtSGST_Amount").val(parseFloat(txtSGST_Amount).toFixed(2));
	$("#txtCGST_Amount").val(parseFloat(txtCGST_Amount).toFixed(2));
	$("#txtIGST_Amount").val(parseFloat(txtIGST_Amount).toFixed(2));
	$("#txtVAT_Amount").val(parseFloat(txtVAT_Amount).toFixed(2));
	var txtInvPAmt = parseFloat($("[id^=txtInvPAmt_]").sum());
	if(isNaN(txtInvPAmt)){txtInvPAmt = 0;}
	
	var2 = parseFloat(var2) - parseFloat(txtInvPAmt);

	var exRate=parseFloat($('#txtExchangeRate').val());

	
	if($("#rdoTaxApplicable1").is(":checked"))
	{
		if($("#rdoGSTVAT1").is(":checked"))
	    {
			var txtAmtPayableWithTax = parseFloat(var2) + parseFloat(txtSGST_Amount) + parseFloat(txtCGST_Amount) + parseFloat(txtIGST_Amount);
			$('#txtAmtPayableWithTax').val(parseFloat(txtAmtPayableWithTax).toFixed(2));

			
			$('#txtEOC').val(parseFloat(txtAmtPayableWithTax*exRate).toFixed(2));

		
		}else{
			var txtAmtPayableWithTax = parseFloat(var2) + parseFloat(txtVAT_Amount);
			$('#txtAmtPayableWithTax').val(parseFloat(txtAmtPayableWithTax).toFixed(2));

			$('#txtEOC').val(parseFloat(txtAmtPayableWithTax*exRate).toFixed(2));
		}
	}else{
		$('#txtAmtPayableWithTax').val(parseFloat(var2).toFixed(2));

		$('#txtEOC').val(parseFloat(var2*exRate).toFixed(2));

		
	}
}

function getValidate(var1)
{
    $('#txtStatus').val(var1);
	
	var file_temp_name = $("[id^=file_]").map(function () {return this.value;}).get().join(",");
	$('#txtCRMFILE').val(file_temp_name);
	var file_actual_name = $("[id^=name_]").map(function () {return this.value;}).get().join(",");
	$('#txtCRMNAME').val(file_actual_name);
	
    if($('#txtStatus').val()==1)
	{   
	    if($('#selApprovers').val()==null || $('#selApprovers').val()=='')
		{
		    jAlert('Please select Level 1 Approvers first.', 'Alert');
			return false;
		}
		else
		{
		    return true;
		}
	}
	
}

function getDelete(var1)
{
	jConfirm('Are you sure you want to Cancel this Entry?', 'Confirmation', function(r) {
	if(r)
	{
		$('#action1').val('submit2');
		$('#txtDEL_ID').val(var1);
		document.frm2.submit();
	}
	else
	{
		return false;
	}
	});
}

function openWin(var1)
{
	$("#divPayment").empty();
	$("#divPayment").html('<div><img src="../../img/ajax-loader.gif" /><br><b>Loading...</b></div>'); 
	$.post("options.php?id=44",{invoiceid:""+var1+""}, function(html) {
		$("#divPayment").empty();
		$("#divPayment").append(html);
		//onkeyUp1();
		
		if($('#txtP_PR').val()=="" || isNaN($('#txtP_PR').val())){var txtP_PR = 0;}else{var txtP_PR = $("#txtP_PR").val();}
		txtP_PR = parseFloat(txtP_PR) + 100;
		if(txtP_PR > $("#txtP_Amt").val())
		{
			$("#rcvdbtnhide").hide();	
		}
		$(".numeric").numeric();
        $('#txtP_Remarks,[id^=txtP_Remarks_]').autosize({append: "\n"});
		$('[id^=txtP_Date_]').datepicker({
			format: 'dd-mm-yyyy',
			autoclose:true
		});
		
	});
}

function AddNewPaymentRow()
{
	var id = $("#txtPaymentID").val();
	if($("#txtP_Date_"+id).val() != "" && $("#txtP_PR_"+id).val() != "")
	{
		id = (id - 1) + 2;
		$('<tr id="trpaymentrow_'+id+'"><td><a href="#pr1" onClick="removePaymentRow('+id+');"><i class="fa fa-times" style="color:red;"></i></a></td><td><input type="text" name="txtP_Date_'+id+'" id="txtP_Date_'+id+'" class="form-control" value="" autocomplete="off"/></td><td><textarea name="txtP_Remarks_'+id+'" id="txtP_Remarks_'+id+'" class="form-control" cols="15" rows="2" placeholder="Remarks.."></textarea></td><td><input type="text" name="txtP_PR_'+id+'" id="txtP_PR_'+id+'" class="form-control numeric" autocomplete="off" placeholder="0.00" value=""  onkeyup="onkeyUp1();"/></td></tr>').appendTo("#paymenttbody");
		$('#txtP_Date_'+id).datepicker({
			format: 'dd-mm-yyyy',
			autoclose:true
		});
		$("#txtPaymentID").val(id);
		$('#txtP_Remarks_'+id).autosize({append: "\n"});
		$(".numeric").numeric();
		onkeyUp1();	
	}
}


function removePaymentRow(var1)
{
	jConfirm('Are you sure you want to remove this entry permanently ?', 'Confirmation', function(r) {
		if(r){
				$("#trpaymentrow_"+var1).remove();
				onkeyUp1();
			 }
		else{return false;}
		});
}

function onkeyUp1()
{
    var txtInv = parseFloat($("[id^=txtP_PR_]").sum());
	if(isNaN(txtInv)){txtInv = 0;}
	$('#txtP_PR').val(txtInv.toFixed(2));
}


function getValid()
{
	if($('#txtP_PR').val() == '' || $('#txtP_Date').val() =='' || $('#txtP_Remarks').val()=='')
	{
		jAlert('Please fill the Payment Received & Date & Remarks', 'Alert');
		return false;
	}
	else
	{
		var file_temp_name = $("[id^=file1_]").map(function () {return this.value;}).get().join(",");
	    $('#txtCRMFILE1').val(file_temp_name);
	    var file_actual_name = $("[id^=name1_]").map(function () {return this.value;}).get().join(",");
	    $('#txtCRMNAME1').val(file_actual_name);
		return true;
	}
}

function getPdf(var1)
{
	location.href='allPdf.php?id=27&im_id='+var1;
}

function getPdfForZero(var1)
{
	location.href='allPdf.php?id=92&im_id='+var1;
}

function getPdfForOutOfScope(var1)
{
	location.href='allPdf.php?id=93&im_id='+var1;
}



function Del_Upload1(var2)
{
	jConfirm('Are you sure you want to delete this upload permanently ?', 'Confirmation', function(r) {
	if(r){ 
		$('#row_file1_'+var2).remove();
	}
	});
}

function Del_Upload(var1)
{
	jConfirm('Are you sure you want to remove this attachment permanently ?', 'Confirmation', function(r) {
	if(r){
			$("#row_file_"+var1).remove();	
		 }
	else{return false;}
	});
}

</script>
<style>
.animated {
	vertical-align: top; 
	transition: height 0.2s;
	-webkit-transition: height 0.2s; 
	-moz-transition: height 0.2s; 
}

form.cmxform label.error, label.error {
	/* remove the next line when you have trouble in IE6 with labels in list */
	font-family:Verdana, Arial, Helvetica, sans-serif;
	font-size:10px;
	color: red;
	font-style:normal;
	font-weight:lighter;
	margin:5px;
	vertical-align:top;
}
.span span{
	font-weight:bold;
}
</style>
</head>
    <body class="skin-blue fixed">
        <!-- header logo: style can be found in header.less -->
        <?php $display->header_tag(); ?>
		<div class="wrapper row-offcanvas row-offcanvas-left">
            <?php $display->leftmenu($nav); ?>
			<aside class="right-side">                
                <!-- Content Header (Page header) -->
                 <section class="content-header">
                    <h1>
                        <i class="fa fa-book"></i>&nbsp;Ops <?php echo $subtitle;?>&nbsp;&nbsp;&nbsp;&nbsp;<small><div class="headline text-center" id="time" style="color:#000; font-weight:bold; font-size:12px;">( 20 Jul 2015 4:40:44 PM )</div></small>
                    </h1>
                    <ol class="breadcrumb">
                        <li><a href="../"><i class="fa fa-home"></i> Home</a></li>
                        <li class="active">Ops <?php echo $subtitle;?>&nbsp;&nbsp;&nbsp;&gt;&nbsp;&nbsp;&nbsp;<?php echo $page_bar;?>&nbsp;&nbsp;&nbsp;</li>
                    </ol>
                </section>
               
                <!-- Main content -->
                <section class="content invoice">
				<?php if(isset($_REQUEST['msg'])){
						$msg = $_REQUEST['msg'];
						if($msg == 0){?>
				<div class="alert alert-success alert-dismissable">
					<i class="fa fa-check"></i>
					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
					<b>Congratulations!</b> invoice data added/updated successfully.
				</div>
				<?php }}?>
				<!--   content put here..................-->




				<div align="left">

					<?php 

					?>
					<?php if($rec>0 && $rows['SHIP_OWNER']=='OB0002'){?><a href="#" title="Pdf" onClick="getPdfForZero(<?php echo $rows['INVOICEID'];?>);"><button class="btn btn-warning" type="button" style="margin-right: 5px;"><i class="fa fa-download"></i> Generate PDF-AED</button></a><?php }?></div>

				
				<div align="right">

				<?php 

				?>
                <?php if($rec>0){?><a href="#" title="Pdf" onClick="getPdf(<?php echo $rows['INVOICEID'];?>);"><button class="btn btn-default" type="button" style="margin-right: 5px;"><i class="fa fa-download"></i> Generate PDF</button></a>&nbsp;&nbsp;&nbsp;<?php }?><a href="<?php echo $page_link;?>?comid=<?php echo $comid;?>&page=<?php echo $page;?>"><button class="btn btn-info btn-flat" type="button" >Back</button></a></div>
							
				<div style="height:10px;">&nbsp;</div>

				<?php


						$status_query = "select * from freight_invoice_master where COMID='".$comid."' and MODULEID='".$_SESSION['moduleid']."' and MCOMPANYID='".$_SESSION['company']."' and VENDOR = '".$vendorid."'  and P_TYPE='".$name."' and CARGOID='".$cargoid."' and RANDOMID='".$randomid."' and STATUS>=5";
									// echo $sql;

									// echo "<br>";
// 									$status = mysql_query($status_query);


// 									// echo "<pre>";
// 									// while($status_value= mysql_fetch_assoc($status)){
// 									// 	print_r($status_value);

// 									// }


// // exit;
									


								?>





					<form role="form" name="frm1" id="frm1" enctype="multipart/form-data" action="<?php echo $pagename;?>" method="post">			
						<div class="row">
							<div class="col-xs-12" style="text-align:center;">
								<h2 class="page-header">
								FREIGHT INVOICE CREATION
								</h2>                            
							</div><!-- /.col -->
						</div>
                        
                        <div class="row invoice-info">
							<div class="col-sm-4 invoice-col">
								<strong>Invoicing Company :</strong>
								<address>
								   <select  name="selFromOwner" class="select form-control" id="selFromOwner">
										<?php 
										$obj->getVendorListNewForCOA(11);
										?>
									</select>
									<script>$('#selFromOwner').val('<?php echo $rows['SHIP_OWNER'];?>');</script>
								</address>
							</div><!-- /.col -->                     
							<div class="col-sm-4 invoice-col">
								 <strong>To :</strong>
								<address>
								   <?php if($rec > 0){?>
                                    <?php echo $obj->getVendorListNewBasedOnID($rows['VENDOR']);?><br>
                                    <?php echo stripslashes($obj->getVendorDataBasedOnID($rows['VENDOR'],'STREET_1'));?>
                                    <?php echo stripslashes($obj->getVendorDataBasedOnID($rows['VENDOR'],'CITY'));?>,
                                    <?php echo stripslashes($obj->getVendorDataBasedOnID($rows['VENDOR'],'COUNTRY'));?>,
                                    <?php echo stripslashes($obj->getVendorDataBasedOnID($rows['VENDOR'],'CITY_POSTAL_CODE'));?>
                                    <input type="hidden" name="txtVendor" id="txtVendor" value="<?php echo $rows['VENDOR'];?>" />
                                    <input type="hidden" name="txtFCAID" id="txtFCAID" value="<?php echo $rows['FCAID'];?>" />
                                    <?php }else{?>
                                    <?php echo $obj->getVendorListNewBasedOnID($vendorid);?><br>
                                    <?php echo stripslashes($obj->getVendorDataBasedOnID($vendorid,'STREET_1'));?>
                                    <?php echo stripslashes($obj->getVendorDataBasedOnID($vendorid,'CITY'));?>,
                                    <?php echo stripslashes($obj->getVendorDataBasedOnID($vendorid,'COUNTRY'));?>,
                                    <?php echo stripslashes($obj->getVendorDataBasedOnID($vendorid,'CITY_POSTAL_CODE'));?>
                                    <input type="hidden" name="txtVendor" id="txtVendor" value="<?php echo $vendorid;?>" />
                                    <input type="hidden" name="txtFCAID" id="txtFCAID" value="<?php echo $obj->getFun1();?>" />
                                    <?php }?>
								</address>
							</div><!-- /.col -->
							<div class="col-sm-4 invoice-col">
								<strong>Freight Details</strong>
								<address>
								   Fixture Ref.: <?php echo $obj->getCompareEstimateData($comid,"VOYAGE_NO");?><br/>
                                   Vessel: <?php echo $obj->getVesselIMOData($obj->getCompareEstimateData($comid,"VESSEL_IMO_ID"),"VESSEL_NAME");?><br/>
                                   CP Date: <?php echo date("d-m-Y",strtotime($obj->getFun3())); ?><br/>
                                   <?php if($cargoid!=0){?>
                                       Cargo: <?php echo $obj->getCargoNameListForMultipleNamemultiple($cargoid);?><br/>
                                   <?php }?>
                                   Port of Loading: <?php echo $lp_name;?><br/>
                                   Port of Discharging: <?php echo $dp_name; ?>
								</address>
							</div><!-- /.col -->
						</div>
						<div class="row invoice-info">
						    <div class="col-sm-4 invoice-col">
								Vendor (Manual)
								<address>
								<?php if($rec > 0){?>
								   <textarea class="form-control areasize" name="txtManualVendorName" id="txtManualVendorName" rows="3" placeholder="Vendor..."><?php echo $rows['MANUAL_VENDOR_NAME'];?></textarea>
								<?php }else{?>
								   <textarea class="form-control areasize" name="txtManualVendorName" id="txtManualVendorName" rows="3" placeholder="Vendor..."><?php echo $obj->getVendorListNewBasedOnID($vendorid);?> <?php echo stripslashes($obj->getVendorDataBasedOnID($vendorid,'STREET_1'));
								 
								 

								 if (stripslashes($obj->getVendorDataBasedOnID($vendorid,'CITY') != '')) {

										
									echo stripslashes($obj->getVendorDataBasedOnID($vendorid,'CITY'));
								}
								 if (stripslashes($obj->getVendorDataBasedOnID($vendorid,'COUNTRY') != '')) {

										
									echo stripslashes($obj->getVendorDataBasedOnID($vendorid,'COUNTRY'));
								}
								 if (stripslashes($obj->getVendorDataBasedOnID($vendorid,'CITY_POSTAL_CODE') != '')) {

										
									echo stripslashes($obj->getVendorDataBasedOnID($vendorid,'CITY_POSTAL_CODE'));
								}		
								 
								 
								 ?></textarea>
								<?php }?>
								</address>
							</div><!-- /.col --> 
							<div class="col-sm-4 invoice-col">
								Port of Loading
								<address>
								<?php if($rec > 0){?>
								   <textarea class="form-control areasize" name="txtLoadPortName" id="txtLoadPortName" rows="2" placeholder="Port of Loading..."><?php echo $obj->shortPortNameWithCountry($rows['LOAD_PORT_NAME']);?></textarea>
								<?php }else{?>
								   <textarea class="form-control areasize" name="txtLoadPortName" id="txtLoadPortName" rows="2" placeholder="Port of Loading..."><?php echo $obj->shortPortNameWithCountry($lp_name);?></textarea>
								<?php }?>
								</address>
							</div><!-- /.col -->                     
							<div class="col-sm-4 invoice-col">
								 <strong>Port of Discharging</strong>
								<address>
							    <?php if($rec > 0){?>
								   <textarea class="form-control areasize" name="txtDischargePortName" id="txtDischargePortName" rows="2" placeholder="Port of Discharging..."><?php echo $obj->shortPortNameWithCountry($rows['DISCHARGE_PORT_NAME']);?></textarea>
								<?php }else{?>
								   <textarea class="form-control areasize" name="txtDischargePortName" id="txtDischargePortName" rows="2" placeholder="Port of Discharging..."><?php echo $obj->shortPortNameWithCountry($dp_name);?></textarea>
								<?php }?>
								</address>
							</div><!-- /.col -->
						</div>
					    
						
						<div class="row invoice-info">
							<div class="col-sm-3 invoice-col">
								<strong>BL Date</strong>
								<address>
								   
								   <input type="text" name="txtBLDate" id="txtBLDate"  autocomplete="off" class="form-control" value="<?php echo $rows['BL_DATE'];?>"/>
								</address>
							</div><!-- /.col -->                     
							<div class="col-sm-3 invoice-col">
								 <strong>BL No.</strong>
								<address>
								   <input type="text" name="txtBLNo" id="txtBLNo"  autocomplete="off" class="form-control" value="<?php echo $rows['BL_NO'];?>"/>
								</address>
							</div><!-- /.col -->
							<div class="col-sm-3 invoice-col">
								<strong>Flag</strong>
								<address>
								   <input type="text" name="txtFlag" id="txtFlag"  autocomplete="off" class="form-control" value="<?php if($rec == 0){echo $obj->getCountryNameBasedOnID($obj->getVesselIMOData($obj->getCompareEstimateData($comid,"VESSEL_IMO_ID"),"FLAG"));}else{echo $rows['FLAG'];}?>"/>
								</address>
							</div><!-- /.col -->
							<div class="col-sm-3 invoice-col">
								<strong>IMO No.</strong>
								<address>
								   <input type="text" name="txtIMONo" id="txtIMONo"  autocomplete="off" class="form-control" value="<?php if($rec == 0){echo $obj->getVesselIMOData($obj->getCompareEstimateData($comid,"VESSEL_IMO_ID"),"IMO_NO");}else{echo $rows['IMO_NO'];}?>"/>
								</address>
							</div><!-- /.col -->
						</div>
									<?php 
									
										$sqlForQtyNRate = 'select BL_QTY_FREIGHT,FREIGHT_GROSS from
										freight_cost_estimete_master where FCAID="'.$fcaid.'" and COMID="'.$comid.'" and MCOMPANYID="'.$_SESSION['company'].'" and MODULEID="'.$_SESSION['moduleid'].'"';

										// echo $sqlForQtyNRate;

										$resForQtyNRate = mysql_query($sqlForQtyNRate) or die($sqlForQtyNRate);

										$rowForQtyNRate = mysql_fetch_assoc($resForQtyNRate);

									
									?>
						<div class="row invoice-info">
							<div class="col-sm-3 invoice-col">
								<strong>BL QUANTITY</strong>
								<address>
								   
								   <input type="text" name="txtBLQuantity" id="txtBLQuantity"  autocomplete="off" class="form-control" value="<?php echo $rowForQtyNRate['BL_QTY_FREIGHT'];?>" readonly/>
								</address>
							</div><!-- /.col -->                     
							<div class="col-sm-3 invoice-col">
								 <strong>FRIEGHT RATE</strong>

								
								<address>
								   <input type="text" name="txtFrieghtRate" id="txtFrieghtRate"  autocomplete="off" class="form-control" value="<?php echo $rowForQtyNRate['FREIGHT_GROSS'].' USD/MT';?>" readonly/>
								</address>
							</div><!-- /.col -->
							
						</div>
					    
                        <div class="row invoice-info">
						   <div class="col-sm-6 invoice-col">
                               <div class="table-responsive">
                                    <table class="table">
                                        <tbody>
                                        <tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;">Invoice Type :</th>
                                            <td><select  name="selIType" class="select form-control" id="selIType"><?php $obj->getInvoiceTypeForInterimFinal($invtype);?></select></td>
                                        </tr>
                                        <script>$("#selIType").val('<?php echo $rows['I_TYPE'];?>');</script>
                                        <tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;">Attn :</th>
                                            <td><input type="text" name="txtAttenName" id="txtAttenName" class="form-control"  placeholder="Attn" autocomplete="off" value="<?php echo $rows['ATTEN'];?>"/></td>
                                        </tr>
                                        <tr>
                                            <th style="padding-top:15px;padding-bottom:15px;">Invoice Number :</th>
                                            <td>
											<?php if($rec == 0){?>
                                            <input type="text" name="txtDNote" id="txtDNote" class="form-control" placeholder="Invoice No." value=""/>
                                            <input type="hidden" name="txtDNote1" id="txtDNote1" value="" readonly/>
                                            <?php }else{?>
                                            <input type="text" name="txtDNote" id="txtDNote" class="form-control" placeholder="Invoice No." value="<?php echo $rows['MESSAGE'];?>"/>
                                            <input type="hidden" name="txtInvoiceid" id="txtInvoiceid" value="<?php echo $rows['INVOICEID'];?>" readonly/>
                                            <input type="hidden" name="txtDNote1" id="txtDNote1" value="<?php echo $rows['MESSAGE'];?>" readonly/>
                                            <?php }?></td>
                                        </tr>
                                        <?php
										$invdate = date('d-m-Y',strtotime($rows['DATE']));
										if($invdate=='01-01-1970'){$invdate = '';}
										$duedate = date('d-m-Y',strtotime($rows['DUE_DATE']));
										if($duedate=='01-01-1970'){$duedate = '';}
										$exchangeDate = date('d-m-Y',strtotime($rows['EXCHANGE_DATE']));
										if($exchangeDate=='01-01-1970'){$exchangeDate = '';}
										?>
                                        <tr>
                                            <th style="padding-top:15px;padding-bottom:15px;">Invoice Date :</th>
                                            <td><input type="text" name="txtDate" id="txtDate"  autocomplete="off" class="form-control" value="<?php echo $invdate;?>"/></td>
                                        </tr>
                                        <tr>
                                            <th style="padding-top:15px;padding-bottom:15px;">Due Date :</th>
                                            <td><input type="text" name="txtDueDate" id="txtDueDate" class="form-control datepicker"  placeholder="dd-mm-yyyy" autocomplete="off" value="<?php echo $duedate;?>"/></td>
                                        </tr>
                                        
                                        <tr>
                                            <th style="padding-top:15px;padding-bottom:15px;">Exchange Rate :</th>
                                            <td><input type="text" name="txtExchangeRate" id="txtExchangeRate" class="form-control numeric"  placeholder="Exchange Rate" autocomplete="off" value="<?php echo $rows['EXCHANGE_RATE'];?>"/></td>
                                        </tr>
                                        <tr>
                                            <th style="padding-top:15px;padding-bottom:15px;">Exchange Date :</th>
                                            <td><input type="text" name="txtExchangeDate" id="txtExchangeDate" class="form-control datepicker"  placeholder="dd-mm-yyyy" autocomplete="off" value="<?php echo $exchangeDate;?>"/></td>
                                        </tr>
                                        <tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;">Exchange To Currency :</th>
                                            <td><select  name="selExchangeCurrency" class="select form-control" id="selExchangeCurrency"><?php $obj->getCurrencyList();?></select></td>
                                        </tr>
                                        <script>$("#selExchangeCurrency").val('<?php echo $rows['EXCHANGE_CURRENCY'];?>');</script>
                                        
                                        <tr>
                                            <th style="padding-top:15px;padding-bottom:15px;">Payment Terms :</th>
                                            <td><input type="text" name="txtPaymentTerms" id="txtPaymentTerms" class="form-control"  placeholder="Payment Terms" autocomplete="off" value="<?php echo $rows['PAYMENT_TERMS'];?>"/></td>
                                        </tr>
                                        <tr>
                                            <th style="padding-top:15px;padding-bottom:15px;">Description :</th>
                                            <td><textarea name="txtDesc" id="txtDesc" class="form-control autosize" rows="3" placeholder="Description"><?php echo $rows['REMARKS'];?></textarea></td>
                                        </tr>
                                        <tr>
                                            <th style="padding-top:15px;padding-bottom:15px;">Banking Details :</th>
                                            <td><select  name="selNOB" class="select form-control" id="selNOB" onChange="getBankingDetailsData()"><?php $obj->getBankingDetails();?></select></td>
                                            <script>$('#selNOB').val('<?php echo $rows['NOB'];?>');</script>
                                        </tr>
                                     </tbody>
                                     <tbody id="bankingrow" style="display:none;">
                                        <tr>
											<td>Address</td>
											<td><span id="span_1_0"></span></td>
										</tr>
										<tr>
											<td>Beneficiary A/C No.</td>
											<td><span id="span_1_1"></span></td>
										</tr>
										<tr>
											<td>Beneficiary Bank</td>
											<td><span id="span_1_2"></span></td>
										</tr>
										<tr>
											<td>Beneficiary Bank Address</td>
											<td><span id="span_1_3"></span></td>
										</tr>
										<tr>
											<td>Beneficiary Bank Swift Code</td>
											<td><span id="span_1_4"></span></td>
										</tr>
										<tr>
											<td>IBAN No.</td>
											<td><span id="span_1_5"></span></td>
										</tr>
										<tr>
											<td>FED ABA</td>
											<td><span id="span_1_6"></span></td>
										</tr>
										<tr>
											<td colspan="4" style="background-color:grey; color:white;"><input type="checkbox" class="c_bank_check" name="c_bank_check" value="Yes"  <?=$rows['c_bank_check']=='Yes'?'checked':''?> > CORRESPONDENT DETAILS</td>
										</tr>
										<tr>
											<td>Correspondent Bank Name</td>
											<td><span id="span_1_7"></span></td>
										</tr>
										
                                        <tr>
                                            <td>Correspondent Bank Address</td>
											<td><span id="span_1_9"></span></td>
										</tr>
                                        <tr>
											<td>Account Number</td>
											<td><span id="span_1_10"></span></td>
										</tr>
                                        <tr>
											<td>Swift Code</td>
											<td><span id="span_1_8"></span></td>
										</tr>
										<tr>
											<td>IFSC</td>
											<td><span id="span_1_11"></span></td>
										</tr>
                                     </tbody>
									 <tbody>
									    <tr>
											<td><strong>Documents</strong></td>
											<td>
											<div class="btn btn-success btn-file btn-flat" data-toggle="tooltip">
											<i class="fa fa-paperclip"></i> Attachment
											<input type="file" class="form-control" multiple name="attach_file[]" id="attach_file" title="" data-widget="Attachment" data-toggle="tooltip" data-original-title="Attachment"/>
											</div>
											<br/>
											<?php if($rows['UPLOAD'] != '')
											{ 
												$fileid = explode(",",$rows['UPLOAD']); 
												$filename = explode(",",$rows['UPLOAD_NAME']); ?>	
											   <?php
												$j =1;
												for($i=0;$i<sizeof($fileid);$i++)
												{
												?>
												<tr id="row_file_<?php echo $j;?>">
													<td width="40%" align="left" class="input-text"  valign="top"><a href="../../attachment/<?php echo $fileid[$i]; ?>" target="_blank" style="color:blue;" data-toggle="tooltip" data-original-title="<?php echo $filename[$i];?>"><i class="fa fa-external-link"></i>&nbsp;&nbsp;<?php echo $filename[$i];?></a>
													<input type="hidden" name="file_<?php echo $j;?>" id="file_<?php echo $j;?>" value="<?php echo $fileid[$i]; ?>" />
													<input type="hidden" name="name_<?php echo $j;?>" id="name_<?php echo $j;?>" value="<?php echo $filename[$i]; ?>" />
													</td>
													<td ><a href="#1" onClick="Del_Upload(<?php echo $j;?>);"><i class="fa fa-times " style="color:red;"></i></a></td>
												</tr>
											   <?php $j++;}?>
									   <?php }?>
											</td>
										</tr>
									 </tbody>
                                   </table>
                               </div>
						   </div><!-- /.col -->
						   <div class="col-sm-6 invoice-col">
							   <div class="table-responsive">
                                    <table class="table">
                                        <tbody>
								<?php if($obj->getFun71() > 0)
								     {?>
									    <tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="2">Net Freight(<?php echo $currency;?>) :</th>
                                            <td><input type="text" name="txtGrossFreightNet" id="txtGrossFreightNet" class="form-control" readonly value="<?php echo $obj->getFun66();?>"></td>
                                        </tr>
										<tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="2">Dead Freight(<?php echo $currency;?>) :</th>
                                            <td><input type="text" name="txtGrossFreightDead" id="txtGrossFreightDead" class="form-control" readonly value="<?php echo $obj->getFun67();?>"></td>
                                        </tr>
								<?php }?>
                                        <?php 
										$jk = 0;
										foreach($clubcharterer as $clubcharterer1){$jk++;
										$sql12 = "select * from freight_invoice_slave1 where VENDOR='".$clubcharterer1['charterer']."' and CARGO='".$clubcharterer1['cargoid']."' and RANDOMID='".$clubcharterer1['randomid']."' and INVOICEID='".$rows['INVOICEID']."' ";
										$res12 = mysql_query($sql12) or die($sql12);
										$num12 = mysql_num_rows($res12);
										
										$sql121 = "select * from freight_invoice_slave1 inner join freight_invoice_master on freight_invoice_master.INVOICEID=freight_invoice_slave1.INVOICEID where freight_invoice_slave1.VENDOR='".$clubcharterer1['charterer']."' and freight_invoice_slave1.CARGO='".$clubcharterer1['cargoid']."' and COMID='".$comid."' and MODULEID='".$_SESSION['moduleid']."' and MCOMPANYID='".$_SESSION['company']."' and freight_invoice_slave1.RANDOMID='".$clubcharterer1['randomid']."' ";
										$res121 = mysql_query($sql121) or die($sql121);
										$num121 = mysql_num_rows($res121);
										?>


										<tr>
										    <th><input name="chkClubFreight_<?php echo $jk;?>" id="chkClubFreight_<?php echo $jk;?>" type="checkbox" style="cursor:pointer;" <?php if($num12>0 || $num121>0){echo "checked";}?> value="<?php echo $jk;?>"/><input type="hidden" name="hddnVendorid_<?php echo $jk;?>" id="hddnVendorid_<?php echo $jk;?>" value="<?php echo $clubcharterer1['charterer'];?>"><input type="hidden" name="hddncargoid_<?php echo $jk;?>" id="hddncargoid_<?php echo $jk;?>" value="<?php echo $clubcharterer1['cargoid'];?>"><input type="hidden" name="hddnrandomid_<?php echo $jk;?>" id="hddnrandomid_<?php echo $jk;?>" value="<?php echo $clubcharterer1['randomid'];?>"></th>
                                            <th><?php echo $clubcharterer1['charterer_name'];?>(<?php echo $clubcharterer1['cargo_name'];?>) :</th>
                                            <td><input type="text" name="txtClubFreight_<?php echo $jk;?>" id="txtClubFreight_<?php echo $jk;?>" class="form-control" readonly value="<?php echo $clubcharterer1['amount'];?>"></td>
                                        </tr>
										<?php }?>
                                        <tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="2">Gross Freight(<?php echo $currency;?>) :</th>

											
                                            <td>
												
											<input type="text" name="txtGrossFreight" data-amt="<?=$add_qty_less_perc_total?>" id="txtGrossFreight" class="form-control" readonly value="<?php   echo $add_qty_less_perc_total;?>">
											
											<input type="hidden" name="hddnClubcount" id="hddnClubcount" value="<?php  echo $jk;?>"></td>
                                        </tr>
                                        
                                        <tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="2">% There Off :</th>
                                            <td><input type="text" name="txtTO" id="txtTO" class="form-control" value="<?php echo $rows['TO_1'];?>" style="text-align:right;" onKeyUp="getAmountThereOff()" autocomplete="off"/><input type="hidden" name="txtFinlGrossFreight" id="txtFinlGrossFreight" class="form-control" readonly value="<?php echo $net_paid;?>"></td>
                                        </tr>
                                        <tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="2"></th>
                                            <td><?php if($rec == 0){?>
											<input type="text"  name="txtNet" id="txtNet" class="form-control" readonly value="0" />
											<?php }else{?>
											<input type="text"  name="txtNet" id="txtNet" class="form-control" readonly value="<?php echo $rows['NET_AMOUNT'];?>" />
											<?php }?></td>
                                        </tr>
                                        <!--<tr>
											<th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="2">Balance</th>
											<td><input type="text"  name="txtBalanceFreight" id="txtBalanceFreight" class="form-control" readonly value="" /></td>	
										</tr>-->

										
										
										<?php 
										
										// echo '<pre>';

										// print_r($rows);

										// die();

										?>
										<?php 	if($obj->getFun155()==2){ ?>
                                        <tr>
												<th style="width:70%;padding-top:15px;padding-bottom:15px;" colspan="2"><input name="chkProRate" class="checkbox" id="chkProRate" type="checkbox"  value="1" <?= ($rows['PRORATE']==1)?'checked="checked"':'';?>/>&nbsp;&nbsp;Prorate</th>

										</tr>
										<?php } ?>

										<input type="hidden"  name="setProRate" id="setProRate" value="">
                                        
                                        <tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="3">Demurrage/Dispatch</th>
                                        </tr>
										
										<?php 
										$sql121    = "select * from freight_cost_estimete_slave1 where FCAID='".$obj->getFun1()."' order by FCA_SLAVEID";
										$result    = mysql_query($sql121);
										$record    = mysql_num_rows($result);
										if($record > 0){$i = 0;
										while($rows11 = mysql_fetch_array($result))
										{
										    if($rows11['IS_SHOW_DDCLP'] == NULL && $rows11['DDCLP_VENDOR'] == $vendorid)
										    {$i++;
											$sql12 = "select count(*) as count from freight_invoice_slave3 where INVOICEID='".$rows['INVOICEID']."' and VENDORID='".$vendorid."' and RANDOMID='".$rows11['RANDOMID']."' and PORT='LP' and PORTID='".$rows11['FROM_PORT']."' ";
											$res12 = mysql_query($sql12) or die($sql12);
											$rows12 = mysql_fetch_assoc($res12);
											
											$sql13 = "select count(*) as count from freight_invoice_slave3 inner join freight_invoice_master on freight_invoice_master.INVOICEID=freight_invoice_slave3.INVOICEID where freight_invoice_slave3.VENDORID='".$vendorid."' and freight_invoice_master.COMID='".$comid."' and freight_invoice_slave3.RANDOMID='".$rows11['RANDOMID']."' and freight_invoice_slave3.PORT='LP' and freight_invoice_slave3.PORTID='".$rows11['FROM_PORT']."' ";
											$res13 = mysql_query($sql13) or die($sql13);
											$rows13 = mysql_fetch_assoc($res13);
											
											if($rows12['count']>0){$checkdem = 1;}else if($rows13['count']>0 && $rec == 0){$checkdem = 1;}else{$checkdem = 0;}
										?>
                                            <tr>
                                                <td colspan="2"><input name="chkDemDis_<?=$i;?>" class="checkbox" id="chkDemDis_<?=$i;?>" type="checkbox" value="1" <?=($checkdem==1)?'checked="checked"':''?>/>&nbsp;&nbsp;Load Port <?php echo $obj->shortPortNameWithCountry($obj->getPortNameBasedOnID($rows11['FROM_PORT']));?>
												<input type="hidden" name="txtDemDisPort_<?=$i;?>" id="txtDemDisPort_<?=$i;?>" value="LP" />
												<input type="hidden" name="txtDemDisPortid_<?=$i;?>" id="txtDemDisPortid_<?=$i;?>" value="<?=$rows11['FROM_PORT'];?>" />
												<input type="hidden" name="txtDemDisRandomid_<?=$i;?>" id="txtDemDisRandomid_<?=$i;?>" value="<?=$rows11['RANDOMID'];?>" />
												<input type="hidden" name="txtDemDisVendorid_<?=$i;?>" id="txtDemDisVendorid_<?=$i;?>" value="<?=$rows11['DDCLP_VENDOR'];?>" />
												</td>

												<?php
												if($obj->getFun155()==2){
													

													$total_qty=mysql_fetch_assoc(mysql_query("select SUM(QUANTITY) as TOTAL_QTY from freight_cost_estimete_slave7 where FCAID='".$obj->getFun1()."' and QTY_VENDORID='".$vendorid."'  and CARGO!=''"))['TOTAL_QTY'];

													

													
													
													// $rows11['DDCDP_NETCOST']

													if($rows['PRORATE']==1){
														$dem_des_cost=round((($rows11['DDCLP_NETCOST']*$id[5])/$total_qty), 2);
														$dem_des_cost_des=round((($rows11['DDCDP_NETCOST']*$id[5])/$total_qty), 2);


													}else{
														$dem_des_cost=$rows11['DDCLP_NETCOST'];
														$dem_des_cost_des=$rows11['DDCDP_NETCOST'];

													}
													
												
													
												}else{
													if($rows['PRORATE']==0){
													
													$dem_des_cost=$rows11['DDCLP_NETCOST'];
													$dem_des_cost_des=$rows11['DDCDP_NETCOST'];
												}
													else{
														$dem_des_cost=round((($rows11['DDCLP_NETCOST']*$id[5])/$total_qty), 2);
														$dem_des_cost_des=round((($rows11['DDCDP_NETCOST']*$id[5])/$total_qty), 2);
													}
												}
												?>
                                                <td><input type="text"  name="txtDemDisAmt_<?=$i;?>" id="txtDemDisAmt_<?=$i;?>" class="form-control" readonly value="<?=$dem_des_cost;?>" /></td>


												<input type="hidden" name="IS_SHOW_DDCLP_CHECK_<?=$i;?>" id="IS_SHOW_DDCLP_CHECK_<?=$i;?>" value="1"> 

												<input type = "hidden" name="ttlQuantity_<?=$i;?>" id="ttlQuantity_<?=$i;?>" value="<?= $total_qty?>">
												<input type = "hidden" name="DDCLP_NETCOST_CHECK_<?=$i;?>" id="DDCLP_NETCOST_CHECK_<?=$i;?>" value="<?= $rows11['DDCLP_NETCOST']?>">
												<input type = "hidden" name="DDCDP_NETCOST_CHECK_<?=$i;?>" id="DDCDP_NETCOST_CHECK_<?=$i;?>" value="<?= $rows11['DDCDP_NETCOST']?>">
												<input type = "hidden" name="id5_<?=$i;?>" id="id5_<?=$i;?>" value="<?= $id[5]; ?>">

                                            </tr>
                                      <?php }
											if($rows11['IS_SHOW_DDCDP'] == NULL && $rows11['DDCDP_VENDOR'] == $vendorid)
											{$i++;
											
											$sql12 = "select count(*) as count from freight_invoice_slave3 where INVOICEID='".$rows['INVOICEID']."' and VENDORID='".$vendorid."' and RANDOMID='".$rows11['RANDOMID']."' and PORT='DP' and PORTID='".$rows11['TO_PORT']."' ";
											$res12 = mysql_query($sql12) or die($sql12);
											$rows12 = mysql_fetch_assoc($res12);
											
											$sql13 = "select count(*) as count from freight_invoice_slave3 inner join freight_invoice_master on freight_invoice_master.INVOICEID=freight_invoice_slave3.INVOICEID where freight_invoice_slave3.VENDORID='".$vendorid."' and freight_invoice_master.COMID='".$comid."' and freight_invoice_slave3.RANDOMID='".$rows11['RANDOMID']."' and freight_invoice_slave3.PORT='DP' and freight_invoice_slave3.PORTID='".$rows11['TO_PORT']."' ";
											$res13 = mysql_query($sql13) or die($sql13);
											$rows13 = mysql_fetch_assoc($res13);
											if($rows12['count']>0){$checkdem = 1;}else if($rows13['count']>0 && $rec == 0){$checkdem = 1;}else{$checkdem = 0;}


											if($obj->getFun155()==2){
													

												$total_qty=mysql_fetch_assoc(mysql_query("select SUM(QUANTITY) as TOTAL_QTY from freight_cost_estimete_slave7 where FCAID='".$obj->getFun1()."' and QTY_VENDORID='".$vendorid."'  and CARGO!=''"))['TOTAL_QTY'];

												

												
												
												// $rows11['DDCDP_NETCOST']

												if($rows['PRORATE']==1){
												
												$dem_des_cost=round((($rows11['DDCLP_NETCOST']*$id[5])/$total_qty), 2);
												$dem_des_cost_des=round((($rows11['DDCDP_NETCOST']*$id[5])/$total_qty), 2);
												}else{
													$dem_des_cost=$rows11['DDCLP_NETCOST'];
													$dem_des_cost_des=$rows11['DDCDP_NETCOST'];
												}
												
											}else{

												if($rows['PRORATE']==0){
												$dem_des_cost=$rows11['DDCLP_NETCOST'];
												$dem_des_cost_des=$rows11['DDCDP_NETCOST'];
												}else{
													$dem_des_cost=round((($rows11['DDCLP_NETCOST']*$id[5])/$total_qty), 2);
													$dem_des_cost_des=round((($rows11['DDCDP_NETCOST']*$id[5])/$total_qty), 2);

												}
											}

											?>
											<tr>

											<input type="hidden" name="IS_SHOW_DDCLP_CHECK_<?=$i;?>" id="IS_SHOW_DDCLP_CHECK_<?=$i;?>" value="0"> 
											<input type = "hidden" name="ttlQuantity_<?=$i;?>" id="ttlQuantity_<?=$i;?>" value="<?= $total_qty?>">
											<input type = "hidden" name="DDCLP_NETCOST_CHECK_<?=$i;?>" id="DDCLP_NETCOST_CHECK_<?=$i;?>" value="<?= $rows11['DDCLP_NETCOST']?>">
											<input type = "hidden" name="DDCDP_NETCOST_CHECK_<?=$i;?>" id="DDCDP_NETCOST_CHECK_<?=$i;?>" value="<?= $rows11['DDCDP_NETCOST']?>">
											<input type = "hidden" name="id5_<?=$i;?>" id="id5_<?=$i;?>" value="<?= $id[5]; ?>">
                                                <td colspan="2"><input name="chkDemDis_<?=$i;?>" class="checkbox" id="chkDemDis_<?=$i;?>" type="checkbox" value="1" <?=($checkdem==1)?'checked="checked"':''?>/>&nbsp;&nbsp;Discharge Port <?php echo $obj->shortPortNameWithCountry($obj->getPortNameBasedOnID($rows11['TO_PORT']));?>
												<input type="hidden" name="txtDemDisPort_<?=$i;?>" id="txtDemDisPort_<?=$i;?>" value="DP" />
												<input type="hidden" name="txtDemDisPortid_<?=$i;?>" id="txtDemDisPortid_<?=$i;?>" value="<?=$rows11['TO_PORT'];?>" />
												<input type="hidden" name="txtDemDisRandomid_<?=$i;?>" id="txtDemDisRandomid_<?=$i;?>" value="<?=$rows11['RANDOMID'];?>" />
												<input type="hidden" name="txtDemDisVendorid_<?=$i;?>" id="txtDemDisVendorid_<?=$i;?>" value="<?=$rows11['DDCDP_VENDOR'];?>" />
												</td>

												<!-- testldj -->
                                                <td><input type="text"  name="txtDemDisAmt_<?=$i;?>" id="txtDemDisAmt_<?=$i;?>" class="form-control" readonly value="<?= $dem_des_cost_des;?>" /></td>
                                            </tr>
                                        <?php }}}?>
										<tr>
                                            <th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="3">Other Add <input type="hidden" name="txtDemDisID" id="txtDemDisID" value="<?=$i;?>" /></th>
                                        </tr>
                                     </tbody>
                                     <?php $sql2 = "select * from freight_invoice_slave where INVOICEID='".$rows['INVOICEID']."' and IDENTIFY='ADD'";
										   $res2 = mysql_query($sql2);
										   $num2 = mysql_num_rows($res2);
										   if($num2 >0){$num21 = $num2;}else{$num21 = 1;}
									       ?>
                                      <tbody id="tblAdd">
                                  <?php if($num2 >0)
									    {$i = 0;
										  while($rows2 = mysql_fetch_assoc($res2))
										  {$i++;
										  ?>
										    <tr id="add_Row_<?php echo $i;?>">
										  	    <td align="center"><a href="#pr<?php echo $i;?>" onClick="removeAddRow(<?php echo $i;?>);"><i class="fa fa-times" style="color:red;"></i></a></td>
										     	<td><textarea class="form-control areasize" name="txtAddDes_<?php echo $i;?>" id="txtAddDes_<?php echo $i;?>" rows="2" placeholder="Description..."><?php echo $rows2['DESCRIPTION'];?></textarea></td>
										   	    <td><input type="text" name="txtAddDesAmt_<?php echo $i;?>" id="txtAddDesAmt_<?php echo $i;?>" class="form-control numeric"  placeholder="Amount" autocomplete="off" value="<?php echo $rows2['AMOUNT'];?>" onKeyUp="getAmountThereOff();"/></td>
										    </tr>
										<?php }}else{?>
										   <tr id="add_Row_1">
										       <td align="center"><a href="#pr1" onClick="removeAddRow(1);"><i class="fa fa-times" style="color:red;"></i></a></td>
										       <td><textarea class="form-control areasize" name="txtAddDes_1" id="txtAddDes_1" rows="2" placeholder="Description..."></textarea></td>
										       <td><input type="text" name="txtAddDesAmt_1" id="txtAddDesAmt_1" class="form-control numeric"  placeholder="Amount" autocomplete="off" value="" onKeyUp="getAmountThereOff();"/></td>
										   </tr>
								   <?php }?>
                                       </tbody>
                                       <tbody>
                                           <tr>
                                               <td align="left" colspan="3"><button type="button" class="btn btn-primary btn-flat" onClick="AddNewAddRow();">Add</button><input type="hidden" name="txtAddID" id="txtAddID" value="<?php echo $num21;?>"/></td>
                                           </tr>
                                           
                                           <tr>
                                               <th colspan="3">Other Less</th>
                                           </tr>
                                           <tr>
											<td style="width:25%;padding-top:15px;padding-bottom:15px;"><i>Brokerage (%)</i></td>
											<td style="width:40%;padding-top:15px;padding-bottom:15px;"><input type="text" name="txtBrokerage" id="txtBrokerage" class="form-control" onKeyUp="getAmountThereOff();" autocomplete="off" value="<?php echo $rows['BROKERAGE_PERCENT'];?>"></td>	
                                            <td><input type="text" name="txtBrokerageAmt" id="txtBrokerageAmt" class="form-control" readonly value="<?php echo $rows['BROKERAGE'];?>"></td>
										   </tr>
                                           <tr>
											<td style="width:25%;padding-top:15px;padding-bottom:15px;"><i>GST on brokrage (%)</i></td>
											<td style="width:40%;padding-top:15px;padding-bottom:15px;"><input type="text" name="gst_on_brokage_perc" id="gst_on_brokage_perc" class="form-control" onKeyUp="getAmountThereOff();" autocomplete="off" value="<?php echo $rows['GST_ON_BROK_PERC'];?>"></td>	
                                            <td><input type="text" name="gst_on_brokage" id="gst_on_brokage" class="form-control" readonly value="<?php echo $rows['GST_ON_BROK'];?>"></td>
										   </tr>
                                           <tr>
											<td style="width:25%;padding-top:15px;padding-bottom:15px;"><i>Less Addcom</i></td>
											<td style="width:40%;padding-top:15px;padding-bottom:15px;"><input type="text" name="txtAddComm" id="txtAddComm" class="form-control"  placeholder="Addcom %" autocomplete="off" value="<?php if($rec > 0){echo $rows['ADDCOM'];}else{echo $obj->getFun74();}?>" onKeyUp="getAmountThereOff();"/></td>	
                                            <td><input type="text" name="txtAddCommAmt" id="txtAddCommAmt" class="form-control"  placeholder="Amount" autocomplete="off" value="<?php echo $rows['ADDCOM_AMOUNT'];?>" readonly/></td>	
										   </tr>
                                           
                                      <?php $sql2 = "select * from freight_invoice_slave where INVOICEID='".$rows['INVOICEID']."' and IDENTIFY='SUB'";
											$res2 = mysql_query($sql2);
											$num2 = mysql_num_rows($res2);
											if($num2 >0){$num21 = $num2;}else{$num21 = 1;}?>
                                       </tbody>
                                       <tbody id="tblSub">
                                     <?php if($num2 >0)
										   {$i = 0;
											while($rows2 = mysql_fetch_assoc($res2))
											{$i++;
											?>
											<tr id="Sub_Row_<?php echo $i;?>">
											   <td align="center"><a href="#pr<?php echo $i;?>" onClick="removeSubRow(<?php echo $i;?>);"><i class="fa fa-times" style="color:red;"></i></a></td>
											   <td><textarea class="form-control areasize" name="txtSubDes_<?php echo $i;?>" id="txtSubDes_<?php echo $i;?>" rows="2" placeholder="Description..."><?php echo $rows2['DESCRIPTION'];?></textarea></td>
											   <td><input type="text" name="txtSubDesAmt_<?php echo $i;?>" id="txtSubDesAmt_<?php echo $i;?>" class="form-control numeric"  placeholder="Amount" autocomplete="off" value="<?php echo $rows2['AMOUNT'];?>" onKeyUp="getAmountThereOff();"/></td>
											</tr>
											<?php }}else{?>
											<tr id="Sub_Row_1">
											   <td align="center"><a href="#pr1" onClick="removeSubRow(1);"><i class="fa fa-times" style="color:red;"></i></a></td>
											   <td><textarea class="form-control areasize" name="txtSubDes_1" id="txtSubDes_1" rows="2" placeholder="Description..."></textarea></td>
											   <td><input type="text" name="txtSubDesAmt_1" id="txtSubDesAmt_1" class="form-control numeric"  placeholder="Amount" autocomplete="off" value="" onKeyUp="getAmountThereOff();"/></td>
											</tr>
									<?php }?>
                                       </tbody>
                                       <tbody>
                                           <tr>
                                               <td align="left" colspan="3"><button type="button" class="btn btn-primary btn-flat" onClick="SubNewSubRow();">Add</button><input type="hidden" name="txtSubID" id="txtSubID" value="<?php echo $num21;?>"/></td>
                                           </tr>
                                           <tr>
                                                <td colspan="2"><strong>Amount Payable</strong></td>
                                                <td><input type="text"  name="txtNetAmtPayable" id="txtNetAmtPayable" class="form-control" readonly value="<?php echo $rows['NET_PAYABLE'];?>" /></td>
                                           </tr>
										   
                                           
										   <tr>
                                                <td><strong>GST/VAT Applicable</strong></td>
                                                <td><input name="rdoTaxApplicable" class="checkbox" id="rdoTaxApplicable1" type="radio" value="1" <?php if($rows['RDOTAXAPPLICABLE'] == 1) echo "checked"; ?> <?php if($rec == 0){?>checked<?php }?>/>&nbsp;&nbsp;Yes&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name="rdoTaxApplicable" class="checkbox" id="rdoTaxApplicable2" type="radio" value="2" <?php if($rows['RDOTAXAPPLICABLE'] == 2) echo "checked"; ?>/>&nbsp;&nbsp;No</td>
												<td><span id="taxRadioDiv"><input name="rdoGSTVAT" class="checkbox" id="rdoGSTVAT1" type="radio" value="1" <?php if($rows['RDOVATGST'] == 1) echo "checked"; ?> <?php if($rec == 0){?>checked<?php }?>/>&nbsp;&nbsp;GST&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name="rdoGSTVAT" class="checkbox" id="rdoGSTVAT2" type="radio" value="2" <?php if($rows['RDOVATGST'] == 2) echo "checked"; ?>/>&nbsp;&nbsp;VAT</span></td>
                                           </tr>

										 

										   <tr id="taxtDiv_1">
                                                <td><i>SGST (%)</i></td>
                                                <td><input type="text" name="txtSGST" id="txtSGST" class="form-control numeric"  placeholder="%" autocomplete="off" value="<?=$rows['SGST_PERCENT'];?>" onKeyUp="readonlytextbox();getAmountThereOff();"/></td>
												<td><input type="text" name="txtSGST_Amount" id="txtSGST_Amount" class="form-control numeric"  placeholder="%" autocomplete="off" readonly="true" value="<?=$rows['SGST_PERCENT_AMOUNT'];?>"/></td>
                                           </tr>
										   <tr id="taxtDiv_2">
                                                <td><i>CGST (%)</i></td>
                                                <td><input type="text" name="txtCGST" id="txtCGST" class="form-control numeric"  placeholder="%" autocomplete="off" value="<?=$rows['CGST_PERCENT'];?>" onKeyUp="readonlytextbox();getAmountThereOff();"/></td>
												<td><input type="text" name="txtCGST_Amount" id="txtCGST_Amount" class="form-control numeric"  placeholder="%" autocomplete="off" readonly="true" value="<?=$rows['CGST_PERCENT_AMOUNT'];?>"/></td>
                                           </tr>
										   <tr id="taxtDiv_3">
                                                <td><i>IGST (%)</i></td>
                                                <td><input type="text" name="txtIGST" id="txtIGST" class="form-control numeric"  placeholder="%" autocomplete="off" value="<?=$rows['IGST_PERCENT'];?>" onKeyUp="readonlytextbox();getAmountThereOff();"/></td>
												<td><input type="text" name="txtIGST_Amount" id="txtIGST_Amount" class="form-control numeric"  placeholder="%" autocomplete="off" readonly="true" value="<?=$rows['IGST_PERCENT_AMOUNT'];?>"/></td>
                                           </tr>
										   <tr id="taxtDiv_4">
                                                <td><i>VAT (%)</i></td>
                                                <td><input type="text" name="txtVAT" id="txtVAT" class="form-control numeric"  placeholder="%" autocomplete="off" value="<?=$rows['VAT_PERCENT'];?>" onKeyUp="getAmountThereOff();"/></td>
												<td><input type="text" name="txtVAT_Amount" id="txtVAT_Amount" class="form-control numeric"  placeholder="%" autocomplete="off" readonly="true" value="<?=$rows['VAT_PERCENT_AMOUNT'];?>"/></td>
                                           </tr>
									<?php   $sql1 = "select * from freight_invoice_master where COMID='".$comid."' and MODULEID='".$_SESSION['moduleid']."' and MCOMPANYID='".$_SESSION['company']."' and VENDOR = '".$vendorid."' and P_TYPE='".$name."' and CARGOID='".$cargoid."' and RANDOMID='".$randomid."' and STATUS=5";
											$res1 = mysql_query($sql1);
											$i =0;
											while($rows1 = mysql_fetch_assoc($res1))
											{ $i++;
											?>
											<tr>
												<th style="width:50%;padding-top:15px;padding-bottom:15px;" colspan="2"><?php echo $rows1['I_TYPE'].'('.$rows1['MESSAGE'].')';?></th>
												<td><input type="text"  name="txtInvPAmt_<?php echo $i;?>" id="txtInvPAmt_<?php echo $i;?>" class="form-control" readonly value="<?php echo $rows1['P_AMT'];?>" /></td>	
											</tr>
										<?php }?>
										   <tr>
                                                <td colspan="2"><strong>Amount Payable (After TAX)</strong></td>
                                                <td><input type="text"  name="txtAmtPayableWithTax" id="txtAmtPayableWithTax" class="form-control" readonly value="<?php echo $rows['NET_PAYABLE_TAX'];?>" /></td>
                                           </tr>
										   <tr>
                                                <td colspan="2"><strong>Exchange To Currency <?php 
												
												if($rows['EXCHANGE_CURRENCY']!=' ')
												{
													echo '('.$rows['EXCHANGE_CURRENCY'].')';
												}else{
													echo  '&nbsp';
												}	
												

												
												
												?></strong></td>

												
                                                <td><input type="text"  name="txtEOC" id="txtEOC" class="form-control" readonly value=" " /></td>

												<script>

												

													$("#txtExchangeRate").keyup(function(){


													var exchangeRate = $(this).val();

													if(exchangeRate.length >= 1){
														var net_pay= $('#txtNetAmtPayable').val();

														$('#txtEOC').val(parseFloat(net_pay * exchangeRate).toFixed(2))

													}
													});

													$(function() {
													var exchangeRate = $('#txtExchangeRate').val();

													if(exchangeRate.length>=1){
														var net_pay= $('#txtAmtPayableWithTax').val();

														$('#txtEOC').val(parseFloat(net_pay * exchangeRate).toFixed(2))
													}
													});


													</script>
												</tr>
                                       </tbody>
                                   </table>
                               </div>
							<?php //if(($rec == 0 && !empty($approverarr1)) || ($rec > 0 )){?>
							   <div class="row invoice-info">
							       <div class="col-sm-4 invoice-col">
								       Level 1 Approver
								   </div>
								   <div class="col-sm-8 invoice-col">
								   <?php
								   if($invtype=='Interim')
									{
										$fieldname = 'INI_FREIGHT_CHK_APP_1';
									}else
									{
										$fieldname = 'FINL_FREIGHT_CHK_APP_1';
									}?>
								    
									<select data-placeholder="Choose Approver..." class="input-text chzn-select" style="width:300px;" multiple name="selApprovers[]" id="selApprovers"><?php $obj->getApproverListBasedOnApprovalMatrix($fieldname, $rows['APPROVERS']);?></select>
								   </div>
							   </div>
							   <div class="row invoice-info">
							       <div class="col-sm-12 invoice-col">&nbsp;</div>
							   </div>
						<?php //}?>
						   </div><!-- /.col -->
						</div>
                        
                        <div class="box-footer" align="right">
                            <input type="hidden" id="action" name="action" value="submit" />
                            <input type="hidden" name="txtStatus" id="txtStatus" value="0"/>
							<input type="hidden" name="txtCRMFILE" id="txtCRMFILE" value="" />
					        <input type="hidden" name="txtCRMNAME" id="txtCRMNAME" value="" />
					  <?php if(($rec==0 && $creator==1) || (($rows['STATUS']==0 || $rows['STATUS']==2) && $creator==1)){
					           if(empty($approverarr1) && empty($approverarr2)){$status = 5;}
							   else if(empty($approverarr1) && !empty($approverarr2)){$status = 4;}
							   else{$status = 1;}
					  ?>
							<button type="submit" class="btn btn-primary btn-flat" onClick="return getValidate(0);">Submit to edit</button>&nbsp;&nbsp;
							<button type="submit" class="btn btn-warning btn-flat" onClick="return getValidate(<?=$status;?>);">Send for Approval</button>
                      <?php }else if($rec>0 && ($rows['STATUS']==1 || $rows['STATUS']==4) && $approver1 == 1){
					             if(empty($approverarr2)){$status = 5;}
							     else{$status = 3;}
						   ?>
						    <button type="submit" class="btn btn-primary btn-flat" onClick="return getValidate(2);">Send for Review</button>&nbsp;&nbsp;
							<button type="submit" class="btn btn-warning btn-flat" onClick="return getValidate(<?=$status;?>);">Submit & Approve</button>
					  <?php }else if($rec>0 && $rows['STATUS']==3 && $approver2 == 1){
					           if(empty($approverarr1)){$status = 2;}
							   else{$status = 4;}
					  ?>
					        <button type="submit" class="btn btn-primary btn-flat" onClick="return getValidate(<?=$status;?>);">Send for Review</button>&nbsp;&nbsp;
					        <button type="submit" class="btn btn-warning btn-flat" onClick="return getValidate(5);">Submit & Approve</button>
					  <?php }?>
							<input type="hidden" name="txtFreightAmtLocal" id="txtFreightAmtLocal" value="<?php echo $id[7];?>" />	
                            						
						</div>
						<div class="box-footer" align="right">&nbsp;</div>
					</form>	

                    <form role="form" name="frm2" id="frm2" enctype="multipart/form-data" action="<?php echo $pagename;?>" method="post">
						<div class="box">
							
							<div class="box-body no-padding">
								<table class="table table-striped">
									<thead>
										<tr>
											<th>Fixture No.</th>
											<th>Vessel</th>
											<th>Invoice Type</th>
											<th>Invoice No.</th>
											<th>Charterer</th>
											<th>Amount</th>
                                            <th>Invoice PDF</th>

											<?php
											if($_SESSION['iutype'] == 'mgmt_user'){

												
												?>
													<th>Cancel Invoice</th>

											<?php
											}
											?>
											<!-- <th>Cancel Invoice</th> -->
											<th>Payment Received</th>
											<th>Description</th>
											<?php
											if($_SESSION['iutype'] == 'mgmt_user'){

												
												?>
											<th>Open</th>

											<?php
											}
											?>
										</tr>
									</thead>
									<tbody>
									<?php
									$sql = "select * from freight_invoice_master where COMID='".$comid."' and MODULEID='".$_SESSION['moduleid']."' and MCOMPANYID='".$_SESSION['company']."' and VENDOR = '".$vendorid."'  and P_TYPE='".$name."' and CARGOID='".$cargoid."' and RANDOMID='".$randomid."' and STATUS>=5";
									
									$res = mysql_query($sql);
									$rec = mysql_num_rows($res);
									
									if($rec == 0)
									{
									?>
									<tr>
										<td colspan="9" align="center" valign="middle" style="color:red;letter-spacing:1px;">SORRY CURRENTLY THERE ARE ZERO(0) RECORDS</td>
									</tr>
									<?php }else
									{
										// echo "<pre>";
										$i=0;
											$temp=0;
										while($rows = mysql_fetch_assoc($res)){

											
											$i=$temp;
										?>
									<tr data-status="<?=$rows['STATUS']?>" data-itype="<?=$obj->getInvoiceTypeName1($rows['I_TYPE'])?>">
										<td align="left" valign="middle" ><?php echo $obj->getCompareEstimateData($comid,"VOYAGE_NO");?></td>

									
										<td align="left" valign="middle"><?php echo $obj->getVesselIMOData($obj->getCompareEstimateData($comid,"VESSEL_IMO_ID"),"VESSEL_NAME");?></td>
										<td align="left" valign="middle"><?php echo $obj->getInvoiceTypeName1($rows['I_TYPE']);?>
										<input type="hidden" name="gridInvType_<?= $i ?>" id="gridInvType_<?= $i ?>" value="<?php echo $obj->getInvoiceTypeName1($rows['I_TYPE']);?>">
									</td>
										<td align="left" valign="middle"><?php echo $rows['MESSAGE'];?>
										<input type="hidden" name="gridInvNo_<?= $i ?>" id="gridInvNo_<?= $i ?>" value="<?php echo $rows['MESSAGE'];?>">
									</td>
										<td align="left" valign="middle"><?php echo $obj->getVendorListNewBasedOnID($rows['VENDOR']);?></td>
                                        <td align="left" valign="middle"><?php echo $rows['NET_PAYABLE_TAX'];?></td>
										<td align="center" valign="middle">
											<a href="#" title="Pdf" onClick="getPdf(<?php echo $rows['INVOICEID'];?>);"><button class="btn btn-default" type="button" style="margin-right: 5px;"><i class="fa fa-download"></i> Generate PDF</button></a>

											<?php if($rows['SHIP_OWNER']=='OB0002'){?>
											<hr>
										<a href="#" title="Pdf" onClick="getPdfForZero(<?php echo $rows['INVOICEID'];?>);"><button class="btn btn-warning" type="button" style="margin-right: 5px;"><i class="fa fa-download"></i> Generate PDF-AED</button></a>
											<?php } ?>
									    </td>

										<?php
											if ($_SESSION['iutype'] == 'mgmt_user') {
												?>

												<td>
											<?php  if($rows['STATUS'] == 5){?>
												 <a title="Cancel Link" href="#1" onClick="return getDelete(<?php  echo $rows['INVOICEID'];?>);" >
													<button class="btn btn-danger" type="button"><i class="fa fa-times"></i> Cancel</button>
												</a> 
												<?php  }else{?>
												 <span class="label label-danger">Cancelled</span>
													<input type ="hidden" name="CancelledInv_<?= $i ?>" id="CancelledInv_<?= $i ?>" value="Cancelled">
													<?php  }?>
												 </td> 

												<?php
											}
										?>
										
												<td align="left" valign="middle">
													<?php if($rows['STATUS'] == 5){?>
														<a href="#Payment" title="Payment Received" class="btn btn-default btn-sm" data-toggle="modal" data-target="#compose-modal" onClick="openWin(<?php echo $rows['INVOICEID'];?>,<?php echo $rows['NET_AMOUNT'];?>);">Payment Received</a>
														<?php }?>
													</td>
													<td align="left" valign="middle"><?php echo $rows['REMARKS'];?></td>

													<?php
													if ($_SESSION['iutype'] == 'mgmt_user') {
													?>
													<td align="left" valign="middle"><button type="button" onclick="return openBtn('<?=$rows['INVOICEID']?>');" class="btn btn-danger btn-flat open_btn">Open</button></td>

													<?php
													}
													?>

													
									</tr>
									<?php $i++;$temp=$i;} }?>
									</tbody>
								</table>
							</div>
						</div>
						<input type="hidden" id="action1" name="action1" value="submit2" />

						<input type="hidden" id="gridCount" name="gridCount" value="<?= $i ?>" />

						<input type="hidden" name="txtDEL_ID" id="txtDEL_ID" value="0"/>						
					</form>
					<div class="modal fade" id="compose-modal" tabindex="-1" role="dialog" aria-hidden="true">
						<div class="modal-dialog" style="width:60%;">
							<div class="modal-content">
								<div class="modal-header">
									<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
								</div>
								<div class="modal-body">
									<form name="frm3" id="frm3" enctype="multipart/form-data" action="<?php echo $pagename;?>" method="post"/>
                                        <div id="divPayment">
                                            
                                        </div>
                                        <div class="box-footer" align="right">
                                            <button type="submit" id="rcvdbtnhide" class="btn btn-primary btn-flat" onClick="return getValid();" >Submit</button>
                                            <input type="hidden" id="action2" name="action2" value="submit1" />
                                            <input type="hidden" name="txtCRMFILE1" id="txtCRMFILE1" value="" />
                                            <input type="hidden" name="txtCRMNAME1" id="txtCRMNAME1" value="" />
                                        </div>
									</form>
								</div>
							</div><!-- /.modal-content -->
						</div><!-- /.modal-dialog -->
					</div>
					
					
					
				<!--   content ends here..................-->
                </section><!-- /.content -->
            </aside><!-- /.right-side -->
			
        </div><!-- ./wrapper -->
<?php $display->footer(); ?>

    </body>
</html>
<script>

	let frm_table=$('#frm2 table ');


function openBtn(invoice_id)
{
	$.post("",{invoice_id:invoice_id}, function(html) {
		if(html){
			location.reload();
		}
	});
}

let invoice_type=	Array.from(frm_table.find("tr"));
let invoice_result=invoice_type.filter(function(in_type){
	return $(in_type).data('status')==5 && $(in_type).data('itype')=='Final';
});

// console.log(invoice_result);
// console.log(invoice_result);

if(invoice_result.length>0){
	$('#frm1').hide();
}
</script>