<?php $this->load->view("common/header"); ?>

<!-- end: HEAD -->

<!-- start: CSS REQUIRED FOR THIS PAGE ONLY -->
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/select2/select2.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/datepicker/css/datepicker.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/bootstrap-timepicker/css/bootstrap-timepicker.min.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/bootstrap-daterangepicker/daterangepicker-bs3.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/bootstrap-colorpicker/css/bootstrap-colorpicker.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/jQuery-Tags-Input/jquery.tagsinput.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/bootstrap-fileupload/bootstrap-fileupload.min.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>plugins/summernote/build/summernote.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>css/jquery-ui.css">
<link rel="stylesheet" href="<?php echo asset_url(); ?>css/pos.css">

<style type="text/css">

</style>

<!-- end: CSS REQUIRED FOR THIS PAGE ONLY -->

<!-- end: HEAD -->

<!-- start: BODY -->

<body>

<!-- start: HEADER -->

<div class="navbar navbar-inverse navbar-fixed-top"> 
  
  <!-- start: TOP NAVIGATION CONTAINER -->
  
  <div class="container">
    <div class="navbar-header"> 
      
      <!-- start: RESPONSIVE MENU TOGGLER -->
      
      <button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button"> <span class="clip-list-2"></span> </button>
      
      <!-- end: RESPONSIVE MENU TOGGLER --> 
      
      <!-- start: LOGO -->
      
      <?php $this->load->view("common/logo"); ?>
      
      <!-- end: LOGO --> 
      
    </div>
    <div class="navbar-tools"> 
      
      <!-- start: TOP NAVIGATION MENU -->
      
      <?php $this->load->view("common/notifications.php"); ?>
      
      <!-- end: TOP NAVIGATION MENU --> 
      
    </div>
  </div>
  
  <!-- end: TOP NAVIGATION CONTAINER --> 
  
</div>

<!-- end: HEADER --> 

<!-- start: MAIN CONTAINER -->

<div class="main-container">
<div class="navbar-content"> 
  
  <!-- start: SIDEBAR -->
  
  <?php $this->load->view("common/navigation"); ?>
  
  <!-- end: SIDEBAR --> 
  
</div>

<!-- start: PAGE -->

<div class="main-content">

<!-- end: SPANEL CONFIGURATION MODAL FORM -->

<div class="container">

<!-- start: PAGE HEADER -->

<div class="row">
  <div class="col-sm-12"> 
    
    <!-- start: PAGE TITLE & BREADCRUMB -->
    
    <!--<ol class="breadcrumb">
      <li> <a href="#"> Dashboard </a> </li>
      <li> <a href="<?php echo base_url('sales'); ?>"> Sales </a> </li>
      <li class="active"> Add Sale </li>
      <li class="search-box">
        <form class="sidebar-search">
          <div class="form-group">
            <input type="text" placeholder="Start Searching...">
            <button class="submit"> <i class="clip-search-3"></i> </button>
          </div>
        </form>
      </li>
    </ol>-->
    
    <div class="space12">
										<div class="btn-group btn-group-sm">
											<a class="btn btn-bricky active" href="<?php echo base_url('sales'); ?>" style="background-color: #428bca; font-family: arial; font-weight: bold;" target="_blank">
												<i class="clip-cart"></i> <br>
List Sales
											</a>
                                            <a class="btn btn-bricky active" href="<?php echo base_url('sales/sale_items'); ?>" style="background-color: #57517b; font-family: arial; font-weight: bold;" target="_blank">
												<i class="clip-list-2"></i> <br>
Sale Items
											</a>
                                            
											<a onClick="show_return_wapper()" id="" class="btn btn-bricky" href="javascript:;" style="background-color: #e6674a;  font-family: arial; font-weight: bold;">
												<i class="fa fa-caret-square-o-left"></i> <br>Return Sales
											</a>
											<a class="btn btn-bricky" href="<?php echo base_url('expenses/manage/0'); ?>" style="background-color: #f0ad4e; font-family: arial; font-weight: bold;">
												<i class="clip-banknote"></i> <br>New Expenses
											</a>
											<a class="btn btn-bricky" href="<?php echo base_url('transfer/add'); ?>" style="background-color: #4d8189; font-family: arial; font-weight: bold;">
												<i class="clip-transfer "></i> <br>New Transfers
											</a>
                                            
                                            <a id="modal_ajax_transactions_btn"  class="btn btn-bricky" href="javascript:;" style="background-color: #428bca; font-family: arial; font-weight: bold;">
												<i class="clip-transfer "></i> <br>Bank Deposit
											</a>
                                            <!-- 
                                            <a id="modal_ajax_help_btn" class="btn btn-bricky" href="javascript:;" style="background-color: #c8c7cc; font-family: arial; font-weight: bold;">
												<i class="clip-user-2"></i> <br>Help
                                                
                                                
											</a>
											-->
											
											<a class="btn btn-bricky" href="<?php echo base_url('reports/product_enquiry_reports'); ?>" style="background-color: #c8c7cc; font-family: arial; font-weight: bold;" target="_blank">
												<i class="clip-transfer "></i> <br>Enquiry
											</a>
                                            
                                          
    
     
										</div>
									</div>
                                    
                                    
<!-- start return box-->                                    
<div id="return_wapper" class="return_wapper" style="display:none">
    
    <div class="panel panel-default">
    <div class="panel-body">
        <div class="panel-heading">
            <i class="fa fa-plus"></i>Add Sales Return
        </div>
    
    	<p style="margin-top:20px" onClick="hide_return_wapper()" class="pull-right"><i class="clip-close-3" ></i></p>
    
    	<div id="class_middle_wappert">
            <div class="col-md-3">
            <div class="form-group">
            
            <br>
            <label>Item  </label><?php //print_r($suppliers);?>
            <input type="hidden" id="sale_id_search"  name="sale_id_search" class="js-data-sales-list-ajax form-control" style="padding:0px 0px; border: none; box-shadow: none" placeholder="-Select Item-" onChange="setitemselect()"/>
            </div>
            </div>    
            
            <div class="col-md-1">
            <div class="form-group">
            <br><br>
            <input name="search_invoice" value="Search Invoice" class="btn btn-primary text_box_height" onClick="search_invoice_data()" style="width:200px; margin-top:7px;" id="add_customer" type="">
            </div>
            </div>
        </div><!--class_middle_wappert-->
        
        <!--start classreturn_invocie_data-->
        <div id="classreturn_invocie_data" class="col-md-12">
        	<!--classreturn_invocie_data-->
        </div> <!--classreturn_invocie_data-->
         
    </div> <!--panel-body-->

    </div> <!--panel panel-default-->
</div>   <!--return_wapper-->                              
                                
                               
<!-- end return box-->
                                    
    <!--<div class="page-header">
      <h1>Add Sales </h1>
    </div>-->
    <p></p>
  </div>
</div>

<!-- end: PAGE HEADER --> 

<!-- start: PAGE CONTENT 

                    <!-- start grid -->

