﻿global_size = 'large';
_keepWindowSize = false;
_overLayBoxId = (navigator.userAgent.indexOf('MSIE') >= 0)?'IE':'';
_forceLoadPage = false;

// This global variable will be use for the iCongo Chat Window and to make sure we are opening only one window
// Some functions through Ajax will manage to open subsequent room in the same window though Gateway.
var chatWindow = null;
eStaraPopup = null;
var isChatWindowOpen = false;

/*
	 The following VAR are concerning the validation of the phone number 
	 in Registration form (and any other place where we intend to use 
	 phone number validation)
*/

// Declaring required variables
var phonedigits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;


function openContent(url)
{
	if(url.indexOf('openPoll') >= 0)
	{
		pollId = url.split("|")[1];
		$('iframePop').src = "/shared/application/onlinePoll.cfm?pollId=" + pollId;
		$('popupWrapper').className = "slim show";	
	}
	else{
		ucaseURL = url.toUpperCase();
		//alert(ucaseURL);
		if (ucaseURL.search(/AS00.ESTARA.COM/) == true || ucaseURL.search(/CLICK4TALK.COM/) == true)
		{
			//alert(ucaseURL);
			openContentEStara(url);
		}
		else
		{
			// Enumerate all frame busting URL here in the IF (or create a SWITCH if it became too big)
			if (url.search(/upstate.edu/i) > 0)
			{
				//alert(url);
				//alert(ucaseURL);
				openContentFrameBustingWindow(url);
			}
			else
			{
				try {
					DWREngine._execute(_cfVTS6_AjaxCalls, null, 'logOpenContent',url, logOpenContent_return);
				}
				catch(e){
					// nothing to do
				}
	
				//alert('no estara');
				$('iframePop').src = url;
				$('popupWrapper').className = "small";	
			}
		}
	}
}

function logOpenContent_return(result)
{
	//nothing to do	
}


function openContentEStara(url)
{
	
	eStaraPopup = window.open(url,"eStaraPopup","menubar=no, status=no, scrollbars=no, menubar=no, directories=no, location=no, width=200, height=100");
	eStaraPopup.window.focus();
}

function openContentFrameBustingWindow(url)
{
	framebustingwin = window.open(url,"framebustingwindow","menubar=yes, status=yes, scrollbars=yes, menubar=yes, directories=yes, location=yes, width=640, height=480");
	framebustingwin.window.focus();
}

// This is a shortcut of the previous function openContentEstara as we have a limit of 200 characters for the parameter_value in the table controllers_site_parameters
function oEStara(url)
{
	eStaraPopup = window.open(url,"eStaraPopup","menubar=no, status=no, scrollbars=no, menubar=no, directories=no, location=no, width=200, height=100");
	eStaraPopup.window.focus();
}

function openJakeChat(url)
{
	jakeChatPopup = window.open(url,"jakeChatPopup","menubar=no, status=no, scrollbars=yes, menubar=no, directories=no, location=no, width=765, height=525, top=0, left=0");
	jakeChatPopup.window.focus();
	closeIframePop();
}


function goToBooth(floorId,boothId)
{
	if(_forceLoadPage)
	{
		parent.window.location = siteUrl + '/' + siteLang + '/visitors/app-lobby/boothId=' + boothId + '&floorId=' + floorId;
	}
	
	params = floorId + "|" + boothId;
	callFlash('gotoBoothWithFloorId','internal', params);
	
	closeIframePop();
}

function popURL(content)
{
	callFlash('openContent', 'internal', content);
}

function callFlash(functionName, functionType, params) {
	getMovieName("vtsID").externalJavaScript(functionName,functionType,params);
}

function getMovieName(movieName) {
   if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
   }
   else {
       return document[movieName];
   }
}

function openUserQuickView(targetKeyId, clientKeyId) {
	
	if(targetKeyId) {

		url = siteUrl + '/shared/presentation/components/userQuickView.cfm?userKeyId=' + targetKeyId;
		window.open(url,"WMWindow_" + up_replaceAlpha(targetKeyId) + "_" + up_replaceAlpha(clientKeyId),"width=700,height=397,toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=1,resizable=1");
	}
}


