<?php

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


include("config.inc.php");
include("Functions_Purchase.php");
include("Forms_DataGrid.php");

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


$querylog="SELECT FI_ProductionTemp as loginaccess, ifNull(FI_ProductionTempApp,0) As FI_ProductionTempApp, ifNull(Login_FastPrint,0) As Login_FastPrint from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['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);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_Pack,0) As Module_Pack From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

//Read From ProductionSetup Table
$queryProductionSetup="Select Currency_code As SetupDftCurrency, Warehouse_code As SetupDftWareHouse From ProductionSetup";
$resultProductionSetup=mysql_query($queryProductionSetup,$connection) or die(mysql_error());
while($rowProductionSetup=mysql_fetch_array($resultProductionSetup)){
	extract($rowProductionSetup);
}


$querydflwh="select default_warehouse_code as defaultwarehouse from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."' and default_warehouse_code != '' ";
$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}

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


<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_G1','ModRec_G1','imgSubmit_1');
			selRecordColor(this,'SelectedRec_G1','SelectedRecColor_G1');
		});
		$(document).on('focusin', '.table-focus-g2', function() { 
			AutoSaveRecordGrid(this.id,'SelectedRec_G2','ModRec_G2','imgSubmit_2');
			selRecordColor(this,'SelectedRec_G2','SelectedRecColor_G2');
		});

		//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 CheckFields(){
  
    x = document.production;
	
	var PrdDate     = x.txtDate.value;
	
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	if (PrdDate=='' )
	{
		alert("Date Column is mandatory!");
		x.txtDate.focus();
		return 0;
	}
		
	
	else
	return 1 ;	
}

function CheckFieldsDtFG(PIndex){
  
    x = document.production;
	
	var PrdDtItemFG 	 = document.getElementById('itemcodefg['+PIndex+']').value;
	var PrdDtWarehouseFG = document.getElementById('warehousecodefg['+PIndex+']').value;
	var PrdDtQtyFGF      = document.getElementById('prddtqtyfgf['+PIndex+']').value;
	var PrdDtQtyFG	     = document.getElementById('prddtqtyfg['+PIndex+']').value;
	
	
	var vmode = x.actionmode.value;
	
	if (PrdDtQtyFGF == '')   PrdDtQtyFGF = 0;
	if (PrdDtQtyFG == '')    PrdDtQtyFG = 0;
	
	PrdDtQtyFGF = parseFloat(PrdDtQtyFGF);	
	PrdDtQtyFG  = parseFloat(PrdDtQtyFG);
	
	
	if (PrdDtItemFG=='')
	{
		alert("Item is mandatory!");
		document.getElementById('itemcodefg['+PIndex+']').focus();
		return 0;
	}	
	else if (PrdDtWarehouseFG=='')
	{
		alert("Warehouse is mandatory!");
		document.getElementById('warehousecodefg['+PIndex+']').focus();
		return 0;
	}
	else if (PrdDtQtyFG*1 != PrdDtQtyFG/1 || PrdDtQtyFG <= 0  ) {
		alert('Quantity ('+PrdDtQtyFG+') should be NUMERIC and POSITIVE and GREATER Than Zero. ');
		document.getElementById('prddtqtyfg['+PIndex+']').focus();
		return 0;
	}
	else if (PrdDtQtyFGF*1 != PrdDtQtyFGF/1 || PrdDtQtyFGF <= 0  ) {
		alert('Quantity ('+PrdDtQtyFGF+') should be NUMERIC and POSITIVE and GREATER Than Zero. ');
		document.getElementById('prddtqtyfgf['+PIndex+']').focus();
		return 0;
	}
		
	
	else
	return 1 ;	
}

