$(document).ready(function(){
	addmaster_usedby();
	var altDown = false;
 $('.focus_feature input:text:not(.date),.focus_feature textarea,.focus_feature select').keydown(function(e) {
        if (e.keyCode == 13&&!$(this).is('textarea'))
        {
			var ntabindex = Number($(this).attr('tabindex'));
ntabindex++;
$('*[tabindex='+ntabindex+']').focus();

        } 
		
		if (e.keyCode == 18&&$(this).is('textarea')) {
			altDown = true;
		}
    }).keyup(function(e) {
   if (e.which == 13&&altDown) 
   { 
   altDown = false;
   var ntabindex = Number($(this).attr('tabindex'));
ntabindex++;
$('*[tabindex='+ntabindex+']').focus();
   }
    });	
	
	
print();
/*$('#enquiry_date').datepick({
	onClose:function(){
		$('#ref_to').focus();
		}
	});*/
	
	$('#orderdate').datepick({
	onClose:function(){
		$('#remarks').focus();
		}
	});
	
	/*$('#validity').datepicker({
	onClose:function(){
		$('#due_date').focus();
		}
	});*/
/*$('#due_date').datepick({
	onClose:function(){
		$('#division').focus();
		}
	});*/
//focus_on_enter();
 $('#addcmp').click(function(){
        if($.trim($('#buyer_code').val())!=''&&$.trim($('#company').val())!='')
        {
            $.post("addcmpdetails.php",$('.cmpdet').serialize(),function(result){
                jSuccess(result);
                
            });
        }
        
        else
        jSuccess('Enter Data');
        
    });
	
	
var newwindow

$('.field_bc').click(function(e) {
	//jSuccess('hello');
if($('#buyer_code').val()!=''){
newwindow=window.open('mastercmpedit.php?compid='+$('#buyer_code').val(),'','height=380,width=600');
}

if (window.focus) {newwindow.focus()}
});

$('#save').click(function(){
	$('#save').hide();	
	$('#print').show();
	$('#message').hide();
	if(validation())
	{
		    $('#transperent').show();

$.post("pinvoice_crud.php?mode=save",$('#enquiry_details,#other_details').find('select,textarea,input').serialize(),function(html){
		var str=html.split('###');
   $('#message').html(str[0]).fadeIn(2000);
    $('#invoice_no').val(str[1]);
	invoice_getdet();
	     $('#transperent').hide();

  });
 // $('#enquiry_details,#other_details').find('select,textarea,input:not(:button)').attr('disabled','disabled');	

	}
});



$('#edit').click(function(){
		$('#print').fadeIn("slow");

		$('#quot_id').show();
	$('#quot_id_unpro').hide();
	$('#message').hide();
	$('#enquiry_details input:text,#enquiry_details select,#enquiry_details textarea,#other_details input:text,#other_details textarea').bind('keydown change',function(){
	if($(this).attr('id')!='quot_id'&&$(this).attr('id')!='enquiry_id'&&$(this).attr('id')!='order_id'&&$(this).attr('id')!='invoice_no'&&$('#invoice_no').val()!='')
	{
		//jSuccess($(this).attr('id'));
$('#update').fadeIn("slow");	
	}
});
$('#enquiry_details,#other_details').find('select,textarea,input:not(:button)').removeAttr('disabled');
$('#enquiry_details,#other_details').each (function(){
  this.reset();
});
 $('#table_prod_details tbody').html("");
  $('#invoice_no').focus();
//$('#update').show();
$('#save').hide();	
});

$('#refresh').click(function(){
	location.reload(true);
});

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

if(validation())
	{
$('#message').hide();
    $('#transperent').show();
 $('#enquiry_id,#order_id').removeAttr('disabled');
$.post("pinvoice_crud.php?mode=update",$('#enquiry_details,#other_details').find('select,textarea,input').serialize(),function(html){
 $('#message').html(html).fadeIn(2000);
 $('#enquiry_id,#order_id').attr('disabled','disabled');
  $('#update').fadeOut('slow');
	    $('#transperent').hide();

  });
	}
});
$('#new').click(function(){
		$('#buyer_code').focus();
		$('#print').hide();
		$('#save').fadeIn("slow");	
		$('#recv_mode option:eq(1)').attr('selected','selected');
	$('#quot_status option:eq(1)').attr('selected','selected');
	$('#quot_id').hide();
	$('#quot_id_unpro').show();
	$('#quot_id_unpro').focus();
	$('#message').hide();
	$('#enquiry_details,#other_details').find('select,textarea,input:not(:button)').removeAttr('disabled');
	
	$('#enquiry_details,#other_details').each (function(){
  this.reset();
  });
  $('#table_prod_details tbody').html("");
  $('#update').hide();
  //$('#save').show();
$('#order_id,#enquiry_id').attr('disabled','disabled');	
});
/*
$('#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($('#quot_id').val()!="")
{
	   $('#transperent').show();
 $('#order_id').removeAttr('disabled');
$.post("invoice_crud.php?mode=save",$('#enquiry_details,#other_details').find('select,textarea,input').serialize(),function(html){
	var str=html.split('###');
 $('#message').html(str[0]).fadeIn(2000);
  $('#order_id').attr('disabled','disabled');
	     $('#transperent').hide();

  });
}
$('#process').hide();
}
});
*/


	$('#roundoff').click(function() {
		roundoffval();
	});

