
/*************************************************************
 *
 * Javascript Form Tools
 * ---------------------
 *
 * These objects take a JSON object representation of a form
 * and manipulate it to achieve various goals.
 *
 * The object format is as follows:
 *
 * var form_object = {
 *
 *   "form_name" : {
 *
 *     "field_name" : {
 *
 *       "type" : string,
 *       "name" : string,
 *       "description" : string,
 *       "minimum" : integer,
 *       "confirm" : boolean,
 *       "empty" : boolean
 *
 *     }
 *
 *   }
 *
 * }
 *
 * type
 * ------------
 *   values: text, password, hidden, email, checkbox, select
 *
 *   Each type of field is validated differently. For example,
 *   email addresses are checked for structure.
 *
 * name
 * ------------
 *   If this is specified, it will override the "field_name"
 *   value when the form is passed; it will not affect validation.
 *
 * description
 * ------------
 *   This is the name of the field to present to the user if
 *   validation fails on the field.
 *
 * minimum
 * ------------
 *   The minimum length that this text input must be in order
 *   to validate.
 *
 * confirm
 * ------------
 *   If this is true, the validator will look for an additional
 *   form input called "confirm_[field_name]" and make sure that
 *   its contents match the field. If they do not match, the
 *   validator will fail.
 *
 * empty
 * ------------
 *   If set to false, the validator will fail if the field is
 *   empty, or in the case of a select control, will fail if the
 *   selected option has an index of 0 (is the first option).
 *
 *
 * NOTE: You do not need to specify all form fields in the JSON
 *       object if you are merely validating it. You only need
 *       to specify the fields that you want to be validated;
 *       i.e., only the required fields.
 *
 ************************************************************/


/**
 * Create an on-the-fly form based on a JSON object.
 *
 * @param json The structure of the form.
 * @param string The form submission URL.
 */
function HO_Submission_Form(json_form,url) {

  this.form_structure = json_form;
  this.submission_url = url;

  this.form_root = document.createElement("form");
  this.form_root.setAttribute("action",this.submission_url);
  this.form_root.setAttribute("method","post");

  // just in case, make sure we're not visible here
  this.form_root.style.display = "none";

}

/**
 * Build the form.
 */
HO_Submission_Form.prototype.build = function() {

  for (var x in this.form_structure) {

    var new_element = document.createElement("input");

    new_element.setAttribute("type",this.form_structure[x].type);
    new_element.setAttribute("name",(this.form_structure[x].name ? this.form_structure[x].name : x));
    new_element.setAttribute("value",this.form_structure[x].value);

    this.form_root.appendChild(new_element);

  }

}

/**
 * Attach the form to an existing element.
 */
HO_Submission_Form.prototype.attach = function(tag) {

  var js_root = document.getElementById(tag);

  js_root.appendChild(this.form_root);

}

/**
 * Submit the form.
 */
HO_Submission_Form.prototype.submit = function() {

  this.form_root.submit();

}

/*************************************************************/

/**
 * Validate form input based on a JSON structure.
 *
 * @param json The structure of the form.
 */
function HO_Form_Validator(json_form) {

  this.form_structure = json_form;

}

/**
 * Check to see if an email address is valid.
 *
 * @param string An email address to validate.
 */
HO_Form_Validator.prototype.validate_email = function(address) {

  var result = false;
  var ndxAt = ndxDot =  0;

  var ndxAt = address.indexOf("@");
  var ndxDot = address.indexOf(".");
  var ndxDot2 = address.lastIndexOf(".");

  if ((ndxDot < 0) || (ndxAt < 0)) {

    alert("Your email address lacks a '.' or '@'.\n\nThe valid format is 'you@domain.suffix.'");

  } else if ( (ndxDot2 - 3) <= ndxAt) {

    alert("You may be missing your domain name.\n\nThe format is 'you@dom.suf'");

  } else {

    result = true;

  }

  return result;

}

/**
 * Check the form input fields.
 */
