<?php
session_name('CAKEPHP'); session_start();
include('includes/stockcalculation.php');
include('cocoon_config.php');
function getFieldvalue_cake($table, $condition, $val, $field)
{

	//echo "select ".$field." from ".$table." where ".$condition." ='".$val."'";
	$sql = mysqli_query($link1, "select " . $field . " from " . $table . " where " . $condition . " ='" . $val . "'");
	$r = mysqli_fetch_array($sql);
	//echo "select ".$field." from ".$table." where ".$condition." ='".$val."'"; 
	return ($r[$field]);
}

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

	date_default_timezone_set('Asia/Calcutta');
	$financial = substr($_SESSION['YearStart'], -2) . "-" . substr($_SESSION['YearEnd1'], -2);
	// $prefixcode="ISS";
	$prefix_sql = DB_query("Select * from prefix_tbl where prefix_name='" . $_REQUEST['frmid'] . "'
	                       and module_id='" . $_REQUEST['modid'] . "' ", $db);
	$prefix_row = DB_fetch_array($prefix_sql);
	//$prefixf=explode("/",$prefix_row['prefix_code']);
	$prefixcode = $prefix_row['prefix_code'];
	//$year=$_SESSION['financialYearStart'];
	//$year_after=$_SESSION['financialYearEnd'];
	$site_code = substr($_REQUEST['sitecode'], 0, 3);
	$sql = "select issue_slipno from addissue where site = '" . $_REQUEST['sitecode'] . "'
						   ORDER BY ID DESC LIMIT 0,1";
	$result = DB_query($sql, $db);
	$myrow = DB_fetch_array($result);
	$numrows = DB_num_rows($result);
	$sqldata = DB_query("select locationname from locations where loccode='" . $_REQUEST['sitecode'] . "'", $db);
	$sqltext = DB_fetch_array($sqldata);
	$sitename = $sqltext['locationname'];
	$siteCode = $sitename;
	$strdata = substr($myrow['issue_slipno'], 14, 6);

	if ($numrows > 0) {
		$i = 0;
		$strmax = "";
		$myrow = DB_Fetch_array($result);

		if ($siteCode != '')
			if ($numrows > 0) {

				$maxval = $strdata;
			} else {
				$maxval = 0;
			} {
			$strChar = $site_code . "/" . $financial . "/" . $prefixcode . "/";
		}
	} else {
		$strChar = $site_code . "/" . $financial . "/" . $prefixcode . "/";
	}

	$strFinal = $maxval + 1;

	$strBothFinal = $strChar . str_pad($strFinal, 6, "0", STR_PAD_LEFT);

	$sql = "INSERT INTO addissue set								
			site='" . $_REQUEST['sitecode'] . "',  
			issue_slipno='" . $strBothFinal . "',  
			issuedate='" . FormatDateForSQL1($_REQUEST['issuedate']) . "',  
			mst_storeid='" . $_REQUEST['store'] . "',  
			store='" . $s->GetFieldValue('storetype', "id='" . $_REQUEST['store'] . "'", 'StoreCode') . "',  
			received_by='" . $_REQUEST['received_by'] . "',
			department='" . $_REQUEST['dept1'] . "',
			job_id='" . $_REQUEST['job_id'] . "',
			wo_id='" . $_REQUEST['work_order_id'] . "',
			finished_item='" . $_REQUEST['oderitem'] . "',
			material_received_by='" . $_REQUEST['material_received_by'] . "',
			material_issue_by='" . $_REQUEST['material_issue_by'] . "',
			remarks='" . $_REQUEST['remarks'] . "',
			createdby='" . $_SESSION['UserID'] . "',
			transaction_time='" . ConvertSQLDate($_REQUEST['issuedate']) . " " . date('H:i:s', time()) . "', 
			companyID='" . $_SESSION['ACGCompanyId'] . "', 
			type='MRS', 
			mrs_id='" . $_REQUEST['mrsid'] . "',
			to_store='" . $_REQUEST['to_store'] . "',
			createddate='" . date('Y-m-d') . "' ";

	$ErrMsg = _('An error occurred Record Note Save') . '. ' . _('The error says');
	$insertResult = DB_query($sql, $db, $ErrMsg);
	$Lastreq_id = DB_Last_Insert_ID($db, 'addissue', $ErrMsg);
	// $Lastreq_id=1;
	if ($Lastreq_id != '') {
		$totalqty = 0;
		for ($i = 0; $i < count($_REQUEST['itemdataid']); $i++) {
			if ($_REQUEST['itemdataid'] != "") {
				$sql2 = "INSERT INTO issueqty set issue_id='" . $Lastreq_id . "',
										 mst_itemid='" . $_REQUEST['itemdataid'][$i] . "',
										 current_stock='" . $_REQUEST['stock'][$i] . "',				 
										 issueqty='" . $_REQUEST['secqty'][$i] . "', 
										 mst_unitid='" . $_REQUEST['unit'][$i] . "',
										 conv_unitid='" . $_REQUEST['secunit'][$i] . "',
										 confac='" . $_REQUEST['confactor'][$i] . "',
										 batch_no='" . $_REQUEST['batch'][$i] . "'";
				$ErrMsg = _('An error occurred Record Note Save') . '. ' . _('The error says');
				$insertResult2 = DB_query($sql2, $db, $ErrMsg);
				$dtls_Lastreq_id = DB_Last_Insert_ID($db, 'issueqty', $ErrMsg);

				/*************************   Stock Valution *******************************/



				$primary_unit = $s->getField('item_master', 'id', $_POST['itemdataid'][$i], 'mst_unitid');
				$secondary_unit = $s->getField('item_master', 'id', $_POST['itemdataid'][$i], 'conv_unit');
				$data_stock['site']                     = $_REQUEST['sitecode'];
				$data_stock['store']                    = $_REQUEST['store'];
				$data_stock['mst_itemid']               = $_POST['itemdataid'][$i];
				$data_stock['primary_unit']             = $primary_unit;
				$data_stock['secondary_unit']           = $secondary_unit;
				$data_stock['against_voucher_main_id']  = $Lastreq_id;
				$data_stock['against_voucher_dtls_id']  = $dtls_Lastreq_id;
				//  $data_stock['date_of_expiry'] 		    =$check_current_op_row['date_of_expiry'];
				// $data_stock['date_of_mfg'] 		        =$check_current_op_row['date_of_mfg'];
				$data_stock['against_tra_id']           = $check_current_op_row['id'];
				$data_stock['type']                     = 'Issue';
				if ($check_current_op_row['status'] == '1')
					$data_stock['status'] = 1;
				else
					$data_stock['status'] = 0;

				$data_stock['outwardqty_primary']       = $_REQUEST['secqty'][$i];
				$data_stock['pending_qty']              = $_REQUEST['secqty'][$i];
				$data_stock['outwardqty_secondary']     = $_REQUEST['secqty'][$i] * $_REQUEST['confac'][$i];
				$data_stock['inward_rate']              = $outward_rate;
				$data_stock['outward_value']            = $outwardamount;
				$data_stock['batch_no']                 = $_REQUEST['batch'][$i];
				$data_stock['trasaction']               = FormatDateForSQL($_REQUEST['issuedate']) . " " . date('H:i:s', time());
				$pendingqty = $pendingqty - $outwards_qty;
				$s->RecordInsert('stock_valuation_tbl', $data_stock);


				/**********************************  Inserting Records in batch table (cake php)*****************************/
				//echo $_REQUEST['storecode'];
				$majorid = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'CategoryID');
				$majormainid = $s->getField('stockmaincategory', 'id', $majorid, 'ref_major_id');
				$storecode = $s->getField('storetype', 'id', $_REQUEST['store'], 'StoreCode');
				$unitcode = $s->getField('unitsofmeasure', 'unitid', $primary_unit, 'unitname');
				$majorcode = getFieldvalue_cake('majors', 'id', $majormainid, 'major_code');


				$itemcode = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'StockID');
				$item_name = $s->getField('item_master', 'id', $_REQUEST['itemdataid'][$i], 'item_name');
				$batchno = $_REQUEST['batch'][$i];



				$query_batch_item = mysqli_fetch_array(mysqli_query($link1, "select SUM(qty) as qty,id FROM batchdetails WHERE item_code='" . $itemcode . "' and store_code='" . $storecode . "' and batch_no='" . $batchno . "' GROUP BY item_code"));

				//$batch_qty=$query_batch_item['qty'];

				$stockbatchqty = $query_batch_item['qty'] - $_REQUEST['secqty'][$i];
				$update_batch = mysqli_query($link1, "update batchdetails set qty ='" . $stockbatchqty . "' where item_code='" . $itemcode . "' and store_code='" . $storecode . "' and batch_no='" . $batchno . "'");


				$query_item = mysqli_fetch_array(mysqli_query($link1, "select SUM(stock_level),id FROM storeitems WHERE item='" . $itemcode . "' and store_code='" . $storecode . "' GROUP BY item"));


				$stockqty = $query_item['SUM(stock_level)'] - $_REQUEST['secqty'][$i];
				$update = mysqli_query($link1, "update storeitems set stock_level ='" . $stockqty . "' where item='" . $itemcode . "' and store_code='" . $storecode . "' and major_code='" . $majorcode . "'");


				/******************************************************************************************************************/

				//Update detail Table
				$sql_issue_mrs = "select sum(primary_qty) from material_job_item inner join material_slip_against_job_card on material_slip_against_job_card.id=material_job_item.material_slip_id where material_slip_against_job_card.id='" . $_REQUEST['mrsid'] . "' and mst_itemid='" . $_REQUEST['itemdataid'][$i] . "'";
				$result_issue_mrs = DB_query($sql_issue_mrs, $db);
				$rs_issue_mrs = DB_fetch_array($result_issue_mrs);


				$sql_issue = "select sum(issueqty) from issueqty inner join addissue on addissue.id=issueqty.issue_id where mrs_id='" . $_REQUEST['mrsid'] . "' and mst_itemid='" . $_REQUEST['itemdataid'][$i] . "'";
				$result_issue = DB_query($sql_issue, $db);
				$rs_issue = DB_fetch_array($result_issue);

				$total = $rs_issue[0];

				if ($rs_issue_mrs[0] == $total) {
					DB_query("update material_job_item set status='1' where mst_itemid='" . $_REQUEST['itemdataid'][$i] . "'", $db);
				}
			}
		}
	}


	$sql_issue_mrs_count = "select count(*) from material_job_item where material_slip_id='" . $_REQUEST['mrsid'] . "'";
	$result_issue_mrs_count = DB_query($sql_issue_mrs_count, $db);
	$rs_issue_mrs_count = DB_fetch_array($result_issue_mrs_count);

	$sql_issue_mrs_appr_count = "select count(*) from material_job_item where material_slip_id='" . $_REQUEST['mrsid'] . "' and status='1'";
	$result_issue_mrs_appr_count = DB_query($sql_issue_mrs_appr_count, $db);
	$rs_issue_mrs_appr_count = DB_fetch_array($result_issue_mrs_appr_count);



	if ($rs_issue_mrs_count[0] == $rs_issue_mrs_appr_count[0]) {
		DB_query("update material_slip_against_job_card set issue_status='1' where id='" . $_REQUEST['mrsid'] . "' ", $db);
	}


	//$updateQty=DB_query("Update addissue set totalqty='".$totalqty."' where id='".$Lastreq_id."'",$db);

	if ($insertResult2 == true) {
		prnMsg(_('Record Inserted Successfully'), 'success');
		echo "<script>location.href='index.php?route=Inventory/transation/Issue_slip_index&modid=" . $_REQUEST['modid'] . "&frmid=" . $_REQUEST['frmid'] . "'</script>";
	}
}
?>
<style type="text/css">
	.body_lightbox {
		width: 100%;
		background-color: #e7e7e7;
		position: absolute;
		left: 894px;
		top: 394px;
		padding-left: 5px;
		padding-right: 5px;
		border: #666666 solid 3px;
		visibility: hidden;
	}