function up_replaceAlpha( strIn )
{
	var strOut = "";
	for( var i = 0 ; i < strIn.length ; i++ )
	{
		var cChar = strIn.charAt(i);
		if( ( cChar >= 'A' && cChar <= 'Z' )
			|| ( cChar >= 'a' && cChar <= 'z' )
			|| ( cChar >= '0' && cChar <= '9' ) )
		{
			strOut += cChar;
		}
		else
		{
			strOut += "_";
		}
	}
	return strOut;
}

function closeIframePop()
{
	$('popupWrapper').className = "hide";
	$('iframePop').src = 'about:blank';
}

function closeBrowserCheckPop()
{
	$('popupWrapper').className = "hide";
}

function changeWindowSize()
{
	if(_keepWindowSize)
	{
		global_size = (global_size=='small')?"large":"small";
	}
	
	$('popupWrapper').className = global_size;
	global_size = (global_size=='small')?"large":"small";
	$('contentBlockPopup').className = global_size2;
	global_size2 = (global_size=='small')?"large":"small";
	_keepWindowSize = false;
}

function minimizePopUp()
{
	$('popupWrapper').className = "hidden";
	//$('overlay').className = "hide";
	_keepWindowSize = true;
}

function showToolTip(hide,msg,msg1)
{
	
	if(msg1)
	{
		$('popToolTip').innerHTML = (!hide)?(global_size=='small')?msg1:msg:'';
	}
	else
	{
		$('popToolTip').innerHTML = (!hide)?msg:'';
	}
	
}


function logOut(uType)
{
	document.location.href = '/shared/logout.cfm';
	//DWREngine._execute(_cfVTS6_AjaxCalls, null, 'logOut',uType, logOut_return);	
	//document.location.href='/';
}

function logOut_return(result)
{
	if(logoutUrl != '')
	{
		window.location = logoutUrl;
	}
	else
	{
		window.location.reload();
	}
	
}

function logOutWithURL(uType,url) {
	document.location.href = '/shared/logout.cfm?redirecturl=' + url;
}

function logOutSiteNavigation()
{
	alert("If you are closing your window. You will be logged out from the show");
	DWREngine._execute(_cfVTS6_AjaxCalls, null, 'logOutSiteNavigation', no_ret);	
}

function no_ret(){}

function logUserFromVisitors()
{
	document.location.href='/shared/administration/';
	//DWREngine._execute(_cfVTS6_AjaxCalls, null, 'logUserFromVisitors',logUserFromVisitors_Return);
}

function logUserFromVisitors_Return(result)
{
	response = convertKeyStructure(result);
	
	if(response.loginsuccess == 'true')
	{
		window.location = response.redirect;
	}
}

function openChatIframe(obj)
{
	//alert('openChatIframe\n\nobj.boothId='+obj.split(',')[0]+'\nobj.userId='+obj.split(',')[1]+'\nobj.length='+obj.length);
	args = {};
	args.boothId = obj.split(',')[0];
	args.userId = obj.split(',')[1];
	
	openContent(siteUrl+'/communication/chat/wc.cfm?sessionGUID='+args.userId+'&key='+args.boothId);
	changeWindowSize();
}


function getLoading(o,type)
{
	if(type == 'simple')
	{
		$('loading').className = (o)?'show':'hide';
	}
	
	if(type == 'extended')
	{
		$('loadingOverlay').className = (o)?'loadingOverlay show':'loadingOverlay hide';
		$('loadingBox').className = (o)?'loadingBox show':'loadingBox hide';
	}
}

function convertKeyStructure(o)
{
	struct = new Object();
	for(x=0;x < o.length; x++)
	{
		struct[o[x].KEY.toLowerCase()] = o[x].VALUE;
	}	
	
	return struct;
}

