<%= form_for(AvailableProduct.new, :html => {:class=>"form-horizontal", :id=> "available_products_form"}) do |f| %>
  <div class="portlet-body form">
    <div id="error_explanation"></div>

      <table class="table table-striped table-bordered table-hover stock-table" id="pointsale_stock" data-source="<%= @showcolumns == 'initial' ?  products_initial_stock_path(@location_id, :format => 'json') : products_stock_path(@location_id, :format => 'json') %>">
        <thead>
          <tr>
            <th class="text-center"><input name="select_all" value="1" id="select-all" type="checkbox" /></th>
            <th>Imagen</th>
            <th>SKU</th>
            <th>Producto</th>
            <th>Línea</th>
            <th>Sublínea</th>
            <% case @showcolumns
              when "initial" %>
                <th>Stock inicial</th>
            <% when "minMax" %>
                <th>Stock mínimo</th>
                <th>Stock máximo</th>
            <% end %>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
  </div>
<% end %>

<script type="text/javascript">
  var rows_selected = [];
  var tableClass = '.stock-table';
  var columns = "<%= @column_definition %>";
  var tableColumns = JSON.parse(columns.replace(/&quot;/g,'"'));
  var order = 3;
  var extraData = {};

  tableWithCheckboxAjax.init(tableClass, tableColumns, order, extraData, rows_selected);

// $(document).on("page:change", function() {
//   App.init();
// });

toastr.options = {
  "closeButton": false,
  "debug": false,
  "positionClass": "toast-bottom-right",
  "onclick": null,
  "showDuration": "1000",
  "hideDuration": "1000",
  "timeOut": "5000",
  "extendedTimeOut": "1000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
}

function updateStock() {
  var min = parseInt($('#min_stock_general').val());
  var max = parseInt($('#max_stock_general').val());
  // checar por campos vacios
  if(!min || !max ) {
      toastr["error"]("Error, No pueden quedar vacios los campos de mínimo y máximo");
  } else {
    //maximo sea menor al minimo
    if( max < min) {
      toastr["error"]("Error, El máximo debe de ser mayor al mínimo");
      //almenos 1 producto seleccionado
    } else if(rows_selected.length == 0) {
      toastr["error"]("Error, Se debe seleccionar al menos un producto para actualizar");
    } else {
        $.ajax({
          type: "PUT",
          url: "/update_stock",
          dataType: "json",
          data: {
            ids: rows_selected,
            stock_min: min,
            stock_max: max
          },
          success: function(xhr, status, error) {
            var table = $('.stock-table').dataTable();
            var rows = $(".stock-table").dataTable().fnGetNodes();
            $.each(rows, function(i, row) {
              var id = $(this).attr('id').substring($(this).attr('id').indexOf('_') + 1, $(this).attr('id').length);

              if($.inArray(id, rows_selected) != -1) {
                minInput = $(row).find("td:eq(6)")
                minInput.text(min);
                maxInput = $(row).find("td:eq(7)")
                maxInput.text(max);
              }
            });
              $('#select-all').click();
              $('#min_stock_general').val("");
              $('#max_stock_general').val("");
              toastr["success"]("Stock mínimo y máximo actualizado.");
          }
        });
    }
  }
}

function initialStock() {
  var initialStock = parseInt($('#initial_stock_input').val());
  if (initialStock || initialStock == 0) {
    if(rows_selected.length > 0) {
      $.ajax({
        type: "PUT",
        url: "/set_initial_stock",
        dataType: "json",
        data: {
          ids: rows_selected,
          stock: initialStock
        },
        success: function(xhr, status, error) {
          var table = $('.stock-table').dataTable();
          var rows = $(".stock-table").dataTable().fnGetNodes();
          $.each(rows, function(i, row) {
            var id = $(this).attr('id').substring($(this).attr('id').indexOf('_') + 1, $(this).attr('id').length);

            if($.inArray(id, rows_selected) != -1) {
              initialStockInput = $(row).find("td:eq(6)");
              initialStockInput.text(initialStock);
            }
          });
            $('#select-all').click();
            $('#initial_stock').val("");
            toastr["success"]("Stock inicial actualizado.");
        }
      });
    } else {
      toastr["error"]("Error, Se debe seleccionar al menos un producto para actualizar");
    }
  } else {
    toastr["error"]("Error, NO puede quedar vacio el campo de stock inicial");
  }
}
</script>



