<?
session_start();
$brcode=$_SESSION['brcode'];
$user=$_SESSION['user'];
if(strlen($brcode)<=0)
{
 print "<script> alert('Session timed out'); parent.document.location='../index.php'; </script>";
 return;
}
include("../opendb.php");
include("../test.php");
include("../util/exqty.php");
//include ("calcsparestock.php");
$ker=mysqli_query($db,"select brstate from branch where brcode='$brcode'");
$kar=mysqli_fetch_array($ker);
$pono=$_REQUEST['pono'];
$vatorcst=$_REQUEST['vatorcst'];
$taxtype=$_REQUEST['taxtype'];

?>
<?php include('../includes/top.php'); ?>
<title>Spare Sales </title>
<script>
function valid()
{
 if(document.f1.paytype.selectedIndex<=0)
 {
  alert('Invalid Payment Type');
  document.f1.paytype.focus();
  return false;
 }
 else
 {
  return true;  
 }

}
</script>
	<link type="text/css" href="../includes/style.css" rel="stylesheet" />

<link href="../css/form.css" type="text/css" rel="stylesheet" media="screen"  />
<link type="text/css" href="../jquery/jquery-ui.min.css" rel="stylesheet" />	
<script type="text/javascript" src="../jquery/jquery-1.7.min.js"></script>
<script type="text/javascript" src="../jquery/jquery-ui.min.js"></script>
<script type="text/javascript" src="../jquery/jquery.jqEasyCharCounter.min.js"></script>



    <script type="text/javascript">
 var count1=0;
 var empname=[];

 var cur=1;
 //var partcode=[];
 var partname=[];
 var unitprice=[];
 var qty=[];
 var tot=[];
 var typ=[];
 var cnt=1;

$(function(){

$(".partcode").live("keydown.autocomplete",function(){
$partcode = $(this);
$row = $partcode.parent().parent();
var vator=document.f1.vatorcst.value;
$(this).autocomplete({
		source: function( request, response ) {

		$.ajax({
		     
			url: "searchsord.php",
			dataType: "json",
			data: "key="+$partcode.val(),
			success: function( data ) {
				response( $.map( data, function( item ) {
					return {
						label: item.partcode+' | '+  item.partname+' | '+  item.stock +' | '+  item.price +' | '+  item.tax +' | '+  item.locat +' |(MRP) '+  item.mrp ,
						value: item.partcode,
						name:item.partname,
						stock:item.stock,
						price:item.price,
						tax:item.tax,
						

					}
				}));
			}
		});
	}
	
,
	minLength: 2,
	select: function( event, ui ) {
	$row.find('.partname').val(ui.item.name);
	$row.find('.price').val(ui.item.price);
	//$row.find('.availqty').val(ui.item.stock);

    
	if(vator=='INTRASTATE')
	{	
		$row.find('.taxcgst').val(ui.item.tax/2);
		$row.find('.taxsgst').val(ui.item.tax/2);
	}
	else
	{
		$row.find('.taxigst').val(ui.item.tax);
	}
	$row.find('.supqty').focus();
	//document.getElementById("unitprice").value=ui.item.stock;
	//$row.find('.rate').val(ui.item.price);
	
	/*log( ui.item ?
	"Selected: " + ui.item.label :
	"Nothing selected, input was " + this.value);
	*/
	 }
	
	});
});
});













