$(document).ready(function() {
   $("input:text,textarea").focus(function(){
    $(this).css("background-color","#cccccc");
  });
  $("input:text,textarea").blur(function(){
    $(this).css("background-color","#ffffff");
  });
$("#ex_excel").hide();
$("#ex_tally").hide();
$( "#from" ).datepick();
$( "#to" ).datepick();


$('#ex_tally_xml').click(function() {	
if($('#tallyxml').prop('checked'))
$win=window.open('getxml.php?mode=xml',"mywindow","menubar=1,resizable=1,width=50,height=50,left=250,top=80");
//else
//$win=window.open('getxml.php?mode=log',"mywindow","menubar=1,resizable=1,width=50,height=50,left=250,top=80");

window.close($win);
});
 
$("#New").click(function() {
  //  $('#bookingform').find("input[type=text],select, textarea").val("");
   var vouchertype    = $("#vouchertype").val();
  if(vouchertype=='RECEIPT')
  positionedPopup("vch_entry.php?mode=RECEIPT",620);
  else  if(vouchertype=='PAYMENT')
  positionedPopup("vch_entry.php?mode=PAYMENT",620)
  else  if(vouchertype=='PURCHASE')
  positionedPopup("vch_entry.php?mode=PURCHASE",620)
  else  if(vouchertype=='CREDITNOTE')
  positionedPopup("vch_entry.php?mode=CREDITNOTE",620)
  else  if(vouchertype=='JOURNAL')
  positionedPopup("vch_entry.php?mode=JOURNAL",620)
  else  if(vouchertype=='CONTRA')
  positionedPopup("vch_entry.php?mode=CONTRA",620)
  else  if(vouchertype=='SALES')
 //jSuccess("Please create sales voucher from billing");
  positionedPopup("vch_entry.php?mode=SALES",620);

});    


	$("#ex_excel").click(function() {

$temp_search=$('#demo').clone();

$('#excel_interstep').html($temp_search);

$temp_search=$('#excel_interstep div tr[filtermatch="false"],#excel_interstep div .filters').remove();				

var data=$('#excel_interstep div').html();

$('body').prepend("<form method='post' action='voucher_export_excel.php?type=voucher_det' style='display:none' id='ReportTableData'><input type='text' name='tableData' value='"+data+"' ></form>");

$('#ReportTableData').submit().remove();

$('#excel_interstep').html('');

});
 
 
 $("#search").click(function()  {
				 
	$('#tally_status').hide();
		
	
		 
        		var from_date= $("#from").val();
		        var to_date    = $("#to").val();
		        var vouchertype    = $("#vouchertype").val();
				var cmp_key=$("#cmpsort").val();
				var billedto= $("#billedto").val();
				 var filltertype = $("#filltertype").val();
				var filltertext = $("#filltertext").val();
				var city=$("#city").val();
				var expst=$("#expst").val();
				

        // forming the queryString
        var data = 'from_date='+ from_date+'&to_date='+to_date+'&vouchertype='+vouchertype+'&cmp_key='+cmp_key+'&billedto='+billedto+'&city='+city+'&expst='+expst+'&filltertype='+filltertype+'&filltertext='+filltertext;
        
            // ajax call
			 $('#transperent').show();
			$.post("vchreg_fill.php",data,function(html){
				var str = html.split('###');
                    $('#form_bookdetails').html(str[0]);
					$('#message').html('TOTAL VOUCHERS = '+str[2]+'  / NET TOTAL AMOUNT ='+str[1]);
					
					
						//make table sticky
						/*$("#demotable1").createScrollableTable({
	           		 	width: '100%',
	            		height: '450'
	        			});
				
			
					
					//table filter	
				var options = {
				clearFiltersControls: [$('#search')],
				enableCookies :false            
				};
				$('#demotable1').tableFilter(options);
				$('#demotable1').tableFilterRefresh();	
				
				//remove default header by filter script
				$('#demotable1 thead tr:eq(0)').remove();*/
				
				var target = $("#demotable"); // <== Getting raw element
  $("#demotable1").scroll(function() {
   target.prop("scrollTop", this.scrollTop)
          .prop("scrollLeft", this.scrollLeft);
  });
			
			
			
			$("#demotable1").tablesorter({
			theme: 'default',
			widthFixed: false,
			showProcessing: true,
			//headerTemplate : '{content} {icon}', // Add icon for various themes

			widgets: ['filter', 'zebra', 'stickyHeaders'  ],
			
    		widgetOptions : {
			filter_searchDelay: 300,
			stickyHeaders_attachTo : '#demotable'
			
			}
		
			});
			//	$("#demotable1 tr.tablesorter-filter-row td:eq(0)").hide();
			
				//disable typing of textarea
				$('#demotable1 textarea').keydown(function(){
				return false;
				});
				
				//calulate total of amount dynamically
				$('.filter').change(function(){
					var sum = 0;
					//iterate through each td based on class and add the values
					  $("#demotable1 tr[filtermatch!=false] .calc_sum").each(function() {
					
						  //add only if the value is number
						  if(!isNaN(this.value) && this.value.length!=0) {
							  sum += parseFloat(this.value);
						  }
					
					  });
					  $('#message').html('NET TOTAL AMOUNT ='+sum.toFixed(2));
					  
					  
					});
				
				
				//hide transperent screen
			 	$('#transperent').hide();
			 
            });   
			 
			$(".add").show();
			$(".ex_excel").show();
		
		

		if(vouchertype=='SALES'||vouchertype=='RECEIPT'||vouchertype=='PURCHASE'||vouchertype=='PAYMENT'||vouchertype=='CREDITNOTE'||vouchertype=='JOURNAL'||vouchertype=='LEDGER')
		{
		$('.ex_tally,.alter_status').show();
		}
		else
		{
		$('.ex_tally,alter_status').hide();
		}
	
 
			
        return false;
		   

    });
	
	
	$('#ex_tally').click(function () {
		$('#tally_status').html('').fadeIn(2000);
		var billedto;
		var billno;
		var status;
		var mode;
		var first_flag=false;

		var tableSize = $('#form_bookdetails  table tbody  tr').length;	
		var actableSize=0;
		for( i=0;i<tableSize;i++)
		{
			
		$row=$('#form_bookdetails  table tbody  tr:eq('+i+')');
	if(
	$row.find("textarea[name=v_status]").val().substr(0,5)!='Tally'
&&($("#vouchertype").val()=='LEDGER'||Number($row.find("textarea[name=v_debit]").val())>0)
	)
		actableSize++;
		}	
			
		for( i=0;i<tableSize;i++)
		{
			 $.ajaxSetup({async:false});
			
	$row=$('#form_bookdetails  table tbody  tr:eq('+i+')');
	if(
	$row.find("textarea[name=v_status]").val().substr(0,5)!='Tally'
	&&($("#vouchertype").val()=='LEDGER'||Number($row.find("textarea[name=v_debit]").val())>0)
	)
	
	{
		if($("#vouchertype").val()!='LEDGER')
		{
		   billedto=$row.find("textarea[name=v_billedto]").val();
		   billno=$row.find("textarea[name=v_billno]").val();
		   status=$row.find("textarea[name=v_status]").val();
			  
		  
			  $.post('ledgersearch.php', {billedto:billedto},function (html) {
				  //$('#transperent').hide();
				  if($.trim(html)=='error')
				  {
					  var ledger=prompt("Ledger for " +billedto+ " For Bill No. " +billno+" not found\nPls Enter Tally Ledger Name");
		  
				  if (ledger!=null)
				   {
					   $.ajaxSetup({async:false});
					  $.post('ledgerentry.php', {ledger:ledger,billedto:billedto},function (html) {
						  //if($.trim(html)!='')
						  //jSuccess(html);
						  
					  });
					  }
					  else
					  return;
					  
					  }//ends if($.trim(html)=='error')
			  
		  
			  });//ends post ledgersearch
		}
			
	
		
		if(first_flag==false)
		{
		first_flag=true;
		cc=0;
		}
		else
		cc++;;
	

		$.ajaxSetup({async:true});
		//$('#transperent').show();
		if($('#tallyxml').prop('checked'))
		mode='xmlfile';
		else
		mode='tally';
	
		$.post('tallyexport.php?vch_type='+$("#vouchertype").val()+'&mode='+mode+'&counter='+cc+'&total='+(Number(actableSize)-1), $row.find("select, textarea, input").serialize(),function (html) {
			//jSuccess(html);
			//$.ajaxSetup({async:false});
			
			var str=html.split('###');
			//jSuccess(html);
			var status=str[0].split("@@@");
			if($.trim(html)!='')
			{
			$('#tally_status').prepend(status[0]);
			}
			
			if(status[1]==status[2])
			{
				if($('#tallyxml').prop('checked'))
				$('#ex_tally_xml').trigger('click');
				else
				{
					$('#ex_tally_xml').trigger('click');
				if(str[1]!="error")
				jSuccess("Tally Export Done");
				}
			$('#transperent').hide();
			}
			
			
	
		});
	
	//if(cc==(Number(actableSize)-1))
		//$('#transperent').hide();
			}//tally ckh ends
			
			else 
			{
			if(first_flag==false)
			first_flag=false;
			}
			
	}//for ends
	


	
});
 $.ajaxSetup({async:true});	
 
 	/*alter status of voucher*/
	$('#alter_status').click(function () {
		var srno='';
		var enteredExpst=$('#expst').val();
		$( "#form_bookdetails table tbody tr:not(.filtered)" ).each(function() {
			 srno=srno+$( this ).find( "textarea:eq(0)" ).val()+',';
			
		  });
		  if($.trim(enteredExpst)=='')
		  {
		  var r=confirm("Blank Status will be updated \n Press OK to continue");
				if (r==false)
			  {
				
			 $('#expst').focus();
			  }
			  else
			  {
				  $('#transperent').show();
				  $.post('save_bill_det.php?mode=alterstatus&vtype='+$('#vouchertype').val(), {srno:srno.substring(0,srno.length-1),status_value:enteredExpst}, function (html) {
			//jSuccess(html);
			var str=html.split("###");
			if(str[1]=='0')
			{
			jSuccess("Status Updated");
			}
			else
			{
			jSuccess("Error:"+str[2]);
			}
			$('#transperent').hide();
			});//post ends
				  }
		  }
		  else
		  {
			  $('#transperent').show();
			$.post('save_bill_det.php?mode=alterstatus&vtype='+$('#vouchertype').val(), {srno:srno.substring(0,srno.length-1),status_value:enteredExpst}, function (html) {
			//jSuccess(html);
			var str=html.split("###");
			if(str[1]=='0')
			{
			jSuccess("Status Updated");
			}
			else
			{
			jSuccess("Error:"+str[2]);
			}
			$('#transperent').hide();
			});//post ends
		  }
	});
	/*alter status of voucher ends*/
	
		$('#filltertext').keydown(function(e) {


if(e.keyCode==13){

if($('#filltertype').val()=='VCHSEARCH')
positionedPopup('vch_entry.php?mode='+$('#vouchertype').val()+'&vchno='+$('#filltertext').val(),670);

return false;
}
});



if($('#filltertype').val()=='COMPANY'){


	
    $("#filltertext").autocomplete(
      "billedto.php?",
      {
  			delay:50,
  			minChars:2,
  			matchSubset:1,
  			matchContains:1,
  			cacheLength:10,
			sortResults :false,
  			autoFill:false
  		});
	}
	
	
	
	/*

  function to animate upcoming duties

  */
  $("#upcomingDuties .dragDown").click(function()
  {
    var divHeight = 0;
    var div = $("#upcomingDuties .dataDiv");
    if (div.hasClass('show'))
    {
      div.html('');
      divHeight = 0;
      div.animate(
      {
        height: divHeight
      }, 1000, function()
      {
        if (!div.hasClass('show'))
        {
          div.addClass('show');
        }
        else
        {
          div.removeClass('show');
        }
      });
    }
    else
    {
      $.post('bookingdet_fill.php',
      {
        'bookingtype': 'outstandingBills'
      }, function(html)
      {
        if (html == 0)
        {
          divHeight = 20;
          div.html('No Outstanding Bills.');
        }
        else
        {
          divHeight = 200;
          div.html(html);
        }
        div.animate(
        {
          height: divHeight
        }, 1000, function()
        {
          if (!div.hasClass('show'))
          {
            div.addClass('show');
          }
          else
          {
            div.removeClass('show');
          }
        });
      });
    }
  });

});
//document ends

var winPop;

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

}
	
 function getCSVData(){
		// $("#table_report_view tr:eq(1)").hide();
 var csv_value=$('.dataTableContainer table:eq(0)').table2CSV({delivery:'value'});
//csv_value=csv_value.replace('&amp;', "&");
 //Commented bcoz not working and replaced 
csv_value=csv_value.replace(/\&amp;/g, "&");
 $("#csv_text").val(csv_value);	
 
  $(".dataTableContainer tr:eq(1)").show();
}
