function trim(s) 
{
  // Remove leading spaces and carriage returns
  
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

//Implementation of split which splits on any one of the characters in the given delims string
function split(s, delims)
{
	var strs = new Array();
	
	var currentStr = "";
	var currentIdx = 0;
	for (var i = 0; i < s.length; i++)
	{
		var doAppend = true;
		var ch = s.charAt(i);
		for ( var j = 0; j < delims.length; j++ )
		{
			if ( ch == delims.charAt(j) )
			{
				doAppend = false;
				if ( currentStr.length > 0 )
				{
					strs[currentIdx++] = currentStr;
					currentStr = "";
				}
				
				break;
			}
		}
		
		if ( doAppend )
		{
			currentStr += ch;
		}
	}
	
	if ( currentStr.length > 0 )
	{
		strs[currentIdx++] = currentStr;
		currentStr = "";
	}
	
	return strs;
}

function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;

	// Note: doesn't use regular expressions to avoid early Mac browser bugs	
	for (var i=0;i<str.length;i++)
	{
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	}
	return result;
}

//Checks that the day is valid, given the month and year
function isValidDay(year, month, day)
{
	switch (month)
	{
		//30 days hath september, april, june and november
		case 4:
		case 6:
		case 9:
		case 11:
			return day < 31;
			break;
		case 2:
			//Here's the fun part: leap years are divisible by four, EXCEPT for 
			//century years, which are only leap years if they are divisible by 400
			if ( year % 4 == 0 && (year % 100 != 0 || year % 400 == 0 ) )
			{
				return day < 30;
			} else
			{
				return day < 29;
			}
		default:
			return day < 32;
			break;
	}
}

//Unfortunately, we can't use a "true" email validator because email addresses actually allow almost any ASCII char, 
//even though most SMTP servers (especially the ones we use) will only allow a small subset. So, here is an attempt at 
//catching common, known errors, without accidentally preventing valid email addresses.
function isEmailAddr(email)
{
  var illegalChars = " \t<>!;,";
  var result = false;
  var theStr = new String(email);
  theStr = trim(theStr);
  
  for (var i = 0; i < illegalChars.length; i++)
  {
    var c = illegalChars.charAt(i);
    if ( theStr.indexOf(c) > 0 )
    {
      return false;
    }
  }
  
  var index = theStr.indexOf("@");
  if (index > 0 && index == theStr.lastIndexOf("@"))
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;
}

function validEmail(formField,fieldLabel,isRequired)
{
	var result = true;
	if (isRequired && formField.value == "")
	{
		alert('Please enter a value for the "' + fieldLabel + '" field.');
		formField.focus(); formField.select();
		return false;
	}

	var emailAddrs = split(formField.value, ",; ");
	
	for(var i = 0; i < emailAddrs.length; i++)
	{
		if (emailAddrs[i].length < 3 || !isEmailAddr(emailAddrs[i]))
		{
			alert("Please enter a complete email address in the form: yourname@yourdomain.com for the \"" + fieldLabel + "\" field");
			formField.focus();
			return false;
		}
	}
	
	return true;
}

function checkRequired1(formField, fieldLabel, isRequired)
{
	if (isRequired && formField.value == "")
	{
		alert('Please enter a value for the "' + fieldLabel + '" field.');
		formField.focus(); formField.select();
		return false;
	}
	return true;
}

function checkRequired(formField, isRequired)
{
	if (isRequired && formField.value == "")
	{
		alert('Please enter a value for this field.');
		formField.focus(); formField.select();
		return false;
	}
	return true;
}

// validate date in the format of YYYY/MM/DD
function validDate(formField, isRequired)
{
	if (!checkRequired(formField, isRequired))
	{
		return false;
	}
	if (formField.value == "")
	{
		return true;
	}
 	
	var elems = formField.value.split("/");
	var result = (elems.length == 3); // should be three components
	if (result)
	{
		var yearStr = elems[0]; var monthStr = elems[1]; var dayStr = elems[2];
		var year = parseInt(yearStr,10);
		var month = parseInt(monthStr,10);
		var day = parseInt(dayStr,10);
		result = allDigits(yearStr) && (yearStr.length == 4) &&  
				 allDigits(monthStr) && (month > 0) && (month < 13) &&
				 allDigits(dayStr) && (day > 0) && (day < 32);
	}
	if (!result)
	{
		alert('Please enter a date in the format YYYY/MM/DD for this field.');
		formField.focus(); formField.select();
		return false;
	}
	return true;
}

