// JavaScript Document
$(document).ready(function(e) {

	
		   var formatResult = function(data) {
            return  data.text;
        };
		
	
		
/* ============ add new client ==============*/		
$("#clientInfo_form").validate();
$("#savemodel_clientx").click(function(e) {
	
	
   if ($('#clientInfo_form').validate().form()) {
	$.ajax({
			type: 'POST',
			url: 'billreceiptAjaxController.php?do=add',
			data: $("#clientInfo_form").serialize(),
			success: function(data) {
				
						if(data == '1')
						{
							document.getElementById("newclientName").style.backgroundColor = "yellow";
							document.getElementById("RepeatedName").style.display = "";
							document.getElementById("RepeatedName").style.color = "red";
							$("#newclientName").val('');
						
							
						}
						else
						{
							if(data != '2')
							{
								document.getElementById("RepeatedName").style.display="none";
							
								$("#clientIdDiv").html(data);
								$('#myModal_client').modal('hide');
							
									$addclientId=$('#addclientId').val();
									$addclientnam=$('#addclientnam').val();
									$("#comp_client").select2();
									$("#comp_client").select2("data", {id: $addclientId, text: $addclientnam});
									
								
							
							}
							else
							{
								alert("يرجى ادخال البيانات بشكل صحيح");
							}
							
						}
							
			}
        });
   }
});
 /* ============ client insurance ==============================================================================*/
/* ============ add new supplier ==============*/
$(".client_supplier").live('change', function() {
        var comp_client_val = $(this).val();
        var data_no_supplier = $(this).attr("data-no");
		
	if (comp_client_val == -2) {
            var elemposition = $(this).data('position');
            $("#myModal_supplier").find(".savemodel_client").attr('data-position', elemposition);
            $("#myModal_supplier").find("#datanosupplier").val(data_no_supplier);
            $('#myModal_supplier').modal('show');
        
   }

$("#supplierInfo_form").validate();
 
$("#savemodel_supplierx").click(function(e) {
   if ($('#supplierInfo_form').validate().form()) {
	  var itr=document.getElementById("datanosupplier").value;
	  var itcc=document.getElementById("clint_insure_no").value;
	  
	  //$("#datanosupplier").val());
	$.ajax({
			type: 'POST',
			url: 'billreceiptAjaxController.php?do=addsupplier&itr='+itr,
			data: $("#supplierInfo_form").serialize(),
			success: function(data) {
				
				if(data == '1')
						{
							document.getElementById("newsupplierName").style.backgroundColor = "yellow";
							document.getElementById("RepeatedNamex").style.display = "";
							document.getElementById("RepeatedNamex").style.color = "red";
							$("#newsupplierName").val('');
						
							
						}
						else
						{
							document.getElementById("newsupplierName").style.backgroundColor = "white";
							//document.getElementById("RepeatedNamex").style.display = none;
							//document.getElementById("RepeatedNamex").style.color = "red";
							if(data != '2')
							{
								document.getElementById("RepeatedName").style.display="none";
							
								
								 $("#myModal_supplier").find("#newsupplierName").val('');
								  $("#myModal_supplier").find("#newsupplierdebt").val('');
								   $("#myModal_supplier").find("#supplieraddress").val('');
								    $("#myModal_supplier").find("#supplierphone").val('');
									$("#myModal_supplier").find("#supplierdetails").val('');
								// $("#myModal_supplier").removeData($('#newsupplierName').val());
								
											$("#supplierIdDiv"+itr).html(data);
									
											$('#myModal_supplier').modal('hide');
									
											$addsupplierId=$('#addsupplierId'+itr).val();
											$addsuppliernam=$('#addsuppliernam'+itr).val();
											
											$("#client_supplier"+itr).select2();
											$("#client_supplier"+itr).select2("data", {id: $addsupplierId, text: $addsuppliernam});
										
							
							}
							else
							{
								alert("يرجى ادخال البيانات بشكل صحيح");
							}
							
						}
							
						
			}
        });
   }
   
});

});
 /* ============ load all company_supplier buy ajax ==============*/
 $("#company_supplier1").select2({
            placeholder: " اسم المورد",
            //minimumInputLength: 3,
            minimumInputLength: document.getElementById("searchvalue").value,
            //	  maximumSelectionSize:3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "billreceiptAjaxController.php?do=getallsupplier",
                dataType: 'json',
                data: function(term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10 // page size
                    };
                },
                results: function(data) {

                    return {results: data};
                   
                }
            },
            formatResult: formatResult,
            initSelection: function(element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        });
 
/* ============ add new product ==============*/
$("#product1").select2({
	
			   placeholder: "إسم المنتج",
           // minimumInputLength: 3,
           minimumInputLength: document.getElementById("searchvalue").value,
            //	  maximumSelectionSize:3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProducts2",
                dataType: 'json',
                data: function(term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10 // page size
                    };
                },
                results: function(data) {
					
                    return {results: data};
                }
            },
            formatResult: formatResult,
            initSelection: function(element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
		});
	/* ============ add new productcompany ==============*/	