function checkUserId(o,beh)
{
	_userId = o.value;
	_o = o;
	//alert("_userId = " + _userId);
	//alert("beh = " + beh);
	try
	{
		if(beh)
		{
			
			$('noteField-'+_o.id).innerHTML = '';
			
			
			if(!checkEmail(_o.value))
			{
				$('noteField-'+_o.id).innerHTML = _registrationInvalidEmail_ErrorMessage;
				if(_o.className != 'text red')
				{
					_o.className = 'text red';
				}
			}
			else
			{
				DWREngine._execute(_cfVTS6_AjaxCalls, null, 'login', _userId, '0000' , 'Y', 'user',checkUserIdFromBlur_Return);	
			}
		}
		else
		{
			if(checkEmail(_o.value))
			{
				DWREngine._execute(_cfVTS6_AjaxCalls, null, 'login', _userId, '0000' , 'Y', 'user',checkUserId_Return);	
			}
		}
	}
	catch(err)
	{
		alert("Error (validate email): " + err.description);
	}
	
}


function checkNickName(o)
{
	_userId = o.value;
	_o = o;
	DWREngine._execute(_cfVTS6_AjaxCalls, null, 'login', _userId, '0000' , 'Y', 'user',checkNickName_Return);	
}


function checkNickName_Return(result)
{
	
	response = convertKeyStructure(result);
	
	result = false;
	
	if(response.useronly == 'true')
	{
		if(response.userlogged == 'false')
		{
			if(_o.value!='')
			{
				result = true;
			}	
		}		
	}
	
	if(!result && _o.value!='')
	{
		$('noteField-'+_o.id).innerHTML = '<p>This nickname already exists.</p>';
	}
	if(result)
	{
		$('noteField-'+_o.id).innerHTML = '';
	}
	
	_o.className = (!result)?'text red':'text green';
	_formCanSubmit = (!result)?false:true;
	
}



function checkUserIdFromBlur_Return(result)
{
	//alert(result);
	response = convertKeyStructure(result);
	
	if(response.userlogged == 'true')
	{
		$('noteField-'+_o.id).innerHTML = _registrationUserAlreadyExists_ErrorMessage;
			if(_o.className != 'text red')
			{
				_o.className = 'text red';
			}
	}
	else
	{
		_o.className = 'text';
	}
}


function checkUserId_Return(result)
{
	response = convertKeyStructure(result);
	
	result = false;
	
	if(response.useronly == 'true')
	{
		if(response.userlogged == 'false')
		{
			if(checkEmail(_o.value))
			{
				result = true;
			}	
		}		
	}
	
	_o.className = (!result)?'text red':'text green';
	_formCanSubmit = (!result)?false:true;
	
}
  
function checkEmail(src) 
{
   
   var emailReg = "^[\\w-]+(?:\\.[\\w-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7}$";
   //var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
   var regex = new RegExp(emailReg);
   return regex.test(src);
}

function showLangSelectionBox(di)
{
	if(!di)
	{
		$('langSelect').className = ($('langSelect').className == 'hide')?'show':'hide';
	}
	else
	{
		$('langSelect').className = di;
	}
	
}

function changeSiteLanguage(actualLang,replaceLang,description)
{
	alert("actualLang="+actualLang);
	alert("replaceLang="+replaceLang);
	alert("description="+description);
	_url = window.location.toString();
	DWREngine._execute(_cfVTS6_AjaxCalls, null, 'changeSiteLanguage', _url, actualLang, replaceLang, changeSiteLanguage_Return);	
	if( _url.indexOf(actualLang) >= 0 )
	{
		window.location.href = '/shared/changeSiteLanguage_redirect.cfm?pageURL='+_url.replace(actualLang,replaceLang);
	}
	else
	{
		window.location.href = '/shared/changeSiteLanguage_redirect.cfm?pageURL='+_url;
	}
}

function changeSiteLanguage_Return(result)
{
	
}

function openMenuList(o)
{
	o.className = (o.className == '')?'languageMenuExpanded':'';
}

