/*
PRODUCT: 	General JavaScript Utilities for Cookies, Popup Windows, and Form Validation
VERSION:	1.01, April 2004
CONTACT:	Future Shock Ltd, www.Future-Shock.net, post@future-shock.net

This file may be used freely as long as none of the comments are not removed.

NOTES:
Optional arguments for functions can be skipped by sending null when you call the function,
for example: FSfncSetCookie('MyCookieName','MyCookieValue',null,null,'www.mydomain.com',true).
This is not required if you are skipping all optional arguments,
for example: FSfncSetCookie('MyCookieName','MyCookieValue')
Both routines use the TITLE attribute of the form element in validity warning messages.
*/

function emailCheck(emailStr) {
	emailStr = emailStr.toLowerCase(); // Validate email address
	var checkTLD=0; // Verify that the address ends in a two-letter country or well-known TLD.  1 means check it, 0 means don't.
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|co|uk)$/; // Known TLDs that an e-mail address must end with.
	var emailPat=/^(.+)@(.+)$/; // Pattern to check if the entered e-mail address fits the user@domain format, also used to separate the username from the domain.
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; // Pattern for matching all special characters. Do not allow special characters in address. These include ( ) < > @ , ; : \ " . [ ]
	var validChars="\[^\\s" + specialChars + "\]"; //Range of characters allowed in username or domainname (really states which chars aren't allowed).
	var quotedUser="(\"[^\"]*\")"; // Pattern applies if "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't).  E.g. "jiminy cricket"@disney.com is a legal e-mail address.
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; // Pattern applies for domains that are IP addresses, rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal e-mail address (square brackets are required).
	var atom=validChars + '+'; // Represents an atom (basically a series of non-special characters).
	var word="(" + atom + "|" + quotedUser + ")"; // Represents one word in the typical username. Eg. in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string.
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); // Pattern describes the structure of the user
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); // Pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above.

	// Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze.
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		// Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address.
		alert("The email address you entered seems incorrect (check @ and .'s)");
		return false;
		}
	var user=matchArray[1];
	var domain=matchArray[2];
	// Check that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {if (user.charCodeAt(i)>127) {alert("The email address you entered contains invalid characters. Please try again.");return false}}
	for (i=0; i<domain.length; i++) {if (domain.charCodeAt(i)>127) {alert("The email address you entered contains invalid characters. Please try again.");return false}}
	// See if "user" is valid
	if (user.match(userPat)==null) {alert("The email address you entered doesn't seem to be valid.");return false}
	// if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid.
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		// this is an IP address
		for (var i=1;i<=4;i++) {if (IPArray[i]>255) {alert("IP address is invalid!");return false}}
		return true;
		}
	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {if (domArr[i].search(atomPat)==-1) {alert("The email address name does not seem to be valid.");return false}}
	// Make sure domain name ends in a known top-level domain or a two-letter word representing country (uk, nl)
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {alert("The email address you enter must end in a well-known domain or two letter " + "country.");return false}
	// Make sure there's a host name preceding the domain.
	if (len<2) {alert("This email address is missing a hostname!");return false}
	// Email address is valid!
	return true;
	}

function checkForm(formRef) {
	if (formRef.Fullname.value=="") {alert("Full name cannot be blank"); formRef.Fullname.focus(); return false}
	if (formRef.Username.value=="") {alert("Username cannot be blank"); formRef.Username.focus(); return false}
	if (formRef.Password.value=="") {alert("Password cannot be blank"); formRef.Password.focus(); return false}
	if (formRef.Password.value.length<5) {alert("Password must be at least 5 characters"); formRef.Password.focus(); return false}
	if (formRef.ConfirmPassword.value!=formRef.Password.value) {alert("Passwords do not match"); formRef.ConfirmPassword.focus(); return false}	
	return emailCheck(formRef.Email.value)
	}
	
function checkFormForgotten(formRef) {
	if (formRef.Username.value=="") {alert("Username cannot be blank"); formRef.Username.focus(); return false}
	return emailCheck(formRef.Email.value)
	}
	
function checkFormComment(formRef) {
	if (formRef.Comment.value.length<2) {
		alert("Comment cannot be blank"); formRef.Comment.focus(); return false
	}
}


function checkFormChangePass(formRef) {
	if (formRef.ExistingPassword.value=="") {alert("Existing password cannot be blank"); formRef.ExistingPassword.focus(); return false}
	if (formRef.Password.value=="") {alert("Password cannot be blank"); formRef.Password.focus(); return false}
	if (formRef.ConfirmPassword.value!=formRef.Password.value) {alert("Passwords do not match"); formRef.ConfirmPassword.focus(); return false}
	}



function FSfncCheckString(FormField,AllowBlank,MaxLength) {
	// MaxLength is optional, when not provided the string is only checked for being blank.
	// Implement by adding onSubmit handler to FORM or onBlur handler to INPUT or TEXTAREA element, eg. onBlur="FSfncCheckString(this,false,10)".
	if ((AllowBlank==false) && (FormField.value=="")) {alert(FormField.title + " cannot be blank"); FormField.focus(); return false}
	if ((MaxLength!="") && (FormField.value.length>MaxLength)) {alert(FormField.title + " must be no more than " + MaxLength + " characters long"); FormField.focus(); return false}
	return true;
	}

