<%= form_for(@promotion, html: { class: "form-horizontal", id: "promotion_form" }) do |f| %>
  <div class="portlet-body form">
    <% if @promotion.errors.any? %>
      <div class="alert alert-danger">
        <strong>Tiene <%= pluralize(@promotion.errors.count, "error") %> no se puede guardar la promoción</strong><br>
        <% @promotion.errors.values.each do |message| %>
          <%= message.first.to_s %><br>
           <!--  $("#error_explanation_move").append($("<li />").html("< %= message.first.to_s %>")); -->
        <% end %>
      </div>
    <% end %>
    <div class="form-body">
      <div class="alert alert-danger hidden" id="error_explanation_for_promotion"></div>
      <div class="row">
        <div class="col-md-12">
          <!-- fechas -->
          <div class="form-group">
            <%= label_tag :begin_date, "Fecha", { class: "col-md-1 control-label" } do %> Del
              <span class="required">*</span>
            <% end %>
            <div class="col-sm-2">
              <div class='input-group date' id='begin_date'>
                <!-- <input id="start" type='text' class="form-control"/> -->
                <%= f.text_field :start_date, { id: 'start', class: 'form-control' } %>
                <span class="input-group-addon">
                  <span class="glyphicon glyphicon-calendar"></span>
                </span>
                <!-- < %= f.hidden_field :start_date, {id: 'start_date_input'} %> -->
              </div>
            </div>
            <%= label_tag :end_date, "Fecha", { class: "col-md-1 control-label" } do %> Al
              <span class="required">*</span>
            <% end %>
            <div class="col-sm-2">
              <div class='input-group date' id='end_date'>
                <!-- <input id="end" type='text' class="form-control"/> -->
                <%= f.text_field :end_date, { id: 'end', class: 'form-control' } %>
                <span class="input-group-addon">
                  <span class="glyphicon glyphicon-calendar"></span>
                </span>
                <!-- < %= f.hidden_field :end_date, {id: 'end_date_input'} %> -->
              </div>
            </div>
          </div>
          <!-- filtro -->
          <div class="form-group">
            <div class="col-md-8" style="padding-top:5px">
              <div class="radio-list">
                <label class="radio-inline" style="margin-left:10px">
                  <input type="radio" name="filter" id="category" value="category">Todos los productos de una línea
                </label>
                <label class="radio-inline" style="margin-left:37px">
                  <input type="radio" name="filter" id="products" value="products" checked>Producto específico
                </label>
              </div>
            </div>
          </div>
          <div class="form-group">
            <%= f.label :percent, "", { class: "col-md-2 control-label" } do %> Porcentaje de descuento <span class="required">*</span> <% end %>
            <div class="col-md-1">
              <div class="input-group">
                <%= f.text_field :percent, { class: "form-control mask_decimal input-xsmall", value: 1 } %>
                <span class="input-group-addon"> % </span>
              </div>
            </div>
          </div>
          <div class="form-group" id="variants_div">
            <%= label_tag :variants, "", { class: "col-md-3 control-label" } do %> ¿Buscar por variantes? <span class="required">*</span> <% end %>
            <div class="col-md-3">
              <%= check_box_tag(:include_variants, true, true, {
                class: "make-switch",
                  data: {
                    on_color: "success",
                    off_color: "danger",
                    on_text: "Si",
                    off_text: "No"
                  }
                }) %>
            </div>
          </div>
          <div class="form-group">
            <div class="well col-md-6">
              <!-- linea -->
              <div class="form-group hidden" id="category_div">
                <%= f.label :category_id, "", { class: "col-md-3 control-label" } do %> Línea de productos
                  <span class="required">*</span>
                <% end %>
                <div class="col-md-8 select2-bootstrap-prepend">
                  <%= f.collection_select(:category_id, Category.activos_padre, :id, :category, {}, class: "form-control select2") %>
                  <span class="help-block">Se agregarán todos los productos de la línea a la tabla.</span>
                </div>
              </div>
              <div class="form-group hidden" id="subcategory_div">
                <%= f.label :subcategory_id, "Sublínea", { class: "col-md-3 col-sm-3 control-label" } %>
                <div class="col-md-8 select2-bootstrap-prepend col-sm-4">
                  <%= f.collection_select(:subcategory_id, {}, :id, :category, {}, class: "form-control select2") %>
                </div>
              </div>
              <!-- producto -->
              <div class="form-group" id="products_div">
                <label class="control-label col-md-3" for="typeahead"> Producto
                  <span class="required">*</span>
                </label>
                <div class="input-groupll col-md-8">
                  <input class="form-control" type="text" id="typeahead" data-option-url="/find_products/%QUERY/VAR">
                  <span class="help-block">Se puede buscar por No. de parte o Nombre de producto </span>
                  <%= f.hidden_field :product_id, { id: 'product_input' } %>
                  <br>
                  <span id="product_name"><% if @promotion.product.present? %><i>Producto seleccionado: <%= @promotion.product.display_sku_name_attributes %></i><% end %></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  <!-- acciones del form -->
    <div class="form-actions">
      <div class="row">
        <div class="col-md-9">
          <!-- < %= f.submit 'Guardar', { class: "btn green" } %> -->
          <button type="button" class="btn green" onclick="addPromotion()" id="submit_promotion">Guardar</button>
          <%= link_to 'Cancelar', promotions_path, { class: "btn default" } %>
        </div>
      </div>
    </div>
  </div>
