<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$producttotalrows = 1;
$currdt = date('Y-m-d');
if($info4edit["info"]) $producttotalrows = count($info4edit["info"]);
//predata($productlist);
?>

      <div class="main my-0">
        <div class="row mt-3 mx-0">
          <div class="col-md-6">
            <h3><?php echo $pgheading;?></h3>
          </div>
          <div class="col-md-5 text-right">
            &nbsp;
          </div>
        </div>
        
        <div class="container_fluid mt-2 px-3">
		<form name="frmgeneral" method="post" action="warehouse/<?php echo $mgmtname;?>/managedata?<?php echo $_SERVER['QUERY_STRING'];?>" enctype="multipart/form-data" onsubmit="return validateFrm();">
		<input type="hidden" name="rsrcid" id="rsrcid" value="<?php echo $rsrcid;?>">
		<input type="hidden" name="vatpercent" id="vatpercent" value="<?php echo $warehouseinfo->fld_vat;?>">
		<input type="hidden" name="tcspercent" id="tcspercent" value="<?php echo $warehouseinfo->fld_tcs;?>">
        <table class="webforms mt-0 table-responsive-sm">
		<tr>
          
          <td width="6%"><label>Client:</label></td>
          <td width="35%">
		  <select name="clientid" id="clientid" required class="js-example-basic-single nxtinput">
		  <option value="">Select Client</option>
						<?php
						if(is_array($clientlist) && count(array_filter($clientlist))>0)
						{

							foreach($clientlist as $outletrow)
							{
								$sel_outlet ="";
								if($info4edit["main"]->fld_vendorid==$outletrow->fld_id)
								{
									$sel_outlet = 'selected="selected"';
								}				
									?>
											<option value="<?php echo $outletrow->fld_id;?>" <?php echo $sel_outlet;?>><?php echo $outletrow->fld_name;?></option>
									<?php
								
							}
						}
						?> 
		  </select>
		  </td>

          <td width="12%"><label>Pass Number:</label></td>
          <td width="15%"><input type="text" name="refno" id="refno" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_refno; }?>"<?php if(!$info4edit["main"]) { ?> onblur="checkduptp('<?php echo base_url();?>');"<?php } ?> required  placeholder="Manual TP No."></td>
  
          <td width="17%"><label>Pass Date:</label></td>
          <td width="15%"><input type="date" name="refdate" id="refdate" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_refdate; }else { echo $currdt;}?>" required ></td>
         </tr> 
		 <tr>
             <td colspan="6" class="text-center">&nbsp;
			 <h5 id="frmerrormsg" class=""></h5>
			 </td>
             
         </tr> 
		
		<tr><td colspan="6" ><h5>Product Info.</h5></td></tr>
		 <tr>
             <td colspan="6" id="divwarehousestockinfo">
			<table class="webforms mt-0 table-responsive-sm">
			 <tbody id="productrowbox">
			 <tr>
				<th width="20%">Product</th>
				<th width="10%">Instock</th>
				<th width="5%">Qty. (Case)</th>
				<th width="5%">Qty. (Bottle)</th>
				<th width="20%">Total Qty. (Bottles)</th>
				<th width="10%">Price (Case)</th>
				<th width="10%">Price (Bottle)</th>
				<th width="10%">SubTotal</th>
				<th width="10%">&nbsp;</th>
			</tr>
			<?php
			
					$casestotal = 0;
					$bottlestotal = 0;
					$grandtotal = 0;
					$productitemsubtotal = 0;
					if($info4edit["info"])
					{
						for($iix=0;$iix<count($info4edit["info"]);$iix++)
						{
							$itemqtyinbottles = 0;
							$rowidx = $iix+1;
							$rowinfo = $info4edit["info"][$iix];
							
							$casestotal += $rowinfo->fld_qty_case;
							$bottlestotal += $rowinfo->fld_qty_bottle;
				?>
					  
				<tr id="productrow_<?php echo $rowidx;?>">
				<td>
					<input type="hidden" name="transactioninfoids[]" id="transactioninfoids<?php echo $rowidx;?>" value="<?php echo $rowinfo->fld_id;?>"> 				
					<select  id="productid<?php echo $rowidx;?>" name="productid[]" required onchange="showproductinstock(this);" class="js-example-basic-single nxtinput" style="width:300px;" >
                      <option value="">--Select Product Name--</option>
						<?php
						if(is_array($productlist) && count(array_filter($productlist))>0)
						{
							foreach($productlist as $itemrow)
							{
								$sel_item ="";
								$instock = $itemrow['instock'];
								if($rowinfo->fld_productid==$itemrow['productid'])
								{
									$itemqtyinbottles = ($rowinfo->fld_qty_case*$itemrow['noofbottlesincase']) + $rowinfo->fld_qty_bottle;
									if($itemqtyinbottles>0) $itemqtyinbottles = round($itemqtyinbottles, 2);
									$sel_item = 'selected="selected"';
									$instock = ($itemrow['instock']+$rowinfo->fld_qty);
									$instocktoshow = $instock; 
								}
								if($instock>0)
								{
									$qtyincase = round(($instock / $itemrow['noofbottlesincase']), 2);
									
								?>
										<option value="<?php echo $itemrow['productid']."_".$instock."_".$itemrow['noofbottlesincase']."_".$itemrow['caseprice']."_".$itemrow['bottleprice'];?>"  <?php echo $sel_item;?>><?php echo $itemrow['name'] . " (" . $instocktoshow . " Bottles / " . $qtyincase . " Case)";?></option>
								<?php
								}
							}
						}
						$grandtotal += $itemqtyinbottles;
						?> 
				</select>
			</td>
			<td id="instockproductid<?php echo $rowidx;?>"><?php echo $instocktoshow;?>
			</td>
			<td><input type="text" name="qty_case[]" id="qty_case<?php echo $rowidx;?>"  placeholder="Quanity" value="<?php echo $rowinfo->fld_qty_case;?>" onchange="checkQtyRCVD('<?php echo $rowidx;?>');" onblur="checkQtyRCVD('<?php echo $rowidx;?>');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:100px">

			<span id="qty_caseemsg<?php echo $rowidx;?>" class=""></span></td>
			<td><input type="text" name="qty_bottle[]" id="qty_bottle<?php echo $rowidx;?>"  placeholder="Quanity" value="<?php echo $rowinfo->fld_qty_bottle;?>" onchange="checkQtyRCVD('<?php echo $rowidx;?>');" onblur="checkQtyRCVD('<?php echo $rowidx;?>');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:100px">

			<span id="qty_bottleemsg<?php echo $rowidx;?>" class=""></span></td>
			<td  id="totalitemqty<?php echo $rowidx;?>"><?php echo $itemqtyinbottles;?></td>
			<td><input type="text" name="price_case[]" id="price_case<?php echo $rowidx;?>"  placeholder="Price" value="<?php echo $rowinfo->fld_price_case;?>" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('<?php echo $rowidx;?>');" onblur="checkQtyRCVD('<?php echo $rowidx;?>');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:120px"></td>
			<td><input type="text" name="price_bottle[]" id="price_bottle<?php echo $rowidx;?>"  placeholder="Price" value="<?php echo $rowinfo->fld_price_bottle;?>" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('<?php echo $rowidx;?>');" onblur="checkQtyRCVD('<?php echo $rowidx;?>');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:120px"></td>
<td><input type="text" name="subtotal[]" id="subtotal<?php echo $rowidx;?>"  placeholder="subtotal" value="<?php echo $rowinfo->fld_subtotal;?>" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('<?php echo $rowidx;?>');" onblur="checkQtyRCVD('<?php echo $rowidx;?>');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:150px"></td>
			<td  id="rowid<?php echo $rowidx;?>"></td>
			</tr>					  
				<?php
						}
				?>
				<?php
					}
					else
					{
				?>
			 <tr id="productrow_1">
				<td><select  id="productid1" name="productid[]" required onchange="showproductinstock(this);" class="js-example-basic-single nxtinput" style="width:300px;" >
                                                                <option value="">--Select Product Name--</option>
						<?php
						if(is_array($productlist) && count(array_filter($productlist))>0)
						{	
							foreach($productlist as $itemrow)
							{
								if($itemrow['instock']>0)
								{
									$qtyincase = round(($itemrow['instock'] / $itemrow['noofbottlesincase']), 2);
								?>
										<option value="<?php echo $itemrow['productid']."_".$itemrow['instock']."_".$itemrow['noofbottlesincase']."_".$itemrow['caseprice']."_".$itemrow['bottleprice'];?>"  ><?php echo $itemrow['name'] . " (" . $itemrow['instock'] . " Bottles / " . $qtyincase . " Case)";?> </option>
								<?php
								}
							}
						}
						?>                                      
</select></td>
<td id="instockproductid1"><span id="rcvdmsg1" class=""></span></td>
<td><input type="text" name="qty_case[]" id="qty_case1"  placeholder="Quanity" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('1');" onblur="checkQtyRCVD('1');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:100px">
<span id="qty_caseemsg1" class=""></span></td>
<td><input type="text" name="qty_bottle[]" id="qty_bottle1"  placeholder="Quanity" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('1');" onblur="checkQtyRCVD('1');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:100px">
<span id="qty_bottleemsg1" class=""></span></td>
<td id="totalitemqty1"></td>
<td><input type="text" name="price_case[]" id="price_case1"  placeholder="Price" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('1');" onblur="checkQtyRCVD('1');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:120px"></td>
<td><input type="text" name="price_bottle[]" id="price_bottle1"  placeholder="Price" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('1');" onblur="checkQtyRCVD('1');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:120px"></td>
<td><input type="text" name="subtotal[]" id="subtotal1"  placeholder="subtotal" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('1');" onblur="checkQtyRCVD('1');" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46' style="width:150px"></td>
<td>&nbsp;</td>
</tr>
	
<?php
					}
		 ?>
		 
		</tbody> 
		</table> 
		</td>
		</tr>
		<tr>
			<td colspan="6">
		<table class="webforms mt-0 table-responsive-sm border-0">
			 <tbody>
			 <tr>
				 <td width="30%"></td>
				 <td width="10%" id="totalcasesid" class="text-center"><strong>Cases: <?php echo $casestotal;?></strong></td>
				 <td width="10%" id="totalbottlesid" class="text-center"><strong>Bottles: <?php echo $bottlestotal;?></strong></td>
				 <td width="10%" id="grandtotalinbottlesid" class="text-left"><strong>Total: <?php echo $grandtotal;?></strong></td>
				 <td width="20%"></td>
				 <td width="5%" class="text-right"><a class="btn btn-success text-white" style="cursor:pointer" onclick="return addrow('<?php echo base_url();?>');"><i class="fa fa-plus"></i> Row</a></td>
			 </tr>
		 </tbody> 
		</table>

			</td>
		</tr>




		 <tr>
					<td width="100%" colspan="6" class="text-right">
						<table style="width:30%!important" class="text-left"  align="right">
						<tr>	
							<td class="text-left" width="40%"> <strong>Items Total:<strong></td>
							<td class="text-right" width="60%" >
							<input type="text" class="form-control form-control-sm" readonly step="any" name="producttsubtotalamount" id="producttsubtotalamount"  placeholder="Total Amount" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_subtotal; }else { echo 0; }?>" required="required" readonly>
							</td> 
						</tr>
						<tr>
							<td><strong> Vat (<?php echo $warehouseinfo->fld_vat;?>%):</strong></td>
							<td  >
							<input type="text" class="form-control form-control-sm calcInvAmnt" name="vatamount"  id="vatamount" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_vatamount; }else { echo 0; }?>" placeholder="Vat Amount" onblur="calctotalquantity();" readonly>
							</td>
						</tr>
						<tr>
							<td ><strong> TSC (<?php echo $warehouseinfo->fld_tcs;?>%):</strong></td>
							<td  >
							<input type="text" class="form-control form-control-sm calcInvAmnt" name="tscamount"  id="tscamount" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_tscamount; }else { echo 0; }?>" placeholder="Discount" onblur="calctotalquantity();" readonly>
							</td>
						</tr>						
							
						<tr>
							<td><strong> Discount :</strong></td>
							<td  >
							<input type="text" class="form-control form-control-sm calcInvAmnt" name="discount"  id="discount" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_discount; }else { echo 0; }?>" placeholder="Discount" onblur="calctotalquantity();">
							</td>
						</tr>
						<tr>
							<td ><strong> Adjustment :</strong></td>
							<td>
							<input type="text" class="form-control form-control-sm calcInvAmnt" name="adjustment"  id="adjustment" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_adjustment; }else { echo 0; }?>" placeholder="Adjustment" onblur="calctotalquantity();">
							</td>
						</tr>
						<tr>
							<td ><strong>Net to Pay:</strong></td>
							<td  >
							<input type="text" class="form-control form-control-sm calcInvAmnt" name="productttotalamount"  id="productttotalamount" value="<?php if($info4edit["main"]) { echo $info4edit["main"]->fld_amount; }?>" placeholder="0"  readonly>
							</td>
						</tr>

						<tr>
							
							<td colspan="2" class="text-right">
							<textarea name="remarks"  class="form-control form-control-sm " id="remarks" rows="2" cols="30" placeholder="Remarks" ><?php if($info4edit) { echo $info4edit["main"]->fld_remarks; }?></textarea>			  
							</td>
						</tr>							
						<tr>							
							<td colspan="2" class="text-right"><button class="btn btn-danger">Submit</button></td>
						</tr>							
						</table>
					</td>
					
				</tr>			

		<input type="hidden" name="producttotalrows" id="producttotalrows" value="<?php echo $producttotalrows;?>"  />
         </table>
         </form> 
	         <div class="clearfix"></div>          
        </div>
       </div>
