<%= form_for(@sale, :remote => true, :html => {:class=>"form-horizontal", :id=> "sale_form"}) do |f| %>
	<div class="portlet-body form">
		<!-- este error explanation se usa para mostrar errores de presales e inventarios -->
		<!-- <div id="error_explanation"></div> -->
		<!-- este error explanation es cuando falla alguna validacion de la venta en sí -->
		<div class="alert alert-danger hidden" id="error_explanation_for_sale"></div>
		<div class="row">
			<!-- cuando no hay caja abierta -->
			<% if @opened_cash_registers.blank? %>
				<div class="alert alert-block alert-danger fade in">
	        <h4 class="alert-heading">¡AVISO! no hay caja abierta</h4>
	        <p> Para realizar una venta es necesario abrir una caja registradora. </p>
	        <p>
	        	<%= link_to "Abrir caja", new_open_cash_register_path, :remote => true, :class => 'btn btn-primary' %>
	        </p>
	      </div>
			<% end %>
			<!-- boton para resetear datos -->
			<div class="col-md-offset-10 col-md-2">
				<button id="reset_pre_sales" type="button" class="btn btn-warning" <%= @disabled_button ? 'disabled' : '' %> onclick="deletePreSales()">Restaurar venta</button>
			</div>
			<div class="col-md-8">
				<h4 class="form-section"> Datos generales</h4>
				<!-- purchase code -->
				<div class="form-group">
					<%= f.label :sale_code, {:class=>"col-md-3 control-label"} do %> Código de compra
					<span class="required">*</span>
					<% end %>
					<div class="col-md-6 input-group">
						<span class="input-group-addon"><i class="fa fa-barcode"></i></span>
						<%= f.text_field :sale_code, {:class=>"form-control", :readonly => true} %>
					</div>
				</div>
				<!-- fecha -->
				<div class="form-group">
					<%= hidden_field_tag :tax_percent, @pos_config.tax_percent %>
					<%= f.label :date_sale, "Fecha", {:class=>"col-md-3 control-label"} do %> Fecha
					<span class="required">*</span>
					<% end %>
					<%= f.hidden_field :date_sale, {:value=>Date.today} %>
					<div class="col-sm-6" style="padding-left:0px;padding-right:0px;">
						<div class='input-group date' id='datetimepicker1'>
							<span class="input-group-addon">
								<span class="glyphicon glyphicon-calendar"></span>
							</span>
							<input type='text' class="form-control" disabled/>
						</div>
					</div>
				</div>
				<!-- open cash register -->
			<!-- 	< % if current_user.usertype == 'C' %>
					< %= f.hidden_field :open_cash_register_id, :value => @open_cash_register.id %>
				< % end %> -->
				<div class="form-group">
					<%= f.label :open_cash_register_id, "Caja registradora", {:class=>"col-md-3 control-label"} do %> Caja registradora
					<span class="required">*</span>
					<% end %>
					<div class="input-group col-md-6 select2-bootstrap-prepend">
						<% if @sale.open_cash_register.nil? %>
							<%= f.select :open_cash_register_id, Pointsale.find(current_user.pointsale_id).open_cash_registers.abiertas.map { |o| [o.cash_register.name, o.id] }, {:prompt => "Seleccione"}, { :class => 'form-control select2', :disabled => @disabled_select } %>
						<% else %>
              <%= f.select :open_cash_register_id, @opened_cash_registers.map{|o| [o.cash_register.name, o.id]}, {:include_blank => "Seleccione", :selected => @sale.open_cash_register.id}, {:class => "form-control", :disabled => true } %>
						<% end %>
						<%= f.hidden_field :open_cash_register_id, { :id => 'open_cash' } %>
					</div>
				</div>
				<!-- cliente -->
				<div class="form-group">
					<%= f.label :customer_id, "Cliente", {:class=>"col-md-3 control-label"} do %> Cliente
					<span class="required">*</span>
					<% end %>
					<div class="input-group col-md-6 select2-bootstrap-prepend" style="float:left">
						<%= f.collection_select :customer_id, Customer.vigentes, :id, :nick_name, { :prompt => "Seleccione", :selected => @sale.customer_id.present? ? @sale.customer_id : @general_public_id}, { :class => "form-control select2" } %>
						<%= f.hidden_field :customer_id, :value => @sale.customer_id.present? ? @sale.customer_id : @general_public_id, :id => 'customer' %>
					</div>
					<div class="col-md-2">
						<% if @pre_sales.count == 0 %>
							<%= link_to new_customer_path, remote: true, class: "btn btn-success", id: :customer_remote do %>
								<i class="fa fa-plus"></i>
							<% end %>
						<% end %>
					</div>
				</div>
				<!-- tipo de venta -->
				<div class="form-group">
					<%= f.label :saletype, {:class=>"col-md-3 control-label"} do %> ¿Tipo de venta?
						<span class="required">*</span><% end %>
					<div class="btn-group col-md-6" data-toggle="buttons" style="padding-left:0px;padding-right:0px">
							<label class="col-md-4 btn default <%= @sale.saletype == 'cash' ? 'active' : (@enable_radios ? '' : 'disabled') %>">
								<%= radio_button_tag 'types', "cash", (@sale.saletype == 'cash'), class: "toggle" %> Contado
							</label>
							<label class="col-md-4 btn default <%= @sale.saletype == 'credit' ? 'active' : (@enable_radios ? '' : 'disabled') %>">
								<%= radio_button_tag 'types', "credit", (@sale.saletype == 'credit'), class: "toggle" %> Crédito
							</label>
							<label class="col-md-4 btn default <%= @sale.saletype == 'reserved' ? 'active' : (@enable_radios ? '' : 'disabled') %>">
								 <%= radio_button_tag 'types', "reserved", (@sale.saletype == 'reserved'), class: "toggle" %> Apartado
							</label>
							<%= f.hidden_field :saletype %>
					</div>
				</div>
				<!-- vale -->
				<div class="form-group hidden" id="credit_note_div">
					<%= f.label :credit_note, {:class=>"col-md-3 control-label"} do %> Folio de vale <% end %>
					<div class="col-md-6 input-group">
						<span class="input-group-addon"><i class="fa fa-ticket"></i></span>
						<%= f.text_field :credit_note, {:class=>"form-control"} %>
					</div>
				</div>
				<!-- vendedor -->
				<div class="form-group">
					<%= f.label :seller_id, "Vendedor", {:class=>"col-md-3 control-label"} do %> Vendedor
					<span class="required">*</span>
					<% end %>
					<div class="input-group col-md-6 select2-bootstrap-prepend">
						<%= f.collection_select :seller_id, Seller.where(:pointsale_id => current_user.pointsale_id, :status => '1'), :id, :full_name, {:prompt => "Seleccione",
							:selected => @seller.blank? ? '' : @seller_id.to_i}, {:class => "form-control select2"} %>
					</div>
				</div>
			</div>
			<div class="col-md-4 hidden" id="customer_info">
			 <h4 class="form-section"> Datos del cliente</h4>
				<div class="panel panel-info">
					<!-- Default panel contents -->
					<div class="panel-heading">
						<h3 class="panel-title" id="customer_name"></h3>
					</div>
					<!-- List group -->
					<ul class="list-group">
						<li class="list-group-item"> ¿Tiene crédito?
							<span class="badge badge-info badge-roundless" id="has_credit"></span>
						</li>
						<li class="list-group-item"> Adeudo del cliente
							<span class="badge badge-info badge-roundless" id="customer_debiting"></span>
						</li>
						<%= hidden_field_tag :available_credit, 0 %>
						<li class="list-group-item"> Límite de crédito
							<span class="badge badge-info badge-roundless" id="credit_limit"></span>
						</li>
						<li class="list-group-item"> Fecha de último abono
							<span class="badge badge-info badge-roundless" id="last_credit_payment"></span>
						</li>
					</ul>
				</div>
				<div class="from-group">
					<div id="error_explanation"></div>
				</div>
			</div>
		</div>

		<!-- agregar productos -->
		<h4 class="form-section"> Agregar producto</h4>
		<div class="row">
			<div class="col-md-12">
				<div class="note note-info">
					<h4 class="block">¡Nota!</h4>
					<p>
						Para hacer una búsqueda avanzada utiliza el siguiente formato: <br>
						Nombre del producto:(inicial del atributo a buscar)atributo a buscar<br>
						Ejemplo: <strong>Blusa:cverde:tch:elargo</strong> (Donde C es Color, T es Talla y E es Estilo, pueden tener cualquier orden, siempre y cuando tenga ese formato)
					</p>
				</div>
			</div>
			<div class='col-md-12'>
				<div class="form-group">
					<label class="col-md-2 control-label" for="typeahead"> Producto
						<span class="required">*</span>
					</label>
					<div class="col-md-4">
					<!-- -->
						<input class="form-control" type="text" id="typeahead">
					</div>
					<button id="products_new" disabled class="btn btn-success" type="button" onclick="addRow()"> Agregar <i class="fa fa-plus"></i> </button>
				</div>
			</div>
		</div>

		<!-- lista de productos -->
		<h4 class="form-section"> Lista de productos</h4>
		<div class="portlet-body">
			<table class="table table-striped table-bordered table-hover tableadvanced" id="products_table">
				<thead>
					<tr>
						<th>#</th>
						<th>SKU</th>
						<th>Imagen</th>
						<th>Producto</th>
						<th>Cantidad</th>
						<th>Precio unitario</th>
						<th>IVA</th>
						<th>Descuento</th>
						<th>Importe</th>
						<th width="15%">Acciones</th>
					</tr>
				</thead>
				<tbody>
				<%= render @pre_sales %>
				</tbody>
			</table>
		</div>

		<!-- totales -->
		<div class="row">
			<div class="col-md-offset-8 col-md-4">
					<div class="well">
							<div class="row static-info align-reverse">
									<div class="col-md-6 name"> Sub Total: </div>
									<div class="col-md-6 value ">
											<div class="input-group">
													<span class="input-group-addon">$ </span>
													 <%= f.text_field :amount, {:class=>"form-control sub_total", :readonly => true, :id => "amount"}  %>
											</div>
									</div>
							</div>
							<div class="row static-info align-reverse">
									<div class="col-md-6 name"> Descuento: </div>
									<div class="col-md-6 value ">
											<div class="input-group">
													<span class="input-group-addon">$ </span>
													 <%= f.text_field :discount, {:class=>"form-control sub_total", :readonly => true, :id => "discount"}  %>
											</div>
									</div>
							</div>
							<div class="row static-info align-reverse">
									<div class="col-md-6 name"> IVA: </div>
									<div class="col-md-6 value ">
											<div class="input-group">
													<span class="input-group-addon">$ </span>
													<%= f.text_field :tax, {:class=>"form-control descto", :readonly => true, :id => "tax"}  %>
											</div>
									</div>
							</div>
							<div class="row static-info align-reverse">
									<div class="col-md-6 name"> Total: </div>
									<div class="col-md-6 value ">
											<div class="input-group">
													<span class="input-group-addon">$ </span>
													<%= f.text_field :total, {:class=>"form-control descto", :readonly => true, :id => "total"}  %>
											</div>
									</div>
							</div>
					</div>
			</div>
		</div>

		<!-- acciones del form -->
		<div class="form-actions">
			<div class="row">
				<div class="col-md-9">
					<button type="button" class="btn green" onclick="addSale()" id="save_sale">Guardar venta</button>
					<%= link_to 'Cancelar', sales_path(:filter => @filter, :current_page => @current_page), {:class=>"btn default"} %>
				</div>
			</div>
		</div>
	</div>
