<?php
/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/
error_reporting(E_ALL & ~E_NOTICE);
ob_start();
$PageSecurity=0;

include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');

?>

	 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <link href='jquery-ui.min.css' type='text/css' rel='stylesheet' >
    <script src="jquery-3.2.1.min.js" type="text/javascript"></script>
    <script src="jquery-ui.min.js" type="text/javascript"></script>
  <script type="text/javascript" src="simple.money.format.js"></script>
  <script type="text/javascript" src="scripts/jquery.formatCurrency-1.4.0.js"></script>


	  <script type="text/javascript"> 
	  
  $( function() {
    $( "#datepicker" ).datepicker({
    dateFormat: 'dd/mm/yy',//check change
    changeMonth: true,
    changeYear: true
});
  } );
	  
  </script>	
  		
  	  <script type="text/javascript">
		  
	window.onmessage = function (e) { console.log(e.data); } 
		  
  $(document).ready(function(){				
	$(document).on('keydown', '.item_name', function() {
  
var id = this.id;
  var splitid = id.split('_');
  var index = splitid[1];

  // Initialize jQuery UI autocomplete
  $( '#'+id ).autocomplete({
   source: function( request, response ) {
    $.ajax({
     url: "sdc/searchitem.php",
     type: 'post',
     dataType: "json",
     data: {
      search: request.term,request:1
     },
     success: function( data ) {
      response( data );
		 
     }
    });
   },
   select: function (event, ui) {
    $(this).val(ui.item.label); // display the selected text
    var stockid = ui.item.value; // selected value

    // AJAX
    $.ajax({
     url: 'sdc/searchitem.php',
     type: 'post',
     data: {stockid:stockid,request:2},
     dataType: 'json',
     success:function(response){
 
      var len = response.length;

		 
      if(len > 0){
 
      var itemid = response[0]['stockid'];
		  var itembarcode = response[0]['barcode'];
       var price = response[0]['price'];
var label = (response[0]['label']);
       // Set value to textboxes
		   document.getElementById('itemid_'+index).value = itemid;
		  document.getElementById('itembarcode_'+index).value = itembarcode;
       document.getElementById('orderitemprice_'+index).value = price;
       document.getElementById('orderitemquantity_'+index).value = 1;
       
		  	  var qty = document.getElementById('orderitemquantity_'+index).value;
		   document.getElementById('ordertaxlabel_'+index).value = label;
      var total = parseFloat(price) * parseFloat(qty);
	  document.getElementById('orderitemfinalamount_'+index).value = total;
 
		   cal_final_total(count);
		  
      }
  
     }
    });

    return false;
   }
  });
 });
			
$(document).on('focus', '.item_barcode', function() {
  
var id = this.id;
  var splitid = id.split('_');
  var index = splitid[1];

  // Initialize jQuery UI autocomplete
  $( '#'+id ).autocomplete({
   source: function( request, response ) {
    $.ajax({
     url: "sdc/searchitembarcode.php",
     type: 'post',
     dataType: "json",
     data: {
      search: request.term,request:1
     },
     success: function( data ) {
      response( data );
		 
     }
    });
   },
   select: function (event, ui) {
    $(this).val(ui.item.label); // display the selected text
    var stockid = ui.item.value; // selected value

    // AJAX
    $.ajax({
     url: 'sdc/searchitembarcode.php',
     type: 'post',
     data: {stockid:stockid,request:2},
     dataType: 'json',
     success:function(response){
 
      var len = response.length;

		 
      if(len > 0){
 
      var itemid = response[0]['stockid'];
		  var itemname = response[0]['description'];
       var price = response[0]['price'];

		  var label = (response[0]['label']);
		  
       // Set value to textboxes
		   document.getElementById('itemid_'+index).value = itemid;
		  document.getElementById('itemname_'+index).value = itemname;
       document.getElementById('orderitemprice_'+index).value = price;
		  
       document.getElementById('orderitemquantity_'+index).value = 1;
		   document.getElementById('ordertaxlabel_'+index).value = label;
		  var qty = document.getElementById('orderitemquantity_'+index).value;
		  
      var total = parseFloat(price) * parseFloat(qty);
	  document.getElementById('orderitemfinalamount_'+index).value = total;
		  
		   cal_final_total(count);
		  
		  
      }
 
     }
    });

    return false;
   }
  });
 });
		$(window).keydown(function(e) {
  switch (e.keyCode) {
   
case 13:
		  return false;
  }
});	
		$("invoice_form").keypress(function(e) {
  //Enter key
  if (e.which == 13) {
    return false;
  }
});	
	
	  $("#results").change(function() {
		alert("Response received");
	})
	  
	});
	  
	  
		    </script>
	
      
      
       <!-- Modal Section -->

		


 									
									<?php
//this is where you paste. Below paste it:

$customer =$_POST['customer'] ;
$quotedateraw = $_POST['order_date'] ;

 $sqldate= FormatDateForSQL(DB_escape_string($_POST['order_date'] ));
$invoiceterms= $_POST['invoiceterms'] ;
$comments = $_POST['comments'] ;
$retention = $_POST['retention'] ;
$retenrate = $retention/100;

$quotedate = $_POST['order_date'];
$quotedated = date("Y-m-d", $quotedateraw);
$yeardate = date('Y',strtotime($sqldate));
$monthdate =date('m',strtotime($sqldate));
$monthname =date('M',strtotime($sqldate));