</style>
<?php
// echo "Select * from material_request_slip where id='".$_REQUEST['mrsid']."'";
$result  = DB_query("Select * from material_slip_against_job_card where id='" . $_REQUEST['mrsid'] . "'", $db);

extract(DB_Fetch_array($result));

?>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
	<div class="tab_div">
		<form name="form1" action="" method="post">
			<h1><?php echo $s->getField('modules_form', 'id', $_REQUEST['frmid'], 'frm_name'); ?></h1>
			<table width="100%" border="0" cellpadding="3" cellspacing="0">
				<tr class="row1">
					<td width="13%" align="right">Branch</td>
					<td width="20%">
						<?php
						//echo $site = $s->GetFieldValue("material_request_slip","mrs_no='".$mat_slip_no."'","branch");
						// $site = $s->GetFieldValue("job_card","id='".$job_card_id."'","site");
						if ($_SESSION['AssignedBranch'] != '') {
							$ss = "Select loccode, locationname from locations  where CompanyId='" . $_SESSION['ACGCompanyId'] . "' and loccode in('" . $_SESSION['AssignedBranch'] . "')";
							$site_sql = DB_query($ss, $db);
						} else {
							$ss = "Select loccode,locationname from locations where CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
							$site_sql = DB_query($ss, $db);
						}


						?>
						<select name="sitecode" id="sitecode" onchange="showsitename158(this.value)">
							<!--  <option value="0">Select</option> -->
							<?php
							while ($myrow = DB_fetch_array($site_sql)) {
								$p = '';
								if ($myrow['loccode'] == $branch_id)
									$p = 'selected';
							?>
								<option value="<?php echo $myrow['loccode']; ?>" <?php echo $p; ?>><?php echo $myrow['locationname']; ?></option>
							<?  } ?>
						</select>
					</td>
					<td width="13%" align="right">To Store</td>
					<td width="20%">
						<div id='hid-Godown-div'>
							<select name="store" id="store">
								<!-- <option value="0">Select</option> -->
								<?php
								$sql_store12 = "SELECT  id, StoreCode, StoreName FROM storetype WHERE id='" . $to_store . "' ";
								$resultStkLocs12 = DB_query($sql_store12, $db);
								while ($storedata = DB_Fetch_array($resultStkLocs12)) { ?>
									<option value="<?php echo $storedata['id'];  ?>" <?php if ($_REQUEST['store'] == $storedata['id']) {
																							echo "selected";
																						} ?>><?php echo $storedata['StoreName']; ?></option>
								<?php }
								?>
							</select>
						</div>
					</td>
					<td width="13%" align="right">Issue No.</td>
					<td><input name="issue_slipno" type="text" id="issue_slipno" size="20" readonly="readonly" value="Auto Generate" /></td>
				</tr>

				<tr class="row1">
					<td align="right">Issue Date</td>
					<td><input name="issuedate" readonly="" type="text" id="issuedate" value="<?php echo ConvertSQLDate(date('Y-m-d')); ?>" class="datepicker" />
						<?php $wo_no = $s->GetFieldValue("job_card", "id='" . $job_card_id . "'", "wo_no"); ?>
						<input type="hidden" name="work_order_id" value="<?php echo $wo_no; ?>">
						<input type="hidden" name="job_id" value="<?php echo $jobcard_id; ?>">
						<input type="hidden" name="oderitem" value="<?php echo $item_id; ?>">
						<input type="hidden" name="mrsid" value="<?php echo $_REQUEST['mrsid']; ?>">
					</td>
					<td align="right">MRS No.</td>
					<td><input name="mrsno" readonly="" type="text" id="mrsno" value="<?php echo $mat_slip_no; ?>" /><input type="hidden" name="mrsid" id="mrsid" value="<?php echo $id; ?>"></td>
					<td align="right">MRS Date</td>
					<td><input name="mrsdate" readonly="" type="text" id="mrsdate" value="<?php echo ConvertSQLDate($date); ?>" /></td>
					<!-- <td>Job Card No.</strong></td>
    <td>
    	<?php
		$job_card_no = $s->GetFieldValue("job_card", "id='" . $job_card_id . "'", "job_card_no");
		$job_card_date = $s->GetFieldValue("job_card", "id='" . $job_card_id . "'", "job_date");

		?>
    	<input name="jobcardno" readonly="" type="text" id="jobcardno" value="<?php echo $job_card_no; ?>"     />
    	<input name="jobcardid" readonly="" type="hidden" id="jobcardid" value="<?php echo $job_card_id; ?>"     />

    </td> -->
				</tr>
				<tr class="row1">
					<td align="right">Store</td>
					<td><select name="to_store" id="to_store">
							<!-- <option value="0">Select</option> -->
							<?php
							$sql_to_store = "select * from storetype where id='" . $_REQUEST['store'] . "'";
							$result_to_store = DB_query($sql_to_store, $db);
							while ($rs_to_store = DB_fetch_array($result_to_store)) {
							?>
								<option value="<?php echo $rs_to_store['id']; ?>"><?php echo $rs_to_store['StoreName']; ?></option>

							<?php  }

							?>
						</select></td>
					<td style="text-align:right;"> Emp Name</strong></td>
					<td>
						<div id="empdta">
							<select name="received_by" id="received_by" onchange="Get_Employee(this.value)">
								<option value="0">Select</option>
								<?php

								$floor_sql = DB_query("Select * from empmaster where CompanyId='" . $_SESSION['ACGCompanyId'] . "' and emp_site ='" . $branch_id . "' order by emp_name ASC   ", $db);
								while ($floor_row = DB_fetch_array($floor_sql)) {
									$p = '';
									if ($floor_row['id'] == $received_by)
										$p = 'selected';

								?>
									<option value="<?php echo $floor_row['id']; ?>" <?php echo $received_by == $floor_row['id'] ? 'selected' : ''; ?>><?php echo $floor_row['emp_name']; ?></option>
								<?php
								}
								?>
							</select>
						</div>
					</td>
					<td style="text-align:right;">Department</td>
					<td>
						<div id="dept"><input type="text" name="dept1" id="dept1" readonly></div>
					</td>
				</tr>
			</table>

			<div id="showpickbuttonimport">
				<!--<input name="button" type="button" class="search" accesskey="A" onClick="addRow('dataTable')" value="Add Rows" />&nbsp;-->
				<!--<input type="button" name="profile_popup" value="Pick Items" id="profile_popup"  onclick="open_items()" accesskey="I" class="search" />&nbsp;
		<input type="button" class="search"  onclick="deleteRowOrder('dataTable')" value="Delete" />-->
			</div>

			<div style="overflow:auto; width:100%; margin:8px auto;">
				<div id="itemdata">
					<table width="100%" border="0" cellpadding="3" cellspacing="0" class="thborder">
						<tr>
							<th width="4%">S. No.</th>
							<th width="11%">Item Code</th>
							<th>Item Name</th>
							<th width="12%">Batch No.</th>
							<!--<th width="10%">UOM</th>
          <th width="10%" colspan="2"><center>Specification</center></th>-->
							<th width="9%">Stock</th>
							<th width="9%">Requested Qty.</th>
							<th style='text-align:center;' colspan='3'>Qty. to be issued</th>
							<!--<td width="10%"><strong>Issue Rate</strong></td>
		  <td width="10%"><strong>Total Amt</strong></td>-->
						</tr>
						<tbody id="dataTable">
							<?php
							//echo "Select * from material_job_item   where material_slip_id='".$id."'";
							$result = DB_query("Select * from material_job_item   where material_slip_id='" . $id . "'", $db);
							$i = 1;
							while ($row = DB_Fetch_array($result)) {

								$function_filter[0] = $_REQUEST['site'];
								$function_filter[1] = $to_store;
								$function_filter[2] = date('Y-m-d');

								$itemcode  = $s->GetFieldValue("item_master", "id='" . $row['mst_itemid'] . "'", "StockID");
								$item_name = $s->GetFieldValue("item_master", "id='" . $row['mst_itemid'] . "'", "item_name");
								$unitname = $s->GetFieldValue("unitsofmeasure", "unitid='" . $row['unit'] . "'", "unitname");
								$get_sec_unit = $s->GetFieldValue("item_master", "id='" . $row['mst_itemid'] . "'", "conv_unit");
								$unitname1 = $s->GetFieldValue("unitsofmeasure", "unitid='" . $get_sec_unit . "'", "unitname");
								$get_conv_factor = $s->GetFieldValue("item_master", "id='" . $row['mst_itemid'] . "'", "conv_factor");

								$batch_required  = $s->GetFieldValue("item_master", "id='" . $row['mst_itemid'] . "'", "batch_item");


								$op = openingBalance($function_filter, $row['mst_itemid']);
								$in_1 = receivedMRN($function_filter, $row['mst_itemid']);
								$out_1 = issueSlip($function_filter, $row['mst_itemid']);
								$out_2 = issueSiteToSite($function_filter, $row['mst_itemid']);
								$in_2 = receivedSiteToSite($function_filter, $row['mst_itemid']);
								$out_3 = issueMatarialReturn($function_filter, $row['mst_itemid']);
								$in_3 = receivedReturn($function_filter, $row['mst_itemid']);
								$out_4 = Rgpchallan($function_filter, $row['mst_itemid']);
								$out_5 = Nrgp($function_filter, $row['mst_itemid']);
								$in_4 = Rgpreturn($function_filter, $row['mst_itemid']);
								$in_5 = FinishedMR($function_filter, $row['mst_itemid']);
								$in_6 = MaterialConReceived($function_filter, $row['mst_itemid']);
								$out_6 = MaterialConIssue($function_filter, $row['mst_itemid']);
								$in_7 = PhysicalStockPlus($function_filter, $row['mst_itemid']);
								$out_7 = PhysicalStockMinus($function_filter, $row['mst_itemid']);
								$out_8 = dispatchIssue($function_filter, $row['mst_itemid']);
								$out_9 = jobWorkChallan57Issue($function_filter, $row['mst_itemid']);
								$in_8 = jobWorkChallan57Received($function_filter, $row['mst_itemid']);
								$in_9 = directPurchase($function_filter, $row['mst_itemid']);
								$in_10 = saleReturn($function_filter, $row['mst_itemid']);
								$out_10 = invoice($function_filter, $row['mst_itemid']);
								$out_11 = drugissue($function_filter, $row['mst_itemid']);

								//	$out_10=invoice($function_filter,$myrow['id']);
								$in_11 = storereceipt($function_filter, $row['mst_itemid']);
								$invalue = ($op + $in_1 + $in_2 + $in_3 + $in_4 + $in_5 + $in_6 + $in_7 + $in_8 + $in_9 + $in_10 + $in_11);
								$outvalue = ($out_1 + $out_2 + $out_3 + $out_4 + $out_5 + $out_6 + $out_7 + $out_8 + $out_9 + $out_10 + $out_11);
								$tot = $invalue - $outvalue;
								$stockallitems = $tot;

								$total_current = $tot;


								$sql_get_issued_data = "select sum(issueqty) from issueqty inner join addissue on addissue.id=issueqty.issue_id where mst_itemid='" . $row['mst_itemid'] . "' and mrs_id='" . $_REQUEST['mrsid'] . "'";
								$result_get_issued_data = DB_query($sql_get_issued_data, $db);
								$rs_get_issued_data = DB_fetch_array($result_get_issued_data);

								//echo "SELECT id,SUM(inwardqty_primary) as quantity,sum(outwardqty_primary) as outward,batch_no  FROM stock_valuation_tbl WHERE mst_itemid='".$row['mst_itemid']."' and store='".$_REQUEST['store']."'   GROUP BY batch_no ORDER BY trasaction";

								//$stockqty1=0;
								//	while ($stockdata = DB_Fetch_array($stockresult)) 
								//{	 
								//echo $stockdata[0];

								//$stockqty=0;
								//if($stockdata['quantity']=='')
								//continue;	
								//else
								// echo $stockqty = $stockdata['quantity']-$stockdata['outward'];
								//	
								//	$stockqty1 += $stockdata['quantity']; 
								// if( $row['item_qty']>$row['prodqty'] ) 
							?>
								<tr id="newrow_<?php echo $i; ?>">
									<td><?php echo $i; ?><input type="hidden" name="itemdataid[]" id="itemid_<?php echo $i; ?>" value="<?php echo $row['mst_itemid'];  ?>">
										<input type="hidden" name="confactor[]" id="convfactor_<?php echo $i; ?>" value="<?php echo $get_conv_factor; ?>">
									</td>
									<td><input type="text" name="itemname[]" readonly value="<?php echo $itemcode; ?>" id="itemname_<?php echo $i; ?>" /></td>
									<td><input type="text" name="itemcode[]" readonly value="<?php echo $item_name; ?>" id="itemcode_<?php echo $i; ?>" /></td>
									<td><input type="text" name="batch[]" placeholder="Double click to get batch list " readonly id="batchno_<?php echo $i; ?>" value="<?php //echo $stockdata['batch_no']; 
																																										?>" ondblclick="displayBatch(this.value,this.id)" /><input type="hidden" name="batchrequired[]" id="batchrequired_<?php echo $i; ?>" value="<?php echo $batch_required;  ?>" /></td>
									<td><input type="text" name="stock[]" readonly id="Stockbalance_<?php echo $i; ?>" value="<?php echo $total_current; ?>" /></td>
									<td width="10%"><input type="text" id="qty_<?php echo $i; ?>" name="qty[]" readonly value="<?php echo $row['primary_qty'] - $rs_get_issued_data[0]; ?>" /></td>
									<td width="10%"><input type="text" name="secqty[]" id="secqty_<?php echo $i; ?>" value="<?php echo ($row['primary_qty'] - $rs_get_issued_data[0]); ?>" /></td>
									<td width="10%"><select name="unit[]" id="unit_<?php echo $i; ?>">
											<option value="<?php echo $row['unit']; ?>"><?php echo $unitname; ?></option>
										</select></td>
									<!-- <td style="width:10%">
			                    <select name="secunit[]" id="secunit_<?php echo $i; ?>" >
			                        <option value="<?php echo $get_sec_unit; ?>"><?php echo $unitname1; ?></option>
			                     </select></td> -->
								</tr>
								<?php
								//}
								?>
							<?php
								$i++;
							}
							?>
						</tbody>
					</table>
				</div>
			</div>

			<input type="hidden" name="hiditemcount" id="hiditemcount" value="1" />
			<input type="hidden" name="" value="1" id="edit_cnt" />
			<input id="total_count" type="hidden" value="<?php echo $i - 1 ?>" />
			<table width="100%" border="0" cellpadding="3" cellspacing="0">
				<tr class="row1">
					<td align="right">Remarks</td>
					<td colspan="5"><textarea name="remarks" id="remark"></textarea></td>
				</tr>
				<tr class="row1">
					<td width="13%" align="right">Material Recd by</td>
					<td width="20%"><input name="material_received_by" type="text" id="material_rec" value="" /></td>
					<td width="13%" align="right">Material Issued by-</td>
					<td><?php echo $s->GetFieldValue('www_users', 'id="' . $_SESSION['UserID'] . '"', 'realname'); ?><input name="material_issue_by" type="hidden" id="material_issued" value="<?php echo $_SESSION['UserID']; ?>" readonly="true" /></td>
					<td colspan="2"></td>
				</tr>
			</table>
			<p align="center"><input type="submit" name="Submit" value="Save" class="search" onclick="return validate()" /> <input type="button" value="Cancel" name="Back" class="search" /></a></p>

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