<script>

document.addEventListener('keyup', function(event) {
	var producttotalrows = $("#producttotalrows").val();
	 eidname =   event.target.name;	
	//alert(event.keyCode);
	//alert(eidname);
if (event.shiftKey==false)
{
if (event.keyCode == 46)
 {
	eid =   event.target.id;
	if(eidname=='productid[]')
	{			
		var eidindex = eid.split("productid");			
	}
	else if(eidname=='qty_case[]')
	{			 
		var eidindex = eid.split("qty_case");			
	}
	else if(eidname=='qty_bottle[]')
	{			
		var eidindex = eid.split("qty_bottle");			
	}
	
	indexno  = eidindex[1];
	indexno = parseInt(indexno);		
	if(indexno>1)
	 {		
		transactioninfoids = $("#transactioninfoids"+indexno).val();
		transactioninfoids = parseInt(transactioninfoids);
		//alert(transactioninfoids);
		if(transactioninfoids>0)
		 {
			removerow(indexno,'product','edit','<?php echo base_url();?>');
		 }
		 else
		 {
			removerow(indexno,'product','add','<?php echo base_url();?>');
		 }
	 }
 }	
	  if (event.keyCode == 9 && eidname=="qty_bottle[]") {

		 eid =   event.target.id;
		 var eidindex = eid.split("qty_bottle");
		 indexno  = eidindex[1];
		 indexno = parseInt(indexno);
		 if(producttotalrows==indexno)
		  {
			 addrow('<?php echo base_url();?>');
		  }
		 indexno = indexno+1;
		indexno = parseInt(indexno);
		 
	  }
  
}
  
});
		function showproductinstock(event)
		{	
			prodval = event.value;
			prodidindex = event.id;			
			var arrprodids = prodidindex.split("productid");
			var proddata = prodval.split("_");
			var stock = proddata[1];
			var caseprice = proddata[3];
			var bottleprice = proddata[4];
			//alert(stock+" => " + caseprice + " => " + bottleprice + " => " + prodidindex+ " => " + prodval+ " => " + arrprodids[0] + " => " + arrprodids[1]);
			$("#instock"+prodidindex).html(stock);
			$("#price_case"+arrprodids[1]).val(caseprice);
			$("#price_bottle"+arrprodids[1]).val(bottleprice);
		}
		function getwarehousestockinfo(basePath)
		{
			var warehouseid = $("#warehouseid").val();
			var rsrcid = $("#rsrcid").val();
			
			  if(warehouseid!="")
			  { 
				$.ajax({
					url: basePath+"warehouse/getwarehousestockinfo",
					data: {'warehouseid': warehouseid,'rsrcid': rsrcid}, 
					type: "post",
					beforeSend: function() {
						//$("#divindentinfo").html('<img src="'+basePath+'assets/images/loader.gif" style="width: 40px;" />');	
					},
					success: function(data){
						
						//$("#divwarehousestockinfo").css('display','block');				
						html = data.trim();
						//alert(html);		
						$("#divwarehousestockinfo").html(html);
					}
				});

			  }	
		}

