function isChar(c)
{
    return ( ( c >= "a" && c <= "z" ) || ( c >= "A" && c <= "Z" ) );
}

function isDigit(c) {
    return ( ( ( c >= "0" ) && ( c <= "9" ) ) || c==".")
}

function isNumeric(c) {
    return ( ( ( c >= "0" ) && ( c <= "9" ) ) )
}

function isAlphaNum( s )
    {
    var i;
    for ( i = 0; i < s.length; i++ )
        {
        var c = s.charAt( i );
        if ( !isNumeric( c ) && !isChar( c ) ) return false;
        }
    return true;
    }

/* Takes the passed String and checks it against the RegEx to determine if it passes
 * There can be any number of spaces, followed by 1-9 digits, 
  * then any number of spaces, followed by a comma. NOTE: a comma cannot end the list.
 */
function isNumberList( s )
    {
    var numListRegex = /^(?:\s*\d{1,9}\s*,)*(?:\s*\d{1,9}\s*)$/;
    return numListRegex.test( s );
    }

function isDecimal(s) {
    if ( s == "." ) return false;
    var i;
    var dots = 0;
    for ( i = 0; i < s.length; i++ )
    {
        var c = s.charAt(i);
        if ( c == "." ) 
        {
            dots++;
            if ( dots > 1 ) return false;
        }    
        if ( ! isDigit(c) ) return false;
    }
    return true;
}

function isInteger(s) {
    var i;
    for ( i = 0; i < s.length; i++ )
    {
        var c = s.charAt(i);
        if ( ! isDigit(c) ) return false;
    }
    return true;
}

function isNumber(s) {
    var i;
    for ( i = 0; i < s.length; i++ )
    {
        var c = s.charAt(i);
        if ( ! isNumeric(c) ) return false;
    }
    return true;
}

function validateMoney(d)
{
    var i;
    i=d.indexOf(".");
    if( !isDecimal(d) ) return false;

    if(d.length>14)
    {
        if ( i == -1)
            return false;
        // Check that no more than 14 digits are on the left hand side
        if (i > 14)
            return false;
    }

    // Check for scale 2
    if ( i>-1 && (d.length-(i+1)) > 2)
        return false;

    return true;
}

function validateDate(objName)
{
    var strDate;
    var strDateArray;
    var strDay;
    var strMonth;
    var strYear;
    var intday;
    var intMonth;
    var intYear;
    var datefield = objName;
    var strSeparator="/";
    var err = 0;
    strDate = datefield.value;

    if (strDate.length < 1)
    {
        return true;
    }

    if (strDate.indexOf(strSeparator) != -1)
    {
        strDateArray = strDate.split(strSeparator);
        if (strDateArray.length != 3)
        {
            err = 1;
            return false;
        }
        else
        {
            strMonth = strDateArray[0];
            strDay = strDateArray[1];
            strYear = strDateArray[2];
        }
    }
    else
    {
        return false;
    }

    if (strYear.length != 4 || strMonth.length != 2 || strDay.length != 2)
    {
        err=1;
        return false;
    }

    intday = parseInt(strDay, 10);
    if (isNaN(intday))
    {
        err = 2;
        return false;
    }

    intMonth = parseInt(strMonth, 10);
    if (isNaN(intMonth))
    {
        err = 3;
        return false;
    }

    intYear = parseInt(strYear, 10);
    if (isNaN(intYear))
    {
        err = 4;
        return false;
    }

    if (intMonth>12 || intMonth<1)
    {
        err = 5;
        return false;
    }

    if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1))
    {
        err = 6;
        return false;
    }

    if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1))
    {
        err = 7;
        return false;
    }

    if (intMonth == 2)
    {
        if (intday < 1)
        {
        err = 8;
        return false;
        }

        if (LeapYear(intYear) == true)
        {
            if (intday > 29)
            {
                err = 9;
                return false;
            }
        }
        else
        {
            if (intday > 28)
            {
                err = 10;
                return false;
            }
        }
    }

    return true;
}

function LeapYear(intYear)
{
    if (intYear % 100 == 0)
    {
        if (intYear % 400 == 0) { return true; }
    }
    else
    {
        if ((intYear % 4) == 0) { return true; }
    }
    return false;
}

function isDate(s) {
    return validateDate(s);
}