if(isset($_POST["create_invoice"]) && ($_POST['customer'] == $customer )){
	
	
	//check 
	
	date_default_timezone_set("Pacific/Fiji");
	
	$business =$_POST['business'];
	$costcenterid =$_POST['department'];
	
	$accountnumber =$_POST['account'];
	$projectno = $_POST['project'];
	$notes = $_POST['order_notes'];
	$lpo = $_POST['lpo'];
	//prepare data for json
	$delivery = $_POST['delivery'];
	
	$quotedate1= date('d/m/Y h:i a');
	$quotedate= date('m/d/Y h:i:s a');

    $date =date(DATE_ISO8601, strtotime($quotedate));
	
		$userid = $_SESSION['UserID'];
		
$SQLuser = "SELECT email,realname,tin,pac
	               
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];
$realname= $myrowuser['realname'];
$usertin= $myrowuser['tin'];	
$pac = $myrowuser['pac'];	
	
	//business customer tin
	  
	   $SQL77 = "SELECT 	departmentname
							 
			FROM department
			WHERE departmentid='" . $_POST['department'] . "'
			";
	
	$result77 = DB_query($SQL77);
	
	$myrow77 = DB_fetch_array($result77) ;
		
	$departmentname = $myrow77['departmentname'];	
//get debtor headoffice details:
		$SQL100 = "SELECT 	name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6,
							 taxref
							 
			FROM debtorsmaster
			WHERE debtorno='" . $_POST['customer'] . "'
			";
	
	$result100 = DB_query($SQL100);
	
	$myrow100 = DB_fetch_array($result100) ;
		$debtorname = $myrow100['name'];
		
		$address1 = $myrow100['address1'];
		$address2 = $myrow100['address2'];
		$address3 = $myrow100['address3'];
		$address4 = $myrow100['address4'];
		$address5 = $myrow100['address5'];
		$address6=  $myrow100['address6'];
		
			$customertaxref=  $myrow100['taxref'];
	$debtorno =  $_POST['customer'];
	if (!isset($customertaxref)){
		
		$customertaxref ="null";
	}
		
		$SQL2 = "SELECT branchcode
			FROM debtoraccount
			WHERE account_number='" . $_POST['account']. "'
			";
	
	$result2 = DB_query($SQL2);
	
	$myrow2 = DB_fetch_array($result2) ;
		//now get other customer details from custbranch tables
		
				$SQL21 = "SELECT brname,
								braddress1,
								braddress2,
								braddress3,
								phoneno,
								contactname,
								email
				   
			FROM custbranch
			WHERE branchcode='" . $myrow2['branchcode']. "'
			";
	
	$result21 = DB_query($SQL21);
	
	$myrow21 = DB_fetch_array($result2) ;
		
		$branchname = $myrow21['brname'];
		$branchad1 = $myrow21['braddress1'];
		$branchad2 = $myrow21['braddress2'];
		$branchad3 = $myrow21['braddress3'];
		$branchad4 = $myrow21['braddress3'];
		$branchad5 = $myrow21['braddress3'];
		$branchad6 = $myrow21['braddress3'];
		$phoneno = $myrow21['phoneno'];
		$contactname = $myrow21['contactname'];
		$email = $myrow21['email'];
		
		



$InvoiceNo = GetNextTransNo(10, $db);
			//get periodno 
	
	$OrderNo = GetNextTransNo(30, $db);
	
	$order_total_before_tax = 0;
    $order_total_tax1 = 0;
    $order_total_tax2 = 0;
    $order_total_tax3 = 0;
    $order_total_tax = 0;
    $order_total_after_tax = 0;
	   
		
 for($count=0; $count<$_POST["total_item"]; $count++)
      {
        
		  //get tax for line item
		  
		  
			
	
		$SQLtax = "SELECT sales_tax
				   
			FROM item_tax
			WHERE stockid='" . $_POST["item_id"][$count]. "'
			";
	
	$result = DB_query($SQLtax);
	$label =array();
	while( $rowtax = DB_fetch_array($result) ){
		
				$SQLlabel = "SELECT tax_label
				   
			FROM new_sales_tax
			WHERE id='" . $rowtax['sales_tax']. "'
			";
	
		
	$resultlabel = DB_query($SQLlabel);
		$rowlabel = DB_fetch_array($resultlabel);
		
		
		$label[] = $rowlabel['tax_label'];
		
		
	};
		$labeljson = json_encode($label);
		  
		  
		  $itemsdata[] = array(
			'Name'=>trim($_POST["item_name"][$count]),
			'Labels'=> json_decode($labeljson),
			'UnitPrice'=>trim($_POST["order_item_price"][$count]),
			'Quantity'=>trim($_POST["order_item_quantity"][$count]),
			'TotalAmount'=> $_POST["order_item_quantity"][$count]* $_POST["order_item_price"][$count]
			);
		  
		  $itemsother[] = array(
			'Stockid'=>trim($_POST["item_id"][$count]),
			'Name'=>trim($_POST["item_name"][$count]),
			'Labels'=> json_decode($labeljson),
			'UnitPrice'=>trim($_POST["order_item_price"][$count]),
			'Quantity'=>trim($_POST["order_item_quantity"][$count]),
			'TotalAmount'=> $_POST["order_item_quantity"][$count]* $_POST["order_item_price"][$count]
			);
		  
	  }
	

			
	 $itemssdc = json_encode($itemsdata,true);
		
     $itemssdcother = json_encode($itemsother,true);
	//check if this is training or normal sales
		$SQLTT = "SELECT trainee
				   
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
	$resultTT = DB_query($SQLTT);
		$rowtt = DB_fetch_array($resultTT);
		
		if ($rowtt['trainee'] == 1){
			
			$invoicetype = "Training";
		}
		if ($rowtt['trainee'] == 0){
			
			$invoicetype = "Normal";
		}
