/*
// Fucntions:


// Properly validates and formats an entered date to match the supplied date mask and diveder character.
formatCheckDate(checkDate, displayText, maskStr, dividerChar)

// Gets correct date part
function setDatePosition(dateType)

// Get mask date type and set the vars dateMon, dateDay, dateYear
function setMaskDateType(maskStr, dateStr)

// Checks if months and days are correct
function verifyDateValues(checkMonth, checkDay, checkYear, displayText, dividerChar)

// Get selected month string for error message.
charFromIntMonth(monthSelected)

// Selects all and copies within a text field. The user will then be able to past the copied contents into any text area or document.
function copyAll(formField) 

// Trims all blank spaces on the left side of string
function leftTrim(strValue)

// Trims all blank spaces on the right side of string
function rightTrim(strValue)

// Trims all blank spaces in string
function trimData(strValue)

// Removes all blank spaces in string
function removeSpaces(stringVal)

// Check if value only contains chars in the validStr var
function isValidValues(validStr, stringValue)

// Checks if phone number entered is correct.
function checkPhoneNbr(formField, displayText)

// Checks if zip code entered is correct.
function checkZipNbr(formField, displayText)

// Checks if integer entered is correct.
function checkInteger(formField, displayText)


*/






// ********************************************************************************************************

// Properly validates and formats an entered date to match the supplied date mask and diveder character.


// Preconditions:
// checkDate 	= Form field object usually identified as "this" in the calling tag.
// displayText 	= Name of form field to be outputed in validation error messages
// maskStr 		= Date mask to be checked against (exp. "YYYY/MM/DD")
// dividerChar 	= Character used to divide date parts. (exp. "/" or "-")

// Postconditions:


// Declare global vars
    var dateMon  = "";
    var dateDay  = "";
    var dateYear = "";

	var maskYear = "";
	var maskMon = "";
	var maskDay = "";
	
	