<% end %>

<script type="text/javascript">
	var selectedProduct;
	var timeout = null;

	$(document).on("page:change", function() {
		App.init();
		calculateTotals();
		fillCustomerInfo();
		enumeratePreSales();
		generateSaleCode();

		// si es publico en general, desactivar venta a credito y apartado
		if ($('#sale_customer_id').val() == '<%= @general_public_id %>') {
			$('#types_credit').attr('disabled', true);
			$('#types_credit').closest('label').addClass('disabled');
			$('#types_reserved').attr('disabled', true);
			$('#types_reserved').closest('label').addClass('disabled');
		}

		$('#datetimepicker1').datetimepicker({
			icons: {
				date: "fa fa-calendar"
			},
			format: "DD/MM/YYYY",
			defaultDate: new Date()
		});

		$("#new_pre_sale").bind('ajax:complete', function() {
			calculateTotals();
		});

		$('form#sale_form').bind('ajax:complete', function() {
			$('#save_sale').attr('disabled', false);
		});

		$('#sale_open_cash_register_id').on('change', function() {
			$(this).attr('disabled', true);
			$('#open_cash').val($(this).val());
			generateSaleCode();
		});

		$('input:radio[name=types]').change(function() {
			if (!$(this).closest('label').hasClass('disabled')) {
				<% if @pre_sales.count == 0 %>
					if (!$(this).closest('label').hasClass('disabled')) {
						$('#sale_saletype').val($(this).val());
					} else {
						var type = $('#sale_saletype').val();
						$(":radio[value=" + type + "]").closest('label').addClass('active');
					}
				<% else %>
					var type  = '<%= @sale.saletype %>';
					$(":radio[value=" + type + "]").closest('label').addClass('active');
				<% end %>
				//Si es tipo crédito, aparecer input de vale
				if ($(this).val() == 'credit') {
					$('#credit_note_div').removeClass('hidden');
				} else {
					$('#credit_note_div').addClass('hidden');
					$('#sale_credit_note').val('');
				}
			}
		});

		$(document).on("keydown", function (e) {
			if (window.location.pathname == "/sales/new") {
				if (e.which === 8 && !$(e.target).is("input, textarea")) {
					e.preventDefault();
				}
			}
		});
	});

	$('#sale_customer_id').on('change', function() {
		// $(this).attr('disabled', true);
		$('#customer').val($(this).val());

		//bloquear boton para agregar nuevo cliente ya que se selecciono o agrego uno
		$('#customer_remote').remove();
		// $('#customer_remote').attr("disabled", true);

		// activar apartado y el credito se activa dependiendo si tiene o no,
		// en la funcion fillCustomer
		if ($('#sale_customer_id').val() != '<%= @general_public_id %>') {
			$('#types_reserved').attr('disabled', false);
			$('#types_reserved').closest('label').removeClass('disabled');
		}
		updatePreSale($(this).val());
	});

	$('#types_cash, #types_credit, #types_reserved').on('change', function() {
		$("#sale_saletype").val($(this).val());
		if($(this).val() == "cash"){
			$("#save_sale").attr("disabled", false);
		}
		$.ajax({
      type: "PUT",
      url: "/update_saletype/" + $(this).val(),
      dataType: "json",
      success: function(xhr, status, error) {
        toastr["warning"]("Se actualizó el tipo de venta");
      },
			error: function (xhr, status, errorThrown) {
				toastr["error"](xhr.responseText.substr(3, (xhr.responseText.length -6)));
			}
    });
	});

	function updatePreSale(customer_id) {
		$.ajax({
      type: "PUT",
      url: "/update_presale_customer/" + customer_id,
      dataType: "json",
      success: function(xhr, status, error) {
        toastr["warning"]("Se actualizó el cliente de venta");
        fillCustomerInfo();
      }
    });
	}

	$('body').barcodeListener().on('barcode.valid', function(e, code) {
		findProductByBarcode(code);
	});

	// initialize bloodhound engine
	var bloodhound = new Bloodhound({
		datumTokenizer: function (d) {
			return Bloodhound.tokenizers.whitespace(d.value);
		},
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		remote: {
			url: '/find_products_from_stock?query=%QUERY',
			wildcard: '%QUERY'
		}
	});
	bloodhound.initialize();


	$('#typeahead').typeahead(
		{
			minLength: 3
		},
		{
			displayKey: 'name',
			source: bloodhound.ttAdapter(),
			limit: Infinity,
			templates: {
				empty: [
					'<div class="empty-message">',
						'No se encontró ningun producto. Favor de verificar',
					'</div>'
				].join('\n'),
				 suggestion: Handlebars.compile(
						'<div class="media">' +
							'<div class="pull-left">' +
									'<div class="media-object">' +
											'<img src="{{small_img}}" width="50" height="50"/>' +
									'</div>' +
							'</div>' +
							'<div class="media-body">' +
									'<h4 class="media-heading"><strong>{{sku}}</strong> | {{name}}</h4>' +
									'<p>{{barcode}}</p>' +
									'<p>{{description}}</p>' +
									'<p>{{display_attributes}}</p>' +
							'</div>' +
						'</div>')
			}
	});

	// this is the event that is fired when a user clicks on a suggestion
	$('#typeahead').bind('typeahead:selected', function(event, datum, name) {
		selectedProduct = datum;

		var openCash = $('#sale_open_cash_register_id').val();
		var customer = $('#sale_customer_id').val();
		var saleType = $('#sale_saletype').val();
		var seller = $('#sale_seller_id').val();

		if (openCash && customer && saleType && seller ) {
			$('#products_new').attr('disabled', false);
		} else {
			toastr["error"]("No ha ingresado toda la información requerida.");
		}
	});

	function addRow() {
		if(selectedProduct) {
			$('#pre_sale_customer_id').val($('#sale_customer_id').val());
			$('#pre_sale_open_cash_register_id').val($('#sale_open_cash_register_id').val());
			$('#pre_sale_sale_type').val($('#sale_saletype').val());
			$('#pre_sale_product_id').val(selectedProduct.id);
			$('#pre_sale_quantity').val(1);
			$('#new_pre_sale').submit();
			$('#typeahead').typeahead('val','');
			$('#products_new').attr('disabled', true);
		}
	}

	function deleteRow(input) {
		var table = $('#products_table').DataTable();
		var idText = input.closest('tr').attr('id');
		var preSaleId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
		$.ajax({
			type: "DELETE",
			url: "/pre_sales/" + preSaleId,
			dataType: "json",
			data: "",
			success: function(xhr, status, error) {
				table.row(input.closest('tr')).remove().draw();
				calculateTotals();
			}
		});
	}

	function calculatePrice(input) {
		if(input.val()) {
			clearTimeout(timeout);
			timeout = setTimeout(function () {
				tax = 0;
				quantity = parseInt(input.val());

				var idText = input.closest('tr').attr('id');
				var preSaleId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
				$('#save_sale').attr('disabled', true);
				$.ajax({
						type: "PUT",
						url: "/pre_sales/" + preSaleId,
						dataType: "json",
						data: { pre_sale: { quantity: input.val() } },
						success: function(xhr, status, error) {

							input.closest('tr').find('td:eq(6)').text(Math.round(xhr.tax * 100) / 100);

							input.closest('tr').find('td:eq(7)').text(Math.round(xhr.discount * 100) / 100);

							input.closest('tr').find('td:eq(8)').text(Math.round(xhr.total * 100) / 100);

							calculateTotals();

							$('#save_sale').attr('disabled', false);
						},
						error: function (xhr, status, errorThrown) {
							input.val(1);
							toastr["error"](xhr.responseText.substr(3, (xhr.responseText.length -6)));
						}
				});
			}, 500);
		}
	}

	function calculateTotals() {
		var amount = 0;
		var discount = 0;
		var tax = 0;
		var total = 0;

		if($('#products_table').dataTable().fnGetData().length > 0) {
			$('#products_table tbody tr').each(function() {
				quantity = parseFloat(($(this).find('td:nth-child(5) input').val()));
				price = parseFloat($(this).find('td:nth-child(6)').text());
				amount += (quantity * price);
			});
		}

		$('#products_table tbody tr td:nth-child(7)').each(function() {
			tax += parseFloat($(this).text());
		});
		$('#products_table tbody tr td:nth-child(8)').each(function() {
			discount += parseFloat($(this).text());
		});

		total = (amount - discount) + tax;
		$('#tax').val(Math.round(tax * 100) / 100);
		$('#discount').val(Math.round(discount * 100) / 100);
		$('#amount').val(Math.round(amount * 100) / 100);
		$('#total').val(Math.round(total * 100) / 100);
		if(total < parseFloat($("#available_credit").val())) {
			$('#types_credit').attr('disabled', false);
			$('#types_credit').closest('label').removeClass('disabled');
		}
	}

	function deletePreSales() {
		$.ajax({
			type: "get",
			url: '/delete_pre_sales',
			dataType: 'json',
			success: function(xhr, status, error) {
				location.reload();
			}
		});
	}

	function addSale() {
		var $form = $('#sale_form');
		var table = $('#products_table').dataTable();

		if ($form[0].checkValidity()) {
			if(table.fnGetData().length > 0) {
				$('#sale_form').submit();
				$('#save_sale').attr('disabled', true);
			} else {
				toastr["error"]("Error, Se debe agregar al menos un producto.");
			}
		} else {
			toastr["error"]("La cantidad de los productos debe de ser mayor o igual a 1.");
		}
	}

	function fillCustomerInfo() {
		var customerId = $('#customer').val();
		var public_customer = "<%= @general_public_id %>";
		if(customerId) {
			$.ajax({
				type: "get",
				url: '/customers/' + customerId + ".json",
				dataType: 'json',
				success: function(data) {
					if(data.credit) {
						$('#customer_name').text(data.nick_name);
						$('#has_credit').text(data.credit ? 'SI' : 'NO');
						// $('#customer_debiting').text(formatter.format(data.customer_debiting.customer_debiting));
						// $('#credit_limit').text(formatter.format(data.credit_limit));
						$('#customer_debiting').text(accounting.formatMoney(data.customer_debiting.customer_debiting));
						$('#credit_limit').text(accounting.formatMoney(data.credit_limit));
						if(data.customer_payment) {
							$('#last_credit_payment').text(data.customer_payment.customer_payment);
						}
						$('#customer_info').removeClass('hidden');
						$("#available_credit").val(data.available_credit.available_credit)
						if(parseInt($("#total").val()) > parseInt(data.available_credit.available_credit)) {
							$('#types_cash').click();
							$('#types_credit').attr('disabled', true);
							$('#types_credit').closest('label').addClass('disabled');
						} else {
							$('#types_credit').attr('disabled', false);
							$('#types_credit').closest('label').removeClass('disabled');
						}
					} else {
						// DISABLEAR EL DE CREDITO
						$("#customer_info").addClass("hidden");
						$('#types_cash').click();
						$('#types_credit').attr('disabled', true);
						$('#types_credit').closest('label').addClass('disabled');
					}
				}
			});
		}
	}

	function enumeratePreSales() {
		if($('#reset_pre_sales').prop("disabled") == false) {
			var table = $('#products_table').dataTable();
			var counter = 1;
			$('#products_table tbody tr').each(function() {
				$(this).find('td:eq(0)').html($(this).find('td:eq(0)').html().replace('#', counter));
				counter++;
			});
		}
	}

	function generateSaleCode() {
		if($('#sale_open_cash_register_id').val()) {
			$.ajax({
				type: "get",
				url: '/get_next_sale_code/' + $('#sale_open_cash_register_id').val(),
				dataType: 'text',
				success: function(data) {
					$('#sale_sale_code').val(data);
				},
			});
		}
	}

	function findProductByBarcode(barcode) {
		var customer = $('#sale_customer_id').val();
		var openCash = $('#sale_open_cash_register_id').val();
		var saleType = $('form input[type=radio]:checked').val();
		var seller = $('#sale_seller_id').val();
		if(customer && openCash && saleType && seller) {
			$.ajax({
				type: "get",
				url: '/add_pre_sale_by_barcode/' + barcode + "/" + customer + "/" + openCash + "/" + saleType,
				dataType: 'script',
				success: function(data) {
					calculateTotals();
				},
			});
		} else {
			toastr["error"]("Falta seleccionar datos del formulario.");
		}
	}
</script>