$host_name = 'www.ebusinessfiji.com';
$port_no = '80';

$st = (bool)@fsockopen($host_name, $port_no, $err_no, $err_str, 10);
if ($st) {
//$message1 = "Communicating with VSDC-FRCS & verifying your smart card";
//echo "<script type='text/javascript'>alert('$message1');</script>";
	
		//echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 

//echo "Communicating with VSDC-FRCS & verifying your smart card....... Please wait.... ";
	echo '<form method="post" id= "completeform" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
	
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
	?>
	<div style='text-align: center'>
  <textarea name= 'results' id='results' cols='100' rows='30' style='display:block'></textarea><br>
  <textarea name= 'invoiceRequest' id='invoiceRequest' cols='100' rows='30' style='display:block'></textarea><br>
   <textarea name= 'otherRequest' id='otherRequest'  cols='100' rows='30' style='display:block'></textarea><br>
    
<input type="submit" name="complete" id="complete" class="btn btn-info" value="Complete"/>


</form>	
    <div id="smart" style='text-align: center'> Communicating with VSDC </div>
  
  
  <div id ="signing" style='text-align: center'> Signing invoice. Please hold.... </div>
               
                </div>
                
                       <div id ="error" style='text-align: center'> Fiscalization process Failed! Please check the error message that has show earlier and contact your admin manager </div>
                </div>
                
                
<a href='Invoicing.php'>  <button type='button' name='invoicing'  id ="invoicebtt" class='btn btn-info'>Go to Invoice Listings</button></a>
<a href='CreateInvoice.php'>  <button type='button' id ="newbtt" name='newinvoice' class='btn btn-success'>Create New Invoice</button></a>
  
   <?

echo "
<div class='row'
>

  <div tyle='text-align: center'>
 <button id='taxcore_sign_element'
 data-taxcore-vsdc-url='https://vsdc.staging.vms.frcs.org.fj/'
 data-taxcore-input-id='invoiceRequest'
 data-taxcore-output-id='results'
 data-taxcore-invoice-request=''
 data-taxcore-debug='true'
 data-taxcore-signed-invoice-response=''>Sign Invoice to FRCS Tax System</button></div>";
 

			
 
 
	
 
 
	echo"<script src='https://vsdc.staging.vms.frcs.org.fj/onlinepos/v1/taxcore.min.js'></script>
 <script>
 document.getElementById('invoiceRequest').innerHTML =
 JSON.stringify(CreateExampleInvoiceRequest(), undefined, 4);
 
 document.getElementById('otherRequest').innerHTML =
 JSON.stringify(Other(),undefined, 4);


 
 
document.getElementById('taxcore_sign_element').dataset.taxcoreInvoiceRequest = JSON.stringify(CreateExampleInvoiceRequest());


 $('#complete').hide();
$('#results').hide();
$('#invoiceRequest').hide();
	$('#otherRequest').hide();
	$('#signing').hide();
  $('#taxcore_sign_element').hide();
   $('#invoicebtt').hide();
  $('#newbtt').hide();
  	$('#error').hide();
 function CreateExampleInvoiceRequest() {

 
 var invoiceRequest = {
 'DateAndTimeOfIssue': '$quotedate',
 'Cashier': '$usertin',
 'BD': '$customertaxref',
 'BuyerCostCenterId': null,
 'IT': '$invoicetype',
 'TT': 'Sale',
 'PaymentType': 'other',
 'InvoiceNumber': '$InvoiceNo',
 'ReferentDocumentNumber': '',
 'PAC': '$pac',
 'Options': {
 'OmitTextualRepresentation': 0,
 'OmitQRCodeGen': 0
	 },
 'Items': $itemssdc
 
 };
 return invoiceRequest;
 
 
 }


function Other() {

 
 var otherRequest = {
 
 'AccountNumber': '$accountnumber',
 'Notes': '$notes',
 'Date': '$quotedate1',
 'Project': '$projectno',
 'LPO': '$lpo',
 'department':'$costcenterid',
 'Items': $itemssdcother,
 'UserTin':'$usertin',
 'Delivery':'$delivery',
 'OrderNo':'$OrderNo',
 'DebtorNo':'$debtorno'
 };
 return otherRequest;
 }


setTimeout(function() {


$('#smart').hide();
    $('#taxcore_sign_element').show();
 
 
  
	
	 
}, 5e3);

  

$('#taxcore_sign_element' ).click(function() {



$('#taxcore_sign_element').hide();

 $('#signing').show();

$(function() {
    var intervalID = setInterval(function() {
	
	         
			 
      var attrmethod = $('#taxcore_sign_element').attr('data-taxcore-signed-invoice-response');
 				var obj = JSON.parse(attrmethod);
				
			if (obj.status_code == 200){
					
				
				
					$('#signing').hide();
					
				 	$('#complete').trigger('click');
					
 			        clearInterval(intervalID);
					   
 			}
			
			if (obj.status_code != 200){
			
	
			alert(attrmethod );
			$('#signing').hide();
			$('#error').show();
			$('#invoicebtt').show();
			$('#newbtt').show();
 			clearInterval(intervalID);
			
			}
    }, 2000);
	
    setTimeout(function() {
        clearInterval(intervalID);
		
    }, 10000);
	
	
});

 
  
});



</script>

		  
	


	

";
	
	
	
}else{
	
	$message = "You are not connected to internet. Try again when internet is up";
	echo "<script type='text/javascript'>alert('$message');</script>";
}
			
	
	
	
} 
elseif (isset($_POST['complete'])&&isset($_POST['results'])) {
	
	
	


	
	$trimmed = str_replace("\\n", "", $_POST['results']);
	
	$finaldata = str_replace("\\r", "", $trimmed);
	$finaldata1 = str_replace("\\", "", $finaldata);
	$response = json_decode($finaldata1);
	 
		$trimmed1 = str_replace("\\n", "", $_POST['invoiceRequest']);
	
	$finaldata1 = str_replace("\\r", "", $trimmed1);
	$finaldata2 = str_replace("\\", "", $finaldata1);
	$request = json_decode($finaldata2);
	
	$trimmedother = str_replace("\\n", "", $_POST['otherRequest']);
	
	$finaldataother = str_replace("\\r", "", $trimmedother);
	$finaldata2other = str_replace("\\", "", $finaldataother);
	$otherrequest = json_decode($finaldata2other);
	
//start printing pdf 
	
	//echo $request->BuyerCostCenterId;
	
	$userid = $_SESSION['UserID'];
	
		//open projectdetail table to start gathering informations which we will first insert at salesorders table  and get pdf headers written. Salesorders will assist in converting quotation to invoice. This below is simply a quote generation.
	
	   
	   
	   $SQL77 = "SELECT 	departmentname
							 
			FROM department
			WHERE departmentid='" . $otherrequest->department. "'
			";
	
	$result77 = DB_query($SQL77);
	
	$myrow77 = DB_fetch_array($result77) ;
		
	$departmentname = $myrow77['departmentname'];	
//get debtor headoffice details:
		$SQL100 = "SELECT 	debtorno,
							name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6
							 
			FROM debtorsmaster
			WHERE debtorno='" . $otherrequest->DebtorNo . "'
			";
	
	$result100 = DB_query($SQL100);
	
	$myrow100 = DB_fetch_array($result100) ;
		$debtorname = $myrow100['name'];
		
		$address1 = $myrow100['address1'];
		$address2 = $myrow100['address2'];
		$address3 = $myrow100['address3'];
		$address4 = $myrow100['address4'];
		$address5 = $myrow100['address5'];
		$address6=  $myrow100['address6'];
		
		
		
		
				$SQL21 = "SELECT branchcode,brname,
								braddress1,
								braddress2,
								braddress3,
								phoneno,
								contactname,
								email
				   
			FROM custbranch
			WHERE debtorno='" . $myrow100['debtorno'] . "'
			";
	
	$result21 = DB_query($SQL21);
	
	$myrow21 = DB_fetch_array($result2) ;
		
		$branchname = $myrow21['brname'];
		$branchad1 = $myrow21['braddress1'];
		$branchad2 = $myrow21['braddress2'];
		$branchad3 = $myrow21['braddress3'];
		$branchad4 = $myrow21['braddress3'];
		$branchad5 = $myrow21['braddress3'];
		$branchad6 = $myrow21['braddress3'];
		$phoneno = $myrow21['phoneno'];
		$contactname = $myrow21['contactname'];
		$email = $myrow21['email'];
		
		

		$SQLpaymentterms = "SELECT 	paymentterms
							 
			FROM debtorsmaster
			WHERE debtorno='" . $myrow100['debtorno'] . "'
			";
	
	$resultpaymentterms = DB_query($SQLpaymentterms);
	$myrowpaymentterms = DB_fetch_array($resultpaymentterms) ;
	
	$SQLterms = "SELECT 	terms,dayinfollowingmonth,daysbeforedue
							 
			FROM paymentterms 
			WHERE termsindicator='" . $myrowpaymentterms['paymentterms'] . "'
			";
	
	
	$resultterms = DB_query($SQLterms);
	$myrowterms = DB_fetch_array($resultterms) ;
	
	$paymentterms = $myrowterms['terms'];
	$DisplayDueDate = CalcDueDate(ConvertSQLDate($sqldate), $myrowterms['dayinfollowingmonth'], $myrowterms['daysbeforedue']);
	
	$DisplayDueDate1 =  date("Y/m/d", strtotime($DisplayDueDate)); 
	
$InvoiceNo = $request->InvoiceNumber;
			//get periodno 
	
$OrderNo = $otherrequest->OrderNo;
	
	$quotedated = $response->DT;
	
	$sqldate = date("Y-m-d");
	
$yeardate = date('Y',strtotime($sqldate));
$monthdate =date('m',strtotime($sqldate));
$monthname =date('M',strtotime($sqldate)); 
	
	$sdctime =  date("Y-m-d h:i:s a",$quotedated );
	    $query22 = "SELECT 
						periodno,
		             lastdate_in_period
		                 
					  
		          FROM periods
				    WHERE YEAR(lastdate_in_period) = '" . $yeardate. "'
					AND MONTH(lastdate_in_period)  = '" . $monthdate. "'";
				
        $result22=DB_query($query22);
        $myrow22=DB_fetch_array($result22);
      
				$PeriodNo = $myrow22['periodno'];
		     	$data = $myrow22['lastdate_in_period'];	
				
	
		$userid = $_SESSION['UserID'];
		
$SQLuser = "SELECT email,realname
	               
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];
$realname= $myrowuser['realname'];
	
	$sql = "INSERT INTO salesorders (
								orderno,
								
								lpo,
								debtorno,
								branchcode,
								account_number,
								job_no,								
								comments,
								orddate,
								sdc_invoice_no,
								ordertype,
								shipvia,
								deliverto,
								deladd1,
								deladd2,
								deladd3,
								deladd4,
								deladd5,
								deladd6,
								contactphone,
								contactemail,
								freightcost,
								fromstkloc,
								deliverydate,
								quotedate,								
								confirmeddate,
								quotation,
								status,
								deliverblind,
								department,
								amount,
								total_amount,
								preparedby)
							VALUES (
								'". $OrderNo . "',
								
								'" . $otherrequest->lpo . "',
								'" . $myrow100['debtorno']. "',
								'" . $myrow21['branchcode'] . "',
								'". $otherrequest->AccountNumber ."',
								'". $otherrequest->Project   ."',
								'". $otherrequest->Notes ."',
								'". $sqldate ."',
								'". $response->IN."',
								'DF',
								'1',
								'".$debtorname."',
								'". $branchad1."',
								'". $branchad2 ."',
								'". $branchad3 ."',
								'". $branchad4 ."',
								'". $branchad5."',
								'". $branchad6 ."',
								'". $phoneno ."',
								'". $email ."',
								'0',
								'SUVA',
								'". $sqldate ."',
								
							     '". $sqldate ."',
								'". $sqldate ."',
								'0',
								
								'Invoiced',
								'1',
								'". $otherrequest->department ."',
								'". $response->TotalAmount ."',
								'". $response->TotalAmount ."',
								'". $realname."'
								)";

		//$ErrMsg = _('This customer could not be added because');
		
			$result = DB_query($sql);
	
	   
	   
	   //get the payid from above
				$sqlpayid =  "SELECT orderno
						 
			FROM salesorders  ORDER BY orderno DESC LIMIT 1;
			
			";
	$ErrMsg = _('This customer could not be added because');
			$resultpayid = DB_query($sqlpayid,$ErrMsg);
			$myrowpayid = DB_fetch_array($resultpayid);
			
			$lastid = $myrowpayid['orderno'];

	
	

	$SQLuser = "SELECT email,realname
	               
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];

