<?php

 
session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

 
include("config.inc.php");
include("Functions_Sales.php");
include("Forms_DataGrid_SalesOrder.php");


$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}



$querylog="SELECT FI_SalesOrder as loginaccess, ifnull(SO_AssignUsers,0) as SO_AssignUsers from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
	$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($resultlog)){
		extract($rows);
	}
if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");

		
//$querylog="select * from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$querylog=" select ifNull(Fi_salesorderdel,0) As FI_SalesOrderDel, ifNull(Fi_salesordermod,0) As FI_SalesOrderMod, ".
          " ifNull(Fi_salesorderapp,0) As FI_SalesOrderIns, ifNull(FI_sorderconfirmed,0) As FI_SalesOrderConfirm, ".
		  " ifNull(ModifyVAT,0) As ModifyVAT, ifNull(Login_ModifyDiscount,0) As Login_ModifyDiscount, ifNull(FI_SalesCheckSalesman,0) As FI_SalesCheckSalesman, ".
		  " ifNull(Login_FastPrint,0) As Login_FastPrint, ifNull(FA_LedgerAccess,0) As FA_LedgerAccess, ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ".
		  " ifNull(FI_SorderAskConfirm,0) As FI_SorderAskConfirm, ifNull(FI_SorderCanceledQty,0) As FI_SorderCanceledQty, ".
		  " ifNull(Login_ModifySellingPrice,0) As Login_ModifySellingPrice, ifNull(Login_NegativeQty,0) As Login_NegativeQty,  ".
		  " ifNull(Login_AllowPrice,1) As Login_AllowPrice, ifNull(Allow_MinimumPrice,0) As Allow_MinimumPrice,ifNull(login_maturitydate,0) as login_maturitydate  ".
		  " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Access Mode On Insert/Edit/Delete
$InsertMode = '';
$ConfirmMode = '';
$DiscountMode = '';
if ($FI_SalesOrderIns == 0)	$InsertMode = ' disabled ';
if ($FI_SalesOrderConfirm == 0)	$ConfirmMode = ' disabled ';
if ($Login_ModifyDiscount == 0)	$DiscountMode = ' readonly ';
	
	
//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ifNull(Client_ValidateProject,0) as Client_ValidateProject, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage, ifnull(costcentminimum,0) as costcentminimum
			 from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ".
             " ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ".
             " ifNull(Module_SorderAutoConfirm,0) As Module_SorderAutoConfirm, ifNull(Module_ShowBalance,0) As Module_ShowBalance, ".
			 " ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ifNull(Module_CreditLimitByProj,0) As Module_CreditLimitByProj, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_TransferSorder,0) As Module_TransferSorder, ifNull(module_negativeSorder,0) As Module_NegativeSorder, ".
             " ifNull(Module_SorderCheckQtyOnPost,0) As Module_SorderCheckQtyOnPost, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ifNull(Module_AutoTransSorder,0) As Module_AutoTransSorder, ".
			 " ifNull(Module_ImportExcell,0) As Module_ImportExcell,ifNull(Module_VehicleWeight,0) As Module_VehicleWeight,ifNull(Module_ShowWarehouseSalesorder,0) As Module_ShowWarehouseSalesorder, ".
			 " ifNull(module_sellingbyclient,0) as module_sellingbyclient ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC, ClientCur, Warehouse As SetupDftWareHouse, ifNull(ExportTransportToJV,0) As ExportTransportToJV
				From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

//Read From SorderSetup Table
$querySorderSetup=" Select ifNull(ShowCostCentLayout,0) As ShowCostCentLayout,ifnull(SubItem_Production,0) as SubItem_Production, default_sorderType, ifnull(allow_duplicateItem,0) as allow_duplicateItem, ".
				  " ifnull(sorderproduction,0) as sorderproduction ".
				  " From SorderSetup ";
$resultSorderSetup=mysql_query($querySorderSetup,$connection) or die(mysql_error());
while($rowSorderSetup=mysql_fetch_array($resultSorderSetup)){
	extract($rowSorderSetup);
}


//Projects List
$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%') ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectrows   = mysql_num_rows($projectresult);
if ($projectrows == 0)
    $queryproject=" select distinct project_code, project_name from project order by project_code ";
			  
//$resultfromproject=mysql_query($queryproject,$connection) or die(mysql_error());

//Costcenter List
$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   " order by costcent.costcent_code";
			  
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentrows   = mysql_num_rows($costcentresult);
if ($costcentrows == 0)
    $querycostcent=" select distinct costcent_code, costcent_name from costcent order by costcent_code ";			  
//$resultcostcent=mysql_query($querycostcent,$connection) or die(mysql_error());



//Warehouse List
$querywarehouse=" select distinct warehouse.warehouse_code, warehouse_name ".
				" from warehouse where warehouse_code in (select warehouse_code from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."') ".
				" order by warehouse.warehouse_code";
$resultwh = mysql_query($querywarehouse,$connection) or die(mysql_error());
$whexist   = mysql_num_rows($resultwh);
if ($whexist == 0)
	$querywarehouse="select warehouse_code,warehouse_name from warehouse order by warehouse_code";
	
$resultwarehouse=mysql_query($querywarehouse,$connection) or die(mysql_error());


$querycurrency="select Currency_code from currency order by currency_code";
$resultcurrency=mysql_query($querycurrency,$connection) or die(mysql_error());

$querysordertype="select distinct Sorder_Type, Sorder_TypeName from sordertype where FormType = 'Sorder' order by Sorder_Type";
$resultsordertype=mysql_query($querysordertype,$connection) or die(mysql_error());




$actionmode = $_POST["actionmode"]; if ($actionmode == ""){$actionmode = $_GET["actionmode"];}   
$mainaction = $_POST["mainaction"]; if ($mainaction == ""){$mainaction = $_GET["mainaction"];}   

if (empty($mainaction))
	$mainaction = 'insert';

$message = ereg_replace("'"," ",$message);


UpdateTransactionSorder($txtSorId,$txtClientCode,$txtProjectCode,$txtCostCentCode,$JOURNALDT_VALUEDATE,$connection);

$directPrintSO = $config['directPrintSO'];

print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">



<link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">

<script type="text/javascript" src="js/grid/UI_DataGrid.js"></script>
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>


<link type="text/css" href="js/calendar/jquery.datepick.css" rel="stylesheet">
<script type="text/javascript" src="js/calendar/jquery.datepick.js"></script>

<link type="text/css" href="js/grid/scripts/jquery-ui.css" rel="stylesheet">
<script type="text/javascript" src="js/grid/scripts/jquery-ui.min.js"></script>

<script type="text/javascript" language="javascript">
	$(document).ready(function() { 
		
		$(document).on('focus', '.date', function() {
			$('.date').datepick({showTrigger: '#calImg'});
		});
		
		$(document).on('focusin', '.table-focus-g1', function() {
			AutoSaveRecordGrid(this.id,'SelectedRec','ModRec_G1','imgSubmit');
			selRecordColor(this,'SelectedRec','SelectedRecColor');
		});
		
		//Set Scroll Positions on Page Load
		scrollToPage();
		
		$(window).scroll(function(){
			scrollPage();
		});
		
		//Set Cursor Position After Page Reload
		var NextElement = readCookie('so-nextcell');
		MoveNextRecord(NextElement);
		eraseCookie('so-nextcell');
		
		
		
	});
	
	
</script>

<script type="text/javascript" language="javascript">



function UpdateDiscount(PIndex,amt){

 

var sordtdiscount   = document.getElementById('sordtdiscount['+PIndex+']').value;
var clientdiscount   = document.getElementById('sorderdt_clientdiscount['+PIndex+']').value;
var itemdiscount   = document.getElementById('sorderdt_itemdiscount['+PIndex+']').value;

if(sordtdiscount=='') sordtdiscount = 0;
sordtdiscount = parseFloat(sordtdiscount);

if(clientdiscount=='') clientdiscount = 0;
clientdiscount = parseFloat(clientdiscount);

if(itemdiscount=='') itemdiscount = 0;
itemdiscount = parseFloat(itemdiscount);


if(sordtdiscount<clientdiscount){
alert('Discount must not be less than '+document.getElementById('sorderdt_clientdiscount['+PIndex+']').value);
document.getElementById('sordtdiscount['+PIndex+']').focus();
return;
}
if(sordtdiscount==clientdiscount){
	clientdiscount = sordtdiscount;
	itemdiscount = 0;
	}
else {
 itemdiscount = sordtdiscount - clientdiscount ;
}

 document.getElementById('sordtdiscount['+PIndex+']').value = sordtdiscount;
 document.getElementById('sorderdt_clientdiscount['+PIndex+']').value = clientdiscount;
 document.getElementById('sorderdt_itemdiscount['+PIndex+']').value = itemdiscount;

}


function kdClient(choice,e)
{   
	 x = document.salesorder;
	
	 if(choice==0)
		var clientcode = x.txtClientCode.value;
		else
		var clientcode = x.txtClientName.value;
		
    var intKey = (window.Event) ? e.which : e.keyCode;
	
		
    if (intKey == 13) { //enter key
	
	
		var xmlhttp = getXMLHttpRequest();	
		
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{ 
				var data = xmlhttp.responseText.split("[BRK]");
				  
					if(data[1]!=''){
							 
							if(choice==0)
								x.txtClientName.value = data[2];
							else
							x.txtClientCode.value = data[1];
								
							x.txtSalesmanCode.value='';
							x.txtSalesmanName.value='';
							x.txtDAddress.value='';
							x.txtSaDiscount_Temp.value = data[3];
							SetMaturityDate($Module_Delivery);
						
						if(x.txtClientName.value!='')
							{
								x.submit();	
							} 
							
						
						
					}else {
					 
					document.getElementById('lstClientCodeH').click();
				}
			}
		}
	    
		xmlhttp.open("GET","Form_Delivery_Actions.php?mode=getclientname&clientcode="+clientcode+"&choice="+choice);
		xmlhttp.send();
	
      
			
			
    }
	
	
  


}



function checkduplicate(PIndex,PItem) {


var x = document.salesorder;
	
		var xmlhttp = getXMLHttpRequest();	
		var SaId  = x.txtSorId.value;
		var vSaClient = x.txtClientCode.value;
		var allow_duplicateItem = x.allow_duplicateItem.value;
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = xmlhttp.responseText.split("[BRK]");
								
						if(data[0]==1 && document.getElementById('sordtid['+PIndex+']').value=='' && allow_duplicateItem == 0)
							alert('Duplicate Item');
					
					//if(Module_AutoDiscount==1){
						//if(data[1]!='')
							//document.getElementById('sordtdiscount['+PIndex+']').value = data[1];
							
							document.getElementById('sorderdt_itemdiscount['+PIndex+']').value = data[1];
							document.getElementById('sorderdt_clientdiscount['+PIndex+']').value = data[2];
							document.getElementById('sordtdiscount['+PIndex+']').value = parseFloat(data[1]) + parseFloat(data[2]);
							
						//}
			}
		}
	    
		xmlhttp.open("GET","Form_SalesOrder_Actions.php?mode=checkduplicate&PItem="+PItem+"&SSaId="+SaId+"&vSaClient="+vSaClient);
		xmlhttp.send();


}



function CheckFields(ModuleRestProj, ModuleRestCost, ClientDetail, CheckSalesman){
  
    x = document.salesorder;
	
	var SorDate = x.txtDate.value;
	var SorMaturityDate = x.txtMaturityDate.value;
	var SorRequestDate = x.txtRequestDate.value;
	var SorClient = x.txtClientCode.value;
	var SorClientDt = x.txtClientDtCode.value;
	var SorSalesman = x.txtSalesmanCode.value;
	var SorProject = x.txtProjectCode.value;
	var SorCostCenter = x.txtCostCentCode.value;
	var SorCurr = x.txtCurr.value;
	var SorType = x.txtSorType.value;
	
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	if (SorDate=='' )
	{
		alert("Date is mandatory!");
		x.txtDate.focus();
		return 0;
	}
	else if (SorMaturityDate=='')
	{
		alert("MaturityDate is mandatory!");
		x.txtMaturityDate.focus();
		return 0;
	}
	else if (SorRequestDate=='')
	{
		alert("RequestDate is mandatory!");
		x.txtRequestDate.focus();
		return 0;
	}
	else if (SorClient=='' )
	{
		alert("Client is mandatory!");
		x.txtClientCode.focus();
		return 0;
	}
	else if (SorClientDt=='' && ClientDetail==1)
	{
		alert("Client Detail is mandatory!");
		x.txtClientDtCode.focus();
		return 0;
	}
	else if (SorSalesman=='' && CheckSalesman==1)
	{
		alert("Salesman is mandatory!");
		x.txtSalesmanCode.focus();
		return 0;
	}
	else if (SorProject=='' && ModuleRestProj==1)
	{
		alert("Project is mandatory!");
		x.txtProjectCode.focus();
		return 0;
	}
	else if (SorCostCenter=='' && ModuleRestCost==1 && document.getElementById('txtCostCentCode').type == 'text')
	{
		alert("CostCenter is mandatory!");
		x.txtCostCentCode.focus();
		return 0;
	}
	else if (SorCurr=='' )
	{
		alert("Currency is mandatory!");
		x.txtCurr.focus();
		return 0;
	}
	else if (SorType=='' )
	{
		alert("Sorder Type is mandatory!");
		x.SorType.focus();
		return 0;
	}
			
	
	else
	return 1 ;	
}


