<?php ob_start();  
$PageSecurity = 4;
include('includes/DefineSuppTransClass.php');
include('includes/DefinePOClass.php');
include('includes/function_lib.php');
include('includes/SQL_CommonFunctions.inc');
include('includes/session.inc');
$title = _('Purchase Requisition');
//print_r($_POST); die;
$identifier=$_GET['identifier'];
$Lastreq_id=$_GET['requisitionno'];
$supply_fromid=explode(',',$_SESSION['Mr_StkLocatio']);
$SupplyFrom=$supply_fromid[0];
 /* If a purchase order header doesn't exist, then go to */

  
    
if (!isset($_SESSION['MR'.$identifier])){

	header('Location:' . $rootpath . '/MR_Header.php?' . SID);

	exit;

} //end if (!isset($_SESSION['MR'.$identifier]))

function productQuantity($reqno,$pid){

	global $db;

         $reqisitionSql='SELECT req_quantity,id  FROM requisitionorderdetails

			WHERE requsitionno ="'.$_REQUEST['requisitionno'].'" and product_id="'.$pid.'" ';

		$reqres=DB_query($reqisitionSql, $db);

		$myrow = DB_fetch_row($reqres);

		//print_r($myrow);

		return $myrow;

}


include('includes/header.inc');
$todaydate = date($_SESSION['DefaultDateFormat']);


$Maximum_Number_Of_Parts_To_Show=50;


 echo '<a href="'. $rootpath . '/index.php?' . SID . "identifier=".$identifier.'">'. _('Purchases'). '</a>>>';
echo '<a href="'.$rootpath.'/MR_SelectOSMaterialRequi.php?' . SID . "identifier=".$identifier. '">' ._('Purchase Requisition') . '</a><br>';



//********To Remove Record from Requisition Summary************************************************
if(isset($_REQUEST['DeleteLineNumber'])){
  	if($_SESSION['MR'.$identifier]->Some_Already_Received($_REQUEST['DeleteLineNumber'])==0){
 		$_SESSION['MR'.$identifier]->LineItems[$_REQUEST['DeleteLineNumber']]->Deleted=True;
 	}  
}
//************************************************************************************************



// add new request here 08-09-26

if (isset($_POST['StockID2']) && $_GET['Edit']=='') {

/* If a stock item is selected and a purchdata record

 * exists for it then find that record.

 */

	$sql = "SELECT

			stockmaster.description,

			purchdata.suppliers_partno,

			stockmaster.pkg_type,

			stockmaster.units,

			stockmaster.netweight,		

			stockmaster.kgs,

			stockmaster.volume

			FROM purchdata INNER JOIN stockmaster

			ON purchdata.stockid=stockmaster.stockid

			WHERE purchdata.stockid='" . $_POST['StockID2'] . "' AND

			purchdata.supplierno='".$_SESSION['MR'.$identifier]->SupplierID."'";



	$ErrMsg = _('The stock record of the stock selected') . ': ' . $_POST['Stock'] . ' ' . 

		_('cannot be retrieved because');

	$DbgMsg = _('The SQL used to retrieve the supplier details and failed was');

	$result =DB_query($sql,$db,$ErrMsg,$DbgMsg);

	$myrow = DB_fetch_row($result);
	print_r($myrow);

	

	$_POST['ItemDescription'] = $myrow[0];

	$_POST['suppliers_partno'] = $myrow[1];

	$_POST['package'] = $myrow[2];

	$_POST['uom'] = $myrow[3];

	$_POST['nw'] = $myrow[4];

	$_POST['gw'] = $myrow[5];

	$_POST['cuft'] = $myrow[6];

} // end if (isset($_POST['StockID2']) && $_GET['Edit']=='')



if (isset($_POST['UpdateLines']) OR isset($_POST['Commit'])) {

	foreach ($_SESSION['MR'.$identifier]->LineItems as $POLine) {

		if ($POLine->Deleted==False) {

			$_SESSION['MR'.$identifier]->LineItems[$POLine->LineNo]->Quantity=$_POST['Qty'.$POLine->LineNo];

			$_SESSION['MR'.$identifier]->LineItems[$POLine->LineNo]->Price=$_POST['Price'.$POLine->LineNo];

			$_SESSION['MR'.$identifier]->LineItems[$POLine->LineNo]->nw=$_POST['nw'.$POLine->LineNo];

			$_SESSION['MR'.$identifier]->LineItems[$POLine->LineNo]->ReqDelDate=$_POST['ReqDelDate'.$POLine->LineNo];

		}

	}

}

