$(function() {
  var documentID = $("#documentID").html();
 

  $("#addAttachment").click(function() {
    $("#addAttachmentModal").dialog('open'); 
  }); 


  $("#addAttachmentModal").dialog({
    autoOpen: false,
    height: 900,
    width: 600,
    modal: true,
    buttons: {
      "Add Attachment": function() {

        var attachmentInputs = $('#DocumentAttachmentAddForm').find('input:checked, #DocumentAttachmentDocumentId');

        $.post('/documents/saveAttachments', attachmentInputs, function(data) {
              $("#addAttachmentModal").dialog( "close" );
        });
        

      },
      Cancel: function() {
                $( this ).dialog( "close" );
      }
    },
    close: function() {
             loadAttachments();
      }


  });

  $("#attachmentPrincipleSelect").change(function() {
    var principleID = $(this).val();
    loadPrincipleAttachments(principleID);
  });

  $("#removeAttachments").click(function() {
      removeAttachments();
  });

  function loadPrincipleAttachments(id) {
    $.get('/documents/getAttachmentsByPrinciple/'+id, function(attachments) {
      $('#principleAttachments').html(attachments);
    });
  }

  function loadAttachments() {
    $.get('/documents/getAttachments/'+documentID, function(attachments) {
      $("#attachments-table").html(attachments);
    });
  }

  function removeAttachments() {
    var selectedAttachments = $(".documentAttachment-checkbox:checked");
	$.post('/documents/removeAttachments', selectedAttachments, function(data) {
            loadAttachments();
    });
    
  }

});