function CheckFieldsDt(PIndex,ModuleNegativeSorder,LoginNegativeQty,ItemNonStock,ItemZeroPrice,AllowZeroPrice,ModuleSorderCheckQtyOnPost,AllowMinPrice,ItemMinPrice,ClientPromotion,Module_ShowWarehouseSalesorder){
  
    x = document.salesorder;
	
	var SorType  	   = x.txtSorType.value;
	var SorDtItem 	   = document.getElementById('itemcode['+PIndex+']').value;
	var costcentminimum = x.costcentminimum.value;
	
	if(Module_ShowWarehouseSalesorder==1)
		var SorDtWarehouse = document.getElementById('warehousecode['+PIndex+']').value;
	else
		var SorDtWarehouse = '';
		
	var SorDtQty       = document.getElementById('sordtquantity['+PIndex+']').value;
	var SorDtQty2	   = document.getElementById('unit2qty['+PIndex+']').value;
	var SorDtPrice     = document.getElementById('price['+PIndex+']').value;
	var SorDtDisc      = document.getElementById('sordtdiscount['+PIndex+']').value;
	var AvailableQty   = document.getElementById('availableqty['+PIndex+']').value;
	
	var OQty = document.getElementById('itemorderedqty['+PIndex+']').value;
	var CQty = document.getElementById('cancelledqty['+PIndex+']').value;
	
	
	var vmode = x.actionmode.value;
	
	if (SorDtPrice == '')	SorDtPrice = 0;
	if (SorDtQty2 == '')    SorDtQty2 = 0;
	if (SorDtQty == '')     SorDtQty = 0;
	if (OQty == '') OQty = 0;
	if (CQty == '') CQty = 0;
	
	SorDtQty = parseFloat(SorDtQty);	
	AvailableQty = parseFloat(Math.abs(AvailableQty));
	OQty = parseFloat(OQty);
	CQty = parseFloat(CQty);
	
	SorDtPrice   = parseFloat(SorDtPrice);
	ItemMinPrice = parseFloat(ItemMinPrice);
	
	if (SorDtItem=='')
	{
		alert("Item is mandatory!");
		document.getElementById('itemcode['+PIndex+']').focus();
		return 0;
	}	
	else if (SorDtWarehouse=='' && Module_ShowWarehouseSalesorder==1)
	{
		alert("Warehouse is mandatory!");
		document.getElementById('warehousecode['+PIndex+']').focus();
		return 0;
	}
	else if(CQty > OQty) {
		alert('Cancelled Qty ['+CQty+'] must be <= Ordered Qty ['+OQty+'].');
		document.getElementById('cancelledqty['+PIndex+']').focus();
		return 0;
	}
	else if ((SorDtQty == 0 || SorDtQty*1 != SorDtQty/1 || SorDtQty < 0 ) && (ModuleNegativeSorder == 0 || LoginNegativeQty == 0) ) {
		alert('Quantity ('+SorDtQty+') should be a NUMERIC and POSITIVE and MORE than ZERO. ');
		document.getElementById('sordtquantity['+PIndex+']').focus();
		return 0;
	}
	else if (SorDtQty > AvailableQty && ModuleSorderCheckQtyOnPost == 1 && (ModuleNegativeSorder == 0 || LoginNegativeQty == 0) && ItemNonStock == 0 && SorType == 'SO'){
		alert('Quantity ('+SorDtQty+') should be NOT MORE than [Available ('+AvailableQty+')] ');
		document.getElementById('sordtquantity['+PIndex+']').focus();
		return 0;
	}
	else if ((SorDtPrice*1 != SorDtPrice/1 || SorDtPrice < 0) ) {
		alert('Price should be a NUMERIC and POSITIVE value');
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if ((SorDtPrice == 0 && AllowZeroPrice == 0 && ItemZeroPrice == 0) ) {
		alert('Not allow Zero price.');
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if ((SorDtPrice < ItemMinPrice && AllowMinPrice == 0 && ItemMinPrice != 0 && ClientPromotion != 1 && costcentminimum != 1) ) {
		alert('Price not allowed, minimum price '+ItemMinPrice);
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if ((SorDtDisc != '' && SorDtDisc*1 != SorDtDisc/1) ) {
		alert('Discount should be a NUMERIC value');
		document.getElementById('sordtdiscount['+PIndex+']').focus();
		return 0;
	}
	else if ((SorDtQty2 != '' && SorDtQty2*1 != SorDtQty2/1) ) {
		alert('Item Qty2 should be a NUMERIC value.');
		document.getElementById('unit2qty['+PIndex+']').focus();
		return 0;
	}
		
	
	else
	return 1 ;	
}

function ClearPage(){
	if (confirm ( "Are you sure you want to Clear Page?"))
	{
		ClearForm('All');
		x = document.salesorder;
		x.mainaction.value='insert';
		x.actionmode.value='';
		x.action='Form_SalesOrder.php';
		x.submit();
	}	
}

function ClearPage1(){
	x = document.salesorder;
	var msg = x.message.value;
	
	ClearForm('All');
	
	x.mainaction.value='insert';
	x.actionmode.value='';
	x.message.value=msg;
	x.action='Form_SalesOrder.php?message='+x.message.value;
	x.submit();
}


function CancelRecord(){
	x = document.salesorder;
	var vmode   = x.mainaction.value;
	var vmode1  = x.actionmode.value;
	var SorId = x.txtSorId.value;
		
	if (confirm ( "Are you sure you want to Delete current pending preparation order permenantly?"))
	{
		x.action="Form_SalesOrder_Actions.php?mode=cancel&mainmode=&SSorId="+SorId;
		x.submit();
	}
    
}


function PostChanges(ModuleRestProj, ModuleRestCost, ClientDetail, CheckSalesman) {
	x = document.salesorder;
	var SorId  = x.txtSorId.value;
	var vMainMode = x.mainaction.value;
	var vVatChkbx = x.txtSorVatChk.value;
	
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ClientDetail, CheckSalesman);
	
	
	if (x.txtSorCountDetail.value == 0 || x.txtSorCountDetail.value == '') {
		alert('Save not allowed. Please add items.');
	}
	else {
		if (result == 1) {
			
			if (confirm ( "Are you sure you want to Save current preparation order?"))
			{
				//Save Grid Before Posting	
				var vModRec  = document.getElementById('ModRec_G1').value;
				if (vModRec != "") {
					var Obj = document.getElementById('CurRec'+vModRec);
					Obj.style.backgroundColor='#F13A3A';
					alert("Please Submit changes before.");
					
				} else {
					if (document.getElementById('btnAddItem'))
						x.btnAddItem.disabled = true;
					if (document.getElementById('btnPost'))
						x.btnPost.disabled = true;
					if (document.getElementById('btnCancel'))
						x.btnCancel.disabled = true;	
					if (document.getElementById('btnClear'))
						x.btnClear.disabled = true;
					if (document.getElementById('btnStatement'))
						x.btnStatement.disabled = true;
					
					x.actionmode.value='post';
					x.action="Form_SalesOrder_Actions.php?mode=post&mainmode="+vMainMode+"&SSorId="+SorId+"&SSorVatChkbx="+vVatChkbx;
					x.submit();
				}	
			}
		
			
			
		}	
	}
}

function confirmProduction(SorId)
{
	x = document.salesorder;
	//var SorId  = x.txtSorId.value;
	if(confirm("Do you want to load the sales order to the production?"))
			{
				var str = "Form_Production_LoadSorder.php?PMode=0&SSorId="+SorId;
				//alert(str);
				window.open(str, 'Form_LoadToProduction', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=1170,height=650,top=100');
			}
}

function ConfirmOrder(SorId) {
	x = document.salesorder;
	var vMainMode = x.mainaction.value;
	
	
	if (confirm ( "Do you want to Confirm saved preparation order?"))
	{
		x.actionmode.value='confirmorder';
		
		x.action="Form_SalesOrder_Actions.php?mode=confirmorder&mainmode="+vMainMode+"&SSorId="+SorId;
		x.submit();
		
	} 
	else {
		x.actionmode.value='confirmorder';
		x.submit();
	}
	

}

	
function DeleteSorDt(SorDtId, ItemPackCode, ItemCode) {
	x = document.salesorder;
	var SorId  = x.txtSorId.value;
	var vMainMode = x.mainaction.value;
	var vVatChkbx = x.txtSorVatChk.value;
	var vDelMsg = '';
	
	
	if (ItemPackCode != '')
	   vDelMsg = "Are you sure you want to Delete Pack Item "+ItemPackCode+" ?";
	else  
	   vDelMsg = "Are you sure you want to Delete Item "+ItemCode+" ?";
	   
	if (confirm ( vDelMsg ))
	{
		x.action="Form_SalesOrder_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SSorId="+SorId+"&SSorDtId="+SorDtId+"&SSorVatChkbx="+vVatChkbx;
		x.submit();
	}

}

function UpdateSorDt(SorDtId) {
    x = document.salesorder;
	var vSorId    = x.txtSorId.value;
	var vSorDate  = x.txtDate.value;
	var vSorType  = x.txtSorType.value;
	var vSorCurr  = x.txtCurr.value;
	var vVatChkbx = x.txtSorVatChk.value;
		
	var vMainMode = x.mainaction.value;
	
	win = window.open('Form_SalesOrderDetail.php?mainaction='+vMainMode+'&actionmode=&PSorId='+vSorId+'&PSorDate='+vSorDate+'&PSorCurr='+vSorCurr+'&PSorDtId='+SorDtId+'&PSorVatChkbx='+vVatChkbx+'&PSorType='+vSorType, 'Form_SalesOrderDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=830,height=325,top=100');		
	win.creator = self;
	win.focus();		

}




//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.salesorder;
	var vmode = x.actionmode.value;
	
	if (Option == 'All') {
		
		x.txtSorId.value='';
		x.txtRef.value='';
		x.txtSorType.value='';
		x.txtDate.value='';
		x.txtMaturityDate.value='';
		x.txtRequestDate.value='';
		x.txtClientCode.value='';
		x.txtClientName.value='';
		x.txtClientVat.value='';
		x.txtClientDtCode.value='';
		x.txtClientDtName.value='';
		x.txtPaymentTerms.value='';
		x.txtCurrentBalance.value='';
		x.txtCreditLimit.value='';
		x.txtSalesmanCode.value='';
		x.txtSalesmanName.value='';
		x.txtRemark.value='';
		x.txtCurr.value='';
		x.txtProjectCode.value='';
		x.txtCostCentCode.value='';
		x.txtIAddress.value='';
		x.txtDAddress.value='';
		x.txtDriverName.value='';
		x.txtVehicalNo.value='';
		x.txtVehicleWeight.value='';
		x.txtPayMode.value='';
		
		
		x.txtSorTaxable.value='';
		x.txtSorNoneTaxable.value='';
		x.txtSorGrossTotal.value='';
		x.txtSorDiscount.value='';
		x.txtSorDiscountAmt.value='';
		x.txtSorVat.value='';
		x.txtSorVatChk.value='';
		x.txtSorNetTotal.value='';
		x.txtSorTotalTaxes.value='';
		x.txtSorTransportAmt.value='';
		
		x.txtSorCountDetail.value='';		
		x.message.value='';
		
		x.actionmode.value = '';
		x.mainaction.value = '';
	} 
}

function AddItems(ModuleRestProj, ModuleRestCost, ClientDetail, CheckSalesman) {
	x = document.salesorder;
	//x.actionmode.value = '';
	
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ClientDetail, CheckSalesman);

	var vSorId = x.txtSorId.value;
	var vSorDate = x.txtDate.value;
	var vSorMaturityDate = x.txtMaturityDate.value;
	var vSorRequestDate = x.txtRequestDate.value;
	var vSorClient = x.txtClientCode.value;
	var vSorClientDt = x.txtClientDtCode.value;
	var vSorSalesman = x.txtSalesmanCode.value;
	var vSorRemark  = x.txtRemark.value;
	var vDriverName = x.txtDriverName.value;
	var vVehicalNo  = x.txtVehicalNo.value;
	var vVehicleWeight = x.txtVehicleWeight.value;
	var vSorCurr = x.txtCurr.value;
	var vSorType = x.txtSorType.value;
	var vSorProjectCode = x.txtProjectCode.value;
	var vSorCostCentCode = x.txtCostCentCode.value;
	var vSorDiscount = x.txtSorDiscount.value;
	var vSorDiscountAmt = x.txtSorDiscountAmt.value;
	var vSorIAddress = x.txtIAddress.value;
	var vSorDAddress = x.txtDAddress.value;
	var vVatChkbx = x.txtSorVatChk.value;
	
	vSorRemark = vSorRemark.replace('&','%26');
	vSorIAddress = vSorIAddress.replace('&','%26');
	vSorDAddress = vSorDAddress.replace('&','%26');
	vDriverName  = vDriverName.replace('&','%26');
	vVehicalNo   = vVehicalNo.replace('&','%26');
	
	vSorRemark = vSorRemark.replace('#','%23');
	vSorIAddress = vSorIAddress.replace('#','%23');
	vSorDAddress = vSorDAddress.replace('#','%23');
	vDriverName  = vDriverName.replace('#','%23');
	vVehicalNo   = vVehicalNo.replace('#','%23');
	
	
	var vMainMode = x.mainaction.value;
	
	if (result == 1) {
		win = window.open('Form_SalesOrderDetail.php?mainaction='+vMainMode+'&actionmode=&PSorId='+vSorId+'&PSorDate='+vSorDate+'&PSorMaturityDate='+vSorMaturityDate+
		                  '&PSorRequestDate='+vSorRequestDate+'&PSorClientCode='+vSorClient+'&PSorClientDtCode='+vSorClientDt+'&PSorSalesmanCode='+vSorSalesman+
						  '&PSorCurr='+vSorCurr+'&PSorProjectCode='+vSorProjectCode+'&PSorCostCentCode='+vSorCostCentCode+'&PSorDiscount='+vSorDiscount+'&PSorDiscountAmt='+vSorDiscountAmt+
						  '&PSorVatChkbx='+vVatChkbx+'&PSorType='+vSorType+'&PDriverName='+vDriverName+'&PVehicalNo='+vVehicalNo+'&PVehicleWeight='+vVehicleWeight+'&PSorRemark='+vSorRemark+
						  '&PSorIAddress='+vSorIAddress+'&PSorDAddress='+vSorDAddress, 
						  'Form_SalesOrderDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=830,height=325,top=100');		
		win.creator = self;
		win.focus();		
	}	
	
    
}

function DeleteRecordGrid(filepath,formname,transid,SorDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction) {
	x = document.salesorder;
	var vSorId    = x.txtSorId.value;
	var vSorCurr  = x.txtCurr.value;
	var vSorDate  = x.txtDate.value;
	var vSorDiscount = x.txtSorDiscount.value;
	var vMainMode = x.mainaction.value;
	var vVatChkbx = x.txtSorVatChk.value;
	var vDelMsg = 'Are you sure you want to delete this record?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = $.parseJSON(xmlhttp.responseText);
					
				var msg = data[0].message;
					
				if (msg != "") {
					$("#Loader").removeClass("ajaxsaving");
					alert(decodeURIComponent(msg));
				} else { 
					ReloadGrid(filepath,formname,transid,'datagrid',index,dftorderby,'DEL',orderby,morelines,startrange,perpage,0,direction);			
					ReloadGridDt(filepath,'SO-TOT','TOTALS','totals',transid,-1);
				}
			}
		}
	    
		xmlhttp.open("GET","Form_SalesOrder_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SSorId="+vSorId+"&SSorDtId="+SorDtId+"&SSorVatChkbx="+vVatChkbx+"&txtCurr="+vSorCurr+"&txtDate="+vSorDate+"&txtSorDiscount="+vSorDiscount);
		xmlhttp.send();
	}	

}


