/*
 * These are validation functions for Plan Link (OPTLink)
 * They are used to ensure that values are valid when entered on a
 * form and submitted to a processing page.
 *
 * Currently these are helper functions, but it may make sense in the future
 * to encapsulate this functionality into a Vaildation class of some sort
 *
 * Cliff Green
 */

var _sMsg = "The following fields are missing or invalid:\n";
var _bResult = true;
var _isNS4 = false;

var _sName = navigator.appName;
var _sVer = parseInt(navigator.appVersion);

_isNS4 = (_sName == "Netscape" && _sVer == 4);

//write a message to the alert box
function writeMessage( msg, elem ) {
	_sMsg += "\n - " + msg;
	if( _bResult ) {
		if( elem != null ) {
			setFocus(elem);
		}
		_bResult = false;
	}
	/* get the name of the element and change the class of the 
	 * span tag to invalidField to show that it is invalid
	 * highlighted red
	 */
	if( ! _isNS4 ) {
		if( elem != null ) {
			//try {
				var sLabelName = elem.name + "Label";
				//alert( elem.type + ":  " + elem.name);
				obj = getObject(sLabelName);
				if( obj != "undefined" && obj != null ) {
					obj.className = "invalidField";
				}
			/*} catch ( err ) {
				//just skip it
			}*/
		}
	}
}

//initialize the variables to begin validation
function beginValidation(oForm) {
	_sMsg = "The following fields are missing or invalid:\n";
	_bResult = true;
	
	//remove any style sheet that we have applied to 
	//text boxes on the form from a previous validation attempt
	if( ! _isNS4 ) {
		//try {
			for( i=0; i < oForm.elements.length; i++ ) {
				sElemType = oForm.elements[i].type;
				if( sElemType == "text" || sElemType == "select-one" || sElemType == "radio" || sElemType == "password" || sElemType == "checkbox") {
					//alert( oForm.elements[i].type + ":  -" + oForm.elements[i].name);
					sLabelName = oForm.elements[i].name + "Label";
					var obj = getObject(sLabelName);
					if( obj != "undefined" && obj != null ) {
						obj.className = "";
					}
				}
			}
		/*} catch( err ) {
			//do nothing just move on
		}
		*/
	}
}


//get the object that is being referenced; cross browser
function getObject(name) {
	if (document.layers) {
    return document.layers[name];
  } else if (document.all) {
    return document.all(name);
  } else if (document.getElementById) {
    return document.getElementById(name);
  }
}
//check to see if the form should be submitted
//@param	oForm			document.formname
function checkForSubmit( oForm ) {
	if( _bResult ) {
		oForm.submit();
	} else {
		alert( _sMsg );
	}
}

function getValidationResult() {
	return _bResult;
}

function getValidationMessage() {
	return _sMsg;
}

//is this a float
function isFloat( val ) {
	if( !isValue(val) ) {
		return false;
	} else {
		return !isNaN( parseFloat( val ));
	}
}

function isFloatRE( val ) {
	pattern = /^\d{1,3}(,?\d{3})*\.?(\d{1,2})?$/;
	var matchArray = val.match(pattern); // is the format ok?
	
  if (matchArray == null) {
    return false;
  }	else { 
		return true;
	}
}

//is this a number
function isInteger( val ) {
	if( !isValue( val ) ) {
		return false;
	} else {
		return !isNaN( parseInt( val ));
	}
}

//is integer and is of length (len)
function isIntegerOfLength( val, len ) {
	return (isInteger(val) && val.length == len);
}

function isPositiveInteger( val ) {
	return (isInteger(val) && val > 0);
}

//is there a value in the field
function isValue( val ) {
	var temp = val.replace(/^\s+/g, '').replace(/\s+$/g, '');
	if( temp.length == 0 ) {
		return false;
	} else {
		return true;
	}
}

function isValueOfLength( val, len ) {
	return (isValue(val) && val.length >= len);
}

function trimValue( val ) {
	return val.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

//is string a date?
function isDate(dateStr) {
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        return false;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        return false;
    }

    if (day < 1 || day > 31) {
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            return false;
        }
    }
    return true; // date is valid
}

//true if date [val] is after today
function isDateInFuture( val ) {
	today = new Date();		//create today
	compareDate = (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear();
	
	iResult = compareDates(val, compareDate);
	
	if( iResult == -1 || iResult == 0) {
		return true;			//date is after today or is today
	} else {
		return false;			//date before today
	}
}

// compares two dates
// returns -1 for date1 after date2
// 0 if dates are the same
// 1 if date1 before date2
function compareDates( date1, date2 ) {
	//break into values
	if( date1.indexOf("/")!=-1 ) {
		startSep = "/";
	} else {
		startSep = "-";
	}
	startVal = date1.split(startSep);
	
	if( date2.indexOf("/")!=-1 ) {
		endSep = "/";
	} else {
		endSep = "-";
	}
	endVal = date2.split(endSep);
	//creates a number in the format yyyymmdd to compare dates (i.e., 20020603)
	startNum = (parseInt((startVal[2] * 10000)) + parseInt((startVal[0] * 100)) + parseInt((startVal[1])));
	endNum = (parseInt((endVal[2] * 10000)) + parseInt((endVal[0] * 100)) + parseInt((endVal[1])));
	
	if( endNum > startNum ) {
		return 1;		
	} else if( endNum == startNum ) {
		return 0;
	} else {
		return -1;
	}
}

//does the parameter contain only alpha numeric characters
function isAlphaNumeric( val ) {
	if( val.search( /^[a-zA-Z0-9]+$/ )==-1 ) {
		return false;
	} else {
		return true;
	}
}

function containsSpecialCharacters( val ) {
	if( !isValue ) {
		return false;
	}
	if( val.search( /[^A-Za-z0-9 ]/ ) == -1 ) {
		return false;
	} else {
		return true;
	}
}

//is this a valid social security number??
function isSSN( val ) {
	pattern = /^\d{3}\-\d{2}\-\d{4}$/;
	var matchArray = val.match(pattern); // is the format ok?
	
  if (matchArray == null) {
    return false;
  }	else { 
		return true;
	}
}	


//is this a valid social security number??
function isZipCode( val ) {
	pattern = /^(\d{5}\-\d{4})|(\d{5})$/;
	var matchArray = val.match(pattern); // is the format ok?
	
  if (matchArray == null) {
    return false;
  }	else { 
		return true;
	}
}	

//is this a valid e-mail address??
function isEmail(value) {
  if (value.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
    return true;
  } else {
		return false;
  }
}

//is the value a valid phone number
function isPhoneNumber( areacode, exchange, number ) {
	if( !isInteger(areacode) || areacode.length < 3 ) {
		return false;
	}
	if( !isInteger(exchange) || exchange.length < 3 || exchange=="555") {
		return false;
	}
	if( !isInteger(number) || number.length < 4 ) {
		return false;
	}
	return true;
}
	

/*
 * These functions are common form functions that help set focus, select text, build a message
 *
 * Cliff Green
 */
 
//sets focus of the element that is passed and selects its text, if there is any
function setFocus( oElem ) {
	if( oElem.visible == true ) {
		oElem.focus();
	}
	if( oElem.type=="text" ) {
		oElem.select();
	}
}
	
	


	