<div id="lightbox1">
</div>
<script language="javascript" type="text/javascript">
	function isNumberKey(evt) {
		var charCode = (evt.which) ? evt.which : event.keyCode;
		if (charCode != 46 && charCode > 31 &&
			(charCode < 48 || charCode > 57))
			return false;

		return true;
	}

	function showconvac(str, id) {

		var brk = id.split('_');

		if (str == '0') {

			if (brk[1] == undefined) {
				var conf = document.getElementById('confactor').value;
				document.getElementById("confac").value = conf;
				var id1 = "issueqty";
				var hrdvalue = document.getElementById(id1).value;
				calamtNew(id1, hrdvalue);
			} else {
				var conf = document.getElementById('confactor_' + brk[1]).value;

				document.getElementById("confac_" + brk[1]).value = conf;
				var id1 = "issueqty_" + brk[1];
				var hrdvalue = document.getElementById(id1).value;
				calamtNew(id1, hrdvalue);
			}


		} else {
			var brk = id.split('_');

			var xmlhttp;
			if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp = new XMLHttpRequest();
			} else { // code for IE6, IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
					if (brk[1] == undefined) {
						document.getElementById("confac").value = xmlhttp.responseText;
						var id1 = "issueqty";
						var hrdvalue = document.getElementById(id1).value;
						calamtNew(id1, hrdvalue);
					} else {
						document.getElementById("confac_" + brk[1]).value = xmlhttp.responseText;
						var id1 = "issueqty_" + brk[1];
						var hrdvalue = document.getElementById(id1).value;
						calamtNew(id1, hrdvalue);
					}
					//document.getElementById("empdta").innerHTML=data[1];
					//var id1="stock_qty_"+brk[1];
					//var hrdvalue=document.getElementById(id1).value;
					//calcValue1(hrdvalue,id1);

				}
			}

			if (brk[1] == undefined) {
				var str2 = document.getElementById("itemid").value;
			} else {
				var str2 = document.getElementById("itemid_" + brk[1]).value;
			}
			xmlhttp.open("GET", "convactor.php?site=" + str + "&itemid=" + str2, true);
			xmlhttp.send();

		}




	}

	function calamtNew(value, obj) {
		var stock = parseInt($(obj).closest('tr').find('td:eq(5)').find('input').val());
		var val = parseInt(value);
		//alert(stock);
		if (stock < value) {
			alert("Quantity can not be greater then stock");
			$(obj).closest('tr').find('td:eq(6)').find('input').val("");
			//$(obj).closest('tr').find('td:eq(9)').find('input').val("");
			return false;

		}
		// var unit=$(obj).closest('tr').find('td:eq(9)').find('input').attr('data');
		var unit = $(obj).closest('tr').find('td:eq(8)').find('input').val();
		// alert(unit);
		var total = parseFloat(value * unit);
		//alert(total);
		$(obj).closest('tr').find('td:eq(9)').find('input').val(total);
		var rates = $(obj).closest('tr').find('td:eq(13)').find('input').val();
		var total = '';
	}




	function getSubGrp(id) {

		$.post('getItemList.php', {
			"subgrp": id,
			"subdis": 'yes'
		}, function(data) {

			$('#subcategory').html(data);
		});
	}

	function getdataforSearchItem() {
		//$('#ItemListDiv').html('<center><span style="font-size:20px;"><strong>Loading...</strong></span></center>');
		var mainCategoryId = $('#lightbox1').find('select[name=category]').val();
		var subCategoty_id = $('#lightbox1').find('select[name=subcategory]').val();
		var item_name = $('#lightbox1').find('input[id=itemname]').val();
		var item_short_code = $('#lightbox1').find('input[id=itemcode]').val();


		var site = document.getElementById('sitecode').value;
		var store = document.getElementById('store').value;
		var issuedate = document.getElementById('issuedate').value;

		// alert(site+"  = "+store+"  "+issuedate);




		//alert(subCategoty_id);
		$('#lightbox1').html('<center><span style="font-size:20px;"><strong>Loading...</strong></span></center>');

		$.ajax({
			url: "crmquotes2_exotic_issue.php",
			type: "POST",
			data: {
				site: site,
				mainCategoryid: mainCategoryId,
				subCategoryid: subCategoty_id,
				itemName: item_name,
				itemScode: item_short_code,
				store: store,
				issuedate: issuedate,
				forfilter: 10
			},
			success: function(data) { //alert(data);
				$('#lightbox1').html(data);
			}
		});

	}

	function open_items() {
		if ($('#sitecode').val() == 0) {
			alert('Please select branch.');
			return false;
		}
		if ($('#store').val() == 0 || $('#store').val() == '') {
			alert('Please select store.');
			return false;
		}

		var site = $('#sitecode').val();
		var store = $('#store').val();
		var issuedate = $('#issuedate').val();


		//window.open("crmquotes2_exotic_issue.php?action=add&modid=<?php echo $_REQUEST['modid']; ?>&frmid=<?php echo $_REQUEST['frmid']; ?>&site="+site+"&stote="+store,"item_popup_window","height=500,width=500,left=1111px,toolbar=no,menubar=no,dependent=yes,resizable =yes, scrollbars=yes");


		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

				$("#lightbox1").dialog({
					title: 'Item List',
					modal: true,
					resizable: false,
					width: 1000,
					height: 500,
					closeText: 'fechar',
					draggable: true,
					show: 'fade',
					hide: 'fade',
					dialogClass: 'main-dialog-class',
					buttons: {
						Exit: function() {
							$(this).dialog("close");
						}
					}
				});

				//alert(xmlhttp.responseText);
				document.getElementById("lightbox1").style.display = 'block';
				document.getElementById("lightbox1").innerHTML = xmlhttp.responseText;
				// document.getElementById("textitem").innerHTML=data[1];	
				// alert();








			}
		}
		// var store=document.getElementById("storeTo").value;




		xmlhttp.open("GET", "crmquotes2_exotic_issue.php?action=add&modid=<?php echo $_REQUEST['modid']; ?>&frmid=<?php echo $_REQUEST['frmid']; ?>&site=" + site + "&store=" + store + "&issuedate=" + issuedate, true);
		xmlhttp.send();

	}


	function displayBatch(value, id) {
		// alert("The paragraph was double-clicked."); 
		// alert(value+"  "+id);
		//alert(id);
		var itemcode = '';
		var itemname = '';
		//var unit='';
		var item_ids = '';

		if (id.indexOf('_') != '-1') {
			var ids = id.split('_');
			itemcode = document.getElementById('itemcode_' + ids[1]).value;
			itemname = document.getElementById('itemname_' + ids[1]).value;
			//unit = document.getElementById('uom_'+ids[1]).value;
			//unit1 = document.getElementById('uom1_'+ids[1]).value;
			item_ids = document.getElementById('itemid_' + ids[1]).value;

		} else {
			itemcode = document.getElementById('itemcode').value;
			itemname = document.getElementById('itemname').value;
			//unit = document.getElementById('uom_').value;
			// unit1 = document.getElementById('uom1_').value;
			item_ids = document.getElementById('itemids').value;

		}

		if (itemcode == '') {
			alert("Please select items");
		} else if (itemname == '') {
			alert("Please enter itemname");
		}
		/* else if(unit=='')
		 {
		   alert("Please enter unit");
		 } */
		else {
			//var LeaveType=document.getElementById("LeaveType_"+tt2).value;
			$("#lightbox1").dialog({
				title: 'Batch List',
				modal: true,
				resizable: false,
				width: 900,
				height: 400,
				closeText: 'fechar',
				draggable: true,
				show: 'fade',
				hide: 'fade',
				dialogClass: 'main-dialog-class',
				buttons: {
					Exit: function() {
						$(this).dialog("close");
					}
				}
			});

			var site = document.getElementById("sitecode").value;
			var store = document.getElementById("store").value;
			//var invoiceTime=$('#invoiceTime').val();
			//alert('Getstock_items_store.php?site='+site+'&invoicedate='+invoicedate+'&invoiceTime='+invoiceTime);
			$.ajax({
				url: 'getItemBatch.php?item_id=' + item_ids + '&batch_id=' + id + '&site=' + site + '&store=' + store,
				success: function(result) {
					$('#lightbox1').html(result);
				}
			});
		}
	}


	function addBatchData(id, value, unit, batch, mfg, expiry) {
		//alert(value);
		if (id.indexOf("_") != "-1") {
			var ids = id.split('_');
			if ($('#Stockbalance_' + ids[1]).val() != '') {

				var batch_no = new Array();
				jQuery('input[id^=batchno_]').each(function() {
					batch_no.push(parseInt(jQuery(this).val()));
					//alert(partic_pack);
				});

				for (var i = 0; i < batch_no.length; i++) {
					if (batch_no[i] == batch) {
						alert('Batch  Is All Ready Selected.');
						return false;
					}
				}

				//alert(a);
				var batchano = document.getElementById('batchno_' + ids[1]).value;
				if (batchano != '') {
					var thisRow = $('#batchno_' + ids[1]).closest('tr')[0];
					$(thisRow).clone().insertAfter(thisRow).find('input:text');
					$('#Stockbalance_' + ids[1]).val(value);
					$('#batchno_' + ids[1]).val(batch);
				} else {
					$('#Stockbalance_' + ids[1]).val(value);
					$('#batchno_' + ids[1]).val(batch);
				}



			} else {
				$('#Stockbalance_' + ids[1]).val(value);
				$('#batchno_' + ids[1]).val(batch);
			}
		} else {
			if ($('#stock').val() != '') {
				var thisRow = $("#batchno").closest('tr')[0];
				$(thisRow).clone().insertAfter(thisRow).find('input:text');
				$('#stock').val(value);
				$('#batchno').val(batch);
				$('#dateofmfg').val(mfg);
				$('#dateofexpiry').val(expiry);
			} else {
				$('#stock').val(value);
				$('#batchno').val(batch);
				$('#dateofmfg').val(mfg);
				$('#dateofexpiry').val(expiry);
			}
		}

		$('.datepicker').removeClass('hasDatepicker').datepicker({
			dateFormat: 'dd/mm/yy',
			changeMonth: true,
			changeYear: true,
			yearRange: '-80:+20'
		});
	}









	/*var xmlHttp

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	  }
	catch (e)
	  {
	  // Internet Explorer
	  try
		{
		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
	  catch (e)
		{
		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	  }
	return xmlHttp;
}*/

	function getsitename(str) {
		if (str.length == 0) {
			document.getElementById("txtsite").innerHTML = "";
			return;
		}
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("txtsite").innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.open("GET", "get_sitename.php?site=" + str, true);
		xmlhttp.send();
	}

	function getsitename22(str) {
		if (str.length == 0) {
			document.getElementById("txtsite22").innerHTML = "";
			return;
		}
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("txtsite22").innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.open("GET", "get_sitename.php?q2=" + str, true);
		xmlhttp.send();
	}

	function Get_issuedetails(str) {
		if (str.length == 0) {
			document.getElementById("issueid").innerHTML = "";
			return;
		}
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("issueid").innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.open("GET", "get_IssueDetails.php?q=" + str, true);
		xmlhttp.send();
	}

	function getpartyname(str) {
		//alert(str);
		var hidparty = document.getElementById("hidden_party").value;
		//alert(hidparty);
		if (str.length == 0) {
			document.getElementById("pname").innerHTML = "";
			return;
		}
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("pname").innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.open("GET", "get_IssuePartyName.php?name=" + str + "&partytype=" + hidparty, true);
		xmlhttp.send();
	}


	function get_referredby(str) {
		if (str.length == 0) {
			document.getElementById("rname").innerHTML = "";
			return;
		}
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("rname").innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.open("GET", "get_IssueEmployeeName.php?q=" + str, true);
		xmlhttp.send();
	}

	var xmlHttp

	function requisition_detail(str) {
		//alert(str);
		xmlHttp = GetXmlHttpObject();
		if (xmlHttp == null) {
			alert("Your browser does not support AJAX!");
			return;
		}
		var url = "reqdetail.php";
		url = url + "?req_number=" + str;

		//url=url+"&sid="+Math.random();
		xmlHttp.onreadystatechange = changedetail;

		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}

	function changedetail() {
		if (xmlHttp.readyState == 4) {
			var responsestr = xmlHttp.responseText;
			resstr = responsestr.split("@@##@");
			document.getElementById("reqdate").value = resstr[0];
			document.getElementById("txtdetail").innerHTML = resstr[1];

		}
	}

	function calculateTotalAmount(str) {
		var str_BRK = str.split('_');
		if (str_BRK[1] == undefined) {
			var issue = document.getElementById("issueqty").value;
			var average = document.getElementById("averageamt").value;
			var TOTAL = issue * average;
			document.getElementById("totalamount").value = TOTAL.toFixed(2);
		} else {
			var issue = document.getElementById("issueqty_" + str_BRK[1]).value;
			var average = document.getElementById("averageamt_" + str_BRK[1]).value;
			var TOTAL = issue * average;
			document.getElementById("totalamount_" + str_BRK[1]).value = TOTAL.toFixed(2);
		}
	}

	function Get_departmentdetails(str) {

		if (str == "") {
			document.getElementById("department").innerHTML = "";
			return;
		}
		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("department").value = xmlhttp.responseText;

			}
		}
		//alert(str);
		xmlhttp.open("GET", "get_department.php?department=" + str, true);
		xmlhttp.send();

		//xmlhttp.open("GET","getSort.php?s="+str+"&cat="+cat,true);

	}

	function showdept(str) {
		if (str == "") {
			document.getElementById("dept").innerHTML = "";
			return;
		}
		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

				document.getElementById("dept").innerHTML = xmlhttp.responseText;

			}
		}

		xmlhttp.open("GET", "get_empdata.php?department=" + str, true);
		xmlhttp.send();


	}

	function calTotal1(str) {
		var k = parseFloat(document.getElementById('issueqty_' + str).value);
		var j = parseFloat(document.getElementById('Stockbalance_' + str).value);
		if (j < k) {
			alert("Issue Qty Not Grater then Stock Balance");
			document.getElementById('issueqty_' + str).focus();
		}
	}

	function calTotal(obj) {

		var k = parseFloat(document.getElementById('issueqty_' + obj).value);
		var j = parseFloat(document.getElementById('Stockbalance_' + obj).value);
		if (j < k) {
			alert("Issue Qty Not Grater then Stock Balance");
			document.getElementById('issueqty_' + obj).focus();
		}

	}

	function Get_contractor(str) {
		//alert(str);
		if (str != '') {
			var element = document.getElementById("received_by");
			element.style.display = "none";
		} else {
			var element = document.getElementById("received_by");
			element.style.display = "";
		}

	}

	function Get_Employee(str) {


		if (str == "") {
			document.getElementById("dept").innerHTML = "";
			return;
		}
		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

				document.getElementById("dept").innerHTML = xmlhttp.responseText;

			}
		}

		xmlhttp.open("GET", "get_empdata.php?department=" + str, true);
		xmlhttp.send();

	}


	function Get_oderdata(str) {


		if (str == "") {
			document.getElementById("dept").innerHTML = "";
			return;
		}
		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var data = xmlhttp.responseText.split("__");
				document.getElementById("oderitem").innerHTML = data[0];
				document.getElementById("jobcarddata").innerHTML = data[1];
			}
		}

		xmlhttp.open("GET", "get_orderdata.php?salid=" + str, true);
		xmlhttp.send();

	}

	function Get_jobcard(str) {


		if (str == "") {
			document.getElementById("dept").innerHTML = "";
			return;
		}
		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var data = xmlhttp.responseText.split("__");
				document.getElementById("jobcarddate1").innerHTML = data[0];
				document.getElementById("issue_req").innerHTML = data[1];
			}
		}

		xmlhttp.open("GET", "get_jobcard.php?jobid=" + str, true);
		xmlhttp.send();

	}

	function Get_jobcard1(str) {
		var site = document.getElementById("sitecode").value;
		var store = document.getElementById("store").value;
		if (str == "0") {
			document.getElementById("para").style.display = "block";
		} else {
			document.getElementById("para").style.display = "hidden";
		}
		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				//alert(xmlhttp.responseText);
				var data = xmlhttp.responseText.split("__");
				document.getElementById("issue_req1").innerHTML = data[0];
				document.getElementById("workod").innerHTML = data[1];
				document.getElementById("orderitem").innerHTML = data[2];
				document.getElementById("cost_center").value = data[3];
				document.getElementById("dataTable").innerHTML = data[4];
				document.getElementById("indentid").innerHTML = data[5];
			}
		}

		xmlhttp.open("GET", "get_jobcard1.php?jobid=" + str + "&site=" + site + "&store=" + store, true);
		xmlhttp.send();

	}


	function chkbalance(str) {
		//alert(str);
		var k = parseFloat(document.getElementById('Stockbalance_' + str).value);

		var j = parseFloat(document.getElementById('issueqty_' + str).value);
		//alert(document.getElementById('Stockbalance_0').value);
		if (isNaN(document.getElementById('issueqty_' + str).value)) {
			alert("String Not Allowed");
			document.getElementById('issueqty_' + str).value = '';
			return false;
		}

		if (j > k) {
			alert("Issue Qty Not Grater then Stock Balance");
			document.getElementById('issueqty_' + str).value = '';
			document.getElementById('issueqty_' + str).focus();
		}


	}

	function validate() {
		var count123 = 0;

		jQuery('input[id^=batchno_]').each(function() {
			var stock = jQuery(this).val();
			if (stock == '') {
				count123 += 1;
			}
		});

		if (parseInt(count123) > 0) {
			alert("Please Select Batch");
			return false;
		}



		var rowCount = 0;
		if (document.getElementById("sitecode").value == '0') {
			alert("Must Select Branch Name");
			document.getElementById("sitecode").focus();
			return false;
		}
		if (document.getElementById("store").value == '0') {
			alert("Please Select from Store");
			document.getElementById("store").focus();
			return false;
		}
		if (document.getElementById("to_store").value == '0') {
			alert("Please Select To Store");
			document.getElementById("to_store").focus();
			return false;
		}


		var count = document.getElementById("total_count").value;
		// alert(count);

		for (var l = 1; l <= count; l++) {
			if (document.getElementById("batchrequired_" + l).value == 'Y') {
				if (document.getElementById("batchno_" + l).value == '') {
					alert("Please Select batch No.");
					return false;
				}
			}
		}



		var count12 = 0;

		jQuery('input[id^=Stockbalance_]').each(function() {
			var id = this.id;
			var idk = id.split("_");
			var qty = document.getElementById("qty_" + idk[1]).value;
			var stock = jQuery(this).val();
			if (parseFloat(qty) > parseFloat(stock)) {
				if (count12 == 0)
					alert("Qty cannot be greater than stock");

				count12++;
			}
		});

		if (count12 > 0)
			return false;

		var countt12 = 0;

		jQuery('input[id^=qty_]').each(function() {

			var id = this.id;
			var idk = id.split("_");
			//var qty = document.getElementById("qty_"+idk[1]).value;


			var secqty = document.getElementById("secqty_" + idk[1]).value;

			var qty = jQuery(this).val();

			if (parseFloat(secqty) > parseFloat(qty)) {

				if (countt12 == 0)
					alert("Issue quantity cannot be greater than Pending Qty");

				countt12++;
			}
		});

		if (countt12 > 0)
			return false;

	}

	function showsitename158(str) {

		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var data = xmlhttp.responseText.split("__");

				document.getElementById("hid-Godown-div").innerHTML = data[0];
				document.getElementById("empdta").innerHTML = data[1];
				//document.getElementById("jobcard").innerHTML=data[2];

			}
		}
		xmlhttp.open("GET", "GoDownIssueSlip.php?site=" + str, true);
		xmlhttp.send();

		//xmlhttp.open("GET","getSort.php?s="+str+"&cat="+cat,true);


	}

	function checkdata() {
		if (document.getElementById("sitecode").value == '0') {
			alert("Must Select Branch Name");
			return false;
		}
		window.open("issu_searchpopupnew.php?1=1<?php echo $rurl; ?>&site=<?php echo $_SESSION['site'] ?>&store=<?php echo $_SESSION['godwan']; ?>", "profiles_popup_window", "height=425,width=600,toolbar=no,menubar=no,dependent=yes,resizable=yes");

		return true;
	}


	function calculateAmt(i) {
		var IssueQty = document.getElementById("issueqty_" + i).value;
		var AverageRate = document.getElementById("averagerate_" + i).value;
		var Amount1 = parseFloat(IssueQty) * parseFloat(AverageRate);
		document.getElementById("amount1_" + i).value = Amount1.toFixed(2);
	}