HO_Form_Validator.prototype.validate_form = function() {

  var errorMsg = "";
  var returnValue = true;

  for (var x in this.form_structure) {

    var thisElement = document.getElementById(x);

    // check to see if we have a confirm field
    if (this.form_structure[x].confirm) {

      var thisElementConfirm = document.getElementById("confirm_" + x);

      if (thisElement.value != thisElementConfirm.value) {

        errorMsg = errorMsg + "The values entered for " + this.form_structure[x].description + " do not match.\n";

        returnValue = false;

      }

    }

    // if it's text, check to make sure it's not empty
    if (!this.form_structure[x].empty && thisElement.value == "") {

      errorMsg = errorMsg + "You must enter a value for " + this.form_structure[x].description + "\n";

      returnValue = false;

    }

    // do any special processing
    switch (this.form_structure[x].type) {

      case "email":

        if (!this.validate_email(thisElement.value)) {

          returnValue = false;

        }

        break;

      case "password":

        if (thisElement.value.length < 6 && !(this.form_structure[x].empty && thisElement.value.length == 0)) {

          errorMsg = errorMsg + "Your password must be at least 6 characters long.\n";

          returnValue = false;

        }

        break;

      case "checkbox":

        if (this.form_structure[x].mandatory && !thisElement.checked) {

          errorMsg = errorMsg + "You must check the " + this.form_structure[x].description + " field.\n";

          returnValue = false;

        }

        break;

      case "select":

        if (!this.form_structure[x].empty && thisElement.selectedIndex == 0) {

          errorMsg = errorMsg + "You must select a value for " + this.form_structure[x].description + ".\n";

          returnValue = false;

        }

        break;

      case "tri_date":

        var js_day = document.getElementById(x + "_day");
        var js_month = document.getElementById(x + "_month");
        var js_year = document.getElementById(x + "_year");

        if (!( (js_day.selectedIndex > 0 && js_month.selectedIndex > 0 && js_year.selectedIndex > 0) || (js_day.selectedIndex == 0 && js_month.selectedIndex == 0 && js_year.selectedIndex == 0) )) {

          errorMsg = errorMsg + "You must enter a complete date for " + this.form_structure[x].description + ".\n";

          returnValue = false;

        }

        break;

      default:

        break;

    }

  }

  // display any errors that we've accumulated
  if (errorMsg != "") {

    alert(errorMsg);

  }

  return returnValue;

}

function getWindowWidth() {

  var width = document.documentElement && document.documentElement.clientWidth ||
              document.body && document.body.clientWidth ||
              document.body && document.body.parentNode && document.body.parentNode.clientWidth ||
              0;

  return width;

}

function getWindowHeight() {

  var height = document.documentElement && document.documentElement.clientHeight ||
               document.body && document.body.clientHeight ||
               document.body && document.body.parentNode && document.body.parentNode.clientHeight ||
               0;

  return height;

}

function centeredWindow(url,name,width,height,scrollbars,resizeable) {

  var xPos = (screen.availWidth / 2) - (width / 2);
  var yPos = (screen.availHeight / 2) - (height / 2);

  var options = "width=" + width + ",height=" + height + ",resizeable=" + resizeable +",scrollbars=" + scrollbars + ",left=" + xPos + ",top=" + yPos;

  window.open(url,name,options);

}

function openPrivacyWindow() {

  centeredWindow(howf_base_directory + "legal.php?action=privacy","legalWindow",600,400,1,1);

  return false;

}

function openTermsWindow() {

  centeredWindow(howf_base_directory + "legal.php?action=legal","legalWindow",600,400,1,1);

  return false;

}

function clearemail() {

  var js_email = document.getElementById("email");

  if(js_email.value == "email address") {
    js_email.value = "";
  }

}

function menu_toggle(id,action) {

  // exclude unsupported browsers
  if (document.getElementById) {

    var obj = document.getElementById("navbutton" + id);

    obj.src = "graphics/button" + id + "_" + action + ".gif";

  }

}