//get line items from response
	
	 $items = $otherrequest->Items; // Replace ... with your PHP Object
	
	
$count=0;
		foreach($items as $key => $lineitems) {
	  
      $uom= 'each';
  $stockid =$lineitems->Stockid;
$stockname = $lineitems->Name;
$qty =$lineitems->Quantity;
			$unitprice = $lineitems->UnitPrice;

			
			
		 $sql6 = "INSERT INTO salesorderdetails (
											orderlineno,
											orderno,
											stkcode,
										    stock_name,
											qtyinvoiced,
											
											unitprice,
											quantity,
											total,
											uom,
											discountpercent,
										
											poline,
											itemdue)
										VALUES  (
								'".   $count. "',
								'" . $OrderNo . "',
								'" .$stockid . "',
								'" .$stockname . "',
								'". $qty."',
								
								'". $unitprice."',
								'". $qty."',
								'". $lineitems->TotalAmount."',
								'". $uom."',
								
								0,
								
								'',
								'". $sqldate."'
								)";

							$ErrMsg = _('This salesorderdetails could not be added because');
			$result6 = DB_query($sql6,$ErrMsg);
  
 
				 $SQLlocstockonhand="SELECT locstock.quantity
								FROM locstock
								WHERE locstock.stockid='" . $stockid . "'
								AND loccode= 'SUVA'";
				 
				 
				  $resultstockonhand = DB_query($SQLlocstockonhand);
				  $rowstockonhand =  DB_fetch_array($resultstockonhand);
				 
				 $QtyOnHandPrior = $rowstockonhand['quantity'];
			
			
		
		
		
		
		
		
		$sql17 ="SELECT typeno from systypes where typeid = 17";
			
		$Result = DB_query($sql17); 
			
			$myrow17 = DB_fetch_array($Result) ;
			
			$AdjustmentNumber = $myrow17['typeno']+1;
			
			
				$SQLstockmoves = "INSERT INTO stockmoves (stockid,
												type,
												transno,
												loccode,
												trandate,
												userid,
												debtorno,
												branchcode,
												price,
												prd,
												reference,
												qty,
												discountpercent,
												standardcost,
												newqoh,
												narrative,
												status)
						VALUES ('" . $stockid . "',
								17,
								'" . $AdjustmentNumber. "',
								'WARE',
								'" . $sqldate. "',
								'" . $userid. "',
								'',
								'',
								'',
								'" . $PeriodNo . "',
								'Credit Sales',
								'" . -$qty . "',
								'',
								'',
								'" . ($QtyOnHandPrior - $qty) . "',
								'Credit Sales',
								'1')";
					 
	
			$Result = DB_query($SQLstockmoves);
			
			
					$sql18 ="UPDATE systypes SET	typeno ='" . $AdjustmentNumber . "' WHERE typeid = 17";
			
		$Result = DB_query($sql18);
			
				$SQL = "UPDATE locstock SET	quantity= locstock.quantity -'" . $qty . "',
											lastupdate ='" . $sqldate."'
									WHERE stockid='" . $stockid . "' AND loccode = 'WARE'";


			$Result = DB_query($SQL); 
			
			
		$count++;

					

			
  }
			

	