</script>

<script language="javascript" type="text/javascript">
	function Remaningqtn(str) {

		var StockBalance = document.getElementById("Stockblance_" + i).value;
		var Issuequantity = document.getElementById("issuebalanc_" + i).value;
		var RemaningBalance = parseFloat(StockBalance) - parseFloat(Issuequantity);
		document.getElementById("remaningbalance_" + i).value = RemaningBalance;
	}

	//var countries=new ddtabcontent("countrytabs")
	//countries.setpersist(true)
	//countries.setselectedClassTarget("link") //"link" or "linkparent"
	//countries.init();
	function GetXmlHttpObject() {
		var xmlHttp = null;
		try {
			// Firefox, Opera 8.0+, Safari
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			// Internet Explorer
			try {
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		return xmlHttp;
	}


	var xmlHttp

	function changestorename(str) {
		// alert('hi');
		xmlHttp = GetXmlHttpObject();
		if (xmlHttp == null) {
			alert("Your browser does not support AJAX!");
			return;
		}
		var url = "storename.php";
		url = url + "?store_code=" + str;
		//alert(url);
		//url=url+"&sid="+Math.random();
		xmlHttp.onreadystatechange = NumberChanged1;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}

	function NumberChanged1() {
		if (xmlHttp.readyState == 4) {
			document.getElementById("txtid").innerHTML = xmlHttp.responseText;
		}
	}

	function GetXmlHttpObject() {
		var xmlHttp = null;
		try {
			// Firefox, Opera 8.0+, Safari
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			// Internet Explorer
			try {
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		return xmlHttp;
	}
</script>
<script language="javascript" type="text/javascript">
	function addRow(tableID) {
		if (document)
			var table = document.getElementById(tableID);

		var rowCount1 = table.rows.length;
		var row = table.insertRow(rowCount1);
		if (document.getElementById("hiditemcount").value == '')
			rowCount = rowCount1 + 1;
		else {
			var t1 = document.getElementById("hiditemcount").value;
			rowCount = parseInt(t1) + 1;
		}
		document.getElementById("hiditemcount").value = rowCount;
		var colCount = table.rows[0].cells.length;
		for (var i = 0; i < colCount; i++) {

			var newcell = row.insertCell(i);
			//newcell.style.background='#e7e7e7';
			//  newcell.className='tabledata';
			newcell.innerHTML = table.rows[0].cells[i].innerHTML;
			switch (newcell.childNodes[0].type) {
				case "text":
					newcell.childNodes[0].value = "";
					//var nod_id = newcell.childNodes[0].id;
					var nod_id = newcell.childNodes[0].id.split("_");
					if (!isNaN(nod_id[1]))
						newcell.childNodes[0].id = nod_id[0] + '_' + rowCount;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rowCount;

					//newcell.childNodes[0].id = newcell.childNodes[0].id+'_'+rowCount;

					break;

				case "hidden":

					newcell.childNodes[0].value = "";

					var nod_id = newcell.childNodes[0].id.split("_");
					if (!isNaN(nod_id[1]))
						newcell.childNodes[0].id = nod_id[0] + '_' + rowCount;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rowCount;

					break;

				case "button":

					var nod_id = newcell.childNodes[0].id.split("_");
					if (!isNaN(nod_id[1]))
						newcell.childNodes[0].id = nod_id[0] + '_' + rowCount;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rowCount;

					break;

				case "checkbox":

					newcell.childNodes[0].checked = false;
					var nod_id = newcell.childNodes[0].id.split("_");
					if (!isNaN(nod_id[1]))
						newcell.childNodes[0].id = nod_id[0] + '_' + rowCount;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rowCount;


					break;

				case "select-one":

					newcell.childNodes[0].selectedIndex = 0;
					var nod_id = newcell.childNodes[0].id.split("_");
					if (!isNaN(nod_id[1]))
						newcell.childNodes[0].id = nod_id[0] + '_' + rowCount;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rowCount;
					break;
			}
		}
	}

	function deleteRowOrder(tableID) {
		try {
			var table = document.getElementById(tableID);
			//alert(table);
			var rowCount = table.rows.length;
			//alert(rowCount);
			for (var i = 0; i < rowCount; i++) {
				var row = table.rows[i];
				var chkbox = row.cells[0].childNodes[0];
				if (null != chkbox && true == chkbox.checked) {
					if (rowCount <= 1) {
						alert("Cannot delete all the rows.");
						break;
					}
					table.deleteRow(i);
					rowCount--;
					i--;
				}

			}
			document.getElementById("hiditemcount").value = parseInt(rowCount) - 1;
		} catch (e) {
			alert(e);
		}

	}

	function opendata(str, id) {
		var store = document.getElementById("store").value;
		var sitecode = document.getElementById("sitecode").value;
		var date = document.getElementById("issuedate").value;

		if (str.length == 0) {
			document.getElementById("lightbox").innerHTML = "";
			document.getElementById("lightbox").style.border = "0px";
			return;
		}

		if (sitecode == '0') {
			alert("Must Select Site");
			document.getElementById("sitecode").focus();
			return;
		} else if (date == '') {
			alert("Must Select Date");
			document.getElementById("issuedate").focus();
			return;
		}

		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				data = xmlhttp.responseText;
				document.getElementById("abc").style.display = 'block';
				document.getElementById("abc").innerHTML = data;

				// document.getElementById("textitem").innerHTML=data[1];

			}
		}
		var store = document.getElementById("store").value;
		var sitecode = document.getElementById("sitecode").value;
		var date = document.getElementById("issuedate").value;

		xmlhttp.open("GET", "showpopup.php?site=" + str + "&data=" + id + "&store=" + store + "&site1=" + sitecode + "&date=" + date, true);
		xmlhttp.send();




	}


	function getItemsList(id, code, shade, netrate, mrprate, ctra, stock) {
		//alert(ctra);
		var ctr = $('#dataTable').find('tr:last').find('td:eq(1)').find('input[type="text"]').attr('id');
		var rowCount = $('#dataTable').find('tr').length;
		var rowItem = $('#dataTable').find('tr').find('td:eq(2)').find('input[type="hidden"]').val();


		var ctr1 = parseInt(document.getElementById("hiditemcount").value) + 1;

		var itemcount = parseInt(document.getElementById('hiditemcount').value) + 1;
		var edit_cnt = document.getElementById('edit_cnt').value;
		if (edit_cnt == '') {
			var counter = 1;
		} else if (edit_cnt > itemcount) {
			var counter = edit_cnt;
			var itemcount = parseFloat(counter) + parseFloat(itemcount);

		} else {
			var counter = edit_cnt;
		}


		if (document.getElementById('itemid_1').value == '') {
			document.getElementById('itemid_1').value = id;
			document.getElementById('itemcode_1').value = code;
			document.getElementById('itemname_1').value = shade;
			document.getElementById('uom_1').innerHTML = netrate;
			document.getElementById('uom1_1').innerHTML = mrprate;
			document.getElementById('confac_1').value = ctra;
			document.getElementById('Stockbalance_1').value = stock;

			//document.getElementById('Stockbalance_1').value = mrprate;
		} else {
			var i = ctr1;
			//alert(i);
			addRow('dataTable');
			//for(i=counter; i<itemcount; i++)
			//{
			if (document.getElementById('itemcode_' + i).value == '') {
				document.getElementById('itemid_' + i).value = id;
				document.getElementById('itemcode_' + i).value = code;
				document.getElementById('itemname_' + i).value = shade;
				document.getElementById('uom_' + i).value = netrate;
				document.getElementById('uom1_' + i).value = netrate;
				document.getElementById('confac_' + i).value = ctra;
				document.getElementById('Stockbalance_' + i).value = stock;

				//document.getElementById('Stockbalance_'+i).value = mrprate;
				//break;
			} else {
				//continue;
			}
			//}
		}

		//document.getElementById("lightbox1").style.display='none';

	}

	function getItemsList1(id, code, shade, netrate, secondary, confac, mrprate, rate, ctr) {
		var data = addRow('dataTable');
		var ctr1 = ctr.split("_");
		var i = ctr1[1]
		var itemcount = parseInt(document.getElementById('hiditemcount').value) + 1;
		var edit_cnt = document.getElementById('edit_cnt').value;
		if (edit_cnt == '') {
			var counter = 1;
		} else if (edit_cnt > itemcount) {
			var counter = edit_cnt;
			var itemcount = parseFloat(counter) + parseFloat(itemcount);
		} else {
			var counter = edit_cnt;
		}

		if (ctr1[1] == undefined) {
			//if(document.getElementById('itemdataid').value=='')
			//{

			document.getElementById('itemdataid').value = id;
			document.getElementById('itemcode').value = code;
			document.getElementById('descriptions').value = shade;
			document.getElementById('uom').value = netrate;
			document.getElementById('secondary').value = secondary;
			document.getElementById('confac').value = confac;
			document.getElementById('Stockbalance').value = mrprate;
			document.getElementById("issuerate").value = rate;
			//}
		} else {
			//if(document.getElementById('itemdataid_'+i).value=='')
			//{		
			document.getElementById('itemdataid_' + i).value = id;
			document.getElementById('itemcode_' + i).value = code;
			document.getElementById('descriptions_' + i).value = shade;
			document.getElementById('uom_' + i).value = netrate;
			document.getElementById('secondary_' + i).value = secondary;
			document.getElementById('confac_' + i).value = confac;
			document.getElementById('Stockbalance_' + i).value = mrprate;
			document.getElementById("issuerate_" + i).value = rate;
			//}	
		}

		document.getElementById("abc").style.display = 'none';


	}
</script>


<script src="js/jquery.min.js"></script>
<script src="js/jquery.bpopup-0.7.0.min.js"></script>
<script src="js/scripting.min.js"></script>
<script>
	function hidedata() {
		document.getElementById("abc").style.display = 'none';
	}


	function calamt1(id, str) {
		var id1 = id.split("_");
		var i = id1[1];
		if (id1[1] == undefined) {
			if (document.getElementById("confac").value != '')
				var confac = parseFloat(document.getElementById("confac").value);
			else
				var confac = 0;

			var total2 = parseFloat(str) / confac;
			document.getElementById("issueqty").value = total2.toFixed(2);
			if (parseFloat(document.getElementById("Stockbalance").value) < parseFloat(document.getElementById("secondaryqty").value)) {
				alert("Issue qty should not be greater than stock qty");
				document.getElementById("secondaryqty").focus();
				document.getElementById("secondaryqty").value = '';
				document.getElementById("totalamt").value = '';
				document.getElementById("issueqty").value = '';
				return;
			}
			if (document.getElementById("issuerate").value != '')
				var issuerate = parseFloat(document.getElementById("issuerate").value);
			else
				var issuerate = 0;
			var total = parseFloat(str) * issuerate;
			document.getElementById("totalamt").value = total.toFixed(2);
		} else {
			if (document.getElementById("confac_" + i).value != '')
				var confac = parseFloat(document.getElementById("confac_" + i).value);
			else
				var confac = 0;
			var total2 = parseFloat(str) / confac;
			document.getElementById("issueqty_" + i).value = total2.toFixed(2);
			if (parseFloat(document.getElementById("Stockbalance_" + i).value) < parseFloat(document.getElementById("secondaryqty_" + i).value)) {
				alert("Issue qty should not be greater than stock qty");
				document.getElementById("secondaryqty_" + i).focus();
				document.getElementById("secondaryqty_" + i).value = '';
				document.getElementById("totalamt_" + i).value = '';
				return;
			}
			if (document.getElementById("issuerate_" + i).value != '')
				var issuerate = parseFloat(document.getElementById("issuerate_" + i).value);
			else
				var issuerate = 0;
			var total = parseFloat(str) * issuerate;
			document.getElementById("totalamt_" + i).value = total.toFixed(2);
		}

	}

	function Get_oderdata1(str) {
		if (str == "") {
			document.getElementById("dept").innerHTML = "";
			return;
		}
		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

				document.getElementById("jobcarddate1").innerHTML = xmlhttp.responseText;

			}
		}

		xmlhttp.open("GET", "get_joborderdata.php?salid=" + str, true);
		xmlhttp.send();

	}

	function check_qty(strid, strval) {
		var strid1 = strid.split("_");
		var i = strid1[1];

		if (strval > parseInt(document.getElementById("Stockbalance_" + i).value)) {
			alert("Primary Issued Qty not more than Stock Qty.");
			document.getElementById(strid).value = "";
			document.getElementById(strid).focus();
			return false;
		}

		if (strval > parseInt(document.getElementById("receive_" + i).value)) {
			alert("Primary Issued Qty not more than Req Qty.");
			document.getElementById(strid).value = "";
			document.getElementById(strid).focus();
			return false;
		}
		if (document.getElementById("confac_" + i).value == '') {
			var secval = strval * 1;
		} else {
			var secval = strval * document.getElementById("confac_" + i).value;
		}
		document.getElementById("secondaryqty_" + i).value = secval;

		var str = document.getElementById("primaryqty_" + i).value;
		if (document.getElementById("issuerate_" + i).value != '')
			var issuerate = document.getElementById("issuerate_" + i).value;
		else
			var issuerate = 0;
		var total = parseFloat(str) * issuerate;
		document.getElementById("totalamt_" + i).value = total.toFixed(2);

		return true;
	}

	function calamt2(strid, strval) {
		var strid1 = strid.split("_");
		var i = strid1[1];
		var str = document.getElementById("primaryqty_" + i).value;

		if (document.getElementById(strid).value != '')
			var issuerate = strval;
		else
			var issuerate = 0;
		var total = parseFloat(str) * issuerate;
		document.getElementById("totalamt_" + i).value = total.toFixed(2);
		return true;
	}

	function isNumberKey(evt) {
		var charCode = (evt.which) ? evt.which : event.keyCode;
		if (charCode != 46 && charCode > 31 &&
			(charCode < 48 || charCode > 57))
			return false;

		return true;
	}
</script>