 <div class="container-fluid m-top-100">
 <div id="loading_wrapper" style="display:none;">
    <div id="loading"></div>
 </div>
 	<div class="row">
 		<!-- Column One -->
 		<div class="col-lg-6 col-md-6 col-sm-6">
 			<!-- Order Details -->
 			<div class="card"  >
        <!-- <div class="card-header">
          <div><strong id="order-title">ORDER DETAILS</strong></div>
      </div> -->
      <div class="card-block">
      	<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" data-height="160">
        	<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.each do |sale_item| %>
        						<% sub_total += 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 %> >
      								<td style="width:60%; text-align:left">
      									<span id="item-account-type" class="hidden"><%=sale_item.account_id%></span>
      									<span id="item-account-qty" class="hidden"><%=sale_item.qty%></span>
      									<span id="item-name-price"><%=sale_item.product_name%>@<%=sale_item.unit_price%></span>
      								</td>
      								<td style="width:20%; text-align:right">
      									<span id="item-qty"><%=sale_item.qty%></span>
      								</td>
      								<td style="width:20%; text-align:right">
      									<span id="item-total-price"><%=(sale_item.qty*sale_item.unit_price)%></span>
      								</td>
      							</tr>
                    <% elsif sale_item.price < 0 && sale_item.status == "Discount" %>
                    <tr class="item-row discount" id=<%= sale_item.sale_item_id %> >
                      <td style="width:60%; text-align:left">
                        <span id="item-account-type" class="hidden"><%=sale_item.account_id%></span>
                        <span id="item-account-qty" class="hidden"><%=sale_item.qty%></span>
                        <span id="item-name-price"><%=sale_item.product_name%>@<%=sale_item.unit_price%></span>
                      </td>
                      <td style="width:20%; text-align:right">
                        <span id="item-qty"><%=sale_item.qty.abs%></span>
                      </td>
                      <td style="width:20%; text-align:right">
                        <span id="item-total-price"><%=(sale_item.qty*sale_item.unit_price)%></span>
                      </td>
                    </tr>
      							<% end %>
      					  <% end %>
      				  </tbody>
        		</table>
        	</div>
      	</div>
      		<div class="card-footer">
      			<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>
                <td class="charges-name"><strong>Food:</strong></td>
                <td class="item-attr"><strong id="order-food"></strong></td>
              </tr>
              <tr>
                <td class="charges-name"><strong>Beverage:</strong></td>
                <td class="item-attr"><strong id="order-beverage"></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">
	<!-- Discount Amount -->
	<div class="card">
		<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="p-l-20">
				<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 bg-info fluid action-btn">Nett</button>
							<button id="percentage" class="btn bg-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 bg-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 id="remove-item-discount" class="btn btn-primary btn- action-btn">Remove Item Discount</button>
			<button id="remove-all" class="btn bg-primary btn-block action-btn">Remove All</button>
			<button id="pay-discount" class="btn bg-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;
	$(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=="quick_service" || cashier_type=="food_court") {
				window.location.href = '/origami/sale/'+sale_id+'/'+cashier_type+'/payment/';
		    }else{
		    	if (type=="Table") {
			      window.location.href = '/origami/table/'+id
			    }else{
			      window.location.href = '/origami/room/'+id
			    }
		    }
		 })

		$(".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 (input_value == "." && original_value.includes(".")) {
              break;
            }
            if (parseFloat(input_value) >= 0 && !original_value.includes(".") && (parseFloat(original_value) == 0)) {
              $('#discount-amount').val(parseFloat(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).children().find("#item-account-type").text() == account_id){
					$(this).removeClass("selected-item");
				}
			});
		}
		else {
			$(this).addClass('selected-account');
			$(".item-row").each(function(i){
				if($(this).children().find("#item-account-type").text() == account_id){
					if(parseInt($(this).children().find("#item-account-qty").text()) >0 && parseInt($(this).children().find("#item-total-price").text()) >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 = "/origami/" + 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");
		}

	});

	// 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 = "/origami/" + 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();
	});

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

		$('.item-row.new-discount').each(function(i){
			// total = total + Math.abs(amount);
			$(this).remove();
		});

		$("#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 = "/origami/" + 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=="quick_service" || cashier_type=="food_court") {
			    		window.location.href = '/origami/sale/'+sale_id+'/'+cashier_type+'/payment/';
			    	}else{
			    		if(result.table_type == "Table"){
			    			window.location.href = "/origami/table/" + result.table_id
				    	}
				    	else {
				    		window.location.href = "/origami/room/" + result.table_id
				    	}
			    	}
			    });
			}
		});
	});

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

		for(var i=0;i < sale_items.length;i++){
			if(sale_items[i].price < 0){
				discount_items.push(sale_items[i]);
			}
			else {
				swal ("Oops" , "You have no selected item!" ,  "error" );
				return;
			}
		}

		var params = { 'cashier_type': cashier_type,'sale_id': sale_id, 'discount_items': JSON.stringify(discount_items) };
		$.ajax({
			type: "POST",
			url: "/origami/" + sale_id + "/remove_discount_items",
			data: params,
			success: function(result){
				swal({
			        title: "Information!",
			        text: result.status,
			        type: "success",
			    }, function () {
			    	if (cashier_type=="quick_service" || cashier_type=="food_court") {
			    		window.location.href = '/origami/sale/'+sale_id+'/'+cashier_type+'/payment/';
			    	}else{
				    	if(result.table_type == "Table"){
				    		window.location.href = "/origami/table/" + result.table_id
				    	}
				    	else {
				    		window.location.href = "/origami/room/" + result.table_id
				    	}
				    }
			    });
			}
		});
	});

	$("#remove-all").on('click', function(e){
		e.preventDefault();
		var sale_id = $('#sale-id').text();
		$.ajax({
			type: "GET",
			url: "/origami/" + sale_id + "/" + cashier_type + "/remove_all_discount",
			success: function(result){
				swal({
			        title: "Information!",
			        text: result.status,
			        type: "success",
			    }, function () {
			    	if (cashier_type=="quick_service" || cashier_type=="food_court") {
			    		window.location.href = '/origami/sale/'+sale_id+'/'+cashier_type+'/payment/';
			    	}else{
				    	if(result.table_type == "Table"){
				    		window.location.href = "/origami/table/" + result.table_id
				    	}
				    	else {
				    		window.location.href = "/origami/room/" + result.table_id
				    	}
				    }
			    });
			}
		});
	});

	// 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 = "/origami/" + 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 = '/origami/sale/'+sale_id+'/'+cashier_type+'/payment/';
			    	}else{
				    	if(result.table_type == "Table"){
				    		window.location.href = "/origami/table/" + result.table_id
				    	}
				    	else {
				    		window.location.href = "/origami/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).find('#item-account-type').text();
 		sale_item.price = $(this).find('#item-total-price').text();
 		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).find('#item_account_type').text();
 		sale_item.price = $(this).find('#item-total-price').text();
 		sale_items.push(sale_item);
 	});
 	return sale_items;
 }

 /* Get discount Item rows */
function get_selected_discount_items(){
	var sale_items = [];
	$('.item-row.discount.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).find('#item_account_type').text();
		sale_item.price = $(this).find('#item-total-price').text();
		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).find('#item-account-type').text();
		sale_item.price = $(this).find('#item-total-price').text();
		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++){
					if(parseFloat(amount) > parseFloat(sale_items[i].price)){
						arrItemName += ", " + sale_items[i].name;
					}else{
						var discount_item_row = item_row_template(type,sale_items[i], dis_amount, amount);
						total_discount = parseFloat(total_discount) + parseFloat(amount);

						if(parseFloat(origin_sub_total) >= parseFloat(total_discount)){
							$("#order-items-table tbody").append(discount_item_row);
						}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++){
							dis_amount = -Math.round(sale_items[i].price * amount / 100 * Math.pow(10, precision)) / Math.pow(10, precision);
							var discount_item_row = item_row_template(type,sale_items[i], dis_amount, amount);

							total_discount = total_discount + dis_amount;
							if(parseFloat(origin_sub_total) >= parseFloat(total_discount)){
								$("#order-items-table tbody").append(discount_item_row);
							}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>
