var debugging = false;

/**
 * E-mail address validadtion
 *
 * @param email - E-mail address to validate
 * @return result - Boolean result of validation test
 */
function isValidEmail(email)
{
	var result = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email);
	
	return result;
}

/**
 * Opens and centers window
 */
function openAndCenterWindow(url, name, h, w, settings)
{
	var openedWindow = null;
					
	if (screen.width)
	{
		var winl = (screen.width-w) / 2;
		var wint = (screen.height-h) / 2;
	}
	else
	{
		winl = 0;
		wint = 0;
	}
				
	if (winl < 0) winl = 0;
	if (wint < 0) wint = 0;
	
	if (settings == null || settings == 'undefined')
		settings = "";
	else
		settings += ",";
		
	settings += 'height=' + h;
	settings += ',width=' + w;
	settings += ',top=' + wint;
	settings += ',left=' + winl;
			
	openedWindow = window.open(url, name, settings);
	
	return openedWindow;
}

/**
 * Date validation
 * 
 * Tests whether date string passed in is a valid
 * calendar date in format mm/dd/yy or mm/dd/yyyy			
 *
 * @param date - Date string to validate
 * @return result - Boolean result of validation test
 */
function isValidDate(date)
{
	var result = parseDate(date);
	
	return result[0];
}

/**
 * Date formatter
 * 
 * Takes a date string and returns either a blank string
 * if it's an invalid date or a date formatted as
 * mm/dd/yyyy.Dates must be in format:
 *	mmddyy
 * 	mmddyyyy
 * and can contain /'s, -'s, /'s and -'s and any number
 * of spaces.They will be stripped out prior to validation.
 *
 * @param String Date string to validate
 * @return String Boolean result of validation test
 */
function getFormattedDate(date)
{
	var result = parseDate(date);
	
	return result[1];
}

/**
 * Date parser
 *
 * Takes a date string and returns an array with the date validation
 * result and, if validation's successful, a date string formatted as
 * mm/dd/yyyy.
 */
function parseDate(date)
{
	var result = new Array(false, "");
	
	var regExp1 = /\s/gi;		// Remove whitespace
	var regExp2 = /[\/-]/gi;	// Remove '/' or '-'
	
	var today = new Date();
	var curYear = today.getFullYear().toString();
	var yrPrefix = curYear.substr(0, 2);
	
	// Remove whitespace, '/' and '-'
	date = date.replace(regExp1, "");
	date = date.replace(regExp2, "")
	
	// Date should be (mmddyyyy)
	if (date.length != 8 || isNaN(date))
		return result;
		
	/*if (date.length != 6 && date.length != 8)
		return result;
	else if (date.length == 6)
		date = date.substr(0, 4) + yrPrefix + date.substr(4, 2);*/
	
	// We use the built-in JS date object and check that the values parsed
	// and returned from the class functions match what the user provided.
	// JavaScript will cycle over if value is invalid.
	// Eg) getMonth() will return '1' if it the month provided was '13'
	var userMo = date.substr(0, 2);
	var userDa = date.substr(2, 2);
	var userYr = date.substr(4, 4);
	var userFormattedDate = userMo + "/" + userDa + "/" + userYr;
	
	var testDate = new Date(userFormattedDate);
	var testMo = testDate.getMonth() + 1;
	var testDa = testDate.getDate();
	var testYr = testDate.getFullYear();
	
	// Check date is valid
	if (Number(userMo) != testMo ||
		Number(userDa) != testDa ||
		userYr != testYr)
	{
		return result;
	}
	
	result[0] = true;
	result[1] = userFormattedDate;
	
	return result;
}

/**
 * Page redirect
 */
function redirect(page) {
	document.location.href = page;
}

/**
 * Left trim string
 */
function ltrim (s1)
{
	return s1.replace(/^\s*/, "")
}

/**
 * Right trim string
 */
function rtrim (s2)
{
	return s2.replace(/\s*$/, "");
}

/**
 * Full trim string
 */
function trim (s3)
{
	return rtrim(ltrim(s3));
}

/**
 * Generic logout function
 */
function logout()
{
	var logoutPage = '/security/logout.php';

	//if (document.URL.indexOf('localhost') == -1)
		//logoutPage = '/' + logoutPage;

	if (confirm("Ok to logout?"))
		document.location.href = logoutPage;	
}

/**
 * Generic function that checks that a value passed in is valid
 */
function isValid(value) {
	
	if (typeof(value) == 'undefined' ||
		typeof(value) == undefined ||
		value == null ||
		value == undefined ||
		value == 'undefined')
	{
		return false;
	}
	
	return true;
}

/**
 * Checks that required fields are not blank and that
 * the length does not exceed the maximum limit
 * 
 * @param {Object} fields
 * @param {Object} formToValidate
 */
function checkReqFieldsAndLengths(fields, formToValidate)
{
	return checkReqFields(fields, formToValidate) &&
		   checkFieldLenghts(fields, formToValidate);
}