if(isset($_POST['Commit'])){ /*User wishes to commit the order to the database */
//******************************Insert data into materialrequisiton table******************************************
		$data['comments'] = $_SESSION['Mr_Comments']; 
		$data['prdate'] = FormatDateForSQL($_SESSION['Mr_PRDate']); 
		$data['dateprinted'] = FormatDateForSQL($_SESSION['DatePrinted']); 
		$data['initiator'] =$_SESSION['Mr_Initiator']; 
		$data['intostocklocationcode'] = $_SESSION['Mr_intostocklocationcode']; 
		$data['intostocklocation'] =  $_SESSION['Mr_intostocklocation']; 
		$data['version'] =  $_SESSION['Mr_version']; 
		$data['revised'] = FormatDateForSQL($_SESSION['Mr_revised']); 
		$data['status'] = $_SESSION['Mr_Stat'] ; 
		$data['stat_comment'] = $_SESSION['Mr_StatComments'] ; 
		$data['sitecode'] =$_SESSION['MR_site_code']; 
		$data['requisition_site'] =$_SESSION['Mr_RequisitionLocationname']; 
		$data['pr_status'] = $_SESSION['PRStatus']; 
		$data['pr_type'] =$_SESSION['Mr_PRType']; 
		$data['requisition_nature'] = $_SESSION['Mr_RequisitionNature']; 
		$data['month_year'] = FormatDateForSQL($_SESSION['Mr_Month']); 
		$data['purchase_category'] =$_SESSION['Mr_PurchaseCategory'] ; 
		
		
	 	
		$data['Reqno'] = $_SESSION['Mr_strBothFinal'] ; 
 
 $getlastid=DB_query("select * from materialrequisitions where requisitionno ='".$_REQUEST['requisitionno']."'",$db);
 if(DB_num_rows( $getlastid)==0)
  {
  $data['requisitionno'] = $_REQUEST['requisitionno']; 
  $sql_materialrequisitions=	$s->insertRecord('materialrequisitions', $data);
  }else{
	   $data['requisitionno'] = $_REQUEST['requisitionno']; 
 		$condition="requisitionno='".$_REQUEST['requisitionno']."'";	
		$sql_materialrequisitions=$s->EditRecord('materialrequisitions', $data, $condition);
   }
  	    	$RecordModified = DB_query($sql_materialrequisitions,$db,$ErrMsg);
								
unset ($_SESSION['Mr_identifier']);	
unset ($_SESSION['Mr_PRDate']);	
unset ($_SESSION['Mr_version']);	
unset ($_SESSION['Mr_revised']);	
unset ($_SESSION['Mr_Initiator']);	
unset ($_SESSION['Mr_PRType']);	
unset ($_SESSION['Mr_intostocklocationcode']);	
unset ($_SESSION['Mr_intostocklocation']);	
unset ($_SESSION['Mr_RequisitionLocationname']);	
unset ($_SESSION['Mr_DatePrinted']);	
unset ($_SESSION['Mr_RequisitionNature']);	
unset ($_SESSION['Mr_Month']);	
unset ($_SESSION['Mr_PurchaseCategory']);	
unset ($_SESSION['Mr_StkLocatio']);	
unset ($_SESSION['Mr_Stat']);	
unset ($_SESSION['Mr_StatComments']);	
unset ($_SESSION['Mr_statcommentscomplete']);	
unset ($_SESSION['Mr_Comments']);	
 unset ($_SESSION['Mr_StatComments']);	
 			if (isset($_SESSION['Mr_RePrint']) and	$_SESSION['Mr_RePrint']==1){
				$_SESSION['MR'.$identifier]->AllowPrintPO=1;
				$sql = 'UPDATE purchorders
					SET purchorders.allowprint=1
					WHERE purchorders.orderno=' . $_SESSION['MR'.$identifier]->OrderNo;
				$ErrMsg = _('An error occurred updating the purchase order to allow reprints') . '. ' . _('The error says');
				$updateResult = DB_query($sql,$db,$ErrMsg);
			}
//**************************************************************************





	if ($InputError!=1){

		$emailsql='SELECT email FROM www_users WHERE userid="'.$_SESSION['MR'.$identifier]->Initiator.'"';

		$emailresult=DB_query($emailsql, $db);

		$emailrow=DB_fetch_array($emailresult);

		$sql = 'BEGIN';

		$result = DB_query($sql,$db);

            /* if(isset($_REQUEST['MRSD'])){
             $requgation_date = $_REQUEST['MRSD']; 
			  $exp = explode("/",$requgation_date);
			 $Requgationscheduldate = $exp[1]."/".$exp[0]."/".$exp[2];
			 }
			 else{
			 $requgation_date = '';
			 // $exp = explode("/",$requgation_date);
			 //$Requgationscheduldate = $exp[1]."/".$exp[0]."/".$exp[2];
			 }*/
		    
  		$requgation_date='';

		if ($_SESSION['ExistingOrder']==0 && $_GET['Edit']==''){ /*its a new order to be inserted */

		

			$date = date($_SESSION['DefaultDateFormat']);

			$StatusComment=$date.' - Order Created by <a href="mailto:'.$emailrow['email'].'">'.$_SESSION['MR'.$identifier]->Initiator.

				'</a> - '.$_SESSION['MR'.$identifier]->StatusMessage.'<br>';

			

			/*Get the order number */

             $_SESSION['MR'.$identifier]->OrderNo =  GetNextTransNo(18, $db);

				

		     /*Insert the purchase order detail records */
			 
			/* print_r($_SESSION['MR'.$identifier]->LineItems);
			 exit;*/
			 
            echo $Lastreq_id;
			foreach ($_SESSION['MR'.$identifier]->LineItems as $POLine) {

			if ($POLine->Deleted==False) {

				 $sql = "INSERT INTO requisitionorderdetails (
					        requsitionno, 
							product_id,
							product_description,
							make,
							color, 
							grade,
							req_quantity, 
							uom, 
							cellingrate, 
                            lastrate, 
							cashrate, 
							delivery_by, 
							totalreceivetilldate, 
							currentmonthstock, 
							materialreqsheduledate, 
							material_category, 
							supply_from,
							Remarks)
                   VALUES (" . $_GET['requisitionno'] . ",

							'" . $POLine->StockID . "',

							'" . $POLine->ItemDescription . "',

							'".$_POST['Make']."',

							'".$_POST['Color']."',

							'".$_POST['Grade']."',

							" . $POLine->Quantity . ",

							'".$_REQUEST['uom']."',

							'".$_REQUEST['CellingRate']."',

							'".$_REQUEST['LastRate']."',

							'".$_POST['CashRate']."',

							'".$_SESSION['UserID']."',

							'".$_POST['TRTD']."',

							'".$_POST['CMS']."',

							'". FormatDateForSQL($Requgationscheduldate) ."',

							'".$_POST['MaterialCategory']."',

							'".$SupplyFrom."',
							
							'".$_POST['remarks']."')";  //exit;
					$ErrMsg =_('One of the purchase order detail records could not be inserted into the database because');

					$DbgMsg =_('The SQL statement used to insert the purchase order detail record and failed was');

					//$result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
					
					$sql = "update purchorderdetails SET total_amount = '" . $_POST['total_amount']. "'	where orderno = '" . $_SESSION['MR'.$identifier]->OrderNo ."'";
												
					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);

				}

			} /* end of the loop round the detail line items on the order */

							//unset($_GET['requisitionno']);

				unset($POLine->StockID);

				unset($POLine->ItemDescription);

				unset($_POST['Make']);

				unset($_POST['Color']);

				unset($_POST['Grade']);

				unset($POLine->Quantity);

				unset($_REQUEST['uom']);

				unset($_REQUEST['CellingRate']);

				unset($_REQUEST['LastRate']);

				unset($_POST['CashRate']);

				unset($_POST['TRTD']);

				unset($_POST['CMS']);

				unset($Requgationscheduldate);

				unset($_POST['MaterialCategory']);

				unset($SupplyFrom);



			echo '<p>';

			prnMsg(_('Requisition No.') . ' ' . $_GET['requisitionno'] . _('has been created'),'success');

			echo '<p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/printer.png" title="' . 

				_('Print') . '" alt="">' . ' ' . _('Print Requisition Order') . '';

		} else { /*its an existing order need to update the old order info */

	//	 		$_SESSION['MR'.$identifier]->version += 0.01;

	

			$date = date($_SESSION['DefaultDateFormat']);

		     /*Update the purchase order header with any changes */

			 
			$sql1 = "SELECT Reqno FROM materialrequisitions WHERE requisitionno='".$_REQUEST['requisitionno']."'";
			$ReqResult = DB_query($sql1,$db);
			$result1 = DB_fetch_array($ReqResult);
			$Reqno = $result1['Reqno'];
			$Req_Site = $result1['requisition_site'];

          //echo "<pre>";  print_r($_SESSION);
		  
		$cnt = count($_SESSION['MR'.$identifier]->LineItems); 
		for($j=0;$j<$cnt;$j++)
		{
		// foreach ($_SESSION['MR'.$identifier]->LineItems as $POLine) {
        // $c=0;
			$sqlChk = "select id from requisitionorderdetails where product_id='".$_REQUEST['itemcode'][$j]."' and requsitionno='".$_GET['requisitionno']."' ";
			$ResultChk = DB_query($sqlChk,$db);
			$ReturnNumberCount = DB_num_rows($ResultChk);
			if(isset($_REQUEST['MRSD'][$j]))
		    $requgation_date = $_REQUEST['MRSD'][$j]; 
		     $exp = explode("/",$requgation_date);
			 $Requgationscheduldate = $exp[1]."/".$exp[0]."/".$exp[2];
			 
			if($ReturnNumberCount>0)
			 {
			 $sql = "UPDATE requisitionorderdetails SET

		     		product_id = '" . $_REQUEST['itemcode']. "' ,

					product_description='" . $_REQUEST['itemdesc']. "',

					make='" . $_POST['Make'] . "',

					color='" .$_POST['Color'] . "',

					grade= '" .$_POST['Grade'] . "',

					req_quantity= '" . $_REQUEST['Qty']. "',

					uom='" . $_REQUEST['uom'] . "',					

					cellingrate='" . $_REQUEST['CellingRate'] . "',

					lastrate= '" . $_REQUEST['LastRate'] . "',

					cashrate='" . $_POST['CashRate'] . "',

					delivery_by='" . $_SESSION['UserID'] . "',

					totalreceivetilldate='" . $_POST['TRTD'] . "',

					currentmonthstock='" . $_POST['CMS'] . "',

					materialreqsheduledate='" . $_REQUEST['MRSD'] . "',

					material_category='" . $_POST['MaterialCategory'] . "',

					supply_from='" . $SupplyFrom . "'

					WHERE requsitionno='".$_GET['requisitionno']."'

					AND product_id='".$_REQUEST['itemcode']."'";
					
			$ErrMsg =  _('The purchase order could not be updated because');

			$DbgMsg = _('The SQL statement used to update the purchase order header record, that failed was');

			$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);		
			}
			else
			{
        		$sql = " INSERT into  requisitionorderdetails SET
			       
		     		product_id = '" . $_REQUEST['itemcode'][$j]. "' ,
					
					requsitionno='" .$_GET['requisitionno']. "',
					
					product_description='" .$_REQUEST['itemdesc'][$j]. "',
					
					make='" .$_REQUEST['Make'][$j]. "',
					
					color='" .$_REQUEST['Color'][$j]. "',
					
					grade= '" .$_REQUEST['Grade'][$j]. "',
					
					req_quantity= '" .$_REQUEST['Qty'][$j]. "',
					
					uom='" .$_REQUEST['uom'][$j]. "',	
									
					cellingrate='" .$_REQUEST['CellingRate'][$j]. "',
					
					lastrate= '" .$_REQUEST['LastRate'][$j]. "',
					
					cashrate='" .$_REQUEST['CashRate'][$j]. "',
					
					delivery_by='" . $_SESSION['UserID']. "',
					
					totalreceivetilldate='" .$_REQUEST['TRTD'][$j]. "',
					
					currentmonthstock='" .$_REQUEST['CMS'][$j]. "',
					
					materialreqsheduledate='" . FormatDateForSQL($_REQUEST['MRSD'][$j]) . "',
					
					material_category='" .$_REQUEST['MaterialCategory'][$j]. "',
					
     				supply_from='" .$_REQUEST['SupplyFrom'][$j]. "',
					
					consumptiondays='" .$_REQUEST['consume'][$j]. "',
					
					Remarks='".$_REQUEST['remarks'][$j]."'";
				
				//print_r($sql);exit;	
				   $ErrMsg =  _('The purchase order could not be updated because');
				   $DbgMsg = _('The SQL statement used to update the purchase order header record, that failed was');
				   $result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);
			
			}
          //$c++;
		 } 
			 echo '<br><br>';

		     prnMsg(_('Requisition order') . ' ' . $Reqno . ' ' . _('has been Inserted'),'success');

		     if ($_SESSION['MR'.$identifier]->AllowPrintPO==1){

			 //    echo '<br><a target="_blank" href="'.$rootpath.'/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $_SESSION['MR'.$identifier]->OrderNo . '">' . _('Print Purchase Order') . '</a>';

		     }

		} /*end of if its a new order or an existing one */



		$sql = 'COMMIT';

		$Result = DB_query($sql,$db);

		

		/* Updating purchase orders taxes */

			$taxid = 1;

			foreach ($_SESSION['SuppTrans']->Taxes as $Tax) {	

				$chkSql = "select count(*) as `totCount` from purchordertax 

						   where orderno = '".$_SESSION['MR'.$identifier]->OrderNo."' and taxgroupid = ".$Tax->TaxAuthID;

				$chkresult =DB_query($chkSql,$db,$ErrMsg,$DbgMsg,true);		

				$chkrow=DB_fetch_array($chkresult);

				if($chkrow['totCount']>0){	

					$sql = "UPDATE purchordertax SET

							tax = '" . $_POST['TaxRate'.$taxid]. "' ,

							amount='" . $_POST['TaxAmount'.$taxid] . "',

							taxgroupid=" . $Tax->TaxAuthID . "

							WHERE orderno = '" . $_SESSION['MR'.$identifier]->OrderNo ."' and taxgroupid = ".$Tax->TaxAuthID;

				}else{

					$sql = "insert into purchordertax SET

							tax = '" . $_POST['TaxRate'.$taxid]. "' ,

							amount='" . $_POST['TaxAmount'.$taxid] . "',

							taxgroupid=" . $Tax->TaxAuthID . ",

							orderno = '" . $_SESSION['MR'.$identifier]->OrderNo ."'";

				}	

					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);

					

					$sql = "update purchorderdetails SET

							total_amount = '" . $_POST['total_amount']. "' 									

							where orderno = '" . $_SESSION['MR'.$identifier]->OrderNo ."'";					

					//echo $sql;die;				

					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);

				$taxid++;	

			}

		

		unset($_SESSION['MR'.$identifier]); /*Clear the PO data to allow a newy to be input*/

		echo "<br><a href='".$rootpath."/MR_SelectOSMaterialRequi.php?" . SID . "'>" . _('Return To Requisition List') . '</a>';

		include('includes/footer.inc');

		exit;

	} /*end if there were no input errors trapped */

} /* end of the code to do transfer the PO object to the database  - user hit the place PO*/

