<script type="text/javascript" language="javascript">
	function selectFunction(val, id) {
		var str = id.split("_");

		var stid = document.getElementById('Stockbalance_' + str[1]).value;
		var val = document.getElementById('adj_' + str[1]).value;
		if (stid != '0') {
			if (val == 'plus') {
				document.getElementById('adj').value = 'plus';
			} else {
				document.getElementById('adj').value = 'plus';
			}
		} else {}
		chk_recived_qty('', id);
	}


	function deleteRow_return(tableID) {

		if ($('#' + tableID).find('input[type="checkbox"][name="delitem[]"]:checked').length > 0) {
			try {
				var table = document.getElementById(tableID);
				//alert(table);
				var rowCount = table.rows.length;

				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--;
					}
				}

			} catch (e) {
				alert(e);
			}
		} else
			alert('Please select at least one row for delete.');
	}

	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 GetStore(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) {
				data = xmlhttp.responseText;
				document.getElementById("store").innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.open("GET", "ajax_getstore.php?site=" + str, true);
		xmlhttp.send();
	}

	function chkitemsstock(str) {


		/*var site=document.getElementById("site").value;
		var date1=document.getElementById("textfield2").value;
		var hidcnt=document.getElementById("hiditemcount").value;
		var arritems=new Array();
		if(hidcnt!='')
		{
			for(var i=1;i<=hidcnt;i++)
			{
				if(document.getElementById("itemdataid_"+i).value!='')
				{
					arritems[i]=document.getElementById("itemdataid_"+i).value;
				}
				
			}
		}
		itemid=document.getElementById("itemdataid").value;
		if(itemid!='')
		{
				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("__");
						if(data[0])
						{
							document.getElementById("Stockbalance").value=data[0];
						}
						if(data[1])
						{
							var sp=data[1].split(",");
							var arrlength=sp.length;
							for(var t=0;t<arrlength;t++)
							{	var r=t+1;
								document.getElementById("Stockbalance_"+r).value=sp[t];
							}
						}
					}
				}
				xmlhttp.open("GET","ajax_getstock.php?site="+site+"&storeid="+str+"&date2="+date1+"&FirstItemsId="+itemid+"&itemsids="+arritems,true);
				xmlhttp.send();
		}*/


	}
