

// This ensures that the value contains at least 1 non-whitespace character
function isNotEmpty(theField) {
	return !isEmpty(theField)
}

function isEmpty(theField) {
	if (!theField) return true;
	return (theField.value.blank());
}

// This ensures that the select element has a selected value that matches one of the values in the list provided.
// If the list is empty, then it can never pass, as it will never match any item in the list.
// If the select element has no options, it can also never pass.
// FIXME: This will not work correctly on select elements that can have multiple values selected. We'd need to modify it for that.
function selectFieldHasToHaveValueInList(theField, arrayOfAllowedValues) {
	if (arguments.length != 2) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'SELECT') return false;	// Check field is select element
	if (theField.options.length == 0) return false;	// Check field has options
	if (!arrayOfAllowedValues.length) return false;	// Check list of allowed values has items
	if (theField.selectedIndex == -1) return false;	// Check field has a selected item

	// Extract the selected item
	var selectedValue = theField.options[theField.selectedIndex].value;

	if (arrayOfAllowedValues.indexOf(selectedValue) != -1) {
		return true;
	} else {
		return false;
	}
}


// Min will always be 0 or greater. Max should always be equal to or greater than min
function textFieldValueIsCertainLength(theField, minLength, maxLength) {
	// Any element with no min/max specified should always fail - even a valid text input element
	if (arguments.length != 3) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;			// Check field is a text input element

	// Min/max should always be positive integers, and max should always be >= min
	if (minLength == null) return false;				// Because "isNaN(null)" returns false in Fx2/Win !!!
	if (maxLength == null) return false;
	if (isNaN(minLength)) return false;
	if (isNaN(maxLength)) return false;
	if (minLength != parseInt(minLength, 10)) return false;
	if (maxLength != parseInt(maxLength, 10)) return false;
	if (minLength < 0) return false;
	if (maxLength < minLength) return false;

	if (theField.value.length < minLength) return false;
	if (theField.value.length > maxLength) return false;

	return true;
}

function textFieldCanOnlyContainCertainCharacters(theField, charString) {
	if (arguments.length != 2) return false;		// Check all args are present
	if (!theField) return false;				// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;		// Check field is a text input element

	charString = escapeStringCharsForRegExp(charString);
	var regExp = new RegExp('[^' + charString + ']');

	var matches = theField.value.match(regExp);
	if (null === matches) return true;
	return false;
}


function isAlphaNumeric(theField, mustHaveAlpha, mustHaveNumber) {
	if (arguments.length != 3) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;			// Check field is a text input element

	if (typeof(mustHaveAlpha) != 'boolean') return false;
	if (typeof(mustHaveNumber) != 'boolean') return false;

	var validField = true;
	if (mustHaveAlpha) {
		if (!theField.value.match(/[a-zA-Z]+/)) validField = false;
	}

	if (mustHaveNumber) {
		if (!theField.value.match(/\d+/)) validField = false;
	}

	return validField;
}


function textFieldMustBeginWithCertainCharacters(theField, charString) {
	if (arguments.length != 2) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;			// Check field is a text input element

	return !textFieldCannotBeginWithCertainCharacters(theField, charString);
}


function textFieldCannotBeginWithCertainCharacters(theField, charString) {
	if (arguments.length != 2) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;			// Check field is a text input element

	charString = escapeStringCharsForRegExp(charString);
	var regExp = new RegExp('^[' + charString + ']');
	var matches = theField.value.match(regExp);
	if (!matches) return true;
	return false;
}


function textFieldCannotEndWithCertainCharacters(theField, charString) {
	if (arguments.length != 2) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;			// Check field is a text input element

	charString = escapeStringCharsForRegExp(charString);
	var regExp = new RegExp('[' + charString + ']$');
	var matches = theField.value.match(regExp);
	if (!matches) return true;
	return false;
}


function textFieldDoesNotContainWord(theField, wordString) {
	if (arguments.length != 2) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;			// Check field is a text input element
	if (wordString == null) return true;
	if (wordString == "") return true;

	return (theField.value.toLowerCase().indexOf(wordString.toLowerCase()) == -1);
}


function textFieldContainsValidEmailAddress(theField) {
	if (arguments.length != 1) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;			// Check field is a text input element

	return validEmailAddress(theField.value);
}