if (isset($_POST['Search']))
{  /*ie seach for stock items */
	//echo "manvi";
	if($_POST['Keywords'] AND $_POST['StockCode']) 
	{
		$msg=_('Stock description keywords have been used in preference to the Stock code extract entered');
	}
	if ($_POST['Keywords']) 
	{

		//insert wildcard characters in spaces
		$i=0;

		$SearchString = '%';

		while (strpos($_POST['Keywords'], ' ', $i)) 
		{

			$wrdlen=strpos($_POST['Keywords'],' ',$i) - $i;

			$SearchString=$SearchString . substr($_POST['Keywords'],$i,$wrdlen) . '%';

			$i=strpos($_POST['Keywords'],' ',$i) +1;

		}

		$SearchString = $SearchString. substr($_POST['Keywords'],$i).'%';



		if ($_POST['StockCat']=='All')
		{

			echo $sql = "select * from item_master INNER JOIN stockcategory

					ON item_master.SubCategoryID=stockcategory.categoryid

					WHERE stockmaster.mbflag!='D'
	
					AND stockmaster.mbflag!='A'

					AND stockmaster.mbflag!='K'

					and stockmaster.discontinued!=1

					AND stockmaster.description " . LIKE . " '$SearchString'

					ORDER BY stockmaster.stockid";

		} else {

			echo $sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units
	
					FROM stockmaster INNER JOIN stockcategory

					ON stockmaster.categoryid=stockcategory.categoryid

					WHERE stockmaster.mbflag!='D'

					AND stockmaster.mbflag!='A'

					AND stockmaster.mbflag!='K'

					and stockmaster.discontinued!=1

					AND stockmaster.description " . LIKE . " '$SearchString'

					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'

					ORDER BY stockmaster.stockid"; 
		}

	} 
	elseif ($_POST['StockCode'])
	{
		$_POST['StockCode'] = '%' . $_POST['StockCode'] . '%';
		
		if ($_POST['StockCat']=='All'){
		echo "1".$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

				FROM stockmaster INNER JOIN stockcategory

				ON stockmaster.categoryid=stockcategory.categoryid

				WHERE stockmaster.mbflag!='D'

				AND stockmaster.mbflag!='A'

				AND stockmaster.mbflag!='K'

				and stockmaster.discontinued!=1

				AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'

				ORDER BY stockmaster.stockid";

		} else {

			echo "2".$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

					FROM stockmaster INNER JOIN stockcategory

					ON stockmaster.categoryid=stockcategory.categoryid

					WHERE stockmaster.mbflag!='D'

					AND stockmaster.mbflag!='A'

					AND stockmaster.mbflag!='K'

					and stockmaster.discontinued!=1

					AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'

					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'

					ORDER BY stockmaster.stockid";
		}
	} 
	else 
	{
		if ($_POST['StockCat']=='All')
		{
		echo 	"3"; $sql = "SELECT *

					FROM item_master INNER JOIN stockcategory

					ON item_master.SubCategoryID=stockcategory.categoryid

					ORDER BY item_master.StockID";
		} 
		else 
		{
			echo "4";$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

					FROM stockmaster INNER JOIN stockcategory

					ON stockmaster.categoryid=stockcategory.categoryid

					WHERE stockmaster.mbflag!='D'

					AND stockmaster.mbflag!='A'

					AND stockmaster.mbflag!='K'

					and stockmaster.discontinued!=1

					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'

					ORDER BY stockmaster.stockid";
		}
	}
	
	$ErrMsg = _('There is a problem selecting the part records to display because');
	$DbgMsg = _('The SQL statement that failed was');
	echo "<br>".$sql; 

	$SearchResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);



	if (DB_num_rows($SearchResult)==0 && $debug==1){

		prnMsg( _('There are no products to display matching the criteria provided'),'warn');

	}

	if (DB_num_rows($SearchResult)==1){

		$myrow=DB_fetch_array($SearchResult);

		$_GET['NewItem'] = $myrow['stockid'];

		DB_data_seek($SearchResult,0);

	}
} //end of if search

else if(isset($_POST['EditSearch']))
{
	if ($_POST['Keywords'] AND $_POST['StockCode']) 
	{
		$msg=_('Stock description keywords have been used in preference to the Stock code extract entered');
	}
	if ($_POST['Keywords']) 
	{
		//insert wildcard characters in spaces
		$i=0;

		$SearchString = '%';

		while (strpos($_POST['Keywords'], ' ', $i)) {

			$wrdlen=strpos($_POST['Keywords'],' ',$i) - $i;

			$SearchString=$SearchString . substr($_POST['Keywords'],$i,$wrdlen) . '%';

			$i=strpos($_POST['Keywords'],' ',$i) +1;

		}

		$SearchString = $SearchString. substr($_POST['Keywords'],$i).'%';
		if ($_POST['StockCat']=='All'){

			$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

				FROM stockmaster INNER JOIN stockcategory

				ON stockmaster.categoryid=stockcategory.categoryid

				WHERE stockmaster.mbflag!='D'

				AND stockmaster.mbflag!='A'

				AND stockmaster.mbflag!='K'

				and stockmaster.discontinued!=1

				AND stockmaster.description " . LIKE . " '$SearchString'

				ORDER BY stockmaster.stockid";

		} else {

			$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

				FROM stockmaster INNER JOIN stockcategory

				ON stockmaster.categoryid=stockcategory.categoryid

				WHERE stockmaster.mbflag!='D'

				AND stockmaster.mbflag!='A'

				AND stockmaster.mbflag!='K'

				and stockmaster.discontinued!=1

				AND stockmaster.description " . LIKE . " '$SearchString'

				AND stockmaster.categoryid='" . $_POST['StockCat'] . "'

				ORDER BY stockmaster.stockid"; 
		}
	} 
	elseif ($_POST['StockCode'])
	{
		$_POST['StockCode'] = '%' . $_POST['StockCode'] . '%';
		if ($_POST['StockCat']=='All'){

			$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

				FROM stockmaster INNER JOIN stockcategory

				ON stockmaster.categoryid=stockcategory.categoryid

				WHERE stockmaster.mbflag!='D'

				AND stockmaster.mbflag!='A'

				AND stockmaster.mbflag!='K'

				and stockmaster.discontinued!=1

				AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'

				ORDER BY stockmaster.stockid";

		} else {

			$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

				FROM stockmaster INNER JOIN stockcategory

				ON stockmaster.categoryid=stockcategory.categoryid

				WHERE stockmaster.mbflag!='D'

				AND stockmaster.mbflag!='A'

				AND stockmaster.mbflag!='K'

				and stockmaster.discontinued!=1

				AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'

				AND stockmaster.categoryid='" . $_POST['StockCat'] . "'

				ORDER BY stockmaster.stockid";
		}

	} 
	else 
	{

		if ($_POST['StockCat']=='All'){

			$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

				FROM stockmaster INNER JOIN stockcategory

				ON stockmaster.categoryid=stockcategory.categoryid

				WHERE stockmaster.mbflag!='D'

				AND stockmaster.mbflag!='A'

				AND stockmaster.mbflag!='K'

				and stockmaster.discontinued!=1

				ORDER BY stockmaster.stockid";


		} else {

		 	$sql = "SELECT stockmaster.stockid,

					stockmaster.description,

					stockmaster.units

				FROM stockmaster INNER JOIN stockcategory

				ON stockmaster.categoryid=stockcategory.categoryid

				WHERE stockmaster.mbflag!='D'

				AND stockmaster.mbflag!='A'

				AND stockmaster.mbflag!='K'

				and stockmaster.discontinued!=1

				AND stockmaster.categoryid='" . $_POST['StockCat'] . "'

				ORDER BY stockmaster.stockid";
		}
	}

	$ErrMsg = _('There is a problem selecting the part records to display because');

	$DbgMsg = _('The SQL statement that failed was');

	//echo $sql; die;

	$SearchResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);

	if (DB_num_rows($SearchResult)==0 && $debug==1){

		prnMsg( _('There are no products to display matching the criteria provided'),'warn');

	}
	if (DB_num_rows($SearchResult)==1){

		$myrow=DB_fetch_array($SearchResult);

		$_GET['NewItem'] = $myrow['StockID'];

		DB_data_seek($SearchResult,0);
	}
}
/* Always do the stuff below if not looking for a supplierid */

