<?php

session_start();
if($_SESSION['dbName']==""){
header("location:../index.php");
}


include("config.inc.php");
include("Functions_Purchase.php");
include("Forms_DataGrid_Items.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");


$querylog="SELECT ifnull(FI_ItemAuction,0) as loginaccess, ifNull(Login_FastPrint,0) As Login_FastPrint 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");

	
	
//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2 from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


$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);

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>

<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">



<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_G1','ModRec_G1','imgSubmit_1');
			selRecordColor(this,'SelectedRec_G1','SelectedRecColor_G1');
		});
		
		//Set Scroll Positions on Page Load
		scrollToPage();
		
		$(window).scroll(function(){
			scrollPage();
		});
		
		//Set Cursor Position After Page Reload
		var NextElement = readCookie('prdtpl-nextcell');
		MoveNextRecord(NextElement);
		eraseCookie('prdtpl-nextcell');
		
		
	});
	
	
</script>

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

function PostChanges() {
	x = document.itemauction;
	var txtAuctionId  = x.txtAuctionId.value;
		
	if (confirm ( "Are you sure you want to Save current Auction?"))
			{
				//Save Grid Before Posting	
				var vModRec_G1  = document.getElementById('ModRec_G1').value;
								
				if (vModRec_G1 != "") {
					var Obj = document.getElementById('CurRec_G1'+vModRec_G1);
					Obj.style.backgroundColor='#F13A3A';
					alert("Please Submit changes before.");
					
				}
				
				else {
				
					if (document.getElementById('btnPost'))
						x.btnPost.disabled = true;
					if (document.getElementById('btnClear'))
						x.btnClear.disabled = true;
								
						
					x.action="Form_ItemAuction_Action.php?mode=post&mainmode=&txtAuctionId="+txtAuctionId;
					x.submit();
				}	
			}
	
	
}

	
function ClearPage(str){
    x = document.itemauction;
		
			
		x.txtAuctionId.value='';
		x.txtRef.value='';
		x.txtDate.value='';
		x.txtStartTime.value='';
		x.txtEndDate.value='';
		x.txtEndTime.value='';
		x.item_code.value='';
		x.item_desc.value='';
		x.txtQty.value='';
		x.auction_remark.value='';
		
		if(str == '0') x.message.value='';
		x.txtPrdCountFG.value='';
		
	x.action='Form_ItemAuction.php';
	x.submit();	
	
}

function AddItem() {
	var x = document.itemauction;
	var vMainMode;
	
	if(x.txtAuctionId.value == '') vMainMode ='insertitem';
	else vMainMode ='updateitem';
	
	if(x.item_code.value == ''){
		alert("Please Select an Item!");
		return 0;
	} else if(x.txtQty.value == '' || x.txtQty.value == 0){
		alert("Quantity Should be Positive and > 0!");
		return 0;
	} else {
		x.action = "Form_ItemAuction_Action.php?mode="+vMainMode;
		x.submit();
		
	}
	
   
}


function SubmitRecordGrid(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction) {
	
	x = document.itemauction;
	
		
	var auction_iddt   = document.getElementById('auction_iddt['+PIndex+']').value;
	vMode = 'editdt-ajax';	
	var checked_auction = 'checked_auction['+PIndex+']';
	
	if(document.getElementById(checked_auction).checked)
		var checked_auction = 1;
	else var checked_auction = 0;
	
	var  the_data = 'mode='+vMode+
					'&txtAuctionId='+x.txtAuctionId.value+
					'&auction_iddt='+auction_iddt+
					'&txtDate='+x.txtDate.value+
					'&txtStartTime='+x.txtStartTime.value+
					'&txtEndDate='+x.txtEndDate.value+
					'&txtEndTime='+x.txtEndTime.value+
					'&txtQty='+x.txtQty.value+
					'&auction_remark='+encodeURIComponent(x.auction_remark.value)+
					'&checked_auction='+checked_auction;
		
	
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader1").addClass("ajaxsaving");
		//$('#datagrid :input').attr('disabled', true);
		
		var SubBtnID = 'imgSubmit_1['+PIndex+']';
		if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;
		
		
		if(xmlhttp) {
					
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200)
				{
					var data = $.parseJSON(xmlhttp.responseText);
					
					var msg = data[0].message;
					
					if (msg != "") {
						$("#Loader1").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){
							transid = data[0].transid;
							
							x.txtAuctionId.value = transid;
							x.submit();
						} 
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'ledger_number['+index+']';
						
						createCookie('prdtpl-nextcell',nextcell);
						
						ReloadGrid(filepath,formname,transid,'datagrid-1',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
							MoveNextRecord(nextcell);
							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_ItemAuction_Action.php?"+the_data);
			xmlhttp.send();
			
		}
	
}


function DeleteRecordGrid(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction) {
	
	x = document.itemauction;
	
		
	var auction_iddt   = document.getElementById('auction_iddt['+PIndex+']').value;
	vMode = 'deletedt';	
		
		
	if (confirm ( 'Are you sure you want to delete this record?' )){
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader1").addClass("ajaxsaving");
					
		if(xmlhttp) {
					
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200)
				{
					var data = $.parseJSON(xmlhttp.responseText);
					
					var msg = data[0].message;
					
					if (msg != "") {
						$("#Loader1").removeClass("ajaxsaving");
						alert(decodeURIComponent(msg));
					} else {	
						$("#Loader").removeClass("ajaxsaving");
						ReloadGrid(filepath,formname,transid,'datagrid-1',PIndex,dftorderby,'DEL',orderby,morelines,startrange,perpage,0,direction);	
					} 
							
					
					
				}
			}
			
			xmlhttp.open("GET","Form_ItemAuction_Action.php?mode="+vMode+"&auction_iddt="+auction_iddt);
			xmlhttp.send();
			
		}
	}
	
}

