<%= form_for(@purchase, :html => {:class=>"form-horizontal", :id=> "purchase_form"}) do |f| %>
	<div class="portlet-body form">
	<%= hidden_field_tag :tax_percent, @pos_config.tax_percent %>
	<div id="error_explanation"></div>
		<!-- purchase code -->
		<div class="form-group">
			<%= f.label :purchase_code, {:class=>"col-md-2 control-label"} do %> Codigo de compra
			<span class="required">*</span>
			<% end %>
			<div class="col-md-3 input-group">
				<span class="input-group-addon"><i class="fa fa-barcode"></i></span>
				<%= f.text_field :purchase_code, {:class=>"form-control", :readonly => true} %>
			</div>
		</div>
		<!-- fecha -->
		<div class="form-group">
			<%= f.label :purchase_date, {:class=>"col-md-2 control-label"} do %> Fecha
			<span class="required">*</span>
			<% end %>
			<div class="col-md-3 input-group date date-picker">
				<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
				<%= f.date_field :purchase_date, {:value=>Date.today, :class=>"form-control", :readonly => true} %>
			</div>
		</div>
		<!-- tipo de destino -->
		<div class="form-group">
			<%= label_tag 'destiny', {:class=>"col-md-2 control-label"} do %> Destino del producto
			<span class="required">*</span>
			<% end %>
			<div class="col-md-3" style="padding-left:0px;padding-right:0px">
				<%= check_box_tag('destiny', 'warehouse', (@destiny == 'warehouse' ? true : false),
					{
						class: "make-switch",
						disabled: @disable_destiny,
						data: {
							on_color: "success",
							off_color: "warning",
							on_text: "Almacén",
							off_text: "Punto de venta"
						}
					}) %>
			</div>
		</div>
		<!-- punto de venta -->
		<div class= "form-group <%=(@destiny == 'pointsale' ? '' : 'hidden')%>"  id='pointsale_div'>
			<%= f.label :pointsale_id, "Punto de venta", {:class=>"col-md-2 control-label"} do %> Punto de venta
			<span class="required">*</span>
			<% end %>
			<div class="input-group col-md-3 select2-bootstrap-prepend">
				<%= f.collection_select :pointsale_id, Pointsale.activos, :id, :name, {:prompt => "Seleccione"}, {:class => "form-control select2", :disabled => @disable_pointsale} %>
				<%= f.hidden_field :pointsale_id, {:id => 'pointsale'} %>
			</div>
		</div>
		<!-- almacen -->
		<div class= "form-group <%=(@destiny == 'warehouse' ? '' : 'hidden')%>"  id='warehouse_div'>
			<%= f.label :warehouse_id, "Almacén", {:class=>"col-md-2 control-label"} do %> Almacén
			<span class="required">*</span>
			<% end %>
			<div class="input-group col-md-3 select2-bootstrap-prepend">
				<%= f.collection_select :warehouse_id, Warehouse.activos, :id, :name, {:prompt => "Seleccione"}, {:class => "form-control select2", :disabled => @disable_warehouse} %>
				<%= f.hidden_field :warehouse_id, {:id => 'warehouse'} %>
			</div>
		</div>
		<!-- proveedor -->
		<div class="form-group">
			<%= f.label :supplier_id, "Proveedor", {:class=>"col-md-2 control-label"} do %> Proveedor
			<span class="required">*</span>
			<% end %>
			<div class="input-group col-md-3 select2-bootstrap-prepend">
				<%= f.collection_select :supplier_id, Supplier.activos, :id, :nick_name, {:prompt => "Seleccione"}, {:class => "form-control select2", :disabled => @disable_supplier} %>
				<%= f.hidden_field :supplier_id, {:id => 'supplier'} %>
			</div>
		</div>
		<div class="form-group">
			<%= f.label :is_in_dollars, {:class=>"col-md-2 control-label"} do %> tipo de Moneda
				<span class="required">*</span>
			<% end %>
			<div class="col-md-3"  style="padding-left:0px;padding-right:0px">
				<%= f.check_box(:is_in_dollars,
					{
						class: "make-switch",
						disabled: @disable_is_in_dollars,
						data: {
							on_color: "success",
							off_color: "warning",
							on_text: "Dolares",
							off_text: "Pesos"
						}
					},
					"true", "false"
				) %>
			</div>
			<%= f.hidden_field :is_in_dollars, {:id => 'is_in_dollars'} %>
		</div>
		<div class="form-group hidden" id="exchange_div">
			<%= f.label :exchange, {:class=>"col-md-2 control-label"} do %> Tipo de cambio
			<span class="required">*</span>
			<% end %>
			<div class="col-md-3 input-group">
				<span class="input-group-addon"><i class="fa fa-usd"></i></span>
				<%= f.number_field :exchange, {:class=>"form-control", :step=>"any"} %>
			</div>
		</div>
		<!-- boton para resetear datos -->
		<div class="col-md-offset-10 col-md-2">
			<button id="reset_pre_purchases" type="button" class="btn btn-warning" <%= @disabled_button ? 'disabled' : '' %> onclick="deletePrePurchases()">Restaurar compra</button>
		</div>
		<!-- agregar productos -->
		<h4 class="form-section"> Agregar producto</h4>
		<div class="row">
			<div class='col-md-12'>
				<div class="col-md-10">
					<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()"> <i class="fa fa-plus"></i> Agregar </button>
					</div>
				</div>
				<div class="col-md-2">
					<button id="products_add_new" class="btn btn-success" type="button" onclick="addNewProduct()">  <i class="fa fa-plus"></i> Nuevo Producto </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 compra neto</th>
						<th>IVA</th>
						<th>Importe</th>
						<th width="5%">Acciones</th>
					</tr>
				</thead>
				<tbody>
				<%= render @pre_purchases %>
				</tbody>
			</table>
		</div>

		<!-- observaciones y totales-->
		<div class="row">
			<div class="col-md-6">
				<div class="form-group">
					 <%= f.label :observations, "Observaciones", {:class=>"col-md-3 control-label"} %>
					 <div class="col-md-8">
						 <%= f.text_area :observations, {:class=>"form-control", :rows=>5} %>
					 </div>
				 </div>
			 </div>
			<div class="col-md-offset-1 col-md-5">
					<div class="well">
							<div class="row static-info align-reverse">
									<div class="col-md-4 name"> Sub Total: </div>
									<div class="col-md-8 value " id="amount_div">
											<div class="input-group">
												<span class="input-group-addon">$ </span>
												<%= f.text_field :amount, {:class=>"form-control sub_total", :readonly => true, :id => "amount"}  %>
												<span class="input-group-addon"></span>
											</div>
									</div>
							</div>
							<div class="row static-info align-reverse">
									<div class="col-md-4 name"> IVA: </div>
									<div class="col-md-8 value " id="tax_div">
											<div class="input-group">
												<span class="input-group-addon">$ </span>
												<%= f.text_field :tax, {:class=>"form-control descto", :readonly => true, :id => "tax"}  %>
												<span class="input-group-addon"></span>
											</div>
									</div>
							</div>
							<div class="row static-info align-reverse">
									<div class="col-md-4 name"> Total: </div>
									<div class="col-md-8 value " id="total_div">
											<div class="input-group">
												<span class="input-group-addon">$ </span>
												<%= f.text_field :total, {:class=>"form-control descto", :readonly => true, :id => "total"}  %>
												<span class="input-group-addon"></span>
											</div>
									</div>
							</div>
					</div>
			</div>
			<div class="col-md-offset-7 col-md-5 hidden" id="total_in_mxn_div">
					<div class="well">
						<div class="row static-info align-reverse">
								<div class="col-md-4 name"> Total en pesos: </div>
								<div class="col-md-8 value ">
										<div class="input-group">
											<span class="input-group-addon">$ </span>
												<%= text_field_tag :total_in_mxn, '' , :class=>"form-control", :readonly => true %>
											<span class="input-group-addon">MXN</span>
										</div>
								</div>
						</div>
					</div>
			</div>
		</div>
		<!-- acciones del form -->
		<div class="form-actions">
			<div class="row">
				<div class="col-md-offset-2 col-md-9">
					<%= f.submit 'Guardar', {:class=>"btn green"} %>
					<%= link_to 'Cancelar', purchases_path(:filter => @filter, :current_page => @current_page), {:class=>"btn default"} %>
				</div>
			</div>
		</div>
	</div>