$SQLdebtor = "INSERT INTO debtortrans (transno,
									type,
									sdc_invoice_no,
									invoice_type,
									debtorno,
									delivery_address,
									projectid,
									branchcode,
									trandate,
									inputdate,
									prd,
									settled,
									reference,
									tpe,
									order_,
									lpo,
									rate,
									
									totalamount,
								   
									
									invtext,
									account_number,
									department,
									entered_by)
				VALUES (
					'" . $InvoiceNo. "',
					'10',
					'" . $response->IN. "',
					'" . $request->IT. "',
					'" . $myrow100['debtorno']. "',
					'" . $otherrequest->Delivery. "',
					'" . $otherrequest->Project. "',
					'" .$myrow100['debtorno']. "',
					'" . $sqldate. "',
					'" . $sqldate . "',
					
					'" . $PeriodNo . "',
					'0',
					'General Invoice',
					'DE',
					
					 '" . $OrderNo . "',
					 '" . $otherrequest->lpo . "',
					'1',
					
					
					'" . $response->TotalAmount . "',
					
					'" . $otherrequest->Notes . "',
					'" . $otherrequest->AccountNumber. "',
					'" . $otherrequest->department. "',
					'" . $realname . "'
					)";
		$ErrMsg = _('Cannot insert a GL entry for the journal line because');
		$DbgMsg = _('The SQL that failed to insert the GL Trans record was');
		$result = DB_query($SQLdebtor,$ErrMsg,$DbgMsg,true);
			
      $DebtorTransID = DB_Last_Insert_ID($db,'debtortrans','id');

	 //its not an email just print the invoice to PDF
	
	//taxes
	
		
	 $itemtaxes = $response->TaxItems; 

					