function SubmitRecordGrid(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction,ModuleNegativeSorder,LoginNegativeQty,AllowZeroPrice,ModuleSorderCheckQtyOnPost,AllowMinPrice,ModuleRestProj,ModuleRestCost,ClientDetail,CheckSalesman,ClientPromotion,Module_ShowWarehouseSalesorder) 
{
	
 	x = document.salesorder;
 
	//alert('invalid item code ');exit;
	//txtItemCode
	var itemcode  = document.getElementById('itemcode['+PIndex+']').value;
	var notallowedtoadditemduetocostcenter = false;
	 
	
	$.get( "Get_AutocompleteQuery.php?tablename=items&term="+itemcode, function( data ) {
		//  used to restrice user to add an item that belong to another cost center  , nb: will only fire  in case user have access to only specific cost center in loginstk NB cost center filtered in Get_AutocompleteQuery tablename:items
       
 if (parseInt(data.length) == parseInt(0) )
 {
	 alert('not allowed to add this item!');
		document.getElementById('itemcode['+PIndex+']').focus();
 }
 
 else
 {
	 //
	 
	 	
	 
	
	var ItemNonStock 	= document.getElementById('itemnonstock['+PIndex+']').value;
	var ItemZeroPrice 	= document.getElementById('itemzeroprice['+PIndex+']').value;
	var ItemMinPrice  	= document.getElementById('itemminprice['+PIndex+']').value;
	var txtAssignedUser = document.getElementById('txtAssignedUser').value;
	var vsorder_export  = x.sorder_export.value;
	 
	if(document.getElementById('sorderdt_quantitybox['+PIndex+']'))
	var sorderdt_quantitybox  = document.getElementById('sorderdt_quantitybox['+PIndex+']').value;
	else var sorderdt_quantitybox  = '';
	if(document.getElementById('sorderdt_itemunit['+PIndex+']'))
	var sorderdt_itemunit  = document.getElementById('sorderdt_itemunit['+PIndex+']').value;
	else var sorderdt_itemunit  = '';
	
	if(document.getElementById('sorderdt_itempackage['+PIndex+']'))
	var sorderdt_itempackage  = document.getElementById('sorderdt_itempackage['+PIndex+']').value;
	else var sorderdt_itempackage  = '';
	
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ClientDetail, CheckSalesman);
	
	if (result == 1) {
		result = CheckFieldsDt(PIndex,ModuleNegativeSorder,LoginNegativeQty,ItemNonStock,ItemZeroPrice,AllowZeroPrice,ModuleSorderCheckQtyOnPost,AllowMinPrice,ItemMinPrice,ClientPromotion,Module_ShowWarehouseSalesorder);
	}
	
	var SorDtId   = document.getElementById('sordtid['+PIndex+']').value;
	if (SorDtId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	var vPayMode = 0; 
	for (var i=0; i < x.txtPayMode.length; i++)
	{
		if (x.txtPayMode[i].checked)
		{
			var vPayMode = x.txtPayMode[i].value;
		}
	}
	
	var sordtdiscount = '';
	if(document.getElementById('sordtdiscount['+PIndex+']'))
		sordtdiscount = document.getElementById('sordtdiscount['+PIndex+']').value;
	
	var txtSorDtPrice = '';
	if(document.getElementById('price['+PIndex+']'))
		txtSorDtPrice = document.getElementById('price['+PIndex+']').value;
	
	var chkpromo = 0;
	if (document.getElementById('chkpromo['+PIndex+']').checked)
		chkpromo = 1;
	
	var PProdQty = document.getElementById('itemprodqty['+PIndex+']').value; 
	var PSentProd = document.getElementById('itemsentprod['+PIndex+']').value;
	
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SSorId='+x.txtSorId.value+
					'&PSorId='+x.txtSorId.value+
					'&PSorDate='+x.txtDate.value+
					'&PSorCurr='+x.txtCurr.value+
					'&PSorMaturityDate='+x.txtMaturityDate.value+
					'&PSorRequestDate='+x.txtRequestDate.value+
					'&PSorClientCode='+x.txtClientCode.value+
					'&PSorClientDtCode='+x.txtClientDtCode.value+
					'&PSorSalesmanCode='+x.txtSalesmanCode.value+
					'&PSorType='+x.txtSorType.value+
					'&PSorDiscount='+x.txtSorDiscount.value+
					'&PSorDiscountAmt='+x.txtSorDiscountAmt.value+
					'&PSorVatChkbx='+x.txtSorVatChk.value+
					'&PSorProjectCode='+x.txtProjectCode.value+
					'&PSorCostCentCode='+x.txtCostCentCode.value+
					'&PDriverName='+encodeURIComponent(x.txtDriverName.value)+
					'&PVehicalNo='+encodeURIComponent(x.txtVehicalNo.value)+
					'&PVehicleWeight='+x.txtVehicleWeight.value+
					'&PPayMode='+vPayMode+
					'&sorder_export='+vsorder_export+'&txtAssignedUser='+encodeURIComponent(txtAssignedUser)+
					'&PSorRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PSorIAddress='+encodeURIComponent(x.txtIAddress.value)+
					'&PSorDAddress='+encodeURIComponent(x.txtDAddress.value)+
					'&SSorDtId='+document.getElementById('sordtid['+PIndex+']').value+
					'&lstWarehouse='+document.getElementById('warehousecode['+PIndex+']').value+
					'&txtItemCode='+encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value)+
					'&txtSorDtRemark='+encodeURIComponent(document.getElementById('remarkdt['+PIndex+']').value)+
					'&sorderdt_clientdiscount='+document.getElementById('sorderdt_clientdiscount['+PIndex+']').value+
					'&sorderdt_itemdiscount='+document.getElementById('sorderdt_itemdiscount['+PIndex+']').value+
					'&txtSorDtOQty='+document.getElementById('itemorderedqty['+PIndex+']').value+
					'&txtSorDtCQty='+document.getElementById('cancelledqty['+PIndex+']').value+
					'&txtSorDtQty='+document.getElementById('sordtquantity['+PIndex+']').value+
					'&txtSorDtQty2='+document.getElementById('unit2qty['+PIndex+']').value+
					'&txtSorDtPrice='+txtSorDtPrice+
					'&txtSorDtDiscount='+sordtdiscount+
					'&txtProjectCodeDt='+document.getElementById('projectcodedt['+PIndex+']').value+
					'&sorderdt_quantitybox='+document.getElementById('sorderdt_quantitybox['+PIndex+']').value+
					'&sorderdt_itemunit='+document.getElementById('sorderdt_itemunit['+PIndex+']').value+
					'&sorderdt_itempackage='+document.getElementById('sorderdt_itempackage['+PIndex+']').value+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').value+
					'&sorder_date='+x.sorder_date.value+'&sorder_card_msg='+x.sorder_card_msg.value+
					'&sorder_contact='+x.sorder_contact.value+'&sorder_contactphone='+x.sorder_contactphone.value+'&sorderdt_promo='+chkpromo+
					'&PProdQty='+PProdQty+'&PSentProd='+PSentProd;
			
	
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader").addClass("ajaxsaving");
		//$('#datagrid :input').attr('disabled', true);
		
		var SubBtnID = 'imgSubmit['+PIndex+']';
		if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;
		
		if(xmlhttp) {
			//xmlhttp.open("POST", "Form_SalesOrder_Actions.php", true);
		
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200)
				{
					var data = $.parseJSON(xmlhttp.responseText);
					
					var msg = data[0].message; 
					
					if (msg != "") {
						$("#Loader").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){
							transid = data[0].transid;
							
							x.txtSorId.value = transid;
							x.submit();
						} 
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'itemcode['+index+']';
						
						createCookie('so-nextcell',nextcell);
						
						ReloadGrid(filepath,formname,transid,'datagrid',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
							MoveNextRecord(nextcell);
						});
						
						ReloadGridDt(filepath,'SO-TOT','TOTALS','totals',transid,-1);
						
						document.getElementById('ModRec_G1').value = "";
					}
				}
			}
			
			// adds  a header to tell the PHP script to recognize the data as is sent via POST
			//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			//xmlhttp.send(the_data);
			
			xmlhttp.open("GET","Form_SalesOrder_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
	}
	 
	 
	 //
 }
 
});
	
	

}


function ImportExcell(transid,ModuleRestProj,ModuleRestCost,ClientDetail,CheckSalesman) {
	
	x = document.salesorder;
	
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ClientDetail, CheckSalesman);
	
	for (var i=0; i < x.txtPayMode.length; i++)
	{
		if (x.txtPayMode[i].checked)
		{
			var vPayMode = x.txtPayMode[i].value;
		}
	}
		
	var vMode = 'import';
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SSorId='+x.txtSorId.value+
					'&PSorId='+x.txtSorId.value+
					'&PSorDate='+x.txtDate.value+
					'&PSorCurr='+x.txtCurr.value+
					'&PSorMaturityDate='+x.txtMaturityDate.value+
					'&PSorRequestDate='+x.txtRequestDate.value+
					'&PSorClientCode='+x.txtClientCode.value+
					'&PSorClientDtCode='+x.txtClientDtCode.value+
					'&PSorSalesmanCode='+x.txtSalesmanCode.value+
					'&PSorType='+x.txtSorType.value+
					'&PSorDiscount='+x.txtSorDiscount.value+
					'&PSorDiscountAmt='+x.txtSorDiscountAmt.value+
					'&PSorVatChkbx='+x.txtSorVatChk.value+
					'&PSorProjectCode='+x.txtProjectCode.value+
					'&PSorCostCentCode='+x.txtCostCentCode.value+
					'&PDriverName='+encodeURIComponent(x.txtDriverName.value)+
					'&PVehicalNo='+encodeURIComponent(x.txtVehicalNo.value)+
					'&PVehicleWeight='+x.txtVehicleWeight.value+
					'&PPayMode='+vPayMode+
					'&PSorRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PSorIAddress='+encodeURIComponent(x.txtIAddress.value)+
					'&PSorDAddress='+encodeURIComponent(x.txtDAddress.value);
					
	if (result == 1) {
		x.action="Form_SalesOrder_Actions.php?"+the_data;
		x.submit();		
	}
	
}


function SearchForRef(){
    
	//ClearForm('All');
    x = document.salesorder;
    win = window.open('Form_SalesOrderSearch.php', 'Form_SalesOrderSearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=1050,height=520,top=100');		
	win.creator = self;
	win.focus();		
			
}