var current = "";

function showInstructions() {

  // if something is showing, hide it
  if (current != "") {
    hideInstructions();
  }

  var chosenId = document.getElementById("selectPage").options[document.getElementById("selectPage").selectedIndex].value;

  var chosenObject = document.getElementById(chosenId);

  if (chosenObject) {

    chosenObject.style.display = "block";

    current = chosenId;

  }

}

function hideInstructions() {

  var currentObject = document.getElementById(current);

  if (currentObject) {

    currentObject.style.display = "none";

    current = "";

  }

}

function showLearnMore() {

  var currentObject = document.getElementById(current);

  if (currentObject) {

    currentObject.style.display = "block";

    current = "";

  }

}

function setCookie(name,value,expires,path,domain,secure) {

  // set time, it's in milliseconds
  var today = new Date();
  today.setTime(today.getTime());

  /*
  if the expires variable is set, make the correct
  expires time, the current script below will set
  it for x number of days, to make it for hours,
  delete * 24, for minutes, delete * 60 * 24
  */
  if (expires) {
    expires = expires * 1000 * 60 * 60 * 24;
  }

  var expires_date = new Date(today.getTime() + (expires));

  document.cookie = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "" );

}

function deleteCookie(name,path,domain ) {

  if (getCookie(name)) {
    document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
  }

}

function getCookie( check_name ) {

  // first we'll split this cookie up into name/value pairs
  // note: document.cookie only returns name=value, not the other components
  var a_all_cookies = document.cookie.split(';');
  var a_temp_cookie = '';
  var cookie_name = '';
  var cookie_value = '';
  var b_cookie_found = false; // set boolean t/f default f

  for (i = 0; i < a_all_cookies.length; i++) {

    // now we'll split apart each name=value pair
    a_temp_cookie = a_all_cookies[i].split('=');

    // and trim left/right whitespace while we're at it
    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

    // if the extracted name matches passed check_name
    if (cookie_name == check_name) {

      b_cookie_found = true;

      // we need to handle case where cookie has no value but exists (no = sign, that is):
      if (a_temp_cookie.length > 1) {
        cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
      }

      // note that in cases where cookie is initialized but no value, null is returned
      return cookie_value;
      break;

    }

    a_temp_cookie = null;
    cookie_name = '';

  }

  if (!b_cookie_found) {
    return null;
  }

}


function initGH(divs) {

  for (var d = 0; d < divs.length; d++) {

    var navImages = document.getElementById(divs[d]).getElementsByTagName("a");
    var imageArray = new Array();
    var imageRE = /^(.*)(\..{3,4})$/;

    // add mouseover/out events to nav images
    for (var i = 0; i < navImages.length; i++) {

      navImages[i].firstChild.onmouseover = imageSwitch;
      navImages[i].firstChild.onmouseout = imageSwitch;

      var data = imageRE.exec(navImages[i].firstChild.src);

      imageArray[i] = data[1] + "_on" + data[2];

    }

    // preload images
    for (var j = 0; j < imageArray.length; j++) {

      var preloadImage = new Image();
      preloadImage.src = imageArray[j];

    }

  }

}


function imageSwitch(e) {

  var target;

  if (!e) var e = window.event;

  if (e.target) {
    target = e.target;
  } else if (e.srcElement) {
    target = e.srcElement;
  }

  // for safari, if its a text node, get the parent
  if (target.nodeType == 3) {
    target = target.parentNode;
  }

  if (e.type == "mouseover") {

    var imgRE = /^(.*)(\..{3,4})$/;

    if (imgRE.test(target.src)) {

      var data = imgRE.exec(target.src);

      target.src = data[1] + "_on" + data[2];

    }

  } else {

    var imgRE = /^(.*)_on(\..{3,4})$/;

    if (imgRE.test(target.src)) {

      var data = imgRE.exec(target.src);

      target.src = data[1] + data[2];

    }

  }

}