/******************************************************************************
Include file containing objects/functions used in contests.

MANIFEST
--------

	function checkForm(form):		Validate the standard contest entry form.
	function checkFormFR(form):		Same as above, with French error messages.
	function keyJump(textbox, targetID, length):
									Shift focus to another control once a 
									certain number of characters has been 
									entered into a textbox (assign to "onkeyup"
									event)	
	function getListIndex(selectList, value):
									Find the index of a value within a dropdown
									list
									
Boolean tests:

	function isEmpty(string)
	function isValidLength(string, min, max)
	function isValidEmail(address)
	function isValidPostalcode(postalcode)
	function isNumeric(string, ignoreWhiteSpace)
	function isAlphanumeric(string, ignoreWhiteSpace)
	function isAlphabetic(string, ignoreWhiteSpace)
	function isWhitespace (string)
	function isRadioValue(ctlRadio)

Formatting functions:

	function removeBadCharacters(string)
	function removeSpaces(string)
	function trimWhitespace(string)

Image-swapping functions:

	function storeImage(passive_image, active_image)
	function swapImage(image)
	
******************************************************************************/

// whitespace characters
var whitespace = " \t\n\r";



/////////////////////////////////////////////////
// validate the standard YTV form.
function checkForm(form) {

	var errors = '';
	
	if (isEmpty(form.firstname.value)) {
		errors += '- Please enter your first name.\n';
		form.firstname.focus();
	}

	if (isEmpty(form.lastname.value)) {
		errors += '- Please enter your last name.\n';
		form.lastname.focus();
	}

	if (isEmpty(form.address1.value)) {
		errors += '- Please enter your address.\n';
		form.address1.focus();
	}
	if (isEmpty(form.city.value)) {
		errors += '- Please enter your city.\n';
		form.city.focus();
	}
	if (form.province[form.province.selectedIndex].value=='empty') {
		errors += '- Please select a province.\n';
		form.province.focus();
	}
			
	if (!isValidPostalcode(form.postalcode1.value + form.postalcode2.value)) {
		errors += '- The postal code field is not valid.\n';
		form.postalcode1.focus();
	}
	//check email if found.
	if(form.email) {
		if (!isEmpty(form.email.value))
		{
			if (!isValidEmail(form.email.value)) {
				errors += '- The email field is not valid.\n';
				form.email.focus();
			}
		}
	}
	if(form.parent) {
		if ((form.age.value < 13)&&(isEmpty(form.parent.value))){
			errors += '- You must provide your Parent/Guardian name.\n';
			form.phone1.focus();
		}
	}
	if(form.under13) {
		if ((form.age.value < 13)&&(!form.under13.checked)) {
			errors += '- You must have consent from your Parent/Guardian.\n';
			form.phone1.focus();
		}
	}
	
	var strPhone = form.phone1.value.toString() + form.phone2.value.toString() + form.phone3.value.toString();
	if ((strPhone.length!=10) || (!isNumeric(strPhone))) {
		errors += '- The phone number must be in the form 123 456 7890.\n';
		form.phone1.focus();
	}
	if (!isNumeric(form.age.value)) {
		errors += '- Your age must be numeric.\n';
		form.age.focus();
	}
	if(form.readrules)
	{
		if (form.readrules.checked) {
			form.readrules.value = '1'
			}
			else {
			errors += '- You must read the Rules.\n';
			form.readrules.focus();
		}
	}
	// check send to friend if found.
	if(form.permission) {
		if (form.permission.checked) {
			if (isEmpty(form.TAG2.value)){
				errors += '- Please provide your friend\'s email address.\n';
				form.TAG2.focus();
			}
			else 
				if(!isValidEmail(form.TAG2.value)){
					errors += '- Your friend\'s email address is invalid.\n';
					form.TAG2.focus();
				}
		}
		else
			if (!isEmpty(form.TAG2.value)){
				errors += '- You must have your friend\'s permission to email them.\n';
				form.TAG2.focus();
			}
	}

	if (errors.length > 0) {
		errors = 'You need to fill in everything before you can enter.' + '\n\n' + errors + '\nPlease fill in all the fields and try again!';
		alert(errors);
		return false
	}
	else
		return true
}




