//----------------------------------------------------------------------------------Global variables
var thisPage	 = document.URL;
var expiration 	 = new Date();
var alpha		 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var digit		 = "0123456789"

expiration.setTime(expiration.getTime() + 94608000000);

//------------------------------------------------------------------
// Enhance the String object with new trim(), ltrim(),
// and rtrim() methods, as in VB
//------------------------------------------------------------------
String.prototype.trim = function()
{ //Trim, as in VB
  return this.replace(/(^\s+)|(\s+$)/g, '');
}

String.prototype.ltrim = function()
{ //LTrim, as in VB
  return this.replace(/^\s+/g, '');
}

String.prototype.rtrim = function()
{ //RTrim, as in VB
  return this.replace(/\s+$/g, '');
}

function y2k(number) {return (number < 1000) ? number + 1900 : number;}

function isDate(year,month,day){
	month = month -1
	var test = new Date(year,month,day);
	if ((y2k(test.getYear()) == year ) && (month == test.getMonth()) && (day == test.getDate()))
		return true;	
	else
		return false;
}

//--- Check if the passing parameter is an alpha or not. Return true if yes, otherwise return false.
function is_alpha(parma) {
   if (alpha.indexOf(parma) == -1) {
      return false;
   } else {
      return true;
   }
}       

//--- Check if the passing parameter is a digit or not. Return true if yes, otherwise return false.
function is_digit(parmn) {
   if (digit.indexOf(parmn) == -1) {
      return false;
   } else {
      return true;
   }
}       

//--- Check if the passing parameter is a number or not. Return true if yes, otherwise return false.
function is_numeric(parmn) {
	if (isNaN(parmn)) return false;
	else return true;
}

//-------------------------------------------------------------------
function openPopupWindow( pageToLoad, winName, width, height, center) {
    xposition=0; yposition=0;
    if ((parseInt(navigator.appVersion) >= 4 ) && (center)){
        xposition = (screen.width - width) / 2;
        yposition = (screen.height - height) / 2;
    }
    args = "width=" + width + "," + "height=" + height + "," 
	+ "location=0,"   + "menubar=0," + "resizable=1," 
	+ "scrollbars=1," + "status=0,"  + "titlebar=0,"   
	+ "toolbar=0,"   + "hotkeys=0,"
    + "screenx=" + xposition + ","  //NN Only
    + "screeny=" + yposition + ","  //NN Only
    + "left=" + xposition + ","     //IE Only
    + "top=" + yposition;           //IE Only
	win = open( pageToLoad,winName,args );
}

//--- Get cookie value
function getCookieVal(offset) {  
	var endstr = document.cookie.indexOf (";", offset); 
	 
	if (endstr == -1)    
		endstr = document.cookie.length;  
	return unescape(document.cookie.substring(offset, endstr));
}

//--- Get cookie
function getCookie(name) {  
	var arg = name + "=";  
	var alen = arg.length;  
	var clen = document.cookie.length;  
	var i = 0;
	
	while (i < clen) {    
		var j = i + alen;    
		if (document.cookie.substring(i, j) == arg)      
			return getCookieVal (j);    
		i = document.cookie.indexOf(" ", i) + 1;    
		if (i == 0) break;   
	}  
	return null;
}

//--- get cookie with key
function getKeyCookie(name,key) {
	var strCookie = getCookie(name) + "&";
	var i = strCookie.indexOf(key, i) + key.length + 1;
	var j = strCookie.indexOf("&", i);

	if ((i == -1) || (j-i <= 0)) {
		return null;
	} else {	
		return strCookie.substr(i, j-i);
	}
}

//--- Set cookie
function setCookie(name, value, expires, path, domain, secure) {  // Set Cookie
  path = "/";
  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}