if(isset($_GET['Delete'])){
 	if($_SESSION['MR'.$identifier]->Some_Already_Received($_POST['LineNo'])==0){

		$_SESSION['MR'.$identifier]->LineItems[$_GET['Delete']]->Deleted=True;

		 include ('includes/PO_UnsetFormVbls.php');

	} else {

		prnMsg( _('This item cannot be deleted because some of it has already been received'),'warn');

	}
}

if (isset($_POST['LookupPrice']) and isset($_POST['StockID2'])){

	$sql = "SELECT purchdata.price,

			purchdata.conversionfactor,

			purchdata.supplierdescription

		FROM purchdata

		WHERE  purchdata.supplierno = '" . $_SESSION['MR'.$identifier]->SupplierID . "'

		AND purchdata.stockid = '". strtoupper($_POST['StockID2']) . "'";

	$ErrMsg = _('The supplier pricing details for') . ' ' . strtoupper($_POST['StockID']) . ' ' . _('could not be retrieved because');

	$DbgMsg = _('The SQL used to retrieve the pricing details but failed was');

	$LookupResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);

	if (DB_num_rows($LookupResult)==1){

		$myrow = DB_fetch_array($LookupResult);

		$_POST['Price'] = $myrow['price']/$myrow['conversionfactor'];

	} else {

		prnMsg(_('Sorry') . ' ... ' . _('there is no purchasing data set up for this supplier') . '  - ' . $_SESSION['MR'.$identifier]->SupplierID . ' ' . _('and item') . ' ' . strtoupper($_POST['StockID']),'warn');

	}

}
if (isset($_POST['UpdateLine'])){

	$AllowUpdate=true; /*Start assuming the best ... now look for the worst*/



	if ($_POST['Qty']==0 OR $_POST['Price'] < 0){

		$AllowUpdate = false;

		prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('You are attempting to set the quantity ordered to zero, or the price is set to an amount less than 0'),'error');

	}



	if ($_SESSION['MR'.$identifier]->LineItems[$_POST['LineNo']]->QtyInv > $_POST['Qty'] OR $_SESSION['MR'.$identifier]->LineItems[$_POST['LineNo']]->QtyReceived > $_POST['Qty']){

		$AllowUpdate = false;

		prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('You are attempting to make the quantity ordered a quantity less than has already been invoiced or received this is of course prohibited') . '. ' . _('The quantity received can only be modified by entering a negative receipt and the quantity invoiced can only be reduced by entering a credit note against this item'),'error');

	}



	if ($_SESSION['MR'.$identifier]->GLLink==1) {

	/*Check for existance of GL Code selected */

		$sql = 'SELECT accountname 

				FROM chartmaster 

				WHERE accountcode =' .  $_SESSION['MR'.$identifier]->LineItems[$_POST['LineNo']]->GLCode;

		$ErrMsg = _('The account name for') . ' ' . $_POST['GLCode'] . ' ' . _('could not be retrieved because');

		$DbgMsg = _('The SQL used to retrieve the account details but failed was');

		$GLActResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);

		if (DB_error_no($db)!=0 OR DB_num_rows($GLActResult)==0){

			$AllowUpdate = false;

			prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('The GL account code selected does not exist in the database see the listing of GL Account Codes to ensure a valid account is selected'),'error');

		} else {

			$GLActRow = DB_fetch_row($GLActResult);

			$GLAccountName = $GLActRow[0];

		}

	}
	include ('PO_Chk_ShiptRef_JobRef.php');



	if (!isset($_POST['JobRef'])) {

		$_POST['JobRef']='';

	}



	if ($AllowUpdate == true) {



		$_SESSION['MR'.$identifier]->update_order_item(

					$_POST['LineNo'],

					$_POST['Qty'],

					$_POST['Price'],

					$_POST['ItemDescription'],

					$_POST['GLCode'],

					$GLAccountName,

					$_POST['ReqDelDate'],

					$_POST['ShiptRef'],

					$_POST['JobRef'],

					$_POST['itemno'],

					$_SESSION['MR'.$identifier]->LineItems[$_POST['LineNo']]->uom,

					$_POST['suppliers_partno'],

					$_POST['Qty']*$_POST['Price'],

					$_POST['package'],

					$_POST['pcunit'],

					$_POST['nw'],

					$_POST['gw'],

					$_POST['cuft'],

					$_POST['Qty'],

					$_POST['Qty']*$_POST['Price']
					);
		include ('includes/PO_UnsetFormVbls.php');
	}

}



if (isset($_POST['EnterLine'])){ /*Inputs from the form directly without selecting a stock item from the search */



	$AllowUpdate = true; /*always assume the best */



	if (!is_numeric($_POST['Qty'])){

		$AllowUpdate = false;

		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The quantity of the order item must be numeric'),'error');

	}

	if ($_POST['Qty']<0){

		$AllowUpdate = false;

		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The quantity of the ordered item entered must be a positive amount'),'error');

	}

	if (!is_numeric($_POST['Price'])){

		$AllowUpdate = false;

		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The price entered must be numeric'),'error');

	}

	if (!is_date($_POST['ReqDelDate'])){

// mark on 081013

		$AllowUpdate = False;

		prnMsg( _('Cannot Enter this order line') . '</b><br>' . _('The date entered must be in the format') . ' ' . $_SESSION['DefaultDateFormat'], 'error');

	}


 /*Then its not a stock item */



		/*need to check GL Code is valid if GLLink is active */

		if ($_SESSION['MR'.$identifier]->GLLink==1){



			$sql = 'SELECT accountname 

					FROM chartmaster 

					WHERE accountcode =' . (int) $_POST['GLCode'];

			$ErrMsg =  _('The account details for') . ' ' . $_POST['GLCode'] . ' ' . _('could not be retrieved because');

			$DbgMsg =  _('The SQL used to retrieve the details of the account, but failed was');

			$GLValidResult = DB_query($sql,$db,$ErrMsg,$DbgMsg,false,false);

			if (DB_error_no($db) !=0) {

				$AllowUpdate = false;

				prnMsg( _('The validation process for the GL Code entered could not be executed because') . ' ' . DB_error_msg($db), 'error');

				if ($debug==1){

					prnMsg (_('The SQL used to validate the code entered was') . ' ' . $sql,'error');

				}

				include('includes/footer.inc');

				exit;

			}

			if (DB_num_rows($GLValidResult) == 0) { /*The GLCode entered does not exist */

				$AllowUpdate = false;

				prnMsg( _('Cannot enter this order line') . ':<br>' . _('The general ledger code') . ' - ' . $_POST['GLCode'] . ' ' . _('is not a general ledger code that is defined in the chart of accounts') . ' . ' . _('Please use a code that is already defined') . '. ' . _('See the Chart list from the link below'),'error');

			} else {

				$myrow = DB_fetch_row($GLValidResult);

				$GLAccountName = $myrow[0];

			}

		} /* dont bother checking the GL Code if there is no GL code to check ie not linked to GL */

		else {

			$_POST['GLCode']=0;

		}

		if (strlen($_POST['ItemDescription'])<=3){

			$AllowUpdate = false;

			prnMsg(_('Cannot enter this order line') . ':<br>' . _('The description of the item being purchase is required where a non-stock item is being ordered'),'warn');

		}



		if ($AllowUpdate == true){



			$_SESSION['MR'.$identifier]->add_to_order ($_SESSION['MR'.$identifier]->LinesOnOrder+1,

						'',

						0, /*Serialised */

						0, /*Controlled */

						$_POST['Qty'],

						$_POST['ItemDescription'],

						$_POST['Price'],

						_('each'),

						$_POST['GLCode'],

						$_POST['ReqDelDate'],

						$_POST['ShiptRef'],

						$_POST['JobRef'],

						0,

						0,

						$GLAccountName,

						2,

						$_POST['itemno'],						

						$_POST['uom'],

						$_POST['suppliers_partno'],

						$_POST['subtotal_amount'],

						$_POST['package'],

						$_POST['pcunit'],

						$_POST['nw'],

						$_POST['gw'],

						$_POST['cuft'],

						$_POST['total_quantity'],

						$_POST['total_amount']
						
						);

						

		   include ('includes/PO_UnsetFormVbls.php');

		}

	}

 /*end if Enter line button was hit */