function SearchForRef(){
    //ClearForm('All');
    x = document.production;
    win = window.open('Form_ItemAuctionSearch.php', 'Form_ItemAuctionSearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=880,height=580,top=100,left=10');		
	win.creator = self;
	win.focus();		
			
}

function SearchForPending(){
	x = document.production;
    win = window.open('Form_AuctionItemPending.php', 'Form_AuctionItemPending.php', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=750,height=580,top=100,left=10');		
	win.creator = self;
	win.focus();	
}

function showlistitem(str){
	window.open('select_item.php?item='+str,'mywindow','width=900,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function setCheck(index){
	var checked_auction = 'checked_auction['+index+']';
	if(document.getElementById(checked_auction).checked)
		document.getElementById(checked_auction).value = 1;
	else document.getElementById(checked_auction).value = 0;
}

function CancelPage(){
	
	document.itemauction.action = 'Form_ItemAuction_Action.php?mode=cancelAuction&txtAuctionId='+document.itemauction.txtAuctionId.value;
	document.itemauction.submit();
}
</script>
<title>Item Auction</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='itemauction' method='post'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='message' value='$message' size='200'>

HERE;


if (empty($txtDate))	$txtDate 	= displayToday();
if (empty($txtEndDate))	$txtEndDate = displayToday();

		
if ($actionmode != "cancel" && $txtAuctionId != '') {
	// Read From Tables For Selected Record				 
	$query = " Select auction_reference, date_format(auction_startDate,'%d/%m/%Y') as startdate, date_format(auction_startDate,'%H:%i') as starttime,  ".
			 " date_format(auction_endDate,'%d/%m/%Y')as enddate, date_format(auction_endDate,'%H:%i')as endtime, item_auction.item_code, item_description, ".
			 " auction_qty, auction_remark, items.Item_UnitSalesDesc ".
	         " From temp_item_auction as item_auction  ".
			 " left join items on items.item_code = item_auction.item_code ".
	         " Where auction_id = ".$txtAuctionId;
			 
			 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	
	$txtRef			= $rows[0];
	$txtDate        = $rows[1];
	$txtStartTime	= $rows[2];
	$txtEndDate     = $rows[3];
	$txtEndTime     = $rows[4];
	$item_code     	= $rows[5];
	$item_desc     	= $rows[6];
	$txtQty    		= $rows[7];
	$auction_remark = $rows[8];
	$txtitemunit	= $rows[9];
		
}


//$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";

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'>
			<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'>ITEM AUCTION</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='720px' align='left'>";


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

if ($txtAuctionId != '')
	echo" <button type='button' id='btnPost' name='btnPost' onclick='PostChanges();return false;' title='Save Changes'><span><span>Save</span></span></button>";


if ($txtAuctionId == ''){
	echo" <button type='button' id='btnSearch' name='btnSearch' onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</span></span></button>";
	echo" <button type='button' id='btnPending' name='btnPending' onclick='SearchForPending();return false;' title='Pending'><span><span>Pending</span></span></button>";
}
				
				
				
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'>";	


print <<<HERE
	
		<table border="0" style='table-layout:fixed'>
		  <col width=90>
		  <col width=300>
		  <col width=40>	
		  <col width=90>
		  <col width=300>
		  <col width=20>		
		<tr bgcolor="#F7F7F7" >
          <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='txtAuctionId' id='txtAuctionId' value='$txtAuctionId' >
			<input type="hidden" name="txtRef" value="$txtRef" ></td><td colspan='4'></td></tr>
		
HERE;

echo "<tr bgcolor='#F7F7F7' >
		  <td align='left'><span class='style1'>Start Date<span class='style16'>*</span></span></td>
		  <td><input type='text' name='txtDate' value='$txtDate' maxlength='10'  style='width:80px;' >
		   <A HREF='#' onClick=\"displayCalendar(document.itemauction.txtDate,'dd/mm/yyyy',this); return false;\" NAME='anchor1' ID='anchor1'>
		   <img src='./img/cal.gif' border=0 align=center></A>
		  </td>";
echo "<td></td>";  
echo "<td align='left'><span class='style1'>Start Time</span></td>
		  <td><input type='time' name='txtStartTime' value='$txtStartTime' style='width:115px;' > </td>";
echo"   </tr>";


echo "<tr bgcolor='#F7F7F7' >
		  <td align='left'><span class='style1'>End Date<span class='style16'>*</span></span></td>
		  <td><input type='text' name='txtEndDate' value='$txtEndDate' maxlength='10'  style='width:80px;' >
		   <A HREF='#' onClick=\"displayCalendar(document.itemauction.txtEndDate,'dd/mm/yyyy',this); return false;\" NAME='anchor1' ID='anchor1'>
		   <img src='./img/cal.gif' border=0 align=center></A>
		  </td>";
echo "<td></td>";
echo "<td align='left'><span class='style1'>End Time</span></td>
		  <td><input type='time' name='txtEndTime' value='$txtEndTime' style='width:115px;' > </td>";
echo"   </tr>";


echo "<tr bgcolor='#F7F7F7' >
		  <td align='left'><span class='style1'>Item<span class='style16'>*</span></span></td>
		  <td><input type='text' name='item_code' id='item_code' value='$item_code' style='width:120px;'>
		<input type='text' name='item_desc' id='item_desc' value='$item_desc' style='width:150px;'>
		<label><span class='style11'><a href='javascript:void(0);' title=' Select Item ' onClick='showlistitem(12); '>
		<img src='img/btnopen.jpg' width='15' height='20' border='0' /></a> </span></label>
		  </td>";
echo "<td></td>";
echo "<td align='left'><span class='style1'>Quantity<span class='style16'>*</span></span></td>
		  <td><input type='text' name='txtQty' value='$txtQty' style='width:80px;' >
				<input type='text' name='txtitemunit' value='$txtitemunit' style='width:50px; border:none;font-weight:bold;' readonly >
		  </td>";
echo"   </tr>";

echo "<tr bgcolor='#F7F7F7' >
		  <td align='left'><span class='style1'>Remark</span></td>
		  <td colspan='3'><input type='text' name='auction_remark' id='auction_remark' value='$auction_remark' style='width:430px;'>
		  </td>";
echo "<td><button type='button' id='btnAdd' name='btnAdd' onclick='AddItem();return false;' title='Submit'><span><span>Submit</span></span></button></td>";
echo "<td align='left'>";
echo "</td><td></td>";
echo"   </tr>";
$Parameters = array();
$Parameters['DecimalBase'] = $DecimalBase;
$Parameters['Base1'] = $base1;
$Parameters['Base2'] = $base2;

$_SESSION['gprdtpl_parameters']  = $Parameters;




//***********Auction Details*******************
	
echo"   <tr><td colspan='6' valign='top'>";
echo"	<div id='datagrid-1' class='grid' style='width:700px;height:500px;' >";
//echo"	<div id='Loader' class=''><div></div></div>";

//Show Items Grid
ShowItemAuctionDtGrid($connection,'IAD',$txtAuctionId,$_SESSION['gprdtpl_parameters'],$_SESSION['gprdtpl_arrayaccess'],'item_auction.auction_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>  ";//end of last table menu
	
	
if ($actionmode == "post" && $txtAuctionId != '') {
	echo '<script type="text/javascript" language="javascript">';
	
	//if ($Login_FastPrint == 1) 
		//echo ' PrintProduction(\''.$PrPrdId.'\', \''.$PrPrdRef.'\'); ';
		
	echo ' ClearPage(1); ';
	echo '</script>';

}

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

HERE;

?>