//-----------------------------------------------------------------------------------------

var sBrowserVersion = navigator.appVersion;

var IE = (document.all) ? true : false;
var IE4 = (IE && !document.getElementById) ? true : false;
var IE5 = (IE && document.getElementById) ? true : false;
var IE6 = IE5 ? (sBrowserVersion.match(/MSIE 5/) ? false : true) : false;

var NS4 = (document.layers) ? true : false;
var NS6 = (document.getElementById && !IE) ? true : false;

var gbFieldFocus;

//-----------------------------------------------------------------------------------------
// Form Manipulation functions
//-----------------------------------------------------------------------------------------

//returns form field/element element object - accepts both a string and existing form object 
function GetForm(loForm)
{
	if (loForm && typeof(loForm) == 'string')
	{
		loForm = document.forms[loForm];
	}
	return(loForm);
}

//-----------------------------------------------------------------------------------------

//returns form field/element element object - accepts both strings and existing objects 
function GetField(loForm, loField)
{
	var loField, lsField, iInputIndex, loFieldSet;
	if (loField && typeof(loField) == 'string')
	{
		lsField = loField;
		loForm = GetForm(loForm);
		if (loForm && loForm.elements)
		{
			loField = loForm.elements[lsField];

			if (!loField || typeof(loField) == 'undefined')
			{
				loField = loForm.elements[lsField.toLowerCase()];
			}
			
			if (loField && typeof(loField.length) != 'undefined' && loField.length && loField[0].type && !loField[0].type.match(/radio|checkbox/i))
			{
				loFieldSet = loField;
				loField = null;
				for (iInputIndex = 0; iInputIndex < loFieldSet.length; iInputIndex ++)
				{
					if (loFieldSet[iInputIndex].type == 'hidden' || loField)
					{
						loFieldSet[iInputIndex].parentElement.removeChild(loFieldSet[iInputIndex]);
						iInputIndex--;
					}
					else
					{
						loField = loFieldSet[iInputIndex];
					}
				}
			}
		}
		else
		{
			loField = null;
		}
	}
	return(loField);
}

//-----------------------------------------------------------------------------

function OriginalClick(lsTextfield, lsOriginalText)
{
	if (lsTextfield.value == lsOriginalText)
	{
		lsTextfield.value = '';
	}
}

//-----------------------------------------------------------------------------
var iPrevSelectIndex, iPrevKeywordLength;
iPrevSelectIndex = iPrevKeywordLength = 0;

function findKeyword(loFormName, lsSelectField, lsKeyword)
{
	var fCompForm, elSelectList, sCurrentJobTitle, iInputCount, iInputIndex;
	var oRegExp;
	fCompForm = document.forms[loFormName];
	elSelectList = fCompForm.elements[lsSelectField];
	iInputCount = elSelectList.length;
	if (lsKeyword.length == 0)
	{
		elSelectList.options[0].selected = true;
		iPrevSelectIndex = 0;
	}
	else if (lsKeyword.length == iPrevKeywordLength - 1)
	{
		for (iInputIndex = iPrevSelectIndex; iInputIndex >= 0; iInputIndex --)
		{
			oRegExp = new RegExp("^" + lsKeyword, "i");
			if (elSelectList.options[iInputIndex].text.match(oRegExp))
			{
				elSelectList.options[iInputIndex].selected = true;
			}
			else
			{
				iPrevSelectIndex = iInputIndex;
				break;
			}
		}
	}
	else
	{
		if (lsKeyword.length < iPrevKeywordLength - 1)
		{
			elSelectList.options[0].selected = true;
			iPrevSelectIndex = 0;
		}
		for (iInputIndex = iPrevSelectIndex; iInputIndex < elSelectList.options.length; iInputIndex ++)
		{
			oRegExp = new RegExp("^" + lsKeyword, "i");
			if (elSelectList.options[iInputIndex].text.match(oRegExp))
			{
				elSelectList.options[Math.min(elSelectList.options.length - 1, iInputIndex + 10)].selected = true;
				elSelectList.options[iInputIndex].selected = true;
				iPrevSelectIndex = iInputIndex;
				break;
			}
		}
	}
	iPrevKeywordLength = lsKeyword.length;
	//window.status = iPrevKeywordLength;
}

//-----------------------------------------------------------------------------