/////////////////////////////////////////////////////
// validate the standard YTV form with French errors.
function checkFormFR(form) {

	var errors = '';
	
	if (isEmpty(form.firstname.value)) {
		errors += '- Inscris ton prénom.\n';
		form.firstname.focus();
	}

	if (isEmpty(form.lastname.value)) {
		errors += '- Inscris ton nom de famille.\n';
		form.lastname.focus();
	}

	if (isEmpty(form.address1.value)) {
		errors += '- Inscris ton adresse.\n';
		form.address1.focus();
	}
	if (isEmpty(form.city.value)) {
		errors += '- Inscris ta ville.\n';
		form.city.focus();
	}
	if (form.province[form.province.selectedIndex].value=='empty') {
		errors += '- Choisis ta province.\n';
		form.province.focus();
	}
			
	if (!isValidPostalcode(form.postalcode1.value + form.postalcode2.value)) {
		errors += "- Ton code postal n'est pas valide.\n";
		form.postalcode1.focus();
	}
	//check email if found.
	if(form.email) {
		if (!isValidEmail(form.email.value)) {
			errors += "- Ton e-mail n'est pas valide.\n";
			form.email.focus();
		}
	}
	if(form.parent) {
		if ((form.age.value < 13)&&(isEmpty(form.parent.value))){
			errors += '- Tu dois inscrire le nom de ton parent/tuteur légal.\n';
			form.phone1.focus();
		}
	}
	if(form.under13) {
		if ((form.age.value < 13)&&(!form.under13.checked)) {
			errors += '- Tu dois obtenir le consentement de ton parent/tuteur légal.\n';
			form.phone1.focus();
		}
	}
	
	var strPhone = form.phone1.value.toString() + form.phone2.value.toString() + form.phone3.value.toString();
	if ((strPhone.length!=10) || (!isNumeric(strPhone))) {
		errors += '- Inscris ton numéro de téléphone de cette façon : 123 456 7890.\n';
		form.phone1.focus();
	}
	if (!isNumeric(form.age.value)) {
		errors += '- Inscris ton âge en chiffres\n';
		form.age.focus();
	}
	if (form.readrules.checked) {
		form.readrules.value = '1'
		}
		else {
		errors += '- Tu dois lire le règlement.\n';
		form.readrules.focus();
	}
	
	// check send to friend if found.
	if(form.permission) {
		if (form.permission.checked) {
			if (isEmpty(form.TAG2.value)){
				errors += '- Please provide your friend\'s email address.\n';
				form.TAG2.focus();
			}
			else 
				if(!isValidEmail(form.TAG2.value)){
					errors += '- Your friend\'s email address is invalid.\n';
					form.TAG2.focus();
				}
		}
		else
			if (!isEmpty(form.TAG2.value)){
				errors += '- You must have your friend\'s permission to email them.\n';
				form.TAG2.focus();
			}
	}

	if (errors.length > 0) {
		errors = 'Remplis bien tous les champs pour pouvoir participer.' + '\n\n' + errors + '\n Remplis bien tous les champs et essaie encore !';
		alert(errors);
		return false
	}
	else
		return true
}




///////////////////////////////////////////////////////////////////////
//shift focus to another control once a certain number of characters 
//has been entered into a textbox (assign to "onkeyup" event)
function keyJump(textbox, targetID, length) {
	if(textbox.value.length >= length)
		{eval('document.frmEnter.' + targetID).focus();
	}
}






//////////////////////////////////////////////////
//Find the index of a value within a dropdown list
function getListIndex(selectList, selectValue) {
	var selectedIndex = 0;
	for(var i=0;i<selectList.length;i++) {
		if(selectList[i].value == selectValue) {
			selectedIndex = i;
		}
	}
	return selectedIndex
}




/***** BOOLEAN TESTS. ******/


// Check whether a string is empty
function isEmpty(string) {
	return ((string==null) || (string.length==0))
}



// Check that the number of characters in a string is between a max and a min
function isValidLength(string, min, max) {
	if (string.length < min || string.length > max) return false;
	else return true;
}

// Check that a Canadian postal code is valid
function isValidPostalcode(postalcode) {
	if (postalcode.search){
		if (postalcode.length == 6 && (postalcode.search(/^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i) != -1)) return true;
		else return false;
	}	
}

/*
// Check that an email address is valid based on RFC 821 (?)
function isValidEmail(address) {
	
	//if (address.toString().indexOf('@') == -1) return false;
	
	var name = address.substring(0, address.indexOf('@'));
	var domain = address.substring(address.indexOf('@') + 1);
	if (name.indexOf('(') != -1 || name.indexOf(')') != -1 || name.indexOf('<') != -1 || name.indexOf('>') != -1 || name.indexOf(',') != -1 || name.indexOf(';') != -1 || name.indexOf(':') != -1 || name.indexOf('\\') != -1 || name.indexOf('"') != -1 || name.indexOf('[') != -1 || name.indexOf(']') != -1 || name.indexOf(' ') != -1) return false;
	if (domain.indexOf('(') != -1 || domain.indexOf(')') != -1 || domain.indexOf('<') != -1 || domain.indexOf('>') != -1 || domain.indexOf(',') != -1 || domain.indexOf(';') != -1 || domain.indexOf(':') != -1 || domain.indexOf('\\') != -1 || domain.indexOf('"') != -1 || domain.indexOf('[') != -1 || domain.indexOf(']') != -1 || domain.indexOf(' ') != -1) return false;
	return true;

}
*/
// FYI: Another email checker
//^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$ 