if (isset($_POST['NewItem'])){ /* NewItem is set from the part selection list as the part code selected */

/* take the form entries and enter the data from the form into the PurchOrder class variable */

/*echo $abc =$_POST['itemedit'];
*/
	foreach ($_POST as $key => $value) {
			  

		if (substr($key, 0, 3)=='qty') {

			$ItemCode=substr($key, 3, strlen($key)-3);

			$Quantity=$value;

			$AlreadyOnThisOrder =0;

            		 

			if ($_SESSION['PO_AllowSameItemMultipleTimes'] ==false){

		

				if (count($_SESSION['MR'.$identifier]->LineItems)!=0){



					foreach ($_SESSION['MR'.$identifier]->LineItems AS $OrderItem) {



					/* do a loop round the items on the order to see that the item

					is not already on this order */

						if (($OrderItem->StockID == $ItemCode) and ($OrderItem->Deleted==false)) {

							$AlreadyOnThisOrder = 1;

							prnMsg( _('The item') . ' ' . $ItemCode . ' ' . _('is already on this order') . '. ' . _('The system will not allow the same item on the order more than once') . '. ' . _('However you can change the quantity ordered of the existing line if necessary'),'error');

						}

					} /* end of the foreach loop to look for preexisting items of the same code */

				}

			}

			if ($AlreadyOnThisOrder!=1 and $Quantity>0){
				 echo $purchdatasql='SELECT COUNT(supplierno)

								FROM purchdata

								WHERE purchdata.supplierno = "' . $_SESSION['MR'.$identifier]->SupplierID . '"

								AND purchdata.stockid="'. $ItemCode . '"';

				$purchdataresult=DB_query($purchdatasql, $db);

				$myrow=DB_fetch_row($purchdataresult);

				

				if ($myrow[0]>0) { 
					$sql = "SELECT stockmaster.description,

						stockmaster.stockid,

						stockmaster.units,

						stockmaster.decimalplaces,

						stockmaster.kgs,

						stockmaster.netweight,

						stockcategory.stockact,

						chartmaster.accountname,

						purchdata.price,

						purchdata.conversionfactor,				

						purchdata.supplierdescription,

						purchdata.suppliersuom,

						purchdata.suppliers_partno,

						purchdata.leadtime

					FROM stockcategory,

						chartmaster,

						stockmaster LEFT JOIN purchdata

					ON stockmaster.stockid = purchdata.stockid

					AND purchdata.supplierno = '" . $_SESSION['MR'.$identifier]->SupplierID . "'

					WHERE chartmaster.accountcode = stockcategory.stockact

						AND stockcategory.categoryid = stockmaster.categoryid

						AND stockmaster.stockid = '". $ItemCode . "'

						AND purchdata.effectivefrom = 

							(SELECT max(effectivefrom) 

								FROM purchdata 

								WHERE purchdata.stockid='". $ItemCode . "'

								AND purchdata.supplierno='" . $_SESSION['MR'.$identifier]->SupplierID . "')";

				} else {
				echo "manvi"; $sql='SELECT item_master.item_name,

						item_master.StockID,

						item_master.unit,
						
						stockcategory.stockact,

						chartmaster.accountname

					FROM stockcategory,

						chartmaster,

						stockmaster

					WHERE chartmaster.accountcode = stockcategory.stockact

						AND stockcategory.categoryid = item_master.StockID

						AND item_master.StockID = "'. $ItemCode . '"';
				}

				$ErrMsg = _('The supplier pricing details for') . ' ' . $ItemCode . ' ' . _('could not be retrieved because');

				$DbgMsg = _('The SQL used to retrieve the pricing details but failed was');

				$result1 = DB_query($sql,$db,$ErrMsg,$DbgMsg);

				
				if ($myrow = DB_fetch_array($result1)){	

						if (is_numeric($myrow['price'])){

						$_SESSION['MR'.$identifier]->add_to_order ($_SESSION['MR'.$identifier]->LinesOnOrder+1,

							$ItemCode,

							0, /*Serialised */

							0, /*Controlled */

							$Quantity, /* Qty */

							$myrow['item_name'],

							$myrow['price'],

							$myrow['unit'],

							$myrow['stockact'],

							$_SESSION['MR'.$identifier]->deliverydate,

							0,

							0,

							0,

							0,

							0,

							$myrow['accountname'],

							$myrow['decimalplaces'],

							$ItemCode,

							$myrow['suppliersuom'],

							$myrow['suppliers_partno'],

							$Quantity*$myrow['price'],

							$myrow['leadtime'],

							'',

							$myrow['netweight'],

							$myrow['kgs'],

							'',

							$Quantity,

							$Quantity*$myrow['price']							

							);

					} else { /*There was no supplier purchasing data for the item selected so enter a purchase order line with zero price */



							

						$_SESSION['MR'.$identifier]->add_to_order ($_SESSION['MR'.$identifier]->LinesOnOrder+1,

							$ItemCode,

							0, /*Serialised */

							0, /*Controlled */

							$Quantity, /* Qty */

							$myrow['item_name'],

							0,

							$myrow['unit'],

							$myrow['stockact'],

							$_SESSION['MR'.$identifier]->deliverydate,

							0,

							0,

							0,

							0,

							0,

							$myrow['accountname'],

							0,

							$ItemCode,

							'',

							'',

							0,

							0,

							'',

							0,

							0,

							0,

							0,

							0

							);

					}

			/*Make sure the line is also available for editing by default without additional clicks */

//					$_GET['Edit'] = $_SESSION['MR'.$identifier]->LinesOnOrder; /* this is a bit confusing but it was incremented by the add_to_order function */

				} else {

					prnMsg (_('The item code') . ' ' . $ItemCode . ' ' . _('does not exist in the database and therefore cannot be added to the order'),'error');

					if ($debug==1){

						echo "<br>".$sql;

					}

					include('includes/footer.inc');

					exit;

				}

			} /* end of if not already on the order */

		}

		header('Location:'.$rootpath.'/MR_Items.php?identifier='.$_REQUEST['identifier'].'&Edit=1&requisitionno='.$_REQUEST['requisitionno']);

	}

} /* end of if its a new item */

else if(isset($_POST['EditItm']))

{

    $sql="UPDATE requisitionorderdetails SET requsitionno = '".$_GET['requisitionno']."',product_id = '$POLine->StockID', product_description = '$POLine->ItemDescription', req_quantity='$DisplayQuantity', uom='$uom', delivery_by ='".$_SESSION['UserID']."' where id='".$_POST['itemedit']."'";

	 $ErrMsg = _('Requisition Order Details is not Created');

	 $DbgMsg = _('The SQL statement used to insert the requisition order detail record that failed was');

	 $result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);	

}
/* This is where the order as selected should be displayed  reflecting any deletions or insertions*/

if(!isset($_GET['Edit']))
{
   echo "<form name=form1 action='" . $_SERVER['PHP_SELF'] . "?" . SID . "&identifier=".$identifier. "&requisitionno=".$Lastreq_id. "' method=post>";
}