//code for email/sms
$('#ShowSMS').click(function(){
	
	$('#EmailTo').val($('#cp_email').val());
	//$('#EmailCc').val($('#bookedbyemail').val());
	$('#EmailBcc').val('offer@nitinfire.com');
	$('#SMSNo').val($('#cp_mobile').val());
	$('#EmailSub').val('Order Confirmation');
	
	if($('#order_id').val().replace(/^\s+|\s+$/g,'')!='')
	{
	$('#EmailMsg').val('Dear Sir !!\nGreetings of the Day !!\nThis is with reference to your enquiry ref. no. :'+$('#enquiry_no').val()+'\nKindly find attached herewith our enquiry.\nHope you will find the same in line with your enquiry. If any query, kindly feel free to write / contact us.\nLooking ahead for your valued order and to serve you.');
	
		$('#SMSMsg').val('With reference to your enquiry  no.:'+$('#enquiry_no').val()+'\ dt:'+$('#enquiry_date').val()+" for the supply of  fire protection materials.   Nitin Fire Protection IL has forwarded its order vide email dt."+$('#enquiry_date').val());
	}

	
    $("#SmsEmail").animate({
      height:'toggle'
    });	
//$('#SmsEmail').toggle();
});



$('#EmailSend').click(function(){	
	        var to, esub, ebody,cc;
        to = $('#EmailTo').val();
		cc=$('#EmailCc').val();
        esub = $('#EmailSub').val();
        ebody = $('#EmailMsg').val().replace(/\n+/g, '%0D%0A');
      //  SendMail(to ,ebody ,esub);
	 // <a href="#" onclick="emailForm();" title="E-mail this page"> 
	 emailForm(to,esub,ebody,cc);

});


$('#SMSSend').click(function(){
	var t_mob=$('#SMSNo').val();
	var mob=t_mob.split(',');
	var msg=$('#SMSMsg').val();
	var i=0;
	while(mob[i])
	{

url = "http://bulk.thesmscity.com/sendhttp.php?user=nitinfire&password=921559&mobiles="+mob[i]+"&message="+msg+"&sender=NFPILF&route=4";
window.open(url,'','height=200,width=400');
	i++;
	}
	
});


$('#EmSmSend').click(function(){	
$('#SMSSend,#EmailSend').trigger('click');

});

$('#SMSClose').click(function(){
	
$('#SmsEmail').hide();	
});




});//document ready ends


function addmaster_usedby(){
	$('#clientmas').fadeIn('slow');
	$('#clientmas').click(function(){
		
		if($.trim($('#buyer_code').val())==''||$.trim($('#company').val())==''||$.trim($('#buy_email').val())=='')
		{
			jSuccess('Enter Required Details');
			return;
			}
			$(this).remove();
		 $.post("add_clientdet.php?mode=insertgml",$('#buyer_code,#company,#address,#buy_city,#cp_name,#buy_email,#buy_phone').serialize(),function(result){
			 $('#message').html(result);
		 });
	});
	
	}



function emailForm(to_address,subject,bdy_msg,cc) 
{ 
/*var to_address = "..TO ADDRESS.."; 
var subject = "..YOUR SUBJECT.."; 
var bdy_msg = "..YOUR MESSAGE.."; */
var mailto_link = 'mailto:'+to_address+'?subject='+subject+'&body='+bdy_msg+'&cc='+cc;
win = window.open(mailto_link,'emailWindow'); 
if (win && win.open &&!win.closed) win.close(); 
}