//--- delete cookie
function deleteCookie(name) {  
	var exp = new Date();  
	var cval = getCookie(name);
	
	exp.setTime (exp.getTime() - 1);  
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

//---------------------------------------------------------------------
function validName(sName)
{
	var sInvalidChars = "1234567890!@#$%^&*()_+-={}|[]";
	var i, c;
	
	for (i=0; i < sName.length; i++)
	{
		c = sName.substr(i,1);
		j = sInvalidChars.indexOf(c);
		if (j != -1)
		{
			return false;
		}
	}
	return true;
}

//---------------------------------------------------------------------
function validAddress(sAddress)
{
	// Valid characters - A to Z, a toz, 0 to 9 and .-,/#
	var sInvalidChars = "~!@$%^&*()_+`={}[]\|:;'<>?";
	var i, c;
	
	for (i=0; i < sAddress.length; i++)
	{
		c = sAddress.substr(i,1);
		j = sInvalidChars.indexOf(c);
		if (j != -1)
		{
			return false;
		}
	}
	return true;
}

//---------------------------------------------------------------------
function validPostalCodeEx(entry) 
{
	var re = /^([a-z]\d){3}$/i;
	if (re.test(entry)) {return true;}
	
	return false;
}

//---------------------------------------------------------------------
function validContent(sContent)
{
	// Valid characters - A to Z, a to z, 0 to 9 and .-,/#
	//var sInvalidChars = "~!@$%^&*()_+`={}[]\|:;'<>?";
	var sInvalidChars = "~@^`";

	var i, c;
	
	for (i=0; i < sContent.length; i++)
	{
		c = sContent.substr(i,1);
		j = sInvalidChars.indexOf(c);
		if (j != -1)
		{
			alert("Invalid characher '" + c + "' found in the content.");
			return false;
		}
	}
	return true;
}

//---------------------------------------------------------------------
// validate the email address. It must contain an @ symbol and a period (.)
// procedures:
// 1. trim the value of the passing object - em.
// 2. declare variables :
//    emadr = the upper case value of em
// 3. Check for the following errors:
//      - user enter email address
//		- '@' symbol not included in the email address
//		- email address begin with a digit.
//		- email address begin with '@' symbol
//		- email address end with '@' symbol
//		- email address contains more than one '@' symbol
//		- '.' not included in the email address
//      - '.' cannot follow right after '@' symbol
//      - email address end with '.'
//---------------------------------------------------------------------
function check_email(em) {
   em.value = em.value.trim();
   var emadr = em.value.toUpperCase();

   var idx   = 0;     
   // check if @ exist
   if (emadr.length == 0) {
   	 alert("Please enter email address !");
   	 return false;
   } else if (emadr.indexOf("@") == -1) {
         alert("Invalid email address. Should include '@' symbol in your email address.");
         return false;
   } else if (is_digit(emadr.charAt(0))) {
         alert("Invalid email address. Email address never start with a digit.");      
         return false;
   } else if (emadr.charAt(0) == '@') {
         alert("Invalid email address. Should not start with '@' symbol.");      
         return false;
   } else if (emadr.charAt(emadr.length-1) == '@') {
         alert("Invalid email address. Should not end with '@' symbol.");      
         return false;         
   } else {  
       
   // split em into two part 
      var email_array = emadr.split("@");
      
      if (email_array[2] != null) {
          alert("Invalid email address. Should contains only one '@' symbol.");
          return false;
      } else {
     
          // check email_array[1] part...
          var em2 = email_array[1];
          if (em2.indexOf(".") == -1) {
               alert("Missing '.' at the second part of the emaill address."); 
               return false;
          } else if (em2.charAt(0) == ".") {
               alert("Invalid email address! '.' can't placed right after '@' symbol");
               return false;
          } else if (em2.charAt(em2.length-1) == ".") {
               alert("Email address cannot end with '.'");
               return false;
          } else {    
             //var dot_array = em2.split(".");
             //while (dot_array[idx] != null) {
          	 //  idx = ++idx;
          	 //}
             //var last_part = dot_array[idx-1].toUpperCase();  
               
             //if (last_part != "COM" &&
             //   last_part != "NET" &&
             //    last_part != "ORG" &&
             //    last_part != "CA" &&
             //    last_part != "US" ) {
             //    alert("Email address not ending with proper type such as '.com' !");
             //    return false;
             //}
          } 
      }
   }
   return true;
}

//------------------------------------------//------------------------------------------//------------------------------------------
function validate()
{
	if (!validateNominatorInfo()) return false;
	if (!validateEntryInfo()) return false;
	if (!validateSurvey()) return false;
	if (!isPermissionCheckBoxChecked()) return false;
	
	document.form1.sNomPostal.value = document.form1.sNomPostal1.value + document.form1.sNomPostal2.value;
	document.form1.sNomPhone.value = document.form1.sNomPhone1.value+document.form1.sNomPhone2.value+document.form1.sNomPhone3.value;
	document.form1.sEntryPostal.value = document.form1.sEntryPostal1.value+document.form1.sEntryPostal2.value;
	document.form1.sEntryPhone.value = document.form1.sEntryPhone1.value+document.form1.sEntryPhone2.value+document.form1.sEntryPhone3.value;
	
	if (document.form1.sEntryAddress1.value.trim() == "") 
	     { document.form1.sEntryLetter.value = "N"; }
	else { document.form1.sEntryLetter.value = ""; } 
	
	document.getElementById("Submit1").disabled = true;
	
	return true;
}

//------------------------------------------//------------------------------------------//------------------------------------------
function isPermissionCheckBoxChecked()
{
	if (document.form1.chkbxPermission.checked)
	{
		return true;
	}
	else
	{
		alert("Veuillez confirmer que vous avez lu les Règlements du programme.");
		return false;
	}
}

//------------------------------------------//------------------------------------------//------------------------------------------
function validateEntryInfo()
{
	var selected;
	var iLen;

	//------------------------------------------ check Entry First name.
	if (document.form1.sEntryFname.value == "") 
	{
		alert("Veuillez entrer le prénom du candidat");
		document.form1.sEntryFname.focus();
		return false;
	} else if (!validName(document.form1.sEntryFname.value)) {
		alert("Le prénom du candidat contient des caractères non valides. ");
		document.form1.sEntryFname.focus();
		return false;
	}

	//------------------------------------------ check Entry Last name.
	if (document.form1.sEntryLname.value == "") 
	{
		alert("Veuillez entrer le nom de famille du candidat.");
		document.form1.sEntryLname.focus();
		return false;
	} else if (!validName(document.form1.sEntryLname.value)) {
		alert("Le nom de famille du candidat contient des caractères non valides.");
		document.form1.sEntryLname.focus();
		return false;
	}

	//-------------------------------------- check Entry City.
	if (document.form1.sEntryCity.value == "") 
	{
		alert("Veuillez entrer la ville du candidat.");
		document.form1.sEntryCity.focus();
		return false;
	} 
	else if (!validAddress(document.form1.sEntryCity.value)) 
	{
		alert("La ville du candidat contient des caractères non valides.");
		document.form1.sEntryCity.focus();
		return false;
	}
	
	//------------------------------------------ check Entry Province.
	if (document.form1.sEntryProv.selectedIndex == 0) 
	{
		alert("Veuillez indiquer la province du candidat.");
		document.form1.sEntryProv.focus();
		return false;
	}
	
	//-------------------------------------- check Entry Phone.
	if (document.form1.sEntryPhone1.value == "" || document.form1.sEntryPhone2.value == "" || document.form1.sEntryPhone3.value == "") 
	{
			alert("Veuillez entrer le numéro de téléphone du candidat.");
			if (document.form1.sEntryPhone1.value == "") document.form1.sEntryPhone1.focus();
			else if (document.form1.sEntryPhone2.value == "") document.form1.sEntryPhone2.focus();
			else document.form1.sEntryPhone3.focus();
			return false;		
	} 
	else 
	{
			if (!is_numeric(document.form1.sEntryPhone1.value+document.form1.sEntryPhone2.value+document.form1.sEntryPhone3.value)) 
			{
				alert("Le numéro de téléphone du candidat n'est pas entré correctement.");
				document.form1.sEntryPhone1.focus();
				return false;
			} 
			else 
			{
				iLen = document.form1.sEntryPhone1.value.length + document.form1.sEntryPhone2.value.length + document.form1.sEntryPhone3.value.length
				if (iLen != 10) 
				{
					alert("Le numéro de téléphone du candidat n'est pas entré correctement.");
					document.form1.sEntryPhone1.focus();
					return false;
				}
			}	
	}	
	
	//------------------------------------------ validate Entry Gender
	selected = false;
	
	for (var i =0; i < document.form1.sEntrySex.length; i++)
	{
		if (document.form1.sEntrySex[i].checked)  selected = true;
	}
		
	if (!selected) 
	{
		alert("Veuillez indiquer le sexe du candidat. ");
		document.form1.sEntrySex[0].focus();
		return false;
	}
		
	//-------------------------------------- check Entry Example.
	if (document.form1.sNomStory1.value == "") {
		alert("Veuillez fournir un exemple.");
		document.form1.sNomStory1.focus();
		return false;
	} else if (!validContent(document.form1.sNomStory1.value)) {
		document.form1.sNomStory1.focus();
		return false;
	}
	
	//-------------------------------------- check Entry Story.
	if (document.form1.sNomStory2.value == "") {
		alert("Veuillez indiquer les raisons pour lesquelles vous proposez ce candidat.");
		document.form1.sNomStory2.focus();
		return false;
	} else if (!validContent(document.form1.sNomStory2.value)) {
		document.form1.sNomStory2.focus();
		return false;
	}	
	
	//=== The following are the optional fields. =================================================================
	//-------------------------------------- check Entry Address line 1.
	/*
	if (document.form1.sEntryAddress1.value.trim() != "") {
		if (!validAddress(document.form1.sEntryAddress1.value)) {
			alert("L'adresse du candidat contient des caractères non valides.");
			document.form1.sEntryAddress1.focus();
			return false;

		}
		
		//-------------------------------------- check Entry Address line 2.
		if (!validAddress(document.form1.sEntryAddress2.value)) {
			alert("La deuxième adresse du candidat contient des caractères non valides.");
			document.form1.sEntryAddress2.focus();
			return false;
		}
		
		//-------------------------------------- check Entry Postal code.
		if (document.form1.sEntryPostal1.value == "" || document.form1.sEntryPostal2.value == "") {
			alert("Veuillez entrer le code postal du candidat.");
			if (document.form1.sEntryPostal1.value == "") document.form1.sEntryPostal1.focus();
			else document.form1.sEntryPostal2.focus();
			return false;		
		} else if (!validPostalCodeEx(document.form1.sEntryPostal1.value+document.form1.sEntryPostal2.value)) {
			alert("Le code postal du candidat n'est pas entré correctement.");
			document.form1.sEntryPostal1.focus();
			return false;
		}
		
		//------------------------------------------ validate email address
		if (document.form1.sEntryEmail.value.length == 0) {
			alert("Veuillez entrer l'adresse courriel du candidat.");
			document.form1.sEntryEmail.focus();
			return false; 	
		} else if (!check_email(document.form1.sEntryEmail)) {
			document.form1.sEntryEmail.focus();
			return false; 	
		}
	}
	*/
		
	return true;
}

//------------------------------------------//------------------------------------------//------------------------------------------
function validateNominatorInfo()
{
	var selected;
	
	//------------------------------------------ check Nom First name.
	if (document.form1.sNomFname.value == "") {
		alert("Veuillez entrer votre prénom.");
		document.form1.sNomFname.focus();
		return false;
	} else if (!validName(document.form1.sNomFname.value)) {
		alert("Votre nom de famille contient des caractères non valides.");
		document.form1.sNomFname.focus();
		return false;
	}
	
	//------------------------------------------ check Nom Last name.
	if (document.form1.sNomLname.value == "") {
		alert("Veuillez entrer votre nom de famille.");
		document.form1.sNomLname.focus();
		return false;
	} else if (!validName(document.form1.sNomLname.value)) {
		alert("Votre nom de famille contient des caractères non valides.");
		document.form1.sNomLname.focus();
		return false;
	}

	//-------------------------------------- check Nom Address 1.
	if (document.form1.sNomAddress1.value == "") {
		alert("Veuillez entrer votre adresse.");
		document.form1.sNomAddress1.focus();
		return false;
	} else if (!validAddress(document.form1.sNomAddress1.value)) {
		alert("Votre adresse contient des caractères non valides.");
		document.form1.sNomAddress1.focus();
		return false;
	}

	//-------------------------------------- check Nom Address 2.
	if (document.form1.sNomAddress2.value.trim() != "") {
		if (!validAddress(document.form1.sNomAddress2.value)) {
			alert("Votre adresse contient des caractères non valides.");
			document.form1.sNomAddress2.focus();
			return false;
		}
	}

	//-------------------------------------- check Nom City.
	if (document.form1.sNomCity.value == "") {
		alert("Veuillez entrer votre ville.");
		document.form1.sNomCity.focus();
		return false;
	} else if (!validAddress(document.form1.sNomCity.value)) {
		alert("Votre ville contient des caractères non valides.");
		document.form1.sNomCity.focus();
		return false;
	}
	
	//------------------------------------------ check Nom Province.
	if (document.form1.sNomProv.selectedIndex == 0) {
		alert("Veuillez indiquer votre province.");
		document.form1.sNomProv.focus();
		return false;
	}
	
	//-------------------------------------- check Nom Postal code.
	if (document.form1.sNomPostal1.value == "" || document.form1.sNomPostal2.value == "") {
		alert("Veuillez entrer votre code postal.");
		if (document.form1.sNomPostal1.value == "") document.form1.sNomPostal1.focus();
		else document.form1.sNomPostal2.focus();
		return false;
	} else if (!validPostalCodeEx(document.form1.sNomPostal1.value+document.form1.sNomPostal2.value)) {
		alert("Votre code postal n'est pas entré correctement.");
		document.form1.sNomPostal1.focus();
		return false;
	}

	//-------------------------------------- check Nom Phone.
	if (document.form1.sNomPhone1.value == "" || document.form1.sNomPhone2.value == "" || document.form1.sNomPhone3.value == "") {
		alert("Veuillez entrer votre numéro de téléphone.");
		if (document.form1.sNomPhone1.value == "") document.form1.sNomPhone1.focus();
		else if (document.form1.sNomPhone2.value == "") document.form1.sNomPhone2.focus();
		else document.form1.sNomPhone3.focus();
		return false;
	} else if (!is_numeric(document.form1.sNomPhone1.value+document.form1.sNomPhone2.value+document.form1.sNomPhone3.value)) {
		alert("Votre numéro de téléphone n'est pas entré correctement.");
		document.form1.sNomPhone1.focus();
		return false;
	} else {
		iLen = document.form1.sNomPhone1.value.length + document.form1.sNomPhone2.value.length + document.form1.sNomPhone3.value.length
		if (iLen != 10) 
		{
			alert("Numéro de téléphone non valide.");
			document.form1.sNomPhone1.focus();
			return false;
		}
	}

	//------------------------------------------ validate email address
	/*
	if (document.form1.sNomEmail.value.length == 0) {
			alert("Veuillez entrer votre adresse courriel.");
			document.form1.sNomEmail.focus();
			return false; 	
	} else {
		if (!check_email(document.form1.sNomEmail)) {
			document.form1.sNomEmail.focus();
			return false; 	
		}
	}
	*/	
	
	//------------------------------------------ validate Nom Gender
	selected = false;

	for (var i =0; i < document.form1.sNomSex.length; i++)
	{
		if (document.form1.sNomSex[i].checked)  selected = true;
	}
		
	if (!selected) {
		alert("Veuillez indiquer votre sexe.");
		document.form1.sNomSex[0].focus();
		return false;
	}
		
	return true;
}
//------------------------------------------//------------------------------------------
function validateSurvey()
{
	return true;
}

function KeyPress(what,e,max,action) {
    if (document.layers) {
        if (e.target.value.length >= max)
            eval(action);
    }
    else if (document.all) {
        if (what.value.length > (max-1))
            eval(action);
    }
}

// Auto tab
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {
var keyCode = (isNN) ? e.which : e.keyCode; 
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if(input.value.length >= len && !containsElement(filter,keyCode)) {
input.value = input.value.slice(0, len);
input.form[(getIndex(input)+1) % input.form.length].focus();
}
function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length)
if(arr[index] == ele)
found = true;
else
index++;
return found;
}
function getIndex(input) {
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input)index = i;
else i++;
return index;
}
return true;
}