$(function() {
  var fields;

  $('#new_item .submit').live('click', function(event) {
    fields = $(this).parent();
  });

  $('#new_item').submit(function(event) {
    if (fields.hasClass('occupancy')) {
      $.ajax({
        type: 'post',
        url: '/items/options',
        data: $("#new_item").serialize(),
        error: function(xhr, statusText, error) {
          if (xhr.status == 422) {
            $('div.fields.occupancy').html(xhr.responseText);
          } else {
            alert('Sory, something went wrong. Please give it another try.');
          }
        },
        success: function(html, result) {
          $('.content').hide('fast');
          $('div.fields.occupancy').hide('fast');
          $('div.fields.options').hide().html(html).show('fast');
        }
      });
    } else if (fields.hasClass('options')) {
      $.ajax({
        type: 'post',
        url: '/items',
        data: $("#new_item").serialize(),
        complete: function(xhr, statusText) {
          switch (xhr.status) {
            case 201:
              window.location = xhr.getResponseHeader('location');
              break;
            case 422:
              $('div.fields.options').html(xhr.responseText);
              break;
            default:
              alert('Sory, something went wrong. Please give it another try.');
          }
        }
      });
    }

    event.preventDefault();
  });
});