function getFieldsAndTest(obj,fieldType,nameCheck,disable,action,action1,value)
{
	fields = obj.getElementsByTagName(fieldType);
	action = (!action)?'disable':action;
	value = (!value)?'':value;
	
	for(y = 0; y < fields.length; y++)
	{
		fieldName = fields[y].name.toUpperCase();
		
		changeField = false;
		
		if(nameCheck == 'ALL')
		{
			
			compareName = '';
			
			if(fieldName.split('_').length > 1)
			{
				compareName = fieldName.split('_')[0];
			}
			else
			{
				compareName = fieldName.split('-')[0];
			}
			
			//debugJs(_systemFieldsNames.indexOf('|'+compareName+'|') + ' - ' + fieldName + ' - ' + compareName + ' - ' + fieldName.split('_').length);
			
			if(_systemFieldsNames.indexOf('|'+compareName+'|')<0)
			{
				changeField = true;
			}
		}
		else
		{
			if(fieldName.indexOf(nameCheck) >= 0)
			{
				changeField = true;
			}
		}
		
		if(changeField)
		{
			applyFieldAction(fields[y],action,action1,disable,value);
		}
	}
}


function applyFieldAction(fields,action,action1,disable,value)
{
	if(action == 'disable'||action1 == 'disable')
	{
		fields.disabled = disable;
		if(fields.type != 'checkbox')
		{
			fields.className += ' disabled';
		}
	}
	
	if(action == 'clear'||action1 == 'clear')
	{
		fields.value = '';
	}
	
	if(action == 'changeName'||action1 == 'changeName')
	{
		fields.name = 'DUMMYFIELD';
	}
	
	if(action == 'setValue'||action1 == 'setValue')
	{
		fields.value = value;
	}
}			


_systemFieldsNames = '|FIRSTNAME|,|LASTNAME|,|USERID|,|NICKNAME|,|PASSWORD|,|EMAIL|,|SUBMIT|,|PRIVACYPRIVILEGECHECKBOX|,|USERTYPEID|,|FORMID|,|PAGEID|,|EMAILID|,|EMAILFIELDID|,|IDENTIFYERFIELDID|,|SITEOWNERCOMPANYID|,|FORMSUBMITID|,|FORMPAGEIDS|,|FORMCONTROLLERID|,|ANONYMOUSUSERID|';
_systemFieldsReadOnly = 'FIRSTNAME,LASTNAME,USERID';

function privateUserFieldCheck(o)
{
	//debugJs('create');
	setFieldValues = _systemFieldsReadOnly.split(",");
	
	if(confirm('Are you sure you want to set your status as private. This will delete the fields. In order to reverse your decision you will need to refresh the page and start the registration again.'))
	{
		pageForms = document.body.getElementsByTagName('form');
	
			for(x=0;x<pageForms.length;x++)
			{	
				
				if(pageForms[x].name.toUpperCase().indexOf('PAGE_')>=0)
				{
					getFieldsAndTest(pageForms[x],'INPUT','ALL',true,'disable','changeName');
					getFieldsAndTest(pageForms[x],'SELECT','ALL',true,'disable','changeName');
					getFieldsAndTest(pageForms[x],'TEXTAREA','ALL',true,'disable','changeName');
					
					/*
					for(h = 0; h < setFieldValues.length;  h++)
					{
						getFieldsAndTest(pageForms[x],'INPUT',setFieldValues[h]+'-',true,'setValue','disable','anonymous@email.com');
					}
					*/
					
					$('PrivacyPrivilegeCheckBox').value = "yes";
				}
			}
	}
	else
	{
		o.checked = false;
	}
}

function debugJs(type)
{
	if(type=='create')
	{
		_te = document.createElement('TEXTAREA');
		_te.style.width = '1000px';
		_te.style.height = '1000px'
		document.body.appendChild(_te);
	}
	else
	{
		_te.value += type + '\n';
	}
}