function focus_on_enter()
{
$field_select=$(".form_billreg_fill input,.form_billreg_fill textarea");
$field_select.keydown(function(e) {
   var n = $field_select.length;
   if (e.which == 13) 
   { //Enter key
     e.preventDefault(); //to skip default behavior of the enter key
     var nextIndex = $field_select.index(this)+1;
     if(nextIndex < n)
       $field_select[nextIndex].focus();
     else
     {
       $field_select[nextIndex-1].blur();
     }
   }
});	
$('input:button').bind("keydown", function(e) {
	if (e.which == 13) 
   { //Enter key
     e.preventDefault(); //to skip default behavior of the enter key
	 $(this).trigger('click');
   }
});

}



function oproduct_fill_rel(){
	//$('#message').hide();
	$("#table_prod_details tbody tr:last td:eq(2) input:text").focus();
$('html').keydown(function(e){
	if(e.keyCode==27)
	{
		$('#message').hide();
	$('#quot_id').trigger('blur');
	}
});

$('#table_prod_details tbody textarea,#table_prod_details tbody input:text').keydown(function(){
	var c=0;
	var flag=0;
	$('#message').hide();
		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)
{
	$('#table_prod_details tbody tr:not(:eq('+i+')) textarea,#table_prod_details tbody tr:not(:eq('+i+')) input:text').attr('disabled','disabled');
	$('#table_prod_details tbody tr:eq('+i+') textarea,#table_prod_details tbody tr:eq('+i+') input:text').css('background-color','#807168');

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

else
{		
var row= $(this).parents('tr');
row.find('#prod_save').show();
row.find('#prod_savenew').show();
$('#update').fadeIn("slow");
}

	
});



$('.prod_save').click(function(){
		$('#message').hide();
		 $("#table_prod_details tbody tr textarea ,#table_prod_details tbody tr input:text").css("background-color","");

			$('#table_prod_details tbody textarea ,#table_prod_details tbody input:text').removeAttr('disabled');
var row= $(this).parents('tr');	


 $('#transperent').show();
 $.post("piproduct_crud.php?mode=update",row.find('textarea,input:text').serialize(),function(html1){
	$('#message').html(html1).show();
	 $('#transperent').hide();
  });
	
	
	$('.prod_save').hide();
});

$('.prod_savenew').click(function(){
	$('#message').hide();
	
			 $("#table_prod_details tbody tr textarea ,#table_prod_details tbody tr input:text").css("background-color","");
	$('#table_prod_details tbody tr textarea ,#table_prod_details tbody tr input:text').removeAttr('disabled');
	
	var row= $(this).parents('tr');	
	 $('#transperent').show();
	 $.post("piproduct_crud.php?mode=insert",row.find('textarea,input:text').serialize(),function(html){
	$('#message').html(html).show();
	 invoice_getdet('newentry');
	  $('#transperent').hide();
	 
	 
  });
$('.prod_savenew').hide();

});


$('input,textarea').keyup(function(e){
if(e.keyCode==222)
$(this).val($(this).val().substring(0,($(this).val().length-1))+"`");

});



	bind();
	roundoffval();
 $("#vatr,#sevtr,#octrair,#exiser,#cust_dutyr,#disr,#extrar").blur(function(){		update_gtotal(); 
	 });
	 
	$('.amount,#total').keydown(function(){
		return false;
	});
	

$('#table_prod_details tbody .qty,#table_prod_details tbody .unit,#table_prod_details tbody .rate,#table_prod_details tbody .amount').css('text-align','right');
	
	
	$(".product_code").autocomplete(
      "product_code_fill.php?",
      {
  			delay:10,
  			minChars:0,
  			matchSubset:1,
  			matchContains:1,
  			cacheLength:10,
  			onItemSelect: function findValue_bt(li) {
  	if( li == null ) return jSuccess("No match!");

  		// if coming from an AJAX call, let's use the CityId as the value
  	if( !!li.data ) {var sValue = li.data[0];var sValue1 = li.data[1];var sValue2 = li.data[2];var sValue3= Number(li.data[3]);var sValue4= li.data[4];var sValue5= li.data[5];var sValue6= Number(li.data[6]);var sValue7 = li.data[7];var sValue8 = li.data[8];}

  	// otherwise, let's just display the value in the text box
  	else var sValue = li.selectValue;
	
	var row= $("*:focus").parents('tr');
	 row.find('.prod_desc').val(sValue);
	row.find('.qty').val(sValue5);
	row.find('.rate').val(sValue3);
	row.find('.unit').val(sValue2);
	row.find('.vatpc').val(sValue6);
     row.find('.srate').val(sValue7);
	 row.find('.manufac').val(sValue8);
   

    
  	//jSuccess("The value you selected was: " + sValue1);
  },
  			showResult:function(row,data){
				return row+"|"+data[0];
				},
  			autoFill:false
  		}
    );
	
	
	}
	