<div class="row">
  <div class="col-md-12"> 
    
    <!-- start: DYNAMIC TABLE PANEL -->
    
    <div class="panel panel-default">
      <!--<div class="panel-heading"> <i class="fa fa-plus"></i> Add Sales </div>-->
      <div class="panel-body">
        <div class="alert alert-danger" style="display:none;">
          <button class="close" data-dismiss="alert"> × </button>
          <i class="fa fa-times-circle"></i> <strong></strong> <span class="errortxt"></span> </div>
        <div class="alert alert-success" style="display:none;">
          <button class="close" data-dismiss="alert"> × </button>
          <i class="fa fa-check-circle"></i> <strong></strong><span class="succetxt"></span> </div>
        <form role="form" class="form-horizontal" id="create_sales_form" action="#" method="post">
          <div class="col-md-12"></div>
          <!--col-md-12-->
          
          <div class="col-md-12  color-green green-wap well well-sm">
            
            
            <div class="col-md-4" style="display:none">
              <div class="form-group">
                <label>$sale_reference_no [for developer only]</label>
                <input id="sale_reference_no2" name="sale_reference_no2" type='text' class="form-control" value="" placeholder="for developer only" />
              </div>
            </div>
            <div class="col-md-4" style="display:none">
              <div class="form-group">
                <label>warehouse_last_id [for developer only]</label>
                <input id="warehouse_last_id" name="warehouse_last_id" type='text' class="form-control" value="" placeholder="for developer only" />
              </div>
            </div>
            
            
           
            
            <div class="col-md-4" style="display:none;">
              <div class="form-group">
                <label>Invoice No</label>
                <input type='text' class="form-control" id="sale_reference_no" name="sale_reference_no" value="" readonly/>
              </div>
            </div>
            <div class="col-md-12">
            
              <div class="panel-default">
                
                <div class="panel-body">
                  <?php $ss_group_id=$this->session->userdata('ss_group_id') ?>
                  <div class="col-sm-2" <?php if ($ss_group_id!=1) echo " style=\"display:none;\""; ?>>
                    <div class="form-group">
                      <label>Warehouse *</label>
                      <select id="warehouse_id" class="form-control text_box_height search-select" name="warehouse_id">
                        
                        <!--<option value="">-- Select Warehouse --</option>-->
                        
                        <?php 

																 $ss_warehouse_id=$this->session->userdata('ss_warehouse_id'); 

                                                              foreach ($warehouse_list as $row)

                                                              {

																  $sel='';

																  if($ss_warehouse_id==$row->id)

																  {

																	  $sel=' selected="selected"';

																  }

                                                              ?>
                        <option value="<?php echo $row->id; ?>" <?php echo $sel ?> > <?php echo $row->name; ?> </option>
                        <?php }?>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-2">
              <div class="form-group">
                <label>Date *</label>
                <?php $nowdate=date("Y-m-d H:i:s");?>
                <input id="sale_datetime" name="sale_datetime" type='text' class="form-control date text_box_height" value="" data-bv-field="date"/>
              </div>
            </div>
            <div class="col-sm-2">
                    <div class="form-group">
                      <label for="customer_id">Sales Rep </label>
                      
                      <!--  search-select-->
                      
                      <?php
                     // print_r($rep_list)
					 $ss_warehouse_id=$this->session->userdata('ss_warehouse_id'); 
                      ?>
                      
                      <select id="rep_id" class="form-control search-select" name="rep_id">
                        <option value="">-- Select Sales Rep --</option> 
                        <?php 

															

															foreach ($rep_list as $row)

															{

															 $sel='';

																  if($ss_warehouse_id==$row->warehouse_id)

																  {

																	//  $sel=' selected="selected"';

																  }
															{

															?>
                        <option value="<?php echo $row->user_id;?>"  <?php echo $sel ?>> <?php //echo $row->id.',' ?><?php echo $row->user_first_name; ?></option>
                        <?php } }  ?>
                      </select>
                    </div>
                  </div>
                  <div class="col-sm-2">
                    <div class="form-group">
                      <label for="customer_id">Customer *  
                     </label>
                     
                      <input type="hidden" id="customer_id" name="customer_id" class="js-data-customer_id-ajax form-control" style="padding:0px 0px; border: none; box-shadow: none" placeholder="-Select-" />
                      
                      <!-- 
                      <select id="customer_id" class="form-control search-select text_box_height" name="customer_id" onChange="cus_city()">
                       
                        
                        <?php foreach ($customer_list as $row){

$set='';	

	if($row['cus_type'] == 'Special'){

		$set = 'color:#06F';

		}

?>
                        <option style=" <?php echo $sel ?>" value="<?php echo $row['cus_id'];?>"><?php echo $row['cus_name']; if($row['cus_phone']) echo " / ".$row['cus_phone'];?> </option>
                        <?php }  ?>
                      </select>
                      
                      -->
                      
                      
                       
                      
                     
                      
                      <!--<a class="" href="#" id="modal_ajax_customers_btn" style="cursor:pointer;"><i style="float: left;position: absolute;margin-left: 3px;margin-top: 5px;" class="fa fa-2x fa-plus-circle addIcon" id="addIcon"></i></a>--> 
                      
                      <!-- <a id="modal_ajax_customers_btn" class=""  id="modal_ajax_sales_payment_btn">
   <i style="float: left;position: absolute;margin-left: 7px;margin-top: 5px;" class="fa fa-2x fa-plus-circle addIcon" id="addIcon"></i>
   </a>   --> 
  <!--  <a class="btn btn-primary " onClick="show_add_customer_button()" id="" name="customer" style="cursor: pointer;    margin-top: 8px; "><i id="addIcon" class="fa fa-1x fa-plus-circle addIcon"></i> Add Customer</a>-->
                      
                    </div>
                    <input type="button" style="display:none" value="REFRESH" onClick="cus_city()">
                  </div>
                  
                    <div class="col-sm-2">
                    <div class="form-group">
                    <!-- <a class="btn btn-primary " onClick="show_add_customer_button()" id="" name="customer" style="cursor: pointer;    margin-top: 8px; "><i id="addIcon" class="fa fa-1x fa-plus-circle addIcon" style="font-size:30px;"></i></a>
                     -->
                     
                     
                     <a onClick="show_add_customer_button()" id="" data-toggle="modal" href="#" style="