/**
 * Moves focus and selects field if properties are valid
 * @param {Object} fields
 * @param {Object} formToValidate
 */
function selectAndFocus(field)
{
	if (isValid(field.focus))
	{
		field.focus();
	}
	if (isValid(field.select))
	{
		field.select();
	}
}

/**
 * 
 * @param {Object} fields
 * @param {Object} formToValidate
 */
function checkFieldLengths(fields, formToValidate)
{
	var form = formToValidate;
	var fieldToCheck = null;
	var fieldTitle = null;
	var numNewlines = 0;
	var debug = false;
	
	for (var fieldName in fields)
	{
		fieldLength = fields[fieldName];

		if (!isNaN(fieldLength))
		{
			fieldToCheck = form[fieldName];
			
			if (fieldToCheck != 'undefined')
			{
				fieldToCheck.value = trim(fieldToCheck.value);
				numNewlines = countNewlines(fieldToCheck.value);
				
				// Newlines are represented by a single character in
				// textarea boxes, but the form post converts them to 2
				if (fieldToCheck.value.length > (fieldLength - numNewlines))
				{
					fieldTitle = fieldToCheck.title;
									
					if (fieldTitle == 'undefined' ||
						fieldTitle == null ||
						trim(fieldTitle) == '')
					{
						errorMessage = "Field cannot be longer than " + fieldLength + " characters";
					}
					else
					{
						errorMessage = fieldTitle + " cannot be longer than " + fieldLength + " characters";
					}
					
					if (numNewlines > 0)
					{
						errorMessage += ".\nPlease be aware that every new line uses up 2 of these characters.";
					}
					
					if (true)
					{
						alert("Num newlines=" + numNewlines + "\n"+
							  "fieldLength=" + fieldLength + "\n" +
							  "Trimming=" + (fieldLength - numNewlines));
					}

					alert(errorMessage);					
					fieldToCheck.value = fieldToCheck.value.substr(0, (fieldLength - 0));
					selectAndFocus(fieldToCheck);
					
					return false;
				}
			}
		}
	}
	
	return true;
}

/**
 * Checks that required fields are not blank
 */
function checkReqFields(fields, formToValidate)
{
	var form = formToValidate;
	var fieldToCheck = null;
	var fieldTitle = null;
	
	// If form not specified, try default form in document
	if ((form == 'undefined' || form == null) &&
		document.forms[0] != null)
	{
		form = document.forms[0];
	}
	
	// Validate form
	if (form != 'undefined' &&
		form != null &&
		fields != 'undefined' &&
		fields != null &&
		fields.length != 'undefined')
	{
		for (var i=0; i < fields.length; i++)
		{
			// Form field to check
			fieldToCheck = form[fields[i]];
			
			debug("Checking field '" + fieldToCheck + 
				  "' with title '" + fieldToCheck.title + "'");
						
			if (fieldToCheck != null &&
				fieldToCheck != 'undefined' &&
				trim(fieldToCheck.value) == '')
			{
				fieldTitle = fieldToCheck.title;
				
				if (fieldTitle == 'undefined' ||
					fieldTitle == null ||
					trim(fieldTitle) == '')
				{
					alert("Required field missing");
				}
				else
				{
					alert("Please enter a value for " + fieldTitle);
				}
				
				selectAndFocus(fieldToCheck);
				
				return false;
			}
		}
	}
	else
		return false;
		
	return true;
}

/**
 * Counts the number of newlines in a string 
 * @param {Object} field
 * @param {Object} value
 */
function countNewlines(value)
{
	if (value.indexOf("\r\n") != -1)
	{
		splitVal = "\r\n";
	}
	else if (value.indexOf("\n") != -1)
	{
		splitVal = "\n";
	}
	else if (value.indexOf("\r") != -1)
	{
		splitVal = "\r";
	}
	else
	{
		return 0;
	}
	
	return value.split(splitVal).length;
}

/**
 * Sets drop-down field based on value
 */
function setDropDown(field, value)
{
	var ddValue = null;
	
	if (field != 'undefined' && field != null &&
		field.options != 'undefined' && field.options != null)
	{
		for (var i=0; i < field.options.length; i++)
		{
			ddValue = field.options[i].value;
			if (ddValue == value)
			{
				field.selectedIndex = i;
				return;
			}
		}
	}
}

/**
 * Debug level debugging
 */
function debug(message)
{
	if (debugging != 'undefined' &&
		debugging != null &&
		debugging == true)
	{
		alert("DEBUG: " + message);
	}
}

/**
 * Info level debugging
 */
function info(message)
{
	if (debugging != 'undefined' &&
		debugging != null &&
		debugging == true)
	{
		alert("INFO: " + message);
	}
}

/**
 * Error level debugging
 */
function error(message)
{
	if (debugging != 'undefined' &&
		debugging != null &&
		debugging == true)
	{
		alert("*** ERROR: " + message + " ***");
	}
}
