/* 
	function validate_date()  6/14/01 JB
	this function takes a string argument as input i.e. myfield.value and attempts to parse it as a date.
	it returns one of seven possible return values, which are documented below.
	possible delimiters for a date are / - .  i.e.  all of these are valid dates:  1/1/2000  1-1-2000  1.1.2000

	possible return values:
		0 - it is a valid date
		1 - it is not a valid date.  prompt the user to use correct format (see above)
		2 - the date entries between the delimiters are not numeric, i.e. something like er/tu/asdk
		3 - the month is not between 1 and 12
		4 - the day is not between 1 and 31
		5 - the year is not between 1900 and 2100
		6 - the day number entered does not correspond to the month entered
		7 - more than 10 characters in the date, does not conform to mm/dd/yyyy

	NOTE:  this script DOES check for leap year consistency.
	
	ALSO NOTE:  just because this function returns all these values doesn't mean you have to check for every single one.  for example, it's sufficient to say 

		(if validate_date(mydate.value) != 0)
		  alert('bad date');
		  
	the extra return values are just there if you need more detailed information about why/what part of the date is invalid.

	ONE MORE NOTE:  this function DOES NOT support eurodates!
	it assumes that the date will be passed with month first, then day, then year.
	if we have a need for eurodates in the future, i can easily extend this function to support it.
	
	THE FINAL NOTE:  i request that if there is a need for enhanced functionality, create a new date validation function, copy my code into it, and go from there.  pretty please with sugar on top, leave this function as is.  thank you.
*/

function validate_date(a)
{
	dmask = "mm/dd/yyyy";
	num_elements = 3;
	monthf = 0;
	dayf = 1;
	yearf = 2;
	
	var pat = /[^0-9\/]/g;			// test for alphas
	var str1 = String(a);
	r1 = pat.test(str1);

	if(r1)							// test for alphas
		return(9);
		
	if (a == '')						  // it's ok if they don't enter a date at all
		return(0);
		
	b = new String(a);				// convert passed value to a String object so we can chop it up
	 
	if (b.length > 10)
		return(7);
	   
	c = b.split(/[\/\-\.]/);		// this chops the passed argument into an array of strings

	if (c.length != num_elements)			// if we don't have 3 elements, the date was not in the right format.
		return(1);
	 
	for (i=0;i<num_elements;i++)		// this makes sure every element of the date is numeric
	{
		if (isNaN(parseInt(c[i])))
			return(2);
	}

	d = new Array(num_elements);
	
	for (i=0;i<num_elements;i++)		// this makes sure every element of the date is numeric
	{
		d[i] = new Number(c[i]);
	}
	
	if (yearf != -1) 
	{
		if (((d[yearf]%4 == 0) && (d[yearf]%100 != 0)) || (d[yearf]%400 == 0))		// leap year calculation
			ly = 1;
		else
			ly = 0;
	}
	else
		ly = 0;

	if (monthf != -1)
	{
		if (d[monthf] < 1 || d[monthf] > 12)		// months must be between 1 and 12
			return(3);
	}

	if (dayf != -1)
	{
		if (d[dayf] < 1 || d[dayf] > 31)		// days must be between 1 and 31
			return(4);
	}
	
	if (yearf != -1)
	{
		if (d[yearf] < 1900 || d[yearf] > 2100)		// years must be between 1900 and 2100
			return(5);
	}

	if ((d[monthf] == 2 && ((ly == 1 && d[dayf] > 29) || (ly == 0 && d[dayf] > 28))) || ((d[monthf] == 4 || d[monthf] == 6 || d[monthf] == 9 || d[monthf] == 11) && d[dayf] > 30))		// the number of days for each month can not exceed certain values
		return(6);

	return(0);
}
  
  
/* 
	function deny()  6/25/01 JB
	this is an extremely simple function that just serves to render a link unusable, without removing it from the screen.
	right now, this is mostly just used in the admin section where i wanted to preserve the formatting of the table, but
	disable the links so that users weren't messing with features they didn't have.
	
	use with the onmousedown() event handler for best results
	
	return values:  always false
*/

function deny()
{
   window.status='';
   alert('The function you\'re attempting to access has been disabled.');
   return false;
}


/* 
	function obscure_status()  6/25/01 JB
	this is an extremely simple function that obscures the status line of the href in a link.  i use this in conjunction with the 
	above deny() function to do a simple disable of some links.
	
	use with the onmouseover() event handler for best results
	
	return values:  always true
*/

function obscure_status()
{
   window.status='';
   return true;
}

// new and improved email validator
function email_validate(str)
{
	t = new String(str);
	if (t.match(/^\s*[-a-zA-Z0-9_\.]+@[-a-zA-Z0-9_\.]+\.[a-zA-Z]{2,}\s*$/)) {
		return true;
	} else {
		return false;
	}
}


/*
	function validate_email()  7/17/01 JB
	this function validates a text field to see if it has a valid email address in it.  it checks to see if there is more than
	one address present, and if so, if the list is delimited by commas.  if it is not, it returns an error.
	
	return values:
	0 - it's a valid email address or a valid email address list
	1 - it is a single email address and is not valid
	2 - it is a list of email addresses with a delimiter that is not a comma
	3 - it is a list of email addresses, comma delimited, with an invalid entry
	
	USAGE:
	the usage for this function is fairly simple.  you can do it one of two ways.
	
	if (validate_email(email.value) != 0)
	{
		alert('bad email address');
		return false;
	}
	
	OR
	
	result = validate_email(email.value);
	
	then test result for each of the 4 return values, and return appropriate messages.
	
*/