function formatCheckDate(checkDate, displayText, maskStr, dividerChar)
{
    var dateValue = checkDate.value;
    var dateRest = ""; 
		
    var datePos1  = "";
    var datePos2  = "";
    var datePos3 = "";
	
	var maskPos1 = "";
	var maskPos1Len = "";
	var maskPos1Type = "";
	var maskPos2 = "";
	var maskPos2Len = "";
	var maskPos2Type = "";
	var maskPos3 = "";
	var maskPos3Len = "";
	var maskPos3Type = "";	
	var maskRest = "";
	
	// The formated date to be outputed
	var outputDate = "";
	
	// Convert mask to uppercase
	maskStr = maskStr.toUpperCase();
	
	
	// get the mask order, type and lengths.
    var isplit = maskStr.indexOf(dividerChar);
    if (isplit == -1 || isplit == maskStr.length)
    {
	alert("A proper date mask has not been supplied.\nOr the delimiter char was not found in the mask.");
    checkDate.value = "";
    return false;
    }
    maskPos1  = maskStr.substring(0, isplit);
    maskRest = maskStr.substring(isplit + 1);

    // get the Day and Year.
    isplit = maskRest.indexOf(dividerChar);
    if (isplit == -1 || isplit == maskRest.length)
    {
	alert("A proper date mask has not been supplied.\nOr the delimiter char was not found in the mask.");
    checkDate.value = "";
    return false;
    }
    maskPos2  = maskRest.substring(0, isplit);
    maskPos3 = maskRest.substring(isplit + 1);
	

	
	// Get mask length
	maskPos1Len = maskPos1.length;
	maskPos2Len = maskPos2.length;
	maskPos3Len = maskPos3.length;
	
	
      
   // Ckeck if a double forward slash was typed by mistake
	var nRegExp = dividerChar + dividerChar;
	var invalidResult = dateValue.search(nRegExp);
	if (invalidResult != -1)
    {
	alert("You can not have '//' in a date.");
    checkDate.value = "";
    return false;
    }
	
	
    // get the Month.
    var isplit = dateValue.indexOf(dividerChar);
    if (isplit == -1 || isplit == dateValue.length)
    {
	alert("Please enter a properly formatted date.");
    checkDate.value = "";
    return false;
    }
    datePos1  = dateValue.substring(0, isplit);
    dateRest = dateValue.substring(isplit + 1);

    // Get the Day and Year.
    isplit = dateRest.indexOf(dividerChar);
    if (isplit == -1 || isplit == dateRest.length)
    {
    alert("Please enter a properly formatted date.");
	checkDate.value = "";
    return false;
    }
    datePos2  = dateRest.substring(0, isplit);
    datePos3 = dateRest.substring(isplit + 1);
	
    
	
	// Get mask date type and set the vars dateMon, dateDay, dateYear
	maskPos1Type = setMaskDateType(maskPos1, datePos1);
	maskPos2Type = setMaskDateType(maskPos2, datePos2);
	maskPos3Type = setMaskDateType(maskPos3, datePos3);
	
	
		
    // Format date to match mask format.	
	
	// Pad month with 0 if not enough characters
    if (dateMon.length == 1 && maskMon.length == 2) 
	dateMon = '0' + dateMon;	
	
	// If mask length is 1 and a 0 was placed before the value the 0 needs to be removed
	if (dateMon.length == 2 && maskMon.length == 1 && parseInt(dateMon.charAt(0)) == 0)
	dateMon = dateMon.charAt(1);
	
	// Pad day with 0 if not enough characters	
    if (dateDay.length == 1 && maskDay.length == 2) 
	dateDay = '0' + dateDay;
	
	// If mask length is 1 and a 0 was placed before the value the 0 needs to be removed
	if (dateDay.length == 2 && dateDay.length == 1 && parseInt(dateDay.charAt(0)) == 0)
	dateDay = dateDay.charAt(1);
	
	
	if (dateYear.length != 2 && dateYear.length != 4)
	{    
	alert("Please enter a valid year.");	
    checkDate.value = "";
	return false;   
    }
	
	
	// If year has 2 characters and the mask requests 4 add either 19 or 20
    if (dateYear.length == 2 && maskYear.length == 4)
    {
        if (dateYear > 50) 
		{
		// For calculation purposes add 19 to the check value
		checkDateYear = '19' + dateYear;
		
			// if the mask is 'YYYY' add 19 to the value	
			if (maskYear.length == 4)
			dateYear = '19' + dateYear;
		}// if (dateYear > 50) 
         	else 
			{
			// For calculation purposes add 20 to the check value
			checkDateYear = '20' + dateYear;
		
				// if the mask is 'YYYY' add 20 to the value	
				if (maskYear.length == 4)
				dateYear = '20' + dateYear;
			}// else
    }// if (dateYear.length == 2)

    
	// If year has 4 characters and the mask requests 2 remove first two
    if (dateYear.length == 4 && maskYear.length == 2)
	dateYear = dateYear.substring(2);
		
	
	// Validate day, month, year
    if (!verifyDateValues(dateMon, dateDay, dateYear, displayText, dividerChar))
    {        
    checkDate.value = "";
	return false;
    }
    else 
	{
	
	// Place formated date parts into correct position
	datePos1 = setDatePosition(maskPos1Type);
	datePos2 = setDatePosition(maskPos2Type);
	datePos3 = setDatePosition(maskPos3Type);
	
	// Create output string
	outputDate = datePos1 + dividerChar + datePos2 + dividerChar + datePos3;
	
	// Output formated date to field
	checkDate.value = outputDate;
	
    return true;
	
	
	}
	
	
	
		
	
}

// ******************************************************************************************************** 

// Gets correct date part

// Precondition:
// dateType		= Date type to be retrieved. Must be a "Y", "M" or "D"

// Postcondition:
// Outputs the date part requested

function setDatePosition(dateType)
{
// Date part to be outputed

var datePart = "";

switch (dateType)
		{
		case "Y" : 
		datePart = dateYear;
		break;
		
		case "M" : 
		datePart = dateMon;
		break;
		
		case "D" : 
		datePart = dateDay;
		break;
		
		default : alert("Error: No date type found.");
		break;
		
		}
		
return datePart;

}

// ******************************************************************************************************** 

// Get mask date type and set the vars dateMon, dateDay, dateYear

// Preconditions:
// maskStr		= Mask string to identify the date part to be saved as. Must be "YYYY", "YY", "DD", "D", "MM" or "M"
// dateStr		= Date part string to be saved