$("#productcompany1").select2({
	
			   placeholder: "إسم المنتج",
           // minimumInputLength: 3,
           minimumInputLength: document.getElementById("searchvalue").value,
            //	  maximumSelectionSize:3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProducts2",
                dataType: 'json',
                data: function(term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10 // page size
                    };
                },
                results: function(data) {
					
                    return {results: data};
                }
            },
            formatResult: formatResult,
            initSelection: function(element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
		});
		
		/* ============ add new productmantance ==============*/	
$("#productmantance1").select2({
	
			   placeholder: "إسم المنتج",
           // minimumInputLength: 3,
           minimumInputLength: document.getElementById("searchvalue").value,
            //	  maximumSelectionSize:3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProducts2",
                dataType: 'json',
                data: function(term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10 // page size
                    };
                },
                results: function(data) {
					
                    return {results: data};
                }
            },
            formatResult: formatResult,
            initSelection: function(element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
		});
 /* ============ load all client_supplier buy ajax ==============*/
$("#client_supplier1").select2({
	
			   placeholder: "إسم المورد",
           // minimumInputLength: 3,
           minimumInputLength: document.getElementById("searchvalue").value,
            //	  maximumSelectionSize:3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "billreceiptAjaxController.php?do=getallsupplier",
                dataType: 'json',
                data: function(term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10 // page size
                    };
                },
                results: function(data) {
					
                    return {results: data};
                }
            },
            formatResult: formatResult,
            initSelection: function(element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
		});

