/**
* SimpleUpdates Validation Javascript Functions
* 
* Contains validation functions for all standard validation types
*/

var SU_standard_validation_types = new Array("required", "multiple_email", "url", "database_date", "time_24h_format");

/**
* email
* 
* @param string email The email to test
*/
function validate_multiple_email(email)
{
	if(email.search(",") != -1)
	{
		var emails = email.split(",");
		for(var i = 0; i < emails.length; i++)
		{
			email = emails[i];
			var apos = email.indexOf("@");
			var dotpos = email.lastIndexOf(".");
			var length = email.length;
			if(apos<=0 || dotpos-apos<=1 || length-dotpos<=2) return false;
		}
		return true;
	}
	else
	{
		var apos = email.indexOf("@");
		var dotpos = email.lastIndexOf(".");
		var length = email.length;
		return (apos>0 && dotpos-apos>1 && length-dotpos>2);
	}
}
function validate_url(url)
{
	var dotpos = url.lastIndexOf(".");
	var length = url.length;
	return (length - dotpos>2 && dotpos > 0);
}

function validate_required(value)
{
	return (value.length > 0);
}

/**
 * Makes sure that the date is in the correct format for the database.
 * @param date the date to test
 */
function validate_database_date(date)
{
	var dateRegex = /^(\d{4})-(\d\d)-(\d\d)$/;
	var matches = dateRegex.exec(date);
	if (matches == null) {
		return false;
	}
	var year = matches[1];
	var month = matches[2];
	var day = matches[3];

	var dateTest = new Date();
	dateTest.setFullYear(year, month-1, day);
	
	if (
		dateTest.getFullYear() != year
		|| dateTest.getDate() != day
		|| dateTest.getMonth() != month-1
	) {
		return false;
	}
	return true;
}

/**
 * This is named improperly for the javascript side of things.  This actually
 * checks to make sure that the time is in the correct 12h format since we want
 * all of our times displayed to the user in 12h format.
 * @param time the time to test
 */
function validate_time_24h_format(time)
{
	//This regex should make sure that the hour is in the range 1-12
	//and the minutes and seconds are in the range 00-59
	var timeRegex = /^(0?[1-9]|1[0-2]):[0-5][0-9](:[0-5][0-9])? (am|pm)$/;
	var matches = timeRegex.exec(time);
	if (matches == null) {
		return false;
	}
	return true;
}