function checkduptp(basePath)
{
	var tprefno = $("#refno").val();
	if(tprefno!="")
	{
		tptype = "wsale";
		$.ajax({
			url: basePath+"warehouse/checktpnumber",
			data: {'tprefno': tprefno,'tptype': tptype}, 
			type: "post",
			success: function(data){
				html = data.trim();
				if(html=="")
				{
					alert("Please try again!");
					$("#refno").val('');
				}
				else if(html=="exists")
				{
					alert("Pass Number already exists, check and try again!");
					$("#refno").val('');
					$("#refno").focus();
				}
			}
		});
	}
}
		</script>
<?php
/*
if($rsrcid>0)
{
	?>
		<script>
		setTimeout(function(){
			getwarehousestockinfo('<?php echo base_url();?>');
		},3000);

	</script>
<?php
}*/
?>
<script>	
function validateFrm()
{
	var totalrows = $("#producttotalrows").val();
	totalrows = parseInt(totalrows);
	errorstatus = 1;
	for(ix=1;ix<=totalrows;ix++)
	{			
		//checkQtyRCVD(ix);
		var qty_case = $("#qty_case"+ix).val();	
		qty_case = parseInt(qty_case);
		if(qty_case>0)
		{
			errorstatus = 0;
		}
		var qty_bottle = $("#qty_bottle"+ix).val();	
		qty_bottle = parseInt(qty_bottle);
		if(qty_bottle>0)
		{
			errorstatus = 0;
		}
	}
	if(errorstatus==1)
	{		
		$("#frmerrormsg").html('Please create at least single row to proceed!');
		$("#frmerrormsg").addClass('alert alert-danger');
		setTimeout(function(){
		$("#frmerrormsg").removeClass('alert alert-danger');			
		$("#frmerrormsg").html("");
		},4000);
		return false;
	}
	else
	{
		return true;	  
	}
		
}

