// Shipments AJAX API

$(document).ready(function() {

  handle_ship_click = function(){
    var link = $(this);
    var shipment_number = link.data('shipment-number');
    var url = Spree.url( Spree.routes.orders_api + "/" + order_number + "/shipments/" + shipment_number + "/ship.json");
    $.ajax({
      type: "PUT",
      url: url
    }).done(function( msg ) {
      window.location.reload();
    }).error(function( msg ) {
      console.log(msg);
    });
  }
  $('[data-hook=admin_order_edit_form] a.ship').click(handle_ship_click);

  //handle shipping method edit click
  $('a.edit-method').click(toggleMethodEdit);
  $('a.cancel-method').click(toggleMethodEdit);

  handle_shipping_method_save = function(){
    var link = $(this);
    var shipment_number = link.data('shipment-number');
    var selected_shipping_rate_id = link.parents('tbody').find("select#selected_shipping_rate_id[data-shipment-number='" + shipment_number + "']").val();
    var unlock = link.parents('tbody').find("input[name='open_adjustment'][data-shipment-number='" + shipment_number + "']:checked").val();
    var url = Spree.url( Spree.routes.orders_api + "/" + order_number + "/shipments/" + shipment_number + ".json");

    $.ajax({
      type: "PUT",
      url: url,
      data: { shipment: { selected_shipping_rate_id: selected_shipping_rate_id, unlock: unlock  } }
    }).done(function( msg ) {
      window.location.reload();
    }).error(function( msg ) {
      console.log(msg);
    });
  }
  $('[data-hook=admin_order_edit_form] a.save-method').click(handle_shipping_method_save);

  //handle tracking edit click
  $('a.edit-tracking').click(toggleTrackingEdit);
  $('a.cancel-tracking').click(toggleTrackingEdit);

  handle_tracking_save = function(){
    var link = $(this);
    var shipment_number = link.data('shipment-number');
    var tracking = link.parents('tbody').find('input#tracking').val();
    var url = Spree.url( Spree.routes.orders_api + "/" + order_number + "/shipments/" + shipment_number + ".json");

    $.ajax({
      type: "PUT",
      url: url,
      data: { shipment: { tracking: tracking } }
    }).done(function( msg ) {
      window.location.reload();
    }).error(function( msg ) {
      console.log(msg);
    });
  }
  $('[data-hook=admin_order_edit_form] a.save-tracking').click(handle_tracking_save);
});