function validate_email(a)
{
	invalid_email = 0;					// inital value for list checking
	if (a == '')							// it's ok if they don't enter a date at all
		return(0);
		
	s = String(a);						// make a new string object out of the passed in value
	cclist = s.split(",");				// split on the comma delimiter
	if (cclist.length == 1)			 // no commas found
	{
		if (cclist[0].indexOf("@") == -1 || cclist[0].indexOf(".") == -1)
		{
			return(1);					// email addresses must have at least . and exactly 1 @
		}
		else if(cclist[0].indexOf(" ") != -1){
			return(4);
		}
		else
		{
			regex = /@/g;			// search for all @
			t = s.match(regex);		
			if (t.length > 1)			// more than 1 @ found - assumed to be multiple addresses
			{
				return(2);				// a list not using a comma delimiter
			}
			else
			{
				return(0);				// valid email address
			}
		}
		
	}
	else
	{
		for (i=0;i<cclist.length;i++)
		{
			if (cclist[i].indexOf("@") == -1 || cclist[i].indexOf(".") == -1)
			{
				invalid_email = 1;			// one of the email addresses didn't have an @ or a .
			}
		}
		if (invalid_email == 1)
		{
			return(3);						// one of the email addresses in the comma delimited list is invalid
		}
		else
		{
			return(0);						// the whole list of addresses looks ok
		}
	}
}


// returns a random number between the 2 numbers specified
// small number first, big second, i.e. RandRange(1, 100)
function RandRange(a, b)
{
	return (Math.floor(Math.random() * (b - a)) + a);
}


// makes a field required
function required(myfield, msg)
{
	popup = 0;
	if (msg == "")
		msg = 'One of the form fields is required';
	
	if (myfield.type == "text" || myfield.type == "textarea" || myfield.type == "password")
	{
		if (myfield.value == "")
		{
			popup = 1;
		}
	}
	else if (myfield.type == "select-one")
	{
		if (myfield.selectedIndex == -1 || myfield.options[myfield.selectedIndex].value == "")
		{
			popup = 1;
		}
	}
	else if (myfield.type == "select-multiple")
	{
		found = 0;
		for (i=0; i<myfield.length; i++)
		{
			if (myfield.options[i].value != "" && myfield.options[i].selected == true)
			{
				found = 1;
			}
		}
		
		if (found == 0)
			popup = 1;
	}
	else if (typeof myfield == "object" && typeof myfield.length == "number") {
		tmp = 0;
		for (i=0; i<myfield.length; i++) {
			if (myfield[i].checked == true) {
				tmp = 1;
				break;
			}
		}
		
		if (tmp == 0)
			popup = 1;
	}
	
	if (popup == 1)
	{
		alert(msg);
		try {
			myfield.focus();
		} catch (e) {
			try {
				myfield[0].focus();
			} catch (f) { }
		}
		return 0;
	}
	else
		return 1;
}


/*	function validate_phone 8/14/02 JB
	validates a phone number for 123-123-1234 format
*/

function validate_phone(num)
{
	str = new String(num);
	
	if (str == "" || str.match(/\s/))
		return 0;		// it's ok if they don't enter anything
	else
	{
		if (str.match(/[0-9]{3}-[0-9]{3}-[0-9]{4}/)){
			return 0;		// valid phone number XXX-XXX-XXXX
		}
		else if (str.match(/\([0-9]{3}\)\s?[0-9]{3}-[0-9]{4}/)){ // tjhanley 05 26 04
			return 0;		// valid phone number (XXX) XXX-XXXX or (XXX)XXX-XXXX 
		}		
		else
			return 1;		// invalid
	}
}

function validate_number(num)
{
	str = new String(num);
	str = str.replace('$',"");
	str = str.replace('.',"");
	str = str.replace(',',"");
	
	if (str == "" || str.match(/\s/))
		return 0;		// it's ok if they don't enter anything
	else
	{
		if (str.match(/\D/))
			return 1;		// invalid
		else
			return 0;		// valid number
	}
}

function validate_currency(num)
{
	str = new String(num);
	if (!str.match(/^\s*\$?((([0-9]{1,3})(,[0-9]{3})*)|([0-9]+))(\.[0-9]{2})?\s*$/)) {
		return false;
	} else {
		return true;
	}
}

function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}

function replaceMSChars(str){
	if(str == ''){
		return str;
	}
	else{
		str = str.replace(/%u2013/g, "-"); // Ñ
		str = str.replace(/%u2018/g, "'"); // Ô
		str = str.replace(/%u2019/g, "'"); // Õ
		str = str.replace(/%u201C/g, "\""); // Ò
		str = str.replace(/%u201D/g, "\""); // Ó
		str = str.replace(/%u2022/g, "*"); // ¥
		str = str.replace(/%u2014/g, "--"); // Ð		
		return str;
	}

}