// Postconditions:
// Saves dateStr as correct type in global var. (Year, Month or Day)
// Saves maskStr as correct type in global var. (Year, Month or Day)
// Outputs type of var saved in single char. ("Y", "M" or "D")

function setMaskDateType(maskStr, dateStr)
{
// String to be outputed
var maskType = "";
	
	// Set values
	switch(maskStr)
	{
	case 'YYYY' : 
	maskType = "Y";
	dateYear = dateStr;
	maskYear = maskStr;
	break;
	
	case 'YY' : 
	maskType = "Y";
	dateYear = dateStr;
	maskYear = maskStr;
	break;
	
	case 'DD' : 
	maskType = "D";
	dateDay  = dateStr;	
	maskDay = maskStr;
	break;
	
	case 'D' : 
	maskType = "D";
	dateDay  = dateStr;
	maskDay = maskStr;
	break;
	
	case 'MM' : 
	maskType = "M";
	dateMon  = dateStr;
	maskMon = maskStr;
	break;
	
	case 'M' : 
	maskType = "M";
	dateMon  = dateStr;
	maskMon = maskStr;
	break;	
	
	default : alert("Mask Error");
	break;
	}
	
return maskType;


}

// ******************************************************************************************************** 

// Checks if months and days are correct

// Preconditions:
// 	checkMonth 	= Month to be checked
//  checkDay 	= Day to be checked
//	checkYear	= Year to be checked
//	displayText	= Name of form to be outputed in error messages
//  dividerChar	= The character used to seperate the day,month and year. exp. "/", "-", "_"

// Postcondition:
// Returns true if everything is OK
// Returns false and pops up an error message if problem found
function verifyDateValues(checkMonth, checkDay, checkYear, displayText, dividerChar)
{
    var minDay  = 1;
	var maxDay  = 31;
	var selectedMonthOutput = "";
	
	
	// Check for unwanted noninteger characters in month		
	if (!isValidValues( "0123456789", checkMonth))
	{
	alert("Please enter only integers for the month.");
	return false
	} 
	  
	// Check for unwanted noninteger characters in day
	if (!isValidValues( "0123456789", checkDay))
	{
	alert("Please enter only integers for the day.");
	return false
	} 
	
	// Check for unwanted noninteger characters in year
	if (!isValidValues( "0123456789", checkYear))
	{
	alert("Please enter only integers for the year.");
	return false
	} 
	
	// Confirm extra characters where not entered
	// Check month
	if (checkMonth.length > 2)
	{
	alert("Too many character where entered for the month.");
	return false
	} 
	
	// Check year
	if (checkYear.length > 4)
	{
	alert("Too many character where entered for the year.");
	return false
	} 
	
	// Check day
	if (checkDay.length > 2)
	{
	alert("Too many character where entered for the day.");
	return false
	} 
	
	
	
	
	
		
	// Check if month is valid
	if (checkMonth > 12 || checkMonth < 1)
	{	
	alert("Please enter a valid month.");	
	return false;
	}
	
    // Determine the max number of days based upon month and year.
	if (checkMonth == 4 || checkMonth == 6 || checkMonth == 9 || checkMonth == 11)
	maxDay=30;
	else
    	if (checkMonth == 2)
    	{
    		if (checkYear % 4 > 0) 
			maxDay =28;
    		else
        		if (checkYear % 100 == 0 && checkYear % 400 > 0) 
				maxDay=28;
        		else maxDay=29;
        }

    // Check the input day against the max day.
    if ((checkDay < minDay) || (checkDay > maxDay))
    {
        alert ("The day of " + charFromIntMonth(checkMonth) + " must be between " + minDay + " and " + maxDay + " for " + displayText + ".");
        return false;
    }

// Return true if no problem found.
return true;
}

// ********************************************************************************************************

// Get selected month string for error message.

// Precondition:
// monthSelected	= The numeric value of the month

// Postcondition
// Returns the character value that matches the numeric value of the month