function update_total() {
  var total = 0;
  $('.amount').each(function(i){
    amount = $(this).val();
    if (!isNaN(amount)) 
	total=parseFloat(total+Number(amount));
  });
   $('#total').val(total.toFixed(2));

  
   update_gtotal();
}

function update_amount()
{
	
	var row= $(this).parents('.item-row');	
	//jSuccess(parseFloat(row.find('.rate').val()*2.2).toFixed(2));
	//jSuccess(isNaN(row.find('.rate').val()));
	if(!isNaN(row.find('.qty').val())&& !isNaN(row.find('.rate').val()))
	{
         //var amount =(Number(row.find('.rate').val())*Number(row.find('.qty').val()))+Number(row.find('.vatamt').val());
        var vatpc = Number(row.find('.vatpc').val());
        var amount =(Number(row.find('.rate').val())*Number(row.find('.qty').val()));
        row.find('.vatamt').val((amount*vatpc)/100);
		row.find('.amount').val(amount.toFixed(2));
		var purtotal = (Number(row.find('.rate').val())+Number(row.find('.vatamt').val()));
		row.find('.ptotal').val(purtotal.toFixed(2));
		var svatpc = Number(row.find('.svatpc').val());
		 var srate = (Number(row.find('.srate').val())*Number(row.find('.qty').val()));
		 row.find('.svatamt').val((srate*svatpc)/100);
		//row.find('.amount').val().toFixed(2);
		//row.find('.amount').val("helo");
		}
	update_total();
	}


function update_gtotal()
{
	//$('#educessa').val(($('#educessr').val()*$('#total').val()*.01).toFixed(2));

	//$('#sheducessa').val(($('#sheducessr').val()*$('#total').val()*.01).toFixed(2));
    

	//$('#sevta').val(($('#sevtr').val()*$('#total').val()*.01).toFixed(2));

        var total = 0;
  $('.vatamt').each(function(i){
    amount = $(this).val();
    if (!isNaN(amount)) 
	total=parseFloat(total+Number(amount));
  });
   $('#sevta').val(total.toFixed(2));

	$('#extraa').val(($('#extrar').val()*$('#total').val()*.01).toFixed(2));
	
	var stax=0;
	if($('#Stvat').prop('checked'))
	stax=Number($('#sevta').val());
	

	var gtot=Number($('#sevta').val())+Number($('#extraa').val())+Number($('#total').val());
	$('#g_total').val(gtot.toFixed(2));
	$('#g_total').trigger('blur');
	}

function bind() {
		
  $(".qty").blur(update_amount);
  $(".rate").blur(update_amount);
   $("#Stvat").click(update_amount);
    $(".vatpc").blur(update_amount);
	 $(".srate").blur(update_amount);
	  $(".svatpc").blur(update_amount);
}

function validation()
{
	if($('#buyer_code').val()=="")
	{
	jSuccess("Blank Buyer Code");
	$('#buyer_code').focus();
	return false;
	}
	else if($('#enquiry_no').val()=="")
	{
	jSuccess("Blank Entry Ref");
	$('#enquiry_no').focus();
	return false;
	} 
	else if($('#buy_email').val()=="")
	{
	jSuccess("Blank Email");
	$('#buy_email').focus();
	return false;
	}
	else 
	return true;
	}