function CheckFieldsDtRM(PIndex){
  
    x = document.production;
	
	var PrdDtItemRM 	 = document.getElementById('itemcoderm['+PIndex+']').value;
	var PrdDtWarehouseRM = document.getElementById('warehousecoderm['+PIndex+']').value;
	var PrdDtQtyRMF      = document.getElementById('prddtqtyrmf['+PIndex+']').value;
	var PrdDtQtyRM	     = document.getElementById('prddtqtyrm['+PIndex+']').value;
	var PrdDtCostRM      = document.getElementById('costpricerm['+PIndex+']').value;
	var PrdDtCurrRM      = document.getElementById('currencycoderm['+PIndex+']').value;
	
	var vmode = x.actionmode.value;
	
	if (PrdDtQtyRMF == '')   PrdDtQtyRMF = 0;
	if (PrdDtQtyRM == '')    PrdDtQtyRM = 0;
	if (PrdDtCostRM == '')   PrdDtCostRM = 0;
	
	PrdDtQtyRMF = parseFloat(PrdDtQtyRMF);	
	PrdDtQtyRM  = parseFloat(PrdDtQtyRM);
	PrdDtCostRM = parseFloat(PrdDtCostRM);
	
	
	if (PrdDtItemRM=='')
	{
		alert("Item is mandatory!");
		document.getElementById('itemcoderm['+PIndex+']').focus();
		return 0;
	}	
	else if (PrdDtWarehouseRM=='')
	{
		alert("Warehouse is mandatory!");
		document.getElementById('warehousecoderm['+PIndex+']').focus();
		return 0;
	}
	else if (PrdDtCurrRM=='')
	{
		alert("Currency is mandatory!");
		document.getElementById('currencycoderm['+PIndex+']').focus();
		return 0;
	}
	else if (PrdDtQtyRM*1 != PrdDtQtyRM/1 || PrdDtQtyRM <= 0  ) {
		alert('Quantity ('+PrdDtQtyRM+') should be NUMERIC and POSITIVE and GREATER Than Zero. ');
		document.getElementById('prddtqtyrm['+PIndex+']').focus();
		return 0;
	}
	else if (PrdDtQtyRMF*1 != PrdDtQtyRMF/1 || PrdDtQtyRMF <= 0  ) {
		alert('Quantity ('+PrdDtQtyRMF+') should be NUMERIC and POSITIVE and GREATER Than Zero. ');
		document.getElementById('prddtqtyrmf['+PIndex+']').focus();
		return 0;
	}
	else if ((PrdDtCostRM*1 != PrdDtCostRM/1 || PrdDtCostRM < 0) ) {
		alert('Cost Price should be a NUMERIC and POSITIVE value');
		document.getElementById('costpricerm['+PIndex+']').focus();
		return 0;
	}	
	
	else
	return 1 ;	
}

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

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


function PostChanges() {
	x = document.production;
	var PrdId  = x.txtPrdId.value;
	var vMainMode = x.mainaction.value;
	
	var result = CheckFields();
	
	/*if (x.txtPrdCountFG.value == 0 || x.txtPrdCountFG.value == '') {
		alert('Save not allowed. Please add at least one item (Finished Good).');
	}
	else if (x.txtPrdCountRM.value == 0 || x.txtPrdCountRM.value == '') {
		alert('Save not allowed. Please add at least one item (Raw Material).');
	}
	else
	{*/
		if (result == 1) {
			if (confirm ( "Are you sure you want to Save current production template?"))
			{
				//Save Grid Before Posting	
				var vModRec_G1  = document.getElementById('ModRec_G1').value;
				var vModRec_G2  = document.getElementById('ModRec_G2').value;
				
				if (vModRec_G1 != "") {
					var Obj = document.getElementById('CurRec_G1'+vModRec_G1);
					Obj.style.backgroundColor='#F13A3A';
					alert("Please Submit changes before.");
					
				}
				else if (vModRec_G2 != "") {
					var Obj = document.getElementById('CurRec_G2'+vModRec_G2);
					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;
					if (document.getElementById('btnAddItemFG'))
						x.btnAddItemFG.disabled = true;
					if (document.getElementById('btnAddItemRM'))
						x.btnAddItemRM.disabled = true;		
					
						
					x.actionmode.value='post';
					x.action="Form_ProductionTemplate_Actions.php?mode=post&mainmode="+vMainMode+"&SPrdId="+PrdId;
					x.submit();
				}	
			}
		}	
	//}
}

	
function DeletePrdDt(PrdDtId, ItemPackCode, ItemCode, Option) {

	x = document.production;
	var PrdId  = x.txtPrdId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg = '';
	
	var vMode = 'deletedt'+Option;


	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_ProductionTemplate_Actions.php?mode="+vMode+"&mainmode="+vMainMode+"&SPrdId="+PrdId+"&SPrdDtId="+PrdDtId;
		x.submit();
	}

}