<% end %>

<script type="text/javascript">
  var selectedProduct;
  // inicialmente dejar en blanco los selects
  $(document).on("page:change", function() {
    <% unless @filter.present? && @filter == "category" %>
      $("#promotion_category_id").select2("val", "");
      $("#promotion_subcategory_id").select2("val", "");
    <% end %>
  });

  $('input[name="include_variants"]').on('switchChange.bootstrapSwitch', function(event, state) {
    $(this).val(state);
  });

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

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

  var bloodhound = new Bloodhound({
    datumTokenizer: function (d) {
      return Bloodhound.tokenizers.whitespace(d.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: $('#typeahead').data('option-url'),
      wildcard: '%QUERY',
      replace: function(url, uriEncodedQuery) {
        variants = $("#include_variants").val();
        return url.replace('VAR', variants).replace('%QUERY', uriEncodedQuery)
      }
    }
  });
  bloodhound.initialize();

  $('#typeahead').typeahead(
    {
      minLength: 3
    },
    {
      displayKey: 'name',
      source: bloodhound.ttAdapter(),
      limit: Infinity,
      templates: {
        empty: [
          '<div class="empty-message">',
            'No se encontró ningún producto. Favor de verificar',
          '</div>'
        ].join('\n'),
        suggestion: function(data) {
          return '<div class="media">' +
                  '<div class="pull-left">' +
                    '<div class="media-object">' +
                      '<img src="'+ data.small_img +'" width="50" height="50"/>' +
                    '</div>' +
                  '</div>' +
                  '<div class="media-body">' +
                    '<h4 class="media-heading"><strong>'+ data.sku +'</strong> | '+ data.name +'</h4>' +
                    '<p>'+ data.barcode +'</p>' +
                    '<p>'+ data.description +'</p>' +
                    '<p>'+ data.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) {
    console.log(selectedProduct)
    selectedProduct = datum;
    $('#product_input').val(selectedProduct.id);
    $("#product_name").html("<i>Producto seleccionado: "+selectedProduct.display_sku_name_attributes+"</i>")
  });

  $('input[type=radio][name=filter]').change(function() {
    switch(this.value) {
      case 'category':
        $('#category_div').removeClass('hidden');
        $("#subcategory_div").removeClass("hidden");
        $('#products_div').addClass('hidden');
        $("#variants_div").addClass('hidden');

        $('#product_input').val('');
        break;
      case 'products':
        $('#category_div').addClass('hidden');
        $("#subcategory_div").addClass("hidden");
        $('#products_div').removeClass('hidden');
        $("#variants_div").removeClass('hidden');

        $("#promotion_category_id").select2("val", "");
        break;
    }
    $('.select2').select2();
  });

  $('#promotion_category_id').on('change', function() {
    if($(this).val()) {
      $.ajax({
        type: "get",
        url: '/getcategories/' + $(this).val(),
        dataType: 'json',
        success: function(data) {
          $('#promotion_subcategory_id').empty();
          if(data.length > 0) {
            $('#promotion_subcategory_id').attr('disabled', false);
            $('#promotion_subcategory_id').append("<option selected value='0'>Seleccione</option>")
          } else {
            $('#promotion_subcategory_id').attr('disabled', true);
          }
          for(i in data){
            $('#promotion_subcategory_id').append("<option value='" + data[i].id +"'>" + data[i].category + "</option>")
          }
        }
      });
    }
  });

  function addPromotion() {
    $('#promotion_form').submit();
  }
</script>
