
// ===========
// Edit Status
// ===========

$(document).ready(function() {

   var $application = $("#APPLICATION_MNEMONIC").val(),
      $sessionStorage = JSON.parse(sessionStorage.getItem($application) || "{}");
  
  // -----------
  // Save Button
  // -----------
  
  $(".btnSave").on("click", function(e) {
    e.preventDefault();
    $("#editStatus").submit();
  });

  // --------------
  // Cancel Button.
  // --------------

  $(".btnCancel").on("click", function() {
    
    $sessionStorage.action = $sessionStorage.editStatus || "";
    
    sessionStorage.setItem($application, JSON.stringify($sessionStorage));

    formSubmit($sessionStorage);
    
  });

  // -------------
  // Delete Button
  // -------------

  $(".btnDelete").on("click", function() {

    if (formPost({ action : "Statuses.statusActive", status_serial : $sessionStorage.status_serial }) === true) {

      $("#continue-dialog").find(".modal-title").html("Cannot Delete Status").end()
                           .find(".modal-body").html("This Status is in use and cannot be deleted.").end()
                           .modal("show");

    } else {

      $("#confirm-dialog").removeClass().addClass("modal confirm-delete-status")
                          .find(".modal-title").html("Confirm Delete Status").end()
                          .find(".modal-body").html("Are you sure you wish to delete this Status?").end()
                          .modal("show");

    } 
    
  });

  $("body").on("click", ".confirm-delete-status .btnConfirmDialogConfirm", function() {
    
    $.post("./", { action : "Statuses.deleteStatus", status_serial : $sessionStorage.status_serial })
      .done(function() {
        formSubmit({ action : $sessionStorage.deleteStatus });
    });
    
  });

  // ---------------
  // Validate Inputs
  // ---------------

  $("#editStatus").submit( function(e) {

    var status_serial  = $("#status_serial"),
        status_name    = $("#status_name"),
        status_classes = $("#status_classes");
        
    clearInputErrors();
    
    status_name.val(trimString(status_name.val()));
    status_classes.val(trimString(status_classes.val()));

    if (isBlank(status_name)) {
      createInputError(status_name, "Name is required");
      return false;
    }
    
    if (formPost({ action : "Statuses.statusExists", status_serial : status_serial.val(), status_name : status_name.val() }) === true) {
      createInputError(status_name, "Name already exists");
      return false;
    }
    
    e.preventDefault();
    
    $.post("./", $(this).serialize())
    
      .done(function() {
    
        $sessionStorage.action = $sessionStorage.editStatus || "";
        $sessionStorage.toast  = "Status was Saved";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);
    
    });
    
  });
  
});