function insRow(event,i1,id2)
{

var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

var cur_val=i1.value;


switch(keyCode)
{
case 38:
   var row=i1.parentNode.parentNode.rowIndex;
   var col  =i1.parentNode.cellIndex ;
			 
   document.getElementById('myTable').rows[row-1].cells[col].getElementsByTagName("input")[0].focus();
  break;
case 40:
  var row=field.parentNode.parentNode.rowIndex;
  var col  =field.parentNode.cellIndex ;
			 
   document.getElementById('myTable').rows[row+1].cells[col].getElementsByTagName("input")[0].focus();
			
  break;
case 37:
  var row=field.parentNode.parentNode.rowIndex;
  var col  =field.parentNode.cellIndex ;
			 
  document.getElementById('myTable').rows[row].cells[col-1].getElementsByTagName("input")[0].focus();
	
}



if(id2!="insrowbttn")
  {
   var i2=i1.parentNode.parentNode.rowIndex;
   var i3=parseFloat(i2)+parseFloat(1);
   var rowCounts = document.getElementById('myTable').rows.length;
   var rowCounts1= rowCounts-1;
   
  
  }
else
  {
   var i2=0;
   var rowCounts1=0;
  }




if(((keyCode == 13) && (i2==rowCounts1))||(cnt==1))
 {
var rowCount = document.getElementById('myTable').rows.length;
var rowcount1=parseFloat(rowCount)+parseFloat(1);
//alert(rowCount);
var x=document.getElementById('myTable').insertRow(rowCount);


if(rowCount>=1)
 {
  document.getElementById('insrowbttn').type='hidden';
 }

var a=x.insertCell(0);
var b1=x.insertCell(1);
var c1=x.insertCell(2);
var d1=x.insertCell(3);	
var e1=x.insertCell(4);
var h1=x.insertCell(5);
var j1=x.insertCell(6);
var k1=x.insertCell(7);
var l1=x.insertCell(8);
var m1=x.insertCell(9);
var r1=x.insertCell(10);
var s1=x.insertCell(11);
var n1=x.insertCell(12);
var o1=x.insertCell(13);
var p1=x.insertCell(14);
var k;//=this.rowIndex;
var k1;
a.innerHTML=cur;

if(cur>1&&cnt>1)
{   var ts;
    var kkkkk=0;
		var disvl;
   		var ages = document.getElementsByName('disc[]'), kkkkk;
   		for(kkkkk = ages.length; kkkkk--;)
		{
			if(ages[kkkkk].value)
			{
				disvl= parseFloat(ages[kkkkk].value, 10);
			}
		}
		var ts=disvl;
   // var ts=document.getElementById('dis'+(cur-1)).value;
}
else
{
    var ts=0;
}

b1.innerHTML="<input type=text name=partcode[] id=partcode"+cur+"  class='partcode' size=10 autocomplete='off' list='partcodelist' >";
c1.innerHTML="<input type=text name=partname[] id=partname"+cur+"  class='partname' size=20  autocomplete='off' list='partlist' onKeydown='return handleEnter(this, event)' >"; 
d1.innerHTML="<input type=text name='supqty[]' class='supqty' id=supqty"+cur+" size=4 onKeyup=calc(this.id) value='0' onKeydown='insRow(event,this,this.id)'>";
e1.innerHTML="<input type=text name=price[] id=price"+cur+" size=4 class='price' onfocus='sel(this.id)' onKeydown='return handleEnter(this, event)' onChange='calc(this.id)'>";


h1.innerHTML="<input type=text id='ap"+cur+"' name=aprice[] readonly value='0' size=5 class='aprice' onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)'  >";

j1.innerHTML="<input type=text id='taxcgst"+cur+"' name=taxcgst[] readonly value='0' size=5 class='taxcgst' onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)'  >";
k1.innerHTML="<input type=text id='taxamtcgst"+cur+"' name=taxamtcgst[] readonly value='0' size=5  onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)'  >";
l1.innerHTML="<input type=text id='taxsgst"+cur+"' name=taxsgst[] readonly value='0' size=5 class='taxsgst' onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)'  >";
m1.innerHTML="<input type=text id='taxamtsgst"+cur+"' name=taxamtsgst[] readonly value='0' size=5 onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)'  >";
r1.innerHTML="<input type=text id='taxigst"+cur+"' name=taxigst[] readonly value='0' size=5 class='taxigst' onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)'  >";
s1.innerHTML="<input type=text id='taxamtigst"+cur+"' name=taxamtigst[] readonly value='0' size=5  onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)'  >";


n1.innerHTML="<input type=text id='taxamt"+cur+"' name=taxamt[] readonly value='0' size=5 onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)'  >";
o1.innerHTML="<input type=text id='tot"+cur+"' name=tot[] readonly value='0' size=6 onKeydown='return handleEnter(this, event)' onfocus='sel(this.id)' onKeyup='insRow(event,this,this.id)'  >";
p1.innerHTML="<input type='button' onClick='delrow(this)' value='Del' style='width:30px;' class='del' id=del"+cur+">";
document.getElementById("partcode"+cur).focus();





prevcur=cur;
cur++; 
cnt++;


var table = document.getElementById("myTable");
var row = table.rows[index];
console.log(secondRow.id);
}
if(keyCode == 40)
{
return handleEnter(this, event);
}
if(keyCode == 13)
{

var tbl = document.getElementById('myTable');
   var id3=tbl.rows[i3].cells[0].innerHTML;
document.getElementById("partcode"+id3).focus();
} 

}// end function insrow