// 
function textFieldCannotHaveConsecutiveCharacters(theField, charString) {
	if (arguments.length != 2) return false;			// Check all args are present
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (!isTextField(theField)) return false;			// Check field is a text input element
	
	var sValue = theField.value;

	for(var i=0; i<charString.length; i++){
		var sSpecialChar = charString.substr(i, 1);
		if(sValue.match(sSpecialChar)){
			for(var j=0; j<sValue.length; j++){
				var sCurrentLetter = sValue.substr(j, 1);
				var sNextLetter = sValue.substr(j+1, 1);
				if((matchWithSpecialCharacters(sCurrentLetter, charString)) && (matchWithSpecialCharacters(sNextLetter, charString))){
					return false;
				}
			}
		}
		else{
			return true;
		}
	}
	return true;
}

function matchWithSpecialCharacters(sLetter, sChars){
	for(var i=0; i<sChars.length; i++){
		var sSpecial = sChars.substr(i, 1);
		if(sLetter == sSpecial){
			return true
		}
	}
}

// Converted from the PHP validator here: http://www.linuxjournal.com/article/9585
function validEmailAddress(email) {
	if (typeof(email) != 'string') return false;

	var atIndex = email.lastIndexOf("@");
	if (atIndex == -1) return false;

	var domain = email.substr(atIndex + 1);
	var local = email.substr(0, atIndex);
	var localLen = local.length;
	var domainLen = domain.length;
	var totalLen = localLen + domainLen;

	if (totalLen > 128) {
		// local part length exceeded
		return false;
	} else if (local.charAt(0) == '.' || local.charAt(localLen-1) == '.') {
         // local part starts or ends with '.'
		return false;
	} else if (local.match(new RegExp('\\.\\.'))) {
         // local part has two consecutive dots
		return false;
	} else if (!domain.match(new RegExp('^[A-Za-z0-9\\-\\.]+$'))) {
         // character not valid in domain part
		return false;
	} else if (domain.match(new RegExp('\\.\\.'))) {
         // domain part has two consecutive dots
		return false;
	} else if (!local.replace(/\\\\/g, "").match(new RegExp('^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$'))) {
         // character not valid in local part unless
         // local part is quoted
         if (!local.replace(/\\\\/g, "").match(new RegExp('^"(\\\\"|[^"])+"$'))) {
        	 return false;
         }
	} else if (!domain.match(new RegExp('[\\S]+\\.[\\S]+'))) {
		// Not part of the RFC, but for our purposes, make sure the domain isn't 'local' (i.e. at least 'x.y', not just 'x')
		return false;
	} else {
		//do nothing
	}
	
	var aDotSplit = domain.split('.');
	if(aDotSplit.length > 5){
		// Can't have more than 2 dots in the suffix, ie: .co.uk.it
		return false;
	}

	return true;
}


function checkboxMustBeChecked(theField) {
	if (!theField) return false;						// Check field is valid
	if (theField.tagName != 'INPUT') return false;		// Check field is input element
	if (theField.type != 'checkbox') return false;		// Check field is a checkbox input element

	return theField.checked == true;
}


/* Helper functions */