// ... 03/07/2003 CWM - add time validation
// ... ensures time is in H, HH, HH:MM, or H:MM format
function isTime( s, ap, required )
    {
    var lengthCheck = s.value.length;

    // ... if not required and empty, get out now
    if ( !required && lengthCheck == 0 ) 
        {
        return true;
        }
    
    // ... do some basic validation before checking the format so we don't get a bad time
    if ( lengthCheck == 0  || lengthCheck == 3 || lengthCheck > 5 )
        {
        // ... no possible way this is the correct format, since the allowable formats are 1, 2, 4, and 5 chars
        return false;
        }
        
    if ( lengthCheck > 2 && s.value.indexOf(":") == -1 )
        {
        // ... no possible way this is the correct format, since times > 2 chars require a colon
        return false;
        }

    // ... if AM/PM isn't selected, get out now
    if ( ap.value == 0 )
        {
        return false;
        }
        
    var timeFormat = /^(\d{1,2}):?(\d{2})?$/;
    var matchArray = s.value.match( timeFormat );
    if ( matchArray == null )
        {
        return false;
        }

    var hour = matchArray[1];
    var minute = matchArray[2];

    if ( hour < 1  || hour > 12 )
        {
        return false;
        }

    if ( minute < 0 || minute > 59 )
        {
        return false;
        }

    return true;
    }

function validateDecimal(d, decimalPlaces)
    {
    if( decimalPlaces == undefined )
        {
        decimalPlaces = 2;
        }
    
    var i;
    i = d.indexOf( "." );
    if( !isDecimal( d ) ) return false;     

    // ... if there's no decimal point, just make sure the value isn't too big
    if ( i == -1 ) return d.length <= 5;
    
    // ... if there's a decimal point, we have to make sure there are 
    // ... at least one and at most decimalPlaces to the right of it
    var lhs = d.substr( 0, i );
    var rhs = d.substr( i + 1, d.length - i - 1 );
    return lhs.length <=5 && rhs.length > 0 && rhs.length <= decimalPlaces;
    }

function validatePhone( phone )
    {
    if( !isNumber( phone ) )return false;
    
    if( phone.length > 0 && phone.length != 7 && phone.length != 10 && phone.length != 11 ) return false;

    return true;
    }

function trim(aString)
{
    var trimedStr = aString;
    while(trimedStr.indexOf(" ") == 0){
        trimedStr = trimedStr.substr(1);
    }

    while(trimedStr.lastIndexOf(" ") == trimedStr.length){
        trimedStr = trimedStr.substr(0,trimedStr.length-1);
    }
	
    return trimedStr;
}

function lrtrim(s)
{
     var l=0; var r=s.length -1;
     while(l < s.length && s[l] == ' ')
     {	l++; }
     while(r > l && s[r] == ' ')
     {	r-=1;	}
     return s.substring(l, r+1);

}

function requiredFieldCheck(field, fieldName)
{
    fieldVal = trim(""+field.value);

    if ( fieldVal.length == 0)
        {
        alert( fieldName + " is a required field." );
        return false;
        }
    return true;
}

function nonReqDigit(fieldName , fld){
    fieldVal=trim(fld.value);
    
//  alert(fieldName + " : " + fieldVal);

    if(fieldVal.length > 0 && !isDecimal(fieldVal)){
        alert(fieldName + " is a numeric field");
        return true;
    }
    return false;
}
function nonReqDate(fieldName, fld){
//  alert("chkDate:" + fieldName + " : " + fieldVal);

    if(!validateDate(fld)){
        alert("Invalid date: " + fieldName);
        return true;
    }
    return false;
}

function display_date(){
    var months=new Array(13);
    months[1]="January";
    months[2]="February";
    months[3]="March";
    months[4]="April";
    months[5]="May";
    months[6]="June";
    months[7]="July";
    months[8]="August";
    months[9]="September";
    months[10]="October";
    months[11]="November";
    months[12]="December";
    var time=new Date();
    var lmonth=months[time.getMonth() + 1];
    var date=time.getDate();
    var year=time.getYear();

    // Y2K Fix by Isaac Powell
    // http://onyx.idbsu.edu/~ipowell

    if ((navigator.appName == "Microsoft Internet Explorer") && (year < 2000))
        year="19" + year;
    if (navigator.appName == "Netscape")
        year=1900 + year;
    document.write(lmonth + " ");
    document.write(date + ", " + year + " ");
}

function display_time () {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds()
    var timeValue = "" + ((hours >12) ? hours -12 :hours)
    if (timeValue == "0") timeValue = 12;
    timeValue += ((minutes < 10) ? ":0" : ":") + minutes
    timeValue += (hours >= 12) ? " P.M." : " A.M."
    document.write(timeValue);
}