margin-top: 7px;">
																<i id="addIcon" class="fa fa-2x fa-plus-circle addIcon" style="font-size:50px; margin-top:31px; color:#000"></i>
															</a>
                     
                   
                    </div>
                    </div>
                  
                 <!-- <div class="col-sm-1">
                    <div class="form-group">
                     <label for="customer_id">&nbsp;
                     </label>
                    <a class="btn btn-primary " onclick="show_add_customer_button()" id="" name="customer" style="cursor: pointer;    margin-top: -3px; "><i id="addIcon" class="fa fa-1x fa-plus-circle addIcon"></i> Add Customer</a>
                    </div>
                    </div> -->
                    
                    
                     <!--customer start-->
            <div class="col-md-12 pull-right">
            
             
              <div class="panel-default" id="customer_des_wap" style="display:none">
                <div class="" style="font-weight: 700;font-weight: 700;margin-left: 17px;margin-top: 17px;">Add Customer
             
                </div>
                <div class="col-md-3">
                
                  <h5>Name *</h5>
                  <input type="text" class="form-control text_box_height" name="cus_name" id="cus_name" <?php echo (isset($customer['cus_name']))?'value="'.$customer['cus_name'].'"':null;?>>
                </div>
                <div class="col-md-3">
                  <h5>Phone *</h5>
                  <input type="text" class="form-control text_box_height" name="cus_phone" id="cus_phone" <?php echo (isset($customer['cus_phone']))?'value="'.$customer['cus_phone'].'"':null;?>>
                </div>
                <div class="col-md-3">
                  <h5>Cus. Type *</h5>
                  <select class="select2-container form-control text_box_height" id="cus_type" name="cus_type">
                            
							<?php 

								$sel='';
								$seldef='';
								if(isset($customer['cus_type'])){
									if($customer['cus_type']=='Special'){
										$sel=' selected="selected"';
									}
									else if($customer['cus_type']=='Normal'){
										$seldef=' selected="selected"';
									}
								}
                            ?>       

                                <option<?php echo $sel;?><?php echo $seldef ?> value="Normal">Normal</option>
                                <option<?php echo $sel;?><?php echo $seldef ?> value="Special">Wholesale</option> 
                             </select>
                </div>
                <div class="col-md-1" style="padding-top:34px">
                  <input type="" name="add_customer" value="<?php echo 'Add'; ?>" class="btn btn-primary" onClick="insertCustomerData()" style="width:60px" id="add_customer">
                </div>
                <div style="clear:both;">&nbsp;</div>
             <!--   <div style="border-bottom:1px solid #ddd; height:3px;"> &nbsp;</div>-->
              </div>
              
              
            </div>
            <!--end customer start-->
                  
                  
                  <div class="col-sm-4" style="display:none">
                    <div class="form-group">
                      <label for="customer_id">Sale Terms * </label>
                      <select id="in_type" class="form-control" name="in_type">
                        <?php 

					$sel_c='';

					$sel_cr='';

					$sel_h='';

					$sel_co='';

					/*

					if(isset($hdr_data->bkng_status) && $hdr_data->bkng_status=='Requested'){

						$sel_p=' selected';

					}

					if(isset($hdr_data->bkng_status) && $hdr_data->bkng_status=='Confirmed'){

						$sel_c=' selected';

					}

					if(isset($hdr_data->bkng_status) && $hdr_data->bkng_status=='Removed'){

						$sel_r=' selected';

					}*/

					

				?>
                        <option value="Cash"<?php echo $sel_c; ?>>Cash</option>
                        <option value="Credit"<?php echo $sel_cr; ?>>Credit</option>
                        <option value="Wholesale"<?php echo $sel_h; ?>>Wholesale</option>
                        <option value="Cost"<?php echo $sel_co; ?>>Cost</option>
                      </select>
                    </div>
                  </div>
                  <div class="col-sm-4" style="display:none">
                    <div class="form-group">
                      <label for="customer_id">Customer PO No. </label>
                      <input value="" id="customer_po_no" class="form-control" name="customer_po_no">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!--col-md-8--> 
          
          <!-- item add box-->
          
          <div id="sticker" class="col-md-9">
          <div class="col-sm-12" style="padding:10px;">
                                                      
															<label>Category</label>
                                                            <?php
															$cat_id=1;
															 //print_r($supplier_list);?>
                                                         <select id="cat_srh" name="cat_srh" style="border-radius: 2px;
    padding: 2px;" class=" search-select">
                                                         
								                               
							<option value="">-Select-</option> 
						<?php foreach ($category_list as $key => $sup) {
								if($sup->cat_name!=''){
																	 ?>
								                             <option value="<?php echo $sup->cat_id; ?>"><?php echo $sup->cat_name; ?></option>
                                                                    <?php
                                                                    }
																	$cat_id=$sup->cat_id;
									                             } ?>  
                                                                
								                             </select>                                                           
														
														</div>
            <div class="well well-sm" id="sale_details_wap">
              <div class="form-group"> 
                
                <!-- auto complete start -->
                
                <div class="input-group wide-tip">
                  <div style="padding-left: 10px; padding-right: 10px;" class="input-group-addon"> <i class="fa fa-2x fa-barcode addIcon"></i> </div>
                  <input type="text" placeholder="Please add products to order list" id="add_item" class="form-control input-lg" value="" name="add_item" onClick="add_items()" style="border-radius: 6px;font-size: 25px;height: 75px;line-height: 1.33;padding: 10px 16px;">
                  
                  <!--<div style="padding-left: 10px; padding-right: 10px;" class="input-group-addon">

															<i id="addIcon" class="fa fa-2x fa-plus-circle addIcon"></i>



														</div>--> 
                  
                </div>
                
                <!-- end auto complete end --> 
                
              </div>
              <div class="clearfix"></div>
              <div class="control-group table-group">
                <label class="table-label">Order Items</label>
                <div class="controls table-controls">
                  <table class="table items table-striped table-bordered table-condensed table-hover" id="soTable">
                    <thead>
                      <tr>
                        <th class="col-md-6">Product Name (Product Code)</th>
                        <th class="col-md-3">Selling Price</th>
                        <th style="width:50px">War.(Months)</th>
                        
                        <th class="col-md-2">Quantity</th>
                        <th class="col-md-1 text-right">Discount </th>
                        <th class="text-right">Subtotal<span class="currency"></span> </th>
                        <th style="width: 30px !important; text-align: center;"><i class="fa fa-trash-o"></i></th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr data-item-id="144680019784" class="row_144680019784" id="row_1446800197032">
                        <td></td>
                        <td class="text-right"></td>
                        <td class="text-right"></td>
                        <td></td>
                        <td class="text-right"></td>
                        <td class="text-right"></td>
                        <td class="text-center"></td>
                      </tr>
                    </tbody>
                    <tfoot>
                      
                      <!--<tr class="tfoot active" id="tfoot">

																	<th colspan="2">Total</th>

																	<th class="text-center"><span id="qtyTotal">0.00</span></th>

																	<th class="text-right"><span id=""> 0.00</span></th>

																	<th class="text-right">0.00</th>

																	<th class="text-right"><span id="Subtotal">00.00</span></th>

																	<th class="text-center"><i class="fa fa-trash-o"></i></th>

																</tr>-->
                      
                      <tr class="tfoot active" id="tfoot">
                        <th colspan="5" class="text-right">Total Amount</th>
                        <th class="text-right"><span id="Subtotal">0.00</span></th>
                      </tr>
                     <?php
					 if(isset($sale_rtn_details['sl_rtn_reference_no']))
					 {
					 ?> 
                       <tr class="tfoot active" id="tfoot">
                        <th colspan="5" class="text-right">Returned Amount ( Ref. No. <?php echo $sale_rtn_details['sl_rtn_reference_no'];?>)</th>
                        <th class="text-right"><span id=""><?php echo $sale_rtn_details['sls_rtn_total_paid'];?></span></th>
                      </tr>
                      <?php }?>
                      <!-- <tr class="tfoot active" id="tfoot">

																	<th colspan="4" class="text-right">Paid </th>

																	<th class="text-right">

                                                                    <input type="text" onChange="changePaidValue(this.value);" onClick="this.select(); setTmpVal(this.value);" id="paid" value="0.00" name="paid" class="form-control text-right rquantity">

                                                                    </th>

																	

																</tr>

                                                                <tr class="tfoot active" id="tfoot">

																	<th colspan="4" class="text-right">Balance </th>

																	<th class="text-right"><span id="balance_dis">0.00</span></th>

																	

																</tr>-->
                      
                    </tfoot>
                  </table>
                  
                  <!-- start list --> 
                  
                  <!-- end list --> 
                  
                </div>
              </div>
              
              
            </div>
            
             
            
            <!-- end item add box-->
            
            <div id="extras-con" class="row"> 
              
              <!--<div class="col-md-4">

																<div class="form-group">

																	<label for="potax2">Order Tax</label>

																	<select id="tax_rate_id" class="form-control" name="tax_rate_id">

                                                                   

																  <?php 

                                                              foreach ($tax_rates_list as $row)

                                                              {

																  

                                                              ?>  

                                                                        

																		<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?>

                                                                        </option>

                                                              <?php }?>

																		

																	</select>

																</div>

															</div>-->
              
             
              <div class="col-md-3" style="display:none">
                <div class="form-group">
                  <label>Rep Commission</label>
                  <input type="text" title="" data-original-title="" value="0" class="form-control input-tip text-right" id="sale_inv_rc" name="sale_inv_rc" onChange="changeRC(this.value)">
                </div>
              </div>
              
             
              
              
              <!--<div class="col-md-4">

											<div class="form-group">

												<label>Shipping</label>

					                             <input type="text" title="" data-original-title="" name="sale_shipping" value="" class="form-control input-tip" id="sale_shipping">

											</div>

										</div>--> 
              
              <!-- <div class="col-md-4">

															<div class="form-group">

													<label for="poshipping">Payment Status *</label>

													 <select id="payment_status" class="form-control selectpicker" name="payment_status">

                                                      <option value="Paid">Paid</option>

                                                     <option value="Pending">Pending</option>

                                                     <option value="Due">Due</option>

                                                     <option value="Partial">Partial</option>

                                                    

					                             </select>

															</div>

														</div>--> 
              
              <!--<div class="col-md-4">

											<div class="form-group">

												<label>Sale Status *</label>

					                            <select id="sale_status" name="sale_status" class="form-control selectpicker">

                                                    <option value="Completed">Completed</option>

                                                     <option value="Pending">Pending</option>

					                             </select>

											</div>

										</div>--> 
              
              <!--<div class="col-md-4">

																<div class="form-group">

																	<label for="podiscount">Payment Term</label>

																	<input type="text" id="sale_payment_term" class="form-control input-tip" value="" name="sale_payment_term" data-original-title="" title="">

																</div>

															</div>

														--> 
              
            </div>
          </div>
          
          <div class="col-md-3" id="sale_sub_btn">
          <div style="margin-left:95px">
