var Login = new function() {  
  //Set up variables.
  this.ajax = null;
  this.form = null;
  this.promptDiv = null;
  this.dotSpan = null;
  this.button = null;
  this.enabled = true;
  this.dots = '';
  this.promptInterval = null;
  
  //Function to clean up memory.  Called at end on window ONUNLOAD.
  this.cleanup = function() {
    var self = Login;
    self.form = null;
    self.promptDiv = null;
    self.dotSpan = null;
    self.button = null;
  };
  
  //Function to intialize the page.  Sets variables.  Called at end on window ONLOAD.
  this.init = function() {
    var self = Login;
    self.ajax = new Ajax();
    self.form = document.getElementById('loginForm');
    self.promptDiv = document.getElementById('promptDiv');
    self.dotSpan = document.getElementById('dotSpan');
    self.button = document.getElementById('submitButton');
    self.setPrompt('base', 'Enter a login ID and password, and click the Submit button.');
    self.form.LoginId.focus();
    self.toggleEnabled(false);
    self.form.onsubmit = function() { return false; }
    self.clearCookie('userId');
    self.enableScreenReaderFeatures();
  };
  
  //Function to clear cookie.  Called in this.init function (above).
  this.clearCookie = function(name) {
    var expireDate = new Date(0);
    document.cookie = name + '=; expires=' + expireDate.toGMTString() + '; path=/';
  };
  
  //Function to set the user prompt in the prompt div.  Called in this.init, as well as setStatusPrompt and showErrorPrompt
  this.setPrompt = function(stat, msg) {
    var self = Login;
    var promptDiv = self.promptDiv;
    var msgSpan = document.getElementById('msgSpan');
    var statusClass = '';
    promptDiv.className = stat + 'Prompt'; // 'base', 'proc' or 'err'
    if (msgSpan.firstChild) {
      msgSpan.removeChild(msgSpan.firstChild);
    }
    msgSpan.appendChild(document.createTextNode(msg));
  };
  
  //Function to monitor keyboard activity.  Called at end with document.keyup
  this.keyup = function(e) {
    var self = Login;
    if (!e) {
      e = window.event;
    }
    if (e.keyCode != 13) {
      self.evalFormFieldState();
    }
    else {
      if (self.enabled) {
        self.submitData();
      }
    }
  };
  
  //Evaluates whether or not the login button can be enabled (if there is date in username/password fields).  Called in this.keyup (above) and in the enablescreenreader features (below).
  this.evalFormFieldState = function() {
    var self = Login;
    if (self.form.LoginId.value.length > 0 && self.form.Pass.value.length > 0) {
      self.toggleEnabled(true);
    }
    else {
      self.toggleEnabled(false);
    }
  };
  
  //Toggles the submit button.  Called from this.evalFormFieldState (above), as well as from this.init (above) to DISABLE the button on form load.  Disabling through JavaScript ensures the form is able to work properly if not AJAX-enabled.
  this.toggleEnabled = function(able) {
    var self = Login;
    if (able) {
      self.button.onclick = self.submitData;
      self.button.disabled = false;
      self.button.className = 'inputButtonActive';
      self.enabled = true;
    }
    else {
      self.button.onclick = null;
      self.button.disabled = true;
      self.button.className = 'inputButtonDisabled';
      self.enabled = false;
    }
  };
  
  //Sends the form data, calling the AJAX functions in ajax.js.  Called from this.keyup (above) if ENTER is pressed, as well as TURNED ON in the toggleEnable code (above)
  this.submitData = function() {
    var self = Login;
    var postData = '';
    postData = formData2QueryString(self.form);
    self.ajax.doPost('ajax/login.php', postData, self.handleLoginResp);
    self.showStatusPrompt();
    self.toggleEnabled(false);
  };
	//Shows visualization of XMLHttpRequst progress.  Called from this.submitdata (above).
	this.showStatusPrompt = function() {
    var self = Login;
    self.dots = '';
    self.setPrompt('proc', 'Processing');
    self.promptInterval = setInterval(self.showStatusDots, 200);
  };
	
	//Shows the dots in the visualization of XMLHttpRequest, called from this.showStatusPrompt above.
	this.showStatusDots = function() {
    var self = Login;
    var dotSpan = self.dotSpan;
    self.dots += '.';
    if (self.dots.length > 4) {
      self.dots = '';
    }
    if (dotSpan.firstChild) {
      dotSpan.removeChild(dotSpan.firstChild);
    }
    dotSpan.appendChild(document.createTextNode(' ' + self.dots));
  };
  
  //Handles the returned response from the AJAX request.  Called from this.submitData (above).
  this.handleLoginResp = function(str) {
    var self = Login;
    var respArr = str.split('|'); //NOTE: This correspondes to PHP var $separator;
    var respType = respArr[0].toLowerCase();
    var respMsg = respArr[1];
    if (respType == 'success') {
      location = respMsg;
    }
    else {
      self.showErrorPrompt(respMsg);
    }
  };
  
  //Function to show error in user status display.  Called from this.handleLoginResp (above)
  this.showErrorPrompt = function(str) {
    var self = Login;
    var dotSpan = self.dotSpan;
    clearInterval(self.promptInterval);
    if (dotSpan.firstChild) {
      dotSpan.removeChild(dotSpan.firstChild);
    }
    self.setPrompt('err', str);
    self.form.Pass.value = '';
    if (self.form.ChangeAlert.checked) {
      alert('Error. ' + str);
    }
  };
  
  //Function to set up accessibility features.  Called from the this.init function (above).
this.enableScreenReaderFeatures = function() {
  var self = Login;
  var fieldDiv = document.getElementById('fieldDiv');
  var msgDiv = null;
  var checkboxDiv = null;
  var label = null;
  var checkbox = null;
  var msg = 'This web page uses dynamic content. Page content' +
    ' may change without a page refresh. Check the following' +
    ' checkbox if you would like an alert dialog to inform' +
    ' you of page content changes.';
  msgDiv = document.createElement('div');
  msgDiv.className = 'readerText';
  msgDiv.appendChild(document.createTextNode(msg));
  self.form.insertBefore(msgDiv, fieldDiv);
  checkboxDiv = document.createElement('div');
  checkboxDiv.className = 'readerText';
  label = document.createElement('label');
  label.appendChild(document.createTextNode('Content Change Alert'));
  checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.id = 'ChangeAlert';
  checkbox.name = 'ChangeAlert';
  checkbox.value = 'true';
  checkbox.title = 'Content Change Alert';
  label.appendChild(checkbox);
  checkboxDiv.appendChild(label);
  self.form.insertBefore(checkboxDiv, fieldDiv);
    self.form.Pass.onchange = self.evalFormFieldState;
    self.form.Pass.title = 'Password. Enter text to activate the Submit button.';
  };
};

//Fires events on window load/unload.
window.onunload = Login.cleanup;
window.onload = Login.init;
document.onkeyup = Login.keyup;
