
function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
 var objRegExp = /^(\s*)$/;
    //alert("passed in strValue = " + strValue + "  typeof = " + typeof(strValue));
    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0) {
            //alert("returning 1 " + strValue);
            return strValue;
       }
    }
    //alert("got to 2");
   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
    //alert("returning 3 " + strValue);
  return strValue;
}

function trimInputVal(inputObject) {
    if (inputObject.type == "text") {
        return trimAll(inputObject.value);
    }
    else if (inputObject.type == "file") {
        return trimAll(inputObject.value);
    }
    else {
        alert("input type is NOT text or file - it's a " + inputObject.type);
        return "";
    }
    return true;
}

function checkFormMaster(required, okClassName) {
    okArr = new Array();
    ok = true;
    for (zz = 0; zz < required.length; zz++) {
        //alert("Checking name = " + required[zz].name + " val = " + required[zz].value);
        if (zeroLengthInputVal(required[zz])) {
            okArr[zz] = 'f';
            //required[zz].style.backgroundColor = "#fffdcf";
            required[zz].className = required[zz].className + " inputRequired";
            //required[zz].style.border = "1px dashed red";
            //alert("Not OK: " + required[zz].name);
            ok = false;
        }
        else {
            okArr[zz] = 't';
            //required[zz].style.backgroundColor = "#ffffff";
            //required[zz].style.border = "";
            if (okClassName) {
                //alert("got okClassName");
                required[zz].className = okClassName;
            }
            else {
                //alert("didnt get okClassName");
                required[zz].className = "";
            }
        }
    }
    return ok;
}

function checkFormMasterNotRequiredJustFormatting(required, okClassName) {
    //alert("checkFormMasterNotRequiredJustFormatting");
    okArr = new Array();
    ok = true;
    for (zz = 0; zz < required.length; zz++) {
        //alert("Checking name = " + required[zz].name + " val = " + required[zz].value);
        if (!formattingOk(required[zz])) {
            //alert("not formattingok: " + required[zz].name);
            okArr[zz] = 'f';
            //required[zz].style.backgroundColor = "#fffdcf";
            required[zz].className = required[zz].className + " inputRequired";
            //required[zz].style.border = "1px dashed red";
            //alert("Not OK: " + required[zz].name);
            ok = false;
        }
        else {
            //alert("formattingok: " + required[zz].name);
            okArr[zz] = 't';
            //required[zz].style.backgroundColor = "#ffffff";
            //required[zz].style.border = "";
            if (okClassName) {
                //alert("got okClassName");
                required[zz].className = okClassName;
            }
            else {
                //alert("didnt get okClassName");
                required[zz].className = "";
            }
        }
    }
    return ok;
}

function dateBeforeToday(inputObject) {
    // assume format mm-dd-yyyy
    if (!zeroLengthInputVal(inputObject)) {
        var str = new String(inputObject.value);
        var m = str.substring(0,2);
        var d = str.substring(3, 5);
        var y = str.substring(6, 10);
        var inpDate = new Date;
        inpDate.setDate(eval(d));
        inpDate.setMonth(eval(m) - 1);
        inpDate.setFullYear(eval(y));
        //alert("inpDate = " + inpDate);
        var today = new Date;
        today.setHours(0);
        today.setMinutes(0);
        //alert("today = " + today);
        return inpDate < today;
    }
    else {
        return false;
    }
}

function formattingOk(inputObject) {
    //alert("inputObject.title = " + inputObject.title + " inputObject.name = " + inputObject.name);
    var str = trimAll(inputObject.value);
    if (str.length == 0) {
        return true;
    }
    else {
        if (inputObject.title == 'currency') {
            return validateCurrency(str);
        }
        else if (inputObject.title == 'email') {
            return emailCheck(str);
        }
        else if (inputObject.title == 'currencysmall') {
            return validateCurrencySmall(str);
        }
        else if (inputObject.title == 'posint') {
            return validatePositiveInt(str);
        }
        else if (inputObject.title == 'CurrencyOrPosInt') {
            return validateCurrencyOrPosInt(str);
        }
        else if (inputObject.title == 'number') {
            //alert("Checking number");
            return validateAnyNumber(str);
        }
        else if (inputObject.title == 'integer') {
            //alert("Checking integer");
            return validateInteger(str);
        }
        return true;
    }
}