<div class="form-group">
<label for="sale_pymnt_given_amount">Cash</label> <input required type="text" class="pa form-control kb-pad amount text_box_height" id="sale_pymnt_given_amount" name="sale_pymnt_given_amount" value="0" style="text-align:right" onClick="this.select()" onKeyUp="calculateBalance(this.value)">
</div>
</div>
          
          <div class="form-group pull-right" style="width:200px; display:none">
                  <label>Order Discount</label>
                  <input type="text" title="" data-original-title="" value="" class="form-control input-tip text-right" id="sale_inv_discount" name="sale_inv_discount" onChange="changeMainDiscount(this.value)">
                </div>
                
                <div class="col-md-3" style="display:none">
                <input type="checkbox" name="is_phone_bill" value="1" id="is_phone_bill" style="height:50px; width:50px; float:left; margin-left:30px;" title="Phone Bill">
                Phone Bill Print
                </div>
                
               <input type="submit" class="btn btn-primary " value="Add Sales" name="add_sale" id="add_sale" style="margin-bottom:10px; float:right">
               
                <a href="#stack1" id="add_payment" data-toggle="modal" class="demo btn btn-success" style="float:right; margin-bottom:10px;">
													Payment
												</a>
                                                
              <button id="reset" class="btn btn-danger" type="button" style="float:right; margin-bottom:10px">Reset</button>
              </div>
              
          <!-- end: col-md-12--> 
          
          <!--<div class="col-md-6">

                            <div class="form-group">

										<label for="form-field-23">

											Safe Note

										</label>

										<textarea class="form-control limited" id="form-field-23" maxlength="50"></textarea>

									</div>

                            </div>--><!-- col-md-6--> 
          
          <!-- <div class="col-md-6">

                            <div class="form-group">

										<label for="form-field-23">

											Staff Note

										</label>

										<textarea class="form-control limited" id="form-field-23" maxlength="50"></textarea>

									</div>

                            </div>--><!-- col-md-6-->
          
          <div class="col-md-12">
             
            
          </div>
          <input name="sale_inv_discount_amount" type="hidden" id="sale_inv_discount_amount" value="0">
          <input name="sale_total" type="hidden" id="sale_total" value="0">
          <input name="sale_paid" type="hidden" id="sale_paid" value="0">
          <input name="sale_balance" type="hidden" id="sale_balance" value="0">
          <input name="rowCount" type="hidden" id="rowCount" value="0">
          <input name="cost_total" type="hidden" id="cost_total" value="0"  readonly>
          <input name="cus_type" type="hidden" id="cus_type" value="">
          <input name="city_id" type="hidden" id="city_id" value="">
          <input name="last_ley" type="hidden" id="last_ley" value="">
           <input name="sl_rtn_id" type="hidden" id="sl_rtn_id" value="<?php echo $sl_rtn_id;?>">
            <input name="sl_rtn_amount" type="hidden" id="sl_rtn_amount" value="<?php echo floatval($sale_rtn_details['sls_rtn_total_paid']);?>">
            
            <input name="last_element_id" type="hidden" id="last_element_id" value="">
            
          
          
          
          
          <!-- payment details start -->
<div id="stack1" class="modal fade" tabindex="-1" data-focus-on="input:first" style="display: none;">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title">Payment Details</h4>
			</div>
			<div class="modal-body">
				<!--Start payment options-->
                <div class="col-md-12">
                <div class="well well-sm" style="padding:0 5px;">
<div class="row">

<!-- start -->
                <div class="col-sm-6">
<div class="form-group">
<label for="amount_1">Amount *</label> <input required type="text" class="pa form-control kb-pad amount text_box_height" id="sale_pymnt_amount" name="sale_pymnt_amount" value="0" style="text-align:right" onClick="this.select()">
</div>
</div>

<div class="col-sm-6">
<div class="form-group">
<label for="amount_1">Paying by</label>
<select class="form-control paid_by text_box_height" id="sale_pymnt_paying_by" name="sale_pymnt_paying_by" data-bv-field="paid_by" tabindex="-1" title="Paying by *" onChange="changePayingby(this.value)">
<option value="Cash">Cash</option>
<option value="Credit Card">Credit Card</option>
<option value="Cheque">Cheque</option>
</select>


</div>
</div>


                <div class="col-sm-6">
<div class="form-group">
<label for="amount_1">Amount *</label> <input required type="text" class="pa form-control kb-pad amount text_box_height" id="sale_pymnt_amount_2" name="sale_pymnt_amount_2" value="0" style="text-align:right" onClick="this.select()">
</div>
</div>

<div class="col-sm-6">
<div class="form-group">
<label for="amount_1">Paying by</label>
<select class="form-control paid_by text_box_height" id="sale_pymnt_paying_by_2" name="sale_pymnt_paying_by_2" data-bv-field="paid_by" tabindex="-1" title="Paying by *" onChange="changePayingby(this.value)">
<option value="Cash">Cash</option>
<option value="Credit Card" selected>Credit Card</option>
<option value="Cheque">Cheque</option>
</select>


</div>
</div>

 

<!--<div class="col-sm-6">
<div class="form-group">
<label for="sale_pymnt_given_amount">Cash Change </label> <input readonly required type="text" class="pa form-control kb-pad amount text_box_height" id="sale_pymnt_balance_amount" name="sale_pymnt_balance_amount" value="0" style="text-align:right" onClick="this.select()">
</div>
</div>-->
<!-- end -->

</div>
</div>
                </div>
				<!--End payment options-->
				
			</div>
            <div style="clear:both;"></div>
			<div class="modal-footer">
				<button type="button" data-dismiss="modal" class="btn btn-primary pos_button">
					Submit
				</button>
				<!--<button type="button" class="btn btn-primary">
					Ok
				</button>-->
			</div>
		</div>
        <!-- end payment details start -->
                
        </form>
        
        <!-- <div onClick="get_cus_tot_credit(1)">check cus tot credit</div>--> 
        
        <!-- end: DYNAMIC TABLE PANEL --> 
        
        <!-- footer amount details -->
        
        <div style="margin-bottom: 0px; position: fixed; bottom: 0px; width: 1082px; z-index: 1;" class="well well-sm" id="bottom-total">
         <table style="margin-bottom:0;" class="table table-bordered table-condensed totals table_tot_amount">
            <tbody>
              <tr class="warning"> 
                
                <!--<td width="20%" style="background-color:#d9534f">Total Credit <span id="totals_cus_credit" class="totals_cus_credit pull-right">0.00</span></td>-->
                
                <td width="15%" style="padding-top:21px !important;">Total <span id="f_total" class="totals_val pull-right">0.00</span></td>
                <td width="20%" style="padding-top:21px !important;"> Discount <span id="tds" class="totals_val pull-right">0.00</span></td>
                
                <td width="20%" style="padding-top:21px !important;">Cash Change <span id="sale_pymnt_balance_amount" class="totals_val pull-right">0.00</span></td>
                <td style="color: #fff;font-size: 32px !important;font-weight: bold !important;">Grand Total <span id="gtotal" class="totals_val pull-right">0.00</span></td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- end footer amount details --> 
        
      </div>
    </div>
    
    <!-- end grid --> 
    
  </div>
  
  <!-- end: PAGE --> 
  
</div>

<!-- end: MAIN CONTAINER --> 

<!-- start: FOOTER -->

<div class="footer clearfix">
  <div class="footer-inner">
    <?php date("Y");?>
    Developed by: Sallelanka Solutions (pvt) Ltd. </div>
  <div class="footer-items"> <span class="go-top"><i class="clip-chevron-up"></i></span> </div>
</div>

<!-- end: FOOTER --> 

<!-- start: RIGHT SIDEBAR --> 

<!-- end: RIGHT SIDEBAR -->