/* ============ load all client_serial buy ajax ==============*/	
 $(".client_serial").live('keyup', function() {
	
	
	 
	 var serialvalue=$(this).val();
	 
	 
	  var no = $(this).attr("data-no");
	  var productid =$('#product'+no).val();
	  
	
	 if(productid =="")
	 {
		 
		 $(this).val('');
		 $(this).val('plase choose product');
		$("#selectfirst"+no).css('display','block');
		$("#selectfirst"+no).css('color','#906');
		
	 }
	 else
	 {
		 $("#selectfirst1").css('display','none');
		  
        $.ajax({
			type: 'POST',
			url: 'billreceiptAjaxController.php?do=getallproductserial&productid='+productid+'&serial='+serialvalue+'&no='+no,
		
			success: function(data) {
				
				var ddd = eval(data);
				//alert(ddd);
			/*for(var index in ddd)
				{*/
					
					//document.getElementById('client_sellbill_serial'+no).value=ddd[0];
					//alert("index " + index + "result" + ddd[index]);
					$("#client_sellbill_serial"+no).val(ddd[0])
					$("#client_buybill_serial"+no).val(ddd[1]);
					$("#client_sellbill_date"+no).val(ddd[2]);
					$("#client_buybill_date"+no).val(ddd[3]);
					$("#client_buybill_type"+no).val(ddd[4]);
					$("#client_sellbill_type"+no).val(ddd[5]);
					$("#client_insurce_duration"+no).val(ddd[6]);
					$("#optionsRadiostype"+no).val(ddd[7]);
					
					$("#addsupplierId"+no).val(ddd[8]);
					$("#addsuppliernam"+no).val(ddd[9]);
	//alert(ddd[8]);
	//alert(ddd[9]);
	//('addsupplierId'+$('#addsupplierId'+no).val());
	
	 $("#client_supplier"+no).select2("data", {id: $('#addsupplierId'+no).val(), text: $('#addsuppliernam'+no).val()});
	 
					if($("#optionsRadiostype"+no).val() == 0)
					{
						$("#optionsRadios"+no).attr('checked',true);
					}
					else
					{
						$("#optionsRadiosx"+no).attr('checked',true);
					}
					
				}
				
			});
	 }
 });


 
 
 /* ============ company insurance ==============================================================================*/
 
  /* ============ add new company supplier ========*/
 $(".company_supplier").live('change', function() {
        var comp_company_val = $(this).val();
        var data_no_supplier = $(this).attr("data-no");
        if (comp_company_val == -2) {
            var elemposition = $(this).data('position');
            $("#myModal_supplierx").find(".savemodel_company").attr('data-position', elemposition);
            $("#myModal_supplierx").find("#datanocompanysupplierx").val(data_no_supplier);
            $('#myModal_supplierx').modal('show');
			
        }
		
		$("#supplierInfox_form").validate();
 
$("#savemodel_supplierxx").click(function(e) {
   if ($('#supplierInfox_form').validate().form()) {
	  var itr=document.getElementById("datanocompanysupplierx").value;
	  
	 
	$.ajax({
			type: 'POST',
			url: 'billreceiptAjaxController.php?do=addcompanysupplier&itr='+itr,
			data: $("#supplierInfox_form").serialize(),
			success: function(data) {
				
				if(data == '1')
						{
							document.getElementById("newsupplierName").style.backgroundColor = "yellow";
							document.getElementById("RepeatedNamex").style.display = "";
							document.getElementById("RepeatedNamex").style.color = "red";
							$("#newsupplierNamex").val('');
						
							
						}
						else
						{
							if(data != '2')
							{
								document.getElementById("RepeatedName").style.display="none";
							
								
								 $("#myModal_supplierx").find("#newsupplierName").val('');
								  $("#myModal_supplierx").find("#newsupplierdebt").val('');
								   $("#myModal_supplierx").find("#supplieraddress").val('');
								    $("#myModal_supplierx").find("#supplierphone").val('');
									$("#myModal_supplierx").find("#supplierdetails").val('');
								// $("#myModal_supplier").removeData($('#newsupplierName').val());
								
											$("#supplierIdDivxx"+itr).html(data);
									
											$('#myModal_supplierx').modal('hide');
									
											$addsupplierId=$('#addsupplierIdx'+itr).val();
											$addsuppliernam=$('#addsuppliernamx'+itr).val();
											
											$("#company_supplier"+itr).select2();
											$("#company_supplier"+itr).select2("data", {id: $addsupplierId, text: $addsuppliernam});
										
							
							}
							else
							{
								alert("يرجى ادخال البيانات بشكل صحيح");
							}
							
						}
							
						
			}
        });
   }
   
});

 });
  /* ============ add new company buybill ========*/
  
  $(".company_serial").live('keyup', function() {
	
	
	 var serialvalue=$(this).val();
	  var no = $(this).attr("data-no");
	 
	  var productid =document.getElementById("productcompany"+no).value;
	 if(productid =="")
	 {
		 
		 $(this).val('');
		$("#selectfirstcompany"+no).css('display','block');
		$("#selectfirstcompany"+no).css('color','#906');
		
	 }
	 else
	 {
		 $("#selectfirstcompany"+no).css('display','none');
		  
        $.ajax({
			type: 'POST',
			url: 'billreceiptAjaxController.php?do=getallproductserial&productid='+productid+'&serial='+serialvalue+'&no='+no,
		
			success: function(data) {
				var ddd = eval(data);
				/*for(var index in ddd){*/
					$("#company_buybill_serial"+no).val(ddd[1]);
					$("#company_buybill_date"+no).val(ddd[3]);
					$("#company_insurce_duration"+no).val(ddd[6]);
					$("#company_optionsRadiostype"+no).val(ddd[7]);
					
					$('#addsupplierIdx'+no).val(ddd[8]);
					$('#addsuppliernamx'+no).val(ddd[9]);
					 $("#company_supplier"+no).select2("data", {id: $('#addsupplierIdx'+no).val(), text: $('#addsuppliernamx'+no).val()});
					 
					if($("#company_optionsRadiostype"+no).val() == 0)
					{
						$("#company_optionsRadios"+no).attr('checked',true);
					}
					else
					{
						$("#company_optionsRadiosx"+no).attr('checked',true);
					}
				//}
				
			}});
	 }
	 
	 
	

 });