// generic function to return value of form field
// including values of select/checkbox & radio lists 
// accepts both strings and form/field objects 
// note: lsValueAttribute is optional, used for user-defined attribute in select/radio & checkbox
function FieldValue(loForm, loField, lsValueAttribute)
{
	var loForm, oFormElement, outFieldValue;
	outFieldValue = '';
	if (loField && typeof(loField) == 'string')
	{
		loForm = GetForm(loForm);
		loField = GetField(loForm, loField);
	}
	if (loField)
	{
		if (loField.type && !loField.type.match(/select/i))
		{
			if (lsValueAttribute)
			{
				outFieldValue = loField.attributes[lsValueAttribute];
			}
			else if (loField.type.match(/radio|checkbox/i))
			{
				if (loField.checked)
				{
					outFieldValue = (loField.value == 'on' ? true : loField.value);
				}
			}
			else
			{
				outFieldValue = loField.value;
			}
		}
		else
		{
			iInputCount = loField.length;
			if ((!iInputCount || iInputCount == 1) && !loField.type.match(/select/i))
			{
				outFieldValue = (loField[0].selected || loField[0].checked);
			} // iInputCount == 1
			else // iInputCount == 1
			{ // iInputCount == 1
				for (iInputIndex = 0; iInputIndex < iInputCount; iInputIndex ++)
				{
					if (loField[iInputIndex].selected || loField[iInputIndex].checked)
					{
						if (lsValueAttribute)
						{
							outFieldValue = (outFieldValue ? outFieldValue + ',' : '')
								+ loField[iInputIndex].attributes[lsValueAttribute];
						}
						else if (loField[iInputIndex].value)
						{
							outFieldValue = (outFieldValue ? outFieldValue + ',' : '')
								+ loField[iInputIndex].value;
						}
						else
						{
							outFieldValue = '';
							break;
						}
						//break;
					}
				}
			} // iInputCount == 1
		}
	}
	return (outFieldValue);
}

//-----------------------------------------------------------------------------

// get text from selected option in select list
function FieldText(loForm, loField)
{
	var loForm, outFieldValue, iInputCount, iInputIndex;
	loField = GetField(loForm, loField);
	if (loField)
	{
		if (loField.type && !loField.type.match(/select/i))
		{
			outFieldValue = loField.text;
		}
		else
		{
			iInputCount = loField.length;
			bRadioCheckboxSelected = false;
			for (iInputIndex = 0; iInputIndex < iInputCount; iInputIndex ++)
			{
				if (loField[iInputIndex].selected)
				{
					outFieldValue = loField[iInputIndex].text;
					break;
				}
			}
		}
	}
	return (outFieldValue);
}

//-----------------------------------------------------------------------------

// enable or disable form field
function EnableField(loForm, loField, lsDisable)
{
	var loForm, lbDisabled;
	loField = GetField(loForm, loField);
	if (loField)
	{
		if (lsDisable && !loField.disabled)
		{
			lbDisabled = 1;
		}
		else if (loField.disabled)
		{
			lbDisabled = 0;
		}
		loField.disabled = lbDisabled;
	}
	return (lbDisabled);
}

//-----------------------------------------------------------------------------

// set a form field value and submit it's parent form
function SetValueSubmitForm(loForm, loField, lsValue)
{
	var lbSuccess, lsField;
	loForm = GetForm(loForm);
	lsField = loField;
	loField = GetField(loForm, loField);
	if (loField)
	{
		loField.value = lsValue;
		loForm.submit();
		lbSuccess = true;
	}
	else
	{
		/*
		alert('Error:loForm:' + (loForm.id || loForm).toString() + '\nloField:' + lsField)
		alert('Field' + loForm.elements[loField])
		*/
		lbSuccess = false
	}
	// return false if success to kill other actions
	return (!lbSuccess); 
}

//-----------------------------------------------------------------------------

// set a form field value
function SetFormValue(loForm, loField, lsValue)
{
	var lsValue; 
	var liCount;
	var laValueList;
	
	loField = GetField(loForm, loField);

	if (loField)
	{
		if (loField.type && loField.type.match(/select/i) ) 
		{
			if (lsValue.toString().indexOf(',') > 0)
			{
				laValueList = lsValue.replace(' ', '').split(',');
				for (liCount in laValueList)
				{
					SetFormValue(loForm, loField, laValueList[liCount]);
				}
			}
			for (i=0;i<=loField.length-1;i++) 
			{
				if (lsValue.toString() == loField.options[i].value.toString())
				{
					loField.options[i].selected = true;
				}
			}
			
		}
		else if (  (loField.length) 
			|| (loField.type && loField.type.match(/radio|checkbox/i))  )
		{
			
			if (loField.length == undefined) 
			{
					if (loField.value == lsValue)
						loField.checked = true;
			}
			else
			{

				for (liCount=0;liCount<loField.length;liCount++)
				{
					if (loField[liCount].value == lsValue)
						loField[liCount].checked = true;
				}
			}

			//loField.checked = lsValue;
		}
		else
		{
			loField.value = lsValue;
		}
	}
	/*
	else
	{
		alert('Error:loForm:' + loForm.toString() + '\nloField:' + loField)
		alert('Field' + loForm.elements[loField])
	}
	*/
}

//-----------------------------------------------------------------------------