<div id="event-management" class="modal fade" tabindex="-1" data-width="760" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button>
        <h4 class="modal-title">Event Management</h4>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" data-dismiss="modal" class="btn btn-light-grey"> Close </button>
        <button type="button" class="btn btn-danger remove-event no-display"> <i class='fa fa-trash-o'></i> Delete Event </button>
        <button type='submit' class='btn btn-success save-event'> <i class='fa fa-check'></i> Save </button>
      </div>
    </div>
  </div>
</div>
<input name="tmpVal" type="hidden" id="tmpVal" value="0">
<input name="" id="type_sale" type="hidden" value="22">

<!-- start ajax model -->

<div id="ajax-modal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" style="display: none;"></div>

<!-- end ajax model --> 

<a id="modal_ajax_serial_no" data-toggle="modal" href="#"></a> <a id="modal_ajax_serial_no_view" data-toggle="modal" href="#"></a>
<input name="" type="hidden" id="curr_row_no" value="0">

<!-- start: MAIN JAVASCRIPTS -->

<?php $this->load->view("common/footer"); ?>
<script src="<?php echo asset_url(); ?>js/jquery-ui.js" ></script> 
<script src="<?php echo asset_url(); ?>js/moment-with-locales.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/bootstrap-datetimepicker.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/bootbox.min.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/accounting.js"></script> 
<script type="text/javascript" src="<?php echo asset_url(); ?>js/accounting.min.js"></script> 

<!-- end: MAIN JAVASCRIPTS --> 

<!-- start: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY VALIDATION--> 

<script src="<?php echo asset_url(); ?>js/form-validation-create_sales.js"></script> 
<script src="<?php echo asset_url(); ?>js/sales.js"></script> 

<!-- end: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY  VALIDATION--> 

<script>
function search_invoice_data(){
	//$("#classreturn_invocie_data").hide();
	
	var sale_id=$("#sale_id_search").val();
	get_invoice_details(sale_id);
}

<!-- show return details -->
function get_invoice_details(sale_id) {
	 $('#ajax-loading-top-corner').hide();
	
	$( "#classreturn_invocie_data" ).load( "<?php echo base_url();?>sales_pos/get_return_details?sale_id="+sale_id, function() {
 // alert( "Load was performed." );

 
});



	
}	
<!-- end return details -->

