<div id="form_wizard_product_return">
  <%= form_for(@products_return, :html => {:class=>"form-horizontal form-bordered form-row-stripped", :id=> "submit_form"}) do |f| %>
    <div class="portlet-body form">
      <div id="error_explanation"></div>
      <div class="form-wizard">
        <div class="form-body">
          <%= hidden_field_tag 'sale_id', '' %>
          <ul class="nav nav-pills nav-justified steps">
            <li class="active">
              <a href="#tab1" data-toggle="tab" class="step" aria-expanded="true">
              <span class="number">1 </span>
              <span class="desc">
                <i class="fa fa-check"></i> Buscar venta</span>
              </a>
            </li>
            <li>
              <a href="#tab2" data-toggle="tab" class="step">
              <span class="number">2 </span>
              <span class="desc">
                <i class="fa fa-check"></i>Producto(s) a devolver</span>
              </a>
            </li>
            <li>
              <a href="#tab3" data-toggle="tab" class="step">
              <span class="number">3 </span>
              <span class="desc">
                <i class="fa fa-check"></i>Detalle de la devolución</span>
              </a>
            </li>
            <li>
              <a href="#tab4" data-toggle="tab" class="step">
              <span class="number">4 </span>
              <span class="desc">
                <i class="fa fa-check"></i>Finalizar devolución</span>
              </a>
            </li>
          </ul>
          <div id="bar" class="progress progress-striped" role="progressbar">
            <div class="progress-bar progress-bar-success" style="width: 25%;">
            </div>
          </div>
          <div class="tab-content">
            <div class="alert alert-error hide">
              <button class="close" data-dismiss="alert"></button>
              Tienes algunos errores. Favor de verificar.
            </div>
            <div class="alert alert-success hide">
              <button class="close" data-dismiss="alert"></button>
              Información Correcta!
            </div>
            <div class="tab-pane active" id="tab1">
              <h3 class="block">Buscar venta</h3>
              <div id="error_explanation"></div>
              <!-- tipo de busqueda -->
              <div class="form-group">
                <div class="col-md-6" style="padding-top:5px">
                  <div class="radio-list">
                    <label class="radio-inline">
                      <input type="radio" name="filter" id="sale_code" value="sale_code" checked> Buscar por folio de venta
                    </label>
                    <label class="radio-inline">
                      <input type="radio" name="filter" id="dates" value="dates"> Buscar por fechas y producto
                    </label>
                  </div>
                </div>
              </div>
              <!-- folio de venta -->
              <div class="row" id="sale_code_div">
                <div class="col-md-12">
                  <h4 class="form-section">Folio de venta</h4>
                  <div class="form-group">
                    <%= label_tag :code, 'folio', {:class=>"col-md-2 control-label"} do %> Folio de venta <span class="required">*</span>
                    <% end %>
                    <div class="col-md-3 input-group" style="float:left">
                      <span class="input-group-addon"><i class="fa fa-barcode"></i></span>
                      <%= text_field_tag :code, '', class: "form-control" %>
                    </div>
                    <div class="col-md-2">
                      <button type="button" id="btn_search_by_period" class="btn blue" style="margin-left:10px" onclick="findSalesByCode()">
                        <i class="fa fa-search"></i> Buscar
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <!-- periodo y producto-->
              <div class="row hidden" id="period_div">
                <div class="col-md-12">
                  <h4 class="form-section">Fechas y producto</h4>
                  <div class="form-group">
                    <label class="col-md-1 control-label" for="typeahead" style="padding-right:0px">Producto</label>
                    <div class="col-md-4">
                      <input class="form-control" type="text" id="typeahead">
                    </div>
                    <button type="button" id="btn_search_by_period" class="btn green" style="margin-left:10px" onclick="clearTypeahead()">Limpiar</button>
                  </div>
                  <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"/>
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </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"/>
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </div>
                    </div>
                    <button type="button" id="btn_search_by_period" class="btn blue" style="margin-left:10px" onclick="findSalesByPeriod()">
                      <i class="fa fa-search"></i> Buscar
                    </button>
                  </div>
                </div>
              </div>
              <!-- tabla con ventas -->
              <div class="margin-top-20 col-md-12">
                  <table class="table table-striped table-bordered table-hover tableadvancedSingleSelection" id="sales_table">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>Folio</th>
                        <% if current_user.usertype == 'A' %>
                          <th>Pto. de venta</th>
                        <% end %>
                        <th>Cliente</th>
                        <th>Vendedor</th>
                        <th>Fecha</th>
                        <th>tipo</th>
                        <th>Productos</th>
                        <th>Status</th>
                        <th>Total</th>
                      </tr>
                    </thead>
                    <tbody>
                    </tbody>
                  </table>
              </div>
            </div>
            <div class="tab-pane" id="tab2">
              <h3 class="block">Seleccionar productos a devolver</h3>
              <!-- tabla -->
              <div class="margin-top-20 col-md-12">
                <table class="table table-striped table-bordered table-hover tableWithCheckbox" id="products_table">
                  <thead>
                    <tr>
                      <th class="text-center">
                        <input name="select_all" value="1" id="select-all" type="checkbox" />
                      </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>
                    </tr>
                  </thead>
                  <tbody>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="tab-pane" id="tab3">
            <div class="col-md-12">
              <div class="col-md-6"><h3 class="block">Cantidad y destino de los productos a devolver</h3></div>
              <div class="col-md-6">
                <h3 class="block pull-right">Total devuelto
                  <span style="color:#26C281" id="returned_money_display"></span>
                </h3>
                <input type="text" class="hidden" id="returned_money_input">
              </div>
            </div>
              <!-- tabla -->
              <div class="col-md-12">
                <table class="table table-striped table-bordered table-hover" id="destiny_table">
                  <thead>
                    <tr>
                      <th>Cantidad a cambiar</th>
                      <th>Producto</th>
                      <th>Motivo</th>
                      <th>Destino del producto a cambiar</th>
                    </tr>
                  </thead>
                  <tbody>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="tab-pane" id="tab4">
              <h3 class="block">Finalizar devolución</h3>

              <div class="col-md-12 margin-top-10">
                <table class="pull-right">
                  <thead>
                    <tr>
                      <th></th>
                      <th></th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td>
                        <h3 class="pull-right" style="margin-top:0px">Disponible para devolución: </h3>
                      </td>
                      <td>&nbsp;</td>
                      <td>
                        <h3 class="pull-right" style="margin-top:0px;color:#26C281" id="money_available_display"></h3>
                        <input type="text" class="hidden" id="money_available_input">
                      </td>
                    </tr>
                    <tr>
                      <td>
                        <h3 class="pull-right" style="margin-top:0px">Total en productos: </h3>
                      </td>
                      <td>&nbsp;</td>
                      <td>
                        <h3 class="pull-right" style="margin-top:0px;color:#26C281" id="total_in_products_display"></h3>
                        <input type="text" class="hidden" id="total_in_products_input">
                      </td>
                    </tr>
                    <tr>
                      <td>
                        <h3 class="pull-right" style="margin-top:0px">A pagar: </h3>
                      </td>
                      <td>&nbsp;</td>
                      <td>
                        <h3 class="pull-right" style="margin-top:0px;color:#26C281" id="to_pay_display"></h3>
                        <input type="text" class="hidden" id="to_pay_input">
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div class="col-md-12">
                <div class="form-group">
                  <label class="col-md-1 control-label" for="typeahead2" style="padding-right:0px;"> Producto
                    <span class="required">*</span>
                  </label>
                  <div class="col-md-4">
                    <input class="form-control" type="text" id="typeahead2">
                  </div>
                  <button id="products_new" class="btn btn-success" type="button" onclick="addnewProd()"> Agregar <i class="fa fa-plus"></i> </button>
                </div>
              </div>
              <div class="margin-top-10 col-md-12">
                <table class="table table-striped table-bordered table-hover tableadvanced" id="change_for_product_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>Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="form-actions">
              <div class="row">
                <div class="col-md-9">
                  <a href="javascript:;" class="btn default button-previous disabled col-md-2" style="display: none;"><i class="fa fa-angle-left"></i> Regresar </a>

                  <a id="button-next"  class="btn blue button-next disabled col-md-2">
                      Siguiente <i class="fa fa-angle-right"></i> </a>

                  <a href="javascript:;" class="btn green button-submit col-md-2" style="display:none;">
                    Guardar <i class="m-icon-swapright m-icon-white"></i> </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  <% end %>
