$(document).ready(function(){
add_del_row();
$( "#insexp" ).datepick();
$( "#puc" ).datepick();
$( "#mfgyear" ).datepick();

$(".rateshow").toggle('fast');	


$(".cursor").click(function () {
    
		$('.ontop').show();
		
	var classval = this.className.split(' ')[0];
	
	$('.classval').val(classval)
	});
	
	var settings = {
    url: "prodentry_crud.php?mode=doc_up",
    dragDrop:true,
    fileName: "myfile",
    allowedTypes:"jpg,png,gif,doc,pdf,zip",	
    returnType:"json",
	multiple:true,
	
	//formData:$('#formRegister').serialize(),
	dynamicFormData: function()
{
	var data ={ EntryID:$('#jobid').val(), typeval:$('.classval').val()}  //imgtype=="empphoto"
	return data;
},
	showDelete:false,
	autoSubmit:false,
	onSubmit:function(files)
{
	//alert("<br/>Submitting:"+JSON.stringify(files));
	 
	//alert(result+"<br/>Submitting:"+JSON.stringify(files));
},
	 onSuccess:function(files,data,xhr)
    {
		if(data.success)
		{
			jSuccess('File Uploaded Successfully');
			location.reload(true);
		}
		elseif(data.error)
		{
			jError(data.error);
		}
       // alert((data));
	  // alert("Data Successfully submitted");
    },
	onError: function(files,status,errMsg)
{
	console.log("<br/>Error for: "+JSON.stringify(errMsg));
},
}

	var uploadObj = $("#mulitplefileuploader").uploadFile(settings);
	
	$('#file_up').click(function(){
	uploadObj.startUpload();
});



$.post("../type_fill.php",{},function(result){
	
	 
	
		if(result == null)
		{
			$('#cat_new').html("")
			return;
		}
		var html = "<option selected value=''>--select--</option>";
		$.each(result, function(key,value) {
		html += "<option  value='"+value.list.option+"'>"+value.list.option+"</option>";
			
		});						
		$('#cat_new').html("").append(html);
		var row_itemline;
        $("#cat_new").on("blur", function(){
		 row_itemline = $(this).closest('tr');	
			
		if($(this).val()=='SERVICES'){
			
		$(".code").autocomplete(
        "services_code_fill.php?",
           {
  			delay:10,
  			minChars:1,
  			matchSubset:1,
  			matchContains:1,
			mustMatch:0,
  			cacheLength:10,
			sortResults :false,
  			onItemSelect:function(row){
			if(row.data[0]!='undefined')
			$('.descrip').val(row.data[0]);	
			if(row.data[1]!='undefined')
			$('.psrate').val(row.data[1]);												
		},
		showResult:function(row,data) {
		return row+"|"+data[0];		
		},  		
  		autoFill:false
  		});
		  
			}
			else
			{
				
	$(".code").autocomplete(
	"product_code_fill.php?",
	   {
		delay:10,
		minChars:1,
		matchSubset:1,
		matchContains:1,
		mustMatch:0,
		cacheLength:10,
		sortResults :false,
		onItemSelect:function(row){
			
			
			if(row.data[0]!='undefined')
			row_itemline.find('.descrip').val(row.data[0]);	
			if(row.data[1]!='undefined')
			row_itemline.find('.psrate').val(row.data[1]);	
			row_itemline.find('.qty').val('1');
			row_itemline.find('.pcost').val(row.data[1]);										
		},
		showResult:function(row,data) {
		return row+"|"+data[0];		
		},	
		autoFill:false		
	});		
    }
});
 	},'json');//post ends
	

$('#showtotal').click(function(e) {

  $(".rateshow").toggle('fast');	
});


	$(".rmnewentry").on("click", function(){
	positionedPopup('carrental_entry.php?bookid='+val,660);
	});
	
$("#sizesetcode").on("dblclick", function(){
	//jSuccess('hello');
	     
    var sizeChart = $(this).attr('sizeChartId');
	var pos = $(this).position();
	$('.sizechartdiv').hide();
	var priceArray = 0;
	var mrpArray = 0;	
	if($('#'+sizeChart+' table tbody tr').length<1)
	{
			var sizeArray = $('#sizesetcode').val().split(',');
			//if($('#ptotal').val()>0){
			//var priceArray = $('#diffmrp').val().split(',');	
			//var mrpArray = $('#diffprice').val().split(',');
			//}
			
			var tr
			$.each(sizeArray, function( index, value ) {
  			console.log( index + ": " + value );
			 tr+= "<tr><td>"+(index+1)+"</td><td><textarea style='height: 32px;' name='size_pv[]' class='size_pv' >"+value+"</textarea></td> <td><textarea style='height: 32px;' name='price_pv[]' class='price_pv'>"+priceArray+"</textarea></td><td><textarea style='height: 32px;' name='mrp_pv[]' class='mrp_pv'>"+mrpArray+"</textarea></td><td><textarea name='spone_pv[]' style='height: 32px;' class='spone_pv'></textarea></td><td><textarea name='sptwo_pv[]' style='height: 32px;' class='sptwo_pv'></textarea></td><td><textarea name='qnty_pv[]'  class='qnty_pv' style='height: 32px;'></textarea></td><td><textarea name='fresh_pv[]' class='fresh_pv' style='height: 32px;'></textarea></td><td><textarea style='height: 32px;' name='reprocess_pv[]' class='reprocess_pv'></textarea></td></tr>";

			});	
				
			//if($('.sizesetcode').val()!='')
			$('#'+sizeChart+' table').append(tr);
	}
	
		if($('.sizesetcode').val()!=''){
	
	if($('#'+sizeChart).is(':visible'))
	{
		$('#'+sizeChart).slideUp();
	}
	else
	{	
	$('#'+sizeChart).css({'left':pos.left-200,'top':pos.top+25}).slideDown();
	}
}

});


$(".ratioflip").on("click", function(){
	//jSuccess('hello');
	     
    var ratioChart = $(this).attr('ratioChartId');
	var pos = $(this).position();
	$('.ratiochartdiv').hide();
	var priceArray = 0;
	var mrpArray = 0;	
	var priceval = 0;
	var mrpval = 0;
	var ratioval = 0;
	if($('#'+ratioChart+' table tbody tr').length<1)
	{
			var sizeArray = $('#sizesetcode').val().split(',');
			var ratioArray = $('#ratio').val().split(',');
			var priceArray = $('#diffprice').val().split(',');	
			var mrpArray = $('#diffmrp').val().split(',');
			//if($('#ptotal').val()>0){
			//var priceArray = $('#diffmrp').val().split(',');	
			//var mrpArray = $('#diffprice').val().split(',');
			//}
			
			var tr
			$.each(sizeArray, function( index, value ) {
			ratioval = ratioArray[index];
			priceval = priceArray[index];
			mrpval =  mrpArray[index];
			
  			console.log( index + ": " + value );
			 tr+= "<tr><td>"+(index+1)+"</td><td><textarea style='height: 32px;' name='rtsize_pv[]' class='rtsize_pv' >"+value+"</textarea></td> <td><textarea style='height: 32px;' name='rtratio_pv[]' class='rtratio_pv'>"+ratioval+"</textarea></td><td><textarea style='height: 32px;' name='mrpdiff_pv[]' class='mrpdiff_pv'>"+mrpval+"</textarea></td><td><textarea style='height: 32px;' name='spdiff_pv[]' class='spdiff_pv'>"+priceval+"</textarea></td></tr>";

			});	
				
			//if($('.sizesetcode').val()!='')
			$('#'+ratioChart+' table').append(tr);
	}
	
		if($('.ratiosetcode').val()!=''){
	
	if($('#'+ratioChart).is(':visible'))
	{
		$('#'+ratioChart).slideUp();
	}
	else
	{	
	$('#'+ratioChart).css({'left':pos.left-200,'top':pos.top+25}).slideDown();
	}
}

});

$("body").on("click", ".closediv",function(e){
	e.preventDefault();
	$('.sizechartdiv').hide();

});	

$("body").on("click", ".closedivval",function(e){
	e.preventDefault();
	
	$('.ratiochartdiv').hide();
});
	
	$('body').on('keydown', '#sizecharttable tbody tr td textarea.qnty_pv', function (e) {
         if (e.which === 13) {
             var index = $('.qnty_pv').index(this) + 1;
             $('.qnty_pv').eq(index).focus();
         }
     });

$("body").on("change",".rtratio_pv,.mrpdiff_pv,.spdiff_pv",function() {
	var currBlur = $(this);
	var tr = currBlur.closest('tr');
	
	var table = currBlur.closest('table');
	
	var ratio = Number(tr.find('.rtratio_pv').val());
	var mrpd = Number(tr.find('.mrpdiff_pv').val());
	var priced = Number(tr.find('.spdiff_pv').val());
	
	var temp='';
	var mrpdval='';
	var pricedval='';
	
	table.find('.rtratio_pv').each(function(index, element) {
         if($(this).val()=='')
		 	temp+=0+',';
		else
		 temp+=$(this).val()+',';
    });
	
	table.find('.mrpdiff_pv').each(function(index, element) {
         if($(this).val()=='')
		 	mrpdval+=0+',';
		else
		 mrpdval+=$(this).val()+',';
    });
	
	table.find('.spdiff_pv').each(function(index, element) {
        if($(this).val()=='')
		 	pricedval+=0+',';
		else
		 pricedval+=$(this).val()+',';
    });
	
	$("#ratio").val(temp);
	$("#diffmrp").val(mrpdval);
	$("#diffprice").val(pricedval);
});

	
$('body').on('change','.qnty_pv', function() {
			var currBlur = $(this);
			var tr = currBlur.closest('tr');
			
			var freshTotal = 0;
			var reprocessTotal = 0;
			var damageTotal = 0;
			var qtyTotal = 0;
			
			var table = currBlur.closest('table');
		
			var total = Number(tr.find('.qnty_pv').val());

			  table.find('.qnty_pv').each(function( index ) {
				qtyTotal+=Number($(this).val());
			  });
			  
			
			  $('#stock').val(qtyTotal);
			  $('#phystock').val(qtyTotal);
			  
			  var sizechartid = table.closest('div').attr('id');
			  
			  $('#sizecharttable .size_pv').each(function( index ) {
				
					var tr = 	$(this).closest('tr');
					
					tr.find('.qty').val(qtyTotal);
					tr.find('.fresh').val(freshTotal);
					tr.find('.reprocess').val(reprocessTotal);
					tr.find('.demage').val(damageTotal);
				
			  });
			
		});
	
	
	
	$("#sizesetcode").autocomplete(
      "../ssetcode_fill.php?",
      {
  			delay:10,
  			minChars:1,
  			matchSubset:1,
  			matchContains:1,
			cacheLength:10,
			showResult:function(row,data) {
    		return row+"|"+data[0]+"|"+data[1];
 			 },
			 onItemSelect:function(row){
				if(row.data[0]!='undefined')
				$('#sizesetcode').val($.trim(row.data[0]));
				if(row.data[1]!='undefined')
				$('#ratio').val($.trim(row.data[1]));
				if(row.data[2]!='undefined')
				$('#ratiotot').val($.trim(row.data[2]));
				
					
			 },
  			autoFill:false
  		});

//for focusing on next field by pressing enter		

var altDown = false;

var n=0;  

$select=$('input:text:not(#client,#address,#callby,#contactno,#email),textarea:not(#address),select:not(#address),input:button:not(#guesmas,#bkbymas,#showva)');

					   

    

$select.keydown(function(e)

    {

		

		$select=$('input:text,textarea,select,input:button');

		  n = $select.length;

	

	if (e.which == 13&&!$(this).is('textarea')) 

   { 

	//Enter key

     e.preventDefault(); //to skip default behavior of the enter key

	  

     var nextIndex = $select.index(this)+1;



     if(nextIndex < n)

       $select[nextIndex].focus();

     else

     {

       $select[nextIndex-1].blur();

     }

   }

		

		

        if (e.keyCode == 18&&$(this).is('textarea')) {

			altDown = true;

		}

    }).keyup(function(e) {

   if (e.which == 13&&altDown) 

   { 

   altDown = false;

   

   //Enter key

     e.preventDefault(); //to skip default behavior of the enter key

     var nextIndex = $select.index(this)+1;



     if(nextIndex < n)

       $select[nextIndex].focus();

     else

     {

       $select[nextIndex-1].blur();

     }

   }

});



		$("#total").keyup(function(e){ 
			var code = e.which; // recommended to use e.which, it's normalized across browsers
			if(code==13){
				e.preventDefault();
		   $('#discount').focus();
			} // missing closing if brace
		});
		
		$("#discount").keyup(function(e){ 
			var code = e.which; // recommended to use e.which, it's normalized across browsers
			if(code==13){
				e.preventDefault();
		   $('#namount').focus();
			} // missing closing if brace
		});
		
		
		$("#namount").keyup(function(e){ 
			var code = e.which; // recommended to use e.which, it's normalized across browsers
			if(code==13){
				e.preventDefault();
		   $('#servicetax').focus();
			} // missing closing if brace
		});
		
		
		$("#servicetax").keyup(function(e){ 
			var code = e.which; // recommended to use e.which, it's normalized across browsers
			if(code==13){
				e.preventDefault();
		   $('#grtotal').focus();
			} // missing closing if brace
		});
		
		$("#grtotal").keyup(function(e){ 
			var code = e.which; // recommended to use e.which, it's normalized across browsers
			if(code==13){
				e.preventDefault();
		   $('#Update').focus();
			} // missing closing if brace
		});



	

		$('#date').datepick();
		
		$("#New").click(function() {
		
		window.location="prodentry.php";
		}); 
		
		$("#Close").click(function() {
		
		
		
		window.close();
		
		
		
		});

	

		$('#Update').click(function(){
		
		$('#message').hide();
		
		$('#transperent').show();
		$('#guesmas').trigger('click');
		$.post("prodentry_crud.php?mode=update",$("#bookingform").serialize(),function(html){
		console.log(html);
		jSuccess(html);
		window.location.reload();
		$('#transperent').hide();
		});	
		
		});

	

		$('#Save').click(function(){
		if(validate_form())
		{
		$('#message').hide();
		$('#transperent').show();
		$('#guesmas').trigger('click');
		$.post("prodentry_crud.php?mode=insert",$("#bookingform").serialize(),function(html){
			console.log(html);
		var str=html.split('###');		
		//$('#message').html(str[0]).fadeIn(2000);
		jSuccess('Product ID:'+str[1]);
			
		 /* $( "#jobdet_container td .edit" ).each(function( index ) {	
		    var row= $(this).closest('tr');	
			$.post("proddet_crud.php?mode=cpyval",row.find('select,textarea').serialize()+'&'+$(".calc").serialize()+'&jobid='+str[1], function (html1) {
						  console.log(html1);
				 });
				 
		 });*/			
			
		window.location="prodentry.php?id="+str[1];
		sessionStorage.clear();
		$('#process').show();
		$('#transperent').hide();		
		});	
         }
        });
	
	
	
	

	

$('#process').click(function(){

	var flag;

	for(i=0;i<$("#table_prod_details  tbody  tr").length;i++)

		{		

		var disp=$('#table_prod_details tbody tr:eq('+i+') div .prod_save,#table_prod_details tbody tr:eq('+i+') div .prod_savenew').css('display'); 
		
		
		if(disp!="none")

		{

		flag=1;

		break;

		}

}


/*if(flag==1||$('#Update').css('display')!='none')

jSuccess('Please save the record before Processing!!');

else

{*/

$('#message').hide();

if($('#jobid').val()!="")

{
 $('#transperent').show();
 $('#order_id').removeAttr('disabled');
 $.post("invoice_crud.php?mode=process",{jobid:$('#jobid').val()},function(html){

	var str=html.split('###');

 $('#message').html(str[0]).fadeIn(3000);
 $('#invoiceno').val(str[1]);
 $('#Update').trigger('click');
 $('#jobid').attr('disabled','disabled');
	
  $('#transperent').hide();
//jSuccess(html);


  });

}

$('#process').hide();


//}

});








$('#print').click(function () {

var oid=$('#jobid').val();
var veh=$('#vehno').val();
var word=$('#tot_words').val();

if(oid!='')

{$("#transperent").show();

	$.post('productreg_export_pdf.php', {jobid:oid,vehno:veh,tword:word,PrePrint:'false',Logo:'true',Stvat:$('#Stvat').prop('checked')},function () {

	window.open("product_det.pdf",'','width=900,height=400');

	$("#transperent").hide();
	});

}

});	

//$("#total").blur(update_total);

//$("#namount").blur(update_total);

//$("#discount").blur(update_total);

//$("#grtotal").blur(update_total);

$("body").on('blur','.psrate,.qty',function(e) {
	
	var row = $(this).closest('tr');
	
	
	var rate  = row.find('.psrate').val();
	if(!isNaN(rate))
	rate = Number(rate)
	
	var qty  = row.find('.qty').val();
	if(!isNaN(qty))
	qty = Number(qty)
	
	var amt = (rate*qty).toFixed(2);
	
	var category = row.find('.cat').val();
	
	//if(category=='PRODUCT')
	row.find('.pamount').val(amt);
	//else if(category=='SERVICES')
	//row.find('.scost').val(amt);
	
	
	});




 $("#copy").click(function(){
	 var color_val = $('#colorc').val();
	 var param1var = $('#prodcode').val();
	 if ((!color_val) | (!param1var))
	 {
		 alert("Please Fill Color and Style Code");
	 }
	 var param1var = getQueryVariable("prodcode");
	
	if($.trim(param1var)=='')
	param1var = $('#prodcode').val();
	if(param1var!=undefined&&$.trim(param1var)!='')
	{
		if(typeof(Storage) == "undefined") {
   			jNotify('Web Storage not Supported!!!');
			return;
	}
		
	sessionStorage.prodcode = $('#prodcode').val();	
	sessionStorage.color=$('#colorc').val();
	sessionStorage.subprdcd=$('#subprdcd').val();
	sessionStorage.note=$('#note').val();
	sessionStorage.stock=$('#stock').val();
	sessionStorage.reorder=$('#reorder').val();
	sessionStorage.cat=$('#cat').val();
	sessionStorage.subcat=$('#subcat').val();
	sessionStorage.ratio=$('#ratio').val();
	sessionStorage.noofcolor=$('#noofcolor').val();
	sessionStorage.sizesetcode=$('#sizesetcode').val();
	sessionStorage.status=$('#status').val();
	sessionStorage.diffprice=$('#diffprice').val();
	sessionStorage.diffmrp=$('#diffmrp').val();
	sessionStorage.ptotal=$('#ptotal').val();
	sessionStorage.pdiscount=$('#pdiscount').val();
	sessionStorage.pnamount=$('#pnamount').val();
	sessionStorage.vat=$('#vat').val();
	sessionStorage.grtotal=$('#grtotal').val();
	
	sessionStorage.table=$('#jobdet_container').html();
	
	
	
	$('#New').trigger('click');
	
	}
	 	});

$('#input').keydown( function(e){
		sessionStorage.updateRate = 0;
        if( $(this).val().length === 2 ) { 
            sessionStorage.updateRate = 1;
        }



    });
	
	
	
	/*var newwindow

  $('body').on("click",".rmnewentry", function(){
	  

   newwindow=window.open('rnmentry.php','','height=200,width=400');
	 
   
	if (window.focus) {newwindow.focus()}
});*/
	
	
	var newwindow;
  $('body').on("click",".rmnewentry", function(){
	
	var row = $(this).closest('tr');
	
	if($.trim(row.find('.rmcode').val())!=''&&$.trim(row.find('.descrip').val())!='')
	{
   newwindow = positionedPopup("rnmentry.php",200,400);
   setTimeout(function(){ newwindow.document.getElementById("rmcode").value = row.find('.rmcode').val();newwindow.document.getElementById("description").value = row.find('.descrip').val();;newwindow.document.getElementById("unit").value = row.find('.unit').val()}, 1500);
	}
   else
   {
	newwindow = positionedPopup("rnmentry.php",200,400);
	
   }
   
	//if (window.focus) {driverwindow.focus()}
});

	
	
	
	
$("body").on('blur','.calc',function(e) {

var price=0;
var p_total = 0;
var s_total = 0;
var discount= 0;
var pdiscount = 0;
var sdiscount = 0;
var pnetamount = 0 ;
var snetamount = 0 ;
var total=0;
var vat=0;
var gsttax=0;


	if ($('#pdiscount').val() > 0) {
     	discount = $('#ptotal').val()*($('#pdiscount').val()/100);
		pnetamount = Math.round(Number($('#ptotal').val())+ Number(discount));

		$('#pnamount').val(pnetamount.toFixed(2));
	}
	else{
		pnetamount= $('#ptotal').val();
		$('#pnamount').val(pnetamount);
	}
		
		
	/*	
	if($('#pnamount').val()>=1000){		
		$('#gstper').val('12');
		$('#taxtype').val('12');
	}
	else {
		$('#gstper').val('5');
		$('#taxtype').val('5');
	}
	*/
	//--by partha as discussed on 3rd sept 2014.

    var gstcal = "1."+$('#gstper').val();
	if($("#pnamount").val() >0){
		gsttax = $('#gstper').val()*Number(pnetamount)*.01;
		gsttax = Math.round(gsttax);
	
		$('#gstamt').val(gsttax.toFixed(2));
		//$('#servicetax').val('0.00');
	
		//+Number(vat)+Number(servicetax)
		var grtotal=Number(pnetamount)+Number(gsttax);
	
		grtotal=Math.round(grtotal);
		$('#grtotal').val(grtotal.toFixed(2));
	}
	else{
			
		pnetamount = Number($("#grtotal").val())/gstcal;
		pnetamount = Math.round(pnetamount);
		console.log(pnetamount);
		$("#pnamount,#ptotal").val(pnetamount);
		
		gsttax = Number($("#grtotal").val()) - pnetamount;
		$('#gstamt').val(gsttax.toFixed(2));

		
	}

	
});
		
		

});