function addrow(base_url)
{
	var id = $("#producttotalrows").val();
	
	var productlist = $("#productid1").html();
	
	id = parseInt(id) + 1;
	$("#producttotalrows").val(id);	
		
	$("#productrowbox").append('<tr id="productrow_'+id+'"><td><select id="productid'+id+'" name="productid[]"  onchange="showproductinstock(this);" class="js-example-basic-single nxtinput" style="width:300px;">'+productlist+'</select></td><td id="instockproductid'+id+'"></td><td><input type="text" name="qty_case[]" id="qty_case'+id+'" placeholder="Quanity" value="0" onchange="checkQtyRCVD('+id+');" onblur="checkQtyRCVD('+id+');" onkeypress="return event.charCode >= 48 &amp;&amp; event.charCode <= 57 || event.charCode==46" style="width:100px"><span id="qty_caseemsg'+id+'" class=""></span></td><td><input type="text" name="qty_bottle[]" id="qty_bottle'+id+'" placeholder="Quanity" value="0" onchange="checkQtyRCVD('+id+');" onkeypress="return event.charCode >= 48 &amp;&amp; event.charCode <= 57 || event.charCode==46" style="width:100px"><span id="qty_bottleemsg'+id+'" class=""></span></td><td id="totalitemqty'+id+'"></td><td><input type="text" name="price_case[]" id="price_case'+id+'"  placeholder="Price" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('+id+');" onblur="checkQtyRCVD('+id+');" onkeypress=\'return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46\' style="width:120px"></td><td><input type="text" name="price_bottle[]" id="price_bottle'+id+'"  placeholder="Price" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('+id+');" onblur="checkQtyRCVD('+id+');" onkeypress=\'return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46\' style="width:120px"></td><td><input type="text" name="subtotal[]" id="subtotal'+id+'"  placeholder="subtotal" value="0" required="required" data-validation-required-message="This field is required" aria-invalid="false" onchange="checkQtyRCVD('+id+');" onblur="checkQtyRCVD('+id+');" onkeypress=\'return event.charCode >= 48 && event.charCode <= 57 || event.charCode==46\' style="width:150px"></td><td id="rowid'+id+'"><a class="btn btn-danger text-white" style="cursor:pointer" onclick="return removerow('+id+',\'product\',\'add\',\''+base_url+'\')">x</a></td></tr>');
	//$('.js-example-basic-single').select2();
	$(document).ready(function() {
        function customMatcher(params, data) {
            if ($.trim(params.term) === '') {
                return data;
            }

            // Split the search term by spaces
            const searchTerms = params.term.toUpperCase().split(" ");
            
            // Split the option text by spaces
            const optionWords = data.text.toUpperCase().split(" ");

            // Check if any part of the search term matches the beginning of any word in the option text
            for (let i = 0; i < searchTerms.length; i++) {
                let matched = false;
                for (let j = 0; j < optionWords.length; j++) {
                    if (optionWords[j].startsWith(searchTerms[i])) {
                        matched = true;
                        break;
                    }
                }
                if (!matched) return null;
            }

            return data;
        }

        $('.js-example-basic-single').select2({
            matcher: customMatcher
        });
    });

}
function removerow(rowId,actionFor,actionType,base_url)
{
	totalRowIdname = '#'+actionFor+'totalrows';
	removerowId= '#'+actionFor+'row_'+rowId;
	if(actionType == "add")
	{
			totalRow = $(totalRowIdname).val();
			//alert(totalRow);
			$(removerowId).remove();
			
			for(i=eval(rowId+1); i<=totalRow; i++)
			{
				if(actionFor=="product")
				{
					addremovelink = '<a class="btn btn-danger text-white" style="cursor:pointer" onclick="return removerow('+eval(i-1)+',\'product\',\'add\',\''+base_url+'\')">x</a>';
					$("#productrow_"+i).attr('id','productrow_'+eval(i-1));
					$("#instockproductid"+i).attr('id','instockproductid'+eval(i-1));
					$("#productid"+i).attr('id','productid'+eval(i-1));
					$("#qty_case"+i).attr('id','qty_case'+eval(i-1));
					$("#qty_bottle"+i).attr('id','qty_bottle'+eval(i-1));	
					$("#qty_bottle"+i).attr('id','totalitemqty'+eval(i-1));	
					$("#rowid"+i).html(addremovelink);	
					$("#rowid"+i).attr('id','rowid'+eval(i-1));						
				}
						
			}
			
			var id = $(totalRowIdname).val();
			id = parseInt(id) - 1;
			$(totalRowIdname).val(id);
		
	}
	if(actionType == "edit")
	{
		if(!confirm('Action will delete the row!\nAre you sure?')) return false;			
				if(actionFor=="product")
				{
					delrowid = $("#transactioninfoids"+rowId).val();
				}				
		//alert(delrowid);
		$.ajax({
			url: base_url+"warehouse/removecommonrow",
			data: {'task': actionFor, 'rowid': delrowid},
			type: "post",

			beforeSend: function() {
				//$("#row"+rowId).html('<img src="'+base_url+'assets/images/loader.gif" width="40" style="margin-left: 141px; margin-top: 11px;" />');
			},
			success: function(data){
				var msg = data.trim();
				//alert(msg);
				if(msg=="success")
				{					
					totalRow = $(totalRowIdname).val();
					
					for(i=eval(rowId+1); i<=totalRow; i++)
					{
						if(actionFor=="product")
						{	
							addremovelink = '<a class="btn btn-danger text-white" style="cursor:pointer" onclick="return removerow('+eval(i-1)+',\'product\',\'add\',\''+base_url+'\')">x</a>';
							$("#productrow_"+i).attr('id','productrow_'+eval(i-1));
							$("#instockproductid"+i).attr('id','instockproductid'+eval(i-1));
							$("#productid"+i).attr('id','productid'+eval(i-1));
							$("#qty_case"+i).attr('id','qty_case'+eval(i-1));
							$("#qty_bottle"+i).attr('id','qty_bottle'+eval(i-1));
							$("#rowid"+i).html(addremovelink);	
							$("#rowid"+i).attr('id','rowid'+eval(i-1));								
						}
					}					
					setTimeout(function(){ 
						$(removerowId).remove();
						var id = $(totalRowIdname).val();
						id = parseInt(id) - 1;
						$(totalRowIdname).val(id);
			
					}, 500);
					
				}
			}
		});
	}
	calctotalquantity();
	
	
}


