Event.addBehavior.reassignAfterAjax = true;

Event.addBehavior({
  '#account_selector_link:click': function() {
    AccountSelector.show();
    return false;
  }
});


Event.addBehavior({
  '#order_terms_and_conditions:click': function() {
    swap_order_save_image(this);
  },

  'form.delete_order:submit': function() {
    return confirm('Are you sure you want to delete this order?');
  },

  'form.duplicate_order:submit': function() {
    AccountSelector.show(function(account_id) {
      var order_id = location.pathname.match(/\/orders\/(\d+)/)[1];
      new Ajax.Request('/orders/' + order_id + '/duplicate', { method: 'post',
        asynchronous: false,
        parameters: {
          account_id: account_id,
          authenticity_token: encodeURIComponent(AUTH_TOKEN)
        },
        onComplete: function(response) {
          location.replace(response.getHeader('Location'));
        }
      });
    });
    return false;
  }
});



Event.addBehavior({
  '.grid .add_to_order:submit': function() {
    $(this.parentNode).addClassName('inorder');

    new Ajax.Request(this.action, { parameters: this.serialize(),
      onFailure: function() {
        alert('Oops an error occured with your last action. This page will be reloaded.')
        location.reload();
      }
    });

    return false;
  },

  '.product_list input[type="checkbox"][name="select_all"]:click': function() {
    var checkboxes = this.form.select('input[type="checkbox"][name="product_id[]"]')
    var checked = this.checked;
    checkboxes.each(function(checkbox) { checkbox.checked = checked; });
  },

  '.product_list button:click': function() {
    return product_list_form(this.form, this);
  },

  '.product_list form:submit': function() {
    return product_list_form(this);
  }
});
