
// ==========
// Add Status
// ==========

$(document).ready(function() {

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

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

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

    formSubmit($sessionStorage);
    
  });

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

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

    var 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 : 0, status_name : status_name.val() }) === true) {
      createInputError(status_name, "Name already exists");
      return false;
    }
    
    e.preventDefault();
    
    $.post("./", $(this).serialize())
    
      .done(function() {
    
        $sessionStorage.action = $sessionStorage.addStatus || "";
        $sessionStorage.toast  = "Status was Added";

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

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