<% end %>

<script type="text/javascript">
	var selectedProduct;
	var timeout = null;
	var regex = /[a,e,i,o,u]/gi;

	 $(document).on("page:change", function() {
			App.init();
			calculateTotals();
			generatePurchaseCode();
			enumeratePrePurchases();
			setDestiny($('#destiny').bootstrapSwitch('state'));
			showExchangeField(<%= @purchase.is_in_dollars? %>);

		$('#destiny').on('switchChange.bootstrapSwitch', function(event, state) {
			setDestiny(state);
		});

		$('#purchase_is_in_dollars').on('switchChange.bootstrapSwitch', function(event, state) {
			showExchangeField(state);
			$('#is_in_dollars').val(state);
		});

		$("#new_pre_purchase").bind('ajax:complete', function() {
			calculateTotals();
			$('#purchase_is_in_dollars').bootstrapSwitch('disabled', true);
			$('#destiny').bootstrapSwitch('disabled', true);
		});

		$('#purchase_supplier_id').on('change', function() {
			$(this).attr('disabled', true);
			$('#supplier').val($(this).val());
		});

		$('#purchase_pointsale_id').on('change', function() {
			if( $(this).val() ) {
				$(this).attr('disabled', true);
			} else {
				$(this).attr('disabled', false);
			}
			$('#pointsale').val($(this).val());
			generatePurchaseCode();
		});

		$('#purchase_warehouse_id').on('change', function() {
			if( $(this).val() ) {
				$(this).attr('disabled', true);
			} else {
				$(this).attr('disabled', false);
			}
			$('#warehouse').val($(this).val());
			generatePurchaseCode();
		});

	 });

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

			var bloodhound = new Bloodhound({
				datumTokenizer: function (d) {
					return Bloodhound.tokenizers.whitespace(d.value);
				},
				queryTokenizer: Bloodhound.tokenizers.whitespace,
				remote: {
					url: '/find_products?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 supplier = $('#purchase_supplier_id').val();
			var pointsale = $('#purchase_pointsale_id').val();
			var warehouse = $('#purchase_warehouse_id').val();

			if( (supplier && pointsale) || (supplier && warehouse) ) {
				$('#products_new').attr('disabled', false);
			} else {
				toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
			}

		});

		function addNewProduct() {
			var pointsale = $('#purchase_pointsale_id').val();
			var supplier = $('#purchase_supplier_id').val();
			var warehouse = $('#purchase_warehouse_id').val();
			var exchange = $('#purchase_exchange').val();
			if( (supplier && pointsale) || (supplier && warehouse) ) {
				$.ajax({
					type: "GET",
					url: "/products/new",
					dataType: "script",
					data: {
						remoto: true,
						pointsale: pointsale,
						warehouse: warehouse,
						supplier: supplier,
						exchange: exchange
					},
					success: function(xhr, status, error) {}
				});
			} else {
				toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
			}
		}

		function addRow() {
			if(selectedProduct) {
				$('#pre_purchase_supplier_id').val($('#supplier').val());
				$('#pre_purchase_pointsale_id').val($('#pointsale').val());
				$('#pre_purchase_warehouse_id').val($('#warehouse').val());
				$('#pre_purchase_exchange').val($('#purchase_exchange').val());
				$('#pre_purchase_price_base').val();
				$('#pre_purchase_product_id').val(selectedProduct.id);
				$('#pre_purchase_quantity').val(1);
				$('#pre_purchase_amount').val(selectedProduct.price_sale);
				$('#pre_purchase_tax').val(0);
				$('#pre_purchase_total').val(0);

				$('#new_pre_purchase').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 prePurchaseId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
			$.ajax({
				type: "DELETE",
				url: "/pre_purchases/" + prePurchaseId,
				dataType: "json",
				data: "",
				success: function(xhr, status, error) {
					table.row(input.closest('tr')).remove().draw();
					calculateTotals();
				}
			});
		}

		function updateQuantity(input) {
			if(input.val()) {
				clearTimeout(timeout);
				timeout = setTimeout(function () {
					tax = 0;
					quantity = parseInt(input.val());
					// sacar el precio del producto
					if (input.closest('tr').find('td:eq(5) input').val()) {
						price = parseFloat(input.closest('tr').find('td:eq(5) input').val());
					} else {
						price = 0;
					}
					amount = price * quantity;
					if(input.closest('tr').find('td:eq(0) input').val() == '1') {
						taxPercent = parseFloat($('#tax_percent').val()) / 100
						tax =  (taxPercent  * amount) / (1 + taxPercent);
					}
					input.closest('tr').find('td:eq(6)').text(Math.round(tax * 100) / 100);
					input.closest('tr').find('td:eq(7)').text(Math.round(amount * 100) / 100);
					calculateTotals();

					var idText = input.closest('tr').attr('id');
					var prePurchaseId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);

					$.ajax({
							type: "PUT",
							url: "/pre_purchases/" + prePurchaseId,
							dataType: "json",
							data: {pre_purchase: {quantity: quantity }},
							success: function(xhr, status, error) {
							}
					});
				}, 700);
			}
		}

		function updateProductPrice(input) {
			if(input.val()) {
				clearTimeout(timeout);
				timeout = setTimeout(function () {
					price = parseFloat(input.val());
					var is_in_dollars = $('#purchase_is_in_dollars').bootstrapSwitch('state');
					var exchange = $('#purchase_exchange').val() ? parseFloat($('#purchase_exchange').val()) : '';
					var productId = input.closest('td').find('span').text();
					$.ajax({
							type: "POST",
							url: "/products/" + productId + "/edit_from_purchase",
							dataType: "script",
							data: {product: {price_base: price }, is_in_dollars: is_in_dollars, exchange: exchange},
							success: function(xhr, status, error) {
									//actualizar datos en la tabla
									tax = 0;
									hasTax = input.closest('tr').find('td:eq(0) input').val();
									quantity = parseFloat(input.closest('tr').find('td:eq(4) input').val());
									price = parseFloat(input.closest('tr').find('td:eq(5) input').val());
									amount = price * quantity;
									if(hasTax == '1') {
										taxPercent = parseFloat($('#tax_percent').val()) / 100
										tax =  (taxPercent  * amount) / (1 + taxPercent);
									}
									input.closest('tr').find('td:eq(6)').text(Math.round(tax * 100) / 100);
									input.closest('tr').find('td:eq(7)').text(Math.round(amount * 100) / 100);
									var preIdText = input.closest('tr').attr('id');
									var prePurchaseId = preIdText.substring(preIdText.lastIndexOf('_') + 1, preIdText.length);
									$.ajax({
											type: "PUT",
											url: "/pre_purchases/" + prePurchaseId,
											dataType: "json",
											data: {pre_purchase: {quantity: quantity }},
											success: function(xhr, status, error) {
												calculateTotals();
											}
									});
							}
					});
				}, 600);
			}
		}

		function calculateTotals() {
			var amount = 0;
			var tax    = 0;
			var total  = 0;
			$('#products_table tbody tr td:nth-child(7)').each(function() {
				 tax+= parseFloat($(this).text());
			});
			$('#products_table tbody tr td:nth-child(8)').each(function() {
				 amount+= parseFloat($(this).text());
			});
			amount = amount - tax;
			total = amount + tax;
			$('#tax').val(Math.round(tax * 100) / 100);
			$('#amount').val(Math.round(amount * 100) / 100);
			$('#total').val(Math.round(total * 100) / 100);

			// mostrar el total en pesos cuando es en dolares
			var is_in_dollars = $('#purchase_is_in_dollars').bootstrapSwitch('state');
			if (is_in_dollars) {
				$('#total_in_mxn').val(Math.round((total * $('#purchase_exchange').val()) * 100) / 100);
			}
		}

		function deletePrePurchases() {
			$.ajax({
				type: "get",
				url:  '/delete_pre_purchases',
				dataType: 'json',
				success: function(xhr, status, error){
					$('#products_table').dataTable().fnClearTable();
					$('#purchase_purchase_code').val('');
					$("#purchase_supplier_id").select2().select2("val", null);
					$("#purchase_supplier_id").attr('disabled',false);
					$("#purchase_pointsale_id").select2().select2("val", null);
					$("#purchase_pointsale_id").attr('disabled',false);
					$("#purchase_warehouse_id").select2().select2("val", null);
					$("#purchase_warehouse_id").attr('disabled',false);
					$("#reset_pre_purchases").attr('disabled',true);
					$('#destiny').bootstrapSwitch('disabled',false);
					$('#purchase_is_in_dollars').bootstrapSwitch('disabled', false);
					$('#purchase_is_in_dollars').bootstrapSwitch('state', false);
					calculateTotals();
				}
			});
		}

		function addPurchase() {
			$('#purchase_form').submit();
		}

		function generatePurchaseCode() {
			if($('#purchase_pointsale_id').val()) {
				$.ajax({
					type: "get",
					url:  '/get_max_purchaseid_by_pointsale/' + $('#purchase_pointsale_id').val(),
					dataType: 'text',
					success: function(data) {
						$('#purchase_purchase_code').val(data);
					},
				});
			} else if($('#purchase_warehouse_id').val()) {
				$.ajax({
					type: "get",
					url:  '/get_max_purchaseid_by_warehouse/' + $('#purchase_warehouse_id').val(),
					dataType: 'text',
					success: function(data) {
						$('#purchase_purchase_code').val(data);
					},
				});
			}
		}

		function findProductByBarcode(barcode) {
			var supplier = $('#purchase_supplier_id').val();
			var pointsale = $('#purchase_pointsale_id').val();
			var warehouse = $('#purchase_warehouse_id').val();

			if (pointsale) {
				url = '/add_pre_purchase_by_barcode_pointsale/' + barcode + "/" + supplier + "/" + pointsale;
			} else {
				url = '/add_pre_purchase_by_barcode_warehouse/' + barcode + "/" + supplier + "/" + warehouse;
			}
			if((supplier && pointsale) || (supplier && warehouse)) {
				$.ajax({
					type: "get",
					url:  url,
					dataType: 'script',
					success: function(data) {
						calculateTotals();
					},
				});
			} else {
				toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
			}
		}

		function enumeratePrePurchases() {
			if($('#reset_pre_purchases').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 setDestiny(state) {
			// true es almacen| false es punto de venta
			$('#purchase_purchase_code').val('');
			if (state) {
				$('#warehouse_div').removeClass('hidden');
				$("#purchase_warehouse_id").select2();
				$('#pointsale_div').addClass('hidden');
				<% if current_user.usertype == 'A' %>
					$('#purchase_pointsale_id').select2('val', null);
				<% end %>
			} else {
				$('#pointsale_div').removeClass('hidden');
				$("#purchase_pointsale_id").select2();
				$('#warehouse_div').addClass('hidden');
				<% if current_user.usertype == 'A' %>
					$('#purchase_warehouse_id').select2('val', null);
				<% end %>
			}
		}

		function showExchangeField(state) {
			// true es dolares | false es pesos
			if (state) {
				$('#exchange_div').removeClass('hidden');
				$('#amount_div div span:last-child').html('USD');
				$('#tax_div div span:last-child').html('USD');
				$('#total_div div span:last-child').html('USD');
				$("#total_in_mxn_div").removeClass('hidden');
			} else {
				$('#exchange_div').addClass('hidden');
				$('#purchase_exchange').val('');
				$('#amount_div div span:last-child').html('MXN');
				$('#tax_div div span:last-child').html('MXN');
				$('#total_div div span:last-child').html('MXN');
				$("#total_in_mxn_div").addClass('hidden');
			}
		}
</script>