function show_return_wapper() {
	
  var x = document.getElementById("return_wapper");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

function show_return_wapper(){
	
	$("#return_wapper").show();
	hide_sale_box();
	
	
}
function hide_return_wapper(){
	$("#return_wapper").hide();
	show_sale_box();
}

function hide_sale_box(){
	$("#bottom-total").hide();
	$("#sale_list_table").hide();
	$("#sale_details_wap").hide();
	$("#sale_sub_btn").hide();
	$(".green-wap").hide();
}

//
function show_sale_box(){
	$("#bottom-total").show();
	$("#sale_list_table").show();
	$("#sale_details_wap").show();
	$("#sale_sub_btn").show();
	$(".green-wap").show();
}

//

//sales payment model load event
var $modal = $('#ajax-modal-2');
$('a#modal_ajax_sales_return_btn').on('click', function () {
	// create the backdrop and wait for next modal to be triggered
	//var sale_type = 'none';
	var sale_id=$('#sale_id').val();
	var sale_type = $('#sale_type').val();
	$('body').modalmanager('loading');
	setTimeout(function () {
		$modal.load('<?php echo base_url("sales_return/sales_return_pos"); ?>', '', function () {
			$modal.modal();
			$('#sale_pymnt_amount').focus(); 
			
			$('#sale_pymnt_date_time').datetimepicker({
			defaultDate: new Date()
			});
		});
	}, 1000);
});


$('a#modal_ajax_help_btn').on('click', function () {
	// create the backdrop and wait for next modal to be triggered
	//var sale_type = 'none';
	var sale_id=$('#sale_id').val();
	var sale_type = $('#sale_type').val();
	$('body').modalmanager('loading');
	setTimeout(function () {
		$modal.load('<?php echo base_url("sales_return/help"); ?>', '', function () {
			$modal.modal();
			$('#sale_pymnt_amount').focus(); 
			
			$('#sale_pymnt_date_time').datetimepicker({
			defaultDate: new Date()
			});
		});
	}, 1000);
});




$(function () {
	//showKeys();
	
	$('#add_item').focus().click();//.keypress().trigger();
	//$('#add_item').click();
	
	$('.js-data-customer_id-ajax').select2('data', {id: 1, text: 'W. CUSTOMER'});
});	



function show_add_customer_button(){
	//$("#customer_des_wap").show();
	  var x = document.getElementById("customer_des_wap");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
$('#sale_inv_discount').on({
    keypress: function() { typed_into = true; },
    change: function() {
        if (typed_into) {
           // alert('type');
            typed_into = false; //reset type listener
        } else {
           // alert('not type');
        }
    }
});



$( "#item_ac_price_p_1" ).change(function() {
  alert( "Handler for .change() called." );
});

$('#item_ac_price_p_1_1').change({
    keypress: function() { typed_into = true; },
    change: function() {
        if (typed_into) {
            alert('type');
            typed_into = false; //reset type listener
        } else {
            alert('not type');
        }
    }
});

$('#add_customer').keypress(function(e){
	insertCustomerData();
    if ( e.which == 13 ) return false;

    //or...

    if ( e.which == 13 ) e.preventDefault();

 }); 

function insertCustomerData(){
var type='A';
var cus_id=$('#cus_id').val();
var country_id=$('#country_id').val();
var city_name=$('#city_name').val();	
var city_name=$('#city_id option:selected').text();
var cus_name=$('#cus_name').val();
var cus_code=$('#cus_code').val();
var cus_email=$('#cus_email').val();
var cus_phone=$('#cus_phone').val();	
var cus_address=$('#cus_address').val();
var cus_state=$('#cus_state').val();
var cus_postal_code=$('#cus_postal_code').val();
var city_id = $('#city_id').val();
var cus_type = $('#cus_type').val();
var cus_credit_limit = $('#cus_credit_limit').val();

if(cus_name=='' || cus_phone==''){
	displayNotice('Error!','Please enter customer name and phone. ');
	return false;
}
else{
	//alert(2);	
}
				 
	$.post( "<?php echo base_url('customers/save_customer'); ?>", {type:type, cus_id:cus_id, city_id:city_id, country_id:country_id, city_name:city_name, cus_name:cus_name, cus_code:cus_code, cus_email:cus_email, cus_phone:cus_phone, cus_address:cus_address, cus_state:cus_state, cus_postal_code:cus_postal_code, cus_type:cus_type,cus_credit_limit:cus_credit_limit })
	  .done(function( data ) {
		
	  var obj = jQuery.parseJSON(data);
	//  alert(11);
	 if (obj.status==0) 
	{
		$('div#error').html('<div class="alert alert-block alert-danger fade in"><button type="button" class="close" data-dismiss="alert">×</button><h4 class="alert-heading"><i class="fa fa-times-circle"></i> Error!</h4>'+obj.validation+'</div>');
		$('body').modalmanager('removeLoading');
		$('body').attr('class','');
	} else {
	  // alert(obj.type); //last id
	  
	 // 
	 // loadGrid();// load customer data
		
	  if(obj.type=='E'){
		 displayNotice('page','Customer has been updated successfully!');
	  }
	  if(obj.type=='A'){
		displayNotice('page','Customer has been added successfully!')  ;
	  }	
	  
	  
	  
	  show_add_customer_button();
	  
	  
	  	if(obj.type=='A'){
	 $('.js-data-customer_id-ajax').select2('data', {id: obj.cus_id, text: obj.cus_name});	
	}
	
	
	 // alert();
	 // var app = $("<option/>",{value:obj.cus_id , text: obj.cus_name});
         //   $('#customer_id').append(app);
		//	$('#customer_id').select2("val", obj.cus_id).trigger('change');
	  $('div#ajax-modal').modal('hide');
	 // location.reload();	
	}
	  

	  });
return false;
}


$("form").submit(function (e) {



      return false;

}); 





function pop_up_add_serial_no(row_no){

	$("#curr_row_no").val(row_no);

	//alert(1);

	document.getElementById("modal_ajax_serial_no").click();

	

}



function pop_up_view_serial_no(row_no){

	$("#curr_row_no").val(row_no);

	//alert(1);

	document.getElementById("modal_ajax_serial_no_view").click();

	

}


//var $modal = $('#stack2');
$('a#modal_ajax_serial_no').on('click', function () {

	var curr_row_no=$("#curr_row_no").val();
	var warehouse_id=$("#warehouse_id").val();

	$("#curr_row_no").val('');

	var qtyfld='#quantity_'+curr_row_no;

	var productfld='#product_id_'+curr_row_no;

	//alert(qtyfld);

	var qty=parseFloat($(qtyfld).val());

	var product_id=$(productfld).val();
	
	var gross_totalfld='#gross_total_'+curr_row_no;
	var gross_total=parseFloat($(gross_totalfld).val());
	var each_price=gross_total/qty;
	//alert(each_price);

	//alert(curr_row_no);

	// create the backdrop and wait for next modal to be triggered

	$('body').modalmanager('loading');

	setTimeout(function () {

		var url="<?php echo base_url("sales/add_serial_no/");?>/"+curr_row_no+'/'+qty+'/'+product_id+'/'+warehouse_id+'/'+each_price+'/sale';

		$modal.load(url, '', function () {

			$modal.modal();

		});

	}, 1000);

});



$('a#modal_ajax_serial_no_view').on('click', function () {

	var curr_row_no=$("#curr_row_no").val();

	var qtyfld='#quantity_'+curr_row_no;

	//alert(qtyfld);

	var qty=$(qtyfld).val();

	//alert(curr_row_no);

	// create the backdrop and wait for next modal to be triggered

	$('body').modalmanager('loading');

	setTimeout(function () {

		var url="<?php echo base_url("sales/add_serial_no_view/");?>/"+curr_row_no+'/'+qty;

		$modal.load(url, '', function () {

			$modal.modal();

		});

	}, 1000);

});

			



function addextraprice(){

	calculateTotal();

}



clearForm();





$(document).ready(function() {
	$( ".navigation-toggler" ).click();
	$("#cat_srh").select2();

	//cus_city();

$(window).keydown(function(event){


    if(event.keyCode == 112) {
		$('#add_item').focus();
      //return false;
    }
    
    if(event.keyCode == 113) {
		var rowCount=parseInt($('#rowCount').val());
				var item_ac_price_p="#item_ac_price_p_"+rowCount;
				$(item_ac_price_p).focus();
				$(item_ac_price_p).select();
    }

  });

});



$('#add_item').keypress(function(e){

    if ( e.which == 13 ) return false;

    //or...

    if ( e.which == 13 ) e.preventDefault();

 }); 



function validate_cost_grater_than_salinng_price(item_cost,prouct_price){
	//alert(item_cost+','+each_price);
	if (item_cost>prouct_price) 
	{
		//bootbox.alert("Product cost greater than selling price. Can not add to the invoicce. Please contact site administrator");	
		//return '';
		return 1;
	}else{
		return 1;
	}
}

function changeQtyByProductID(qty,nxtCount){

	//alert(qty+' '+nxtCount);
	
	//check cost grater than selling price
	var gross_totalfld='#gross_total_'+nxtCount;
	var gross_total=parseFloat($(gross_totalfld).val());
	var each_price=gross_total/qty;
	
	var item_cost_fld='#item_cost_'+nxtCount;
	var item_cost=parseFloat($(item_cost_fld).val());
	var quantity_fld='#quantity_'+nxtCount;
	var oldVal=$('#tmpVal').val();
	
	console.log(qty);
	console.log(isNaN(qty));
	/*if
	(isNaN(qty) || isNaN(qty)==0)
	*/
	if(isNaN(qty) || qty==0) {

		displayNotice('page','Invalid Quantity');
		
		var product_id_fld='#product_id'+nxtCount;
		

		$(quantity_fld).val(oldVal); //set last val

	}else if(!validate_cost_grater_than_salinng_price(item_cost,each_price)){
		var quantity_fld='#quantity_'+nxtCount;
		var product_id_fld='#product_id'+nxtCount;
		var oldVal=$('#tmpVal').val();
		$(quantity_fld).val(oldVal);
	}
		else {

		//getavalable product count

		var product_id_fld='#product_id'+nxtCount;

		var product_id=$(product_id_fld).val();
		var new_qty_val=$(quantity_fld).val();
		
		var rowCount=$('#rowCount').val();
		var item_qty_added=0;
 		for(k=1; k<=rowCount; k++){
			var quantity_each_fld="#quantity_"+k;
			var quantity_each_val=parseInt($(quantity_each_fld).val());
			if(quantity_each_val){
				item_qty_added=item_qty_added+quantity_each_val;
			}
		}
		

		var warehouse_id=$('#warehouse_id').val();

		$.get( "<?php echo base_url();?>sales/get_avalable_product_qty", { product_id: product_id, warehouse_id: warehouse_id,new_qty_val:new_qty_val } )

			.done(function( data ) {

				var obj = jQuery.parseJSON(data);
				
				//alert(obj.new_qty_val + ' , '+obj.remmnaingQty);
				//alert(oldVal);
				
				//allredy added qty this invoice
				
				
				if((parseInt(obj.new_qty_val)+item_qty_added)<=parseInt(obj.remmnaingQty)){
					//alert(1);
				}else{
					//alert(2);
					//displayNotice('Error',"Product "+ new_qty_val+" not avalable in stock");
					
					bootbox.alert("Product "+ new_qty_val+" not avalable in stock");	
					$(quantity_fld).val(oldVal);
					calculateTotal();
					//return false;	
				}
				
				//alert(obj.remmnaingQty);

				//alert(obj.remmnaingQty);

	   });
		//end getavalable product count
		
		
		
		calculateTotal();

		//displayNotice('page','Product quantity successfully updated!');

	}

}





function get_cus_tot_credit(cus_id){

	if(cus_id!=1){

	$.post( "<?php echo base_url();?>sales/get_cus_tot_credit/"+cus_id)

	  .done(function( data ) {

		  var obj = jQuery.parseJSON(data);

		  $('#totals_cus_credit').html(obj.totals_cus_credit);

	  });

	}

}

function getNextRefNo(){

	//return 'SALE/2015/11/0001';

	//alert();

	

	$.post( "<?php echo base_url();?>sales/get_next_ref_no")

	  .done(function( data ) {

		  var obj = jQuery.parseJSON(data);

		  $('#sale_reference_no').val(obj.sale_reference_no);

	  });

	//return false;

}


$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#id_of_button").click();
    }
});

	$(document).on('keypress',function(e) {
	//	alert(e.which);
    if(e.which == 13) {
        //alert('You pressed enter!');
		 $("#last_ley").val(13);
    }
	else{
		$("#last_ley").val('');
	}
});


$(document).keydown(function (e) {
    if (e.keyCode == 16) {
       // alert(e.which + " or Shift was pressed");
	  
		//$("#create_sales_form").submit();
    }
});