function validLdapUsername( ldapUsername ) {
	var invalidCharactersRegExp="[\"\\[\\]:;|=+\\*\\?<>\\/\\\,]";
	
	if ( ldapUsername.match(invalidCharactersRegExp) ) {
		alert( 'The LDAP Username cannot contain any of the following characters: " [ ] : ; | = + * ? < > / \ ,' );
		return false;
	}
	
	return true;
}

function CheckEmail (emailStr) {
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	 alert("Email address 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("Email username is invalid.")
		return false
	}

	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("Email Destination IP address is invalid!")
				return false
			}
		}
		return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Email domain name is invalid.")
		return false
	}

	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<1) {
	   alert("The email address must end with a minimum of one letter.")
	   return false
	}

	if (len<2) {
	   var errStr="The Email address is missing a hostname!"
	   alert(errStr)
	   return false
	}

	return true;
}

function helpWindow( loc )
    {
    window.open( loc, '',
                    'height=700' +
                    ',width=800' +
                    ',toolbar=yes,status=yes,menubar=yes,scrollbars=yes' +
                    ',location=yes,directories=yes,resizable=yes,screenX=50,screenY=50' );
    }

function certWindow( loc )
    {
    window.open( loc, '',
                    'height=700' +
                    ',width=800' +
                    ',toolbar=no,status=no,menubar=no,scrollbars=yes,location=no,' +
                    'directories=no,dependent=yes,resizable=yes,screenX=50,screenY=50' );
    }

function validateEmail(stringValue) {
// check if email field is blank
if (stringValue=="")
{
  return true;
}
return CheckEmail(stringValue);
}

function validSRN(field){
    var ErrMsg = "Session reference numbers must be numbers only, up to 15 digits in length.  Please re-enter";
    var fieldVal = trim(""+field.value);
    if(fieldVal.length == 0)
        return true;
    if(!isNumber(fieldVal)){
        alert(ErrMsg);
        return false;
    }
    if(fieldVal.length <= 15)
        return true;
        
    alert(ErrMsg);
    return false;
}

/* Validate the passed fields as an equation */
function validateEquation( opField1, opField2, operatorField )
    {
    var isValid = true;
    var op1Value = opField1.value.toUpperCase();;
    var op2Value = opField2.value.toUpperCase();
    var operatorValue = operatorField.value;

    if ( op1Value != "" || operatorValue != "" || op2Value != "" )
        isValid = ( ( op1Value == "CREDITS" || op1Value == "HOURS" || isDecimal( op1Value ) ) &&
                    operatorValue != "" && 
                    ( op2Value == "CREDITS" || op2Value == "HOURS" || isDecimal( op2Value ) ) );

    return isValid;
    }
    
/* return whether 1) dateField1's value is less than dateField2's and 2) dateField1's value <= dateField2's */
function validateDateRange( dateField1, dateField2 )
    {   
    var isValid = true;
    var date1 = dateField1.value;
    var date2 = dateField2.value;
    
    if ( date1 !== "" || date2 != "" )
        {
        // ... if either is present, both have to be present
        if ( date1 == "" || date2 == "" )
            {
            isValid = false;
            }
        else
            {
            isValid = isDate( dateField1 ) && isDate( dateField2 ) && datesInOrder( date1, date2 );
            }
        }
        
    return isValid;
    }
    
/* 
    verifies that date1 is on or before date2 
    NOTE: this function assumes that date1 and date2 are valid dates - to verify this call 
    isDate() on each field which these values come from before calling this function
*/
function datesInOrder( date1, date2 )
    {
    var separator = "/";
    var date1Array = date1.split( separator );
    var date2Array = date2.split( separator );
    
    var month1 = parseInt( date1Array[0], 10 );
    var month2 = parseInt( date2Array[0], 10 );
    var day1 = parseInt( date1Array[1], 10 );
    var day2 = parseInt( date2Array[1], 10 );
    var year1 = parseInt( date1Array[2], 10 );
    var year2 = parseInt( date2Array[2], 10 );
    
    return ( year1 < year2 ) || 
                ( year1 == year2 && month1 < month2 ) || 
                ( year1 == year2 && month1 == month2 && day1 <= day2 );
    }
    