//document ends




function run()
{
$("textarea").click(function(){

row_u= $(this).parents('tr');
curr_u=$(this);
undo_u=  $(row_u).clone();

//undo.appendTo("body");

  });

}





function inline_edit()

{
	
	
	
	var tableid='#msview ';

	$(tableid+'tbody textarea,'+tableid+' tbody .pwd').click(function(event){

		if($('#inline_edit').val()==0){


		$(tableid+' tbody tr input:button').hide();

		var row= $(this).closest('tr');

		row_u= $(this).closest('tr');	

		curr_u=$(this);

  		undo_u=  $(row_u).clone(true);	

		row.find('input:button').show();
		}

		else	

		$('#message').html("Please Save the changes made OR press ESC to UNDO").show();

	});

	

		$(tableid+' tbody textarea,'+tableid+' tbody .pwd').keyup(function(event){

			if((event.keyCode==67 && event.ctrlKey)||event.ctrlKey||event.keyCode==9)

		 	return;

			if(event.keyCode==222){

			//event.preventdefault();

			  $(this).val($(this).val().substring(0,($(this).val().length-1))+"`");

			  }

			  if($('#inline_edit').val()==0){

			var row= $(this).closest('tr');

			$(tableid+' tbody tr  textarea').attr('readonly','readonly');

			row.find('textarea').removeAttr('readonly');

			row.find('textarea').css('background-color','#E0B99F');

			row.find('input:button').show();

			$('#inline_edit').val('1');

			  }

		});
	
}