function SearchForPending(){
    //ClearForm('All');
    x = document.salesorder;
    win = window.open('Form_SalesOrderSearchPending.php', 'Form_SalesOrderSearchPending', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=940,height=560,top=100');		
	win.creator = self;
	win.focus();		
			
}

function SetMaturityDate() {

	x = document.salesorder;
	var vmode = x.mainaction.value;
	
	//if(x.txtClientVat.value == 1)
	    //x.chkSorVat.checked = true;
		
		
    
	//if (vmode == 'insert' || vmode == 'edit') {
	    var str   = document.getElementById('txtPaymentTerms').value;
		var str1 = '';
		
		if (str == '') str = 0;
		var sdays = parseInt(str);	
		var sdate = document.getElementById('txtDate').value;
		sdate = ChangeDate(sdate);
		var d = new Date(sdate); 
		
		d.setDate(d.getDate() + sdays); 
		
		str = d.getDate();
		str1 = str.toString();
		
		if (str1.length == 1)
     		str1 = "0"+str1;
			
		str = d.getMonth()+1;
		str2 = str.toString();
		
		if (str2.length == 1)
     		str2 = "0"+str2;	
		
		
		x.txtMaturityDate.value=(str1 + "/" + str2 + "/" + d.getFullYear()); 
		
	//}  
	
	    
		
}

function ChangeDate(sdate){
	var idate = new String;
	idate = sdate;
      
    dt_array = idate.split("/");
      
    if ((dt_array[0] < 10) && (dt_array[0].length == 1))
		dt_array[0] = "0" + dt_array[0];
        
	if ((dt_array[1] < 10) && (dt_array[1].length == 1))
		dt_array[1] = "0" + dt_array[1];
   	
	//fdate = dt_array[2] + "-" + dt_array[1] + "-" + dt_array[0];
	// "mm/dd/yyyy"
	fdate = dt_array[1] + "/" + dt_array[0] + "/" + dt_array[2];
	
	return fdate;
}



function CalcSorDiscount(option, dec, vatapplied, vatperc, SalesTTC) {
	x = document.salesorder;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var TaxAmt	     = x.txtSorTaxable.value;
	var GrossTotal   = x.txtSorGrossTotal.value;
	var DisPer	     = x.txtSorDiscount.value;
	var DisAmt	     = x.txtSorDiscountAmt.value;
	var VatAmt	     = x.txtSorVat.value;
	var TaxesAmt     = x.txtSorTotalTaxes.value;
	var TransportAmt = x.txtSorTransportAmt.value;
	
	if ((DisAmt*1 != DisAmt/1 || DisAmt < 0) ) {
		alert('Discount Amount should be a NUMERIC value');
		x.txtSorDiscountAmt.focus();
		return 0;
	}
	else if ((DisPer*1 != DisPer/1 || DisPer < 0) ) {
		alert('Discount Percentage should be a NUMERIC value');
		x.txtSorDiscount.focus();
		return 0;
	}
	
	
	if (TaxAmt == '') 	    TaxAmt = 0;
	if (GrossTotal == '')   GrossTotal = 0;
	if (DisPer == '') 	    DisPer = 0;
	if (DisAmt == '') 	    DisAmt = 0;
	if (TaxesAmt == '')     TaxesAmt = 0;
	if (TransportAmt == '') TransportAmt = 0;
	
	TaxAmt 	     = parseFloat(TaxAmt);
	GrossTotal   = parseFloat(GrossTotal);
	DisPer	     = parseFloat(DisPer);
	DisAmt 	     = parseFloat(DisAmt);
	VatAmt 	     = parseFloat(VatAmt);
	TaxesAmt     = parseFloat(TaxesAmt);
	TransportAmt = parseFloat(TransportAmt);
			
			
	
	if (GrossTotal > 0 && (DisPer > 0 || DisAmt > 0)) {
		if (option == 1 )  //Option by Percentage Get The Amount
			x.txtSorDiscountAmt.value = roundNumber((GrossTotal*DisPer/100),dec);
		else if (option == 2 ){  //Option by Amount Get The Per
		    x.txtSorDiscount.value = roundNumber(((DisAmt/GrossTotal)*100),dec);
				
			if (DisAmt > 0)	x.txtSorDiscount.readOnly = true; 
			else	x.txtSorDiscount.readOnly = false;
					
		}

		// Calculation of Vat Amount and Net Total
		DisAmt = x.txtSorDiscountAmt.value;
		if (DisAmt == '') DisAmt = 0;
		DisAmt = parseFloat(DisAmt);
		
		VatAmt = 0;
		if (SalesTTC == 1) {		
			if (vatapplied == 1 && TaxAmt > 0) {
				VatAmt = roundNumber((((TaxAmt - DisAmt + TransportAmt) / (1 + vatperc/100)) * (vatperc/100)),dec);
			}
			
			NetTotal = 	roundNumber((GrossTotal + TaxesAmt - DisAmt + TransportAmt),dec);
			
		}
		else {
			if (vatapplied == 1 && TaxAmt > 0) {
				VatAmt = roundNumber(((TaxAmt - ((DisAmt - TransportAmt)*TaxAmt/GrossTotal))*vatperc/100),dec);
			} 
			
			NetTotal = 	roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt + TransportAmt),dec);
		}
		
		VatAmt 	 = parseFloat(VatAmt);
		NetTotal = parseFloat(NetTotal);
		x.txtSorVat.value      = formatNumber(VatAmt,dec);
		x.txtSorNetTotal.value = formatNumber(NetTotal,dec);

	}   
	
}