function insertSalesData(){
	



	var type='A';

	var sale_reference_no=$('#sale_reference_no').val();
var rep_id=$('#rep_id').val();
	 var fields = $("#create_sales_form").serialize();

	  

	  var rowCount=$('#rowCount').val();
	  
	  var last_ley=$('#last_ley').val();
	  
	  // alert('last_ley:'+last_ley);

	//  last_ley=0;
if(last_ley!=13){
	  //check searial no added

	  var validationFailed=false;

    var invalid_sn='';
   
   for(k=1; k<=rowCount; k++){
		//alert(k);
		//var invalid_sn='';
		var fld_sn="#product_sn_"+k  
		var fld_product_sn_exissts='#product_sn_exissts_'+k;
		
		var fld_qty="#quantity_"+k   
		const sn_val=$(fld_sn).val();
		var qty_val=$(fld_qty).val();
		//alert(sn_val);
		if($(fld_product_sn_exissts).val()==1){
		if(sn_val){
			const splitString = sn_val.split(",");
			var sn_length=splitString.length;
		
			if($(fld_sn).val()==''){
				validationFailed = true;
			}else if(qty_val!=sn_length){
				//invalid_sn="Serial no qty does't match with product qty ."+qty_val;
				if(invalid_sn) invalid_sn=invalid_sn+' ,';
				invalid_sn=invalid_sn+qty_val;
			}
		}else if(qty_val){
			if(!sn_val) {
				validationFailed = true;
			}
		}
		}

		//console.log(splitString);   
   }
/**/

//Cost grater than salling price validation
	var costValidationFailed=false;
	var costValidationMsg='';
	
   for(k=1; k<=rowCount; k++){
	   var nxtCount=rowCount;
	var gross_totalfld='#gross_total_'+nxtCount;
	var gross_total=parseFloat($(gross_totalfld).val());
	
	var quantity_fld='#quantity_'+nxtCount;
	var qty=$(quantity_fld).val(); //set last val
	var rep_id=$("#rep_id").val();
		
	var each_price=gross_total/qty;
	
	var item_cost_fld='#item_cost_'+nxtCount;
	var item_cost=parseFloat($(item_cost_fld).val());
	//alert(item_cost+' , '+each_price);
	
	if (item_cost>each_price) 
	{
		//costValidationFailed=true;
		costValidationMsg=costValidationMsg+' Row no:'+rowCount;
	}
	
	    
		//
   }

//alert(rep_id);
/*if(rep_id==''){
	  alert('Please select Sales Rep');
}
else*/

var rep_id=$("#rep_id").val();
//alert(rep_id);
if(rep_id==''){
    	alert("Select sales rep");
}else if(invalid_sn){
	alert("Serial no qty does't match with product qty : "+invalid_sn);
}
/*
else if (costValidationFailed) {
	  alert(costValidationMsg+ ' Product cost greater than selling price. Can not complete  invoicce. Please contact site administrator');
}*/
else if (validationFailed) {

	   alert('Please add serial No.');

	 

     // e.preventDefault();

     // return false;

   }
   /*
   else if($("#cost_total").val()=='' || $("#cost_total").val()=='0'){
	    alert('System fail. Please contact administrator');
   }*/

 else if(rowCount!=0){

		  $("#add_sale").prop("disabled", true);

		  $("#add_sale").val('Please wait...');



		 // create_sales_form.add_sale.disabled = true;

   		// create_sales_form.add_sale.value = "Please wait...";

    	//	return true;

	

	//alert(fields);s

	//type:type, sale_reference_no:sale_reference_no

	$.post( "<?php echo base_url();?>sales/save_sales", fields)

	  .done(function( data ) {

		  var obj = jQuery.parseJSON(data);

			if(obj.error==1){

				

				$('.alert-success').hide();

				$('.alert-danger').show();

				$( ".errortxt" ).text( obj.disMsg );

				window.scrollTo(500, 0);

				//empty item table

				

			}

			if(obj.error==0){

				//$('.alert-danger').hide();

				//$('.alert-success').show();

				//$( ".succetxt" ).text( obj.disMsg );

				window.scrollTo(500, 0);

				//$("#soTable tr:gt(0)").remove();

				$("#soTable > tbody").empty();

				displayNotice('page','Sale successfully added!');

				

				clearForm();

				//empty footer details

				

				//alert(obj.sale_id);

				//sendUrl='sales/view/'+obj.sale_id;
				
				sendUrl='sales/add';

				//alert(sendUrl);
				
				
				
			//	if($("#is_phone_bill").prop("checked") == false)
				{
				   // alert(1);
				
				fbs_click_wholesale_print(obj.sale_id);
				}

				window.location.href = "<?php echo base_url();?>"+sendUrl;

				

			}

			

			

	  });

return false;



	  }else  {

		 bootbox.alert('Please add products.', function () {

                        $('#add_item').focus();

                    });

	  }

}// end last_ley if 
else{
	 displayNotice('Error!','Invalid value entered. Please confirm details');
	 //var last_element_id=$("#last_element_id").val();
	// var last_element_id_fld="#".$(':focus').attr('id');
	 
	// alert(last_element_id_fld);
	// alert($(':focus').attr('id'));
	 
	 var last_element_id_fld="#"+$(':focus').attr('id');
	 
	// alert(last_element_id_fld);
	// $(last_element_id_fld).val(0);
	// alert($(':hover').last().attr('name'));
	
	/*$(document).on('mouseover', 'input', function(e) {
   		alert(($(e.target).attr('id')));
	});*/

	

	 
	//alert('Please click "Add Save Button" to complete sale');
}// end last_ley if 

}


function fbs_click_wholesale_print(id) {
	u=location.href;
	t=document.title;
	window.open('<?php echo base_url() ?>sales/sale_details_ser?sale_id='+id,'sharer','toolbar=0,status=0,width=700,height=700, left=10, top=10,scrollbars=yes');return false;
}


function fbs_click(id) {
	//alert();
	sendUrl = 'sales/add';
                //alert(sendUrl);
   
	
	u=location.href;
	t=document.title;
	window.open('<?php echo base_url() ?>sales/sale_details?sale_id='+id,'sharer','directories=no,titlebar=no,location=no,menubar=no, toolbar=0,status=0,width=300,height=400, left=0, top=10,scrollbars=yes');
	
	 window.location.href = "<?php echo base_url(); ?>" + sendUrl;
	return false;
}


