function Save_invoice_detaile(txtS){
	
	if (jQuery('form#invoice_generation').valid() === false) {
		return false;
	} else {
		
		if($('#invoice_subTotal').val()=="" || $('#invoice_client_name :selected').val()==""){
			
			$('#invoice_msg').text('Please fill all mandatory details*').css('color','red');
			setTimeout(function(){
				$('#invoice_msg').text('');
			}, 3000);
			return false;
		}else{	
			var auto_rem=0;		
			if(document.getElementById("auto_reminder").checked){
				auto_rem=1;
			} 
			 
			var invoice_price=$('input[name="invoice_price[]"]').serializeArray();
			var invoiceArray=[];
			for(var i=0; i<invoice_price.length;i++){
				invoiceArray[i]= invoice_price[i].value;		  
			}
			
			var invoiceDescription=$('input[name="invoice_Description[]"]').serializeArray();
			var descriptionArray=[];
			for(var i=0; i<invoiceDescription.length;i++){
				descriptionArray[i]= invoiceDescription[i].value;		  
			}
			var U_T_C=jQuery('#invoice_UTC').val();
			var formData = new FormData();
			formData.append('name', jQuery('#invoice_client_name :selected').val());
			formData.append('invoice_utc',jQuery('#invoice_UTC').val());
			formData.append('invoice_NO',jQuery('#invoice_NO').val());
			formData.append('invoice_Date',jQuery('#invoice_Date').val());
			formData.append('amount', JSON.stringify(invoiceArray));
			formData.append('description', JSON.stringify(descriptionArray));				
			formData.append('netamount', jQuery('#invoice_subTotal').val());
			formData.append('othercharges', jQuery('#invoice_other').val());
			formData.append('invoice_tax', jQuery('#invoice_client_tax :selected').val());
			formData.append('totalamount', jQuery("#invoice_Total").val());			
			formData.append('auto_reminder', auto_rem);			
		   
			jQuery.ajax({
				url: baseurl + 'Invoice/addInvoice',
				type: 'post',
				data: formData,
				processData: false,
				contentType: false,
				dataType: 'json',
				beforeSend: function () {
					 jQuery('.rems').remove();
					 jQuery('#footerModalDiv').html('<img width="70" src="'+baseurl+'assets/images/ajax-loading.gif">');
				},
				complete: function () {
					 
					jQuery('#add-invoice-details').find('input[type=text]').each(function () {
						jQuery(this).val('');
					});
					jQuery('#add-invoice-details').modal('hide');
				},
				success: function (html) {						 
					if(html.invoice){ 
						if(txtS=='share'){
							var emailS=$('#shareText_email').val();
							share_invoice(emailS,U_T_C);
						}
						if(txtS=="save"){
							if(html){
								$('.edit_success_msg').html('<div class="alert alert-success">Invoice Create Successfully.</div>');	 
								setTimeout(function(){
									location.reload(true);
								},3000);
							}else{
								$('.edit_success_msg').html('<div class="alert alert-success">Error! Please try again.</div>');	 
								setTimeout(function(){
									location.reload(true);
								},3000);
							}
						}
						if(txtS=='print'){						
							 window.open(baseurl+'download_pdf/invoice/'+U_T_C);
						}
					}else{
						$('.edit_success_msg').html('<div class="alert alert-danger">Error! Please Try again.</div>');	 
						setTimeout(function(){
							location.reload(true);
						},3000);
					}
					
					 
			   },
				error: function (xhr, ajaxOptions, thrownError) {
					console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
				}
			});
		}
	}
}

$(function(){ 
	
	jQuery(document).on('click', '#print_invoice_details', function () {
		Save_invoice_detaile('print');
		$('#save_invoice_details').hide();
		$('#share_invoice_details').hide();
	}); var share=1;
	jQuery(document).on('click', '#share_invoice_details', function () {
		if(share==2){ 
			if($('#removeEmail').text()!=""){
				$('#removeEmail').text('Before Remove Error.');
				$('#shareText_email').css("border-color", "#f00");
				$('#shareText_email').focus();
				return false;
			}else{				
				if($('#shareText_email').val()==""){
					$('#removeEmail').text('Please enter Share email address.');
					$('#shareText_email').css("border-color", "#f00");
					$('#shareText_email').focus();
					return false;
				}else{					
					Save_invoice_detaile('share');
				}
			}
		}else{ 
			share=2;
			var htl='<div class="col-sm-5 col-sm-push-7"><input class="form-control" id="shareText_email" placeholder="Enter Share Email Address *" value="" type="text"><p id="removeEmail" style="color:red"></p></div>';
			$('#ShareInput').html(htl);
		}
		 
		$('#save_invoice_details').hide();
		$('#print_invoice_details').hide();
	});
	jQuery(document).on('click', '#save_invoice_details', function () {
		Save_invoice_detaile('save');
		$('#print_invoice_details').hide();
		$('#share_invoice_details').hide();
	});
	

	
	$('#invoice_service_tax').change(function(){
		var amount=$('#invoice_amount').val();
		var otherCharge=$('#invoice_other_charges').val();
		var tax=$('#invoice_service_tax').val();
		var setamount=parseInt(amount)+parseInt(otherCharge);
		var netAmount=parseInt(setamount)+(parseInt(setamount)/100)*parseInt(tax);
		$('#invoice_net_amount').val(netAmount);
		$('#invoice_total_amount').val(netAmount);
		 
	});
	
});