// Escape any meta characters chars so the RegExp works correctly. Chars escaped are: ^ [ ] . $ { * ( \ + ) | ? < > -
function escapeStringCharsForRegExp(charString) {
	charString = charString.replace(/\\/g, '\\\\');		// THIS MUST BE THE FIRST ESCAPE DONE, AS OTHERWISE ALL \ WILL BE QUADRUPLED!
	charString = charString.replace(/\^/g, '\\^');
	charString = charString.replace(/\[/g, '\\[');
	charString = charString.replace(/\]/g, '\\]');
	charString = charString.replace(/\./g, '\\.');
	charString = charString.replace(/\$/g, '\\$');
	charString = charString.replace(/\{/g, '\\{');
	charString = charString.replace(/\*/g, '\\*');
	charString = charString.replace(/\(/g, '\\(');
	charString = charString.replace(/\+/g, '\\+');
	charString = charString.replace(/\)/g, '\\)');
	charString = charString.replace(/\|/g, '\\|');
	charString = charString.replace(/\?/g, '\\?');
	charString = charString.replace(/\</g, '\\<');
	charString = charString.replace(/\>/g, '\\>');
	charString = charString.replace(/\-/g, '\\-');
	return charString;
}

function isTextField(theField) {
	if (theField.type == 'text') return true;
	if (theField.type == 'password') return true;
	return false;
}

function serverError(){
	//validateAddressline1();
	//validatePostcode();
	//validatePhoneNumber();
	var dServerErrors = document.getElementById('serverErrors');
	dServerErrors.style.display = 'block';
	var aInputs = document.getElementsByTagName('input');
	for(var i=0; i < aInputs.length; i++){
		if(aInputs[i].type == 'text'){
			aInputs[i].style.border = '2px solid #CF0008';
		}
	}
}

function enableFields(event){
	//identify delete stroke and capture when length is 1
	//delete key = 46
	//backspace key = 8
	//tab key = 9
	//down key = 40
	//ctrl key = 17
	
	clearTimeout(oEnableDBLClick);
	
	var dUsername = document.getElementById('primaryUsername');
	var dViewing = document.getElementById('viewingCardNumber');
	var dDigits = document.getElementById('last6Digits');
	if(!event){
		if(dUsername){
			dUsername.disabled = false;
		}
		dViewing.disabled = false;
		dViewing.value = '';
		dDigits.disabled = false;
		dDigits.value = '';
		return false;
	}
	
	// When user hold ctrl and cuts
	if((event.keyCode == 17) && (event.target.value == '')){
			if(dUsername){
				dUsername.disabled = false;
			}
			dViewing.disabled = false;
			dDigits.disabled = false;
			changeOrColor('#5686B6');
			return false;
	}

	if(event.keyCode == 9){
		return false;
	}
	if(event.keyCode == 40){
		//
		//setTimeout(function(){ alert(event.target.value) }, 2500);
	}
	
	var nCharLength = event.target.value.length;	
	var bEnable = ((event.keyCode == 46) || (event.keyCode == 8)) ? true : false;
	//alert(event.keyCode)

	if((bEnable) && (nCharLength == 0)){
		//alert(bEnable + '\n' + event.target.value.length);
		if(dUsername){
			dUsername.disabled = false;
		}
		dViewing.disabled = false;
		dDigits.disabled = false;
		changeOrColor('#5686B6');
	}
	else if((bEnable) && (event.target.selected)){
		if(dUsername){
			dUsername.disabled = false;
		}
		dViewing.disabled = false;
		dDigits.disabled = false;
		changeOrColor('#5686B6');
	}
	else {
		var sFieldActive = event.target.id;
		disableFields(sFieldActive);
	}
}

function disableFields(sFieldActive){
	var dUsername = document.getElementById('primaryUsername');
	var dViewing = document.getElementById('viewingCardNumber');
	var dDigits = document.getElementById('last6Digits');
	if(sFieldActive == 'primaryUsername'){
		dViewing.disabled = true;
		dViewing.value = '';
		dDigits.disabled = true;
		dDigits.value = '';
		hideError('viewingCardNumber');
		hideError('last6Digits');
	}
	else if(sFieldActive == 'viewingCardNumber'){
		if(dUsername){
			dUsername.disabled = true;
			dUsername.value = '';
			hideError('primaryUsername');
		}
		dDigits.disabled = true;
		hideError('last6Digits');
	}
	else{
		if(dUsername){
			dUsername.disabled = true;
			dUsername.value = '';
			hideError('primaryUsername');
		}
		dViewing.disabled = true;
		dViewing.value = '';
		hideError('viewingCardNumber');
	}
	changeOrColor('#CCC');
}

var oEnableDBLClick = null;
function enableFieldsDBLClick(event){
	var sFieldActive = event.target.id;
	if(event.target.value != ''){
		disableFields(sFieldActive);
		clearTimeout(oEnableDBLClick);
	}
	else{
		var oEnableDBLClick = setTimeout(function(){
											enableFieldsDBLClick(event);
											}, 200
										);
	}
}

function registerObjSelected(dObj){
	if(dObj.selectionStart == dObj.value.length){
		dObj.selected = true;
	}
	else{
		dObj.selected = false;
	}
}


function changeOrColor(sColor){
	var dIdandVSecurityPod = document.getElementById('idandVSecurityPod');
	var aSpans = dIdandVSecurityPod.getElementsByTagName('span');
	for(var i=0; i<aSpans.length; i++){
		if(aSpans[i].className.match('or ')){
			aSpans[i].style.color = sColor;
		}
	}
}

function showCountrySpecificFields(sCountry){

	if( (sCountry == 'UK') || (sCountry == 'GBR') || (sCountry == 'GB') ){
		var dCountryUK = document.getElementById('countryUK');
		dCountryUK.checked = true;
		$('addressWrapper').show();
		$('postcodeWrapper').show();
		$('phoneWrapper').hide();
		if($('phoneNumberErrorMessage')){
			hideError('phoneNumber');
		}
	}
	else{
		var dCountryROI = document.getElementById('countryROI');
		dCountryROI.checked = true;
		$('addressWrapper').hide();
		if($('addressline1ErrorMessage')){
			hideError('addressline1');
		}
		$('postcodeWrapper').hide();
		if($('postcodeErrorMessage')){
			hideError('postcode');
		}
		$('phoneWrapper').show();
	}
	
	$$('.rounded-box').each(function(thePod) { 
		thePod.addClassName('jsVHidden'); thePod.style.visibility = 'hidden'; 
	});

	if($$(".validationArrow")[0]) $$(".validationArrow")[0].remove();
	if($$(".validationArrowFix")[0]) $$(".validationArrowFix")[0].remove();
}




/*
 *	Used to enable fields in a particular group and disable others that are part of the associated collection.
 *	When the user populates a form field the group becomes active and all other fields in the wider collection become disabled.
 *	When the user removes content all fields in the collection become enabled.
 *	Fields become active by key presses or selecting previous values from the browser history (problematic).
 */

// Create generic object for multiple associations within a <form/>
function toggleFormFieldAccess(aCollection, sName, aSeperatorIds, bDynamicGroup){
	this.name = sName;
	this.collection = aCollection;
	this.groupIds = [];
	this.allIds = [];
	this.fieldIdsAsStrings = [];
	this.seperatorIds = aSeperatorIds;
	this.dynamicGroup = bDynamicGroup || false;
	this.dynamicCount = 0;
	this.cancelDisable = false;
	this.timeout = null;
	this.activeColor = '#5686B6';
	this.passiveColor = '#CCC';
	this.init();
}

/*
 *  Initialise the following arrays:
 *  groupIds: the group ids in our collection;
 *  allIds: the ids of all form fields in our collection;
 *  fieldIdsAsStrings: convert the field ids per group into a string for quick lookup.
 *  Attach necessary events to all fields in the collection.
 */

toggleFormFieldAccess.prototype.init = function(){
	// Initialise arrays
	for(var i=0; i<this.collection.length; i++){
		var groupId = this.collection[i].id;
		this.groupIds.push(groupId);
		var aGroupFieldIds = this.collection[i].fieldIds;
		this.fieldIdsAsStrings[groupId] = aGroupFieldIds.join();
		for(var j=0; j<aGroupFieldIds.length; j++){
			this.allIds.push(aGroupFieldIds[j]);
			// Initialise form field events.
			// Use prototype bind() to bind 'this' instance to the event.			
			if($(aGroupFieldIds[j]).type == 'text'){
				// We want the fields to disable dynamically depending on the previous inputs
				// We have to be careful of the order of assignment depending on Browser
				if(this.dynamicGroup){
					if(document.all){
						Event.observe($(aGroupFieldIds[j]), 'keyup', this.enableFields.bind(this));
						Event.observe($(aGroupFieldIds[j]), 'keyup', this.registerDynamicGroup.bind(this));
					}
					else{
						Event.observe($(aGroupFieldIds[j]), 'keyup', this.registerDynamicGroup.bind(this));
						Event.observe($(aGroupFieldIds[j]), 'keyup', this.enableFields.bind(this));
					}
				}
				else{
					Event.observe($(aGroupFieldIds[j]), 'keyup', this.enableFields.bind(this));
				}
				Event.observe($(aGroupFieldIds[j]), 'blur', this.enableFields.bind(this));
				Event.observe($(aGroupFieldIds[j]), 'select', this.registerObjSelected);
			}
			else{
				Event.observe($(aGroupFieldIds[j]), 'change', this.enableFields.bind(this));
			}
		}
	}
	//should we remove?
	//this.enableAllFields();
}

toggleFormFieldAccess.prototype.enableAllFields = function(){
	for(var i=0; i<this.collection.length; i++){
		var aGroup = this.collection[i].fieldIds;
		for(var j=0; j<aGroup.length; j++){
			var dElement = document.getElementById(aGroup[j]);
			if(dElement){
				dElement.disabled = false;
				//IE disabled background
				if(document.all){
					dElement.style.backgroundColor = '';
					dElement.style.color = '';
				}
			}
		}
	}
	// Enable 'seperator' label
	this.setSeperatorColor(true);
}

toggleFormFieldAccess.prototype.enableFields = function(event){
	// delete key = 46; backspace key = 8; tab key = 9; down key = 40; ctrl key = 17; x key = 88;
	
	// Don't do anything if tabkey or no valid keycode entered
	if(((!event.keyCode) && (event.type != 'blur')) || (event.keyCode == 9)){
		if(event.type == 'change'){
			//do nothing
		}
		else{
			return false;
		}
	}
	// When user hold ctrl and cuts (using x)
	if(((event.keyCode == 17) && (event.target.value.length == 0)) || ((event.keyCode == 88) && (event.target.value.length == 0))){
		if(this.dynamicGroup){
			this.unRegisterDynamicGroup(event);
		}
		// enable everything
		this.enableAllFields();
		return false;
	}
	if(event.keyCode == 40){
		//setTimeout(function(){ alert(event.target.value) }, 2500);
	}
	
	var nCharLength = event.target.value.length;
	var bEnable = ((event.keyCode == 46) || (event.keyCode == 8)) ? true : false;
	if(event.type.match('change')){
		// enable everything in the collection if user changes a select box back to a default value
		bEnable = (event.target.selectedIndex === 0) ? true : false;
		nCharLength = (event.target.selectedIndex === 0) ? 0 : 1;
	}
	
	if(this.dynamicGroup){
		if((bEnable) && (nCharLength == 0)){
			this.unRegisterDynamicGroup(event);
		}
	}
	bEnable = this.getSiblingsAreEmpty(event.target.id);

	if((bEnable) && (nCharLength == 0)){
		//alert(bEnable + '\n' + event.target.value.length);
		this.enableAllFields();
	}
	else if((bEnable) && (event.target.selected)){
		// enable everything
		this.enableAllFields();
	}
	else{
		var sActiveElementId = event.target.id;
		var aTempDisabledIds = this.getDisableFields(sActiveElementId)
		if(!this.cancelDisable){
			this.disableFields(aTempDisabledIds, event);
		}
	}
}

toggleFormFieldAccess.prototype.getDisableFields = function(sActiveElementId){
	// If the target field is being filled in, identify which group it belongs to and disable the opposite group(s)
	var aTempDisabledIds = [];
	for(var i=0; i<this.groupIds.length; i++){
		var sIds = this.fieldIdsAsStrings[this.groupIds[i]];
		if(!sIds.match(sActiveElementId)){
			//Add group to collection to be disabled
			var aTempDisabledIds = aTempDisabledIds.concat(this.collection[i].fieldIds);
		}
	}
	return aTempDisabledIds;
}

toggleFormFieldAccess.prototype.disableFields = function(aFieldIds, event){
	for(var i=0; i<aFieldIds.length; i++){
		var dElement = document.getElementById(aFieldIds[i]);
		if(dElement){
			dElement.disabled = true;
			//IE disabled background
			if(document.all){
				dElement.style.backgroundColor = '#EBEBE4';
				dElement.style.color = '#ACA899';
				dElement.style.border = 'solid 1px #7F9DB9';
				dElement.style.padding = '2px';
			}
			if(dElement.type == 'text'){
				dElement.value = '';
			}
			else{
				dElement.selectedIndex = 0;
			}
			var dErrorMessage = document.getElementById(aFieldIds[i] + 'ErrorMessage');
			if(dErrorMessage){
				var fieldName = aFieldIds[i];
				var errorDiv = $(fieldName + 'ErrorMessage');
				if(errorDiv){ 
					Element.remove(errorDiv);
				}
				hideFieldIcon(fieldName);
				$(fieldName).up('.formRow').removeClassName('formRowError');
				$(fieldName).parentNode.removeClassName('errors');
				//hideError(aFieldIds[i]);
			}
		}
	}
	
	// Disable 'seperator' label
	this.setSeperatorColor(false);
}

toggleFormFieldAccess.prototype.enableFieldsDBLClick = function(event){
	this.timeoutFunction = function(){ 
		var sActiveElementId = event.target.id;
		if(sActiveElementId != ''){
			var aTempDisabledIds = this.getDisableFields(sActiveElementId)
			this.disableFields(aTempDisabledIds);
		}
		else{
			//this.timeout = setTimeout(this.timeoutFunction, 5000);
		}
	}
	this.timeout = setTimeout(this.timeoutFunction, 1000);
}

toggleFormFieldAccess.prototype.setSeperatorColor = function(bEnabled){
	if(this.seperatorIds){
		var sColor = (bEnabled) ? this.activeColor :  this.passiveColor;
		for(var i=0; i<this.seperatorIds.length; i++){
			var dElement = document.getElementById(this.seperatorIds[i]);
			dElement.style.color = sColor;
		}
	}
}

toggleFormFieldAccess.prototype.registerObjSelected = function(event){
	var dObj = event.target;
	if(dObj.selectionStart == dObj.value.length){
		dObj.selected = true;
	}
	else{
		dObj.selected = false;
	}
}

toggleFormFieldAccess.prototype.getSiblingsAreEmpty = function(sId){
	var bEmpty = true;
	for(var i=0; i<this.groupIds.length; i++){
		var sIds = this.fieldIdsAsStrings[this.groupIds[i]];
		if(sIds.match(sId)){
			var aFieldIds = this.collection[i].fieldIds;
			for(var j=0; j<aFieldIds.length; j++){
				var dElement = document.getElementById(aFieldIds[j]);
				if(dElement.type == 'text'){
					if(dElement.value != ''){ 
						bEmpty = false;
					}
				}
				else if(dElement.type.match('select')){
					if(dElement.selectedIndex != 0){ 
						bEmpty = false;
					}
				}
				else{
					alert('not a text or select field')
				}
			}
		}
	}
	return bEmpty
}

toggleFormFieldAccess.prototype.registerDynamicGroup = function(event){
	var sId = event.target.id;
	if(this.fieldIdsAsStrings['active'].match(sId)){
		return false;
	}
	
	if(this.dynamicCount < 1){
		this.cancelDisable = true;
	}
	else{
		this.cancelDisable = false;
	}
	
	if(this.dynamicCount < 2){
		var aActiveIds = this.collection[0].fieldIds;
		var aPassiveIds = this.collection[1].fieldIds;
		for(var i=0; i<aPassiveIds.length; i++){
			if(aPassiveIds[i] == sId){
				var aRemoved = aPassiveIds.splice(i,1);
				aActiveIds.push(aRemoved[0]);
			}
		}
		this.updateInit();
		this.dynamicCount++;
	}
}

toggleFormFieldAccess.prototype.unRegisterDynamicGroup = function(event){
	var sId = event.target.id;
	var aActiveIds = this.collection[0].fieldIds;
	var aPassiveIds = this.collection[1].fieldIds;
	for(var i=0; i<aActiveIds.length; i++){
		if(aActiveIds[i] == sId){
			var aRemoved = aActiveIds.splice(i,1);
			aPassiveIds.push(aRemoved[0]);
		}
	}
	this.updateInit();
	this.dynamicCount--;
	this.cancelDisable = true;
}

toggleFormFieldAccess.prototype.updateInit = function(){
	// Initialise arrays
	this.allIds = [];
	this.groupIds = [];
	for(var i=0; i<this.collection.length; i++){
		var groupId = this.collection[i].id;
		this.groupIds.push(groupId);
		var aGroupFieldIds = this.collection[i].fieldIds;
		this.fieldIdsAsStrings[groupId] = aGroupFieldIds.join();
		for(var j=0; j<aGroupFieldIds.length; j++){
			this.allIds.push(aGroupFieldIds[j]);
		}
	}
}