/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function isValidEmail(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}




/*
//function seriousEmailCheck (emailStr) {
function isValidEmail(emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {
		return false;
	}

	var user=matchArray[1];
	var domain=matchArray[2];

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
		return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			return false;
		}
	}

	if (user.match(userPat)==null) {
		return false;
	}

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
			return false;
		   }
		}
		return true;
	}

	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) {
			return false;
	   }
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		return false;
	}

	if (len<2) {
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}
*/



// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) return false;
	}
	return true;
}



// Check that a string contains only letters and numbers
function isAlphanumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
	}
	return true;
}




// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
	}
	return true;
}






// Returns true if string s is empty or whitespace characters only.
function isWhitespace (string) {
   var i;
    if (isEmpty(string)) return true;
    
    for (i = 0; i < string.length; i++) {   
		// Check that current character isn't whitespace.
		var c = string.charAt(i);
		if (whitespace.indexOf(c) == -1) return false;
		}
    // All characters are whitespace.
    return true;
}



// Check that a radio button has been picked
function isRadioValue(ctlRadio) {
	var radio_choice = false;

	// Loop from zero to the one minus the number of radio button selections
	for (counter = 0; counter < ctlRadio.length; counter++) {
		// If a radio button has been selected it will return true
		if (ctlRadio[counter].checked) {
			radio_choice = true;
		}
	}
	return radio_choice;
}



/***** FORMATTING FUNCTIONS. *****/


// Remove characters that might cause security problems from a string 
function removeBadCharacters(string) {
	if (string.replace) {
		string.replace(/[<>\"\'%;\)\(&\+]/, '');
	}
	return string;
}



// Remove all spaces from a string
function removeSpaces(string) {
	var newString = '';
	for (var i = 0; i < string.length; i++) {
		if (string.charAt(i) != ' ') newString += string.charAt(i);
	}
	return newString;
}





// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
	var newString  = '';
	var substring  = '';
	beginningFound = false;
	
	// copy characters over to a new string
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < string.length; i++) {
		
		// copy non-whitespace characters
		if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {
			
			// if the temporary string contains some whitespace characters, copy them first
			if (substring != '') {
				newString += substring;
				substring = '';
			}
			newString += string.charAt(i);
			if (beginningFound == false) beginningFound = true;
		}
		
		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (beginningFound == true) substring += string.charAt(i);
	}
	return newString;
}



/*****  IMAGE SWAPPING FUNCTIONS  *****/


var arrNavImage;


//Add an image to the nav array.
function storeImage(passive_image, active_image)
{
	if(document.images)
	{
		if(arrNavImage!=null)
		{
			var arrBuffer = new Array(arrNavImage.length);
			for(var i=0;i<arrBuffer.length;i++)
			{
				arrBuffer[i] = new Array(2);
				arrBuffer[i][0] = arrNavImage[i][0];
				arrBuffer[i][1] = arrNavImage[i][1];
			}
			arrNavImage = new Array(arrBuffer.length + 1)
			for(var i=0;i<arrBuffer.length;i++)
			{
				arrNavImage[i] = new Array(2);
				arrNavImage[i][0] = arrBuffer[i][0];
				arrNavImage[i][1] = arrBuffer[i][1];
			}
		}
		else
			arrNavImage = new Array(1);

		arrNavImage[arrNavImage.length-1] = new Array(2);
		arrNavImage[arrNavImage.length-1][0] = new Image();
		arrNavImage[arrNavImage.length-1][0].src = passive_image;
		arrNavImage[arrNavImage.length-1][1] = new Image();
		arrNavImage[arrNavImage.length-1][1].src = active_image;
	}
}



//swap an image's passive image with its active version.
function swapImage()
{

	var myImage;
	
	//Find the image in question.
	if(swapImage.arguments.length > 0)
	{
		if(typeof swapImage.arguments[0] == 'string')
			myImage = document.getElementById(swapImage.arguments[0]);
		else
			myImage = image;
	}

	//Swap the image with its alternate version.
	if(document.images && arrNavImage != null && myImage != null)
	{
		for(var i=0;i<arrNavImage.length;i++)
		{
			//check passive images.
			if(arrNavImage[i][0].src == myImage.src)
			{
				//swap with active version.
				myImage.src = arrNavImage[i][1].src;
				break;
			}
			//check active images.
			else if(arrNavImage[i][1].src == myImage.src)
			{
				//swap with passive version.
				myImage.src = arrNavImage[i][0].src;
				break;
			}

		}
	}
}