<div class="container-fluid h-100">
  <div id="loading_wrapper" style="display:none;">
    <div id="loading"></div>
  </div>
  <div class="row h-100">
    <!-- Column One -->
    <div class="col-lg-6 col-md-6 col-sm-6 d-flex flex-column h-100">
      <!-- Order Details -->
      <div class="card h-100">
        <div class="card-block d-flex flex-column h-100">
          <div class="card-title row">
            <div class="col-lg-6 col-md-6 col-sm-6">
              <%if !@table.nil?%>
              <span class="hidden" id ="table_id" value="<%=@table.id%>"><%=@table.id%></span>
              <span class="hidden" id="table_type" value="<%=@table.type%>"><%=@table.type%></span>
              <%else%>
              <span class="hidden" id ="table_id" value="<%=@table%>"><%=@table%></span>
              <span class="hidden" id="table_type" value="<%=@table%>"><%=@table%></span>
              <%end%>

              <p id="sale-id" class="hidden"><%=@sale_data.sale_id %></p>
              <p class="m-l-10">Receipt No: <span id="receipt_no"><%=@sale_data.receipt_no rescue ' '%></span></p>
              <!-- <p>Cashier:  <span id="cashier"><%=@sale_data.cashier_name rescue ' '%></span></p> -->
            </div>
            <div class="col-lg-6 col-md-6 col-sm-6 text-right">
              <p class="m-r-10">Date:  <span id="receipt_date"> <%=@sale_data.receipt_date.strftime("%d/%m/%Y - %I:%M %p") rescue '-'%></span></p>
            </div>
          </div>
          <div id="order-detail-slimscroll">
            <div class="card-text dining">
              <span id="discount_itemsErr" style="color:red;"></span>
              <table class="table table-default" id="order-items-table">
                <thead>
                  <tr>
                    <th class="item-name">Items</th>
                    <th class="item-attr">QTY</th>
                    <th class="item-attr">Price</th>
                  </tr>
                </thead>
                <tbody>
                  <% sub_total = 0 %>
                  <% @sale_data.sale_items.includes(:discount_item).each do |sale_item| %>
                  <% sub_total += sale_item.status == "Discount"? sale_item.price : sale_item.qty * sale_item.unit_price %>
                  <% if sale_item.price > 0 && sale_item.status.blank? %>
                  <tr class="item-row item" id="<%= sale_item.sale_item_id %>"
                      data-account-type="<%=sale_item.account_id%>"
                      data-item-qty="<%=sale_item.qty%>"
                      data-item-unit-price="<%=sale_item.unit_price%>"
                      data-item-price="<%=sale_item.unit_price%>"
                      <% if sale_item.discount_item %>
                      data-item-discount="<%=sale_item.discount_item.discount%>"
                      data-item-discount_type="<%=sale_item.discount_item.discount_type%>"
                      <% end %>>
                    <td style="width:60%; text-align:left">
                      <span id="item-name-price"><%=sale_item.product_name%>@<%=sale_item.unit_price%></span>
                      <% if sale_item.discount_item %>
                        <% if sale_item.discount_item.nett? %>
                      <div id="item-discount" class="text-secondary">With a <strong><%= number_format(sale_item.discount_item.discount) %></strong> discount</div>
                        <% elsif sale_item.discount_item.percentage? %>
                      <div id="item-discount" class="text-secondary">With a <strong><%= number_format(sale_item.discount_item.discount, precision: 0) %>%</strong> discount</div>
                        <% end %>
                      <% else %>
                      <div id="item-discount" class="text-secondary hidden"></div>
                      <% end %>
                    </td>
                    <td style="width:20%; text-align:right">
                      <span id="item-qty"><%=sale_item.qty%></span>
                    </td>
                    <td style="width:20%; text-align:right">
                      <% item_price = sale_item.qty*sale_item.unit_price %>
                      <% if sale_item.discount_item %>
                      <% discount_price = item_price + sale_item.discount_item.price %>
                      <span id="item-total-price"><%= discount_price %></span>
                      <div id="item-old-price" class="text-secondary"><s><%= item_price %></s></div>
                      <% else %>
                      <span id="item-total-price"><%= item_price %></span>
                      <div id="item-old-price" class="text-secondary"></div>
                      <% end %>
                    </td>
                  </tr>
                  <% end %>
                  <% end %>
                </tbody>
              </table>
            </div>
          </div>
          <div class="card-text">
            <table class="table" id="order-charges-table" border="0">
              <tr>
                <td class="charges-name"><strong>Sub Total:</strong></td>
                <td class="item-attr"><strong id="order-sub-total"><%= number_format(sub_total, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i ) %></strong></td>
              </tr>
              <tr>
                <%if @sale_data.discount_type == 'member_discount'%>
                <td class="charges-name"><strong>Member Discount:</strong></td>
                <%else%>
                <td class="charges-name"><strong>Discount:</strong></td>
                <%end%>

                <td class="item-attr">(<strong id="order-discount"><%= number_format(@sale_data.total_discount, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i ) %></strong>)</td>
              </tr>
              <tr class="hidden">
                <td class="charges-name"><strong>Tax:</strong></td>
                <td class="item-attr"><strong id="order-Tax"><%= number_format(@sale_data.total_tax, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i ) %></strong></td>
              </tr>
              <tr class="hidden">
                <td class="charges-name"><strong>Grand Total:</strong></td>
                <td class="item-attr"><strong id="order-grand-total"><%= number_format(@sale_data.grand_total, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i ) %></strong></td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </div>
    <!-- Column One -->

    <!-- Column Two -->
    <div class="col-lg-5 col-md-5 col-sm-5 d-flex flex-column h-100">
      <!-- Discount Amount -->
      <div class="card h-100">
        <div class="card-header">
          <div><strong id="order-title">Discount Control</strong></div>
        </div>
        <div class="card-block">
          <div class="card-title">
            <div class="form-horizontal">
              <div class="col-md-12">
                <div class="form-group">
                  <input type="text" id="discount-amount" name="discount-amount" value="0" class="form-control" />
                  <span id="discount-amountErr" style="color:red;"></span>
                </div>
                <br>
                <div class="form-group">
                  <% @accounts.each do |acc| %>
                  <button id="account-<%= acc.id %>" class="accounts-type btn bg-default"><%= acc.title %></button>
                  <% end %>
                </div>
              </div>
            </div>
          </div>

          <hr />
          <div class="container-fluid p-l-20 p-r-10">
            <div class="row">
              <div class="col-md-8">
                <div class="row bottom">
                  <div class="col-md-3">
                    <div class="fluid cashier_number" data-value="5" data-type="add">5%</div>
                  </div>
                  <div class="col-md-9">
                    <div class="row">
                      <div class="col-md-3 cashier_number" data-value="1" data-type="num" style="margin-left: 6px;">1</div>
                      <div class="col-md-3 left cashier_number" data-value="2" data-type="num">2</div>
                      <div class="col-md-3 left cashier_number" data-value="3" data-type="num">3</div>
                    </div>
                  </div>
                </div>

                <div class="row bottom clearfix">
                  <div class="col-md-3">
                    <div class="fluid cashier_number" data-value="10" data-type="add">10%</div>
                  </div>
                  <div class="col-md-9">
                    <div class="row">
                      <div class="col-md-3 cashier_number" data-value="4" data-type="num" style="margin-left: 6px;">4</div>
                      <div class="col-md-3 left cashier_number" data-value="5" data-type="num">5</div>
                      <div class="col-md-3 left cashier_number" data-value="6" data-type="num">6</div>
                    </div>
                  </div>
                </div>

                <div class="row bottom">
                  <div class="col-md-3">
                    <div class="fluid cashier_number" data-value="15" data-type="add">15%</div>
                  </div>
                  <div class="col-md-9">
                    <div class="row">
                      <div class="col-md-3 cashier_number" data-value="7" data-type="num" style="margin-left: 6px;">7</div>
                      <div class="col-md-3 left cashier_number" data-value="8" data-type="num">8</div>
                      <div class="col-md-3 left cashier_number" data-value="9" data-type="num">9</div>
                    </div>
                  </div>
                </div>

                <div class="row bottom">
                  <div class="col-md-3">
                    <div class="fluid cashier_number" data-value="20" data-type="add">20%</div>
                  </div>
                  <div class="col-md-9">
                    <div class="row">
                      <div class="col-md-3 cashier_number" data-value="0" data-type="num" style="margin-left: 6px;">0</div>
                      <div class="col-md-3 left cashier_number" data-value="." data-type="num">.</div>
                      <div class="col-md-3 left cashier_number" data-value="00" data-type="num">00</div>
                    </div>
                  </div>
                </div>

                <div class="row bottom">
                  <div class="col-md-3">
                    <div class="fluid cashier_number" data-value="30" data-type="add">30%</div>
                  </div>
                  <div class="col-md-9">
                    <div class="row">
                      <div class="col-md-3 cashier_number" style="margin-left: 6px;"></div>
                      <div class="col-md-3 left cashier_number red" data-type="del">DEL</div>
                      <div class="col-md-3 left cashier_number green" data-type="clr">CLR</div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <button id="net" class="btn btn-info fluid action-btn">Nett</button>
                  <button id="percentage" class="btn btn-primary fluid action-btn" style="font-size: 12.4px">Percentage</button>
                  <button id="remove-item" class="btn bg-default fluid action-btn">Clear Discount</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- <div class="card">
      <div class="card-header">
      <div><strong id="order-title">Promo Code</strong></div>
    </div>
    <div class="card-block">
    <div class="card-title">
    <div class="form-horizontal">
    <div class="p-l-20">
    <div class="row">
    <div class="col-md-8 form-group">
    <div class="form-group">
    <input type="text" id="promo-code" name="promo-code" value="" class="form-control" /></span>
  </div>