function checkQtyRCVD(indexno)
{
	//alert(indexno);
	 total_qty =0;
	 instock = parseFloat(instock);
	 var qty_case = $("#qty_case"+indexno).val();	
	 var pricecase = $("#price_case"+indexno).val();
	 var pricebottle = $("#price_bottle"+indexno).val();
	 if(pricecase=="") pricecase = 0;
	 if(pricebottle=="") pricebottle = 0;
	 qty_case = parseFloat(qty_case);

	prodval = $("#productid"+indexno).val();	
	var proddata = prodval.split("_");
	var noofbottlesincase = proddata[2];	
	noofbottlesincase = parseFloat(noofbottlesincase);
	var instock = proddata[1];
	//alert(noofbottlesincase);
	var qty_bottle = $("#qty_bottle"+indexno).val();	
	qty_bottle = parseFloat(qty_bottle);
	if(qty_case>0)
	{
		if(noofbottlesincase>0)
		{
			total_qty = (qty_case*noofbottlesincase);
		}
		else
		{
			total_qty = qty_case;
		}
	}
	if(qty_bottle>0)
	{
		total_qty = total_qty+qty_bottle;
	}
	
	var subtotal = 0;
	if(total_qty!="" && pricebottle!="")
	{
		subtotal = (parseFloat(qty_case) * parseFloat(pricecase)) + (parseFloat(qty_bottle) * parseFloat(pricebottle));
	}
	$("#subtotal"+indexno).val(subtotal);
	
	
	calctotalquantity();
	
	//total_qty = (qty_bottle+qty_case);
	//alert(total_qty);
	if(instock<total_qty)
	{
		$("#frmerrormsg").html('Quantity should not exceed Instock');
		$("#frmerrormsg").addClass('alert alert-danger');
		setTimeout(function(){
		$("#frmerrormsg").removeClass('alert alert-danger');			
		$("#frmerrormsg").html("");
		},4000);
		//alert(checkrqty);
		//$("#qtymsg"+indexno).html('Quantity should not exceed Instock');
		//$("#qty_caseemsg"+indexno).addClass('alert alert-danger');
		$('#qty_case'+indexno).css('border-color', 'red');
		$('#qty_bottle'+indexno).css('border-color', 'red');
		setTimeout(function(){
			//$("#qty_caseemsg"+indexno).removeClass('alert alert-danger');			
			//$("#qtymsg"+indexno).html("");
			$('#qty_case'+indexno).css('border-color', '');
			$('#qty_bottle'+indexno).css('border-color', '');
		},4000);
		$("#qty_case"+indexno).val(0);
		$("#qty_bottle"+indexno).val(0);
		return false;
	}
	else
	{
		return true;
	}
}