function print()
{
		$('#print').click(function () {
var oid=$('#invoice_no').val();
var word=$('#tot_words').val();
if(oid!='')
{$("#transperent").show();
	$.post('pinvoice_export_pdf.php', {order:oid,tword:word,PrePrint:$('#PrePrint').prop('checked'),Logo:$('#Logo').prop('checked'),Stvat:$('#Stvat').prop('checked')},function () {
	
				window.open("pinvoice.pdf",'','width=500,height=400');
				$("#transperent").hide();

	});
}
});	
		

	}	
function roundoffval()
{
	if($('#roundoff').prop('checked')==true)
	{

	$('#g_total').val(Math.round($('#g_total').val()).toFixed(2));
	$('#g_total').trigger('blur');	

	}
	else
	 update_amount();
	}	
	
	
function invoice_getdet(){
var oid=$('#invoice_no').val();
if(oid!="")
{
	    $('#transperent').show();
$.post("pinvoice_crud.php?mode=edit3",{'invoice_no':oid},function(html){
  var str=html.split('$$$');
  /*$('#enquiry_id').val(str[0]);
  $('#city').val(str[1]);
  $('#country').val(str[2]);
  $('#division').val(str[3])*/
  $('#buyer_code').val(str[0]);
  $('#company').val(str[1]);
  $('#address').val(str[2]);
 /* $('#buy_country').val(str[7]);*/
  $('#buy_city').val(str[3]);
  $('#buy_email').val(str[4]);
  $('#buy_phone').val(str[5]);
  $('#buy_fax').val(str[6]);
  $('#subject').val(str[7]);
  
 /* $('#enquiry_no').val(str[12]);
  $('#enquiry_date').val(str[13]);
  $('#due_date').val(str[14]);
  $('#place_of_del').val(str[15]);*/
  $('#pay_opt').val(str[8]);
 /* $('#quot_status').val(str[17]);
  $('#recv_mode').val(str[18]);
  $('#ref_to').val(str[19]);*/
  $('#cp_name').val(str[9]);
 /* $('#cp_mobile').val(str[21]);
  $('#cp_email').val(str[22]);
  $('#remarks').val(str[23]);
    $('#quot_curr').val(str[24]);*/
  $('#pay_terms').val(str[10]);
  /*$('#dest').val(str[26]);
  $('#freight').val(str[27]);
  $('#validity').val(str[28]);
  $('#mode_of_disp').val(str[29]);
  $('#quot_smode').val(str[30]);
  $('#prep_by').val(str[31]);
  $('#check_by').val(str[32]);*/
 // $('#educessr').val(str[11]);
 // $('#educessa').val(str[12]);
  $('#sevtr').val(str[13]);
  $('#sevta').val(str[14]);
 /* $('#exiser').val(str[37]);
  $('#exisea').val(str[38]);
  $('#octrair').val(str[39]);
  $('#octraia').val(str[40]);*/
 // jSuccess(str[40]);
  //$('#sheducessr').val(str[15]);
 // $('#sheducessa').val(str[16]);
  $('#total').val(str[17]);
  $('#g_total').val(str[18]);
   /* $('#quot_id').val(str[45]);
	$('#project').val(str[46]);*/
	$('#disclaimer').val(str[19]);
	$('#orderref').val(str[20]);
	 $('#make').val(str[21]);
	 $('#model').val(str[22]);
	 $('#serial').val(str[23]);
	 $('#imei').val(str[24]);
	 $('#orderdate').val(str[25]);
		/*$('#prices').val(str[50]);
	 $('#taxes').val(str[51]);
	 $('#delivery').val(str[52]);
	 $('#warranty').val(str[53]);
	 $('#disr').val(str[54]);
	 $('#disa').val(str[55]);*/
	 $('#extra').val(str[26]);
	 $('#extrar').val(str[27]);
	 $('#extraa').val(str[28]);
	$('#invno').val(str[29]);
	 
	/* $('#insp_duty').val(str[59]);
	 $('#order_id').val(str[60]);*/
	$('#g_total').trigger('blur');
		  $('#process').show();
  //jSuccess(str[42]);
   $.post("piproduct_fill.php",{'invoice_no':$('#invoice_no').val()},function(html){
	  $('#prod_details').html(html); 
	  $("#table_prod_details").createScrollableTable({
	            width: '1020',
	            height: '194'
	        });
						$('#update').fadeIn("slow");

	  focus_on_enter() ;
	  oproduct_fill_rel();
	  update_amount();
	    $('#transperent').hide();
  });
									
   
  
  });
  
  
 
}
	
}	