function SetFormDate(loForm, lsDatePrefix, lsValue)
{
	var liMonth;
	loForm = GetForm(loForm);
	if (loForm)
	{
		//alert(lsValue);
		SetFormValue(loForm, lsDatePrefix + 'Day', lsValue.getDate());
		liMonth = lsValue.getMonth() + 1;
		SetFormValue(loForm, lsDatePrefix + 'Month', liMonth);
		SetFormValue(loForm, lsDatePrefix + 'Year', lsValue.getFullYear());
		SetFormValue(loForm, lsDatePrefix + 'Time', lsValue.getHours() + ':' + lsValue.getMinutes());
	}
	else
	{
		alert('Error:loForm:' + loForm.toString())
		alert('Date Field' + lsDatePrefix);
	}
} // SetFormDate

//-----------------------------------------------------------------------------

// accepts a string form name to submit a form
// also optionally sets cursor to wait
function SubmitForm(loForm, lbCursorWait)
{
	loForm = GetForm(loForm);
	if (loForm)
	{
		loForm.submit();
		if (lbCursorWait)
		{
			//document.body.style.cursor = 'wait';
		}
	}
}

//-----------------------------------------------------------------------------

function GetFormDate(loForm, lsDatePrefix)
{
	var liMonth, liYear, liDay, ldDate;
	loForm = GetForm(loForm);
	if (loForm)
	{
		//alert(lsValue);
		liDay = FieldValue(loForm, lsDatePrefix + 'Day');
		liMonth = FieldValue(loForm, lsDatePrefix + 'Month');
		liYear = FieldValue(loForm, lsDatePrefix + 'Year');
		ldDate = new Date();
		ldDate.setDate(liDay);
		ldDate.setMonth(liMonth - 1);
		ldDate.setFullYear(liYear);
	}
	else
	{
		alert('Error:loForm:' + loForm.toString())
		alert('Date Field' + lsDatePrefix);
	}
	return(ldDate);
} // GetFormDate

//-----------------------------------------------------------------------------
		
function FocusForm(loForm)
{
	focusField(loForm, null)
}

function focusField(loForm, loField)
{
	var iFormElement, loPageElement, lbHidden;
	loForm = GetForm(loForm);
	if (loForm)
	{
		if (loField)
		{
			loField = GetField(loForm, loField);
		}
		if (loField && !(loField.disabled || loField.type == 'hidden'))
		{
			loPageElement = loField;
			lbHidden = (loPageElement.style.display == 'none');
			while (loPageElement.parentElement)
			{
				loPageElement = loPageElement.parentElement;
				lbHidden = (lbHidden || loPageElement.style.display == 'none');
			}
			if (!lbHidden)
			{
				loField.focus();
			}
		}
		else
		{
			loPageElement = loForm;
			lbHidden = (loPageElement.style.display == 'none');
			while (loPageElement.parentElement)
			{
				loPageElement = loPageElement.parentElement;
				lbHidden = (lbHidden || loPageElement.style.display == 'none');
			}
			if (!lbHidden)
			{
				for (iFormElement=0; iFormElement<loForm.elements.length; iFormElement++)
				{
					if (!(loForm.elements[iFormElement].disabled 
						|| loForm.elements[iFormElement].type == 'hidden'))
					{
						loForm.elements[iFormElement].focus();
						break;	
					}
				}
			}
		} //loField
	}
}
		
//-----------------------------------------------------------------------------
// Validation Functions												
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------

function RequiredDate(lsForm, lsFieldName, lsFieldTitle)
{
	var sError;
	sError = "";
	if (lsForm && lsForm.elements[lsFieldName + 'Day']
		 && lsForm.elements[lsFieldName + 'Month'] && lsForm.elements[lsFieldName + 'Year'])
	{
		if (!(FieldValue(lsForm, lsFieldName + 'Day') && FieldValue(lsForm, lsFieldName + 'Month')
			&& FieldValue(lsForm, lsFieldName + 'Year')))
		{
			sError = (lsFieldTitle ? lsFieldTitle : lsFieldName) 
				+ " - date not selected or incomplete\n";
		}
	}
	return(sError);
}

//-----------------------------------------------------------------------------

var cSalaryPeriodWeekly = 0;
var cSalaryPeriodMonthly = 1;
var cSalaryPeriodYearly = 2;

var cSalaryPeriodNet = 0;
var cSalaryPeriodGross = 1;