function delrow(r)
{

var i=r.parentNode.parentNode.rowIndex;

 document.getElementById('myTable').deleteRow(i);

  var rowCount = document.getElementById('myTable').rows.length;
prevcur=cur;
   var tbl = document.getElementById('myTable');
   
  var q;
  var id1;
  var part; 
  var sum2=0;
   var sum3=0;
  var stot;
  var ltot;
    
   var k=0;
			var ups = document.getElementsByName('discamt[]'), sum = 0, k;
			for(k = ups.length; k--;)
			{
				if(ups[k].value)
				{
					sum += parseFloat(ups[k].value, 10);
				}
                  document.getElementById('totdiscvl').value=sum.toFixed(2);
			}
			var l=0;
			var ups1 = document.getElementsByName('taxamt[]'), sum1 = 0, l;
			for(l = ups1.length; l--;)
			{
				if(ups1[l].value)
				{
					sum1 += parseFloat(ups1[l].value, 10);
				}
				 
                  document.getElementById('tottx').value=sum1.toFixed(2);
			}

			var m=0;
			var ups2 = document.getElementsByName('tot[]'), sum2 = 0, m;
			for(m = ups2.length; m--;)
			{
				if(ups2[m].value)
				{
					sum2 += parseFloat(ups2[m].value, 10);
				}
				  
                  document.getElementById('ggtot').value=sum2.toFixed(2);
			}
			var n=0;
			var ups3 = document.getElementsByName('supqty[]'), sum3 = 0, n;
			for(n = ups3.length; n--;)
			{
				if(ups3[n].value)
				{
					sum3 += parseFloat(ups3[n].value, 10);
				}
                  document.getElementById('totsupqty').value=sum3.toFixed(2);
			}
             handling();
	
 if(rowCount<=1)
 {
  document.getElementById('insrowbttn').type='button';
  ///alert(rowCount);
 }

//cnt--;
//cur--;     
 }

 $(document).ready(function(){
  
  $("#svbttn").click(function(){
$("#msgbox").html('<small>Loading...</small>');



 if(document.f1.paytype.selectedIndex<=0)
 {
  alert('Invalid Payment Type');
  document.f1.paytype.focus();
  return false;
 }
 if(confirm('Do you want to save?'))
	  {
 

      // var name= $(this).attr('name');

       //$('#type_name').val(name);

     var values1 = $("#jforms").serialize();
alert(values1);
   // $(".typeselecter").attr("disabled", true);
    // $("#td1").html('');

      $.ajax({
        url: "svinvoice_new.php",
        type: "POST",
       data:   values1,
         success: function(msg){
              if(parseInt(msg)!=0)

              {

                $('#msgbox').html(msg);
               // $("#load").html('');
                //$(".typeselecter").attr("disabled", false);
    }


        },
      error:function(){
          alert("failure");
          $("#msgbox").html('there is error while submit');
      }
      });
	 }
	 else
	  {
   return false;
	  }
   });








   });

</script>
<style>
.login-popup{
		display:none;
	background:white;
	padding: 10px; 	
	border: 2px solid #ddd;
	float: left;
	font-size: 1.2em;
	position: fixed;
	top: 4%; left: 45%;
	z-index: 99999;
	box-shadow: 0px 0px 20px #999;
	-moz-box-shadow: 0px 0px 20px #999; /* Firefox */
    -webkit-box-shadow: 0px 0px 20px #999; /* Safari, Chrome */
	border-radius:3px 3px 3px 3px;
    -moz-border-radius: 3px; /* Firefox */
    -webkit-border-radius: 3px; /* Safari, Chrome */
}
.pop-up2 {position:absolute; top:2px; left:50px;padding-left:180px;}
.pop-up2:target {position:static; left:0;}

.popBox2 {
  background:#ffffff;

 
  width:75%;
  min-height:100%;



   z-index:1;

  border:1px solid #3a3a3a;


  -moz-border-radius:12px;
  border-radius:12px;
  -webkit-box-shadow:2px 2px 4px #3a3a3a;
  -moz-box-shadow:2px 2px 4px #3a3a3a;
  box-shadow:2px 2px 4px #3a3a3a;
  opacity:0;
 -webkit-transition: opacity 0.5s ease-in-out;
  -moz-transition: opacity 0.5s ease-in-out;
  -o-transition: opacity 0.5s ease-in-out;
  -ms-transition: opacity 0.5s ease-in-out;
  transition: opacity 0.5s ease-in-out;  
}
:target .popBox2 {position:fixed; opacity:1;}

