$(function() {

  var attachmentHandlers = {
    afterUpload : function(data, status, xhr, form) {
      if(data.status == 'CREATED') {
        li = '<li id="attachment_'+data.attachment.id+'" class="'+ data.attachment.content_type_class +'">'+ data.attachment.label_and_filename +'<input type="hidden" name="attachment_ids[]" value="'+data.attachment.id+'"> <a href="#" class="deleteAttachment">[ Remove ]</a></li>';
        $("div.attachments ul").append(li);
        $("#new_attachment")[0].reset();
        $("#attachmentModal").jqmHide();
      } else {
        errors = [];
        i = 0;
        $.each(data.errors, function(count, error) {
          errors[i++] = '<li>' + error[0].replace(/_/g,' ') + ' ' + error[1] + '</li>';
        });
        $("#attachmentModal .errors").append(errors.join(''));
      }
      return false;
    },

    beforeUpload : function(formData, jqForm, options) {
      for (var i=0; i < formData.length; i++) {
        if (formData[i].name == 'attachment[attached]' && !formData[i].value) {
          alert('Please choose a file to attach.'); 
          return false;
        } 
      }
    }
  };

  // Show attachment dialog
  $("div.attachments a.newAttachment").click(function(e) {
    $("#attachmentModal").jqmShow();
    e.preventDefault();
    return false;
  });

  // Delete an attachment on the server and then remove the LI
  $("div.attachments a.deleteAttachment").livequery('click', function(e) {
    var id = $(this).siblings("input").val();

    jQuery.post( 
      '/attachments/'+id+'/destroy', 
      {authenticity_token: AUTHENTICITY_TOKEN, _method: 'delete'}, 
      function(data, textStatus, XMLHttpRequest) {
        if(textStatus == 'success' && data.status == 'DELETED') {
          $("#attachment_"+id).fadeOut().remove();
        }
      },
      'json'
    );

    e.preventDefault();
    return false;
  });

  $("#new_attachment").ajaxForm({ 
    beforeSubmit: attachmentHandlers.beforeUpload,
    success: attachmentHandlers.afterUpload,
    dataType: 'json', 
    clearForm: true });
});