$totaltax= 0;
		foreach($itemtaxes as $key => $lineitemtax) {
			
			if ($lineitemtax->Label =='P'){
				
				
			$SQL = "UPDATE debtortrans SET	plastic ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
				
			}
			if ($lineitemtax->Label =='A'){
				
				
			$SQL = "UPDATE debtortrans SET	ovgst ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
				
			}
			if ($lineitemtax->Label =='E'){
				
				
			$SQL = "UPDATE debtortrans SET	stt ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
				
			}
			if ($lineitemtax->Label =='F'){
				
				
			$SQL = "UPDATE debtortrans SET	ecal ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
				
			}
			
			
			$totaltax = $totaltax + $lineitemtax->Amount;
		}
	
		$SQL = "UPDATE debtortrans SET	total_tax ='" . $totaltax. "'
									WHERE id  = '" . $DebtorTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
	
	
	 $itemtaxes = $response->TaxItems; // Replace ... with your PHP Object
	
	

		foreach($itemtaxes as $key1 => $lineitemtax) {
	  
      $uom= 'each';
  
			
			
		 $SQLdebtortax = "INSERT INTO debtortranstaxes (debtortransid,invoicenumber,
											
											taxlabel,categoryname,rate,
											
											taxamount)
								VALUES ('" . $DebtorTransID . "',
								'" . $InvoiceNo. "',
									'" . $lineitemtax->Label. "',
									'" . $lineitemtax->CategoryName. "',
									'" . $lineitemtax->Rate. "',
									'" . $lineitemtax->Amount. "')";

		$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction taxes records could not be inserted because');
		$DbgMsg = _('The following SQL to insert the debtor transaction taxes record was used');
 		$Result = DB_query($SQLdebtortax,$ErrMsg,$DbgMsg,true);
  



					

			
  }
			

	
	

	
	
	$_SESSION['results'] = $_POST['results'];
	$_SESSION['invoiceRequest'] = $_POST['invoiceRequest'];
	$_SESSION['otherRequest'] = $_POST['otherRequest'];
//database done now throw message in new page and option to print it in pdf.
	
 header('Location: Complete.php');
	
	
	
	
	
	
}
	else {
		
		
			
	

	
?>
        
 <div class="container-fluid">

    
     
     <?
	
	
	
     echo '<form method="post" id= "invoice_form" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
	
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';?>
        <div class="table-responsive">
          <table class="table table-bordered">
            <tr>
              <td colspan="2" align="center"><h2 style="margin-top:10.5px">Create Invoice</h2></td>
            </tr>
            <tr>
                <td colspan="2">
                    
               
                  <div class="row">
                    <div class="col-sm-6">
                      To,<br />
                        <b>RECEIVER (Bill TO)</b><br />
                       <select name="customer" required = "required">
                       <?
                       $SQL = "SELECT 
											debtorno,
											name
		                            FROM debtorsmaster";

$result=DB_query($SQL);




//echo '<option value="0">0 - ' . _('None Available') . '</option>';
echo '<option value="0">' . _('Choose Customer') . '</option>';
while ($myrow=DB_fetch_array($result)){

	//check customer name and project name
	
	if (isset($_POST['customer']) AND $_POST['customer']==$myrow['debtorno']){
	    
		echo '<option selected="selected" value="' . $myrow['debtorno'] . '">' . $myrow['name'].' - ' .$myrow['debtorno']  .'</option>';
	} else {
			echo '<option value="' . $myrow['debtorno'] . '">' . $myrow['name'].' - ' .$myrow['debtorno'] .'</option>';
	}
	
	
	
}
echo '</select>';
		
						   echo '<div class="row"><div class="col-sm-8"><select name="account" placeholder="Account Number" >';
							
							
echo '</select></div></div>';
						   
	   ?><input type="text" name="delivery" id="delivery" class="form-control input-sm" placeholder="Enter Delivery Details" />
					
					<?
						echo '<div class="row"><div class="col-sm-8"> <select name="department" required = "required">';
                    
                       $SQL = "SELECT 
											departmentid,
											departmentname
		                            FROM department";

$result=DB_query($SQL);




//echo '<option value="0">0 - ' . _('None Available') . '</option>';
 echo '<option value="0"> ' . _('Choose Department') . '</option>';
while ($myrow=DB_fetch_array($result)){

	//check customer name and project name
	
	if (isset($_POST['department']) AND $_POST['department']==$myrow['departmentid']){
	    
		echo '<option selected="selected" value="' . $myrow['departmentid'] . '">' . $myrow['departmentname'].' - ' .$myrow['departmentid']  .'</option>';
	} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . $myrow['departmentname'].' - ' .$myrow['departmentid'] .'</option>';
	}
	
	
	
}
echo '</select></div></div>';   
						
		
						   ?>
                       
                         
                    </div>
                    <div class="col-sm-4">
                     
                 
                      <input  type="text" name="order_date" value="<?php echo date('F d, Y h:i a') ?>" class="form-control input-sm orderdate" placeholder="Select Invoice Date" readonly />
                      
                      <input type="text" name="lpo" id="lpo" class="form-control input-sm" placeholder="Enter LPO No." />
                      <?
                     
                    
							
								echo '<select name="project" >';
                    
                       $SQL = "SELECT 
											projectid,
											project_name
		                            FROM projectdetails";