else
{
   	echo "<form name=formedit action='" . $_SERVER['PHP_SELF'] . "?" . SID . "identifier=".$identifier. "&Edit=1&requisitionno=".$Lastreq_id. "' method=post>";
}
//echo  _('Purchase Order') . ': <font color=BLUE size=4><b>' . $_SESSION['MR'.$identifier]->OrderNo . ' ' . $_SESSION['MR'.$identifier]->SupplierName . ' </b></font> - ' . _('All amounts stated in') . ' ' . $_SESSION['MR'.$identifier]->CurrCode . '<br>';
/*need to set up entry for item description where not a stock item and GL Codes */
if(count($_SESSION['MR'.$identifier]->LineItems)>0)
{
	echo '<p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/supplier.png" title="' . 
		_('Purchase Order') . '" alt="">';
	
	if (isset($_SESSION['MR'.$identifier]->OrderNo)) 
	{
		echo  ' ' . _('Purchase Requisition Order') .' '. $_GET['requisitionno'] ;
	}
	echo '<br><b>'._(' Requisition Summary') . '</b>';
print_r($_SESSION['MR'.$identifier]);
	echo '<table cellpadding=2 border=0>';

	echo "<tr>

		<th><strong>" . _('Item Code') . "</strong></th>

		<th><strong>" . _('Description') . "</strong></th>

		<th><strong>" . _('Make') . "</strong></th>

		<th><strong>" . _('Color') . "</strong></th>

		<th><strong>" . _('Grade') . "</strong></th>

		<th><strong>" . _('UOM') ."</strong></th>	

		<th><strong>" . _('Selling Rate') . "</strong></th>

		<th><strong>" . _('Last Purchase Rate') . "</strong></th>

        <th><strong>" . _('Cash Rate') . "</strong></th>

		<th><strong>" . _('Total Received Till Date') . "</strong></th>

		<th><strong>" . _('Current Month Stock') . "</strong></th>

		<th><strong>" . _('Schedule Date of Requisition') . "</strong></th>

		<th><strong>" . _('Category of Material') . "</strong></th>

		<th><strong>" . _('Requisition Quantity') . "</strong></th>

		<th><strong>" . _('Supply From') . "</strong></th>

		<th><strong>" . _('Site Purchase Quantity') . "</strong></th>

		<th><strong>" . _('Approximate Value of Material') . "</strong></th>

		<th><strong>" . _('Consumption Days') . "</strong></th>

		<th><strong>" . _('Remarks/<br>Specifications') . "</strong></th>
		
		<th><strong>" . _('Action') . "</strong></th>
		
		</tr>";

	$_SESSION['MR'.$identifier]->total = 0;
	$k = 0;  //row colour counter
	$count= count($_SESSION['MR'.$identifier]->LineItems); 
	echo "<input type='hidden' name='cntcc' id='cntcc' value='".$count."'>";
   	$cnt = count($_SESSION['MR'.$identifier]->LineItems); 
	//print_r($_SESSION['MR'.$identifier]->LineItems);
	$i=0;
	foreach($_SESSION['MR'.$identifier]->LineItems as $POLine)
	{
     

		if ($POLine->Deleted==False) {

			$LineTotal = $POLine->Quantity * $POLine->Price;

			// Note decimal places should not fixed at 2, use POLine->DecimalPlaces instead

			//              $DisplayLineTotal = number_format($LineTotal,2);

			$DisplayLineTotal = number_format($LineTotal,2);

			// Note if the price is greater than 1 use 2 decimal place, if the price is a fraction of 1, use 4 decimal places

			// This should help display where item-price is a fraction

			if ($POLine->Price > 1) {

				$DisplayPrice = number_format($POLine->Price,2,'.','');

			} else {

				$DisplayPrice = number_format($POLine->Price,2,'.','');

			}

			$DisplayQuantity = number_format($POLine->Quantity,$POLine->DecimalPlaces,'.','');



			if ($k==1){

				echo '<tr class="EvenTableRows">';

				$k=0;

			} else {

				echo '<tr class="OddTableRows">';

				$k=1;

			}

			 $uomsql='SELECT conversionfactor, suppliersuom FROM purchdata  WHERE supplierno="'.$_SESSION['MR'.$identifier]->SupplierID.'"	AND stockid="'.$POLine->StockID.'"';

			$uomresult=DB_query($uomsql, $db);

			if (DB_num_rows($uomresult)>0) {

				$uomrow=DB_fetch_array($uomresult);

				if (strlen($uomrow['suppliersuom'])>0) {

					$uom=$uomrow['suppliersuom'];

				} else {

					$uom=$POLine->Units;

				}

			} 

			else {

				 $uom=$POLine->Units;

			}			
			////Requisition Item Table DISPLAY////
		
			{
				//$i=0;
			echo "<td>".$POLine->StockID."<input type='hidden' name='itemcode[".$i."]' id='itemcode[".$i."]' value='".$POLine->StockID."'><input type='hidden' ></td>

		<td>".$POLine->ItemDescription."<input type='hidden' name='itemdesc[".$i."]' id='itemdesc[".$i."]' value='".$POLine->ItemDescription."'><input type='hidden' ></td>";
			
			  echo"<td>";
			  $sql='SELECT distinct(manufacture) FROM item_specification WHERE proc_id='."'".$POLine->StockID."'";
				$result=DB_query($sql,$db);
				$myrow=DB_fetch_array($result); 
				 
				$make_sql = "select * from product_manufacture where id='".$myrow['manufacture']."'";
				$make_result = DB_query($make_sql,$db);
				$make_row = DB_fetch_array($make_result);
				
				
				 echo '<input type="hidden" name="Make['.$i.']" value="'.$myrow['manufacture'].'">'.$make_row['manufacturer'].'
				 <input type="hidden">
				 ';
				
			echo "</td>";
			echo"<td>";
			
			$sql='SELECT distinct(color) FROM item_specification WHERE proc_id='."'".$POLine->StockID."'";
				$result=DB_query($sql,$db);
				$myrow=DB_fetch_array($result);
				
				$color_sql = "select * from product_color where id='".$myrow['color']."'";
				$color_result = DB_query($color_sql,$db);
				$make_row = DB_fetch_array($color_result);
				
				echo '<input type="hidden" name="Color['.$i.']" value="'.$myrow['color'].'">'.$make_row['color'].'
				<input type="hidden" >
				';
				
			echo "</td>";
		
				echo "<td>";
				$sql='SELECT distinct(grade) FROM item_specification WHERE proc_id='."'".$POLine->StockID."'";
				$result=DB_query($sql,$db);
				$myrow=DB_fetch_array($result);
				
				$grade_sql = "select * from product_grade where id='".$myrow['grade']."'";
				$grade_result = DB_query($grade_sql,$db);
				$make_row = DB_fetch_array($grade_result);
				
				
				echo '<input type="hidden" name="Grade['.$i.']" value="'.$myrow['grade'].'">'.$make_row['grade'].'
				<input type="hidden" >';
				
			echo "</td>
				<td>$uom<input type=hidden name=uom[".$i."] value=".$uom.">
				<input type=hidden ></td>";
			    $current_date = date("Y-m-d");  
				$Current_year=date('Y');
				$Current_Month =date('m');
				$Current_day = "1";
				$Start_date = $Current_year."-".$Current_Month."-".$Current_day;
           		$sql='SELECT actualcost, lastcost FROM stockmaster WHERE stockid='."'".$POLine->StockID."'";
				$result=DB_query($sql,$db);
				$myrow=DB_fetch_array($result);
				$FindTotalrec_sql = "SELECT Sum(PassedQty) FROM qualityposting Where ItemCode='".$POLine->StockID."'";
				$Find_Total_result=DB_query($FindTotalrec_sql,$db);
				$Total_TillDate_Quantity = DB_fetch_array($Find_Total_result);
				$Totalreceivequantity = $Total_TillDate_Quantity['Sum(PassedQty)'];
				$count_sql="SELECT Sum(Rate), itemcode,(select count(itemcode) from purchorderdetails) as cnt FROM purchorderdetails Where itemcode='".$POLine->StockID."' group by itemcode ";
				$Count_PurchaseQty_result=DB_query($count_sql,$db);
				$Find_Count_result= DB_fetch_array($Count_PurchaseQty_result);
				$countNumberofitencomming = $Find_Count_result['cnt'];
				$countNumberofrate = $Find_Count_result['Sum(Rate)'];
				if(isset($countNumberofitencomming))
				$actual_Rate = $countNumberofrate/$countNumberofitencomming;
				$totalprice1 = $Totalreceivequantity*$actual_Rate;
				$totalprice = round($totalprice1, 2);
				$Find_PurchaseQty_sql = "SELECT Sum(PassedQty) FROM qualityposting Where ItemCode='".$POLine->StockID."' AND site_puraches='".$_SESSION[UserStockLocation]."'";
				$Find_PurchaseQty_result=DB_query($Find_PurchaseQty_sql,$db);
				$Total_Find_PurchaseQty_result_Quantity = DB_fetch_array($Find_PurchaseQty_result);
				$TotalPurchaseQty = $Total_Find_PurchaseQty_result_Quantity['Sum(PassedQty)'];
				$Find_Current_Stock_sql = "SELECT Sum(PassedQty) FROM qualityposting Where ItemCode='".$POLine->StockID."' AND site_puraches='".$_SESSION[UserStockLocation]."' AND date between '$Start_date' AND '$current_date'";
				$Find_Current_Stock_result=DB_query($Find_Current_Stock_sql,$db);
				$Total_Find_current_Stock_result = DB_fetch_array($Find_Current_Stock_result);
				$Total_Current_Month_Qty = $Total_Find_current_Stock_result['Sum(PassedQty)'];
				
				$cashRate_sql = "select purchorders.orderno, 
								 purchorders.orddate,
								 purchorders.payment_terms,
								 purchorderdetails.orderno,
								 purchorderdetails.itemcode,
								 purchorderdetails.Rate
								 from purchorders INNER Join purchorderdetails 
								 On purchorderdetails.orderno = purchorders.orderno 
								 Where payment_terms='CA' And itemcode='".$POLine->StockID."' ORDER By orddate DESC";
								$CA_result=DB_query($cashRate_sql,$db);
								$CA_Rate = DB_fetch_array($CA_result);
								$current_rate  =$CA_Rate['Rate'];
				       
			echo "<td>".$myrow['actualcost']."<input type='hidden' name='CellingRate[".$i."]' value='".$myrow['actualcost']."'>
			<input type='hidden' ></td>";

			echo "<td>".$myrow['lastcost']."<input type='hidden' name='LastRate[".$i."]' value='".$myrow['lastcost']."'>
			<input type='hidden' ></td>";

			echo "<td>".$current_rate."<input type='hidden' name='CashRate[".$i."]' size='6' value='".$current_rate."'>
			<input type='hidden'></td>";

			echo "<td>".$Totalreceivequantity."<input type='hidden' name='TRTD[".$i."]' size='6' value='".$Totalreceivequantity."' >                  <input type='hidden' ></td>";

			echo "<td>".$Total_Current_Month_Qty."<input type='hidden' name='CMS[".$i."]' size='6' value='".$Total_Current_Month_Qty."' ><input type='hidden' ></td>";

			echo "<td><input type='text' name='MRSD[".$i."]' size='10' class='datepicker' value='$todaydate'></td>";
		
			
			echo "<td><select name='MaterialCategory[".$i."]'>

               <option selected value='NonDebitable'>"."NonDebitable"."</option>
			   
			     <option value='Debitable'>"."Debitable"."</option></select></td>";

		echo "<td>".$DisplayQuantity."<input type=hidden class=number name=Qty[".$i."] size=6 value=".$DisplayQuantity." >
		<input type=hidden ></td>";
			    $sql="SELECT materialrequisitions.intostocklocationcode, materialrequisitions.intostocklocation FROM materialrequisitions WHERE requisitionno='".$_GET['requisitionno']."'";
				 $result=DB_query($sql,$db);
				 $myrow=DB_fetch_array($result);
                  $myrow['intostocklocationcode'];
				  $myrow['intostocklocation'];
				 $sitename = $myrow['intostocklocation'];
			      if($myrow['intostocklocationcode']== "H001"){
					  $SuppFrom=$myrow['intostocklocation'];
					  }
				   else{$SuppFrom="Local";
				   }	 
			
     echo  '<td>'.$SupplyFrom.'<input type="hidden"  name="SupplyFrom['.$i.']" size="11" value="'.$SupplyFrom.'">
	 <input type="hidden"  ></td>';
	  
			echo '<td>'.$TotalPurchaseQty.'<input type="hidden" class=number name="SPQ['.$i.']" size=6 value='.$TotalPurchaseQty.'>
			<input type="hidden" ></td>';
			
			echo '<td>'.$totalprice.'<input type="hidden" class=number name="price['.$i.']" size=10 value='.$totalprice.'>
			<input type="hidden" ></td>';

			echo '<td><input type=text class=number name="consume['.$i.']" size="10" value="" id="consume_'.$i.'" onblur="consumption('.$i.')">
				</td>';
			
			echo '<td><input type="text" name="remarks['.$i.']" size="10" value="" id="remarks_'.$i.'">
				</td>';

			echo "<td><a href='" . $_SERVER['PHP_SELF'] . "?" . SID . "identifier=".$identifier."&requisitionno=".$_GET['requisitionno']. "&DeleteLineNumber=" . $POLine->LineNo . "'>" . _('Delete') . "</a></td></tr>";

			$_SESSION['MR'.$identifier]->total = $_SESSION['MR'.$identifier]->total + $LineTotal;
			
			//$i++;
			}
		} 
		
	////////////////////////////// Select Product Id And Requsition No /////////////////////////////////////////////

  
		if($_POST['itemedit'] == '')

		{
			/*$sql_matrial = "Select * from requisitionorderdetails WHERE requsitionno='".$_GET['requisitionno']."' AND product_id='".$POLine->StockID."'";

			$ErrMsg = _('Requisition number is already exist And Prodfuct Id all ');

			$DbgMsg = _('The SQL statement used to Select the requisition order detail record that failed was');

			$result_matrial =DB_query($sql_matrial,$db,$ErrMsg,$DbgMsg);

			$matrialeq = DB_fetch_array($result_matrial);*/

			 if($_GET['requisitionno'] <= 0)
			 {	
			 echo  $sql="INSERT INTO requisitionorderdetails(requsitionno,

										product_id,

										product_description,

										make,

										color,

										grade,

										uom,

										cellingrate,

										lastrate,

										cashrate,

										weight,

										totalreceivetilldate,

										currentmonthstock,

										materialreqsheduledate,

										material_category,

										req_quantity,

										delivery_by,

										supply_from,
										Remarks) VALUES ('".$_GET['requisitionno']."',

										'".$POLine->StockID."',	

										'".$POLine->ItemDescription."',

										'".$_POST['Make']."',

										'".$_POST['Color']."',

										'".$_POST['Grade']."',

										'".$uom."',

										'".$DisplayQuantity."',

										'1',

										'2',

										'3',

										'0',

										'4',

										'5',

										'6',

										'7',

										'8',
                                        '".$_SESSION['UserID']."',
										'".$_POST['remarks']."')"; 

		 $ErrMsg = _('Requisition Order Details not Created');

		 $DbgMsg = _('The SQL statement used to insert the requisition order detail record that failed was');

		 //$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);									

		}
		 else

		 {
		   $ErrMsg = _('Product Already Exists');
		 }
		}
     else

		 {
			$sql="UPDATE requisitionorderdetails SET requsitionno = '".$_GET['requisitionno']."',

			product_id = '$POLine->StockID', 

			product_description = '$POLine->ItemDescription', 

			req_quantity='$DisplayQuantity', 

			uom='$uom', 

			delivery_by ='".$_SESSION['UserID']."' 

			where id='".$_POST['itemedit']."'";

		 $ErrMsg = _('Requisition Order Details is not Updateed');

		 $DbgMsg = _('The SQL statement used to insert the requisition order detail record that failed was');

		 $result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);	

		}