function UpdatePrdDt(PrdDtId, Option) {
    x = document.production;
	
	var vItemType   = Option;
	var vPrdId      = x.txtPrdId.value;
	var vPrdDate    = x.txtDate.value;
		
	var vMainMode = x.mainaction.value;
	
	win = window.open('Form_ProductionTemplateDetail.php?PItemType='+vItemType+'&mainaction='+vMainMode+'&actionmode=&PPrdId='+vPrdId+'&PPrdDate='+vPrdDate+'&PPrdDtId='+PrdDtId, 
					  'Form_ProductionTemplateDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=600,height=380,top=100');		
	win.creator = self;
	win.focus();		

}


//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.production;
	var vmode = x.actionmode.value;
	
	if (Option == 'All') {
		
		x.txtPrdId.value='';
		x.txtRef.value='';
		x.txtDate.value='';
		x.txtActive.value='';
		x.txtRemark.value='';
		
		x.message.value='';
		x.txtPrdCountFG.value='';
		x.txtPrdCountRM.value='';
		
		x.actionmode.value = '';
		x.mainaction.value = '';
	} 
}

function AddItems(Option) {
	x = document.production;
	var result = CheckFields();
	
	var vItemType      = Option;
	var vPrdId    	   = x.txtPrdId.value;
	var vPrdDate  	   = x.txtDate.value;
	var vPrdActive     = x.txtActive.value;
	var vPrdRemark     = x.txtRemark.value;
		
	vPrdRemark  = vPrdRemark.replace('&','%26');
	vPrdRemark  = vPrdRemark.replace('#','%23');
	
	var vMainMode = x.mainaction.value;
	
	if (result == 1) {
		win = window.open('Form_ProductionTemplateDetail.php?PItemType='+vItemType+'&mainaction='+vMainMode+'&actionmode=&PPrdId='+vPrdId+'&PPrdDate='+vPrdDate+
		                  '&PPrdActive='+vPrdActive+'&PPrdRemark='+vPrdRemark, 
						  'Form_ProductionTemplateDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=600,height=380,top=100');		
		win.creator = self;
		win.focus();		
	}	
	
   
}

function DeleteRecordGridFG(filepath,formname,transid,PrdDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction) {
	x = document.production;
	var vPrdId    = x.txtPrdId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg = 'Are you sure you want to delete this record?';

		
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader1").addClass("ajaxsaving");
		
		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 { 
					$("#Loader1").removeClass("ajaxsaving");
					ReloadGrid(filepath,formname,transid,'datagrid-1',index,dftorderby,'DEL',orderby,morelines,startrange,perpage,0,direction);			
				}
			}
		}

		xmlhttp.open("GET","Form_ProductionTemplate_Actions.php?mode=deletedtFG&mainmode="+vMainMode+"&SPrdId="+vPrdId+"&SPrdDtId="+PrdDtId);
		xmlhttp.send();
	}	

}


function SubmitRecordGridFG(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction) {
	
	x = document.production;
	
	
	var result = 1;
	result = CheckFields();
	
	if (result == 1) {
		result = CheckFieldsDtFG(PIndex);
	}
	
	var PrdDtFGId   = document.getElementById('prdfgid['+PIndex+']').value;
	if (PrdDtFGId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	var vCostOption = document.getElementsByName('txtCostOptionFG['+PIndex+']');
	for (var i=0; i < vCostOption.length; i++)
	{
		if (vCostOption[i].checked)
		{
		  var vPrdCostOption = vCostOption[i].value;
		}
	}
		
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SItemType=FG'+
					'&SPrdId='+x.txtPrdId.value+
					'&PPrdId='+x.txtPrdId.value+
					'&PPrdDate='+x.txtDate.value+
					'&PPrdActive='+x.txtActive.value+
					'&PPrdRemark='+encodeURIComponent(x.txtRemark.value)+
					'&SPrdDtId='+document.getElementById('prdfgid['+PIndex+']').value+
					'&lstWarehouse='+document.getElementById('warehousecodefg['+PIndex+']').value+
					'&txtItemCode='+document.getElementById('itemcodefg['+PIndex+']').value+
					'&txtPrdDtRemark='+document.getElementById('remarkdtfg['+PIndex+']').value+
					'&txtPrdDtQtyF='+document.getElementById('prddtqtyfgf['+PIndex+']').value+
					'&txtPrdDtQty='+document.getElementById('prddtqtyfg['+PIndex+']').value+
					'&txtCostOption='+vPrdCostOption;
		
	
	if (result == 1) {
		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.open("POST", "Form_ProductionTemplate_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 != "") {
						$("#Loader1").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){
							transid = data[0].transid;
							
							x.txtPrdId.value = transid;
							x.submit();
						} 
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'itemcodefg['+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_ProductionTemplate_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
	}
}


function DeleteRecordGridRM(filepath,formname,transid,PrdDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction) {
	x = document.production;
	var vPrdId    = x.txtPrdId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg = 'Are you sure you want to delete this record?';

		
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader2").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = $.parseJSON(xmlhttp.responseText);
					
				var msg = data[0].message;
					
				if (msg != "") {
					$("#Loader2").removeClass("ajaxsaving");
					alert(decodeURIComponent(msg));
				} else { 
					$("#Loader2").removeClass("ajaxsaving");
					ReloadGrid(filepath,formname,transid,'datagrid-2',index,dftorderby,'DEL',orderby,morelines,startrange,perpage,0,direction);			
				}
			}
		}

		xmlhttp.open("GET","Form_ProductionTemplate_Actions.php?mode=deletedtRM&mainmode="+vMainMode+"&SPrdId="+vPrdId+"&SPrdDtId="+PrdDtId);
		xmlhttp.send();
	}	

}