/*
verifies that time1 is on or before time2
NOTE: this function assumes that date1 and date2 are valid dates - to verify this call isTime()
on each field which these values come from before calling this function
*/
function timesInOrder( time1, time1AP, time2, time2AP )
    {
    var separator = ':';
    var time1Array = time1.split( separator );
    var time2Array = time2.split( separator );
    
    var hour1 = parseInt( time1Array[0], 10 );
    var minute1 = ( time1Array[1] == null ? parseInt( 0, 10 ) : parseInt( time1Array[1], 10 ) );
    var hour2 = parseInt( time2Array[0], 10 );
    var minute2 = ( time2Array[1] == null ? parseInt( 0, 10 ) : parseInt( time2Array[1], 10 ) );    
    
    // ... adjust to a 24-hour clock for the comparison 
    if ( time1AP == 'am' && hour1 == 12 )
        hour1 = parseInt( 0, 10 );
    else if ( time1AP == 'pm' && hour1 != 12 )
        hour1 += 11;
    if ( time2AP == 'am' && hour2 == 12 )
        hour2 = parseInt( 0, 10 );
    else if ( time2AP == 'pm' && hour2 != 12 )
        hour2 += 11;
        
    return ( hour1 < hour2 ) ||
                ( hour1 == hour2 && minute1 <= minute2 );
    }
    
function validateNumericRange( numberField1, numberField2 )
{
	var isValid = true;
	var num1 = lrtrim(""+numberField1.value);
	var num2 = lrtrim(""+numberField2.value);
	if ( num1 !== "" || num2 != "" )
	{
		// If either is present, both have to be present
		if ( num1 == "" || num2 == "" )
		{
			isValid = false;
		}
		else
		{
			isValid = isDecimal( num1 ) && isDecimal( num2 ) && ( parseFloat( num1, 10 ) <= parseFloat( num2, 10 ) );
		}
	}
	return isValid;
}
    

function validateStringRange( string1, string2 )
{
	var isValid = true;
	var val1 = string1.value;
	var val2 = string2.value;
	if ( val1 !== "" || val2 != "" )
	{
		// If either is present, both have to be present
		isValid = ( val1 != "" && val2 != "" );
	}
	return isValid;
}
    
function singleField(field)
{
	var val=true;
	if(field.length > 0)
	{
		val = false;
	}
	return val;
}

function selectedCheckValue(field)
{
	var val=false;
	if(singleField(field))
	{
		return field.checked;
	}
	for(var i=0; i< field.length;i++)
	{
		if(field[i].checked)
		{
			val = val || field[i].checked;
		}
	}
	return val;
}

function reqCheckBoxValid(field, fieldName)
{
	if(!selectedCheckValue(field))
	{
	    alert("You must select a " + fieldName);
	    return false;
	}
	return true;
}

function toggleVisibility( id )
{
	return switchClass( id, "shown", "hidden" );
}

function toggleVisibilityBlock( id )
{
	return switchClass( id, "showBox", "hideBox" );
}

// If the element w/the passed ID is class1 make it class2 and vice versa
function switchClass( id, class1, class2 )
{
	var elem = document.getElementById( id );
	// Force to class1 if class2 isn't passed
	if ( class2 == undefined )
	{
		elem.className = class1;
	}
	else
	{
		elem.className = ( elem.className == class1 ? class2 : class1 );
	}
	return elem.className;
}
    
function toggleRequired( id )
{
	var oldClass = document.getElementById( id ).className;
	var newClass = switchClass( id, "optionalLabel", "requiredLabel" );
	doStar( id, oldClass, newClass );
}

function toggleRequiredAlignTop( id )
{
	var oldClass = document.getElementById( id ).className;
	var newClass = switchClass( id, "optionalLabelAlignTop", "requiredLabelAlignTop" );
	doStar( id, oldClass, newClass );
}

function setRequired( id )
{
	var oldClass = document.getElementById( id ).className;
	var newClass = switchClass( id, "requiredLabel" );
	doStar( id, oldClass, newClass );
}

function setNotRequired( id )
{
	var oldClass = document.getElementById( id ).className;
	var newClass = switchClass( id, "optionalLabel" );
	doStar( id, oldClass, newClass );
}

function setRequiredAlignTop( id )
{
	var oldClass = document.getElementById( id ).className;
	var newClass = switchClass( id, "requiredLabelAlignTop" );
	doStar( id, oldClass, newClass );
}

function setNotRequiredAlignTop( id )
{
	var oldClass = document.getElementById( id ).className;
	var newClass = switchClass( id, "optionalLabelAlignTop" );
	doStar( id, oldClass, newClass );
}
    
function doStar( id, oldClass, newClass )
{
	// Don't add the image if the class didn't change.
	if ( oldClass == newClass )
	{
		return;
	}
	var elem = document.getElementById( id );
	var image = '<img src="/images/asterisk.png" width="12" height="12" />';
	if ( newClass == "requiredLabel" || newClass == "requiredLabelAlignTop" )
	{
		// Put the image before the label.
		elem.innerHTML = image;
	}
	else
	{
		// Remove the image before the label.
		elem.innerHTML = "";
	}
}
    