$i++;
	}
 
	echo '<tr>

			<td colspan=7 align="right">  

			 <table border=0 align="right">';

	 $_SESSION['SuppTrans'] = new SuppTrans;

	$TaxTotal=0; //initialise tax total

	$DisplayTotal = $_SESSION['MR'.$identifier]->total;

	 $sql = "SELECT suppliers.vendor_name, paymentterms.terms, paymentterms.daysbeforedue,
paymentterms.dayinfollowingmonth,  suppliers.tax_group, taxgroups.taxgroupdescription 
FROM suppliers, taxgroups, currencies, paymentterms, taxauthorities 
WHERE suppliers.tax_group=taxgroups.taxgroupid  AND suppliers.payterms=paymentterms.termsindicator 
AND suppliers.vendor_code =  '" .$_SESSION['MR'.$identifier]->SupplierID . "'";
/* ////////////// if currency code to be added in table suppliers (22/09/11)//////////////////////
 select * from currenciessuppliers.currcode, AND suppliers.currcode=currencies.currabrev*/
//echo $sql;

	 $ErrMsg = _('The supplier record selected') . ': ' . $_SESSION['SupplierID'] . ' ' . _('cannot be retrieved because');

	 $DbgMsg = _('The SQL used to retrieve the supplier details and failed was');

	 $result = DB_query($sql, $db, $ErrMsg, $DbgMsg);



	 $myrow = DB_fetch_array($result);

	 

	 $_SESSION['SuppTrans']->SupplierName = $myrow['vendor_name'];

	 $_SESSION['SuppTrans']->TermsDescription = $myrow['terms'];

	 //$_SESSION['SuppTrans']->CurrCode = $myrow['currcode'];

	 //$_SESSION['SuppTrans']->ExRate = $myrow['exrate'];

	$_SESSION['SuppTrans']->TaxGroup = $myrow['tax_group'];

	$_SESSION['SuppTrans']->TaxGroupDescription = $myrow['taxgroupdescription'];

	

	$LocalTaxProvinceResult = DB_query("SELECT taxprovinceid FROM locations WHERE loccode = '" . $_SESSION['UserStockLocation'] . "'", $db);


	$LocalTaxProvinceRow = DB_fetch_row($LocalTaxProvinceResult);

	$_SESSION['SuppTrans']->LocalTaxProvince = $LocalTaxProvinceRow[0];

	

	foreach ($_SESSION['SuppTrans']->Taxes as $Tax) {

		

		echo '<tr><td>'  . $Tax->TaxAuthDescription . '</td><td>';

		

		/*Set the tax rate to what was entered */

		if (isset($_POST['TaxRate'  . $Tax->TaxCalculationOrder])){

			$_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxRate = $_POST['TaxRate'  . $Tax->TaxCalculationOrder]/100;

		}

		

		$chkSql = "select * from purchordertax where orderno = '".$_SESSION['MR'.$identifier]->OrderNo."' and taxgroupid = ".$Tax->TaxAuthID;

		//echo $chkSql;		   

		$chkresult =DB_query($chkSql,$db,$ErrMsg,$DbgMsg,true);		

		$chkrow=DB_fetch_array($chkresult);

		if (DB_num_rows($chkresult)>0) {			

			$taxRate = $chkrow['tax'];

			$taxAmt = $chkrow['amount'];



			//echo $taxAmt;

			//print_r($_SESSION['SuppTrans']);

			if(!empty($_POST['TaxRate'.$Tax->TaxCalculationOrder])){

				$taxRate = $_POST['TaxRate'.$Tax->TaxCalculationOrder];				

			}

			/*if($_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxOvAmount){

				$taxAmt = $_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxOvAmount;

			}*/

			

		}else{

			$taxRate = $_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxRate * 100;

			$taxAmt = round($_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxOvAmount,2);

		}

				

		

		/*If a tax rate is entered that is not the same as it was previously then recalculate automatically the tax amounts */

		//if (isset($_POST['TaxRate'  . $Tax->TaxCalculationOrder])){

			if (!isset($_POST['OverRideTax']) or $_POST['OverRideTax']=='Auto'){

			

				echo  ' <input type=TEXT class="number" name=TaxRate' . $Tax->TaxCalculationOrder . ' maxlength=4 size=4 VALUE=' . $taxRate . '>%';

				

				/*Now recaluclate the tax depending on the method */

				if ($Tax->TaxOnTax ==1){

					

					$_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxOvAmount = $_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxRate * ($DisplayTotal + $TaxTotal);

				

				} else { /*Calculate tax without the tax on tax */



					$_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxOvAmount = $_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxRate * $DisplayTotal;
				}

				if(isset($_POST['TaxAmount'  . $Tax->TaxCalculationOrder])){

					$taxAmt = $_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxOvAmount;

				}

				

				echo '<input type=hidden name="TaxAmount'  . $Tax->TaxCalculationOrder . '"  VALUE=' . $taxAmt . '>';

				

				echo '</td><td align=right>' . $taxAmt;					

			} else { /*Tax being entered manually accept the taxamount entered as is*/



				$_SESSION['SuppTrans']->Taxes[$Tax->TaxCalculationOrder]->TaxOvAmount = $_POST['TaxAmount'  . $Tax->TaxCalculationOrder];

				

				echo  ' <input type=hidden name=TaxRate' . $Tax->TaxCalculationOrder . ' VALUE=' . $taxRate . '>';

	

				echo '</td><td><input type=TEXT class="number" size=12 maxlength=12 name="TaxAmount'  . $Tax->TaxCalculationOrder . '"  VALUE=' . $taxAmt . '>';

			}

			

			$TaxTotal += $taxAmt;

		

		echo '</td></tr>';	

	}

	//}


	$DisplayNewTotal = number_format(( $DisplayTotal + $TaxTotal), 2);

	$_SESSION['SuppTrans']->OvAmount = round($_SESSION['SuppTrans']->OvAmount,2);			

	echo '</table>

			</td>
		 </tr></table>';

	echo '<br><div class="centre"><input type="submit" name="UpdateLines" value="Update Requisition Lines">';

	echo '<br><input type="submit" name="Commit" value="Process Requisition" onclick="return checkvalid()">';
} /*Only display the order line items if there are any !! */

