<?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">
<style type="text/css">
label {
	font-weight: 700;
}
.table > thead:first-child > tr:first-child > th, .table > thead:first-child > tr:first-child > td, .table-striped thead tr.primary:nth-child(2n+1) th {
	background-color: #428bca;
	border-color: #357ebd;
	border-top: 1px solid #357ebd;
	color: white;
	text-align: center;
}
.form-horizontal .form-group {
	margin-left: 0;
	margin-right: 0;
}
.col-sm-4 {
	height: 70px;
}
.select2-container-active .select2-choice {
	border: 1px solid #428bca !important;
	box-shadow: 0px 0px 8px #428bca !important;
}

textarea:focus, input[type="text"]:focus, input[type="password"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, input[type="date"]:focus, input[type="month"]:focus, input[type="time"]:focus, input[type="week"]:focus, input[type="number"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="color"]:focus {

  border:#2d4259 solid 2px;
  background-color:#d9edf7;
}
#add_sale, #reset {
font-size: 30px;
height: 80px;
width: 200px;
}

.btnlg {
  font-size: 21px;
  line-height: 2.5;
}
.panel-body {
 /* padding: 5px;*/
}
body{
	font-size:15px;
}
.width_1{
	width:70px !important;
}
.border-color{
border: 2px solid #5cb85c !important;
font-size: 16px !important;
padding: 8px 3px !important;
	
}
</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="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 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>
            
            
            <!--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" 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" 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" 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-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-3" <?php if ($ss_group_id!=1) echo " style=\"display:none;\""; ?>>
                    <div class="form-group">
                      <label>Warehouse *</label>
                      <select id="warehouse_id" class="form-control" 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-3">
              <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" value="" data-bv-field="date"/>
              </div>
            </div>
            <div class="col-sm-3">
                    <div class="form-group">
                      <label for="customer_id">Sales Rep </label>
                      
                      <!--  search-select-->
                      
                      <?php
                     // print_r($rep_list)
                      ?>
                      
                      <select id="rep_id" class="form-control search-select" name="rep_id">
                        <option value="">-- Select Sales Rep --</option> 
                        <?php 

															

															foreach ($rep_list as $row)

															{

															//if($row->id==$this->session->userdata('ss_warehouse_id'))
															{

															?>
                        <option value="<?php echo $row->user_id;?>"> <?php //echo $row->id.',' ?><?php echo $row->user_first_name; ?></option>
                        <?php } }  ?>
                      </select>
                    </div>
                  </div>
                  <div class="col-sm-3">
                    <div class="form-group">
                      <label for="customer_id">Customer *  
                     </label>
                      <select id="customer_id" class="form-control search-select" name="customer_id" onChange="cus_city()">
                        <!--<option value="">-- Select Customer --</option>-->
                        
                        <?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-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> -->
                  
                  
                  <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="well well-sm">
              <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 style="width:50px">War.(Months)</th>
                        <th class="col-md-3">Selling Price</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>
                      
                      <!-- <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">
          
          <div class="form-group pull-right" style="width:200px;">
                  <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>
                
               <input type="submit" class="btn btn-primary " value="Add Sales" name="add_sale" id="add_sale" style="margin-bottom:30px; float:right">
              <button id="reset" class="btn btn-danger" type="button" style="float:right">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">
              <p>( Page Short Cut : Add Item-F1 , Quantity field to Discount Field-Tab , Selling Price-F2 )</p>
            
          </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="">
          
        </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: 50000;" class="well well-sm" id="bottom-total">
          <table style="margin-bottom:0;" class="table table-bordered table-condensed totals">
            <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="20%">Total <span id="f_total" class="totals_val pull-right">0.00</span></td>
                <td width="20%">Order Discount <span id="tds" class="totals_val pull-right">0.00</span></td>
                <td>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 () {
	//showKeys();
	
	$('#add_item').focus().click();//.keypress().trigger();
	//$('#add_item').click();
});	



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!')  ;
	  }	
	  
	 // 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();

	

}



$('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();

	//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) {
    if(e.which == 13) {
        //alert('You pressed enter!');
		 $("#last_ley").val(13);
    }
	else{
		$("#last_ley").val('');
	}
});


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*/

 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);
				
				fbs_click(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!','Please click "Add Sales Button" to complete sale');
	//alert('Please click "Add Save Button" to complete sale');
}// end last_ley if 

}


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();

        $("#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(),

            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');	
							
						}
						*/

				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()
		});
	//$("#warehouse_id").select2();

	$("#supp_id").select2();
	$("#customer_id").select2();
	$("#rep_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');
}



 
</script>
</body>

<!-- end: BODY -->

</html>