function add_del_row(){
			


		$('body').on('keydown','.sizechartdiv table tbody tr textarea',function(e)
		{
			var tr = $(this).closest('tr');
			 if(e.altKey &&  e.which == 65)
			 {
				e.preventDefault();
				  var prot = $("#prototype").clone();
				  prot.attr("id", "")
				  tr.after(prot);	
			 }
		  });

			


		$('body').on('keydown','.sizechartdiv table tbody tr textarea',function(e)
		{
			var tr = $(this).closest('tr');
		  if(e.altKey &&  e.which == 88)
		  {
			e.preventDefault();
			tr.remove();
			
		  }
  			});

		}




function prodentry_rel()

{
	
	

$('#jobdet_container table td textarea').autoCap();



//for focusing on next field by pressing enter		

var n=0;  

$select=null;

    

$('#jobdet_container table td textarea').keydown(function(e)

    {

		$select=$('#jobdet_container table td textarea');

		  n = $select.length;

	

	if (e.which == 13) 

   { 

	//Enter key

     e.preventDefault(); //to skip default behavior of the enter key

     var nextIndex = $select.index(this)+1;

     if(nextIndex < n)

       $select[nextIndex].focus();

     else

     {

       $select[nextIndex-1].blur();

     }

  

		

     e.preventDefault(); //to skip default behavior of the enter key

     var nextIndex = $select.index(this)+1;

     if(nextIndex < n)

       $select[nextIndex].focus();

     else

     {

       $select[nextIndex-1].blur();

     }

 }

});





$('body').keydown(function(e){

	if(e.keyCode==27)

	{

		//reload page	 

	}	

});


$('#jobdet_container td .edit').click(function(){

		$('#message').hide();

		$('#jobdet_container td .edit').hide();

		 $("#msview tbody tr textarea").css("background-color","");

			$('#msview tbody textarea').removeAttr('disabled');

		   var row= $(this).closest('tr');	

  			$('#transperent').show();

 $.post("proddet_crud.php?mode=update",row.find('select,textarea').serialize()+'&'+$(".calc").serialize(),function(html){

	// var str=html.split('###');
console.log(html);
	 

	  jSuccess(html);
	  $('#Update').trigger('click');

	  window.location.reload();

	  $('#transperent').hide();

  });
 
});


$('#jobdet_container td .deletedet').click(function(){
		//jSuccess("hello");
		$('#message').hide();

		$('#jobdet_container td .deletedet').hide();

		 $("#msview tbody tr textarea").css("background-color","");

			$('#msview tbody textarea').removeAttr('disabled');

           var row= $(this).closest('tr');	
			row.remove();
          $('#transperent').show();

 			$.post("proddet_crud.php?mode=delete",row.find('textarea').serialize()+'&'+$(".calc").serialize(),function(html){

	// var str=html.split('###');
		
	  jSuccess(html);
	  
	  $.when( update_total()  ).done($('#Update').trigger('click'));
	 // update_total();
		//$('#Update').trigger('click');
		
	 // window.location.reload();
	  
		
	  $('#transperent').hide();

  });
});


$('#jobdet_container td  .addnew').click(function(){

	$('#message').hide();

	$('#jobdet_container td .addnew').hide();

	$("#msview tbody tr textarea").css("background-color","");

	$('#msview tbody textarea').removeAttr('disabled');

	var row= $(this).closest('tr');	

	 $('#transperent').show();
	 $.post("proddet_crud.php?mode=insert",row.find('select,textarea').serialize()+'&'+$(".calc").serialize(),function(html){
		 jSuccess(html);
		 
		 console.log(html);
	 jSuccess(html);
	 $('#Update').trigger('click');
	 window.location.reload();
	 $('#transperent').hide();
  });

});	



$(".Calculaterate").click(function(){

update_total();
$('.calc').trigger('blur');
});





}