$result=DB_query($SQL);




//echo '<option value="0">0 - ' . _('None Available') . '</option>';
 echo '<option value="0">' . _('Choose Project/jobs(if applicable)') . '</option>';
while ($myrow=DB_fetch_array($result)){

	//check customer name and project name
	
	if (isset($_POST['project']) AND $_POST['project']==$myrow['projectid']){
	    
		echo '<option selected="selected" value="' . $myrow['projectid'] . '">' . $myrow['project_name'].' - ' .$myrow['projectid']  .'</option>';
	} else {
			echo '<option value="' . $myrow['projectid'] . '">' . $myrow['project_name'].' - ' .$myrow['projectid'] .'</option>';
	}
	 
	
	
}
echo '</select>';
						?>
                   
                    </div>
                  </div>
                  <br />
                  
                   
                   
                  <table id="invoice-item-table" class="table table-responsive ">
                    <tr>
                      <th width="7%">StockID</th>
                       <th width="15%">Barcode</th>
                      <th width="33%">Item Name</th>
                      <th width="5%">Quantity</th>
                      <th width="10%">Price</th>
                     <th width="15%">Tax Label</th>
                      <th width="10%" >Total</th>
                      <th width="5%" ></th>
                    </tr>
                  
                    <tr>
                      <td><input type="text" name="item_id[]" id="itemid_1" class="form-control input-sm item_id" /></td>
                       <td><input type="text" name="item_barcode[]" id="itembarcode_1" class="form-control input-sm item_barcode" /></td>
                      <td><input type="text" name="item_name[]" id="itemname_1" class="form-control input-sm item_name" /></td>
                      <td><input type="text" name="order_item_quantity[]" id="orderitemquantity_1" data-srno="1" class="form-control input-sm order_item_quantity" /></td>
                      <td><input type="text" name="order_item_price[]" id="orderitemprice_1" data-srno="1" class="form-control input-sm number_only order_item_price"  /></td>
                      <td><input type="text" name="order_tax_label[]" id="ordertaxlabel_1" data-srno="1" class="form-control input-sm number_only order_tax_label" /></td>
                      <td><input type="text" name="order_item_final_amount[]" id="orderitemfinalamount_1" data-srno="1"  class="form-control input-sm order_item_final_amount" disabled ="disabled"/></td>
                      <td></td>
                    </tr>
                  </table>
                  <div align="right">
                    <button type="button" name="add_row" id="add_row" class="btn btn-success btn-xs">+</button>
                  </div>
                </td>
              </tr>
            
                    </div>
                    <tr style="font-size: 20pix;">
                <td align="right" >  <textarea name="order_notes" id="order_notes" class="form-control" placeholder="Enter Notes/Comments"></textarea></td>
               
              </tr>
              <tr>
              <tr >
                <td align="right" style=" background-color:bisque"><b><font size="+3">Total(incl Taxes)</font></td>
                <td align="right" style="background-color:bisque"><b><font size="+3"><span id="final_total_amt"></span></b></font></td>
              </tr>
              <tr>
                <td colspan="2"></td>
              </tr>
              <tr>
                <td colspan="2" align="center">
                  <input type="hidden" name="total_item" id="total_item" value="1" />
                  <input type="submit" name="create_invoice" id="create_invoice" class="btn btn-info" value="Create" />
                  	
	
                <a href="Invoicing.php">  <button type="button" name="invoicing" id="invoicing" class="btn btn-success">Invoice Listings</button></a>
                </td>
              </tr>
          </table>
        </div>
      </form>
     
     
<?	
}
		
		
	
	
//echo 'Quotation Created Successfully'. $jobno.'!';
//header("location:Invoicing.php");



//echo 'Quotation Created Successfully'. $jobno.'!';
echo '</div>';
echo '</div>';





			  
 	echo '</div >';
	?>
						

		
					</div>
				</div>
			</div>
					
					

						<!--end:: Widgets/Stats-->

						<!--Begin::Section-->
						

		<!-- end::Quick Sidebar -->

		<!-- begin::Scroll Top -->
		<div id="m_scroll_top" class="m-scroll-top">
			<i class="la la-arrow-up"></i>
		</div>

		<!-- end::Scroll Top -->

		<!-- begin::Quick Nav -->
		

		<!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

		<!--end::Page Scripts -->
	</body>

	<!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
	$_SESSION['Module'] = $_GET['Application'];
}








//include('includes/footer.inc');