function UploadDocuments(vform){

var txtPorId = document.salesorder.txtSorId.value;

win = window.open('UploadDocuments.php?vform='+vform+'&porderid='+txtPorId, 'Upload', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=990,height=600,top=60,left=100');		
	win.creator = self;
	win.focus();	

}



function CalcNetTotal(dec, vatapplied, vatperc, SalesTTC) {
	x = document.salesorder;
	
	var TaxAmt 		 = x.txtSorTaxable.value;
	var GrossTotal   = x.txtSorGrossTotal.value;
	var VatAmt       = x.txtSorVat.value;
	var DisAmt       = x.txtSorDiscountAmt.value;
	var NetTotal     = x.txtSorNetTotal.value;
	var TaxesAmt     = x.txtSorTotalTaxes.value;
	var TransportAmt = x.txtSorTransportAmt.value;
	
	if (TaxAmt == '') 		TaxAmt = 0;
	if (GrossTotal == '') 	GrossTotal = 0;
	if (VatAmt == '') 		VatAmt = 0;
	if (DisAmt == '') 		DisAmt = 0;
	if (NetTotal == '') 	NetTotal = 0;
	if (TaxesAmt == '') 	TaxesAmt = 0;
	if (TransportAmt == '') TransportAmt = 0;
	
	TaxAmt		 = parseFloat(TaxAmt);
	VatAmt		 = parseFloat(VatAmt);
	NetTotal	 = parseFloat(NetTotal);
	DisAmt		 = parseFloat(DisAmt);
	GrossTotal	 = parseFloat(GrossTotal);
	TaxesAmt 	 = parseFloat(TaxesAmt);
	TransportAmt = parseFloat(TransportAmt);
	
	
	
	VatAmt = 0;
	
	if (SalesTTC == 1) {
		if (vatapplied == 1 && TaxAmt > 0) {
			VatAmt = roundNumber((((TaxAmt - DisAmt + TransportAmt) / (1 + vatperc/100)) * (vatperc/100)),dec);
		}
			
		NetTotal = GrossTotal + TaxesAmt + TransportAmt - DisAmt;
	} else {
		if (vatapplied == 1 && TaxAmt > 0) {
			VatAmt = roundNumber(((TaxAmt - ((DisAmt - TransportAmt)*TaxAmt/GrossTotal))*vatperc/100),dec);
		}
			
		NetTotal = GrossTotal + VatAmt + TaxesAmt + TransportAmt - DisAmt;
	}
	
	VatAmt 	   = parseFloat(VatAmt);
	NetTotal   = parseFloat(NetTotal);
	x.txtSorVat.value      = formatNumber(VatAmt,dec);	
	x.txtSorNetTotal.value = formatNumber(roundNumber(NetTotal,dec),dec);

}

function SetSorVat(dec, vatapplied, vatperc, SalesTTC) {
	x = document.salesorder;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var vAmount = 0;
	
	var TaxAmt 		 = x.txtSorTaxable.value;
	var GrossTotal 	 = x.txtSorGrossTotal.value;
	var VatAmt 		 = x.txtSorVat.value;
	var DisAmt 	 	 = x.txtSorDiscountAmt.value;
	var NetTotal     = x.txtSorNetTotal.value;
	var TaxesAmt     = x.txtSorTotalTaxes.value;
	var TransportAmt = x.txtSorTransportAmt.value;
	
	if (TaxAmt == '') 		TaxAmt = 0;
	if (GrossTotal == '') 	GrossTotal = 0;
	if (VatAmt == '') 		VatAmt = 0;
	if (DisAmt == '') 		DisAmt = 0;
	if (NetTotal == '') 	NetTotal = 0;
	if (TaxesAmt == '') 	TaxesAmt = 0;
	if (TransportAmt == '') TransportAmt = 0;
	
	VatAmt 		 = parseFloat(VatAmt);
	NetTotal 	 = parseFloat(NetTotal);
	DisAmt 		 = parseFloat(DisAmt);
	TaxAmt 		 = parseFloat(TaxAmt);
	GrossTotal 	 = parseFloat(GrossTotal);
	TaxesAmt 	 = parseFloat(TaxesAmt);
	TransportAmt = parseFloat(TransportAmt);
	
	
	if (x.chkSorVat.checked) {
		
		x.txtSorVatChk.value = 1;
		
		// Calculation of Vat Amount and Net Total
		
		VatAmt = 0;
		if (SalesTTC == 1) {		
			if (vatapplied == 1 && TaxAmt > 0) {
				VatAmt = roundNumber((((TaxAmt - DisAmt + TransportAmt) / (1 + vatperc/100)) * (vatperc/100)),dec);
			}
			
		}
		else {
			if (vatapplied == 1 && TaxAmt > 0) {
				VatAmt = roundNumber(((TaxAmt - ((DisAmt - TransportAmt)*TaxAmt/GrossTotal))*vatperc/100),dec);
			} 
			
			NetTotal = 	roundNumber((GrossTotal + VatAmt + TaxesAmt - DisAmt + TransportAmt),dec);
		}
		
		VatAmt	   = parseFloat(VatAmt);
		TaxAmt 	   = parseFloat(TaxAmt);
		GrossTotal = parseFloat(GrossTotal);
		NetTotal   = parseFloat(NetTotal);
		
		x.txtSorTaxable.value    = formatNumber(TaxAmt,dec);
		x.txtSorGrossTotal.value = formatNumber(GrossTotal,dec);
		x.txtSorVat.value        = formatNumber(VatAmt,dec);
		x.txtSorNetTotal.value   = formatNumber(NetTotal,dec);

	}
	else
	{
		x.txtSorVatChk.value = 0;
		
		if (SalesTTC == 1) {
			x.txtSorVat.value      = formatNumber(0,dec);
		}
		else {
			x.txtSorVat.value      = formatNumber(0,dec);
			x.txtSorNetTotal.value = formatNumber(roundNumber((NetTotal - VatAmt),dec),dec);
		}
		
	}  

}
/*
function roundNumber(num, dec) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  newnumber = parseFloat(newnumber); 
  
  return newnumber;
}

function formatNumber(num, dec) { // Arguments: number to format, number of decimal places
	return num.toFixed(dec);
}*/

function PrintSalesOrder(SorId, SorRef, SorType) {
	var str = '';
	var vShowDetail = 1;
	
	if(SorType=='PF')
		str = 'Form_SalesOrderPreview.php?SorderId='+SorId+'&ShowDetail='+vShowDetail;
	else
	str = 'Form_SalesOrderPreview.php?SorderId='+SorId+'&ShowDetail='+vShowDetail;
		window.open(str);
	/* if (confirm ( "Do you want to Print current preparation order with reference "+SorRef+" ?"))
	{
		if (SorType == 'QO') {
			vShowDetail = 0;
			if (confirm ( "Do you want to Print with Detail ?","Yes","No") )
			{
				vShowDetail = 1;
			}
		}
		
		str = 'Form_SalesOrderPreviewNoPrice.php?SorderId='+SorId+'&ShowDetail='+vShowDetail;
		window.open(str);
	}	 */
	
}

function PrintStatement(Base1Curr,ModuleReferenceByProject) {
	x = document.salesorder;
	var vCurrDate = new Date();
	var m = vCurrDate.getMonth()+1;
	var d = vCurrDate.getDate();
	var vMonth = (m < 10) ? '0' + m : m;
	var vDays  = (d < 10) ? '0' + d : d; 
	var vYear  = vCurrDate.getYear();
	
	if (x.txtClientCode.value == '') {
		alert('Please choose a client.');
		return;
	}	
		
	varfromledger  = x.txtClientCode.value;
	vartoledger    = x.txtClientCode.value;
	varfromproject = x.txtProjectCode.value;
	vartoproject   = x.txtProjectCode.value;
	varfromcst     = x.txtCostCentCode.value;
	vartocostcent  = x.txtCostCentCode.value;
	varfromdate    = "01/01/" + vYear;
	vartodate 	   = vDays + "/" + vMonth + "/" + vYear;
	
	if (ModuleReferenceByProject == 1) {
		str =   'Rep_StatementProjCost.php?option=1&fromdate='+varfromdate+'&todate='+vartodate+'&fromledger='+varfromledger+'&toledger='+vartoledger
			   +'&fromproject='+varfromproject+'&toproject='+vartoproject+'&fromcst='+varfromcst+'&tocostcent='+vartocostcent
			   +'&currency='+Base1Curr+'&groupby=1&balance=1&prtvaluedate=1&prtjvtype=1&prtprevbal=1&showdetail=1&alltypes=1'
			   +'&exclude=0&jvtype=&parentprjcost=0';
	} else {
		str =   'rep_statementofaccount.php?fromdate=&todate=&fromledger='+varfromledger+'&toledger='+vartoledger
			   +'&dateoption=1&transaction=3&ledgeroption=1&curr=1&currbase1=0&currbase2=0&cum=0'
			   +'&alltypes=1&exclude=0&jvtype=&showunposted=0&prtfolio=1&prtref=1&prtdesc=1&prtvaluedate=1'
			   +'&prtjvtype=0&prtcostcent=0&prtproject=0&prevbal=1&dtjv=0&dtdate=1&checks=1';
	}
   
   
	window.open(str);
}

function showlistClient(str){
	var vdate, vcode;
	vdate=document.salesorder.txtDate.value;
	vcode=encodeURIComponent(document.salesorder.txtClientCode.value);
  
	window.open('List_SorClient.php?frm=1&item='+str+'&PLedger_number='+vcode+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');

}
function showlistClientName(str) {
	var vdate, vcode;
	vdate=document.salesorder.txtDate.value;
	vname=encodeURIComponent(document.salesorder.txtClientName.value);
  
	window.open('List_SorClient.php?frm=1&item='+str+'&PLedger_name='+vname+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistClientDetail(str){
  var vcltcode, vcode;
  vcode   =document.salesorder.txtClientDtCode.value;
  vcltcode=encodeURIComponent(document.salesorder.txtClientCode.value);
  
  window.open('List_ClientDetail.php?frm=1&item='+str+'&PDetailCode='+vcode+'&PClientCode='+vcltcode,'List_ClientDetail','width=700,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistSalesman(str){
  var vdate, vcode;
  vdate=document.salesorder.txtDate.value;
  vcode=encodeURIComponent(document.salesorder.txtSalesmanCode.value);
  
  window.open('List_SorSalesman.php?frm=1&item='+str+'&PLedger_number='+vcode+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistProject(str){

	vProjectCode = encodeURIComponent(document.getElementById('txtProjectCode').value);
	window.open('List_SorProject.php?frm=1&item='+str+'&PProject_Code='+vProjectCode,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistCostcenter(str){

	vCostcentCode = encodeURIComponent(document.getElementById('txtCostCentCode').value);
	window.open('List_SorCostcenter.php?frm=1&item='+str+'&PCostcent_Code='+vCostcentCode,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistProjectDt(str,PIndex){
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vProjectCode = encodeURIComponent(document.getElementById('projectcodedt['+PIndex+']').value);
	
	window.open('List_SorProject.php?frm=25&index='+PIndex+'&item='+str+'&PProject_Code='+vProjectCode,'List_SorProject','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistCostcenterDt(str,PIndex){
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vCostcentCode = encodeURIComponent(document.getElementById('costcentcodedt['+PIndex+']').value);
	
	window.open('List_SorCostcenter.php?frm=25&index='+PIndex+'&item='+str+'&PCostcent_Code='+vCostcentCode,'List_SorCostcenter','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistItems(str,PIndex){
	var vDate, vItemCode;
	x = document.salesorder;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemCode  = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
	
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&PItem_Code='+vItemCode+'&ItemType=All&TransDate='+vDate,'List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistItemsDesc(str,PIndex){
	var vDate, vItemCode;
	x = document.salesorder;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemDesc  = encodeURIComponent(document.getElementById('itemdescription['+PIndex+']').value);
	
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&PItem_Description='+vItemDesc+'&ItemType=All&TransDate='+vDate,'List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistWarehouse(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vWarehouseCode = encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	
	window.open('List_SorWarehouse.php?frm=2&index='+PIndex+'&PWarehouse_Code='+vWarehouseCode,'List_SorWarehouse','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function CalcSorDtTotal(dec,PIndex) {
	x = document.salesorder;
	var vmode = x.actionmode.value;
	var Qty      = document.getElementById('sordtquantity['+PIndex+']').value;
	var Price    = document.getElementById('price['+PIndex+']').value;
	var Discount = document.getElementById('sordtdiscount['+PIndex+']').value;
	
	if (Qty == '') 		Qty = 0;
	if (Price == '') 	Price = 0;
	if (Discount == '') Discount = 0;
	
	Qty      = parseFloat(Qty);
	Price    = parseFloat(Price);
	Discount = parseFloat(Discount);
	
	if (Qty > 0 && Price >= 0) {
	   document.getElementById('sordttotal['+PIndex+']').value = roundNumber(((Qty*Price) - roundNumber((Qty*Price*Discount/100),0)),dec);
	}  
	
}

function CalcSorDtQty(PIndex) {
	x = document.salesorder;
	var OQty = document.getElementById('itemorderedqty['+PIndex+']').value;
	var CQty = document.getElementById('cancelledqty['+PIndex+']').value;
	
	if (OQty == '') OQty = 0;
	if (CQty == '') CQty = 0;
	
	OQty = parseFloat(OQty);
	CQty = parseFloat(CQty);
	
	
	document.getElementById('sordtquantity['+PIndex+']').value = (OQty - CQty);
	

}



function CalcQty2(ModuleUnit1Method,Option,PIndex) {
	x = document.salesorder;
	var Qty  = document.getElementById('sordtquantity['+PIndex+']').value; 
	var Qty2 = document.getElementById('unit2qty['+PIndex+']').value;
	var UnitCoef = document.getElementById('itemunitcoef['+PIndex+']').value;
	
	if (Qty == '')  Qty = 0;
	if (Qty2 == '') Qty2 = 0;
	
	if(ModuleUnit1Method == 1) {
		if (Qty > 0 && Option == 1 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = Qty*UnitCoef;
		}	
		else if (Qty == 0 && Option == 1 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = '';
		}
	}
	//Case Modify Qty and Qty2 Should Be Empty
	else if(ModuleUnit1Method == 0 && Option == 1 && Qty2 == 0) {
		if (Qty > 0 && UnitCoef != 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = Qty/UnitCoef;
		}	
		else if (Qty == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = '';
		}
	}
	//Case Modify Qty2 Get Qty
	else if(ModuleUnit1Method == 0 && Option == 2) {
		if (Qty2 > 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('sordtquantity['+PIndex+']').value = Qty2*UnitCoef;
		}	
		else if (Qty2 == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('sordtquantity['+PIndex+']').value = '';
		}
	}
}

function ShowSlidingDiv(PIndex) {
	var Div = "#slidingDiv"+PIndex;
	$(Div).slideToggle();
	
}


function kd(e)
{ 

	x=document.salesorder;
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { //enter key
        //x.btnSubmitRecord.click();
		
		/*el = x.elements;
		var w = '';
		for(var i=0;i<el.length;i++){
		
			el[i].getfocus=function(){
				w=this.name;
				alert(w);
			}
		}*/
		

		return false;
    }
    return true;
}

function changeQty2(vuniteQty,index){ 
	var vUnit2 = document.getElementById("itemunit2["+index+"]").value;
	
	if(vUnit2 == '') vUnit2 =0;
	if(vuniteQty == '') vuniteQty=0;
	document.getElementById("sordtquantity["+index+"]").value = vuniteQty/vUnit2;
	var newqty = document.getElementById("sordtquantity["+index+"]").value;
	if(document.getElementById("sordttotal["+index+"]"))
	 document.getElementById("sordttotal["+index+"]").value = parseFloat(newqty)*parseFloat(document.getElementById("price["+index+"]").value);
	
	
}
function openAddressInfo(txtSorId)
{
	var x = document.salesorder;
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	if(txtSorId == null)
	{
		txtSorId = "";
	}
	var sorder_date = x.sorder_date.value;
	var sorder_card_msg = x.sorder_card_msg.value;
	var sorder_contact = x.sorder_contact.value;
	var txtDAddress = x.txtDAddress.value;
	var sorder_contactphone = x.sorder_contactphone.value;
	
	window.open('updateAddressInfo2.php?SorId='+txtSorId+'&sorder_date='+sorder_date+'&sorder_card_msg='+sorder_card_msg+'&sorder_contact='+sorder_contact+'&txtDAddress='+txtDAddress+'&sorder_contactphone='+sorder_contactphone,'updateAddressInfo','width=520,height=250,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function loadtransfer(){
	var clientcode = document.getElementById("txtClientCode").value;
	window.open('Form_sorder_loadtransfer.php?clientcode='+clientcode,'Load Transfer','width=520,height=250,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,width=950,height=560,top=100')
}

function showMaterials(){
	var sorder_id = document.salesorder.txtSorId.value;
	window.open("Rep_ProductionRecipe.php?sorder_id="+sorder_id,"Receipe");
}	
function setType(){
	var x = document.salesorder;
	x.submit();
}
function AddParamter(index,transdt_id){
	XPos = (screen.availHeight - 750) / 2;
	YPos = (screen.availWidth - 1050) / 2;
	var item_code = document.getElementById("itemcode["+index+"]").value;
	window.open('Form_add_itemAttr.php?item_code='+item_code+'&sorderdt_id='+transdt_id,'Add Item Attribute','width=1100,height=700,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}


function showlistUsers(str){
	window.open('list_users.php?frm='+str,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Preparation Order</title>



<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>

</head>
<body>
<form name='salesorder' id='salesorder' method='post' action=''  enctype='multipart/form-data'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='message' value='$message' size='200'>
<input type='hidden' name='directPrintSO' value='$directPrintSO'>		
<input type='hidden' name='costcentminimum' id='costcentminimum' value='$costcentminimum'>		
<input type='hidden' name='allow_duplicateItem' value='$allow_duplicateItem'>
HERE;

//$message='';

	
//Initializations

$PriceLabel = 'Price';	
if ($SalesTTC == 1) 	
	$PriceLabel = 'Price TTC';	


//Get Default Project from sordersetup
$querydflproject="select defaultproject as defaultprojectsordersetup from sordersetup ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}


	
//Get Default Project
$querydflproject="select project_code as defaultproject from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_project=1 ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}

 if (empty($defaultproject))
 {
	 $defaultproject =  $defaultprojectsordersetup;
 }


//Get Default Coscenter
$querydflcostcent="select costcent_code as defaultcostcent from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_costcenter=1 ";
$resultdflcostcent=mysql_query($querydflcostcent,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflcostcent)){
	extract($rows);
}

$querydflwh="select warehouse_code as defaultwarehouse from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and ifNull(default_warehouse,0) = 1 ";
$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}

if ((empty($txtProjectCode)) && $Module_Project == 1)
	$txtProjectCode = $defaultproject;
if ((empty($txtCostCentCode)) && $Module_CostCenter == 1)	
	$txtCostCentCode = $defaultcostcent;	
if (empty($txtCurr))
{
	if ($ClientCur != '')
		$txtCurr = $ClientCur;
	else
		$txtCurr = $base1;
}
if (empty($txtDate))	
	$txtDate = displayToday();
if (empty($txtMaturityDate))	
	$txtMaturityDate = displayToday();
if (empty($txtRequestDate))	
	$txtRequestDate = displayToday();	

if($default_sorderType != '' && empty($txtSorType))  $txtSorType = $default_sorderType;	
if (empty($txtSorType))
	$txtSorType = 'SO';	

$txtClientDetail = 0;

if ($actionmode != "cancel" && $txtSorId != '') {
	// Read From Temp Tables For Selected Record				 
	$query = " Select Sorder_ID, Sorder_Reference, Date_Format(Sorder_Date,'%d/%m/%Y') As Sorder_Date, ".
	         " Date_Format(Sorder_MaturityDate,'%d/%m/%Y') As MaturityDate, Date_Format(Sorder_RequestDate,'%d/%m/%Y') As RequestDate, ".
			 " Sorder.Client_code As ClientCode, Clients.Ledger_name As ClientName, Client_VAT,   ".
			 " Sorder.Salesman_code As SalesmanCode, Salesmen.Ledger_name As SalesmanName, ".
			 " Sorder.Currency_code, Sorder_ClientContact, Sorder_DeliveryPlace, ".
			 " Sorder_Remark, Sorder.Project_Code, Sorder.Costcent_code,  ".
			 " Round(if($SalesTTC=1,ifNull(Sorder_Taxable,0)*(1+$Setup_VatPercentage/100),ifNull(Sorder_Taxable,0)), ".$DecimalBase."), Round(ifNull(Sorder_NoneTaxable,0), ".$DecimalBase."), ".
			 " Round(if($SalesTTC=1,ifNull(Sorder_Taxable,0)*(1+$Setup_VatPercentage/100),ifNull(Sorder_Taxable,0)) + ifNull(Sorder_NoneTaxable,0), ".$DecimalBase.") As GrossTotal, ".
			 " Round(ifNull(Sorder_DiscountPer,0), ".$DecimalBase."), Round(ifNull(Sorder_DiscountAmount,0), ".$DecimalBase."),  ".
			 " Round(ifNull(Sorder_VAT,0), ".$DecimalBase.") As Sorder_VAT, ".
			 " Round((if($SalesTTC=1,ifNull(Sorder_Taxable,0)*(1+$Setup_VatPercentage/100),ifNull(Sorder_Taxable,0)) + ifNull(Sorder_NoneTaxable,0) + if($SalesTTC=1,0,IfNull(Sorder_VAT,0)) + if($SalesTTC=1,IfNull(Sorder_TransportTTC,0),IfNull(Sorder_TransportAmount,0)) - IfNull(Sorder_DiscountAmount,0) + (ifNull(Sorder_Tax1,0) + ifNull(Sorder_Tax2,0) + ifNull(Sorder_Tax3,0) + ifNull(Sorder_Tax4,0) + ifNull(Sorder_Tax5,0))), ".$DecimalBase.") As Sorder_NetTotal,  ".
			 " ifNull(Sorder_VatChckbx,0) As Sorder_VatChckbx, ".
			 " Round((ifNull(Sorder_Tax1,0) + ifNull(Sorder_Tax2,0) + ifNull(Sorder_Tax3,0) + ifNull(Sorder_Tax4,0) + ifNull(Sorder_Tax5,0)), ".$DecimalBase.") As TotalTaxes,  ".
			 " Sorder_Type, ClientsDetail.Detail_Code, ClientsDetail.Detail_Name, Sorder_DriverName, Sorder_VehicalNo, Sorder_VehicleWeight, ".
			 " Round(if($SalesTTC=1,IfNull(Sorder_TransportTTC,0),IfNull(Sorder_TransportAmount,0)), ".$DecimalBase.") As TransportAmt, ifNull(Sorder_PaymentMode,0) as PaymentMode,sorder_export, ".
			 " date_format(Sorder_ClientSorderDate, '%d/%m/%Y') as sorder_date1, Sorder_ClientPhone as sorder_contactphone, Sorder_ShippingWay as sorder_card_msg, Sorder_ShipName as sorder_contact, ".
			 " assignto_user ".
			 " From Temp_Sorder As Sorder ".
			 " Left Join Clients on Sorder.Client_code = Clients.Ledger_Number ".
			 " Left Join ClientsDetail on Sorder.Detail_Code = ClientsDetail.Detail_Code ".
			 " Left Join Salesmen on Sorder.Salesman_code = Salesmen.Ledger_Number ".
	         " Where Sorder_ID = ".$txtSorId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
			 
			 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	extract($rows);
	$txtSorId 	= $rows[0];
	$txtRef   	= $rows[1];
	$txtDate  	= $rows[2];
	$txtSorType = $rows[25];
	
	if($txtMaturityDate=="")
	$txtMaturityDate = $rows[3];
	
	$txtRequestDate  = $rows[4];
	
	if (empty($txtClientCode)) {
		$txtClientCode   = $rows[5];
		$txtClientName   = $rows[6];
		$txtClientVat    = $rows[7];
	}
	
	$txtSalesmanCode = $rows[8];
	$txtSalesmanName = $rows[9];
	$txtCurr         = $rows[10];
	$txtIAddress     = $rows[11];
	$txtDAddress     = $rows[12];
	$txtRemark       = $rows[13];
	$txtProjectCode  = $rows[14];
	$txtCostCentCode = $rows[15];
	
	
	$txtSorTaxable      = $rows[16];
	$txtSorNoneTaxable  = $rows[17];
	$txtSorGrossTotal   = $rows[18];
	$txtSorDiscount     = $rows[19];
	$txtSorDiscountAmt  = $rows[20];
	$txtSorVat          = $rows[21];
	$txtSorNetTotal     = $rows[22];
	$txtSorVatChk       = $rows[23];
	$txtSorTotalTaxes   = $rows[24];
	$txtSorTransportAmt = $rows[31];
	
	$txtClientDtCode   = $rows[26];
	$txtClientDtName   = $rows[27];
	
	$txtDriverName     = $rows[28];
	$txtVehicalNo      = $rows[29];
	$txtVehicleWeight  = $rows[30];
	
	$txtPayMode 		= $rows[32];
	$sorder_export 		= $rows[33];
	$txtAssignedUser 	= $rows[38];
	
	$query = " Select Count(*) FROM Temp_SorderDt ".
			 " WHERE Sorder_id = ".$txtSorId;
	$result = selectData($connection, $query);
	//echo $result[0];
	$txtSorCountDetail = $result[0];
	if($txtSorCountDetail == '') $txtSorCountDetail = 0;
	//echo $txtSorCountDetail;

	
}
//echo $txtSorCountDetail;

/*
//Search/Cancel Mode	
if ($actionmode == "cancel" && $txtSorId != '') {
	
		
	// Delete From Temp Tables Already Filled By Search
	$query = " DELETE FROM Temp_SorderDt ".
			 " WHERE Sorder_id = ".$txtSorId;
			 //" AND Logged_Code = '".$_SESSION['useraccount']."' ";
	if (!updateData($connection, $query, true))
      $message  = mysql_error(); 
	  
	
	  
	$query = " DELETE FROM Temp_Sorder ".
			 " WHERE Sorder_id = ".$txtSorId;
			 //" AND Logged_Code = '".$_SESSION['useraccount']."' ";
	if (!updateData($connection, $query, true))
      $message  = mysql_error();   

	$txtSorId = '';
}*/






//$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";
//echo $txtSorCountDetail;
echo"<table cellpadding='0' cellspacing='0' border='0'  align='center' class='layout-width'>";
include_once("header.php");
echo" <tr><td  valign='top'>";

include_once("sidemenu.php");
echo"  </td></tr>";


echo" <tr style='height:26px;'>
		<td  valign='top' id='content-top'><input type='hidden' id='txtSaDiscount_Temp'  name='txtSaDiscount_Temp' value='$txtSaDiscount_Temp'>
			<table border='0' cellpadding='0' cellspacing='0' style='table-layout:fixed; height:26px;' class='layout-width'>
			<tr style='height:26px;'>
				<td style='width:38px; height:26px;'>&nbsp;</td>
				<td valign='middle' style='width:300px; height:26px;'><span class='title'>PREPARATION ORDER</span></td>
				<td class='message' valign='middle' style='height:26px;'>".htmlspecialchars($message, ENT_QUOTES)."</td>
			</tr></table>
		</td>
	  </tr>";

echo"<tr>
		<td  height='34'  valign='top' id='content-top2'>
			<table border='0' cellpadding='0' cellspacing='0' class='layout-width'>
			<tr>
				<td width='30'  height='34'>&nbsp;</td>
				<td valign='middle' height='34' width='800px' align='left'>";
	
//if ($FI_SalesOrderIns == 1)
//	echo"	<input type='button' id='btnAddItem' name='btnAddItem' value='Add Item'  onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $txtClientDetail, $FI_SalesCheckSalesman)' $style title='Add Item' >";

echo" <button type='button' id='btnClear' name='btnClear' onclick='ClearPage();return false;' title='Clear Page'><span><span>Clear Page</span></span></button>";

				
if ($txtSorId != '')
	echo" <button type='button' id='btnCancel' name='btnCancel' onclick='CancelRecord();return false;' title='Cancel Changes'><span><span>Cancel</span></span></button>";

	
if ($txtSorId != '')
	echo" <button type='button' id='btnPost' name='btnPost' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $txtClientDetail, $FI_SalesCheckSalesman);return false;' title='Save Changes'><span><span>Save</span></span></button>";


if ($txtSorId == '')
	echo" <button type='button' id='btnSearch' name='btnSearch' onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</span></span></button>";


if ($txtSorId == ''){
	echo" <button type='button' id='btnPending' name='btnPending' onclick='SearchForPending();return false;' title='Pending Preparation Order'><span><span>Pending</span></span></button>";

echo" <button type='button' id='btnloadTransfer' name='btnloadTransfer' onclick='loadtransfer();return false;' title='Load Transfer'><span><span>Load Transfer</span></span></button>";
}

if ($RA_StatementofAccount == 1 && $txtClientCode != '')
	echo" <button type='button' id='btnStatement' name='btnStatement' onclick=\"PrintStatement('".$base1."',$Module_ReferenceByProject)\";return false; title='Print Client Statement'><span><span>Client Statement</span></span></button>";
if ($txtSorId != '')
	echo" <button type='button' id='btnShow' name='btnShow' onclick='showMaterials();return false;' title='Show Materials'><span><span>Show Materials</span></span></button>";


if ($txtSorId !='')	
	echo"<button type='button' id='btnUpload' name='btnUpload' 
			onclick=\"UploadDocuments('salesorder');return false;\" title='Upload Documents'><span><span>Upload Documents</span></span></button>";
			
	
echo"</td><td>";

if($Module_ImportExcell==1)
echo"<table border=0><tr><td>
<button type='button' id='btnImp' name='btnImp' onclick=\"ImportExcell('$txtSorId',$Module_RestrictProjCost,$Module_RestrictCost,$txtClientDetail,$FI_SalesCheckSalesman);return false;\" title='Import From Excel'><span><span>Import from Excell</span></span></button>
<input type='file'  name='image'    id='image' style='width:200px;' accept='file/xls'>
</td>
</tr></table>";
	
echo"	</td></tr></table>";
echo"</td></tr>";				

		
echo"<tr><td id='content-body'>
<table border='0'  align='center' valign='top' width=100% class='tablecontent'>
   <tr bgcolor='#F7F7F7'><td valign='top' align='left' colspan='10'>";		
   //$query = " Select Count(*) FROM Temp_SorderDt ".
			 //" WHERE Sorder_id = ".$txtSorId;
	//$result = selectData($connection, $query);
	//echo $result[0];
	//$txtSorCountDetail = $result[0];
	//if($txtSorCountDetail == '') $txtSorCountDetail = 0;
	//echo $result[0];
$strt = $_SESSION['StartFinancial_Date'];
$end = $_SESSION['EndFinancial_Date'];
echo"<input type='hidden' name='sorder_export' value='$sorder_export' size='10'>";
print <<<HERE

		<table border="0" style='table-layout:fixed'>
		  <col width=90>
		  <col width=155>
		  <col width=90>
		  <col width=155>
		  <col width=120>
		  <col width=200>
		  <col width=270>
		<tr bgcolor="#F7F7F7" height='25'>
          <td valign="center" align='left' ><span class="style1">Reference&nbsp;<span class="style16">*</span></span></td>
		  <td><font face='Verdana' size='2'><b>&nbsp;$txtRef</b></font><input type='hidden' name='txtSorCountDetail' value='$txtSorCountDetail' ><input type='hidden' name='txtSorId' value='$txtSorId' size='10'><input type="hidden" name="txtRef" value="$txtRef" size='10' readonly></td>
		  <td align="left"><span class="style1">Date&nbsp;<span class="style16">*</span></span></td>
		  <td><input type='text' size='10' name='txtDate' id='txtDate' value='$txtDate'   onBlur=checkDateFormat(this,$strt,$end)   onchange='SetMaturityDate();' maxlength='10'  >
		                   <A HREF="#" onClick="displayCalendar(document.salesorder.txtDate,'dd/mm/yyyy',this);  return false; " NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A></td>
          <td align='left' ><span class='style1'>Maturity&nbsp;<span class="style16">*</span></span></td>
HERE;
		  
      echo"    <td ><input type='text' style='width:95px;' name='txtMaturityDate' value='$txtMaturityDate' maxlength='10' ";if($login_maturitydate==0) echo ' readonly'; echo" >";
	  
	  
	if($login_maturitydate==1) {
		print <<<HERE
						  <A HREF="#" onClick="displayCalendar(document.salesorder.txtMaturityDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A>
HERE;
	
	}
	
echo"</td>";


if ($txtClientCode != "" ){				
	$query = " SELECT Client_CreditLimit, Client_Address, Ifnull(Client_PaymentTerms,0), Clients.Salesmen_Code, Salesmen.Ledger_name As Salesmen_Name, ifNull(Clients.Client_Detail,0), Clients.Project_Code, ".
			 " Clients.CostCenter_Code, ifNull(Client_DeliveryTransfer, 0) As Client_DeliveryTransfer, Clients.Currency_Code, Salesmen.Salesman_WarehouseCode, ifNull(Client_Promotion,0) ".
	         " FROM Clients ".
			 " Left Outer Join Salesmen on Clients.Salesmen_Code = Salesmen.Ledger_number ".
			 " WHERE Clients.Ledger_Number = '".$txtClientCode."'";
	$result = selectData($connection, $query);

	$txtCreditLimit = $result[0];
	//$txtIAddress = $result[1];
	$txtPaymentTerms = $result[2];
	
	$txtMaturityDate =  date('d/m/Y', strtotime(insertDate($txtDate). ' + '.$txtPaymentTerms.' days'));
	

	
	//if ($txtDAddress == ""){$txtDAddress = $txtIAddress;}
	if ($txtDAddress == ""){$txtDAddress = $result[1];}
	
	$txtClientPromotion = $result[11];
	if (empty($txtClientPromotion)) $txtClientPromotion = 0;
	
	if ($txtSalesmanCode == "") {
		$txtSalesmanCode = $result[3];
		$txtSalesmanName = $result[4];
	}
	
	if ($Module_Project == 1 && $Client_ValidateProject == 1)
		$txtProjectCode = $result[6];
	if ($Module_CostCenter == 1 && $Client_ValidateProject == 1)
		$txtCostCentCode = $result[7];	
			
	if ($txtSorId == "") {
		if ($txtCurr != $result[9]) $txtCurr = $result[9];	
		if ($result[10] != '') $SetupDftWareHouse = $result[10];
	}
	
	$txtClientDetail = $result[5];
	
	$vClientDeliveryTransfer = $result[8];
	
	if ($Module_TransferSorder == 1 && $txtSorId == "" && $vClientDeliveryTransfer == 2)
		$txtSorType = 'ST';	
	
	if ($txtSorId == "") $vCltProjectCode = $result[6];
	else	$vCltProjectCode = $txtProjectCode;
	
	if ($Module_CreditLimitByProj == 1 && $vCltProjectCode != '') {
		$query = "SELECT ifNull(Client_CreditLimit,0) FROM ClientsCreditLimit WHERE Client_Code = '".$txtClientCode."' and '".$vCltProjectCode."' like concat(Project_Code,'%') limit 1 ";
		//echo "<br><br>".$query;
		$result = selectData($connection, $query);
		$txtCreditLimit = $result[0];
	}
	
			
	//Get Current Balance
	if ($Module_CreditLimitByProj == 1 && $vCltProjectCode != '') {
		$querybalance = " SELECT Round(IFNULL(SUM(if(journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1), (-1)*if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1))), 0)) As Balance FROM journaldt ".
						" Left outer Join CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
						" where journaldt.ledger_number = '".$txtClientCode."' ".
						" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".insertMySQLDate($txtDate)."','%Y%m%d') ".
						" and CstJour.Project_Code like concat('".$vCltProjectCode."', '%') ";
	} else {
		$querybalance = "SELECT IFNULL(SUM(if(journaldt_dbcd = 'D', journaldt_amount1, (-1)*journaldt_amount1)), 0) As Balance FROM journaldt where ledger_number = '".$txtClientCode."' and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".insertMySQLDate($txtDate)."','%Y%m%d')";
	}	
	//echo "<br><br>".$querybalance;
	$result = selectData($connection, $querybalance);
	$q1 = $result[0];
	if (is_numeric($q1)){
		//Do Nothing
	}else{
		$q1 = 0;
	}
	
	//$txtCurrentBalance = $txtCreditLimit - $q1;
	$txtCurrentBalance = $q1;

	$sub_query = "select InvoiceDays('".$txtClientCode."', '".insertMySQLDate(displayToday())."', 0)";
	//echo "<br><br>".$sub_query;
	$sub_result = selectData($connection, $sub_query);
	$txtLastInvoiceDay = $sub_result[0];
	//echo "<br><br>".$result[0];				
	
}

if ($txtSalesmanCode != "" ){
	$query = " SELECT Salesmen.Salesman_WarehouseCode ".
	         " FROM Salesmen ".
			 " WHERE Salesmen.Ledger_Number = '".$txtSalesmanCode."'";
	$result = selectData($connection, $query);
	if($result[0] != '') $SetupDftWareHouse = $result[0];
}

// Check If Vat Applied
$VatApplied = 0;
if ((insertDate($txtDate) > insertDate($Setup_VatStartDate) && $Setup_VatPercentage != 0) || ($Module_AdditionalTaxes == 1)) {		  
  $VatApplied = 1;
}		  

$AllowModifyVAT = '';
if ($ModifyVAT == 0) $AllowModifyVAT = ' disabled ';



$Parameters = array();
$Parameters['FI_SorderCanceledQty'] 			= $FI_SorderCanceledQty;
$Parameters['FI_SalesCheckSalesman'] 			= $FI_SalesCheckSalesman;
$Parameters['Login_AllowPrice'] 				= $Login_AllowPrice;
$Parameters['Login_NegativeQty'] 				= $Login_NegativeQty;
$Parameters['Login_ModifySellingPrice'] 		= $Login_ModifySellingPrice;
$Parameters['Login_ModifyDiscount'] 			= $Login_ModifyDiscount;
$Parameters['Allow_MinimumPrice'] 				= $Allow_MinimumPrice;
$Parameters['Module_Delivery'] 					= $Module_Delivery;
$Parameters['Module_NegativeSorder'] 			= $Module_NegativeSorder;
$Parameters['Module_Unit1Method'] 				= $Module_Unit1Method;
$Parameters['Module_SorderCheckQtyOnPost'] 		= $Module_SorderCheckQtyOnPost;
$Parameters['Module_Pack'] 						= $Module_Pack;
$Parameters['Module_DoubleUnit'] 				= $Module_DoubleUnit;
$Parameters['Module_ProjectDt'] 				= $Module_ProjectDt;
$Parameters['Module_CostCenterDt'] 				= $Module_CostCenterDt;
$Parameters['Module_RestrictProjCost'] 			= $Module_RestrictProjCost;
$Parameters['Module_RestrictCost'] 				= $Module_RestrictCost;
$Parameters['ShowCostCentLayout']			 	= $ShowCostCentLayout;
$Parameters['SalesTTC'] 						= $SalesTTC;
$Parameters['DecimalBase'] 						= $DecimalBase;
$Parameters['Setup_VatPercentage'] 				= $Setup_VatPercentage;
$Parameters['Module_AdditionalTaxes'] 			= $Module_AdditionalTaxes;
$Parameters['ExportTransportToJV'] 				= $ExportTransportToJV;
$Parameters['VatApplied'] 						= $VatApplied;
$Parameters['AllowModifyVAT'] 					= $AllowModifyVAT;

$Parameters['SetupDftWareHouse'] 				= $SetupDftWareHouse;
$Parameters['defaultwarehouse'] 			 	= $defaultwarehouse;


$Parameters['txtDate'] 		   					= $txtDate;
$Parameters['txtClientCode']   					= $txtClientCode;
$Parameters['txtClientDetail'] 					= $txtClientDetail;
$Parameters['txtCurrCode']     					= $txtCurr;
$Parameters['txtClientPromotion']   			= $txtClientPromotion;
$Parameters['Module_ShowWarehouseSalesorder']   = $Module_ShowWarehouseSalesorder;
$Parameters['sorder_export']   					= $sorder_export;
$Parameters['txtSorType']   					= $txtSorType;
$Parameters['SubItem_Production']   			= $SubItem_Production;
$Parameters['FI_DeliverySalesPrice']   			= $FI_DeliverySalesPrice;
$Parameters['sorderproduction']   				= $sorderproduction;


$_SESSION['gso_parameters']  = $Parameters;

echo"	  <td rowspan='7' valign='top'>";
if($FI_DeliverySalesPrice == 1){
	echo"	<div id='totals' style='width:240px; height:100px; margin-top:3px; float:right;'>";
		ShowSorderTotals($connection,$txtSorId,$_SESSION['gso_parameters'],$_SESSION['gso_arrayaccess']);
	echo"	</div>"; 
} else {
	echo "<input type='hidden' id='taxable'  name='txtSorTaxable' value='' >".
		 "<input type='hidden' id='nontaxable' name='txtSorNoneTaxable' value=''> ".
		 "<input type='hidden' id='grosstotal' name='txtSorGrossTotal' value=''> ".
		 "<input type='hidden' id='sordiscount' name='txtSorDiscount' value=''> ".
		 "<input type='hidden' id='sordiscountamt' name='txtSorDiscountAmt' value=''>".
		 "<input type='hidden' id='sortransportamt' name='txtSorTransportAmt' value=''>".
		 "<input type='hidden' id='sorvat' name='txtSorVat' value=''>".
		 "<input type='hidden' name='txtSorTotalTaxes' value=''>".
		 "<input type='hidden' id='nettotal' name='txtSorNetTotal' value=''>".
		 "<input type='hidden' name='txtSorVatChk' id='txtSorVatChk' value='' >".
		 "<input type='hidden' name='chkSorVat' id='chkSorVat' value='0'>";
}
echo"	  </td>
		</tr>";




echo"   <tr bgcolor='#F7F7F7'  height='30'>
		  <td align='left' ><span class='style1'>Client&nbsp;<span class='style16'>*</span></span></td>";
echo"     <td colspan='3' ><span class='style1'>";
echo"     <label>
           <input type='text'   name='txtClientCode' id='txtClientCode' value='$txtClientCode' style='width:95px;' maxlength='10' onBlur='SetMaturityDate();' onchange=\"CheckLookup('chkcodeexists','clients','ledger_number',this.value,'lstClientCodeH'); \" onkeydown='return kdClient(0,event);'    />
           <input type='text'   name='txtClientName' id='txtClientName' value='$txtClientName' style='width:270px;' onchange=\"CheckLookup('chkcodeexists','clients','ledger_name',this.value,'lstClientNameH');\" />
		   <label><img src='img/btnopen.jpg' title='Select Client' id='lstClientCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistClient(1); ' /></label>
		   <label><img src='img/btnopen.jpg' title='Select Client' id='lstClientNameH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistClientName(1);' style='display:none;' /></label>
		   <input type='hidden' name='txtClientVat' id='txtClientVat' value='$txtClientVat' />
          </label>
          </span>
          </td>";

echo"     <td align='left'><span class='style1'>Delivery Date&nbsp;<span class='style16'>*</span></span></td>
		  <td><input type='text' style='width:95px;' name='txtRequestDate' value='$txtRequestDate' maxlength='10'  >
		                   <A HREF=\"#\" onClick=\"displayCalendar(document.salesorder.txtRequestDate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><img src='./img/cal.gif' border=0 align=center></A></td>";

echo"   </tr>";



echo "  <input type='hidden' name='txtPaymentTerms' id='txtPaymentTerms' value='$txtPaymentTerms' />
		<input type='hidden' name='txtCurrentBalance' value='$txtCurrentBalance'>
		<input type='hidden' name='txtCreditLimit' value='$txtCreditLimit' />";


//Tarek 20111006
if($txtClientDetail == 1) {
	echo"<tr bgcolor='#F7F7F7'  height='30'>
		    <td align='left' ><span class='style1'>Detail&nbsp;<span class='style16'>*</span></span></td>";
	echo"   <td colspan='3' ><span class='style1'>";
	echo"      <input type='text'   name='txtClientDtCode' id='txtClientDtCode' value='$txtClientDtCode' style='width:95px;' maxlength='50' />
			   <input type='text'   name='txtClientDtName' id='txtClientDtName' value='$txtClientDtName' style='width:270px;'  />
			   <label><img src='img/btnopen.jpg' title=' Select Client Detail ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistClientDetail(1); ' /></label>
			  </span>
			</td>";

	echo"   <td align='left' colspan='2'>&nbsp;</td>";
	echo"</tr>";

} else {
	echo"<input type='hidden'   name='txtClientDtCode' id='txtClientDtCode' value='$txtClientDtCode'  />
		 <input type='hidden'   name='txtClientDtName' id='txtClientDtName' value='$txtClientDtName' />";
}

echo"   <tr bgcolor='#F7F7F7'  height='25'>
		  <td align='left' ><span class='style1'>Salesman&nbsp;<span class='style16'>*</span></span></td>";
echo"     <td colspan='3' ><span class='style1'>";
echo"     <label>
           <input type='text'   name='txtSalesmanCode' id='txtSalesmanCode' value='$txtSalesmanCode' style='width:95px;' maxlength='10' readonly />
           <input type='text'   name='txtSalesmanName' id='txtSalesmanName' value='$txtSalesmanName' style='width:270px;'  readonly />
          </label>
          </span>
          <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Salesman ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistSalesman(1); ' /> </span></label></td>";
if($FI_DeliverySalesPrice == 1){
echo"     <td align='left' ><span class='style1'>Currency&nbsp;<span class='style16'>*</span></span></td>";

echo"     <td ><span class='style1'><select name='txtCurr' id='txtCurr' style='width:60px;'>";
		  echo"<option></option>";
		  while($curf=mysql_fetch_row($resultcurrency)){
		  echo"<option ";
			if ($txtCurr==$curf[0])
				echo " selected ";
		    echo" value='$curf[0]'>$curf[0] </option>";
		  }
		  echo"</select></span></td>";	
} else  echo "<td></td><td><input type='hidden' name='txtCurr' id='txtCurr' value='$txtCurr'></td>";      
echo"   </tr>";


echo"   <tr bgcolor='#F7F7F7'  height='25'>
		  <td align='left' valign='center'><span class='style1'>Remark</span></td><td colspan='3' > <span class='style1'>
		  <textarea name='txtRemark' rows=2 cols=44 >".htmlspecialchars($txtRemark, ENT_QUOTES)."</textarea></span></td>";
		  
echo"     <td align='left' ><span class='style1'>Type&nbsp;<span class='style16'>*</span></span></td>";
echo"     <td ><span class='style1'><select name='txtSorType' id='txtSorType' style='width:120px;' ";
if($SubItem_Production == 1) echo " onchange=\"setType();\" ";
echo ">";
		  echo"<option></option>";
		  while($row=mysql_fetch_row($resultsordertype)){
		  echo"<option ";
			if ($txtSorType==$row[0])
				echo " selected ";
		    echo" value='$row[0]'>$row[0] - $row[1] </option>";
		  }
		  echo"</select></span></td>";	
		  
echo"   </tr>";		  

echo"   <tr bgcolor='#F7F7F7' height='25'>";
echo"		<td align='left' ><span class='style1'>Driver Name&nbsp;</span></td>";
echo"		<td align='left' > <span class='style1'><input type='text' name='txtDriverName' id='txtDriverName' value='".htmlspecialchars($txtDriverName, ENT_QUOTES)."' style='width:125px;' maxlength='30' /></span></td>";

if($Module_VehicleWeight==1) {
	echo"		<td align='left' ><span class='style1'>Vehical No&nbsp;</span></td>";
	echo"		<td align='left' > <span class='style1'><input type='text' name='txtVehicalNo' id='txtVehicalNo' value='".htmlspecialchars($txtVehicalNo, ENT_QUOTES)."' style='width:125px;' maxlength='30' /></span></td>";
	}
	else {
	echo"		<td align='left' ><span class='style1'></span></td>";
	echo"		<td align='left' > <span class='style1'><input type='hidden' name='txtVehicalNo' id='txtVehicalNo' value='".htmlspecialchars($txtVehicalNo, ENT_QUOTES)."' style='width:125px;' maxlength='30' /></span></td>";
	}
	
if($Module_VehicleWeight==1) {
	echo"		<td align='left' ><span class='style1'>Vehicle Weight&nbsp;</span></td>";
	echo"		<td align='left' > <span class='style1'><input type='text' name='txtVehicleWeight' id='txtVehicleWeight' value='$txtVehicleWeight' style='width:117px;' maxlength='30' /></span></td>";
	}
	else {
	echo"		<td align='left' ></td>";
	echo"		<td align='left' > <span class='style1'><input type='hidden' name='txtVehicleWeight' id='txtVehicleWeight' value='$txtVehicleWeight' style='width:117px;' maxlength='30' /></span></td>";		
	}
		
		
echo"   </tr>";

echo"   <tr bgcolor='#F7F7F7' height='25'>";

if ($Module_Project == 1) {
	echo" <td align='left' ><span class='style1'>Project&nbsp;<span class='style16'>*</span></span></td>
	      <td align='left' > <span class='style1'>
		    <input type='text' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' size='13' maxlength='20' onchange=\"CheckLookup('chkcodeexists','project','project_code',this.value,'lstProjectCodeH');\" /></span>
		    <label><span class='style1'><img src='img/btnopen.jpg' title='Select Project' id='lstProjectCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
} else {
	echo" <td align='left' colspan='2'><input type='hidden' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' /></td>";

}			

if ($Module_CostCenter == 1 && $ShowCostCentLayout == 1) {
	echo" <td align='left' ><span class='style1'>Costcenter&nbsp;<span class='style16'>*</span></span></td>		
		  <td align='left' ><span class='style1'>
		    <input type='text' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' style='width:126px;' maxlength='20' onchange=\"CheckLookup('chkcodeexists','costcent','costcent_code',this.value,'lstCostCentCodeH');\" /></span>
		    <label><span class='style1'><img src='img/btnopen.jpg' title='Select Costcenter' id='lstCostCentCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistCostcenter(1); ' /></span></label></td>";
} else {
	echo" <td align='left' colspan='2'><input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' /></td>";

}
	/* 
if($FI_DeliverySalesPrice == 1){	
echo" 	<td align='left' ><span class='style1'>Payment Mode</span></td>";
echo" 	<td align='left' ><span class='style1'>";
echo"		<input type='radio' name='txtPayMode' id='txtPayMode' value='0'"; if($txtPayMode=='0' || $txtPayMode=='') echo "checked />"; else echo " />"; echo " Credit";
echo"		<input type='radio' name='txtPayMode' id='txtPayMode' value='1'"; if($txtPayMode=='1') echo "checked />"; else echo " />"; echo " Cash";
echo"		<input type='radio' name='txtPayMode' id='txtPayMode' value='2'"; if($txtPayMode=='2') echo "checked />"; else echo " />"; echo " Check";
echo"	</span></td>";
} else  */
echo "<td></td><td><input type='hidden' name='txtPayMode' id='txtPayMode' value='0'></td>";

echo"   </tr>";

if ($Module_ShowBalance == 1) {

	echo"   <tr bgcolor='#F7F7F7'  height='45px'>
			  <td align='left' ><span class='style1'>Credit Limit</span></td>";
	echo "    <td align='left' ><font face='Verdana' size='2'><b>".addComma($txtCreditLimit)."</b></td> 
			  <td align='left' ><span class='style1'>Balance</span></td>
			  <td align='left' ><font face='Verdana' size='2'><b>".addComma($txtCurrentBalance)."</b></td> 
			  <td align='left' ><span class='style1'>Days Status</span></td>
			  <td align='left' ><font face='Verdana' size='2'><b>".($txtPaymentTerms - $txtLastInvoiceDay)."</b></td>";
	echo"   </tr>";
}

echo "<tr bgcolor='#F7F7F7' height='25'><td colspan='4'></td>";
if ($txtAssignedUser == '') $txtAssignedUser = $_SESSION['useraccount'];
if ($SO_AssignUsers == 1){
	echo "<td><span class='style1'>Assigned to </span></td>";
	echo "<td><input type='text' name='txtAssignedUser' id='txtAssignedUser' value='$txtAssignedUser' style='width:100px;' readonly>
		<label><span class='style1'><img src='img/btnopen.jpg' title=' Select User ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick=\"showlistUsers('2');\"  /></span></label></td>";
} else {
	echo "<td></td>";
	echo "<td><input type='hidden' name='txtAssignedUser' id='txtAssignedUser' value='$txtAssignedUser' readonly></td>";
}
echo "</tr>";
echo"   <tr bgcolor='#F7F7F7'>
		   <td align='left' valign='top' colspan='4'><span class='style1'>Terms & Conditions</span><br><textarea name='txtIAddress' rows='4' cols='55'>".htmlspecialchars($txtIAddress, ENT_QUOTES)."</textarea></td>
		   <td align='left' valign='top' colspan='3'><span class='style1'>Delivery Address</span><br><textarea name='txtDAddress' rows='4' cols='37'>".htmlspecialchars($txtDAddress, ENT_QUOTES)."</textarea>";
		   echo "<input type='hidden' name='sorder_date' value='".$sorder_date1."'>";
		   echo "<input type='hidden' name='sorder_card_msg' value='".$sorder_card_msg."'>";
		   echo "<input type='hidden' name='sorder_contact' value='".$sorder_contact."'>";
		   echo "<input type='hidden' name='sorder_contactphone' value='".$sorder_contactphone."'>";
		   echo "&nbsp;<img src='img/openlist.png' style='cursor: pointer' onclick='openAddressInfo(".$txtSorId.")'>";
		echo "</td></tr>";


/*
echo"   <tr><td colspan='7' valign='top'>";
echo"	<div style='overflow:scroll; height:180px; width:970px;' >";
echo"     <table border='0' style='table-layout:fixed'>
		  <col width=20>
		  <col width=20>";
		  
if ($Module_DoubleUnit == 1) {		  
	echo" <col width=120>
		  <col width=120>
		  <col width=200>
		  <col width=80>
		  <col width=60>
		  <col width=70>
		  <col width=60>
		  <col width=70>
		  <col width=90>
		  <col width=50>
		  <col width=100>";
		  
	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";	  
} else {
	echo" <col width=120>
		  <col width=120>
		  <col width=260>
		  <col width=80>
		  <col width=60>
		  <col width=70>
		  <col width=90>
		  <col width=50>
		  <col width=100>";
	
	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
}		  
		  
		  echo"<tr height='25'>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
          echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Item Code Packed</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Item Code</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Description</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Warehouse</span></td>";
		  
		  //if ($Module_DoubleUnit == 1)
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit1</span></td>";
			
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Qty</span></td>";
		  
		  if ($Module_DoubleUnit == 1) {
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit2</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit2 Qty</span></td>";
		  }
		  
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>$PriceLabel</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Disc(%)</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Total</span></td>";
		  
		  if ($Module_ProjectDt == 1)	
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Project</span></td>";
		  if ($Module_CostCenterDt == 1)
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>CostCenter</span></td>";
			
          echo"</tr>";
		  
		  if ($txtSorId != '' ) {
		      
			$TotalQty = 0;
			
			$querydt = " Select SorderDt.SorderDt_id, SorderDt.Item_CodePacked, SorderDt.Item_code, Item_Description, SorderDt.Warehouse_Code, ".
					   " SorderDt_Remark, SorderDt_Quantity, Round(SorderDt_Price, ".$DecimalBase."), SorderDt_PriceBase1, SroderDt_PriceBase2, ".
					   " Round(SorderDt_Discount, ".$DecimalBase."),  ".
					   " Round(((SorderDt_Quantity*SorderDt_Price)-((SorderDt_Quantity*SorderDt_Price*ifNull(SorderDt_Discount,0))/100)), ".$DecimalBase.") As Total, ".
					   " Round(SorderDt_PriceTTC, ".$DecimalBase."), ".
					   " Round(((SorderDt_Quantity*SorderDt_PriceTTC)-((SorderDt_Quantity*SorderDt_PriceTTC*ifNull(SorderDt_Discount,0))/100)), ".$DecimalBase.") As TotalTTC, ".
					   " SorderDt.Item_Unit2Qty, Item_UnitPurchaseDesc, Item_UnitSalesDesc, SorderDt.Project_code, SorderDt.CostCent_Code ".
					   " From Temp_SorderDt As SorderDt Left Join Items on SorderDt.Item_code = Items.Item_code ".
					   " Where SorderDt.Sorder_ID = ".$txtSorId.
					   //" And SorderDt.Logged_Code = '".$_SESSION['useraccount']."' ".
					   " Order By SorderDt.SorderDt_ID Desc ";
			//echo $querydt;
			$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){
			    
				$ct+=1;

				if($ct%2==0)
					$Color="style='background-color:".$grid_color1."'";
				else			
					$Color="style='background-color:".$grid_color2."'";	
						
				$sub_query  = " Select QtyExistsWSorder('".$rowsdt[2]."', '".$rowsdt[4]."', '".insertMySQLDate($txtDate)."', 0, 'SO', '', '') QtyExists From Dual ";
				//echo $sub_query;
				$sub_result = selectData($connection, $sub_query);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result[0];		
						
				$TextColor = 'style15';
				if ($vItemQtyExists < 0) {
					$Color="style='background-color:#FF0000;'";
					$TextColor = 'style16';
				}	
				
				echo "<tr ".$Color." >";
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_edit.png'  onMouseOver=\"style.cursor='hand'\" onclick=UpdateSorDt('".$rowsdt[0]."') title='Edit Record'  ></span></td>";
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/c_delete.png'  onMouseOver=\"style.cursor='hand'\" onclick=\"DeleteSorDt('".$rowsdt[0]."','".htmlentities($rowsdt[1])."','".htmlentities($rowsdt[2])."')\" title='Delete Record'  ></span></td>";
				echo "	<td align='left'><span class='".$TextColor."'>".$rowsdt[1]."</span></td>";
				echo "	<td align='left'><span class='".$TextColor."'>".$rowsdt[2]."</span></td>";
				echo "	<td align='left'><span class='".$TextColor."'>".$rowsdt[3]."</span></td>";
				echo "	<td align='left'><span class='".$TextColor."'>".$rowsdt[4]."</span></td>";
				
				//if ($Module_DoubleUnit == 1)
					echo "	<td align='left'><span class='".$TextColor."'>".$rowsdt[16]."</span></td>";
					
				echo "	<td align='right'><span class='".$TextColor."'>".$rowsdt[6]."</span></td>";
				
				if ($Module_DoubleUnit == 1) { 
					echo "	<td align='left'><span class='".$TextColor."'>".$rowsdt[15]."</span></td>";	
					echo "	<td align='right'><span class='".$TextColor."'>".$rowsdt[14]."</span></td>";	
				}
				
				if ($SalesTTC == 1) 
					echo "	<td align='right'><span class='".$TextColor."'>".number_format($rowsdt[12], $DecimalBase)."</span></td>";
				else
					echo "	<td align='right'><span class='".$TextColor."'>".number_format($rowsdt[7], $DecimalBase)."</span></td>";
					
				echo "	<td align='right'><span class='".$TextColor."'>".$rowsdt[10]."</span></td>";
				
				if ($SalesTTC == 1) 
					echo "	<td align='right'><span class='".$TextColor."'>".number_format($rowsdt[13], $DecimalBase)."</span></td>";
				else
					echo "	<td align='right'><span class='".$TextColor."'>".number_format($rowsdt[11], $DecimalBase)."</span></td>";
					
				if ($Module_ProjectDt == 1)	
					echo "	<td align='left'><span class='style15'>".$rowsdt[17]."</span></td>";
				if ($Module_CostCenterDt == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[18]."</span></td>";	
					
				echo "</tr>";
						
				if ($Module_DoubleUnit == 1) {		
					if (strtoupper($rowsdt[16]) == 'PCS') {
						$TotalQty 	 = $TotalQty 	+ $rowsdt[6];
					}
					else if (strtoupper($rowsdt[16]) == 'KG') {
						$TotalWeight = $TotalWeight + $rowsdt[6];
					}
					
					if (strtoupper($rowsdt[15]) == 'PCS') {
						$TotalQty 	 = $TotalQty 	+ $rowsdt[14];
					}
					else if (strtoupper($rowsdt[15]) == 'KG') {
						$TotalWeight = $TotalWeight + $rowsdt[14];
					}		
				} else {	
					$TotalQty = $TotalQty + $rowsdt[6];	
				}	
								
			}
			
			if ($Module_DoubleUnit == 1) {
				echo "<tr bgcolor='#D8D8D8' >";
				echo "	<td align='left' colspan='5'><span class='style1'>&nbsp;</span></td>";
				echo "	<td align='center' colspan='2'><span class='style1'>Total Qty</span></td>";
				echo "	<td align='right'><span class='style1'>".$TotalQty."</span></td>";
				echo "	<td align='left' colspan='2'><span class='style1'>Total Weight</span></td>";
				echo "	<td align='right'><span class='style1'>".$TotalWeight."</span></td>";
				echo "	<td align='left' colspan='4'><span class='style1'>&nbsp;</span></td>";
				echo "</tr>";	
			} else {
				echo "<tr bgcolor='#D8D8D8' >";
				echo "	<td align='left' colspan='6'><span class='style1'>&nbsp;</span></td>";
				echo "	<td align='center'><span class='style1'>Total</span></td>";
				echo "	<td align='right'><span class='style1'>".$TotalQty."</span></td>";
				echo "	<td align='left' colspan='5'><span class='style1'>&nbsp;</span></td>";
				echo "</tr>";	
			}
		 }
		
		echo "</table></div>";  

echo"   </td></tr>";*/
/*
echo"   <tr bgcolor='#D8D8D8' height='30'><td colspan='7' align='center'>";

if ($FI_SalesOrderIns == 1)
	echo"	<input type='button' id='btnAddItem' name='btnAddItem' value='Add Item'  onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $txtClientDetail, $FI_SalesCheckSalesman)' $style title='Add Item' >";

echo"       <input type='button' id='btnClear' name='btnClear' value='Clear Page'   onclick='ClearPage();' $style title='Clear Page'>";
				
if ($txtSorId != '')
	echo"   <input type='button' name='btnCancel' id='btnCancel' value='Cancel' onclick='CancelRecord();' $style title='Cancel Changes'>";
	
if ($txtSorId != '')
	echo"   <input type='button' name='btnPost' id='btnPost' value='Save' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $txtClientDetail, $FI_SalesCheckSalesman);' $style	title='Save Changes' />";

if ($txtSorId == '')
	echo"   <input name='btnSearch' type='button' id='btnSearch' value='Search' onclick='SearchForRef();' $style title='Search By Reference' />";

if ($txtSorId == '')
	echo"   <input name='btnPending' type='button' id='btnPending' value='Pending' onclick='SearchForPending();' $style title='Pending Preparation Order'  />";

if ($FA_LedgerAccess == 1 && $txtClientCode != '')
	echo"<input name='btnStatement' type='button' id='btnStatement' value='Client Statement' onclick=\"PrintStatement('".$base1."',$Module_ReferenceByProject);\" $style title='Print Client Statement' /> ";

echo"   </td></tr>";*/


echo"   <tr bgcolor='#ffffff'><td colspan='7' valign='top'>";
echo"	<div id='datagrid' class='grid' style='width:1090px;' >";

//Show Items Grid
ShowSorderDtGrid($connection,'SO',$txtSorId,$_SESSION['gso_parameters'],$_SESSION['gso_arrayaccess'],'SorderDt.SorderDt_ID');

echo"	  </div>"; 
echo"   </td></tr>"; 
	
echo"   </table></td></tr>"; 
 echo"   </table></td></tr><tr height='30'><td align='center' id='content-bottom' ></td></tr>";  
echo"   </table></td></tr>"; 

echo" </table>  ";//end of last table menu
	
if (($actionmode == "post" || $actionmode == "confirmorder") && $PrSorId != '') {

	$query    = " SELECT Sorder_Reference, Client_CashMode, ifNull(Sorder_Confirmed,0), Sorder_Type ".
			    " FROM Sorder Inner Join Clients on Sorder.Client_Code = Clients.Ledger_Number ".
                " WHERE Sorder_id = $PrSorId ";
	$result   = selectData($connection, $query);
	$PrSorRef = $result[0];
	$c_cashmode = $result[1];
	$SorConfirmed = $result[2];
	$SorType = $result[3];
		
	$AskComfirm = 0;
	
	echo '<script type="text/javascript" language="javascript">';
	
	if (($mainaction == "insert" || ($mainaction == "edit" && $SorConfirmed == 0)) && $actionmode == "post" && $FI_SalesOrderConfirm == 1 && $FI_SorderAskConfirm == 1 && $Module_SorderAutoConfirm == 0 && $SorType == 'SO') {
		echo ' ConfirmOrder(\''.$PrSorId.'\'); ';
		
		//echo ' confirmProduction(\''.$PrSorId.'\'); ';
		
	
		$AskComfirm = 1;
	}
	
	if	 ($actionmode == "confirmorder" || ($mainaction == "edit" && $AskComfirm == 0) || ($mainaction == "insert" && $Module_SorderAutoConfirm == 1)|| ($mainaction == "insert" && $FI_SalesOrderConfirm == 0) || ($mainaction == "insert" && $FI_SorderAskConfirm == 0) || $SorType != 'SO') {
	//if ($AskComfirm == 0) {
		if($sorderproduction == 1) echo ' confirmProduction(\''.$PrSorId.'\'); ';
		if ($Login_FastPrint == 1) {
			  if($directPrintSO == 1){
			      echo ' PrintSalesOrder(\''.$PrSorId.'\', \''.$PrSorRef.'\', \''.$SorType.'\'); ';
			  }
		}
		echo ' ClearPage1(); ';
	}
	
	echo '</script>';

}

print <<<HERE
</form>
</body>

HERE;

?>