<!-- BEGIN CONTAINER -->
<div class="page-container">
	<!-- BEGIN CONTENT -->
	<div class="page-content-wrapper">
		<!-- BEGIN CONTENT BODY -->
		<!-- BEGIN PAGE HEAD-->
		<div class="page-head">
			<div class="container-fluid">
				<!-- BEGIN PAGE TITLE -->
				<div class="page-title">
					<h1>Seguimiento de productos </h1>
				</div>
				<!-- END PAGE TITLE -->
			</div>
		</div>
		<!-- END PAGE HEAD-->
		<!-- BEGIN PAGE CONTENT BODY -->
		<div class="page-content">
			<div class="container-fluid">
				<!-- BEGIN PAGE BREADCRUMBS -->
				<ul class="page-breadcrumb breadcrumb">
					<%= render_breadcrumbs :tag => :li, :separator => ' <i class="fa fa-circle"></i> ' %>
				</ul>

				<div class="page-content-inner">
					<div class="row ">
						<div class="portlet light">
							<div class="portlet-title">
								<div class="caption">
									<i class="fa fa-location-arrow font-blue-dark"></i>
									<span class="caption-subject font-blue-dark bold uppercase">Seguimiento de productos</span>
								</div>
							</div>
							<div class="portlet-body form" id="tracking">
								<div class="form-horizontal">
									<div class="row">
										<div class="form-group">
										  <div class="col-md-6 col-sm-12">
										  	<%= label_tag :begin_date, "Fecha", { class: "col-md-2 col-sm-1 control-label" } do %> Desde <% end %>
											  <div class="col-sm-2 col-md-4" style="padding-left:0px;padding-right:0px;">
											    <div class='input-group date' id='begin_date'>
											      <input id="start" type='text' class="form-control" value="<%= l(Date.today.beginning_of_month, format: '%d/%m/%Y') %>" />
											      <span class="input-group-addon">
											        <span class="glyphicon glyphicon-calendar"></span>
											      </span>
											    </div>
											  </div>
											  <%= label_tag :end_date, "Fecha", { class: "col-md-2 col-sm-1 control-label" } do %> Hasta <% end %>
											  <div class="col-sm-2 col-md-4" style="padding-left:0px;padding-right:0px;">
											    <div class='input-group date' id='end_date'>
											      <input id="end" type='text' class="form-control" value="<%= l(Date.today.end_of_month, format: '%d/%m/%Y') %>" />
											      <span class="input-group-addon">
											        <span class="glyphicon glyphicon-calendar"></span>
											      </span>
											    </div>
											  </div>
										  </div>
										</div><!--   -->
										<div class="form-group">
											<div class="col-md-5 col-sm-5">
										  	<label class="col-md-3 col-sm-3 control-label" for="typeahead"> Producto <span class="required">*</span> </label>
												<div class="col-md-9 col-sm-9">
													<input class="form-control" type="text" id="typeahead">
												</div>
										  </div>
											<div class="col-md-6 col-sm-6">
												<%= label_tag :pointsale, "Punto de venta", class: "control-label col-md-3 col-sm-3" %>
												<div class="col-md-6 col-sm-7">
										      <%= select_tag "pointsale", options_from_collection_for_select(Pointsale.vigentes, :id, :name), include_blank: "Todos",  class: "form-control input-medium" %>
										    </div>
										    <button class="btn btn-icon-only blue" onclick="findSalesByPeriod()">
	                        <i class="fa fa-search"></i>
	                      </button>
											</div>
										</div>
									</div>
								</div>
								<div class="product_track_search">
									<div class="row">
									  <div class="col-md-12">
									    <div class="tabbable-custom">
									      <ul class="nav nav-tabs">
									        <li class="active">
									          <a href="#sales_tab" data-toggle="tab" aria-expanded="false">Ventas</a>
									        </li>
									        <li>
									          <a href="#purchases_tab" data-toggle="tab" aria-expanded="false">Compras</a>
									        </li>
									      </ul>
									      <div class="tab-content">
									        <div class="tab-pane active" id="sales_tab">
									          <div class="product_track_search" id='track_detail'>
									            <!-- < %= render "products_track_dtl" %> -->
									          </div>
									        </div>
									        <div class="tab-pane" id="purchases_tab">
									          <div class="product_track_purchases_search" id='track_detail_purchases'>
									            <!-- < %= render "products_track_purchases_dtl" %> -->
									          </div>
									        </div>
									      </div>
									    </div>
									  </div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<!-- END PAGE CONTENT INNER -->
			</div>
		</div>
		<!-- END PAGE CONTENT BODY -->
		<!-- END CONTENT BODY -->
	</div>
	<!-- END CONTENT -->
</div>
<!-- END CONTAINER -->
<script type="text/javascript">
	$(document).on("page:change", function() {
    App.init();
     $('#start').datetimepicker({
      icons: {
        date: "fa fa-calendar"
      },
      format: "DD/MM/YYYY"
    });

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

	var rows_selected = [];
	var selectedProduct = null;
	var timeout = null;
	//para no avanzar cuando la cantidad a regresar sea mayor
	var shouldProcess = false;
	var sale_id = null;

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

	$('#typeahead').bind('typeahead:selected', function(event, datum, name) {
		selectedProduct = datum;
		$('#btn_search_by_period').attr('disabled', false);
	});

	//buscar ventas por periodo de tiempo
	function findSalesByPeriod() {
		var product = selectedProduct ? selectedProduct.id : '';
		var pointsale = $('#pointsale').val();
		var start = moment($("#start").data("date"), "DD-MM-YYYY").startOf('day').format('YYYY-MM-DD HH:mm:ss');
    var end = moment($("#end").data("date"), "DD-MM-YYYY").add(23, 'hours').add(59, 'minutes').add(59, 'seconds').format('YYYY-MM-DD HH:mm:ss');
		$('#product_id').val(product);

		if ($("#start").val() && $("#end").val()) {
			if (product) {
				$.ajax({
					type: "get",
					url: '/product_track/',
					data: {
						start_date: start,
    				end_date: end,
						product_id: product,
						pointsale_id: pointsale
					},
					dataType: 'script',
					success: function(data) {
						App.unblockUI($("#track_detail"));
						App.unblockUI($("#track_detail_purchases"));
					}
				});
			} else {
				toastr["error"]("Es necesario indicar un producto.");
			}
		} else {
			toastr["error"]("Es necesario indicar fechas.");
		}
	}
</script>