function add_items(){

        //ItemnTotals();
		//alert(1);

        $("#add_item").autocomplete(

		{

            source: '<?php echo base_url();?>sales/suggestions?t='+$("#in_type").val()+'&cus_type='+ $('#cus_type').val()+'&city_id='+ $('#city_id').val()+'&srh_warehouse_id='+ $('#warehouse_id').val()+'&cat_id='+ $('#cat_srh').val(),

            minLength: 1,

            autoFocus: false,

            delay: 5,

            response: function (event, ui) {

			

				if (ui.content.length == 1 && ui.content[0].product_id != 0)

				{

					ui.item = ui.content[0];

 					$(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);

					$(this).autocomplete('close');

                    $(this).removeClass('ui-autocomplete-loading');

				}else if(ui.content.length ==0){

					var noResult = { value:"",label:"No matching result found! Product might be out of stock in the selected warehouse." };

            		ui.content.push(noResult);

				}else {



				}

			

            },

            select: function (event, data) {

				//alert( "You selected: " + data.item.product_id );

				if(data.item.value){
				    
				$('#in_type option:not(:selected)').prop('disabled', true);
			//	$('#customer_id option:not(:selected)').prop('disabled', true);
				//$('#sales_rep_id option:not(:selected)').prop('disabled', true);
				$('#warehouse_id option:not(:selected)').prop('disabled', true);

					

					//check is added prodcut

					rowCount=parseInt($('#rowCount').val());

					var tmp='';

					if(rowCount){

						//increase only have serial
						//if(data.item.product_sn_exissts){
	  					tmp=isAddedProduct(data.item.product_id,data.item.product_sn_exissts);
						//}

						

						

					}

	   				if(!tmp)

					{
						/*
						alert('item_cost:'+data.item.item_cost);
						alert('product_price:'+data.item.product_price);
						if(data.item.item_cost>data.item.product_price){
							alert('Product cost greater than selling price');	
							
						}
						*/
						
						//alert(1);

				addProductToListByID(data.item.product_id,data.item.product_name,data.item.product_code,data.item.product_price,data.item.product_part_no,data.item.product_oem_part_number,data.item.item_cost,data.item.product_sn,data.item.product_w,data.item.product_sn_exissts);

				var rowCount=parseInt($('#rowCount').val());
				/*
                
				var quantity="#quantity_"+rowCount;
				$(quantity).focus();
				$(quantity).select();
				
				*/
				
				
				var item_ac_price_p="#item_ac_price_p_"+rowCount;
				$(item_ac_price_p).focus();
				$(item_ac_price_p).select();
				

						//alert(data.item.product_sn);

						//add next serial no.
						var rowCount=parseInt($('#rowCount').val());
						var product_sn_fld='#product_sn_'+rowCount;
						var product_sn_val=($(product_sn_fld).val());
						if(data.item.is_search_by_sn){
							
							
							
							//set sn cost start
								var prouct_price=data.item.product_price;
								
								//alert(data.item.pis_cost_price +' , '+ prouct_price);
								
								//alert(prouct_price);
								if(data.item.pis_cost_price){
								    
								    var cost_validate='';
								   if(3!="<?php echo $this->session->userdata('ss_warehouse_id');?>") {
								if (data.item.pis_cost_price>prouct_price) 
								{
								     cost_validate=1;
								}
								   }
								
								cost_validate='';	
								if (cost_validate==1) 
								{
									//alert(1);
									//displayNotice('Error','Product cost greater than selling price');
									bootbox.alert(data.item.product_sn+" Emi no product cost greater than selling price. Can not add to the invoicce. Please contact site administrator");
									
									return false;	
										
								}else{
									
									if(product_sn_val) {
										$(product_sn_fld).val(product_sn_val+','+data.item.product_sn);
									}else{
										$(product_sn_fld).val(data.item.product_sn);
									}
								}
								
								
									//set serial no item cost
									var fld_item_cost="#item_cost_"+rowCount;
									//alert(data.item.pis_cost_price);
									
									if(data.item.pis_cost_price!='0.00'){
										$(fld_item_cost).val(data.item.pis_cost_price);
									}	
								
								}
							
						
							//end set cost

						}
					}else {
						//alert(data.item.product_sn);
						//add next serial no.
						//var rowCount=parseInt($('#rowCount').val());
						var rowCount=tmp;
						var product_sn_fld='#product_sn_'+rowCount;
						var product_sn_val=($(product_sn_fld).val());
						if(data.item.is_search_by_sn){
						//	alert(1);
						//check product cost grater than sale value
						var prouct_price=data.item.product_price;	
						//alert(data.item.pis_cost_price +' , '+ prouct_price);
						
						 var cost_validate='';
						 if(3!="<?php echo $this->session->userdata('ss_warehouse_id');?>") {
						     if (data.item.pis_cost_price>prouct_price) {
						          var cost_validate=1;
						     }
						     
						 }
						cost_validate='';
						if (cost_validate==1) {
							bootbox.alert(data.item.product_sn+" Emi no product cost greater than selling price. Can not add to the invoicce. Please contact site administrator");
						}else{
							if(product_sn_val) {
							//	alert(2);
								var array_sn_old=product_sn_val.split(",");
								//alert(array_sn_old);
								
								if(product_sn_val==data.item.product_sn){
									alert('Allredy Added');
								}else if(array_sn_old.includes(data.item.product_sn)){
									alert('Allredy Added');
								}else{
									//alert('no');
									
									
									$(product_sn_fld).val(product_sn_val+','+data.item.product_sn);
								}
								//$(product_sn_fld).val(product_sn_val+','+data.item.product_sn);

								}else{

								$(product_sn_fld).val(data.item.product_sn);

							}
						} // end cost grater than sale price validation

						}
						calculateTotal();
					}				
				$("#add_item").val('');
					 return false;
				}
				$(this).autocomplete('close');
                    $(this).removeClass('ui-autocomplete-loading');
            }
        });
}
		$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       //alert("bottom!");
	   $('#bottom-total').css({
        position: 'static',
		width: '100%'
    });
   }else {
	    $('#bottom-total').css({
        position: 'fixed',
		width: '1082px'
    });
   }
});

//function to initiate bootstrap-datepicker

$(function () {
	//showKeys();
	
	//$('#add_item').focus();
	
	var currentDate = new Date();

	$('#sale_datetime').datetimepicker({
		defaultDate: new Date(),
		minDate:new Date()
		});
	//$("#warehouse_id").select2();

	$("#supp_id").select2();
	$("#customer_id").select2();
	$("#rep_id").select2();
	$("#warehouse_id").select2();
});	



function cus_city()

  {

var cus_id = $('#customer_id').val();



      jQuery.ajax({

       type: "POST",

       url: "<?php echo base_url().'customers/get_customer_city?cus_id='?>"+cus_id,

//       data: 'id='+id,

       cache: false,

       success: function(response)

       {

//		   displayNotice('page','Customer Changed!');

//$.each(alert(response));



var obj = JSON.parse(response);

$('#cus_type').val(obj.cus_type);

$('#city_id').val(obj.city_id);



//alert($('#city_id').val());

//alert($('#cus_type').val());

//        bootbox.alert("RESPONSE:["+response+"]");

       }

     });

//	 resetfun();

 }

 
function test(){
	 alert();
	  var app = $("<option/>",{value:1 , text: 01});
            $('#customer_id').append(app);
			$('#customer_id').select2("val", obj.id).trigger('change');
}



  
   $(".js-data-sales-list-ajax").select2({
	   
	  // var cat_srh=$("#cat_srh").val();
	 //  var subcategory=$("#subcategory").val();
        ajax: {
			'type': 'POST',
				'url': '<?php echo base_url('sales_pos/js_data_sales_list_ajax?srh_warehouse_id=');?>'+$("#warehouse_id").val(),
                dataType: 'json',
                delay: 0,
			
                data: function (query) {
							//alert(1);
                if (!query)
                        query = '';
                return {
                search_string: query,
				 cat_srh: $("#cat_srh").val(),
				  srh_warehouse_id: $("#srh_warehouse_id").val(),
				service_item_avalable: $("#service_item_avalable").val(),
                        format: 'json'
                };
                },
                results: function (data) {
                return {
                results: $.map(data, function (item) {
                return {
					//alert();
                text: item.sale_reference_no,
                        slug: item.sale_id,
                        id: item.sale_id
                };
                })
                };
                },
                cache: true
         }
        });
		
		

	 function calculateBalance(amount1){
		// alert(amount1);
		 var total_paymnt=0;
		 var total_paid=0;
		 var amount=parseFloat($('#sale_pymnt_amount').val());
		  var sale_pymnt_amount_2=parseFloat($('#sale_pymnt_amount_2').val());
		 var total_paymnt=parseFloat($('#total_paymnt_tmp').val());
		 //alert(total_paymnt);
		 var total_paid=parseFloat($('#sale_pymnt_given_amount').val());
		 var amount=parseFloat(amount);
		 
		 
		 
		 if(isNaN(amount)) {
			  set_message('Error!','Please enter valid amount');
		
			$('#sale_pymnt_amount').val('');
			
		 }else {
			 if(amount=='0.00'){
				 
			 }else {
				 //$('#sale_pymnt_amount').val((amount));
				 
				 //alert('amount:'+amount+', sale_pymnt_amount_2:'+sale_pymnt_amount_2 +'total_paid:'+total_paid);
				 var balance=total_paid-(amount+sale_pymnt_amount_2);
				 
				  $('#sale_pymnt_balance_amount').html(convertToAmount(balance));
				// $('#sale_pymnt_balance_amount').val(((parseFloat($('#sale_pymnt_given_amount').val()+sale_pymnt_amount_2)-amount)));
			 }
			 
		 var balance=(amount+sale_pymnt_amount_2)-total_paid;
		 //balance=11;
	//	 $('#nw_paid_amt_dis').text(convertToAmount(amount));
	//	 $('#balance_amt_dis').text(convertToAmount(balance));
		 }

		 
		 //alert();
		 
		 
		// $('#sale_pymnt_amount').focus();
		//setTimeout(alert(),1000)
		 //alert(amount);
	 }
	 
	 

// searchable dropdown get data with ajax
$(".js-data-customer_id-ajax").select2({
ajax: {
url: "<?php echo base_url('customers/getCustomer') ?>",
		dataType: 'json',
		delay: 250,
		data: function (query) {
		if (!query)
				query = '';
		return {
		search_string: query,
				format: 'json'
		};
		},
		results: function (data) {
		return {
		results: $.map(data, function (item) {
		return {
		text: item.cus_name+ ' / '+ item.cus_address+ ' / '+ item.cus_phone,
				slug: item.cus_name+ '/'+ item.cus_phone,
				id: item.cus_id
		};
		})
		};
		},
		cache: true
}
});

</script>


                                                
</body>

<!-- end: BODY -->

</html>