function openResizedChatWindow(siteUrl, userId, boothId, loungeId)
{
	try
	{
		urlCheckerLink = siteUrl + '/communication/iCongoChat/popupCheck.cfm';
		idchecker = 'ICONGOCHATCHECKER';
		var chatCheckerWindow = window.open(urlCheckerLink, idchecker , 'width=1,height=1,left=0,top=0,scrollbars=no');
		if (chatCheckerWindow)
		{
			chatCheckerWindow.window.close();	
			if (!(loungeId) || !loungeId > 0)
			{
				loungeId = 0;
			}
			//alert('siteUrl = ' + siteUrl + '\nuserId = ' + userId + '\nboothId = ' + boothId + '\nloungeId = ' + loungeId);
			isChatWindowOpen = false;
			if (chatWindow){isChatWindowOpen=true;}
			//alert('isChatWindowOpen = ' + isChatWindowOpen);
			try
			{
				DWREngine._execute(_cfVTS6_AjaxCalls, null, 'fCheckIfICongoChat', siteUrl, userId, boothId, loungeId, isChatWindowOpen, openResizeChatWindow_Return);
			}
			catch(err2)
			{
				chatWindow = null;
				openResizedChatWindow(siteUrl, userId, boothId, loungeId);
			}
		}
		else
		{
			alert('A problem has occurred. Usually this problem is caused by a popup blocker. Please verify that your browser allows popups.');
		}
	}
	catch(err)
	{
		//alert("Error (openResizedChatWindow): " + err.description);
		chatWindow = null;
		openResizedChatWindow(siteUrl, userId, boothId, loungeId);
	}
}