function requireIfNotEmpty( elem, id )
{
	if ( elem.value == "" )
	{
		setNotRequired( id );
	}
	else
	{
		setRequired( id );
	}
}
    
function requireIfSelected( elem, id )
{
	if ( elem.selectedIndex == 0 )
	{
		setNotRequired( id );
	}
	else
	{
		setRequired( id );
	}
}

function requireIfNotEmptyAlignTop( elem, id )
{
	if ( elem.value == "" )
	{
		setNotRequiredAlignTop( id );
	}
	else
	{
		setRequiredAlignTop( id );
	}
}
    
function requireIfSelectedAlignTop( elem, id )
{
	if ( elem.selectedIndex == 0 )
	{
		setNotRequiredAlignTop( id );
	}
	else
	{
		setRequiredAlignTop( id );
	}
}
    
// script for expand/collapse with image of +/-
imgoutTANGO = new Image(9,9);
imginTANGO = new Image(9,9);
imgoutTANGO.src = "/images/expand.gif";
imginTANGO.src = "/images/collapse.gif";

//this switches expand collapse icons
function filterTANGO(imagename,objectsrc){
	if (document.images){
		document.images[imagename].src=eval(objectsrc+".src");
	}
}

//show OR hide function depends on if element is shown or hidden
function shohTANGO(id) { 	
	if (document.getElementById)
	{
		if (document.getElementById(id).style.display == "none")
		{
			document.getElementById(id).style.display = 'inline';
			filterTANGO(("img"+id),'imginTANGO');			
		}
		else
		{
			filterTANGO(("img"+id),'imgoutTANGO');
			document.getElementById(id).style.display = 'none';			
		}	
	}
	else
	{ 
		if (document.layers)
		{	
			if (document.id.display == "none")
			{
				document.id.display = 'inline';
				filterTANGO(("img"+id),'imginTANGO');
			}
			else
			{
				filterTANGO(("img"+id),'imgoutTANGO');	
				document.id.display = 'none';
			}
		}
		else
		{
			if (document.all.id.style.visibility == "none")
			{
				document.all.id.style.display = 'inline';
			}
			else
			{
				filterTANGO(("img"+id),'imgoutTANGO');
				document.all.id.style.display = 'none';
			}
		}
	}
}

// Used to limit the size of <textarea> - can also be used for <input type="text">
function limitTextTANGO(limitField, limitCount, limitNum)
{
	if (limitField.value.length > limitNum)
	{
		limitField.value = limitField.value.substring(0, limitNum);
	}
	else
	{
		limitCount.value = limitNum - limitField.value.length;
	}
}

// Used for 'Select All' and 'Clear All'
function checkState( elemArray, value )
{
	for ( var i = 0; i < elemArray.length; i++ )
	{
		if ( value )
		{
			checkBox( elemArray[i] );
		}
		else
		{
			uncheckBox( elemArray[i] );
		}
	}
}

function uncheckBox( elem )
{
	if ( elem != null )
	{
		if (elem.disabled != true)
		{
			elem.checked = false;
		}
	}
}

function checkBox( elem )
{
	if ( elem != null )
	{
		if (elem.disabled != true)
		{
			elem.checked = true;
		}
	}
}

// Used for 'Select All' and 'Clear All' when needing to change the state of a button based on selection
function checkStateChangeButtonStatus( elemArray, value, buttonToChangeState )
{
	if ( elemArray != null )
	{
		if ( elemArray.length == undefined )
		{
			if ( value )
			{
				elemArray.checked = true;
				buttonToChangeState.disabled = false;
			}
			else
			{
				elemArray.checked = false;
				buttonToChangeState.disabled = true;
			}
		}
		else
		{
			for ( var i = 0; i < elemArray.length; i++ )
			{
				if ( value )
				{
					checkBox( elemArray[i] );
					buttonToChangeState.disabled = false;
				}
				else
				{
					uncheckBox( elemArray[i] );
					buttonToChangeState.disabled = true;
				}
			}
		}
	}
}

function anyCheckedChangeButtonStatus( elemArray, buttonToChangeState )
{
	if ( elemArray != null )
	{
		if ( elemArray.length == undefined )
		{
			if ( elemArray.checked == true )
			{
				buttonToChangeState.disabled = false;
			}
			else
			{
				buttonToChangeState.disabled = true;
			}
			
			return;
		}
		else
		{
			for ( var i = 0; i < elemArray.length; i++ )
			{
				if ( elemArray[i].checked == true )
				{
					buttonToChangeState.disabled = false;
					// we can return here because at least 1 item is selected
					return;
				}
			}
		}
	}
	
	buttonToChangeState.disabled = true;
}

