/**
 * This script contains general purpose string and form input manipulation and validation functions.
 */

/**
 * Trim function that eliminates whitespace at the begging and end of "theString". Returns the modified string.
 */
function trim (theString) {
  theString = theString.replace(/^\s+/g,"");
  theString = theString.replace(/\s+$/g,"");
  return theString;
}

/**
 * Returns true only is the length of "theString" is greater than or equal to "minLength".
 */
function minimumLength (theString,minLength) {
  theString = trim (theString);
  if (theString.length < minLength) {
    return false;
  }
  return true;
}

/**
 * Eliminates non-numeric characters from theString. Returns the modified string.
 */
function onlyNumbers (theString) {
  theString = theString.replace(/[^0-9]/g,"");
  return theString;
}

/**
 * Takes a selectbox form object as input: "selectFormObj". Returns true only if the form value of "selectFormObj" has a string length greater than 1. The assumption is made that valid selections have string length greater than 1 and invalid values have a string length of zero.
 */
function validOptionSelected (selectFormObj) {
  theValue = getSelectionValue(selectFormObj);
  if (!minimumLength(theValue,1)) {
    return false;
  }
  return true;
}

/**
 * Takes a selectbox form object as input: "selectFormObj". Returns the value of the item selected in the form box
 */
function getSelectionValue (selectFormObj) {
  return trim(selectFormObj.options[selectFormObj.selectedIndex].value);
}

/**
 * String equality comparison function. Return true if they are the same, false if they are not.
 */
function compareValues (stringValue1,stringValue2) {
  compareValue = (stringValue1==stringValue2);
  return compareValue;
}

/**
 * Takes a radioset as input: "radioFormObj". Determines if the user selected one of the options.
 */
function radioButtonSelected (radioFormObj) {
  for (radioIndex=0;radioIndex < radioFormObj.length;radioIndex++) {
    if (radioFormObj[radioIndex].checked) {
      return true;
    }
  }
  return false;
}

/**
 * Checks for only alphanumeric characters. Returns boolean value.
 */
function noSpecialChars (theString) {
  loc = theString.search(/[^0-9a-zA-Z]/);
  if (loc==-1) return true;
  else return false;
}

/**
 * Takes a form object and a value to search for. Returns the index of the value if it found in the form object.
 */
function getValueIndex (form_obj, obj_val) {
  for (lcv=0;lcv < form_obj.length;lcv++) {
    if (form_obj.options[lcv].value == obj_val) return lcv;
  }
  return 0;
}

/** 
 * For counting chars in a form field. Ex: hotel_reserve.html
 */
function textCounter(field, countfield, maxlimit) 
{
  if (field.value.length > maxlimit) {
    field.value = field.value.substring(0, maxlimit); 
  }
  else {
    countfield.value = maxlimit - field.value.length;
  }
}