function zeroLengthInputVal(inputObject) {

    /*output = "";
    for (obj in inputObject) {
        output += obj + " ";
    }
    alert(output);*/

    //alert("inputObject.class = " + inputObject.class);
    //alert("zeroLengthInputVal(" + inputObject + ") type = " + inputObject.type + " value = " + inputObject.value);
    if ((inputObject.type != "text") && (inputObject.type != "password") && (inputObject.type != "file") && (inputObject.type != "textarea") && (inputObject.type != "hidden")  && (inputObject.type != "select-one") ){
        alert("input type is NOT text or file or textarea or hidden or password: " + inputObject.type + "   name = " + inputObject.name);
        return true;
    }
    else {
        var str = trimAll(inputObject.value);
        if (str.length == 0) {
            return true;
        }
        else if (inputObject.type == "select-one") {
            //alert("Checking a select-one - str = " + str);
            if (str == '-Select-') {
                //alert("It equals -Select-   returning true");
                return true;
            }
        }
        return !formattingOk(inputObject);
    }
}

function  validatePositiveInt( strValue ) {
  var objRegExp  =  /(^\d*$)/;
    return objRegExp.test(strValue);
}

function  validateAnyNumber( strValue ) {
  var objRegDecimal  = /(^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$)/;
  var objInteger = /(^([-]|[0-9])[0-9]*$)/;
    return objRegDecimal .test(strValue) || objInteger.test(strValue);
}

function validateInteger(strValue) {
  var objRegExp  =  /(^([-]|[0-9])[0-9]*$)/;
//      ^([-]|[0-9])[0-9]*$
    return objRegExp.test(strValue);
}

function  validateCurrencySmall( strValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  =  /(^\d\d*\.\d*$)/;

  //check for numeric characters
  return objRegExp.test(strValue);
}

function  validateCurrency( strValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  =  /(^\d\d*\.\d\d$)/;

  //check for numeric characters
  return objRegExp.test(strValue);
}

function  validateCurrencyOrPosInt( strValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  =  /(^\d\d*\.\d\d$)/;

  //check for numeric characters
  return validateCurrency(strValue) || validatePositiveInt(strValue);
}

function emailCheck (emailStr) {
    //alert("emailCheck(" + emailStr + ")");
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("The email name doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("The email address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

function spewAttrs(obj) {
    str = "Attrs for " + obj.nodeName + "\n\n";
    for (attr in obj) {
        str += attr;
        if (obj.getAttribute(attr) == null) {
            str += " (null)";
        }
        else {
            str += "<font color='red'> = " + obj.getAttribute(attr) + "</font>";
        }
        str += "<br/>"
    }
    //var div = document.getElementById("debugDiv");
    var newDiv = document.createElement("div");
    newDiv.setAttribute("id", "spew");
    newDiv.style.top = "100px";
    newDiv.style.left = "100px";
    newDiv.style.width = "250px";
    newDiv.style.height = "400px";
    newDiv.style.position = "absolute";
    newDiv.style.border = "3px double blue";
    newDiv.style.backgroundColor = "#CCCCCC";
    newDiv.style.padding = "10px";
    newDiv.style.overflow = "auto";

    /*str = "new str<br/>";
    for (attr in obj) {
        str += attr + "<br/>";
        str += " - " + obj.getAttribute(attr) + "<br/>";
    }*/

    newDiv.innerHTML = str;


    //var copyDiv = document.getElementById("spew");
    //alert("copyDiv = " + copyDiv);
    var mybody = document.getElementsByTagName("body")[0];
    mybody.appendChild(newDiv);
}