function calctotalquantity()
{
	// calc total
	var totalrows = $("#producttotalrows").val();
	totalrows = parseInt(totalrows);
	var totalcases = 0;
	var totalbottles = 0;
	var grandtotalqty = 0;
	var producttsubtotalamount = 0;
	
	var vatpercent = $("#vatpercent").val();
	var tcspercent = $("#tcspercent").val();

	for(ix=1;ix<=totalrows;ix++)
	{
		var itemqtytotal = 0;
		prodval = $("#productid"+ix).val();	
		price_case = $("#price_case"+ix).val();	
		price_bottle = $("#price_bottle"+ix).val();	
		if(price_case=="") price_case = 0;
		if(price_bottle=="") price_bottle = 0;
		var proddata = prodval.split("_");
		var noofbottlesincase = proddata[2];	
		noofbottlesincase = parseFloat(noofbottlesincase);
		
		var qty_case = $("#qty_case"+ix).val();	
		qty_case = parseInt(qty_case);
		if(qty_case>0)
		{
			totalcases = totalcases + qty_case;
			itemqtytotal = qty_case * noofbottlesincase;
		}
		var qty_bottle = $("#qty_bottle"+ix).val();	
		qty_bottle = parseInt(qty_bottle);
		if(qty_bottle>0)
		{
			totalbottles = totalbottles + qty_bottle;
			itemqtytotal = itemqtytotal + qty_bottle;
		}
		$("#totalitemqty"+ix).html(itemqtytotal);
		grandtotalqty = grandtotalqty + itemqtytotal;
		
		var subtotal = (parseFloat(qty_case) * parseFloat(price_case)) + (parseFloat(qty_bottle) * parseFloat(price_bottle));
		$("#subtotal"+ix).val(subtotal);
		
		producttsubtotalamount = producttsubtotalamount + subtotal;
	}
	//alert(producttsubtotalamount);
	$("#grandtotalinbottlesid").html("<strong>TOTAL: " + grandtotalqty + "</strong>");
	$("#totalcasesid").html("<strong>CASES: " + totalcases + "</strong>");
	$("#totalbottlesid").html("<strong>BOTTLES: " + totalbottles + "</strong>");
	// end of calc total
	
	$("#producttsubtotalamount").val(producttsubtotalamount);
	
	vatamount = (parseFloat(producttsubtotalamount) * parseFloat(vatpercent)) / 100;
	tscamount = (parseFloat(producttsubtotalamount) * parseFloat(tcspercent)) / 100;
	vatamount = parseFloat(vatamount);
	totalproductamount = producttsubtotalamount;
	if(vatamount>0)
	{
			totalproductamount = totalproductamount+vatamount;
	}
	$("#vatamount").val(vatamount);
	$("#tscamount").val(tscamount);
	//tscamount = $("#tscamount").val();	
	tscamount = parseFloat(tscamount);
	if(tscamount>0)
	{
			totalproductamount = totalproductamount+tscamount;
	}
	discount = $("#discount").val();
	if(discount=="") discount = 0;
	discount = parseFloat(discount);
	if(discount!="")
	{
			totalproductamount = (totalproductamount-discount);
	}
	adjustment = $("#adjustment").val();
	if(adjustment=="") adjustment = 0
	adjustment = parseFloat(adjustment);
	if(adjustment!="")
	{
		if (adjustment >= 0)
		{
			totalproductamount = (totalproductamount+adjustment);
		}
		else
		{
			totalproductamount = (totalproductamount+(adjustment));
		}		
	}
	totalproductamount = parseFloat(totalproductamount);
	$("#productttotalamount").val(totalproductamount.toFixed(2));
}

/*
function validateFrm()
{
	
		erroralert = 1;
		var producttotalrows = $("#producttotalrows").val();
		for(c=1; c<=producttotalrows; c++)
		{
			var qty_case = $("#qty_case"+c).val();	
			qty_case = parseFloat(qty_case);
			var qty_bottle = $("#qty_bottle"+c).val();	
			qty_bottle = parseFloat(qty_bottle);
			if(qty_case>0)
			{
			
				erroralert = 0;
			}
			if(qty_bottle>0)
			{
			
				erroralert = 0;
			}
			
		}
		//alert(erroralert);
		if(erroralert==1)
		{			
			errorvalmsg ='Please enter qty greater then 0';
			$("#frmerrormsg").html(errorvalmsg);
			$("#frmerrormsg").css('color', 'red');
			$("#frmerrormsg").css('border-color', 'red');
			setTimeout(function(){
			$("#frmerrormsg").html('');
			$("#frmerrormsg").css('color', '');
			$("#frmerrormsg").css('border-color', '');
			},4000);
			alert(errorvalmsg);
		
	
			
			return false;
		}


}*/
</script>