function charFromIntMonth(monthSelected)
{

// String to be outputed
var monthString = "";

// Make sure the value is an int
var monthSelectedInt = parseInt(monthSelected);

	switch(monthSelectedInt)
	{
	case 1 : monthString = "January";
	break;
	
	case 2 : monthString = "February";
	break;
	
	case 3 : monthString = "March";
	break;
	
	case 4 : monthString = "April";
	break;
	
	case 5 : monthString = "May";
	break;
	
	case 6 : monthString = "June";
	break;
	
	case 7 : monthString = "July";
	break;
	
	case 8 : monthString = "August";
	break;
	
	case 9 : monthString = "September";
	break;
	
	case 10 : monthString = "October";
	break;
	
	case 11 : monthString = "November";
	break;
	
	case 12 : monthString = "December";
	break;	
	
	default : monthString = "of the month";
	}

return monthString;
}


// ********************************************************************************************************

// Selects all and copies within a text field. The user will then be able to past the copied contents into any text area or document.

// Precondition:
// = Contains field and form name to be checked. exp.(formName.FieldName)

// Postcondition:
// Value in requested field is copied to window clipboard.

function copyAll(formField) 
{
// Creates form field object
var tempval=eval("document."+ formField);

// Puts focus on field
tempval.focus();

// Selects entire field
tempval.select();

	// Copy value in field
	if (document.all && copytoclip==1)
	{
	therange=tempval.createTextRange();
	therange.execCommand("Copy");
	window.status="Contents highlighted and copied to clipboard!";
	setTimeout("window.status=''",2400);
	}
}

// ********************************************************************************************************

// Trims all blank spaces on the left side of string

// Precondition:
// strValue		= String to be trimmed

// Postcondition:
// String is returned with all blank spaces on the left side of string trimmed


function leftTrim(strValue)
{
    while('' + strValue.charAt(0) == ' ')
	strValue=strValue.substring(1,strValue.length);
		
    if (strValue.length == 0) 
	strValue = '';
    
	return strValue;
}


// ********************************************************************************************************

// Trims all blank spaces on the right side of string

// Precondition:
// strValue		= String to be trimmed

// Postcondition:
// String is returned with all blank spaces on the right side of string trimmed

function rightTrim(strValue)
{
    while('' + strValue.charAt(strValue.length-1) == ' ')
	strValue = strValue.substring(0,strValue.length-1);

    if (strValue.length == 0) 
	strValue = '';
    
	return strValue;
}

// ********************************************************************************************************

// Trims all blank spaces in string

// Precondition:
// strValue		= String to be trimmed

// Postcondition:
// String is returned with all blank spaces on the left and right side trimmed

function trimData(strValue)
{
    strValue = rightTrim(strValue);
    strValue = leftTrim(strValue);
	return strValue;
}


// ********************************************************************************************************	

// Removes all blank spaces in string

// Precondition:
// stringVal		= String to have spaces removed

// Postcondition:
// String is returned with all blank spaces removed 	
	function removeSpaces(stringVal)
	{
	
	// Initialize vars
	var checkBlank = stringVal;
	var searchResult = 0;
			
			// Loop through all spaces and remove
			while(searchResult != -1)
			{
			checkBlank = checkBlank.replace(' ','');			
			searchResult = checkBlank.indexOf(' ');
			}
			
	return checkBlank;
		
	}	
	
// ******************************************************************************************************** 
	
// Check if value only contains chars in the validStr var

// Preconditions:
// validStr		= Contains values to check by.
// stringValue	= Value to be checked

// Postconditions:
// Returns true if string only contains characters in validStr or false if other characters were found. 

function isValidValues(validStr, stringValue)
{
	var checkOK = validStr;
	var checkStr = stringValue;
	var allValid = true;
    
	// Loop through string to check each char	
	for (i = 0;  i < checkStr.length;  i++)
	{
		// Get next char
		ch = checkStr.charAt(i);
		
		// Check string against valid list characters
		for (j = 0;  j < checkOK.length;  j++)
				if (ch == checkOK.charAt(j)) 
				break;
		
		// Check if all character in string were found	
		if (j == checkOK.length)
		{
		  allValid = false;
		  break;
		}
	}
return allValid;
}

// ******************************************************************************************************** 

// Checks if phone number entered is correct.

// Preconditions:
// formField	= Contains field object to be checked. exp.(this or document.formName.FieldName)
// displayText	= Contins field name to be outputed in error message.

// Postconditions:
// Returns true if phone number is valid and false if invalid