function openResizeChatWindow_Return(result)
{
	response = convertKeyStructure(result);
	if(response) {
		// The system has detected the struct return by the function fCheckIfICongoChat
		switch(response.chatsupplier)
		{
			case 'ICONGO':
				if (chatWindow)
				{
					chatWindow.window.focus();
					if (navigator.appName != "Microsoft Internet Explorer")
					{
						alert("Please check your Chat Window as we added the new Chat's room in it");
					}
				}
				else
				{
					urlLink = response.siteurl + '/communication/iCongoChat/chatLauncher.cfm?sessionGUID=' + response.userid + '&boothID=' + response.boothid + '&loungeid=' + response.loungeid;
					id = 'ICONGOCHAT';
					chatWindow = null;
					chatWindow = window.open(urlLink, id , 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,titlebar=0,width=950,height=650,left=100,top=100');
					if (chatWindow)
					{
						chatWindow.window.focus();
					}
					else
					{
						alert('A problem has occurred. Usually this problem is caused by a popup blocker. Please verify that your browser allows popups.');
					}
				}
				break;
			
			case 'USERPLANE':
				urlLink = response.siteurl + '/communication/chat/wc.cfm?sessionGUID=' + response.userid + '&key=' + response.boothid;
				day = new Date();
				id = day.getTime();
				eval("page" + id + " = window.open(urlLink, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=775,height=500,left=100,top=100');");
				break;
		}
	}
	else
	{
		alert('Technical problem. Your chat request cannot be established.');
	}
}

function openMessenger(args, type)
{
	urlCheckerLink = '/communication/iCongoChat/popupCheck.cfm';
	idchecker = 'ICONGOCHATCHECKER';
	var chatCheckerWindow = window.open(urlCheckerLink, idchecker , 'width=1,height=1,left=0,top=0,scrollbars=no');
	if (chatCheckerWindow)
	{
		chatCheckerWindow.window.close();
		chattype = (!type)?"request":type;
		//alert('chattype = ' + chattype);
		isChatWindowOpen = false;
		if (chatWindow){isChatWindowOpen=true;}
		
		sp = args.split(',');
		userId = sp[0];
		targetId  = sp[1];
		DWREngine._execute(_cfVTS6_AjaxCalls, null, 'fCheckIfICongoIM', sp, userId, targetId, chattype, isChatWindowOpen, openMessenger_Result);
	}
	else
	{
		alert('A problem has occurred. Usually this problem is caused by a popup blocker. Please verify that your browser allows popups.');
	}
	
}

function openMessenger_Result(result)
{
	response = convertKeyStructure(result);
	if(response) {
		//alert('response.roomid = ' + response.roomid);
		if (response.roomid && response.roomid.length > 0)
		{
			switch (response.chatsupplier)
			{
				case 'ICONGO':
					if (chatWindow)
					{
						chatWindow.window.focus();
						if (navigator.appName != "Microsoft Internet Explorer")
						{
							alert("Please check your Chat Window as we added the new Chat's room in it");
						}
					}
					else
					{
						urlLink = response.siteurl + '/communication/iCongoChat/imLauncher.cfm?initiatoruserkeyid=' + response.initiatoruserkeyid + '&targeteruserkeyid=' + response.targeteruserkeyid + '&roomid=' + response.roomid;
						id = 'ICONGOCHAT';
						chatWindow = null;
						chatWindow = window.open(urlLink, id , 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,titlebar=0,width=950,height=765,left=100,top=100');
						if (chatWindow)
						{
							chatWindow.window.focus();
						}
						else
						{
							alert('A problem has occurred. Usually this problem is caused by a popup blocker. Please verify that your browser allows popups.\n\nYou might have to reinitialize the chat request once you accept popup for this site.');
						}
	
					}
	
					if (response.chattype == "ACCEPT" || response.chattype == "DENY")
					{
						//deleteChatRequest2(result);
					}
					
					break;
					
				case 'USERPLANE':
					url = siteUrl + '/shared/presentation/communication/messenger/connect.cfm?type=' + response.chattype + '&targetUserID='+response.targeteruserid+'&userID='+response.initiatoruserid;
					window.open(url,"WMWindow_" + up_replaceAlpha(userId) + "_" + up_replaceAlpha(targetId),"width=360,height=397,toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable=1");
					break;
			}
		}

		else
		{
			alert('We are encountering some technical problems to connect you to the Chat at this moment. Please try again later.')			
		}				
	}
	return false;
}

function closeChatWindow()
{
	//DWREngine._execute(_cfVTS6_AjaxCalls, null, 'updateChatRequestWhenChatWindowClose');
	chatWindow = null;
}

function acceptChatRequest(args)
{
	openMessenger(args,'accept');
	//deleteChatRequest(args);
}

function deleteChatRequest(args)
{
	targetId = args.split(",")[0];
	userKeyId = args.split(",")[1];
	//DWREngine._execute(_cfVTS6_AjaxCalls, null, 'deleteChatRequest', userKeyId, targetId, deleteChatRequest_Return);
}

function deleteChatRequest2(args)
{
	response = convertKeyStructure(args);
	if(response) {
	//	DWREngine._execute(_cfVTS6_AjaxCalls, null, 'deleteChatRequest2', response.initiatoruserkeyid, response.targeteruserkeyid, response.roomid, deleteChatRequest_Return);
	}	
}

function deleteChatRequest_Return(result)
{

}

function declineChatRequest(args)
{
	targetId = args.split(",")[0];
	userKeyId = args.split(",")[1];
	DWREngine._execute(_cfVTS6_AjaxCalls, null, 'declineChatRequest', userKeyId, targetId ,declineChatRequest_Return);
}

function declineChatRequest_Return(result)
{
	callFlash('forceTimedRequest', 'internal', 'whoIsOnLine');
}


// The following 2 functions has been remaded by Fran�ois-Yanick Bourassa
// The reason of this restructure is because of the universal login.
// This function has been created on March 2009.
function checkUserIdRegistration(objField,objAction)
{
	_o = objField; //This line is linked to a global variable that is resused with the same name from the Ajax Return function.
	if(checkEmail(objField.value))
	{
		DWREngine._execute(_cfVTS6_AjaxCalls, null, 'fCheckIfUserExistForThisShow', objField.value, checkUserIdRegistration_Return);	
	}
}
function checkUserIdRegistration_Return(result)
{
	_o.className = (!result)?'text red':'text green';
	_formCanSubmit = (!result)?false:true;
	
}
// End of the restructure by Francois-Yanick Bourassa

/*
 *	The following functions are serving the validation of any phone/fax number
*/
		function phoneIsInteger(s)
		{   var i;
		    for (i = 0; i < s.length; i++)
		    {   
		        // Check that current character is number.
		        var c = s.charAt(i);
		        if (((c < "0") || (c > "9"))) return false;
		    }
		    // All characters are numbers.
		    return true;
		}
		function phoneTrim(s)
		{   var i;
		    var returnString = "";
		    // Search through string's characters one by one.
		    // If character is not a whitespace, append to returnString.
		    for (i = 0; i < s.length; i++)
		    {   
		        // Check that current character isn't whitespace.
		        var c = s.charAt(i);
		        if (c != " ") returnString += c;
		    }
		    return returnString;
		}
		function phoneStripCharsInBag(s, bag)
		{   var i;
		    var returnString = "";
		    // Search through string's characters one by one.
		    // If character is not in bag, append to returnString.
		    for (i = 0; i < s.length; i++)
		    {   
		        // Check that current character isn't whitespace.
		        var c = s.charAt(i);
		        if (bag.indexOf(c) == -1) returnString += c;
		    }
		    return returnString;
		}
		
		function checkInternationalPhone(strPhone){
			var bracket=3
			strPhone = phoneTrim(strPhone)
			if(strPhone.indexOf("+")>1) return false
			if(strPhone.indexOf("-")!=-1)bracket=bracket+1
			if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
			var brchr=strPhone.indexOf("(")
			if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
			if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
			s=phoneStripCharsInBag(strPhone,validWorldPhoneChars);
			return (phoneIsInteger(s) && s.length >= minDigitsInIPhoneNumber);
		}
		
		function ValidatePhone(o, phoneType){
			var Phone=o
			
			if ((Phone.value==null)||(Phone.value=="")){
				if (phoneType == 'phone')
				{
					alert("Please Enter your Phone Number");	
				}
				else
				{	alert("Please Enter you Fax Number");
					
				}				
				Phone.focus()
				return false
			}
			if (checkInternationalPhone(Phone.value)==false){
				if (phoneType == 'phone')
				{
					alert("Please Enter a Valid Phone Number");
				}
				else
				{
					alert("Please Enter a Valid Fax Number");					
				}
				
				Phone.value=""
				Phone.focus()
				return false
			}
			return true
		 }
 
 /*
  * The following functions can be used to validate ZIP and Postal Code (from US and Canada)
  */
	function isValidZipcode(zipcode) 
	{
		if (!(zipcode.length == 5)) return false;
		if (!isNumeric(zipcode)) return false;
		return true;
	}
	
	function isValidPostalcode(postalcode) 
	{
	    if (postalcode.length == 6 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/) != -1) return true;
	    else if (postalcode.length == 7 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z](-|\s)\d[a-zA-Z]\d$/) != -1) return true;
	    else return false;
		return true;
	}
	
	function validZip(zip, errMsg)  {
		if (isValidZipcode(zip) == false && isValidPostalcode(zip) == false) 
		{ 
			if (errMsg.length > 0)
			{
				alert(errMsg);				
			}
			else
			{
				alert ("Incorrect US or Canadian Postal Code Format.");	
			}			
			return false;
		}
		return true;
	}
	
	function validateNumericInput(field)
	{
		if ((field.value * 1) || (field.value == 'N/A'))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	function validateNumericFieldNumberOfDigits(field, label, nbrdigit)
	{
		if (field.value.length == nbrdigit || field.value.length == nbrdigit+1 || field.value.toUpperCase() == 'N/A')
		{
			
		}
		else
		{
			theNA = 'N/A';
			
			if (nbrdigit == 2)
			{
				theNA = 'N/A';
			}
			
			alert('Your answer for the question ' + label + ' should have ' + nbrdigit + ' digits. Enter ' + theNA + ' if you do not wish to provide your score.');
		}
	}
	
	function validatePasswordWithMinOfChars(field, minchars)
	{
		// Regular expressions used for pattern matching.
		var anUpperCase = /[A-Z]/;
		var aLowerCase = /[a-z]/;
		var aNumber = /[0-9]/;
		var message="Password must be minimum 7 characters";
		/* The function specified by the onValidate attribute.
			Tests for existence of at least one uppercase, lowercase, and numeric
			character, and checks the length for a minimum.
			A maximum length test is not needed because of the cfinput maxlength
			attribute. */
		/*
		if (field.value.length < minchars || field.value.search(anUpperCase) == -1 || 
			field.value.search (anUpperCase) == -1 || field.value.search (aNumber) == -1) 
		{
		*/
		if (field.value.length < minchars)
		{
			alert(message);
		} 
		else
		{
			return (true);
		} 
	}

	function toggleVisibility(objToTest,objIdCible, value, inputId) {
		if (objToTest.value == value) {
			document.getElementById(objIdCible).style.display = '';
			document.getElementById(inputId).value = "";
		}
		else {
			document.getElementById(objIdCible).style.display = 'none';
			document.getElementById(inputId).value = "N/A";
		}
	} 