//We strictly require that the time stamp be in the form YYYY-MM-DD hh:mm
function validTimestamp(formField, isRequired)
{
	if (!checkRequired(formField, isRequired))
	{
		return false;
	}
	if (formField.value == "")
	{
		return true;
	}
	
	var components = formField.value.split(" ");
	
	//components should now contain two elements: the date and time
	var result = (components.length == 2);
	if (result)
	{
		var dateStr = components[0];
		var timeStr = components[1];

		//Check date
		var elems = dateStr.split("-");
		result = (elems.length == 3);

		if (result)
		{
			var yearStr = elems[0]; var monthStr = elems[1]; var dayStr = elems[2];
			var year = parseInt(yearStr,10);
			var month = parseInt(monthStr,10);
			var day = parseInt(dayStr,10);
			result = allDigits(yearStr) && (yearStr.length == 4) &&  
					 allDigits(monthStr) && (monthStr.length < 3) && (month > 0) && (month < 13) &&
					 allDigits(dayStr) && (dayStr.length < 3) && (day > 0) && isValidDay(year, month, day);
		}
		
		//Check time
		elems = timeStr.split(":");
		result = (elems.length == 2) && result;
		
		if (result)
		{
			var hourStr = elems[0];
			var minStr = elems[1];
			var hour = parseInt(hourStr, 10);
			var minute = parseInt(minStr, 10);
			result = allDigits(hourStr) && hourStr.length < 3 && hour >= 0 && hour < 24 &&
			  allDigits(minStr) && minStr.length < 3 && minute >= 0 && minute < 60;
		}
	
	}
	if (!result)
	{
		alert('Please enter a timestamp in the format YYYY-MM-DD hh:mm for this field.');
		formField.focus(); formField.select();
		return false;
	}
	return true;
}

//We strictly require that the time be in the form hh:mm
function validTime(formField, isRequired)
{
	if (!checkRequired(formField, isRequired))
	{
		return false;
	}
	if (formField.value == "")
	{
		return true;
	}
	
	var components = formField.value.split(":");
	
	//components should now contain three elements: hour, minute and second
	var result = (components.length == 3);
	if (result)
	{
		var hourStr = components[0];
		var minStr = components[1];
		var secStr = components[2];
		var hour = parseInt(hourStr, 10);
		var minute = parseInt(minStr, 10);
		var second = parseInt(secStr, 10);
		result = allDigits(hourStr) && hourStr.length < 3 && hour >= 0 && hour < 24 &&
		  allDigits(minStr) && minStr.length < 3 && minute >= 0 && minute < 60 &&
		  allDigits(secStr) && secStr.length < 3 && second >= 0 && second < 60;
	}
	if (!result)
	{
		alert('Please enter a time in the format hh:mm:ss for this field.');
		formField.focus(); formField.select();
		return false;
	}
	return true;
}


function validInt(formField, isRequired)
{
	if (!checkRequired(formField, isRequired))
	{
		return false;
	}
	if (formField.value == "")
	{
		return true;
	}

	if (!allDigits(formField.value))
	{
		alert('Please enter a number for this field.');
		formField.focus(); formField.select();
		return false;
	}
	return true;
}

function validDouble(formField, isRequired)
{
	if (!checkRequired(formField, isRequired))
	{
		return false;
	}
	if (formField.value == "")
	{
		return true;
	}

	if (!inValidCharSet(formField.value, "0123456789."))
	{
		alert('Please enter a number for this field.');
		formField.focus(); formField.select();
		return false;
	}
	return true;
}

function validYear(formField, isRequired)
{
	if (!checkRequired(formField, isRequired))
	{
		return false;
	}
	if (formField.value == "")
	{
		return true;
	}
	
	if (allDigits(formField.value) && formField.value.length == 4)
	{
		return true;
	}
	else
	{
		alert('Please enter a valid year for this field.');
		formField.focus(); formField.select();
		return false;
	}
}

// the currency should be in the format 150,000 or 150000
function validPriceInt(formField, isRequired)
{
	if (!checkRequired(formField, isRequired))
	{
		return false;
	}
	if (formField.value == "")
	{
		return true;
	}

	var num = formField.value.replace(/\,/g,'');
	if(!allDigits(num))
	{
		alert('Please enter a valid amount in the format 10,000 for this field.');
		formField.focus(); formField.select();
		return false;
	}

	// format it to be 150,000 format
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	{
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	}

	formField.value = num;
	return true;
}

// Given a phone number, formats it and validates it
function formatPhone(textField)
{
	var value = textField.value;

	if ( value == "" )
	{
		return true;
	}

	var newValue = "";
	for ( var i = 0; i < value.length; i++ )
	{
		var ch = value.substr(i, 1);
		if ( !isNaN(parseInt(ch)) )
		{
			newValue += ch;
		}
	}
	
	value = newValue;

	if ( value.length == 7 )
	{
		textField.value = value.substr(0, 3) + "-" + value.substr(3, 4);
	}
	else if ( value.length == 10 )
	{
		textField.value = value.substr(0, 3) + "-" + value.substr(3, 3) + "-" + value.substr(6, 4);
	}
	else
	{
		alert("A phone number is expected to have 7 or 10 digits");
		textField.focus();
		textField.select();
		return false;
	}
	return true;
}

// Given a postal/zip code, formats it for the user
function formatPostalCode(textField)
{
	var value = textField.value;
	if ( !allDigits(value) && value.length == 6 )
	{
		//Must be a postal code, so lets space it out for them
		textField.value = value.substr(0, 3) + " " + value.substr(3, 3);
	}
	
	textField.value = textField.value.toUpperCase();
}