.popBox2:hover {box-shadow:3px 3px 6px #5a5a5a;}



.lightbox {display:none; text-indent:0em; background:#000; opacity:0.0; width:100%; height:60%; position:fixed; top:0; left:0; bottom:0; right:0;}
:target .lightbox {display:block}



  


/* .popScroll {max-height:99%; overflow-y:scroll;} removed 17/07/2012 */
.popScroll2 {position:absolute; top:2%; left:3%; right:3%; bottom:9%; overflow-y:auto; *overflow-y:scroll; padding-right:0.5em}
</style>
<link rel="stylesheet" href="../style.css" type="text/css" />
<body background="../back_ground.jpg">

<br>
<?



?>
<table class="container"><tr><td>
<center>

    <form name="f1" id="jforms">
        <div id="view" class="login-popup">

</div>
		<div id="login-box" class="login-popup">
        <a href="#" class="close"><img src="../images/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>
          <div id='msgbox'></div>
		</div>
<input type=hidden name='saleordno' value='<?print $pono?>'>
<input type=hidden name='invtype' value='<?print $taxtype?>'>
<input type=hidden name='vatorcst' id='vatorcst' value='<?print $vatorcst?>'>
<?
$sq="select max(invno) from spareinvoice where brcode='$brcode' ";
//and invtype='$taxtype' and vatorcst='$vatorcst'
$re=mysqli_query($db,$sq);
$prow=mysqli_fetch_row($re);
if($prow[0]<=0)
 	$invno=1;
else
 	$invno=($prow[0]+1);
 	$cusres=mysqli_query($db,"select * from customer where brcode='$brcode' order by acname asc");
 	
print "<table border=0 bgcolor=ivory cellspacing=1 cellpadding=3 class='form' ><th colspan=6><H3> SPARE INVOICE $taxtype-$vatorcst</TH>";

print "<tr><td>Customer</td><td colspan=3><select name='customer' onChange=getaddr()><option value='select'>-select one-</option>";
while($custrow=mysqli_fetch_array($cusres))
{
print "<option value='$custrow[acname]'>$custrow[acname]</option>";
}
print "</select></td>";
print "<td><font color=red>Payment Type</font></td><td><select name='paytype'><option></option>";

print "<option value='Cash'>Cash</option><option value='Credit'>Credit</option></select></td></tr>";

print "<tr><td>Site Address</td><td><textarea name='addr'>$cusrow[addr1].$cusrow[dist1]</textarea></td>";
print "<td>GST No.</td><td><input type=text name='tin' readonly value='$cusrow[tin]'></td>";

print "<td>Sale Bill No.</td><td><input type=text readonly name='invno' value='$invno'></td></tr>";



print "<tr><td>Sale Date</td><td>dd<input type=text readonly name='d' size=2 maxlength=2 value='".date("d")."'>
mm<input type=text readonly name='m' size=2 maxlength=2 value='".date("m")."'>
yy<input type=text readonly name='y' size=4 maxlength=4 value='".date("Y")."'>
</td>";
print "<td>Entry Date</td><td>dd<input type=text readonly name='d1' size=2 maxlength=2 value='".date("d")."'>
mm<input type=text readonly name='m1' size=2 maxlength=2 value='".date("m")."'>
yy<input type=text readonly name='y1' size=4 maxlength=4 value='".date("Y")."'>
</td>";




print "<td colspan=2>Ref: <input type=text name='ref' size=30></td> </tr>";
print "<tr><td>Engineer </td><td><select name='engineer'><option>Counter Sale</option>";
$enres=mysqli_query($db,"select * from empmaster where dept like '%service%' and doret='0000-00-00' order by empname");
while($enrow=mysqli_fetch_array($enres))
{
 print "<option>$enrow[empname]</option>";
}
print "<option>FOC</option></select></td><td colspan=4></td></tr>";
print "<tr><th colspan=10></tr>";
print"</table><br>";

?>
<link rel="stylesheet" href="../style.css" type="text/css" />
<style>
//	tr{background-color:white}
	th{background-color:steelblue;color:white}
.right{text-align:right};
</style>
<center>

<table class=report>

<tr>    
<input type="button" id='insrowbttn' onclick="insRow(event,this,this.id)" style="color:#6B6B6B;font-weight:bold;font-size:15px;" value="+">
<td colspan='6' align=center>  
<table border=0 cellspacing=1 cellpadding=3 id="myTable" class='tble1'>
<tr class='trcls'><th>No<th>P Code <th> Name <th> Sale Qty
<th>Price <th>A Price
<?

   print "<th>CGST%<th>CGST Amt<th>SGST%<th>SGST Amt";

 print "<th>IGST%<th>IGST Amt";
?>
<th> Tax Amt<th> Total<th> Del</tr>
</table></td></tr>
</table>
<?

print "\n<table class=report><tr><td colspan=4> <center><b>Total </td><td colspan=4 align=center></td><td></td><td align=center>Qty Total<input type=text class=right name='totsupqty[]' id='totsupqty' size=8></td>";
print "\n<td align=center>Disc Total<input type=text class=right name='totdiscvl' id='totdiscvl' readonly size=8></td><td align=center>";
print "Tax Total<input type=text class=right id='tottx' size=8></td><td>CESS @ 1%<input type=text name=cessval id='cessval' value=0 size=5></td><td>Handling<input type=text name=hnd id='hnd' value='0' onkeyup='handling()' size=5></td>";
print "<td>Hand Tax%<input type=text name=hndtax readonly id='hndtax' value='28' size=5></td>";
print "<td>Round<input type=text readonly name=rnd id='rnd' size=6></td>";
print "<td>Grand Total<input type=text name=ggtot id='ggtot' size=10></td></tr>";

?>
<div id='strdiv'></div>
<tr>
<th colspan=17><input value="Save"  type="button" id='svbttn'>
<input type=button value='Cancel' onClick=window.close()></th>
</table>
</form>

<script>
 function calc(x)
 {
     var thenum = x.match(/\d+$/)[0];
    var x=thenum;
var qty='supqty'+x;
 var ele='price'+x;
 var actele='ap'+x;
 var taxele='taxcgst'+x;
 var taxsgstele='taxsgst'+x;
 var taxigstele='taxigst'+x;

 var txamtele='taxamt'+x;
 var taxamtcgstele='taxamtcgst'+x;
 var taxamtsgstele='taxamtsgst'+x;
 var taxamtigstele='taxamtigst'+x;
  var totele='tot'+x;
 

/*
 if(parseFloat(document.getElementById(qty).value)>parseFloat(document.getElementById(avail).value) || document.getElementById(avail).value=='')
 {
   alert('Stock only '+document.getElementById(avail).value);
  document.getElementById(x).value=0;
  document.getElementById(x).focus();
   return false;
 }
 */

 var amt=(parseFloat(document.getElementById(ele).value))*(parseFloat(document.getElementById(qty).value)); 
 
 //var disc=amt*parseFloat(document.getElementById(disele).value)/100;
 var disc=0;
 var actamt=amt-disc;
document.getElementById(actele).value=parseFloat(actamt);

var vator=document.getElementById('vatorcst').value;

    if(vator=='INTRASTATE')
	 {  
		var tx=parseFloat(document.getElementById(taxele).value);
		var txsgst=parseFloat(document.getElementById(taxsgstele).value);
		var taxc=(actamt*tx)/100;
		var taxs=(actamt*txsgst)/100;
		var floodcs=0;
		var intratot=0;
		intratot=tx+txsgst;
		var cessflag=0;
		//cessflag=document.getElementById('cessflg').value;
		
		
		//document.getElementById(floodvl).value=floodcs.toFixed(2);
		
		document.getElementById(taxamtcgstele).value=taxc.toFixed(2);
		document.getElementById(taxamtsgstele).value=taxs.toFixed(2);
		var tot_tax=parseFloat(document.getElementById(taxamtcgstele).value)+parseFloat(document.getElementById(taxamtsgstele).value);
		document.getElementById(txamtele).value=tot_tax.toFixed(2);
	    var total=parseFloat(actamt)+parseFloat(tot_tax);
		document.getElementById(totele).value=parseFloat(total).toFixed(2);

	 }
	 else
	 {
		var txigst=parseFloat(document.getElementById(taxigstele).value);
		var tot_tax=(actamt*txigst)/100;
		document.getElementById(txamtele).value=tot_tax.toFixed(2);
		document.getElementById(taxamtigstele).value=tot_tax.toFixed(2);
		var total=parseFloat(actamt)+parseFloat(tot_tax);
		document.getElementById(totele).value=parseFloat(total).toFixed(2);
	 }














 }
 function getaddr()
 {
    var str=document.f1.customer.value;
    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("strdiv").innerHTML=xmlhttp.responseText;
            
            document.f1.addr.value=document.getElementById("cstaddr").value;
            document.f1.tin.value=document.getElementById("cstgst").value;
        }
    }
    
    xmlhttp.open("GET","searchcust.php?cname="+str,true);
    xmlhttp.send();
 }
</script>