function SubmitRecordGridRM(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction) {
	
	x = document.production;
	
	
	var result = 1;
	result = CheckFields();
	
	if (result == 1) {
		result = CheckFieldsDtRM(PIndex);
	}
	
	var PrdDtRMId   = document.getElementById('prdrmid['+PIndex+']').value;
	if (PrdDtRMId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	var vCostOption = document.getElementsByName('txtCostOptionRM['+PIndex+']');
	for (var i=0; i < vCostOption.length; i++)
	{
		if (vCostOption[i].checked)
		{
		  var vPrdCostOption = vCostOption[i].value;
		}
	}
	

		
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SItemType=RM'+
					'&SPrdId='+x.txtPrdId.value+
					'&PPrdId='+x.txtPrdId.value+
					'&PPrdDate='+x.txtDate.value+
					'&PPrdActive='+x.txtActive.value+
					'&PPrdRemark='+encodeURIComponent(x.txtRemark.value)+
					'&SPrdDtId='+document.getElementById('prdrmid['+PIndex+']').value+
					'&lstWarehouse='+document.getElementById('warehousecoderm['+PIndex+']').value+
					'&txtItemCode='+document.getElementById('itemcoderm['+PIndex+']').value+
					'&txtPrdDtRemark='+document.getElementById('remarkdtrm['+PIndex+']').value+
					'&txtPrdDtQtyF='+document.getElementById('prddtqtyrmf['+PIndex+']').value+
					'&txtPrdDtQty='+document.getElementById('prddtqtyrm['+PIndex+']').value+
					'&txtCostOption='+vPrdCostOption+
					'&txtCurr='+document.getElementById('currencycoderm['+PIndex+']').value+
					'&txtPrdDtCost='+document.getElementById('costpricerm['+PIndex+']').value+
					'&txtWasteRate='+document.getElementById('wasteraterm['+PIndex+']').value+
					'&txtWastePerBillet='+document.getElementById('wasteperbilletrm['+PIndex+']').value;
		
	
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader2").addClass("ajaxsaving");
		//$('#datagrid :input').attr('disabled', true);
		
		var SubBtnID = 'imgSubmit_2['+PIndex+']';
		if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;
		
		
		if(xmlhttp) {
			//xmlhttp.open("POST", "Form_ProductionTemplate_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 != "") {
						$("#Loader2").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){
							transid = data[0].transid;
							
							x.txtPrdId.value = transid;
							x.submit();
						} 
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'itemcoderm['+index+']';
						
						createCookie('prdtpl-nextcell',nextcell);
						
						ReloadGrid(filepath,formname,transid,'datagrid-2',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
							MoveNextRecord(nextcell);
							document.getElementById('ModRec_G2').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_ProductionTemplate_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
	}
}

function SearchForRef(){
    //ClearForm('All');
    x = document.production;
    win = window.open('Form_ProductionTemplateSearch.php', 'Form_ProductionTemplateSearch', '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 SetAcive() {
	x = document.production;
	
	x.txtActive.value = 0;
	if (x.chkActive.checked) x.txtActive.value = 1;

}


function PrintProduction(PrdId, PrdRef) {
	var str = '';
	
	if (confirm ( "Do you want to Print current Production Template with reference "+PrdRef+" ?"))
	{
		str = 'Form_ProductionTemplatePreview.php?ProductionId='+PrdId;
		window.open(str);
	}	
}





function showlistItemsFG(str,PIndex){
	var vDate, vItemCode;
	x = document.production;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemCode  = encodeURIComponent(document.getElementById('itemcodefg['+PIndex+']').value);
  
	window.open('List_SorItems.php?frm=8&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 showlistItemsDescFG(str,PIndex){
	var vDate, vItemCode;
	x = document.production;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemDesc  = encodeURIComponent(document.getElementById('itemdescriptionfg['+PIndex+']').value);
	
	window.open('List_SorItems.php?frm=8&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 showlistWarehouseFG(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vWarehouseCode = encodeURIComponent(document.getElementById('warehousecodefg['+PIndex+']').value);
	
	window.open('List_SorWarehouse.php?frm=3&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 showlistItemsRM(str,PIndex){
	var vDate, vItemCode;
	x = document.production;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemCode  = encodeURIComponent(document.getElementById('itemcoderm['+PIndex+']').value);
  
	window.open('List_SorItems.php?frm=9&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 showlistItemsDescRM(str,PIndex){
	var vDate, vItemCode;
	x = document.production;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemDesc  = encodeURIComponent(document.getElementById('itemdescriptionrm['+PIndex+']').value);
	
	window.open('List_SorItems.php?frm=9&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 showlistWarehouseRM(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vWarehouseCode = encodeURIComponent(document.getElementById('warehousecoderm['+PIndex+']').value);
	
	window.open('List_SorWarehouse.php?frm=4&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);
}



</script>
<title>Production Template</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='production' 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($txtActive))  $txtActive = 1;
		
if ($actionmode != "cancel" && $txtPrdId != '') {
	// Read From Tables For Selected Record				 
	$query = " Select ProdRecipe_ID, ProdRecipe_Reference, Date_Format(ProdRecipe_Date,'%d/%m/%Y') As ProdRecipe_Date, ".
	         " ProdRecipe_Remark, ifNull(ProdRecipe_Active,0) ".
			 " From ProdRecipe ".
	         " Where ProdRecipe_ID = ".$txtPrdId;
			 
			 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	
	$txtPrdId      = $rows[0];
	$txtRef        = $rows[1];
	$txtDate       = $rows[2];
	$txtRemark     = $rows[3];
	$txtActive     = $rows[4];
	
	$query = " Select Count(*) FROM ProdRecipeFG ".
			 " WHERE ProdRecipe_Id = ".$txtPrdId;
	$result = selectData($connection, $query);
	$txtPrdCountFG = $result[0];
	if($txtPrdCountFG == '') $txtPrdCountFG = 0;
	
	$query = " Select Count(*) FROM ProdRecipeRM ".
			 " WHERE ProdRecipe_Id = ".$txtPrdId;
	$result = selectData($connection, $query);
	$txtPrdCountRM = $result[0];
	if($txtPrdCountRM == '') $txtPrdCountRM = 0;
	
}


//$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'>PRODUCTION TEMPLATE</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'>";

if ($FI_ProductionTempApp == 1)
	echo" <button type='button' id='btnAddItemFG' name='btnAddItemFG' onclick=\"AddItems('FG');return false;\"' title='Add Finished Good'><span><span>Add Item FG</span></span></button>";
	
					
if ($FI_ProductionTempApp == 1)
	echo" <button type='button' id='btnAddItemRM' name='btnAddItemRM' onclick=\"AddItems('RM');return false;\"' title='Add Raw Material'><span><span>Add Item RM</span></span></button>";


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


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


if ($txtPrdId == '')
	echo" <button type='button' id='btnSearch' name='btnSearch' onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</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=100>
		  <col width=60>
		  <col width=120>
		  <col width=200>
		  <col width=500>

		<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='txtPrdCountFG' value='$txtPrdCountFG' >
			<input type='hidden' name='txtPrdCountRM' value='$txtPrdCountRM' >
			<input type='hidden' name='txtPrdId' value='$txtPrdId' >
			<input type="hidden" name="txtRef" value="$txtRef" >
			<input type="hidden" name="txtActive" value="$txtActive" ></td>
		  <td align="left"><span class="style1">Date&nbsp;<span class="style16">*</span></span></td>
		  <td><input type='text' name='txtDate' value='$txtDate' maxlength='10'  style='width:80px;' >
		                   <A HREF="#" onClick="displayCalendar(document.production.txtDate,'dd/mm/yyyy',this); return false;" NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A>
		  </td>
						   
HERE;


echo" 		<td align='left'><span class='style1'><input type='checkbox' name='chkActive' id='chkActive' value='1' onclick='SetAcive();' "; if($txtActive==1) echo "checked />"; else echo " />"; echo " Active</span></td>";
echo" 		<td align='left'>&nbsp;</td>";	  
echo"   </tr>";

echo"   <tr bgcolor='#F7F7F7' >
		  <td align='left' ><span class='style1'>Remark</span></td><td colspan='4' > <span class='style1'>
		  <input type='text' name='txtRemark' value='".htmlspecialchars($txtRemark, ENT_QUOTES)."'  style='width:385px;' maxlength='100' ></td>";

echo" 	  <td align='left'><span class='style1'>&nbsp;</span></td>";
echo"   </tr>";	


		  
/*
echo"   <tr><td colspan='6' valign='top'>";
echo"     <table border='0' style='table-layout:fixed'>
		  <col width=20>
		  <col width=20>
		  <col width=140>
		  <col width=140>
		  <col width=210>
		  <col width=100>
		  <col width=80>
		  <col width=80>
		  <col width=60>
		  <col width=103>";
		  
//***********Finished Goods*******************
		  
echo"<tr bgcolor='#D8D8D8' height='20'>";
echo"  <td align='center' colspan='10'><span class='style16'>Finished Goods</span></td>";
echo"</tr>";		  


echo"<tr>";
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='center'><span class='style27'>WH</span></td>";
echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Qty From</span></td>";
echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Qty To</span></td>";
echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit</span></td>";
echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Cost Option</span></td>";
echo"</tr>";

		  
		  
if ($txtPrdId != '' ) {
			
	$sub_query1 = " Select ProdRecipeFG.ProdRecipeFG_ID, ProdRecipeFG.Item_CodePacked, ProdRecipeFG.Item_Code, Item_Description, ".
				  " ProdRecipeFG.Warehouse_Code, ProdRecipeFG_Quantity, ProdRecipeFG_Remark, ".
				  " if(ProdRecipeFG_DistOption=1, 'Percentage', if(ProdRecipeFG_DistOption=2, 'Quantity', 'Fixed')) As DistOption,  ".
				  " Items.Item_UnitSalesDesc, ProdRecipeFG_QuantityFrom ".
				  " From ProdRecipeFG Left Join Items on ProdRecipeFG.Item_Code = Items.Item_code ".
				  " Where ProdRecipeFG.ProdRecipe_ID = '".$txtPrdId."' ".
				  " Order By ProdRecipeFG.ProdRecipeFG_ID Desc ";
	//echo $sub_query1;
	$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error());
	while($sub_rows1=mysql_fetch_array($sub_result1)){
		$ct+=1;

		if($ct%2==0)
			$Color="style='background-color:".$grid_color1."'";
		else			
			$Color="style='background-color:".$grid_color2."'";	
					
				
		echo "<tr ".$Color." >";

		echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_edit.png'  onMouseOver=\"style.cursor='hand'\" onclick=UpdatePrdDt('".$sub_rows1[0]."','FG') 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=\"DeletePrdDt('".$sub_rows1[0]."','".htmlentities($sub_rows1[1])."','".htmlentities($sub_rows1[2])."','FG')\" title='Delete Record'  ></span></td>";
				
		echo "	<td align='left'><span class='style15'>".$sub_rows1[1]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$sub_rows1[2]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$sub_rows1[3]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$sub_rows1[4]."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($sub_rows1[9],2)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($sub_rows1[5],2)."</span></td>";
		echo "	<td align='center'><span class='style15'>".$sub_rows1[8]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$sub_rows1[7]."</span></td>";
		echo "</tr>";
			
	}
			
}

//***********Raw Materials*******************
		  
echo"<tr bgcolor='#D8D8D8' height='20'>";
echo"  <td align='center' colspan='10'><span class='style16'>Raw Materials</span></td>";
echo"</tr>";		  

echo"<tr>";
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='center'><span class='style27'>WH</span></td>";
echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Qty From</span></td>";
echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Qty To</span></td>";
echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit</span></td>";
echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Cost Option</span></td>";
echo"</tr>";	  
		  
if ($txtPrdId != '' ) {
			
	$sub_query2 = " Select ProdRecipeRM.ProdRecipeRM_ID, ProdRecipeRM.Item_CodePacked, ProdRecipeRM.Item_Code, Item_Description, ".
				  " ProdRecipeRM.Warehouse_Code, ProdRecipeRM_Quantity, ProdRecipeRM_Remark,  ".
				  " if(ProdRecipeRM_DistOption=1, 'Percentage', if(ProdRecipeRM_DistOption=2, 'Quantity', 'Fixed')) As DistOption,  ".
				  " Items.Item_UnitSalesDesc, ProdRecipeRM_QuantityFrom ".
				  " From ProdRecipeRM Left Join Items on ProdRecipeRM.Item_Code = Items.Item_code ".
				  " Where ProdRecipeRM.ProdRecipe_ID = '".$txtPrdId."' ".
				  " Order By ProdRecipeRM.ProdRecipeRM_ID Desc ";
	//echo $sub_query2;
	$sub_result2=mysql_query($sub_query2,$connection) or die(mysql_error());
	while($sub_rows2=mysql_fetch_array($sub_result2)){
		$ct+=1;

		if($ct%2==0)
			$Color="style='background-color:".$grid_color1."'";
		else			
			$Color="style='background-color:".$grid_color2."'";	
					
				
		echo "<tr ".$Color." >";

		echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_edit.png'  onMouseOver=\"style.cursor='hand'\" onclick=UpdatePrdDt('".$sub_rows2[0]."','RM') 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=\"DeletePrdDt('".$sub_rows2[0]."','".htmlentities($sub_rows2[1])."','".htmlentities($sub_rows2[2])."','RM')\" title='Delete Record'  ></span></td>";
				
		echo "	<td align='left'><span class='style15'>".$sub_rows2[1]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$sub_rows2[2]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$sub_rows2[3]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$sub_rows2[4]."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($sub_rows2[9],2)."</span></td>";
		echo "	<td align='right'><span class='style15'>".number_format($sub_rows2[5],2)."</span></td>";
		echo "	<td align='center'><span class='style15'>".$sub_rows2[8]."</span></td>";
		echo "	<td align='left'><span class='style15'>".$sub_rows2[7]."</span></td>";
		echo "</tr>";
			
	}
			
}

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


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



$Parameters = array();
$Parameters['Module_Pack'] = $Module_Pack;
$Parameters['DecimalBase'] = $DecimalBase;
$Parameters['Base1'] = $base1;
$Parameters['Base2'] = $base2;
$Parameters['txtDate'] 	  = $txtDate;
$Parameters['DefaultCur'] = $SetupDftCurrency;

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

$_SESSION['gprdtpl_parameters']  = $Parameters;




//***********Finished Goods*******************
		  
echo"	<tr bgcolor='#D8D8D8' height='20'>";
echo"  		<td align='center' colspan='6'><span class='style16'>Finished Goods</span></td>";
echo"	</tr>";
echo"   <tr><td colspan='6' valign='top'>";
echo"	<div id='datagrid-1' class='grid' style='width:1090px;height:200px;' >";
//echo"	<div id='Loader' class=''><div></div></div>";

//Show Items Grid
ShowProdTplDtGridFG($connection,'PRD-TPL-1',$txtPrdId,$_SESSION['gprdtpl_parameters'],$_SESSION['gprdtpl_arrayaccess'],'ProdRecipeFG.ProdRecipeFG_ID');

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


//***********Raw Materials*******************
		  
echo"<tr bgcolor='#D8D8D8' height='20'>";
echo"  <td align='center' colspan='6'><span class='style16'>Raw Materials</span></td>";
echo"</tr>";
echo"   <tr><td colspan='6' valign='top'>";
echo"	<div id='datagrid-2' class='grid' style='width:1090px;height:200px;' >";
//echo"	<div id='Loader' class=''><div></div></div>";

//Show Items Grid
ShowProdTplDtGridRM($connection,'PRD-TPL-2',$txtPrdId,$_SESSION['gprdtpl_parameters'],$_SESSION['gprdtpl_arrayaccess'],'ProdRecipeRM.ProdRecipeRM_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" && $PrPrdId != '') {
	echo '<script type="text/javascript" language="javascript">';
	
	//if ($Login_FastPrint == 1) 
		//echo ' PrintProduction(\''.$PrPrdId.'\', \''.$PrPrdRef.'\'); ';
		
	echo ' ClearPage1(); ';
	echo '</script>';

}

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

HERE;

?>