function GetRptLinks($GroupID) {
/*
This function retrieves the reports given a certain group id as defined in /reports/admin/defaults.php
in the acssociative array $ReportGroups[]. It will fetch the reports belonging solely to the group
specified to create a list of links for insertion into a table to choose a report. Two table sections will
be generated, one for standard reports and the other for custom reports.
*/
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) { // then there are reports to show, show by grouping
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			// now fetch the form groups that are a part of this group (List after reports)
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']); // break into main group and form group array
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>
<script>
			function confirmDialog() {
		var password = window.prompt('Enter Management password',''); 
		if ((password == '7') && keycode ==13)
			return true;
          
        else
          return false;
    
}
	

jQuery(document).ready(function($){

   // event must be delegated from .xcrud
	

	$( "select[name='customer']" ).change(function () {
    var debtorno = $(this).val();


    if(debtorno) {

		

        $.ajax({
            url: "invoice/accountnumber.php",
            dataType: 'Json',
            data: {'id':debtorno},
            success: function(data) {
                $('select[name="account"]').empty();
                $.each(data, function(key, value) {
                    $('select[name="account"]').append('<option value="'+ key +'">'+ value +'</option>');
                });
            }
        });


    }else{
        $('select[name="account"]').empty();
    }
		
	
		
});


	
		
		var final_total_amt = $('#final_total_amt').text();
        var count = 1;
        
        $(document).on('click', '#add_row', function(){
	
			
          count++;
          $('#total_item').val(count);
          var html_code = '';
          html_code += '<tr id="row_id_'+count+'">';
          html_code += '<td><input type="text"  name="item_id[]" id="itemid_'+count+'" class="form-control input-sm item_id" /></td>';
           html_code += '<td><input type="text" name="item_barcode[]" id="itembarcode_'+count+'" class="form-control input-sm item_barcode" /></td>';
          html_code += '<td><input type="text" name="item_name[]" id="itemname_'+count+'" class="form-control input-sm item_name" /></td>';
          
          html_code += '<td><input type="text" name="order_item_quantity[]" id="orderitemquantity_'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_quantity" /></td>';
          html_code += '<td><input type="text" name="order_item_price[]" id="orderitemprice_'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_price" /></td>';
			html_code += '<td><input type="text"  name="order_tax_label[]" id="ordertaxlabel_'+count+'" class="form-control input-sm item_id" /></td>';
       
          
          html_code += '<td><input type="text" name="order_item_final_amount[]" id="orderitemfinalamount_'+count+'" data-srno="'+count+'" class="form-control input-sm order_item_final_amount" /></td>';
          html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button></td>';
          html_code += '</tr>';
          $('#invoice-item-table').append(html_code);
        });
        
        $(document).on('click', '.remove_row', function(){
			
			
	
			
            var row_id = $(this).attr("id");
          var total_item_amount = $('#orderitemfinalamount_'+row_id).val();
          var final_amount = $('#final_total_amt').text();
          var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);
          $('#final_total_amt').text(result_amount);
          $('#row_id_'+row_id).remove();
          count--;
          $('#total_item').val(count);
      
			
			
        
        });

        function cal_final_total(count)
        {
          var final_item_total = 0;
          for(j=1; j<=count; j++)
          {
            var quantity = 0;
            var price = 0;
        
            var item_total = 0;
            quantity = $('#orderitemquantity_'+j).val();
            if(quantity > 0)
            {
              price = $('#orderitemprice_'+j).val();
              if(price > 0)
              { 
           
                item_total = parseFloat(quantity) * parseFloat(price);
                final_item_total = parseFloat(final_item_total) + parseFloat(item_total);
				  final_item_total = parseFloat(final_item_total).toFixed(2)
                $('#orderitemfinalamount_'+j).val(item_total);
              }
            }
          }
			 final_item_total = parseFloat(final_item_total).toFixed(2)
          $('#final_total_amt').text(final_item_total);
			
        }
		

	 $(document).on('blur', '.order_item_quantity', function(){
          cal_final_total(count);
        });

        $(document).on('blur', '.order_item_price', function(){
          cal_final_total(count);
        });

     

        $('#create_invoice').click(function(){
          

            if($.trim($('#delivery').val()).length > 30 )
            {
              alert("Max 30 characters allowed. Please shorten the context");
              $('#delivery').focus();
              return false;
            }
  if($.trim($('#order_notes').val()).length > 35 )
            {
              alert("Max 35 characters allowed. Please shorten the context");
              $('#order_notes').focus();
              return false;
            }
			
			 if($.trim($('#lpo').val()).length > 35 )
            {
              alert("Max 35 characters allowed. Please shorten the context");
              $('#lpo').focus();
              return false;
            }

          for(var no=1; no<=count; no++)
          {
            if($.trim($('#itemname_'+no).val()).length == 0)
            {
              alert("Please Enter Item Name");
              $('#itembarcode_'+no).focus();
              return false;
            }

            if($.trim($('#orderitemquantity_'+no).val()).length == 0)
            {
              alert("Please Enter Quantity");
              $('#orderitemquantity_'+no).focus();
              return false;
            }

            if($.trim($('#orderitemprice_'+no).val()).length == 0)
            {
              alert("Please Enter Price");
              $('#orderitemprice_'+no).focus();
              return false;
            }

          }

			
   $('#invoice_form').submit();

        });

	
$("#typeid").change(function(){
	
  var typeid = $("#typeid").val();
	 

	 
	
        if(typeid != 2)
       {
		
		 $('#TaxRef').attr("disabled", true);
		
       }
	else{
		 $('#TaxRef').attr("disabled", false);
		$('#TaxRef').attr("required", true);
		
	}
        
});
	
	
	function disableF5(e) {
		
if ((e.which || e.keyCode) == 116) 
	
	e.preventDefault(); 
	
	};
// To disable f5
    /* jQuery < 1.7 */
$(document).bind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).on("keydown", disableF5);

// To re-enable f5

$(document).keydown(function (event) {
    if (event.keyCode == 123) { // Prevent F12
        return false;
    } else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) { // Prevent Ctrl+Shift+I        
        return false;
    }
});
	
	$(document).on("contextmenu", function (e) {        
    e.preventDefault();
});
	
	
	 });
	
	
	
	

	
	
	
	
</script>