/* =============================================================================================================*/
/* $("#mantance").click(function(e) {
   
   var e = document.getElementById('mantancediv');
  	
       if(e.style.display == 'block')
	   {
          e.style.display = 'none';
		 }
       else
	   {
          e.style.display = 'block';
		  	caculcateshiprecept();
    		caculcateinitialrecept();
		 
	   }
	//$(this).parent('h6').parent('div').hide();
});*/

/*$("#company").click(function(e) {
   
    var ex = document.getElementById('companydiv');
  			
			 if(ex.style.display == 'block')
			   {
				  ex.style.display = 'none';
				  
				  
				 }
			   else
			   {
				  ex.style.display = 'block';
				  caculcateshiprecept();
    				//caculcateinitialrecept();
			   }
	
	//$(this).parent('h6').parent('div').hide();
});
*/
/*$("#client").click(function(e) {
   
   var e = document.getElementById('clientdiv');
  	
       if(e.style.display == 'block')
	   {
		   $(".client_removeproduct").parent().parent().remove();
          e.style.display = 'none';
		  caculcateshiprecept();
    		caculcateinitialrecept();
		 }
       else
	   {
          e.style.display = 'block';
		  	caculcateshiprecept();
    		caculcateinitialrecept();
		 
	   }
	//$(this).parent('h6').parent('div').hide();
});*/
//caculcateshiprecept();
//caculcateinitialrecept();
});
/////mantancediv

 /* var caculcateshiprecept = function() {
        var caculcateshiprecept_total = 0;
        $(".ship_value").each(function() {
			
            caculcateshiprecept_total += Number($(this).val());
        });
        $(".company_ship_value").each(function() {
			
			var ex = document.getElementById('companydiv');
			 if(ex.style.display == 'none')
			   {
				   $(this).parent().parent().remove();
				  caculcateshiprecept_total +=0;
			 	}
			   else
			   {
				   caculcateshiprecept_total += Number($(this).val());
			   }
            //caculcateshiprecept_total += Number($(this).val());
			
			//caculcateinitialrecept_total += Number($(this).val());
        });
		
        $("#recept_total_shop").html(caculcateshiprecept_total);
		 $("#recept_total_shopx").val(caculcateshiprecept_total);
    };
	*/

/*
    var caculcateinitialrecept = function() {
        var caculcateinitialrecept_total = 0;
        $(".intinal_value").each(function() {
            caculcateinitialrecept_total += Number($(this).val());
        });
		
		
		$(".company_intinal_value").each(function() {
			
			var ex = document.getElementById('companydiv');
			 if(ex.style.display == 'none')
			   {
				  caculcateinitialrecept_total +=0;
			 	}
			   else
			   {
				   caculcateinitialrecept_total += Number($(this).val());
			   }
            
        });
        $(".mantance_intinal_value").each(function() {
            
			
			var e = document.getElementById('mantancediv');
			   if(e.style.display == 'none')
			   {
		 			caculcateinitialrecept_total +=0;
					
			   }
			   else
			   {
				  
					caculcateinitialrecept_total += Number($(this).val());
			   }
        });
        $("#recept_total_intinal").html(caculcateinitialrecept_total);
		 $("#recept_total_intinalx").val(caculcateinitialrecept_total);
    };
    
 
 var calutecompanyshiptotal = function() {
        var company_ship_total = 0;
        $(".company_ship_value").each(function() {
            company_ship_total += Number($(this).val());
        });
        $("#company_total_ship").html(company_ship_total);
		$("#company_total_shipx").val(company_ship_total);
    };*/