function validSalary(sInputString, iSalaryPeriodID)
{
	var bValidNumber, iInputSalary, iYearlySalary, sError, sSalary, sConfirm;
	sError = validCurrency(sInputString);
	if (!sError)
	{

		iSalaryPeriodID = iSalaryPeriodID ? iSalaryPeriodID : cSalaryPeriodYearly;
		iInputSalary = Number(sInputString.replace(/[^\d\.]*/g, ''));

		
		iYearlySalary = CalculateYearlySalary(iInputSalary, iSalaryPeriodID);


		
		if (iYearlySalary > 350000)
		{
			sError = "Yearly Salary is too high\n";
		}
		else if (iYearlySalary < 5000)
		{
			sError = "Yearly Salary is too low\n";
		}
		else if (iYearlySalary > 70000 || iYearlySalary < 8000)
		{
			sSalary = String(iInputSalary);
			sSalary = sSalary.replace(/^£?/, '£');
			sSalary = sSalary.replace(/\,?(\d{3}(\.\d*)?)$/, ',$1');
			sConfirm = 'Please confirm your';
			switch (Number(iSalaryPeriodID))
			{
				case cSalaryPeriodWeekly:
					sConfirm = sConfirm + ' weekly';
					break;
				case cSalaryPeriodMonthly:
					sConfirm = sConfirm + ' monthly';
					break;
				default:
					sConfirm = sConfirm + ' yearly';
			}
			sConfirm = sConfirm + ' salary is ' + sSalary;
			if (!confirm(sConfirm))
			{
				if (iYearlySalary > 70000)
				{
					sError = "Yearly Salary is too high\n";
				}
				else
				{
					sError = "Yearly Salary is too low\n";
				}
			}
		}
	}
	return sError;
}
		
//-----------------------------------------------------------------------------

function CalculateYearlySalary(lsSalary, lsSalaryPeriodID)
{
	var iYearlySalary;
	if (lsSalary)
	{
		switch (Number(lsSalaryPeriodID))
		{
			case cSalaryPeriodWeekly:
				iYearlySalary = lsSalary * 52;
				break;
			case cSalaryPeriodMonthly:
				iYearlySalary = lsSalary * 12;
				break;
			case cSalaryPeriodYearly: //assume gross
				iYearlySalary = lsSalary;
				break;
		}
	}
	return (iYearlySalary);
}

//-----------------------------------------------------------------------------