function FSfncCheckNumber(FormField,AllowBlank,PositiveOnly,IntegerOnly) {
	// AllowBlank, PositiveOnly, and IntegerOnly are optional
	// Implement by adding onSubmit handler to FORM or onBlur handler to INPUT element, eg. onBlur="FSfncCheckNumber(this,false,true,true)".
	if (isNaN(FormField.value)) {alert(FormField.title + " must be a number"); FormField.focus(); return false}
	if ((AllowBlank==false) && (FormField.value=="")) {alert(FormField.title + " cannot be blank"); FormField.focus(); return false}
	if ((PositiveOnly) && (FormField.value<0)) {alert(FormField.title + " cannot be negative"); FormField.focus(); return false}
	if ((IntegerOnly) && (FormField.value.indexOf(".")>-1)) {alert(FormField.title + " cannot contain a decimal point"); FormField.focus(); return false}
	return true;
	}

function FSfncCheckTime(FormField) {
	// Check time is supplied in valid 24 hour clock (hh:mm) format.
	// Implement by adding onSubmit handler to FORM or onBlur handler to INPUT element, eg. onBlur="FSfncCheckTime(this)".
	if (FormField.value.indexOf(":")==-1) {alert(FormField.title + " is not a valid time"); FormField.focus(); return false}
	var ArrayTime = FormField.value.split(":");
	if ((ArrayTime.length!=2) || (isNaN(ArrayTime[0])) || (ArrayTime[0]=="") || (isNaN(ArrayTime[1])) || (ArrayTime[1]=="")) {alert(FormField.title + " is not a valid time"); FormField.focus(); return false}
	if ((parseInt(ArrayTime[0],10)<0) || (parseInt(ArrayTime[0],10)>23) || (parseInt(ArrayTime[1],10)<0) || (parseInt(ArrayTime[1],10)>59)) {alert(FormField.title + " is not a valid time"); FormField.focus(); return false}
	return true;
	}

function FSfncCheckDateFormat(FormField,FormatMode) {
	// Check date supplied is valid. FormatMode is optional, when not supplied it defaults to 1 (1=dd/mm/yyyy, 0=mm/dd/yyyy).
	// Implement by adding onSubmit handler to FORM or onBlur handler to INPUT element, eg. onBlur="FSfncCheckDateFormat(this,0)".
	if (FormatMode!=0) {FormatMode=1}
	if (FormField.value.indexOf("/")==-1) {alert(FormField.title + " is not a valid date"); FormField.focus(); return false}
	var ArrayDate = FormField.value.split("/");
	if ((ArrayDate.length!=3) || (isNaN(ArrayDate[0])) || (ArrayDate[0]=="") || (isNaN(ArrayDate[1])) || (ArrayDate[1]=="") || (isNaN(ArrayDate[2])) || (ArrayDate[2]=="")) {alert(FormField.title + " is not a valid date"); FormField.focus(); return false}
	var daysInMonth = new Array(0,31,29,31,30,31,30,31,31,30,31,30,31);
	if ((parseInt(ArrayDate[1 - FormatMode],10)<1) || (parseInt(ArrayDate[1 - FormatMode],10)>daysInMonth[parseInt(ArrayDate[0 + FormatMode],10)])) {alert(FormField.title + " is not a valid date"); FormField.focus(); return false}
	if ((parseInt(ArrayDate[0 + FormatMode],10)==2) && (parseInt(ArrayDate[1 - FormatMode],10)>FSfncDaysInFebruary(parseInt(ArrayDate[2],10)))) {alert(FormField.title + " is not a valid date"); FormField.focus(); return false}
	if ((parseInt(ArrayDate[0 + FormatMode],10)<1) || (parseInt(ArrayDate[0 + FormatMode],10)>12)) {alert(FormField.title + " is not a valid date"); FormField.focus(); return false}
	return true;
	}

function FSfncDaysInFebruary(year) {return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 )}

function FSfncPopUp(NextPage,width,height,resizable,scrollbars,status) {
	// resizable,scrollbars, and status are optional, when not provided these default to no.
	// Implement by adding onClick handler to any element, eg. onClick="FSfncPopUp('PopupContent.htm',200,100,'yes','yes','yes')".
	if (resizable=="") {resizable="no"}
	if (scrollbars=="") {scrollbars="no"}
	if (status=="") {status="no"}
	x=self.screenLeft + 10;
	y=self.screenTop + 10;
	if (navigator.appVersion.indexOf("AOL")>0) {winName="A" + (Math.round(Math.random() * 1000))} else {winName="FSpopUpWindow"}
	FSpopUp=window.open(NextPage,winName,'toolbar=no,width=' + width + ',height=' + height + ',left=' + x + ',screenX=' + x + ',top=' + y + ',screenY=' + y + ',status=' + status + ',scrollbars=' + scrollbars + ',resizable=' + resizable + ',menubar=no,directories=no');
	}

function FSfncReadCookie(key) {
	// Implement by calling the function with the name of the cookie required, eg. FSfncReadCookie('MyCookieName'), the cookie value will be returned.
	var cookie_string='' + document.cookie;
	var cookie_array=cookie_string.split('; ');
	for (var i=0; i<cookie_array.length; i++) {
		var single_cookie=cookie_array[i].split('=');
		if (single_cookie.length!=2) {continue}
		if (key==unescape(single_cookie[0])) {return unescape(single_cookie[1])}
		}
	return 'None';
	}

function FSfncSetCookie(name,value,expires,path,domain,secure) {
	// expires,path,domain,secure are optional, if supplied the expires must be a JavaScript date object, path and domain are strings, and secure is true/false.
	// Implement by calling the function, eg. FSfncSetCookie('MyCookieName','MyCookieValue').
	document.cookie=name + '=' + escape(value) + ((expires == null) ? '' : ('; expires=' + expires.toGMTString())) + ((path == null) ? '' : ('; path=' + path)) + ((domain == null) ? '' : ('; domain=' + domain)) + ((secure == true) ? '; secure' : '');
	}