$(document).ready(function(){
	 
	$("#invoice_other_charges").keydown(function (e) { 
		if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || 
			(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||  
			(e.keyCode >= 35 && e.keyCode <= 40)) { 
				 return;
		} 
		if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
			e.preventDefault();
		}
	});
	$(document).on("keydown",".invoice_price",function (e) { 
		if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || 
			(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||  
			(e.keyCode >= 35 && e.keyCode <= 40)) { 
				 return;
		} 
		if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
			e.preventDefault();
		}
	});
	
	jQuery(document).on('click', '#addINVOICEBTN', function () {
		var x = Math.floor((Math.random() * 100) + (Math.random() * 10));
		var html='<div id="removeDesc_'+x+'" style="display:flex;padding-bottom:10px"><span onclick="remove_desc('+x+')" class="fa fa-close" style="position: absolute; right: 15px; margin-top: 9px; color: red; cursor: pointer;"></span><div class="col-sm-9">';
		html +='<input class="form-control invoice_Description" placeholder="Description *" name="invoice_Description[]" value="" type="text">';
		html +='</div><div class="col-sm-3"><input class="form-control invoice_price" placeholder="Price *" name="invoice_price[]" value="" type="text"></div></div>';
		$('#addINvoiceDiv').append(html);
	});
	
	jQuery(document).on('change', '.invoice_price', function () {
		all_input_value();
	});
	$(document).on("click","#btnCreateInvoice",function (e) { 
		create_invoice_data();
	});
});

function remove_desc(x){
	$('#removeDesc_'+x).remove();
	all_input_value();
}
function all_input_value(){	
	var d=0;
	var subtotal=0;var tax_amount=0;
	var data=$('input[name="invoice_price[]"]').serializeArray();
	for(var i=0; i<data.length;i++){
		var c=data[i].value;
		if(c!=""){
			d += parseInt(data[i].value);
		}		  
	}
	$('#invoice_subTotal').val(d);

	var other=$('#invoice_other').val();

	if(other==""){
		subtotal=parseInt(d);      
	}else{
		subtotal=parseInt(d)+parseInt(other);
	}
	 
	var tax=$('#invoice_client_tax').val();
 
	if(tax!=0){
		tax_amount=parseInt(subtotal)*parseInt(tax)/100;
	}	
	$('#settax_price').val(tax_amount);

	$('#invoice_Total').val(tax_amount+subtotal);
}



jQuery(document).on('blur', '#shareText_email', function () { 
	var Email = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var emailID=$(this).val(); 
	var emailData=emailID.split(',');	
	 for(var i=0;i<emailData.length;i++){
		var str=emailData[i];
		if (!str.match(Email)){
			$('#removeEmail').text('Please enter a valid email address-' + emailData[i]).css('color','red');
			 
			 return false;
		}else{
			$('#removeEmail').text('').css('color','');
			$('#shareText_email').css("border-color", "");
		}
	} 
     
});
 
 function share_invoice(email,Utc){
	 jQuery.ajax({
		url: baseurl + 'Invoice/invoice_mail_listShare',
		type: 'post',
		data: {utcid:Utc,emails:email}, 
		dataType: 'json',		 
		success: function (html) {
			if(html!=""){ 
				$('.edit_success_msg').html('<div class="alert alert-success">' + html + '</div>');
				setTimeout(function(){
					location.reload(true);
				},3000);
			}else{
				$('.edit_success_msg').html('<div class="alert alert-danger">Error! Please Try again.</div>');	 
				setTimeout(function(){
					location.reload(true);
				},3000);
			}
		},
		error: function (xhr, ajaxOptions, thrownError) {
			console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
		}
	});
 }
 
 function create_invoice_data(){
	 jQuery.ajax({
		url: baseurl + 'Invoice/cerate_invoice_popup',
		type: 'post',
		data: {true:true}, 
		dataType: 'json',		 
		success: function (html) {
			var datas=html;
			if(datas.success==true){
				var clients=datas.client_list;
				var client_html='<option value="">Select Client Name</option>';
				for(var i=0; i<clients.length;i++){
					client_html +='<option value="'+clients[i].id+'">'+clients[i].client_name+'</option>';
				}
				$('#invoice_client_name').html(client_html);
				$('#invoice_UTC').val(datas.invoice_utc);
				$('#invoice_NO').val(datas.invoice_no);
				$('#invoice_Date').val(datas.invoice_date);
				var tax='';
				for (var i = 0; i <= 30; i++) {	
					if(i==datas.get_tax){
						tax += '<option selected="selected" value="'+i+'">'+i+'</option>';
					}else{
						tax +='<option value="'+i+'">'+i+'</option>';
					}
				}
				$('#invoice_client_tax').html(tax);
			}else{
				window.location.href=baseurl + 'invoice';
				
			}
			
			 
		},
		error: function (xhr, ajaxOptions, thrownError) {
			console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
		}
	});
 }
  
  