if (isset($_POST['NonStockOrder'])) {

	echo '<br><table><tr><td>'._('Description of Item').'</td>';

	echo '<td><input type=text name=ItemDescription size=40></td></tr>';

	echo '<tr><td>'._('General Ledger Code').'</td>';

	echo '<td><select name="GLCode">';

	$sql='SELECT 

			accountcode, 

			accountname 

		  FROM chartmaster 

		  ORDER BY accountcode ASC';

	$result=DB_query($sql, $db);

	while ($myrow=DB_fetch_array($result)) {

		echo '<option value="'.$myrow['accountcode'].'">'.$myrow['accountcode'].' - '.$myrow['accountname'].'</option>';

	}

	echo '</td></tr>';

	echo '<tr><td>'._('Quantity to purchase').'</td>';

	echo '<td><input type=text class=number name=Qty size=10></td></tr>';

	echo '<tr><td>'._('Price per item').'</td>';

	echo '<td><input type=text class=number name=Price size=10></td></tr>';

	echo '<tr><td>'._('Delivery Date').'</td>';

	echo '<td><input type=text class=date alt="'.$_SESSION['DefaultDateFormat'].'" name=ReqDelDate size=11

			value="'.$_SESSION['MR'.$identifier]->deliverydate .'"></td></tr>';

	echo '</table>';

	echo '<input type=submit name="EnterLine" value="Enter Item">';

}



echo '<hr>';



/* Now show the stock item selection search stuff below */



if (!isset($_GET['Edit'])) {

	$sql="SELECT categoryid,

			categorydescription

		FROM stockcategory

		WHERE stocktype<>'L'

		AND stocktype<>'D'

		ORDER BY categorydescription";

		

	$ErrMsg = _('The supplier category details could not be retrieved because');

	$DbgMsg = _('The SQL used to retrieve the category details but failed was');

	$result1 = DB_query($sql,$db,$ErrMsg,$DbgMsg);



	echo '<table><tr><p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/magnifier.png" title="' . 

		_('Print') . '" alt="">' . ' ' . _('Search For Stock Items') . '';



	echo ":</font></tr><tr><td><select name='StockCat'>";



	echo "<option selected value='All'>" . _('All');

	while ($myrow1 = DB_fetch_array($result1)) {

		if (isset($_POST['StockCat']) and $_POST['StockCat']==$myrow1['categoryid']){

			echo "<option selected value=". $myrow1['categoryid'] . '>' . $myrow1['categorydescription'];

		} else {

			echo "<option value=". $myrow1['categoryid'] . '>' . $myrow1['categorydescription'];

		}

	}

	if (!isset($_POST['Keywords'])) {

		$_POST['Keywords']='';

	}

	if (!isset($_POST['StockCode'])) {

		$_POST['StockCode']='';
	}

	unset($_POST['Keywords']);

	unset($_POST['StockCode']);

	echo '</select></td>

		<td><font size=2>' . _('Enter text extracts in the description') . ":</font></td>

		<td><input type='text' name='Keywords' size=20 maxlength=25 value='" . $_POST['Keywords'] . "'></td></tr>

		<tr><td></td>

		<td><font size=3><b>" . _('OR') . ' </b></font><font size=2>' . _('Enter extract of the Stock Code') . 

			":</font></td>

		<td><input type='text' name='StockCode' size=15 maxlength=18 value='" . $_POST['StockCode'] . "'></td>

		</tr>

		<tr><td></td>

		</tr>

		</table><br>

		<div class='centre'><input type=submit name='Search' value='" . _('Search Now') . "'>
		</div><br>";


	$PartsDisplayed =0;

}

else if (isset($_GET['Edit']))
 {
	$sql="SELECT categoryid,

			categorydescription

		FROM stockcategory

		WHERE stocktype<>'L'

		AND stocktype<>'D'

		ORDER BY categorydescription";

		

	$ErrMsg = _('The supplier category details could not be retrieved because');

	$DbgMsg = _('The SQL used to retrieve the category details but failed was');

	$result1 = DB_query($sql,$db,$ErrMsg,$DbgMsg);



	echo '<table><tr><p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/magnifier.png" title="' . 

		_('Print') . '" alt="">' . ' ' . _('Search For Stock Items') . '';



	echo ":</font></tr><tr><td><select name='StockCat'>";



	echo "<option selected value='All'>" . _('All');

	while ($myrow1 = DB_fetch_array($result1)) {

		if (isset($_POST['StockCat']) and $_POST['StockCat']==$myrow1['categoryid']){

			echo "<option selected value=". $myrow1['categoryid'] . '>' . $myrow1['categorydescription'];

		} else {

			echo "<option value=". $myrow1['categoryid'] . '>' . $myrow1['categorydescription'];

		}

	}

	if (!isset($_POST['Keywords'])) {

		$_POST['Keywords']='';

	}

	if (!isset($_POST['StockCode'])) {

		$_POST['StockCode']='';

	}
	unset($_POST['Keywords']);

	unset($_POST['StockCode']);



	echo '</select></td>

		<td><font size=2>' . _('Enter text extracts in the description') . ":</font></td>

		<td><input type='text' name='Keywords' size=20 maxlength=25 value='" . $_POST['Keywords'] . "'></td></tr>

		<tr><td></td>

		<td><font size=3><b>" . _('OR') . ' </b></font><font size=2>' . _('Enter extract of the Stock Code') . 

			":</font></td>

		<td><input type='text' name='StockCode' size=15 maxlength=18 value='" . $_POST['StockCode'] . "'></td>

		</tr>
		</table><br>

		<div class='centre'><input type=submit name='EditSearch' value='" . _('Search Now') . "'>

		<input type=submit name='NonStockOrder' value='" . _('Requisition a non stock item') . "'>

		</div><br>";

	$PartsDisplayed =0;

 }
if (isset($SearchResult)) {

print_r($_SESSION['MR'.$identifier]->SupplierID);

	echo "<table cellpadding=1 colspan=7 border=1>";
	$tableheader = "<tr>

			<th>" . _('Code')  . "</th>

			<th>" . _('Description') . "</th>

			<th>" . _('Units') . "</th>

			<th><a href='#end'>"._('Go to end of list')."</a></th>

			</tr>";

	echo $tableheader;
	$j = 1;
	$k=0; //row colour counter
	while ($myrow=DB_fetch_array($SearchResult)) {
		if ($k==1){

			echo '<tr class="EvenTableRows">';

			$k=0;

		} else {

			echo '<tr class="OddTableRows">';

			$k=1;

		}



		$filename = $myrow['stockid'] . '.jpg';

		if (file_exists( $_SESSION['part_pics_dir'] . '/' . $filename) ) {



			$ImageSource = '<img src="'.$rootpath . '/' . $_SESSION['part_pics_dir'] . '/' . $myrow['stockid'] . 

				'.jpg" width="50" height="50">';



		} else {

			$ImageSource = '<i>'._('No Image').'</i>';

		}



			$uomsql='SELECT conversionfactor, suppliersuom

					FROM purchdata

					WHERE supplierno="'.$_SESSION['MR'.$identifier]->SupplierID.'"

					AND stockid="'.$myrow['stockid'].'"';



			$uomresult=DB_query($uomsql, $db);

			if (DB_num_rows($uomresult)>0) {

				$uomrow=DB_fetch_array($uomresult);

				if (strlen($uomrow['suppliersuom'])>0) {

					$uom=$uomrow['suppliersuom'];

				} else {

					$uom=$myrow['units'];

				}

			} else {

				$uom=$myrow['units'];

			}

		

			$prdrecaray = 	productQuantity($_REQUEST['requisitionno'],$myrow['stockid']);

			
			printf("<td>%s</td>

			<td>%s</td>

			<td>%s</td>

			<td>%s</td>

			<td><input class='number' type='text' size=6 value='".$prdrecaray[0]."' name='qty%s'>

			<input type='text' name='itemedit'  value='". $prdrecaray[1]."'  id='itemedit' /></td>

			</tr>",

			$myrow['StockID'],

			$myrow['item_name'],

			$uom,

			$ImageSource,

			$myrow['stockid']);

		      

		$PartsDisplayed++;

		if ($PartsDisplayed == $Maximum_Number_Of_Parts_To_Show){

			break;

		}

#end of page full new headings if

	}

#end of while loop

	echo '</table>';

	if ($PartsDisplayed == $Maximum_Number_Of_Parts_To_Show){



	/*$Maximum_Number_Of_Parts_To_Show defined in config.php */



		prnMsg( _('Only the first') . ' ' . $Maximum_Number_Of_Parts_To_Show . ' ' . _('can be displayed') . '. ' . 

			_('Please restrict your search to only the parts required'),'info');

	}

		echo '<a name="end"></a><br>';

		

		echo '<div class="centre"><input type="submit" name="NewItem" value="Order Items">

		

	</div>';

	

}#end if SearchResults to show
echo '<hr>';
echo '</form>';
include('includes/footer.inc');
?>
<link rel="stylesheet" href="css/jquery.ui.all.css">
<script src="js/jquery-1.5.1.js"> </script>
<script src="ui/jquery.ui.core.js"> </script>
<script src="ui/jquery.ui.widget.js"></script>



<script>
function consumption(str)
{
	var con = document.getElementById("consume_"+str).value;
	if(con == '')
	{
		alert("Please Enter Consumption Days!");
	}
}
function checkvalid()
{
	var count=document.getElementById("cntcc").value;
	for(var i=0; i<=count; i++)
	{
		var con=document.getElementById("consume_"+i).value;
		//alert(con);
		if(con == '')
		{
			alert("Please Enter The Number Of Consumtion Days!");
			return false;
		}
	}
}
$(function() {
		  $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' ,changeMonth: true,
					changeYear: true,
					yearRange: '-80:+20'});
		  });
</script>
