 (function ($) {
	"use strict";
 var base_url;
$(document).ready(function(){
	base_url = $('#base_url').val();
	var GodownToShopPopup = $( window ).height();
	$('#mfwAddDirectSale .modal-dialog').css('height',GodownToShopPopup-30);
	
	
	/* Fetch data by code */
	$(document).on('blur' , '.mfw_DWSaleItemCode_New' ,  function(){
		
		var _this = $(this).closest('tr');
		
		var ItemCode = $(this).val();	
		
		 if(ItemCode!=''){
			resp = check_saleitem_exist(ItemCode, _this);  
			if(resp == 0){
				toastr.error('Item already exists.');
				_this.find('.mfw_DWSaleItemCode').val('').focus();
			}else{
				get_saleitem_data(ItemCode, _this);
			}
			
		}else{
			calc_DWSalesSubtotal();
		}		
	}); 
	
	  /* delete item row */
	$(document).on("click",".wholesales_item_delete",function(){
	    var item_id = $(this).attr('id');		
	    var SaleItemAmount = $(this).attr('data-itemamount');  			
	    var totalAmount = $('#mfw_DWinvoiceTotal').val();  			
	    var mainAmount = totalAmount-SaleItemAmount;  			
		if(confirm("Are you sure you want to delete this item?")){
			var row = $(this).closest('tr');		
			$('#'+row.attr('id')).remove(); 	
			$('#mfw_DWinvoiceTotal').val(mainAmount.toFixed(2));
			
			if(item_id !== undefined &&  item_id !== ''){
				$.ajax({
				method : 'post',
				url : base_url+'Directsales/remove_wholesalesitem',
				data : {'removesaleitemId' : item_id,'total_amount':mainAmount},
				success : function(resp){
					if(resp == 1){
						toastr.success('Successfully removed');		
					}else if(resp == 0){
						toastr.success('Something went wrong, please try.');
					}
				}
			});
		} 
	}
	});
	
	
	/* reset wholesales popup modal */
	$(document).on('click' , '.mfwDWSalesModalReset' ,  function(){ 
		$("#mfwDWSalesItemFormId").validate().resetForm();
		$('#mfwDWSaleItem_Savebtn').attr("disabled", false);
		$('#mfw_SelectedSaleType').attr("disabled", false);
		$('#billno_div').hide();
		$('#mfwDWSaleItem_Savebtn').text('Generate Invoice');
		 
		$('#mfw_WholeSaleBillNo').val('');
		$('#mfw_DWUpdateSaleid').val('');	
		$('#mfw_WholeSaleType').val(''); 
		$('#mfw_WholeSaleRateType').val(''); 
		
		$('#mfwDWSalesItemFormId').find('input[type=text], input[type=number]').val('');
		$('#mfw_WholeSalePartyName').val(''); 
		$('#mfw_DWPaidAmount').val(0);
		$('#extra_dis').hide();
		$('#pay_type').hide();
		$('#Advanced_paid_amount').hide();
		$('#remaining_amount').hide();
		$('#mfw_WholeSalePartyName').focus();
		 $('#item_error').html('');
		$('#DWsale_item_tbl > tbody').html('');
		var today = new Date();
		var day = today.getDate();
		day =	day < 10 ? '0' + day : '' + day; 
		var month = today.getMonth() + 1;
		month =	month < 10 ? '0' + month : '' + month; 
		var date = day+'/'+month+'/'+today.getFullYear();
		$('#mfw_WholeSaleDate').val(date);
	});	
	
	$("#mfwDWSalesItemFormId").validate({
		rules: {
			mfwWholeSalePartyName: "required",
			mfwDWSaleItemName: "required",
			mfwDWAdvancedAmount: {
                number: true
            },
		}, 
		 
	  submitHandler: function(form) {
	      //not working
		 var error=0;
		 $('#item_error').html('');
		 var BtnType =  $('#mfw_WholeSaleRateType').val();
		 if(BtnType =='godown_rate'){
			 
			  $('#DWsale_item_tbl tbody tr').each(function(){
				  
				var Gqty = $.trim($(this).find('.mfw_DWSaleItemqty_Godown').val());
				var MESSAGE_ERROR ="Please Enter Valid Quantity";
				var Item_code = $.trim($(this).find('.mfw_DWSaleItemCode').val());
				   
				if (isNaN(Gqty) || Gqty == '') { Gqty = 0; }
			  
				if(Gqty == 0){
					$('#item_error').append('<b><p style="color:red;">Item Code('+Item_code+'):- '+ 
					MESSAGE_ERROR+'</p></b>');
					 error++;
				}
			 });
			  
			  
		 }else if(BtnType =='shop_rate4'){
			 
			  $('#DWsale_item_tbl tbody tr').each(function(){
				  
				var Sqty = $.trim($(this).find('.mfw_DWSaleItemqty_Shop').val());
				var MESSAGE_ERROR ="Please Enter Valid Quantity";
				var Item_code = $.trim($(this).find('.mfw_DWSaleItemCode').val());
				   
				if (isNaN(Sqty) || Sqty == '') { Sqty = 0; }
			  
				if(Sqty == 0){
					$('#item_error').append('<b><p style="color:red;">Item Code('+Item_code+'):- '+ 
					MESSAGE_ERROR+'</p></b>');
					 error++;
				}
			 
			 });
		 }
		 
		 
		 
		if(error ==0){
		var _this = $('#mfwDWSaleItem_Savebtn');
		var btnText = _this.text();
		var targetForm = _this.closest('form');
		$('#mfwDWSaleItem_Savebtn').attr("disabled", true);
		if(!_this.hasClass('adding')){
		    
			_this.html(btnText+' <i class="fa fa-spinner fa-pulse"></i>');//.addClass('adding');
			
			 var mfwSaleBillNo_Str = $('input[name="mfwWholeSaleBillNo"]').val(); 
			 var mfwSaleType_Str = $('input[name="mfwWholeSaleType"]').val();  
			 var mfwSaleRateType_Str = $('input[name="mfwWholeSaleRateType"]').val();
			
			 var mfwSaleDate_Str = $('input[name="mfwWholeSaleDate"]').val(); 	 
			 var mfwSelectedPartyName_Str = $('input[name="mfwWholeSalePartyName"]').val(); 
			 
			 var mfwSelectedPartyId_Str = $('input[name="mfwWholeSalePartyId"]').val(); 
			 var mfwDWPaymentType_Str = $('select[name="mfwDWPaymentType"]').val(); 
			 var mfwDWAdvancedAmount_Str = $('input[name="mfwDWAdvancedAmount"]').val();
			 var mfwDWRemainingAmount_Str = $('input[name="mfwDWRemainingAmount"]').val();
			 var mfwDWExtraDiscount_Str = $('input[name="mfwDWExtraDiscount"]').val();
    		 var UpdateSaleItemid_Arr = [];
			 var mfwSaleItemId_Arr = [];       
			 var mfwSaleItemCode_Arr = [];           
			 /* var mfwCompanyId_Arr = []; */
			 /* var mfwSaleItemName_Arr = []; */
			 var mfwSaleItemqty_Godown_Arr = [];
			 var mfwSaleItemqty_Shop_Arr = [];
			 var mfwSaleOldqty_Godown_Arr =[]; 
			 var mfwSaleOldqty_Shop_Arr =[]; 
			 var mfwSaleOldqty_itemId_Arr =[]; 
			 var mfwSaleItemGodown_Arr = [];	
			 var mfwSaleItemShop_Arr = [];
			 var mfwSaleItemboxqty_Arr = [];
			 var mfwSaleItemRate_Arr = [];
			 var mfwDWSaleItemRate_Hide_Arr = [];
			 var mfwSaleItemAmount_Arr = [];
			 var mfwSalesSubTotal_Str = $('input[name="mfwDWSalesSubTotal"]').val();
			 var mfwInvoiceTotal_Str = $('input[name="mfwDWInvoiceTotal"]').val(); 
			 // bil id
			 var mfwUpdateSaleid_Str = $('input[name="mfwDWUpdateSaleid"]').val();
			 
			 
			 $('input[name="DWUpdateSaleItemid[]"]').each(function(){
				 
				 UpdateSaleItemid_Arr.push($(this).val()); 
				 
			 });
			 var UpdateSaleItemid_Str =  UpdateSaleItemid_Arr.join("@$#");
			 
			 $('input[name="mfwDWSaleItemId[]"]').each(function(){
				 
				 mfwSaleItemId_Arr.push($(this).val()); 
				 
			 });
			 var mfwSaleItemId_Str =  mfwSaleItemId_Arr.join("@$#");
			 
			 $('input[name="mfwDWSaleItemCode[]"]').each(function(){
				 
				 mfwSaleItemCode_Arr.push($(this).val());
				  
			 });
			 var mfwSaleItemCode_Str =  mfwSaleItemCode_Arr.join("@$#");

			 
			 $('input[name="mfwDWSaleItemqty_Godown[]"]').each(function(){
				 
				  mfwSaleItemqty_Godown_Arr.push($(this).val());
				 
			 });
			 var mfwSaleItemqty_Godown_Str =  mfwSaleItemqty_Godown_Arr.join("@$#");
			 
			
			$('input[name="mfwDWSaleItemqty_Shop[]"]').each(function(){
				 
				 mfwSaleItemqty_Shop_Arr.push($(this).val());
				 
			 });
			 var mfwSaleItemqty_Shop_Str =  mfwSaleItemqty_Shop_Arr.join("@$#"); 
			 
			 $('input[name="mfwDWSaleItemGodown[]"]').each(function(){
				 
				 mfwSaleItemGodown_Arr.push($(this).val());
				 
			 });
			 var mfwSaleItemGodown_Str =  mfwSaleItemGodown_Arr.join("@$#"); 
			 
			
			  $('input[name="mfwDWSaleOldqty_Godown[]"]').each(function(){
				 
				 mfwSaleOldqty_Godown_Arr.push($(this).val());
				 
			 });
			 var mfwSaleOldqty_Godown_Str =  mfwSaleOldqty_Godown_Arr.join("@$#"); 
			 
			 
			  $('input[name="mfwDWSaleOldqty_Shop[]"]').each(function(){
				 
				 mfwSaleOldqty_Shop_Arr.push($(this).val());
				 
			 });
			 var mfwSaleOldqty_Shop_Str =  mfwSaleOldqty_Shop_Arr.join("@$#");
			 
			 $('input[name="mfwDWSaleOldqty_item_id[]"]').each(function(){
				 
				 mfwSaleOldqty_itemId_Arr.push($(this).val());
				 
			 });
			 var mfwDWSaleOldqty_item_Str =  mfwSaleOldqty_itemId_Arr.join("@$#");
			 
			 
			  $('input[name="mfwDWSaleItemShop[]"]').each(function(){
				 
				 mfwSaleItemShop_Arr.push($(this).val());
				 
			 });
			 var mfwSaleItemShop_Str =  mfwSaleItemShop_Arr.join("@$#");  
			 
			 
			  $('input[name="mfwDWSaleItemboxqty[]"]').each(function(){
				 
				 mfwSaleItemboxqty_Arr.push($(this).val());
				 
			 });
			 var mfwSaleItemboxqty_Str =  mfwSaleItemboxqty_Arr.join("@$#");
			 
			 
			  $('input[name="mfwDWSaleItemRate[]"]').each(function(){
				 
				 mfwSaleItemRate_Arr.push($(this).val());
				 
			 });
			 var mfwSaleItemRate_Str =  mfwSaleItemRate_Arr.join("@$#");
			 
			 
			 $('input[name="mfwDWSaleItemRate_Hide[]"]').each(function(){
				 
				 mfwDWSaleItemRate_Hide_Arr.push($(this).val());
				 
			 });
			 var mfwDWSaleItemRate_Hide_Str =  mfwDWSaleItemRate_Hide_Arr.join("@$#");
			  
			 // item amount total 
			 $('input[name="mfwDWSaleItemAmount[]"]').each(function(){
				 
				 mfwSaleItemAmount_Arr.push($(this).val());
				 
			 });
			 var mfwSaleItemAmount_Str =  mfwSaleItemAmount_Arr.join("@$#");
			

        	$.ajax({ 
        				method : 'post',
        				url : base_url+'directsales/Create_wholesales_item',
        				data : {mfwSaleBillNo :mfwSaleBillNo_Str,mfwWholeSaleType :mfwSaleType_Str, mfwWholeSaleRateType : mfwSaleRateType_Str, mfwWholeSaleDate : mfwSaleDate_Str,mfwWholeSalePartyName : mfwSelectedPartyName_Str,mfwWholeSalePartyId : mfwSelectedPartyId_Str,DWUpdateSaleItemid : UpdateSaleItemid_Str, mfwDWSaleItemId : mfwSaleItemId_Str,mfwDWSaleItemCode : mfwSaleItemCode_Str, mfwDWSaleItemqty_Godown :mfwSaleItemqty_Godown_Str,mfwDWSaleItemqty_Shop : mfwSaleItemqty_Shop_Str, mfwDWSaleItemGodown : mfwSaleItemGodown_Str,mfwDWSaleItemShop :mfwSaleItemShop_Str,mfwDWSaleOldqty_Godown : mfwSaleOldqty_Godown_Str, mfwDWSaleOldqty_Shop : mfwSaleOldqty_Shop_Str,mfwDWSaleItemboxqty :mfwSaleItemboxqty_Str,mfwDWSaleItemRate :mfwSaleItemRate_Str,mfwDWSaleItemRate_Hide :mfwDWSaleItemRate_Hide_Str, mfwDWSaleItemAmount : mfwSaleItemAmount_Str,mfwDWSalesSubTotal : mfwSalesSubTotal_Str, mfwDWInvoiceTotal : mfwInvoiceTotal_Str, mfwDWPaymentType: mfwDWPaymentType_Str,mfwDWAdvancedAmount : mfwDWAdvancedAmount_Str, mfwDWRemainingAmount : mfwDWRemainingAmount_Str, mfwDWExtraDiscount : mfwDWExtraDiscount_Str, mfwDWSaleOldqty_item_id : mfwDWSaleOldqty_item_Str}, 
        				success : function(resp){
        					resp = $.parseJSON(resp);
        					if(resp['status'] == 1){
        						 _this.html(btnText).removeClass('adding');
  					    		toastr.success(resp['msg']);
  					    		$( ".mfwDWSalesModalReset" ).trigger( "click" );
  					    		setTimeout( function() {
 								window.location.reload();
 							}, 500);
        					}else{
        					    _this.html(btnText).removeClass('adding');
        						toastr.success('Something went wrong, please try.');
        						$('#mfwDWSaleItem_Savebtn').attr("disabled", false);
        					}
        				}
        			});

		 
		}
	   }
	  }
	});
	
	
	
	/* Edit Sale Invoice */
	$(document).on('click' , '.wholesales_edit_btn' ,  function(){
	 
	var _this = $(this); 		
	var SalesEditId = _this.attr('data-id');
	var btnText = _this.text(); 
	if(SalesEditId !='')
	{ 
		_this.html(btnText+' <i class="fa fa-spinner fa-pulse"></i>');//.addClass('adding'); 
		$('.MfwItemNameEdit').select2("destroy");
		$.ajax({   
			method : 'post',
			url : base_url+'Directsales/edit_wholesales',
			data : {'salesId' : SalesEditId}, 
			success : function(resp){ 
				 var respData = JSON.parse(resp);				
				 if(respData['status'] == 1)
				 {
					$('#DWsale_item_tbl > tbody').html('');		
					$('#mfw_DWUpdateSaleid').val(respData['salesdata']['id']);					
					$('#mfw_WholeSalePartyId').val(respData['salesdata']['user_id']);
					$('#mfw_WholeSalePartyName').val(respData['salesdata']['user_name']);
					 $('#mfw_WholeSalePartyName').focus();
					$('#mfw_WholeSaleBillNo').val(respData['salesdata']['id']);
					$('#billno_div').show();					
					$('#mfw_WholeSaleDate').val(respData['salesdata']['sale_date']);
					$('#mfw_WholeSaleType').val(respData['salesdata']['sale_type']);
					$('#mfw_WholeSaleRateType').val(respData['salesdata']['rate_type']);
					$('#mfw_DWSalesSubTotal').val(respData['salesdata']['subtotal']);
					$('#mfw_DWinvoiceTotal').val(respData['salesdata']['total_amount']);
					$('#mfw_DWPaidAmount').val(respData['salesdata']['advance_amount']);
					$('#Advanced_paid_amount').show();
					$('#mfw_DWRemainingAmount').val(respData['salesdata']['remaining_amount']);
					$('#mfw_DWExtraDiscount').val(respData['salesdata']['extra_discount']);
					$('#extra_dis').show();
					$('#pay_type').show();
					$('#remaining_amount').show();
					
					$('#DWsale_item_tbl > tbody').append(respData['saleitemList']);
					  setTimeout( function() {					
						 
						   if(respData['salesdata']['rate_type'] =='godown_rate'){
							 
							  $('.for_godown_wholesale').show();	 
							  $('.for_shop_wholesale').hide();
						   }else if(respData['salesdata']['rate_type'] =='shop_rate4'){
							 
							  $('.for_shop_wholesale').show();
							  $('.wholesales_item_delete').show();
							  $('.for_godown_wholesale').hide();
						   }
						
						 $("#mfwAddDirectSale").modal({backdrop: "static",keyboard: false});
						
						 $('#mfwDWSaleItem_Savebtn').text('Update Invoice');				   
						_this.html(btnText+' <i class="fa fa-pencil-square-o"></i>'); 
						
					  }, 1000); 
					
									
					 
				}else if(respData['status'] == 0){ 
					_this.html(btnText+' <i class="fa fa-pencil-square-o"></i>');					
					toastr.error(respData['error']);
				} 
			}, 
			error : function(){
				_this.html(btnText+' <i class="fa fa-pencil-square-o"></i></i>');
				toastr.error('Something went wrong, please try.');
			}
		});
	}		 
  });
	
	
	
		/* Edit Sale Invoice */
	$(document).on('change' , '.deliveryStatus' ,  function(){
	 
	var _this = $(this); 		
	var SalesEditId = _this.attr('data-deliverystatus');
	var deliveryValue = $(this).children("option:selected").val();
	var btnText = _this.text(); 
	
	if(SalesEditId !='')
	{ 
	    var alertmsg = confirm("Are you sure update your order delivery?");
	    if(alertmsg==true){
    		$.ajax({   
    			method : 'post',
    			url : base_url+'directsales/deliveryStatus',
    			data : {'salesId' : SalesEditId,'deliveryValue' : deliveryValue}, 
    			success : function(resp){ 
    				 var respData = JSON.parse(resp);
    				 if(respData['status'] == 1){
    				     toastr.success(respData['msg']);
      					  setTimeout( function() {
     								window.location.reload();
     							}, 500);
    				 }else{
    			    	toastr.error(respData['error']);
    			    	
    				 }
    				 
    			}, 
    			error : function(){
    				_this.html(btnText+' <i class="fa fa-pencil-square-o"></i></i>');
    				toastr.error('Something went wrong, please try.');
    			}
    		});
	    }else{
	    return false;
	    }	
	}else{
	    return false;
	}		 
  });
	
//search filter order by date	


var currentDate = new Date();  
$(".txtDate").datepicker("setDate",currentDate);

$(document).on('submit', '.datefilter', function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');
    var form_date =$('.form_date').val();
	var to_date =$('.to_date').val();
	var customerRol =$('#customerRol').val();
	var id = $('#customer_id').val();
	if(new Date(to_date)<new Date(form_date)){
	    toastr.error('To date cannot be less than from date.');
	    return false;
	}

    if(form_date !="" && to_date !=""){
        if(id!=""){
		    var form = "/?id="+id+"&from="+form_date+"&to="+to_date ;
		    
        }else{
            if(customerRol!=""){
                var form = "/customer/?from="+form_date+"&to="+to_date ;
            }else{
                var form = "/?from="+form_date+"&to="+to_date ;
            }
        }
		   window.location.href = base_url+url+form;;
		       
		  }

});
	


$(document).on('submit', '.wholesalerName', function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');
    var select_value =$('.wholesaler_a').val();
	
	if(select_value!=0){
		  
	   window.location.href = base_url+url+select_value;; 
	}

	
});
	
	

	
	
	
	/* View wholesale invoice Button  */
	$(document).on("click",".wholesales_InvoiceViewbtn",function(){
			var saleinvoice_id = $(this).attr('data-saleinvoiceid');
			generate_wholesales_invoice(saleinvoice_id);
	});
	
	/* view wholesale  invoice function */
	function generate_wholesales_invoice(saleinvoice_id){
	    
		if(saleinvoice_id !== undefined &&  saleinvoice_id !== ''){
				$.ajax({ 
				method : 'post',
				url : base_url+'Directsales/generate_wholesales_invoice',
				data : {'invoiceId' : saleinvoice_id}, 
				success : function(resp){
				   
					var respData = JSON.parse(resp);
					if(respData['status'] == 1){
						 $('#purchase_report_modal').html(respData['itemList']);
						 $('#mfw_wholesales_invoice').modal('show');
						 $('table tr.count_row').each(function(index) {
							$(this).find('td:nth-child(1)').html(index+1);
						 });
						 
						 
					}else if(respData['status'] == 0){
						toastr.success('Something went wrong, please try.');
					}
				}
			});
		}
	}
	
	
		function nWin() {
			var w = window.open();
			var html = $("#purchase_report_modal").html();

			$(w.document.body).html(html);
			w.print();
		}

		$(function() {
			$("#mfwGenerateInvoice_new").click(nWin);
		});
	
	
	
	
	
	 /* calculate wholesale item amount */
	function calc_DWsalesAmount(_this) {
		 
		var rate =$.trim(_this.find('.mfw_DWSaleItemRate').val());
		var item_quenty = _this.find('.mfw_DWSaleItemqty_Shop').val();
		var SaleRateType = $('#mfw_WholeSaleRateType').val();
		var mfwSaleItemAmount_Arr = [];
	
		if (isNaN(rate) || rate == '') {
			rate = 0;
		}
		if (rate != '') {
		var mainAmount = rate*item_quenty;
		_this.find('.mfw_DWSaleItemAmount').val(mainAmount.toFixed(2));
		 var sumItemAmount = 0;
		$('input[name="mfwDWSaleItemAmount[]"]').each(function(index, value){
		 
		 mfwSaleItemAmount_Arr.push($(this).val());
		 
		  sumItemAmount+=parseFloat($(this).val());
	    });
	   var mfwSaleItemAmount_Str =  mfwSaleItemAmount_Arr.join("@$#");
    	$('#mfw_DWinvoiceTotal').val(sumItemAmount.toFixed(2));

		}
	} 
	
	$(document).on("keyup blur","#mfw_DWExtraDiscount",function(){
			 calc_DWSalesSubtotal();
	});

	
	$(document).on("keyup blur","#mfw_DWAdvancedAmount",function(){
			 calc_remaining_amount();
	});
	
	
/*------------------------------------- Cash Counter Secion Start ----------------------------------------------*/	
	
	
	
	$(document).on("keyup blur","#mfw_CCExtraDiscount",function(){
			 calc_CCSalesSubtotal();
	});
	

	
	
	/* Calculate Return Amount */
	$(document).on("keyup blur","#mfw_CCReceiveAmount",function(){
			 calc_return_amount();
	});

	
});

})(jQuery);