function checkPhoneNbr(formField, displayText)
{
	// Check if value only contains digits or a hypen
	if (!isValidValues( "0123456789-", formField.value))
	{
	  alert("Please enter only digits and a hypen in the " + displayText + " field.");
	  formField.value = "";
	  return false;
	}
    return true;
}

// ******************************************************************************************************** 

// Checks if zip code entered is correct.

// Preconditions:
// formField	= Contains field object to be checked. exp.(this or document.formName.FieldName)
// displayText	= Contins field name to be outputed in error message.

// Postconditions:
// Returns true if phone number is valid and false if invalid

function checkZipNbr(formField, displayText)
{
// Length of zip code
var ziplength = 5;
	
	if (!isValidValues( "0123456789", formField.value))
	{
	  alert("Please enter only digits in the " + displayText + " field.");
	  formField.value = "";
	  return false;
	}
    if (formField.value.length != ziplength)
    {
	  alert("Please enter " + ziplength + " digits in the " + displayText + " field.");
	  formField.value = "";
	  return false;
    }
    return true;
}




// ******************************************************************************************************** 

// Checks if integer entered is correct.

// Preconditions:
// formField	= Contains field object to be checked. exp.(this or document.formName.FieldName)
// displayText	= Contins field name to be outputed in error message.

// Postconditions:
// Returns true if integer is valid and false if invalid

function checkInteger(formField, displayText)
{
	if (!isValidValues( "-0123456789", formField.value))
	{
	  alert("Please enter only integers in the " + displayText + ".");
	  formField.value = "";
	  return false;
	}
    return true;
}




// ******************************************************************************************************** 

// Checks if integer entered is correct.

// Preconditions:
// formField	= Contains field object to be checked. exp.(this or document.formName.FieldName)
// displayText	= Contins field name to be outputed in error message.

// Postconditions:
// Returns true if float is valid and false if invalid

function checkFloat(formField, displayText)
{
	if (!isValidValues( "-0123456789.", formField.value))
	{
	  alert("Please only enter a number in the " + displayText + ".");
	  formField.value = "";
	  return false;
	}
    return true;
}



		

// ******************************************************************************************************** 

// Checks if fields are null that have the attribute required as Yes. Skips hidden form fields and displays output message using the title attribute of the fields.

// Preconditions:
// formObj = form object
// All fields must have a value assigned to the title attribute.
// All fields that are required must have the value yes assigned to the required attribute.


// Postconditions:
// If field value is null it returns false and displays output message using the title attribute of the fields.
// If all field values are not null returns true.


function checkNullFields(formObj)
{
		
// Get number of fields to check
var fieldCount = formObj.length;

// Initialize field value var
var checkVal = '';

// Initialize the isRequired var
var isRequired = '';

// Initialize the field title var
var fieldTitle = '';

	// Loop through all fields
	for(x=0; x<fieldCount;x++)
	{
	// Get field value
	checkVal = formObj[x].value;
	
		// Reinitialize the isRequired var
		isRequired = '';
	
		// Check if the required attribute exists
		if(formObj[x].required)
		{
		isRequired = formObj[x].required.toLowerCase();
		}// if(document.issueTrackerForm[x].required)
		
							
		// Check if null and not hidden
		if(removeSpaces(checkVal) == '' && formObj[x].type != 'hidden' && isRequired == 'yes')
		{
		
		// Get field title
		fieldTitle = formObj[x].title;
				
		// Check if "an" or "a" should be used				
		if(isValidValues("euioaEUIOA", removeSpaces(fieldTitle.charAt(0))))
		var openingStr = "Please enter an ";
			else
			var openingStr = "Please enter a ";
		
		// Output validation error message				
		alert(openingStr + fieldTitle + ".");
		
		// Set focus on field
		formObj[x].focus();
		
		return false;
		} // if(removeSpaces(checkVal) == '' && document.issueTrackerForm[x].type != 'hidden' && isRequired == 'yes')
	
	}//for(x=0; x<=fieldCount;x++;)

// If all fields validate return true
return true;

}


// ******************************************************************************************************** 

// Checks email address inputed for the '@' and '.' characters

// Preconditions:
// formObj = field object


// Postconditions:
// returns true if email address is valid
// returns false and outputs an error message if not valid.