function validHouseNum(sHouseNum)
{
	var bValid, sHouseNumPattern, oHouseNumRe;
	bValid = false;
	if (sHouseNum && sHouseNum.length >= 1)
	{
		//sHouseNumPattern = "^[\\w\\d\\s]+$"
		//oHouseNumRe = new RegExp(sHouseNumPattern)
		if (sHouseNum.match(/^[\w\d\s\,\'\-]+$/))
		{
			bValid = true;
		}
	}
	return bValid;
}
		
//-----------------------------------------------------------------------------
//	elementName = the id/name of your input field.
//	errorName = the name that the GUI/error msg displays
function validDate2(loForm, elementName, errorName)
{
	var sError, lsDateVal;
	var iDay, iMonth, iYear, aMonthDays, laDateParts;
	sError = '';
	loForm = GetForm(loForm);
	
	//alert(loForm.elements[elementName].value);
	if (GetField(loForm, elementName))
	{
		
		lsDateVal = FieldValue(loForm, elementName)
		laDateParts = lsDateVal.split('/')
		iDay = laDateParts[0]
		iMonth = laDateParts[1]
		iYear =laDateParts[2]

		if (iDay && iMonth && iYear)
		{
			iMonth --;
			aMonthDays = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
			if (iDay > aMonthDays[iMonth])
			{
				sError = errorName + ' is incorrect\n';
			}
		}
		else
		{
			sError = errorName + ' is incorrect\n';
		} //iDay && iMonth && iYear
	} // if (GetField(loForm, elementName))	
	return(sError);
}


//-----------------------------------------------------------------------------

// wrapper function for backwards compatibility
function isEmail(sEmail, bOptional, lbReturnBool) 
{
	return validEmail(sEmail, bOptional, lbReturnBool);
}
 		
//-----------------------------------------------------------------------------


function validEmail(sEmail, bOptional, lbReturnBool)
{
	var bEmail, sValidChar, sEmailPattern, oEmailRe, sError;
	bEmail = false;
	sError = "";
	if (sEmail && sEmail.length > 0)
	{
		sValidChar = "[\\w\\-\\_\\.']+";
		sEmailPattern = "^\\s*" + sValidChar + 
			"@(" + sValidChar + "\\.)+" + sValidChar + "\\s*$"
		oEmailRe = new RegExp(sEmailPattern);
		if (sEmail.match(oEmailRe))
		{
			bEmail = true;
		}
		else
		{
			sError = "invalid email format (should be username@domain.com)\n";
		}
	}
	else if (!bOptional)
	{
		sError = "required\n";
	}
	return(bEmail);
}
		
//-----------------------------------------------------------------------------

function validCurrency(sInputString)
{
	var bValidNumber, iNumber, sError;
	bValidNumber = sInputString.match(/^\s*£?[\d]+(\,\d+)*(\.\d{2})?$/);
	sError = '';
	if (bValidNumber)
	{
		iNumber = Number(sInputString.replace(/\D*/g, ''));
		bValidNumber = (iNumber <= 250000);
	}
	else
	{
		sError = "invalid currency format (should be 20000 or £20,000)\n";
	}
	return sError;
}
		
//-----------------------------------------------------------------------------

function validNumber(sInputString)
{
	var bValidNumber;
	bValidNumber = sInputString.match(/^\d+$/)
	return bValidNumber;
}
		
//-----------------------------------------------------------------------------

function containsNumber(sInputString)
{
	var bDigit;
	if (sInputString.match(/\d+/))
	{
		bDigit = true;
	}
	else
	{
		bDigit = false;
	}
	return bDigit;
}
		
//-----------------------------------------------------------------------------

function IsIn(lsArray, lsItem)
{
	var iArrayIndex, bIsIn;
	bIsIn = false;
	for (iArrayIndex in lsArray)
	{
		if (lsArray[iArrayIndex] == lsItem)
		{
			bIsIn = true;
			break;
		}
	}
	return(bIsIn);
}

//-----------------------------------------------------------------------------

function ScrollToEnd()
{
	window.scrollTo(0, 999999);
}

/*-----------------------------------------------------------------------------
HS 12/01/04
Prepopulator objects - allow questionnaires to be populated by
users' previous answers
*/
function Prepopulator(){
	this.form;
	this.questions = new Array();
	this.add = function(QuestionID, QuestionType, AnswerID, AnswerText, ReplaceStringColumnID, PopulateQuestionnaireId){
		this.questions[this.questions.length] = new this.PopulateItem(QuestionID, QuestionType, AnswerID, AnswerText, ReplaceStringColumnID, PopulateQuestionnaireId)
	}
	this.prepopulate = function(){
		this.form = document.forms['Questions'];
		for(var i=0;i<this.questions.length;i++){
			var oQuestion = this.questions[i];
			var oElem = this.form['Q' + oQuestion.QuestionID];
			var replaceCopy = new RegExp("CopyQ" + oQuestion.QuestionID, "gi")
			if(!oElem){//check the element exists
				continue;
			}
					
			if(document.getElementById("span1Q" + oQuestion.QuestionID) != null && oQuestion.AnswerText.replace(/\s+/g, '').length != 0 ){
				if (document.getElementById("span2Q" + oQuestion.QuestionID) != null )
				{
					document.getElementById("span1Q" + oQuestion.QuestionID).style.display = "none";
					document.getElementById("span2Q" + oQuestion.QuestionID).style.display = "inline";
					document.getElementById("span2Q" + oQuestion.QuestionID).innerHTML = document.getElementById("span2Q" + oQuestion.QuestionID).innerHTML.replace(replaceCopy,oQuestion.AnswerText)
				}
				else
				{
					document.getElementById("span1Q" + oQuestion.QuestionID).innerHTML = document.getElementById("span1Q" + oQuestion.QuestionID).innerHTML.replace(replaceCopy,oQuestion.AnswerText)
				}
				
				if(document.getElementById("tblQ" + oQuestion.QuestionID)!=null)
				{
					document.getElementById("tblQ" + oQuestion.QuestionID).style.display="block"
				} //document.getElementById("tblQ" + oQuestion.QuestionID)										

			}
						
			switch(oQuestion.QuestionType){
				case 1://text field
				case 5://email 
				case 7://password
				case 8://phone number
					
					oElem.value = oQuestion.AnswerText;
					if(document.getElementById("span1Q" + oQuestion.QuestionID) != null && document.getElementById("span2Q" + oQuestion.QuestionID) != null && oQuestion.AnswerText.replace(/\s+/g, '').length != 0 ){
						document.getElementById("span1Q" + oQuestion.QuestionID).style.display = "none";
						document.getElementById("span2Q" + oQuestion.QuestionID).style.display = "inline";					
						if(document.getElementById("tblQ" + oQuestion.QuestionID)!=null)
						{
							document.getElementById("tblQ" + oQuestion.QuestionID).style.display="block"
						} //document.getElementById("tblQ" + oQuestion.QuestionID)						
						if (oQuestion.QuestionType == 8)
							oElem.value = "";
						document.getElementById("span2Q" + oQuestion.QuestionID).innerHTML = document.getElementById("span2Q" + oQuestion.QuestionID).innerHTML.replace(replaceCopy,oQuestion.AnswerText)
					}
					
					this.raiseEvents(oElem);
					break;
				case 2://drop down
				
					for(var j=0;j<oElem.options.length;j++){
					
						if(oElem.options[j].value=='~' + oQuestion.AnswerID){						
							oElem.options[j].selected=true;
							this.raiseEvents(oElem);
							break;							
						}
					}
					break;
				case 3://radio
				case 4://check box
					if(oElem.length){
						for(var j=0;j<oElem.length;j++){
							if(oElem[j].value=='~' + oQuestion.AnswerID){
								oElem[j].checked=true;
								this.raiseEvents(oElem[j]);
							}
						}
					}else{
						if(oElem.value=='~' + oQuestion.AnswerID){
							oElem.checked=true;
							this.raiseEvents(oElem);
						}
					}
					break;
				case 6://date of birth
				case 9://day month
					/*--------To do--------*/
					break;
			}
			
			
		}
	}
}
Prepopulator.prototype.PopulateItem = function(iQuestionID, iQuestionType, iAnswerID, sAnswerText, iReplaceStringColumnID, iPopulateQuestionnaireId){
											this.QuestionID = iQuestionID;
											this.QuestionType = iQuestionType;
											this.AnswerID = iAnswerID;
											this.AnswerText = sAnswerText;
											this.ReplaceStringColumnID = iReplaceStringColumnID;
											this.PopulateQuestionnaireId = iPopulateQuestionnaireId;
										}
										
Prepopulator.prototype.raiseEvents = function (oElem){
	
	if(document.createEventObject){//IE
		oElem.fireEvent('onchange', document.createEventObject());
		oElem.fireEvent('onclick', document.createEventObject());
	}
	else if(document.createEvent){//W3C Dom
	
		var loEvt = document.createEvent("Events");
		loEvt.initEvent('change', false, false);
		oElem.dispatchEvent(loEvt);
		var loEvt = document.createEvent("Events");
		loEvt.initEvent('click', false, false);
		oElem.dispatchEvent(loEvt);
	}	
}

/*End prepopulation objects*/

// sets all checkboxes to lbOnOff value or if not passed in sets to the opposite of the first checkbox
function SelectAll(loForm, lsFieldName, lbOnOff)
{

	// make the arguments like C
	var argv = SelectAll.arguments;
	var argc = SelectAll.arguments.length;
	// get the OnOff value if its been passed in, else make it null
	var lbOnOff = (argc > 2) ? argv[2] : null;

	loForm = GetForm(loForm);
	laFields = GetField(loForm, lsFieldName)


	// if a set value has not been passed in then get the first checkbox and do the opposite of that
	if (laFields.length && argc <=2)
	{
		lbOnOff = ! laFields[0].checked
	}

	// if there is only one checkbox
	if (laFields.length == undefined && laFields)
	{
		laFields.checked = lbOnOff
	}
	

	// set all the check boxes to a value
	for(liCount = 0; liCount < laFields.length; liCount++) 
	{
		laFields[liCount].checked = lbOnOff 
	}


}

/////////////////////////////////////////////////////////////////////////////////////
// these two functions will sort a select box in text order. places values into an array, then sorts using OptionCompare
function OptionCompare(a, b) 
{   
	if (a.txt < b.txt)      
		return -1   
	if (a.txt > b.txt)
		return 1   
		
	// a must be equal to b   
	return 0
}

function SortSelect(loForm, loSel) 
{

	//debugger;
	loSel = GetField(loForm, loSel)
	if (loSel)
	{
		var laOpts = loSel.getElementsByTagName('option');
		var laListVals = new Array();

		for(var i = 0; i < laOpts.length; i++)
			laListVals.push( {val: laOpts.item(i).value, txt: laOpts.item(i).text} );

		laListVals.sort(OptionCompare);

		for(var i = 0; i < laListVals.length; i++) 
		{

			loSel.options[i].text = laListVals[i].txt;
			loSel.options[i].value = laListVals[i].val;

		}

		return true;
	}
	
	return false
} 

////////////////////////////////////////////////////////
function AddOption(loForm, loSel, lsText, liVal) 
{

	var loSel = GetField(loForm, loSel)
	var loOption

	if (loSel)
	{
		//debugger;
		loOption = new Option(lsText, liVal);
		loSel.options[loSel.options.length] = loOption
		

	} // if(loSel)
} //AddOption

////////////////////////////////////////////////////////
function RemoveAllOptions(loForm, loSel) 
{

	var loSel = GetField(loForm, loSel)
	var liCount

	if (loSel)
	{
		//debugger;
		for (liCount = loSel.options.length; liCount >= 0 ; liCount--)
		{
			loSel.options[liCount] = null
		}


	} // if(loSel)
} //RemoveAllOptions




/////////////////////////////////////////////////////////



function isValidNumber(oInput) {

	if( !oInput.value ) { return false; }
	for( var mXi = 0; mXi < oInput.value.length; mXi++ ) {
		if( oInput.value.charAt( mXi ) != '' + parseInt( oInput.value.charAt( mXi ) ) + '' ) { return false; }
	} return true;

}
//------------  äëüïöâêûîôèàùçé ---------------------
//-----------------------------------------------------------------------------
// Validation Functions												
//-----------------------------------------------------------------------------
function RequiredField(loForm, loField, lsFieldTitle)
{
	var sError, iInputCount, iInputIndex, bRadioCheckboxSelected;
	sError = "";
	loField = GetField(loForm, loField);
	if (loField && (!loField.type || loField.type.toLowerCase() != 'hidden') && !FieldValue(loForm, loField))
	{
		sError = (lsFieldTitle || loField.name || loField.id || loField) 
			+ " est un champ obligatoire.\n";
		if (!gbFieldFocus)
		{
			//loField.focus();
			gbFieldFocus = true;
		}
	}
	return(sError);
}
//-----------------------------------------------------------------------------
function ValidField(loForm, lsCheckType, loField, lsFieldTitle, lbNotRequired)
{
	var sError, sFieldValue, bFieldValid, iSalaryPeriodID;
	sError = '';
	try
	{   
		lsCheckType = (lsCheckType || loField);
		loField = GetField(loForm, loField);
		if (loField)
		{
		    sFieldValue = FieldValue(loForm, loField);

			if (sFieldValue && sFieldValue.length > 0)
			{
				bFieldValid = true;
				switch (lsCheckType.toLowerCase())
				{
					case "email":
						bFieldValid = validEmail(sFieldValue);
						lsFieldTitle = "Email";
						break;
					case "postcode":
						bFieldValid = validPostcode(sFieldValue);/* ju_french_modif         need to use validPostcode_fr */
						lsFieldTitle = "Code postal";
						break;
					case "streetnumber":
						bFieldValid = validHouseNum(sFieldValue);
						lsFieldTitle = "No de maison/appt";
						break;
					case "name":
						bFieldValid = validName(sFieldValue);
						if(loField.name=='namefirst' || loField.name=='Namefirst'|| loField.name=='NameFirst')
							lsFieldTitle = "Prénom";
						else
							lsFieldTitle = "Nom";
						break;
					case "number":
						bFieldValid = validNumber(sFieldValue);
						lsFieldTitle = "Numéro";
						break;
					case "currency":
						bFieldValid = validCurrency(sFieldValue);
						lsFieldTitle = "Valeur courante";
						break;
					case "mobilenumber":
						bFieldValid = validMobile(sFieldValue, !lbNotRequired);
						lsFieldTitle = "Numero de téléphone portable";
						break;
					case "salary":
						iSalaryPeriodID = FieldValue(loForm, 'SalaryPeriodID');
						sError = validSalary(sFieldValue, iSalaryPeriodID);
						lsFieldTitle = "Salaire";
						break;
				   case "address1":
				        bFieldValid = validAddress(sFieldValue);
				        lsFieldTitle  = "Adresse"
				        break;
				    case "town":
				        bFieldValid = validName(sFieldValue);
				        lsFieldTitle  = "Ville"
				        break;
				    case "pseudo":
				        bFieldValid = validPseudo(sFieldValue);
				        lsFieldTitle = "Pseudo"
				        break;
				}
				if (!bFieldValid)
				{
					sError = (lsFieldTitle || loField.name || loField)
						+ " - invalide\n";
					if(lsFieldTitle == "Code postal")
					{
					    sError = sError + "Ce jeu concours est ouvert aux personnes habitant la France Métropolitaine (Dom-Tom et Corse inclus)\n ";
					}
					if (!gbFieldFocus)
					{
						//loField.focus();
						gbFieldFocus = true;
					}
				}
			}
			else if (!lbNotRequired)
			{
				sError = RequiredField(loForm, loField, lsFieldTitle);
				if (!gbFieldFocus)
				{
					//loField.focus();
					gbFieldFocus = true;
				}
			}
		}
	}
	catch(e)
	{
		alert('error in ValidField: ' + e.description)
	}
	
	return(sError);
} // ValidField_fr
//-----------------------------------------------------------------------------

function validPostcode(sPostcode)
{
	var bValid, sPostcodePattern, oPostcodeRe, sLetter, sAlphaNumeric, sDigit;
	bValid = false;
	if (sPostcode && sPostcode.length >= 5 && sPostcode.length <= 9)
	{
		sDigit = "[0-9]";
		if(!(document.getElementById("registrationstageid") != null && document.getElementById("registrationstageid").value == 3))
		{
		    sProhibitPattern = '^\\s*' + '[0]{2,2}' + sDigit + '{3,3}\\s*$';
		}
		else
		{
		    sProhibitPattern = '^\\s*' + '[9]{5,5}' + '\\s*$';
		}
		oProhibitPostCodeRe = new RegExp(sProhibitPattern);
		sPostcodePattern = '^\\s*' + sDigit + '{5,5}\\s*$';
		oPostcodeRe = new RegExp(sPostcodePattern);
		if ((sPostcode.match(oPostcodeRe)) && (!sPostcode.match(oProhibitPostCodeRe)))
		{
			bValid = true;
		}
	}
	return bValid;
} /* validPostcode */
//-----------------------------------------------------------------------------
function validPassword(loForm, loPasswordField, loConfirmPasswordField)
{
	var bValid, sError, sPassword, sConfirmPassword;
	sError = "";
	bValid = true;
	loForm = GetForm(loForm);
	loPasswordField = GetField(loForm, loPasswordField);
	loConfirmPasswordField = GetField(loForm, loConfirmPasswordField);
	if (loPasswordField)
	{
		sPassword = FieldValue(loForm, loPasswordField);
		sConfirmPassword = FieldValue(loForm, loConfirmPasswordField);
		if (sPassword.length < 4 && loForm.name != 'frmETUserDetails' && loForm.name != 'frmETLogin')
		{
			sError = "Mot de passe - doit être composé de 4 caractères minimum\n";
		}
		else if(sPassword.length > 14)
		{
			sError = "Mot de passe - doit être composé de 14 caractères maximum\n";
		}
		else if (loConfirmPasswordField)
		{
			if (sPassword != sConfirmPassword)
			{
				sError = "Les mots de passe ne correspondent pas\n";
			}
		}
	}
	return sError;
}
// the following function is set up to determine if a date is valid. 
// the optional field, iMageAge, is currently used on myoffers to make sure a user 
// is over 18 (ie. if iMaxAge = 18 is input)
function validDate(loForm, sPrefix, iMaxAge)
{
	var sError;
	var iDay, iMonth, iYear, dDate, dCurrentDate, dNow, iYearDiff, aMonthDays;
	var oDay, oMonth, oYear;
	sError = '';
	loForm = GetForm(loForm);
	oDay = GetField(loForm, sPrefix + 'Day');
	if (oDay)
	{
		oMonth = GetField(loForm, sPrefix + 'Month');
		oYear = GetField(loForm, sPrefix + 'Year');
		if (oMonth && oYear)
		{
			iDay = FieldValue(loForm, oDay);
			iMonth = FieldValue(loForm, oMonth);
			iYear = FieldValue(loForm, oYear);
			if (iDay && iMonth && iYear)
			{
				iMonth --;
				aMonthDays = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
				if (iDay > aMonthDays[iMonth])
				{
					sError = 'Valid ' + sPrefix + ' Date\n';
				}
				else if (iMaxAge)
				{
					dDate = new Date(iYear, iMonth, iDay);
					dCurrentDate = new Date();
					iYearDiff = (dCurrentDate - dDate) / 31536000000;
					if (iYearDiff < iMaxAge)
					{
						sError = 'Vous devez avoir plus de ' + iMaxAge + ' ans pour souscrire\n';
					}
				}
			}
			else
			{
				if (sPrefix == 'Birth')
						sPrefix = 'de naissance';
				sError = 'Date ' + sPrefix + ' incomplète\n';
			} //iDay && iMonth && iYear
		} // oDay && oMonth && oYear
	}
	return(sError);
}
//--------------------------------------------------
function validName(sName, iLength)
{
	var bName, sValidChar, sNamePattern, oNameRe;
	bName = false;
	if ((iLength && sName && sName.length > iLength)
		|| (!iLength && sName && sName.length > 0))
	{
		sNamePattern = "^\\s*[äëüïöâêûîôèàùçéA-Za-z]+([äëüïöâêûîôèàùçéA-Za-z]|[\\-\\s\\'])*\\s*$"
		oNameRe = new RegExp(sNamePattern)
		if (sName.match(oNameRe))
		{
			bName = true;
		}
	}
	return bName;
}
//-----------------------------------------------Added code by sg
function validAddress(sAddress, iLength)
{
	var bAddress, sValidChar, sAddressPattern, oAddressRe;
	bAddress = false;
	if ((iLength && sAddress && sAddress.length > iLength)
		|| (!iLength && sAddress && sAddress.length > 0))
	{
		sAddressPattern = "^\\s*[äëüïöâêûîôèàùçéA-Za-z0-9,]+([äëüïöâêûîôèàùçéA-Za-z0-9,]|[\\-\\s\\'])*\\s*$"
		oAddressRe = new RegExp(sAddressPattern)
		if (sAddress.match(oAddressRe))
		{
			bAddress = true;
		}
	}
	return bAddress;
}
//------------------------------------------------
function validMobile(lsMobileNumber, lsRequired)
{
	var bValid;
	bValid = true;
	sError = '';
	if (lsMobileNumber && lsMobileNumber.length > 0)
	{
		// remove white spaces
		lsMobileNumber = lsMobileNumber.replace(/\s*/g, '');

		if (!lsMobileNumber.match(/^(\s*|06\d{8})$/))
		{
			bValid = false;
			sError += 'Valid mobile number (10 digits long starting with 06)\n';
		}
	}
	else if (lsRequired)
	{
		bValid = false;
		sError = "required\n";
	}
	return(bValid);
}
//---------------------------------------------------