</script>
<link rel="stylesheet" href="css/new_mxerp.css">
<?php
ob_start();
include('cocoon_config.php');
function getFieldvalue_cake($table, $condition, $val, $field)
{
	global $db;
	//echo "select ".$field." from ".$table." where ".$condition." ='".$val."'";
	$sql = mysqli_query($db, "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($_REQUEST['Save'])) {
	//echo '<pre>'; print_r($_REQUEST);die;

	date_default_timezone_set('Asia/Calcutta');
	$financial = substr($_SESSION['YearStart'], -2) . "-" . substr($_SESSION['YearEnd1'], -2);
	$prefix = $s->GetFieldValue('locations', "loccode='" . $_REQUEST['site'] . "'", 'prefix');


	$sql = "Select ADJ_voucher_no from physical_stock where site='" . $_REQUEST['site'] . "' 
	and INSTR(`ADJ_voucher_no`, '$financial') > 0 order by ADJ_voucher_no desc limit 0,1";

	$result = DB_query($sql, $db);
	$myrow = DB_fetch_array($result);
	//echo DB_num_rows($result);
	if (DB_num_rows($result) > 0) {
		//$Reqno=$myrow['Reqno'];
		//$req_part1=substr($Reqno,-4);
		$ExplBill = explode("/", $myrow['ADJ_voucher_no']);
		$maxval = $ExplBill[3];
		//echo $req_part1;
		$next_digit = $maxval + 1;
		//echo "<br>".$req_final;
	} else {
		$next_digit = "1";
	}

	$string = 'PHY/';
	$final_string = $prefix . '/' . $string . $financial . '/' . str_pad($next_digit, 4, "0", STR_PAD_LEFT);
	/////echo $_REQUEST['date'];
	////echo FormatDateForSQL($_REQUEST['date']);die;
	$datap['site'] = $_REQUEST['site'];
	$datap['ADJ_voucher_no'] = $final_string;
	$datap['date1'] = FormatDateForSQL($_REQUEST['date']);
	$datap['store'] = $_REQUEST['store'];
	$datap['remarks'] = $_REQUEST['remarksP'];
	$datap['CompanyId'] = $_SESSION['ACGCompanyId'];
	$datap['createdBy'] = $_SESSION['UserID'];
	$datap['createdDate'] = date('Y-m-d');
	$datap['transaction_time'] = FormatDateForSQL($_REQUEST['date']) . " " . date('H:i:s', time());
	$datap['adjustment_type1'] = $_REQUEST['entry_type'];


	$s->RecordInsert('physical_stock', $datap);
	$last_id = DB_Last_Insert_Id($db, "physical_stock", "id");
	for ($i = 0; $i < count($_REQUEST['itemdataid']); $i++) {
		$data_stock = '';
		$datac['physical_stock_id'] = $last_id;
		$datac['mstitemid'] = $_REQUEST['itemdataid'][$i];
		$datac['stock'] = $_REQUEST['stock'][$i];
		$datac['adjustment_qty'] = $_REQUEST['adjustment_qty'][$i];
		$datac['adjustment_type'] = $_REQUEST['adjustment_type'][$i];
		$datac['remarks'] = $_REQUEST['remarks'][$i];
		$datac['size_id'] = $_REQUEST['sizesp'][$i];
		$datac['grade_id'] = $_REQUEST['gradesp'][$i];
		$datac['uom'] = $_REQUEST['uom'][$i];
		$datac['uom1'] = $_REQUEST['uom1'][$i];
		$datac['conv_fac'] = $_REQUEST['confac'][$i];
		$datac['stock_qty2'] = $_REQUEST['secondaryqty'][$i];
		$datac['batch_no'] = $_REQUEST['batchno'][$i];
		$datac['adj_type'] = $_REQUEST['entry_type'];
		$datac['rate'] = $_REQUEST['rate'][$i];
		$datac['amount'] = $_REQUEST['amount'][$i];
		$s->RecordInsert('physical_stock_details', $datac);

		$dtls_Lastreq_id = DB_Last_Insert_ID($db, 'physical_stock_details', $ErrMsg);

		$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['site'];
		$data_stock['store']                    = $_REQUEST['store'];
		$data_stock['mst_itemid']               = $_POST['itemdataid'][$i];
		$data_stock['size_id']                  = $_REQUEST['sizesp'][$i];
		$data_stock['grade_id']                 = $_REQUEST['gradesp'][$i];
		$data_stock['primary_unit']             = $primary_unit;
		$data_stock['secondary_unit']           = $secondary_unit;
		$data_stock['against_voucher_main_id']  = $last_id;
		$data_stock['against_voucher_dtls_id']  = $dtls_Lastreq_id;
		$data_stock['date_of_mfg'] 				= FormatDateForSQL($_REQUEST['dateofmfg'][$i]);
		$data_stock['date_of_expiry'] 			= FormatDateForSQL($_REQUEST['dateofexpiry'][$i]);
		$data_stock['type']                     = 'PHY';
		$data_stock['pending_qty']              = $_REQUEST['adjustment_qty'][$i];

		if ($_REQUEST['adjustment_type'][$i] == 'plus') {
			$data_stock['inwardqty_primary']        = $_REQUEST['adjustment_qty'][$i];
			$data_stock['inwardqty_secondary']      = $_REQUEST['secondaryqty'][$i];
		} else {
			$data_stock['outwardqty_primary']        = $_REQUEST['adjustment_qty'][$i];
			$data_stock['outwardqty_secondary']      = $_REQUEST['secondaryqty'][$i];
		}

		$data_stock['trasaction']               = FormatDateForSQL($_REQUEST['date']) . " " . date('H:i:s', time());
		$data_stock['batch_no']                 = $_REQUEST['batchno'][$i];
		$s->RecordInsert('stock_valuation_tbl', $data_stock);
       
        //print_r($datac);


		/**********************************  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['batchno'][$i];


		/* $insertBatchRec = array(
                                                'store_code' => $storecode,
                                                'item_code' => $itemcode,
                                                'item_desc' => $item_name,
                                                'batch_no' => $_REQUEST['batchNo'][$i],
                                                'manufacturing_date'=>FormatDateForSQL($_REQUEST['dateofmfg'][$i]),
                                                'expire_date' =>FormatDateForSQL($_REQUEST['dateofexpiry'][$i]),
                                                'uom' => $unitcode,
                                                'qty' => $_REQUEST['adjustment_qty'][$i],                         
                                                'created_by' =>getFieldvalue_cake('userrolls','user_name',$_SESSION['c_uid'],'user_id'),
                                                'created' => date('Y-m-d H:i:s'),
                                            );

                                    
                                            $sql_insert="Insert into batchdetails set ";
                                            $t=0;
                                            foreach($insertBatchRec as $key => $val)
                                                {
                                                if($t==0)
                                                $sql_insert.=" ".$key." = '".$val."'";
                                                else
                                                $sql_insert.=", ".$key." = '".$val."'";         
                                                $t++;
                                                }
                                                //echo "<br>". $sql_insert;
                                             mysqli_query($link1,$sql_insert);

             */


		$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'];

		if ($_REQUEST['adjustment_type'][$i] == 'plus') {
			$stockbatchqty = $_REQUEST['adjustment_qty'][$i] + $query_batch_item['qty'];
			$update_batch = mysqli_query($link1, "update batchdetails set qty ='" . $stockbatchqty . "' where item_code='" . $itemcode . "' and store_code='" . $storecode . "' and batch_no='" . $batchno . "'");
		} else if ($_REQUEST['adjustment_type'][$i] == 'minus') {
			$stockbatchqty = $query_batch_item['qty'] - $_REQUEST['adjustment_qty'][$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"));

		if ($_REQUEST['adjustment_type'][$i] == 'plus') {
			$stockqty = $_REQUEST['adjustment_qty'][$i] + $query_item['SUM(stock_level)'];
			$update = mysqli_query($link1, "update storeitems set stock_level ='" . $stockqty . "' where item='" . $itemcode . "' and store_code='" . $storecode . "' and major_code='" . $majorcode . "'");
		} else if ($_REQUEST['adjustment_type'][$i] == 'minus') {
			$stockqty = $query_item['SUM(stock_level)'] - $_REQUEST['adjustment_qty'][$i];
			$update = mysqli_query($link1, "update storeitems set stock_level ='" . $stockqty . "' where item='" . $itemcode . "' and store_code='" . $storecode . "' and major_code='" . $majorcode . "'");
		}










		/******************************************************************************************************************/
	}

	$s->pageLocation("index.php?route=physical_adjustment_index" . $rurl);
}




if (isset($_REQUEST['action']) && isset($_REQUEST['phy'])) {
	if ($_REQUEST['action'] == 'edit' && !empty($_REQUEST['phy'])) {
		$recEdit = DB_fetch_array($s->GetRecordById('physical_stock', 'id=' . $_REQUEST['phy']));
		extract($recEdit);
		$recEdit2 = $s->GetRecordById('physical_stock_details', 'physical_stock_id=' . $_REQUEST['phy']);
	}
}



?><div class="body_contain">
	<div class="tab_div">
		<h1>Physical Stock Adjustment Add</h1>
		<form action="" method="post" name="myform">
			<table width="100%" border="0" cellpadding="3" cellspacing="0">
				<tr class="row1">
					<td width="13%" align="right">Branch</td>
					<td width="35%">
						<?php $ss = "Select loccode, locationname from locations  where CompanyId='" . $_SESSION['ACGCompanyId'] . "' and loccode in('" . $_SESSION['AssignedBranch'] . "')";
						$site_sql = DB_query($ss, $db); ?>
						<select name="site" onchange="GetStore(this.value)" id="site">
							<option value="0">Select</option>
							<?php while ($siteRow = DB_fetch_array($site_sql)) {
								$s = '';
								if ($_SESSION['fromSite'] == $siteRow['loccode'])
									$s = "selected";
							?>
								<option value="<?php echo $siteRow['loccode']; ?>" <?php echo $s; ?>><?php echo $siteRow['locationname']; ?></option>
							<?php 	} ?>
						</select>
					</td>
					<td width="13%" align="right">Store</td>
					<td><select name="store" id="store" onchange="chkitemsstock(this.value)">
							<option value="0">Select</option>
						</select></td>
				</tr>

				<tr class="row1">
					<td align="right">ADJ. Voucher No.</td>
					<td><input type="text" name="ADJ_voucher_no" id="ADJ_voucher_no" value="Auto Generated" readonly=""></td>
					<td align="right">Date</strong></td>
					<td><input type="text" name="date" id="textfield2" readonly="" value="<?php echo ConvertSQLDate(date('Y-m-d')); ?>" class="datepicker"></td>
				</tr>

				<tr class="row1">
					<td align="right">Remarks</td>
					<td colspan="3"><textarea name="remarksP" rows="5"></textarea></td>
				</tr>

				<tr class="row1">
					<td align="right">Type</td>
					<td><select name="entry_type" id="adjustment_type" onchange="change_type(this.value);">
							<option value="0">Select</option>
							<option value="P">Physical Adjustment</option>
							<option value="B">Breakage</option>
						</select>
					</td>
					<td colspan="2"></td>
				</tr>
			</table>

			<p align="left">
				<input type="button" name="profile_popup" value="Pick Items" id="profile_popup" class="search" />
				<input type="button" onclick="deleteRow_return('dataTable')" value="Delete" class="search" />
			</p>

			<table width="100%" border="0" cellpadding="3" cellspacing="0" class="thborder">
				<tr>
					<th width="3%">Select</th>
					<th width="8%">Item Code</th>
					<th width="1"></th>
					<th>Item Name</th>
					<!--<th class="tabledata">UOM</th>-->
					<th width="5%">Adj. Type</th>
					<th width="8%">Batch No.</th>
					<th width="6%">Date of Mfg.</th>
					<th width="6%">Date of Expiry</th>
					<th width="6%">Total Stock Qty.</th>
					<th width="6%">Batch Stock Qty.</th>
					<th colspan="5" style="text-align:center;">Adjustment Qty.</th>
					<th width="8%">Remarks</th>
					<th width="8%">Rate</th>
					<th width="8%">Amount</th>
					<th width="1"></th>
				</tr>
				<tbody id="dataTable">
					<tr>
						<td><input name="delitem[]" type="checkbox" id="delitem" /></td>
						<td><input type="text" id="itemcode_1" name="itemcode[]" readonly="" onkeyup="opendata(this.value,this.id)" /></td>
						<td><input type="hidden" id="itemdataid_1" name="itemdataid[]" /></td>
						<td><input type="text" name="itemname[]" id="itemname_1" readonly /></td>
						<td><select name="adjustment_type[]" id="adj_1" onchange="selectFunction(this.value,this.id)">
								<option value="plus"><strong>Plus</strong></option>
								<option value="minus"><strong>Minus<strong></option>
							</select></td>
						<td><input type="text" name="batchno[]" id="batchno_1" ondblclick="displayBatch(this.value,this.id);" readonly /></td>
						<td><input id="dateofmfg_1" class="datepicker" readonly="" type="text" name="dateofmfg[]"></td>
						<td><input id="dateofexpiry_1" class="datepicker" readonly="" type="text" name="dateofexpiry[]"></td>
						<td><input type="text" name="totalstock[]" id="totalstockbalance_1" readonly /></td>
						<td id="stockbal"><input type="text" onchange="selectFunction(this.value,this.id)" name="stock[]" id="Stockbalance_1" readonly /></td>
						<td width="6%"><input type="text" name="adjustment_qty[]" autocomplete="off" onkeypress="return isNumberKey(event)" onkeyup="chk_recived_qty(this.value,this.id);" id="adjustment_qty_1" /></td>
						<td width="1"><input type="hidden" name="confac[]" id="confac_1" value="<?php echo $row['conv_fac']; ?>" /></td>
						<td width="5%"><select name="uom[]" id="uom_1">
								<option value='0'>Select</option>
							</select></td>
						<td width="6%"><input type="text" name="secondaryqty[]" id="secondary_1" value="<?php echo $secondary_qty; ?>" readonly /></td>
						<td width="5%"><select name="uom1[]" id="uom1_1">
								<option value='0'>Select</option>
							</select></td>
						<td><input type="text" name="remarks[]" id="remarks_1" autocomplete="off" /></td>
						<td><input type="text" name="rate[]" id="rate_1" autocomplete="off" /></td>
						<td><input type="text" name="amount[]" readonly id="amount_1" autocomplete="off" /></td>
						<td width="1"><input type="hidden" style="width:100%;" id="confactor_1" value="" /></td>
					</tr>
				</tbody>
			</table>
			<p align="center">
				<input type="submit" class="search" name="<?php if ($_REQUEST['action'] == 'edit') echo 'update';
															else echo 'Save'; ?>" value="Save" onclick="return validate();">
				<input type="submit" name="Cancel" class="search" value="Cancel">
			</p>
			<input type="hidden" name="hiditemcount" id="hiditemcount" value="" />
			<input type="hidden" name="" value="" id="edit_cnt" />
			<input type="hidden" name="" value="0" id="rowcount1" />
		</form>
		<div id="PickedItems" style="display:none"></div>
		<div id="PickedItems1" style="display:none"></div>
	</div>
</div>



<script language="javascript" type="text/javascript">
	//$.noConflict();
	$(document).ready(function() {
		//var cnt=document.getElementById("count").value;
		$('input[name=profile_popup]').click(function() {
			var tt = this.id;
			var tt1 = tt.split("_");
			var tt2 = tt1[1];
			var site = document.getElementById("site").value;
			if ($('#site').val() == '000') {
				alert('Please select site.');
				return false;
			}
			if ($('#store').val() == '' || $('#store').val() == 0) {
				alert('Please select store.');
				return false;
			}

			//var LeaveType=document.getElementById("LeaveType_"+tt2).value;
			$("#PickedItems").dialog({
				title: 'Item List',
				modal: true,
				resizable: false,
				width: 950,
				height: 400,
				closeText: 'fechar',
				draggable: true,
				show: 'fade',
				hide: 'fade',
				dialogClass: 'main-dialog-class',
				buttons: {
					Exit: function() {
						$(this).dialog("close");
					}
				}

			});
			GetitemListForDirectPO(site);
		});
	});


	function getSubCategory(id) {

		$.post('getItemList.php', {
			"subgrp": id,
			"subdis": 'yes'
		}, function(data) {
			$('#srch_subcateory').html(data);
			// getdata1();
		});
	}

	function getdata1() {
		$('#ItemListDiv').html('<center><span style="font-size:20px;"><strong>Loading...</strong></span></center>');
		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("ItemListDiv").innerHTML = xmlhttp.responseText;
			}
		}
		var site = document.getElementById("site").value;
		var store = document.getElementById("store").value;
		var code = document.getElementById("srch_code").value;
		var name = document.getElementById("srch_name").value;
		var category = document.getElementById("srch_cateory").value;
		var subcat = document.getElementById("srch_subcateory").value;

		xmlhttp.open("GET", "popup_physical_stock_ajax.php?code=" + code + "&site=" + site + "&name=" + name + "&cat=" + category + "&subcat=" + subcat + "&store=" + store, true);
		xmlhttp.send();
		//xmlhttp.open("GET","getSort.php?s="+str+"&cat="+cat,true);
	}

	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;
			item_ids = document.getElementById('itemdataid_' + ids[1]).value;
			// alert(item_ids);

		} else {
			itemcode = document.getElementById('itemcode_1').value;
			itemname = document.getElementById('itemname_1').value;
			unit = document.getElementById('uom1_1').value;
			item_ids = document.getElementById('itemdataid_1').value;
			//alert("asdas"+item_ids);

		}
		//alert(itemcode+"/"+itemname+"/"+unit+"/"+item_ids);

		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;
			$("#PickedItems1").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("site").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_phy.php?item_id=' + item_ids + '&batch_id=' + id + '&site=' + site + '&store=' + store,
				success: function(result) {
					$('#PickedItems1').html(result);
				}
			});
		}
	}





	function addBatchData(id, value, unit, batch, mfg, expiry, rate) {

		if (id.indexOf("_") != "-1") {
			var ids = id.split('_');
			//alert(ids);
			if ($('#Stockbalance_' + ids[1]).val() != '') {

				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);
				$('#rate_' + ids[1]).val(rate);
				document.getElementById('dateofmfg_' + ids[1]).value = mfg;
				document.getElementById('dateofexpiry_' + ids[1]).value = expiry;

			} else {

				$('#Stockbalance_' + ids[1]).val(value);
				$('#batchno_' + ids[1]).val(batch);
				$('#rate_' + ids[1]).val(rate);
				document.getElementById('dateofmfg_' + ids[1]).value = mfg;
				document.getElementById('dateofexpiry_' + ids[1]).value = expiry;
			}
		} 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);
				$('#rate').val(rate);
			} else {
				$('#stock').val(value);
				$('#batchno').val(batch);
				$('#dateofmfg').val(mfg);
				$('#dateofexpiry').val(expiry);
				$('#rate').val(rate);
			}
		}

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


	function deleteRow_return(tableID) {

		if ($('#dataTable').find('input[type="checkbox"][name="delitem[]"]:checked').length > 0) {
			try {
				var table = document.getElementById(tableID);
				//alert(table);
				var rowCount = table.rows.length;

				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--;
					}
				}

			} catch (e) {
				alert(e);
			}
		} else
			alert('Please select at least one row for delete.');
	}

	function GetitemListForDirectPO(str) {
		$('#PickedItems').html('<center><span style="font-size:20px;"><strong>Loading...</strong></span></center>');


		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("PickedItems").innerHTML = xmlhttp.responseText;
			}
		}

		var store = $('#store').val();

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

	function getItemsList(obj, id, code, shade, desc, unit, unit2, stock, ctr, confac) {
		//alert(stock);
		var t1 = parseInt(document.getElementById('rowcount1').value) + 1;
		if (t1 == '')
			var rowTableCount = 1;
		else
			var rowTableCount = parseInt(t1);

		if (obj.checked) {
			if (rowTableCount > 1)
				addRow('dataTable');
		}
		//alert(window.opener.document.getElementById('dataTable').getElementsByTagName("tr").length);

		//alert(rowTableCount);
		var dup = 'empty';
		var itemcount = rowTableCount;
		var counter = 1;
		//alert(itemcount);
		if (document.getElementById("row_id_" + ctr).checked == true) {

			for (var i = counter; i <= itemcount; i++) {

				if (dup == 'empty') {

					//var data= addRow('dataTable');

					if (document.getElementById('itemdataid_' + i)) {
						if (document.getElementById('itemdataid_' + i).value == '') {
							document.getElementById('itemdataid_' + i).value = id;
							document.getElementById('itemcode_' + i).value = code;
							document.getElementById('itemname_' + i).value = shade;
							document.getElementById('uom_' + i).innerHTML = unit;
							document.getElementById('uom1_' + i).innerHTML = unit2;
							document.getElementById('totalstockbalance_' + i).value = stock;
							//document.getElementById('Stockbalance_'+i).value = '';
							document.getElementById('confac_' + i).value = confac;
							document.getElementById('confactor_' + i).value = confac;
							document.getElementById('rowcount1').value = rowTableCount;
							//document.getElementById('itemdesc_'+i).value = desc;	
							//document.getElementById('price_'+i).value = netrate;
							//document.getElementById('mrpper_'+i).value = mrprate;						
							break;
						}
					} else {
						continue;
					}
				}
			}

		} else {


			for (var i = counter; i <= itemcount; i++) {
				if (document.getElementById('itemdataid_' + i)) {
					if (document.getElementById('itemdataid_' + i).value == document.getElementById("row_id_" + ctr).value) {
						document.getElementById('itemdataid_' + i).value = '';
						document.getElementById('itemcode_' + i).value = '';
						document.getElementById('itemname_' + i).value = '';
						document.getElementById('uom_' + i).value = '';
						document.getElementById('totalstockbalance_' + i).value = '';
						document.getElementById('confac_' + i).value = '';
						document.getElementById('confactor_' + i).value = '';
						//document.getElementById('itemdesc_'+i).value = '';	
						//document.getElementById('price_'+i).value = '';
						//document.getElementById('mrpper_'+i).value = '';
					}
				}
			}
		}


	}

	function addRow(tableID) {

		if (document)
			var table = document.getElementById(tableID);
		var rowCount = table.rows.length;
		var rowCount = table.rows.length;

		var row1 = parseInt(document.getElementById("rowcount1").value);
		var rr = parseInt(row1) + 1;
		document.getElementById("rowcount1").value = rr;
		var row = table.insertRow(rowCount);
		document.getElementById("hiditemcount").value = rr;
		document.getElementById("edit_cnt").value = rr;
		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;
			//alert(newcell.childNodes[0].type);
			switch (newcell.childNodes[0].type) {
				case "text":
					newcell.childNodes[0].value = "";
					var nod_id = newcell.childNodes[0].id.split("_");
					if (!isNaN(nod_id[1]))
						newcell.childNodes[0].id = nod_id[0] + '_' + rr;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
					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] + '_' + rr;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
					break;
				case "button":
					var nod_id = newcell.childNodes[0].id.split("_");
					if (!isNaN(nod_id[1]))
						newcell.childNodes[0].id = nod_id[0] + '_' + rr;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
					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] + '_' + rr;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
					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] + '_' + rr;
					else
						newcell.childNodes[0].id = nod_id[0] + '_' + nod_id[1] + '_' + rr;
					break;
			}
			//document.getElementById("stock_perunit_"+rowCount).value=1;
		}
		//document.getElementById(countid).innerHTML=rowCount;

	}


	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 = "adjustment_qty";
				var hrdvalue = document.getElementById(id1).value;
				chk_recived_qty(hrdvalue, id1);
			} else {
				var conf = document.getElementById('confactor_' + brk[1]).value;

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


		} 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 = "adjustment_qty";
						var hrdvalue = document.getElementById(id1).value;
						chk_recived_qty(hrdvalue, id1);
					} else {
						document.getElementById("confac_" + brk[1]).value = xmlhttp.responseText;
						var id1 = "adjustment_qty_" + brk[1];
						var hrdvalue = document.getElementById(id1).value;
						chk_recived_qty(hrdvalue, id1);
					}
					//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("itemdataid").value;
			} else {
				var str2 = document.getElementById("itemdataid_" + brk[1]).value;
			}
			xmlhttp.open("GET", "convactor.php?site=" + str + "&itemid=" + str2, true);
			xmlhttp.send();

		}




	}

	function chk_recived_qty(val, id) {
		var countt12 = 0;

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

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


			var adjustment_qty = document.getElementById("adjustment_qty_" + idk[1]).value;
			var adjustment_type = document.getElementById("adj_" + idk[1]).value;

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

			if (adjustment_type == 'minus') {

				if (parseFloat(adjustment_qty) > parseFloat(Stockbalance)) {

					if (countt12 == 0)
						alert("Adjustment Quantity should be greater than stock");
					document.getElementById("adjustment_qty_" + idk[1]).value = "";
					document.getElementById("secondary_" + idk[1]).value = "";
					val = '0';
					//  ClearFields();
					countt12++;

				}
			}
		});

		//if(countt12>0)
		//	return false;
		var id1 = id.split("_");
		var i = id1[2];
		//alert(i);
		if (id1[2] == undefined) {
			var stockBal = document.getElementById("Stockbalance").value;
			//var isuRate = document.getElementById("issuerate").value;
			var confac = document.getElementById("confac").value;
			if (confac == '') confac = 0;
			//if(isuRate==''){isuRate=0}
			// var totamt = parseFloat(isuRate)*val;
			// document.getElementById("totalamt").value=totamt.toFixed(2);
			var secondaryqty = parseFloat(val) * parseFloat(confac);
			document.getElementById("secondary").value = secondaryqty.toFixed(2);


			var rate = document.getElementById("rate").value;
			if (rate == '') {
				rate = 0;
			}

			var amt = parseFloat(rate) * parseFloat(val);
			document.getElementById("amount").value = parseFloat(amt).toFixed(2);

		} else {
			var stockBal = document.getElementById("Stockbalance_" + i).value;
			//alert(stockBal);
			var confac = document.getElementById("confac_" + i).value;
			if (confac == '') confac = 0;
			var secondaryqty = parseFloat(val) * parseFloat(confac);
			document.getElementById("secondary_" + i).value = secondaryqty.toFixed(2);


			var rate = document.getElementById("rate_" + i).value;
			if (rate == '') {
				rate = 0;
			}

			var amt = parseFloat(rate) * parseFloat(val);
			document.getElementById("amount_" + i).value = parseFloat(amt).toFixed(2);

		}

	}

	function ClearFields() {

		document.getElementById("adjustment_qty_1").value = "";

	}

	function validate() {
		var item_count = 0;
		var remarks_count = 0;
		var adj_count = 0;

		var site = $('#site').val();
		var store = $('#store').val();
		var adj_type = $('#adjustment_type').val();

		if (site == '0') {
			alert("Please Select Branch");
			return false;
		}


		if (store == '0') {
			alert("Please Select Store");
			return false;
		}


		if (adj_type == '0') {
			alert("Please Select Adjustment Type");
			return false;
		}

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

			var val_item = (jQuery(this).val());
			if (val_item == '') {
				item_count += 1;
			}


		});

		if (item_count > 0) {
			alert("Please Select at least one item");
			return false;
		}

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

			var val_remarks = (jQuery(this).val());
			if (val_remarks == '') {
				remarks_count += 1;
			}
		});

		if (remarks_count > 0) {
			alert("Please Write Remarks");
			return false;
		}


		if (adj_type == 'B') {

			jQuery('select[id^=adj_]').each(function()

				{
					var val_adj = (jQuery(this).val());
					if (val_adj == 'plus') {
						adj_count += 1;
					}
				});
		}
		if (adj_count > 0) {
			alert("Please Select Correct Adjustment Type ");
			return false;
		}


	}
</script>