// variant autocompletion

$(document).ready(function() {

  if ($('#variant_autocomplete_template').length > 0) {
    window.variantTemplate = Handlebars.compile($('#variant_autocomplete_template').text());
    window.variantStockTemplate = Handlebars.compile($('#variant_autocomplete_stock_template').text());

    // handle variant selection, show stock level.
    $('#add_variant_id').change(function(){
      var variant_id = $(this).val();

      var variant = _.find(window.variants, function(variant){
        return variant.id == variant_id
      })
      $('#stock_details').html(variantStockTemplate({variant: variant}));
      $('#stock_details').show();

      $('button.add_variant').click(addVariantFromStockLocation);

      // Add some tips
      $('.with-tip').powerTip({
        smartPlacement: true,
        fadeInTime: 50,
        fadeOutTime: 50,
        intentPollInterval: 300
      });

    });

    //handle edit click
    $('a.edit-item').click(toggleItemEdit);

    //handle cancel click
    $('a.cancel-item').click(toggleItemEdit);

    handle_save_click = function(){
      var save = $(this);
      var shipment_number = save.data('shipment-number');
      var variant_id = save.data('variant-id');

      var quantity = parseInt(save.parents('tr').find('input.line_item_quantity').val());

      toggleItemEdit();

      adjustItems(shipment_number, variant_id, quantity);
      return false;
    }
    $('a.save-item').click(handle_save_click);

    handle_delete_click = function(){
      var del = $(this);
      var shipment_number = del.data('shipment-number');
      var variant_id = del.data('variant-id');

      toggleItemEdit();

      adjustItems(shipment_number, variant_id, 0);
    }
    $('a.delete-item').click(handle_delete_click);
  }
});

adjustItems = function(shipment_number, variant_id, quantity){
    var shipment = _.findWhere(shipments, {number: shipment_number + ''});
    var inventory_units = _.where(shipment.inventory_units, {variant_id: variant_id});

    var url = Spree.routes.orders_api + "/" + order_number + "/shipments/" + shipment_number;

    var new_quantity = 0;
    if(inventory_units.length<quantity){
      url += "/add"
      new_quantity = (quantity - inventory_units.length);
    }else if(inventory_units.length>quantity){
      url += "/remove"
      new_quantity = (inventory_units.length - quantity);
    }
    url += '.json';

    if(new_quantity!=0){
      $.ajax({
        type: "PUT",
        url: Spree.url(url),
        data: { variant_id: variant_id, quantity: new_quantity }
      }).done(function( msg ) {
        window.location.reload();
      });
    }
}

toggleTrackingEdit = function(){
  var link = $(this);
  link.parents('tbody').find('tr.edit-tracking').toggle();
  link.parents('tbody').find('tr.show-tracking').toggle();
}

toggleMethodEdit = function(){
  var link = $(this);
  link.parents('tbody').find('tr.edit-method').toggle();
  link.parents('tbody').find('tr.show-method').toggle();
}

toggleItemEdit = function(){
  var link = $(this);
  link.parent().find('a.edit-item').toggle();
  link.parent().find('a.cancel-item').toggle();
  link.parent().find('a.save-item').toggle();
  link.parent().find('a.delete-item').toggle();
  link.parents('tr').find('td.item-qty-show').toggle();
  link.parents('tr').find('td.item-qty-edit').toggle();

  return false;
}

addVariantFromStockLocation = function() {
  $('#stock_details').hide();

  var variant_id = $('input.variant_autocomplete').val();
  var stock_location_id = $(this).data('stock-location-id');
  var quantity = $("input.quantity[data-stock-location-id='" + stock_location_id + "']").val();

  var shipment = _.find(shipments, function(shipment){
    return shipment.stock_location_id == stock_location_id && (shipment.state == 'ready' || shipment.state == 'pending');
  });

  if(shipment==undefined){
    $.ajax({
      type: "POST",
      url: Spree.url(Spree.routes.orders_api + "/" + order_number + "/shipments.json"),
      data: { variant_id: variant_id, quantity: quantity, stock_location_id: stock_location_id }
    }).done(function( msg ) {
      window.location.reload();
    }).error(function( msg ) {
      console.log(msg);
    });
  }else{
    //add to existing shipment
    adjustItems(shipment.number, variant_id, quantity);
  }
  return 1
}