</div>
<script type="text/javascript">
  var rows_selected = [];
  var selectedProduct = null;
  var newProduct = null;
  var timeout = null;
  var shouldProcess = false;
  var sale_id = null;
  //los products in, son los regresados
  var products_in = [];
  // products out, son los nuevos, estan al revez en la bd
  var products_out = [];

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

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

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

  $('input[type=radio][name=filter]').change(function() {
      if (this.value == 'sale_code') {
        $('#sale_code_div').removeClass('hidden');
        $('#period_div').addClass('hidden');
      }
      else if (this.value == 'dates') {
        $('#period_div').removeClass('hidden');
        $('#sale_code_div').addClass('hidden');
      }
  });

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

  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();

  $('#typeahead2').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>')
      }
  });

  $('#typeahead2').bind('typeahead:selected', function(event, datum, name) {
      newProduct = datum;
  });

  //buscar ventas por periodo de tiempo
  function findSalesByPeriod() {
    var start = moment($("#begin_date").data("date"), "DD-MM-YYYY").format('YYYY-MM-DD HH:mm:ss');
    var end = moment($("#end_date").data("date"), "DD-MM-YYYY").endOf('day').format('YYYY-MM-DD HH:mm:ss');
    var product = selectedProduct ? selectedProduct.id : '';

    if ($("#begin_date").data("date") && $("#end_date").data("date")) {
      App.blockUI({
           target: $("#sales_table"),
           animate: true
      });

      $.ajax({
        type: "get",
        url:  '/find_sales_by_dates_or_code/',
        data: {
          start_date: start,
          end_date: end,
          product_id: product
        },
        dataType: 'script',
        success: function(data) {
          App.unblockUI($("#sales_table"));
        }
      });
    } else {
      toastr["error"]("Es necesario indicar fechas.");
    }
  }

  //buscar venta por folio
  function findSalesByCode() {
    var sale_code = $('#code').val();
    if(sale_code) {
      $.ajax({
        type: "get",
        url:  '/find_sales_by_dates_or_code/',
        data: {
          sale_code: sale_code
        },
        dataType: 'script',
        success: function(data) {
          App.unblockUI($("#sales_table"));
        }
      });
    } else {
      toastr["error"]("Ingresa folio de venta para buscar.");
    }
  }

  //dependiendo de la venta seleccionada, traer sus detalles
  function selectSale() {
    var table = $('#sales_table').dataTable();
    var rows = table.fnGetNodes();
    var selected_sale = null;

    //pick selected sale
    for ( var i=0; i < rows.length; i++ ) {
      if ( $(rows[i]).hasClass('active') ) {
        selected_sale = rows[i];
        break;
      }
    }

    if(selected_sale) {
      var idText = selected_sale.id;
      sale_id = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
      $('#sale_id').val(sale_id);
      $.ajax({
        type: "get",
        url:  '/sales_details/' + sale_id,
        dataType: 'script',
        success: function(data) {
          return true;
        }
      });
    } else {
      selected_sale = null;
      sale_id = null;
      toastr["error"]("Seleccione la venta a devolver");
      return false;
    }

    rows_selected = [];
  }

  // detalles para mostrar la tabla donde seleccionan destino y motivo
  function selectProducts() {
    if (rows_selected.length > 0) {
      var destiny_select = "<select class='form-control'><option value='stock'>Inventario</option><option value='waste'>Merma</option></select>";
      var details_to_return = [];
      $('#destiny_table').find('tbody').empty();

      for (var i =0 ; i < rows_selected.length; i++) {
        // iterar los rows de la tabla de productos para obtener toda la info de los que se regresaran
        $('#products_table tbody tr').each(function() {
          var idText = $(this).attr('id');
          var detailId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);

          var input_with_total = "<input class='hidden total' value='" + $(this).find('td:eq(8) input').val() + "'/>";

          var input_with_sold_quantity = "<input class='hidden quantity' value='" + $(this).find('td:eq(4)').html().trim() + "'/>";

          var input_with_prod_id = "<input class='hidden product' value='" + $(this).find('td:eq(1) input').val() + "'/>";

          var input_with_total_returned = "<input class='hidden returned_total' value=''/>";


          if(detailId == rows_selected[i]) {
            var row = $("<tr id='"+ $(this).attr('id') +"'><td><input type='number' min='1' class='form-control input-small' oninput='checkBoughtExistence($(this))' required></td><td>" + $(this).find("td:nth-child(4)").html() + input_with_total + input_with_total_returned +input_with_sold_quantity + input_with_prod_id + "</td><td><input type='text' class='form-control input-large'></td><td>"+ destiny_select +"</td></tr>");

            $('#destiny_table > tbody:last-child').append(row);
          }
        });
      };
      shouldProcess = false;
    } else {
      toastr["error"]("Seleccione producto(s).");
      return false;
    }
    $('#returned_money_input').val('');
    $('#returned_money_display').html('$0.00');
  }

  function processProducts() {
    if(shouldProcess) {
      products_in = [];
      $('#change_for_product_table').dataTable().fnClearTable();

      $('#destiny_table tbody tr').each(function() {
        var obj = {};
        obj.product_id = $(this).find('td:eq(1) .product').val();
        obj.quantity = $(this).find('td:eq(0) input').val();
        obj.reason =  $(this).find('td:eq(2) input').val();
        obj.is_wasted = $(this).find('td:eq(3) select option:selected').val() == 'waste' ? true : false;
        obj.amount = $(this).find('td:eq(1) .returned_total').val();
        products_in.push(obj);
      });

      var returned_money = $('#returned_money_input').val();
      $('#change_for_product_table').find('tbody').empty();
      $("#money_available_display").html(accounting.formatMoney(returned_money));
      $("#money_available_input").val(returned_money);
      $("#total_in_products_display").html(accounting.formatMoney(0));
      $('#total_in_products_input').val(0);
      $("#to_pay_display").html(accounting.formatMoney(0));
      $('#to_pay_input').val(0);
      return true;
    } else {
      toastr["error"]("Se está intentando regresar mas de lo que se vendió, verifica la(s) cantidad(es)");
      return false;
    }
  }

  //para saber si avanzar o no en el wizard, ejecutando las funciones de cada tab
  function nextStep(step) {
    switch(step) {
      case 1:
        return selectSale();
      case 2:
        return selectProducts();
      case 3:
        return processProducts();
    }
  }

  //checar que la cantidad a devolver que ingresan coincida con la cantidad vendida
  function checkBoughtExistence(input) {
    if(input.val()) {
      clearTimeout(timeout);
      timeout = setTimeout(function () {
        var idText = input.closest('tr').attr('id');
        var detailId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);

        $.ajax({
          type: "get",
          url:  '/check_sale_detail_quantity/',
          data: {
            sale_detail_id: detailId
          },
          dataType: 'json',
          success: function(data) {
            //checar si la cantidad corresponde a lo vendido y mostrar el total del producto devuelto
            var sold = parseInt(data);
            var quantity = parseInt(input.val());
            var product_text = input.closest('tr').find('td:eq(1)').html();
            var product_name = product_text.substring(0, product_text.lastIndexOf('<br>')).trim();
            shouldProcess = sold >= quantity ? true : false;
            if (!shouldProcess) {
              toastr["error"]("Del producto " + product_name + " se vendió " + sold + " articulo(s), NO se puede regresar mas de lo que se vendió");
              input.val('');
            }
            getReturnedMoneyTotal();
          }
        });
      }, 300);
    }
  }

  //borrar el producto seleccionado al buscar ventas
  function clearTypeahead() {
    $('#typeahead').typeahead('val', '');
    selectedProduct = null;
  }

  function getReturnedMoneyTotal() {
    var returned_money = 0;
    $('#destiny_table tbody tr').each(function() {
      var quantity_typed = parseInt($(this).closest('tr').find('td:eq(0) input').val());
      var sold_quantity = parseInt($(this).closest('tr').find('td:eq(1) .quantity').val());
      if(quantity_typed <= sold_quantity) {
        var product_total = parseFloat($(this).closest('tr').find('td:eq(1) .total').val());
        var total_product_returned = (product_total / sold_quantity) * quantity_typed;
        returned_money += total_product_returned;
        $(this).closest('tr').find('td:eq(1) .returned_total').val(total_product_returned);
      } else {
        $(this).closest('tr').find('td:eq(0) input').val('');
        shouldProcess = false;
      }
    });
    $('#returned_money_input').val(returned_money);
    $('#returned_money_display').html(accounting.formatMoney(returned_money));
  }

  function addnewProd() {
    if(newProduct) {
      $.ajax({
        type: "post",
        url:  '/add_product_to_return/',
        data: {
          sale_id: $('#sale_id').val(),
          product_id: newProduct.id
        },
        dataType: 'script',
        success: function(data) {
          $('#typeahead2').typeahead('val','');
          newProduct = null;
          calculateTotals();
        }
      });
    } else {
      toastr["error"]("Selecciona producto");
    }
  }

  function deleteRow(button) {
    var table = $('#change_for_product_table').DataTable();
    table.row(button.closest('tr')).remove().draw();
    calculateTotals();
  }

  function updateQuantity(input) {
    if(input.val()) {
      clearTimeout(timeout);
      timeout = setTimeout(function () {
        var idText = input.closest('tr').attr('id');
        var product_id = idText.substring(idText.lastIndexOf('_') + 1, idText.length);

        var linkForModal = input.closest('tr').find('td:eq(9)').find('a');
        //reemplazar la cantidad en el href del a element que manda llamar el modal, para mostrar correctamente la cantidad
        linkForModal.attr('href', linkForModal.prop('href').replace(/(quantity=).*?(&)/,'$1' + input.val() + '$2'));

        $.ajax({
          type: "get",
          url:  '/update_quantity_prod_return/',
          data: {
            product_id: product_id,
            sale_id: $('#sale_id').val(),
            quantity: input.val()
          },
          dataType: 'json',
          success: function(data) {
            if (data) {
              // iva
              input.closest('tr').find('td:eq(6)').html(accounting.formatMoney(data.tax));
              //dicount
              input.closest('tr').find('td:eq(7)').html(accounting.formatMoney(data.discount));
              //total
              text = accounting.formatMoney(data.total) + "<input type='hidden' name='total' id='total' value=" + data.total + ">"
              input.closest('tr').find('td:eq(8)').html(text);

              calculateTotals();
            } else {
              input.val('');
              toastr["error"]("Stock insuficiente del producto.");
            }
          }
        });
      }, 300);
    }
  }

  function calculateTotals() {
    var available_money = parseFloat($('#money_available_input').val());
    var total_in_prods = 0;

    $('#change_for_product_table tbody tr').each(function() {
      total_in_prods += parseFloat($(this).find('td:eq(8) input').val());
    });

    $('#total_in_products_input').val(total_in_prods);
    $('#total_in_products_display').html(accounting.formatMoney(total_in_prods));

    if(total_in_prods > available_money) {
      var to_pay = total_in_prods - available_money;
      $('#to_pay_input').val(to_pay);
      $('#to_pay_display').html(accounting.formatMoney(to_pay));
    } else {
      $('#to_pay_input').val(0);
      $('#to_pay_display').html(accounting.formatMoney(0));
    }
  }

  function submitForm() {
    var sale_id = $('#sale_id').val();

    $('#change_for_product_table tbody tr').each(function() {
      var obj = {};
      var idText = $(this).attr('id');
      var product_id = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
      obj.product_id = product_id;
      obj.quantity = $(this).find('td:eq(4) input').val();
      obj.amount = $(this).find('td:eq(8) input').val();
      products_out.push(obj);
    });

    var table = $('#change_for_product_table').dataTable();
    if(sale_id && products_in.length > 0 && products_out.length > 0 && table.fnGetData().length > 0) {

      $('.button-submit').attr('disabled', true);
      $.ajax({
        type: "post",
        url:  '/products_returns',
        data: {
          sale_id: sale_id,
          products_in: JSON.stringify(products_in),
          products_out: JSON.stringify(products_out),
          new_amount: $('#total_in_products_input').val(),
          returned_amount: $('#money_available_input').val(),
          difference_amount: $('#to_pay_input').val()
        },
        dataType: 'script',
        success: function(data) {}
      });
    } else {
      toastr["error"]("Complete todos los campos para guardar la devolución");
    }
  }
</script>