function checkEmailAddress(fieldObj)
{

// Get the email address inputed and make lower case
var emailAddress = fieldObj.value.toLowerCase();	
	
	// Find the '@' character
    var strLocation = emailAddress.indexOf("@");
    if (strLocation == -1 || strLocation == emailAddress.length)
    {
	alert("An email address must contain a \'@\' character.");
    fieldObj.value = "";
    return false;
    }	
	
    var emailName  = emailAddress.substring(0, strLocation);
    var emailDomain = emailAddress.substring(strLocation + 1);

	
	// Look for a second '@' character
    var strLocation = emailName.indexOf("@");
	
	if(emailName.indexOf("@") != -1 || emailDomain.indexOf("@") != -1)
    {
	alert("An email address cannot contain more than one \'@\' character.");
    fieldObj.value = "";
    return false;
    }	
	
	// Find the '.' character
	var strLocation = emailDomain.indexOf(".");
	if(strLocation == -1 || strLocation == emailDomain.length-1 || strLocation == 0)
	{
	alert("The domain of the email address is invlaid.");
    fieldObj.value = "";
    return false;	
	}
		
	
// All is valid
return true;


}

// ******************************************************************************************************** 

// Count the number of characters inputed

// Preconditions:
// formObj = field object
// charMax = max number of characters


// Postconditions:
// returns true if count is less then supplied number
// returns false and outputs an error message if inputed value is greater then supplied number.

function checkMaxChar(fieldObj, charMax)
{

var getCharAmt = fieldObj.value.length;
	
	if(getCharAmt > charMax)
	{
	// Truncate inputed string
	var getInputedString = fieldObj.value;
	var truncatedStr  = getInputedString.substring(0, charMax);
	
	// Output message
	alert("The value inputed contains " + getCharAmt + " characters.\nThis exceeds the allowed maximum of " + charMax + " characters.\nYour value has been truncated.");
	
	// Change value to truncated value
	fieldObj.value = truncatedStr;
	return false;
	}
	
// All is valid
return true;


}



// ******************************************************************************************************** 

// Compare to password fields

// Preconditions:
// password1Obj = password 1 field object
// password2Obj = password 2 field object


// Postconditions:
// returns true fields are identical or null
// returns false if fields do not match and neither are null

function checkPasswords(password1Obj, password2Obj)
{
	if(password1Obj.value!=password2Obj.value&&removeSpaces(password1Obj.value)!=""&&removeSpaces(password2Obj.value)!="")
	{
	// Send message	
	alert("Passwords entered do not match.\nPlease reenter passwords.");
	
	// Clear values
	password1Obj.value="";
	password2Obj.value="";
	
	// Set focus
	password1Obj.focus();
	
	return false;
	}
	
// If all is OK
return true;
	
}
       

// ******************************************************************************************************** 

// Identifies if obj exists

// Preconditions:
    // checkObj = Object to be checked


// Postconditions:
    // returns true if defined else false if undefined
    
function objIsDefined(checkObj) 
{                                              
    // Check if defined
    // Some browsers return null instead of undefined
    if(typeof(checkObj) == "undefined" || typeof(checkObj) == "")
    return false;  
        else
        return true;

}



	
//******************************************************************************************
	
	// Precondition
		//  activeFlag = identifies if user wants to maintain a live connection with the database
	
	// Postcondition
		// If true app continues to check for new data else it stops  
		
		
function getCurrentDate()
{
	
var currentDateTime = new Date();
var month = currentDateTime.getMonth() + 1;
var day = currentDateTime.getDate();
var year = currentDateTime.getFullYear();


var hours = currentDateTime.getHours();
var minutes = currentDateTime.getMinutes();

	// Keep minutes with two chars
	if (minutes < 10)
	minutes = "0" + minutes;
	
	// Set amPm var
	if(hours > 11)
	var amPm = "PM";	 
		else 
		var amPm = "AM";

var outputDate = month + "/" + day + "/" + year + " - " + hours + ":" + minutes + " " + amPm;
	
return outputDate;
}
	

	
//******************************************************************************************
	
	// Precondition
		//  fieldObj = Fields object failed
	
	// Postcondition
		// Clears value and sets focus back to failed object  
		
		
function objFailed(fieldObj)
{
	fieldObj.value="";
	fieldObj.focus();	
}