//alert("Hello");


function update_total(){	

var price=0;
var p_total = 0;
var s_total = 0;
var discount= 0;
var pdiscount = 0;
var sdiscount = 0;
var pnetamount = 0 ;
var snetamount = 0 ;
var total=0;
var vat=0;
var gsttax=0;


     


    $('.pamount').each(function(i){

        price = $(this).val();

        if (!isNaN(price)) 
		p_total += Number(price);

    });	

	
		

	total=Number(p_total);
	$('.tpcost').val(p_total.toFixed(2));
	$('.tscost').val(s_total.toFixed(2));
	$('#ptotal').val(p_total.toFixed(2));
	$('#stotal').val(s_total.toFixed(2));

	

	

	if ($('#pdiscount').val() > 0) {
     discount = p_total*($('#pdiscount').val()/100);
	pnetamount = Math.round(Number(p_total)+ Number(discount));

	$('#pnamount').val(pnetamount.toFixed(2));

	}

	else{
		pnetamount= p_total.toFixed(2);

		$('#pnamount').val(pnetamount);

		}
		
		


	

	gsttax=$('#gstper').val()*Number(pnetamount)*.01;

	gsttax=Math.round(gsttax);

	$('#gstamt').val(gsttax.toFixed(2));

       

	//$('#servicetax').val('0.00');

//+Number(vat)+Number(servicetax)

	var grtotal=Number(pnetamount)+Number(gsttax);

	grtotal=Math.round(grtotal);

	$('#grtotal').val(grtotal.toFixed(2));

}



function validate_form()

{

	if($.trim($('#colorc').val())=="")
		{
			jSuccess("Blank Color");
			$('#colorc').focus();
			return false;
		}
		/*else if($.trim($('#address').val())=="")
		{
			jSuccess("Blank Address");
			$('#address').focus();
			return false;
		}*/
		/*
		else if($.trim($('#callby').val())=="")
		{
			jSuccess("Blank Contact name");
			$('#callby').focus();
			return false;
		}*/
		/*else if($.trim($('#telephone').val())=="")
		{
			jSuccess("Blank Contact No");
			$('#telephone').focus();
			return false;
		}*/
		
		
		
		
		
		else 

		return true;

		

	}



function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  
  
  

  //jSuccess('Query Variable ' + variable + ' not found');
} 



var winPop;

function positionedPopup(url,height,width){
	if(!width)
	width=300
	
	 if(winPop&&!winPop.closed&&winPop.document.location.href!=url){  //checks to see if window is open  
    winPop.close();  
  } 
 winPop =window.open (url,"mywindow1","menubar=1,resizable=1,width="+width+",height="+height+",left=250,top=0");
 
  if(winPop&&winPop.document.location.href==url)
winPop.focus();

return winPop;

}