</div>
<div class="col-md-4">
<button id="" class="btn btn-primary btn-block action-btn">Promo</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div> -->
</div>
<!-- Column Three -->
<div class="col-lg-1 col-md-1 col-sm-1">
  <!-- Action Panel -->
  <div>
    <button type="button" class="btn bg-default btn-block" id="back" ><i class="material-icons">reply</i> Back </button>
    <button type="button" class="btn btn-block btn-default waves-effect" id='refresh'>Refresh</button>
    <hr>
    <button id="remove-item-discount" class="btn btn-primary btn- action-btn">Remove Item Discount</button>
    <button id="remove-all" class="btn btn-primary btn-block action-btn">Remove All</button>
    <button id="pay-discount" class="btn btn-primary btn-block action-btn">Enter</button>
    <% if @member_discount%>
    <!-- <hr />
      <button id="member-discount" class="btn btn-success btn-block action-btn
      <%= @sale_data.customer.membership_id ? " " : "disabled"%>">Member Discount</button> -->
      <%end %>
    </div>
  </div>
</div>
</div>

<script type="text/javascript">
  var cashier_type = "<%= @cashier_type %>";
  var totalAmount = <%= sub_total %>;
  var totalDiscount = <%= @sale_data.total_discount %>;
  var precision = <%= precision %>;
  var originalAmount = totalAmount;
  var originalDiscount = totalDiscount;
  var queryParams = new URLSearchParams(window.location.search)

  $(document).ready(function(){
    setHeaderBreadCrumb(_DISCOUNTS_);
    /* check webview loaded*/
    var webview = <%= @webview %>;
    showHideNavbar(webview);

    $('#back').on('click',function(){
      var id       = $("#table_id").text();
      var type     = $("#table_type").text();
      var sale_id = $('#sale-id').text();
      if (cashier_type=="food_court"  && queryParams.get('payment_type') == 'qr') {
          window.location.href = '/foodcourt/'+sale_id+'/'+'qrpay/precreate';
      } else if(cashier_type == "food_court") {
        window.location.href = '/foodcourt/sale/'+sale_id+'/'+cashier_type+'/payment/';
      }
    })

    $(".cashier_number").on('click', function(event){
      if(event.handled !== true) {
        var original_value = 0;
        original_value = $('#discount-amount').val();
        var input_type = $(this).attr("data-type");
        switch (input_type) {
          case 'num':
          var input_value = $(this).attr("data-value");
          if (parseFloat(original_value) == 0){
            $('#discount-amount').val(input_value);
          }
          else{
            $('#discount-amount').val(original_value + '' + input_value);
          }
          break;
          case 'add':
          var input_value = $(this).attr("data-value");
          amount = parseInt(input_value);
          $('#discount-amount').val(amount);
          break;
          case 'del' :
          var discount_text=$('#discount-amount').val();
          $('#discount-amount').val(discount_text.substr(0,discount_text.length-1));
          break;
          case 'clr':
          $('#discount-amount').val("0");
          break;
        }
        event.handled = true;
      } else {
        return false;
      }
    });

    // Select Sale Item
    $('#order-items-table').on('click', '.item-row', function(){
      if($(this).hasClass('selected-item') == true){
        $(this).removeClass('selected-item');
      }
      else {
        $(this).addClass('selected-item');
      }
    });

    // Select for account types
    $(".accounts-type").on('click', function(e){
      var account_id = $(this).attr('id').substr(8);
      if($(this).hasClass('selected-account') == true){
        $(this).removeClass('selected-account');
        $(".item-row").each(function(i){
          if($(this).data("account-type") == account_id){
            $(this).removeClass("selected-item");
          }
        });
      }
      else {
        $(this).addClass('selected-account');
        $(".item-row").each(function(i){
          if($(this).data("account-type") == account_id){
            if(parseInt($(this).data("item-qty")) >0 && parseInt($(this).data("item-price")) >0){
              $(this).addClass("selected-item");
            }
            else{
              console.log("discount item");
            }
          }
        });
      }
    });

    // Calculate Net Discount for Payment
    $("#net").on('click', function(e){
      e.preventDefault();
      var sale_id = $('#sale-id').text();
      var discount_value = $('#discount-amount').val();
      var sub_total = totalAmount;
      var ajax_url = "/foodcourt/" + sale_id + "/discount";

      if(discount_value!=""){
        if(discount_value > 0){
          if(parseFloat(discount_value) > sub_total){
            $("#discount-amount").val("");
            $("#discount-amountErr").html("Discount is greater than sub total!");
          }else{
            $("#discount-amountErr").html("");
            // Selected Items
            var sale_items = get_selected_sale_items();

            // Selected Account
            var account_types = get_selected_account_types();

            if(sale_items.length == 0 && account_types.length == 0){
              calculate_overall_discount(0, discount_value);
            }
            else if(sale_items.length > 0){
              calculate_item_discount(0, discount_value, sale_items, account_types);
            }

            // Remove Selection
            selection_remove();
          }
        }else{
          $("#discount-amountErr").html("Discount must be greater than 0!");
        }
      }else{
        $("#discount-amountErr").html("can't be  blank");
      }
      $('#discount-amount').val("0");
    });

    // Calculate Percentage Discount for Payment
    $("#percentage").on('click', function(e){
      e.preventDefault();
      var sale_id = $('#sale-id').text();
      var discount_value = $('#discount-amount').val();
      var ajax_url = "/foodcourt/" + sale_id + "/discount";

      if(discount_value!=""){
        if(discount_value > 0){
          $("#discount-amountErr").val("");

          // Selected Items
          var sale_items = get_selected_sale_items();
          // Selected Account
          var account_types = get_selected_account_types();

          if(sale_items.length == 0 && account_types.length == 0){
            calculate_overall_discount(1, discount_value);
          } else if(sale_items.length > 0){
            calculate_item_discount(1, discount_value, sale_items, account_types);
          }
        }else{
          $("#discount-amountErr").html("Discount must be greater than 0!");
        }
      }else{
        $("#discount-amountErr").html("can't be  blank");
      }

      // Remove Selection
      selection_remove();
      $('#discount-amount').val("0");
    });

    // Remove selected discount items
    $("#remove-item").on('click', function(e){
      e.preventDefault();
      // var total = 0;

      $('.item-row.new-discount').each(function(i){
        if (parseInt($(this).data("new-discount")) > 0) {
          if (parseInt($(this).data("item-discount")) > 0) {
            var amount = $(this).data("item-discount");
            var type = $(this).data("item-discount-type");

            $(this).data("item-discount", amount);
            $(this).data("item-discount-type", type);

            if (type == 'net') {
              $(this).find("#item-discount").html("With a " + amount + " discount")
            } else if (type == 'percentage') {
              $(this).find("#item-discount").html("With a " + amount + "% discount")
            }

            $(this).find('#item-total-price').text(parseFloat($(this).data("item-price")));
          } else {
            $(this).find("#item-discount").addClass("hidden");
            $(this).find("#item-discount").html("");
            $(this).find('#item-total-price').text(parseFloat($(this).data("item-price")));
            $(this).find('#item-old-price').html('');
          }
          $(this).removeData("new-discount");
          $(this).removeData("new-discount");
        }
        $(this).removeClass("new-discount")
      });

      $("#order-sub-total").text(originalAmount.toFixed(<%= precision.to_i %>));
      $("#order-discount").text(originalDiscount.toFixed(<%= precision.to_i %>));
    });

    // Pay Discount for Payment
    $("#pay-discount").on('click', function(e){
      e.preventDefault();
      if($('#pay-discount').is(":visible")) {
        $('#pay-discount').prop("disabled",true);
      }
      $("#loading_wrapper").show();
      var sale_id = $('#sale-id').text();
      var discount_items = JSON.stringify(get_new_discount_item_rows());
      var overall_discount = totalDiscount;
      var sub_total = totalAmount;
      var ajax_url = "/foodcourt/" + sale_id + "/discount";

      var params = { 'cashier_type' : cashier_type, 'sale_id': sale_id, 'sub_total': sub_total, 'discount_items': discount_items, 'overall_discount': overall_discount };

      $.ajax({
        type: "POST",
        url: ajax_url,
        data: params,
        success:function(result){
          $("#loading_wrapper").hide();
          swal({
            title: "Information!",
            text: result.status,
          }, function () {
            if (cashier_type=="food_court"  && queryParams.get('payment_type') == 'qr') {
              window.location.href = '/foodcourt/'+sale_id+'/'+'qrpay/precreate';
            }
            else if(cashier_type == "food_court") {
              window.location.href = '/foodcourt/sale/'+sale_id+'/'+cashier_type+'/payment/';
            }
          });
        }
      });
    });

    // Remove selected given discount item
    $("#remove-item-discount").on('click', function(e){
      e.preventDefault();
      var sale_id = $('#sale-id').text();
      var discount_items = [];

      var sale_items = get_selected_discount_items();

      if (sale_items == null || sale_items.length <= 0) {
        swal ("Oops" , "You have not selected discount item!" ,  "error" );
        return;
      }

      for(var i=0;i < sale_items.length;i++){
        console.log(parseFloat(sale_items[i].discount));
        if(parseFloat(sale_items[i].discount) > 0){
          discount_items.push(sale_items[i]);
        }
      }

      var params = { 'cashier_type': cashier_type,'sale_id': sale_id, 'discount_items': JSON.stringify(discount_items) };
      $.ajax({
        type: "POST",
        url: "/foodcourt/" + sale_id + "/remove_discount_items",
        data: params,
        success: function(result){
          swal({
            title: "Information!",
            text: result.status,
            type: "success",
          }, function () {
            if (cashier_type=="food_court"  && queryParams.get('payment_type') == 'qr') {
              window.location.href = '/foodcourt/'+sale_id+'/'+'qrpay/precreate';
            }
            else if(cashier_type == "food_court") {
              window.location.href = '/foodcourt/sale/'+sale_id+'/'+cashier_type+'/payment/';
            }
          });
        }
      });
    });

    $("#remove-all").on('click', function(e){
      e.preventDefault();
      var sale_id = $('#sale-id').text();
      $.ajax({
        type: "GET",
        url: "/foodcourt/" + sale_id + "/" + cashier_type + "/remove_all_discount",
        success: function(result){
          swal({
            title: "Information!",
            text: result.status,
            type: "success",
          }, function () {
            if (cashier_type=="food_court"  && queryParams.get('payment_type') == 'qr') {
              window.location.href = '/foodcourt/'+sale_id+'/'+'qrpay/precreate';
            }
            else if(cashier_type == "food_court") {
              window.location.href = '/foodcourt/sale/'+sale_id+'/'+cashier_type+'/payment/';
            }
          });
        }
      });
    });

    // Pay Discount for membership
    $("#member-discount").on('click', function(e){
      e.preventDefault();
      var sale_id = $('#sale-id').text();
      var sub_total = totalAmount;
      var ajax_url = "/foodcourt/" + sale_id + "/member_discount";

      // Selected Account
      //var account_types = JSON.stringify(get_selected_account_types());

      // if($('.accounts-type').hasClass('selected-account') == true){

      // var params = {'sale_id':sale_id, 'sub_total':sub_total, 'account_types':account_types };

      var params = {'cashier_type': cashier_type,'sale_id':sale_id, 'sub_total':sub_total };

      $.ajax({
        type: "POST",
        url: ajax_url,
        data: params,
        success:function(result){
          if (result.status == "Success") {
            type   = 'success'
            btn_color = 'green'
          }else{
            type   = 'error'
            btn_color = 'red'
          }
          swal({
            title: "Information!",
            text: result.status,
            confirmButtonText: 'OK',
            confirmButtonColor: btn_color,
          }, function () {
            if (cashier_type=="quick_service" || cashier_type=="food_court") {
              window.location.href = '/foodcourt/sale/'+sale_id+'/'+cashier_type+'/payment/';
            }else{
              if(result.table_type == "Table"){
                window.location.href = "/foodcourt/table/" + result.table_id
              }
              else {
                window.location.href = "/foodcourt/room/" + result.table_id
              }
            }
          });
        }
      });

    });//end member discount
  });

  /* Remove Selection */
  function selection_remove(){
    $(".item-row").removeClass("selected-item");
    $(".accounts-type").removeClass("selected-account");
  }

  /* Get Item rows but not discount*/
  function get_item_rows(){
    var sale_items = [];
    $('.item-row.item').not('.discount').each(function(i){
      var sale_item = {};
      sale_item.id = $(this).attr('id').substr(0,16);
      sale_item.name = $(this).find('#item-name-price').text().split('@')[0];
      sale_item.account_id = $(this).data('account-type');
      sale_item.price = $(this).data('item-price');
      sale_items.push(sale_item);
    });
    return sale_items;
  }

  /* Get discount Item rows */
  function get_new_discount_item_rows(){
    var sale_items = [];
    $('.item-row.new-discount').each(function(i){
      var sale_item = {};
      sale_item.id = $(this).attr('id');
      sale_item.name = $(this).find('#item-name-price').text();
      sale_item.account_id = $(this).data('account_type');
      sale_item.price = $(this).data('item-price');
      sale_item.discount = $(this).data('new-discount');
      sale_item.discount_type = $(this).data('new-discount-type')
      sale_items.push(sale_item);
    });
    return sale_items;
  }

  /* Get discount Item rows */
  function get_selected_discount_items(){
    var sale_items = [];
    $('.item-row.selected-item').each(function(i){
      var sale_item = {};
      sale_item.id = $(this).attr('id');
      sale_item.name = $(this).find('#item-name-price').text();
      sale_item.account_id = $(this).data('account_type');
      sale_item.price = $(this).data('item-price');
      sale_item.discount = $(this).data('item-discount');
      sale_item.discount_type = $(this).data('item-discount-type')
      sale_items.push(sale_item);
    });
    return sale_items;
  }

  /* Get Selected Sale Item's ID and Price */
  function get_selected_sale_items(){
    var sale_items = [];
    $('.item-row.item.selected-item').each(function(i){
      var sale_item = {};
      sale_item.id = $(this).attr('id').substr(0,16);
      sale_item.name = $(this).find('#item-name-price').text().split('@')[0];
      sale_item.account_id = $(this).data('account-type');
      sale_item.price = $(this).data('item-price');
      sale_items.push(sale_item);
    });
    return sale_items;
  }

  /* Get Selected Accounts ID and Price */
  function get_selected_account_types(){
    var account_types = [];

    $('.selected-account').each(function(i){
      var account= {};
      account.id = $(this).attr('id').substr(8);
      account.name = $(this).text();
      account_types.push(account);
    });
    return account_types;
  }

  /* Calculate Overall Discount*/
  function calculate_overall_discount(type, amount){
    var sub_total = totalAmount;
    var total_discount = 0;

    // For Net Pay
    if(type == 0){
      total_discount = Math.round(amount * Math.pow(10, precision)) / Math.pow(10, precision);
    }

    // For Percentage Pay
    if(type == 1){
      if(amount > 100 ){
        swal({
          title:"Oops!",
          text:'Percentage Value over 100!',
          type: "error",
          confirmButtonText: 'OK',
          confirmButtonColor:"red"
        });
      }
      else{
        total_discount = Math.round(sub_total * amount / 100 * Math.pow(10, precision)) / Math.pow(10, precision);
      }
    }
    totalDiscount = total_discount
    $("#order-discount").text(parseFloat(total_discount).toFixed(<%= precision.to_i %>));
  }

  /* Calculate Items Discount*/
  function calculate_item_discount(type, amount, sale_items, account_types){
    var origin_sub_total = totalAmount;
    var dis_amount = 0;
    var sub_total = 0;
    var total_discount = 0;
    var arrItemName = "";

    $("#discount_itemsErr").html("");
    $("#discount-amountErr").html("");
    // For Net Pay
    if(origin_sub_total > 0){
      if(type == 0){
        dis_amount = -Math.round(amount * Math.pow(10, precision)) / Math.pow(10, precision);
        if(sale_items.length > 0){
          for(var i=0;i < sale_items.length;i++){
            var sale_item = sale_items[i]
            if(parseFloat(amount) > parseFloat(sale_item.price)){
              arrItemName += ", " + sale_item.name;
            }else{
              total_discount = parseFloat(total_discount) + parseFloat(amount);

              if(parseFloat(origin_sub_total) >= parseFloat(total_discount)){
                var item_row = $('#'+sale_item.id);

                item_row.data('new-discount', amount);
                item_row.data('new-discount-type', 'nett');

                var discount = item_row.find('#item-discount');
                discount.html('With a <strong>'+ amount +'</strong> discount');
                discount.removeClass('hidden');

                item_row.find('#item-total-price').text(parseFloat(sale_item.price) - amount);
                item_row.find('#item-old-price').html('<s>'+ parseFloat(sale_item.price) +'</s>');
                item_row.addClass('new-discount');
              }else{
                total_discount = parseFloat(total_discount) - parseFloat(amount);
                $("#discount-amountErr").html("Discount is greater than sub total!");
              }
            }
          }
        }

        if(arrItemName!=""){
          arrItemName = arrItemName.substr(2);
          if(arrItemName.match(/,/g || []) != null){
            if(arrItemName.match(/,/g || []).length >= 1){
              $("#discount_itemsErr").html("Discount is greater than "+arrItemName+" prices");
            }
          }else{
            $("#discount_itemsErr").html("Discount is greater than "+arrItemName+" price");
          }

        }

        sub_total = parseFloat(origin_sub_total) - parseFloat(total_discount);
        totalAmount = sub_total
        $("#order-sub-total").text(parseFloat(sub_total).toFixed(<%= precision.to_i %>));
      }

      // For Percentage Pay
      if(type == 1){
        if(amount > 100 ){
          swal({
            title:"Oops!",
            text:'Percentage Value over 100!',
            type: "error",
            confirmButtonText: 'OK',
            confirmButtonColor:"red"
          });
        }
        else{
          // Check sale items exists
          if(sale_items.length > 0){
            for(var i=0;i < sale_items.length;i++){
              var sale_item = sale_items[i];
              dis_amount = -Math.round(sale_item.price * amount / 100 * Math.pow(10, precision)) / Math.pow(10, precision);

              total_discount = total_discount + dis_amount;
              if(parseFloat(origin_sub_total) >= parseFloat(total_discount)){
                var item_row = $('#'+sale_item.id);

                item_row.data('new-discount', amount);
                item_row.data('new-discount-type', 'percentage');

                var discount = item_row.find('#item-discount');
                discount.html('With a <strong>'+ amount +'%</strong> discount');
                discount.removeClass('hidden');

                item_row.find('#item-total-price').text(parseFloat(sale_item.price) + dis_amount);
                item_row.find('#item-old-price').html('<s>'+ parseFloat(sale_item.price) +'</s>');
                item_row.addClass('new-discount');
              }else{
                total_discount = total_discount - dis_amount;
                $("#discount-amountErr").html("Discount is greater than sub total!");
              }
            }
            sub_total = parseFloat(origin_sub_total) + parseFloat(total_discount);
            totalAmount = sub_total
            $("#order-sub-total").text(parseFloat(sub_total).toFixed(<%= precision.to_i %>));
          }
        }
      }

    }else{
      $("#discount-amountErr").html("Discount is greater than sub total!");
    }

  }

  function item_row_template(type, item, discount_amount, amount){
    var dis_str = "-discount";
    if(type == 1){
      dis_str = dis_str + "(" + amount + "%)"
    }
    var discount_item_row = "<tr class='item-row new-discount' id='" + item.id + "'>" +
    "<td style='width: 60%; text-align: left;'>" +
    "<span id='item_account_type' class='hidden'>" +
    item.account_id +
    "</span>" +
    "<span id='item-name-price'>" +
    item.name + dis_str +
    "</span>" +
    "</td>" +
    "<td style='width: 20%; text-align: right;'>" +
    "<span id='item-qty'>1</span>" +
    "</td>" +
    "<td style='width: 20%; text-align: right;'>" +
    "<span id='item-total-price'>" +
    discount_amount +
    "</span>" +
    "</td>" +
    "</tr>";
    return  discount_item_row;
  }

</script>
