

/*window.addEvent('domready', function(){
  thelements = document.getElementsBySelector('.hiddenfield');
	if(thelements){
		for(i=0;i<=thelements.length-1;i++){
		   thelements[i].style.display="none";
		}
	}
});*/
function validate_form(theform){
	var counter;
	var formElements = theform.elements;
	var proceed;
	var msg = '';
	var extra = '';
	
	for (i=0; i<formElements.length; i++) {
	   var clName = formElements[i].className;
	   //alert("Class: "+clName+" "+formElements[i].type+" "+formElements[i].name);
	   if(clName == "required"){
		  myName = formElements[i].name;
		  myType = formElements[i].type;
		  switch(myType){
		     case 'undefined': msg +="Error detected in the form"; break;
			 case 'radio': 
			 radios = theform[myName].length-1;
				 myOption = -1;
				 for (r=radios; r > -1; r--) {
					 if (theform[myName][r].checked) {
					 	myOption = r;
					    //i = myOption;
					 }
				     //i++;
				 }
				 
				 if (myOption == -1) {
				 	changeClass(myName, 'alertMe');
					msg = 'Please make sure all required fields are properly completed. Errors were found and have been marked in red.';										
				    //blankquestions += ","+document[theform][myName];
				 } else {
					changeClass(myName, 'preField');
				 }
				 
				 //i = i-1; //subtract one from the i variable used on the for loop to compensate for the i++ already found within the for loop
				          //if we do not subtract 1 then we will end up skipping one of the inputs
			 break;
			 case 'checkbox':
				 boxes = theform[myName].length;
				 
				 txt = ""
				 for (c = 0; c < boxes; c++) {
					if (theform[myName][c].checked) {
					 txt = "at least one checked";
					 //i = boxes;
					}
					//i++;
				 }
				 var e = myName.indexOf("[]");
				  if(e >=1){
					 myName =  myName.replace("[]","");
				  }
				 if (txt == "") {
				   changeClass(myName, 'alertMe');
				   msg = 'Please make sure all required fields are properly completed. Errors were found and have been marked in red.';
				 } else {
				   changeClass(myName, 'preField');
				 }
				
				// i = i-1;
			 break;
			 case 'select':
			    if (theform[myName].selectedIndex == 0) {
					 s = myName.replace("_"," ");
					 msg += s;
					 changeClass(myName, 'alertMe');
					 msg = 'Please make sure all required fields are properly completed. Errors were found and have been marked in red.';
				  }else{
					 changeClass(myName, 'preField');
				  }
			 break;
			 default:
				 if (theform[myName].value == '') {
					 s = myName.replace("_"," ");
					 msg += s;
					 changeClass(myName, 'alertMe');
					 msg = 'Please make sure all required fields are properly completed. Errors were found and have been marked in red.';
				  }else{
					 if(myName == "repassword"){ 
						if(theform.password.value != theform.repassword.value){
							msg ="The passwords entered didn't match";
							changeClass('password', 'alertMe')
							changeClass('repassword', 'alertMe')
						}
					 }
					 changeClass(myName, 'preField');
				  }
			 break;    
		  }
		  
	   }
	}
	if (msg != '') {
		alert(msg);
		mylegend = document.getElementById('thelegend');
		if(mylegend){
			mylegend.innerHTML = "Please fix the items in red";
		}
		return false;
	}else{
	   switch(theform){
		  default:
		     return true
	   }
	}
}
	
function changeClass(who, which){
   pos = who.indexOf("-");
   len = who.length;
   if(pos >=1){
	   newidentitiy = who.substr(0, pos);
	   extra = who.substr(pos, len);
	   who = newidentitiy+"_label"+extra;
   }else{
	  who = who+'_label'   
   }
   //alert(who+" "+which);
   identity=document.getElementById(who);
   if(identity){
      identity.className=which;
   }
} 

function setsame(from, to, what, trigger){
	// Get Values of the Div or Fieldset that will set the values;
	theel = getElementValue(what);
	if((theel == trigger)||(theel)){
	   thesetelements = new Array();
	   var fromset = document.getElementById(from);
	   var allelements = fromset.getElementsByTagName("input");
	   var fromsetsel = document.getElementById(from);
	   var allelementssel = fromsetsel.getElementsByTagName("select");
	   for (var i = 0; i < allelements.length; i++) {
	      var elem = allelements[i];
		  switch(elem.type){
		     case 'undefined': ""; break;
			 case 'radio': thesetelements[i] = elem.checked; break;
			 case 'checkbox': thesetelements[i] = elem.checked;  break; 
			 default: thesetelements[i] = elem.value; break;
		  }
	   }
	   for (var i = 0; i < allelementssel.length; i++) {
		   var elem = allelementssel[i];
		   n = i + thesetelements.length;
		   thesetelements[n] = elem.selectedIndex;
	   }
   
	   // Get the ids of the fields to which the values are going to be set
	   thetoelements = new Array();
	   var fromset = document.getElementById(to);
	   var allelements = fromset.getElementsByTagName("input");
	   var fromsetsel = document.getElementById(to);
	   var allelementssel = fromsetsel.getElementsByTagName("select");
	   for (var i = 0; i < allelements.length; i++) {
	      var elem = allelements[i];
		  thetoelements[i] = elem;
	   }
	   for (var i = 0; i < allelementssel.length; i++) {
		   var elem = allelementssel[i];
		   n = i + thetoelements.length;
		   thetoelements[n] = elem;
	   }
	   for (var i = 0; i < thetoelements.length; i++){
		  if(thetoelements[i]){
			//alert(thetoelements[i]+" | "+thesetelements[i]);
	      	setElementValue(thetoelements[i], thesetelements[i]);
		  }
	   }
	}
}
function allowgo(){
	//Open submitbutton;
}
function animate(from, to, trigger, speed){
   theel = getElementValue(from);
   var speed = (speed == null) ?  0.15 : speed;
   if(theel == trigger){ 
      new Effect.Appear(document.getElementById(to),{duration:speed}); 
   }else{
      new Effect.BlindUp(document.getElementById(to),{duration:speed}); 
   }
}


function setElementValue(formElement, value){
	//alert(formElement+" | "+value);
	switch(formElement.type){
		case 'undefined': return;
		case 'radio': formElement.checked = value; break;
		case 'checkbox': formElement.checked = value; break;
		case 'select-one': formElement.selectedIndex = value;break;

		case 'select-multiple':
			for(var x=0; x < formElement.length; x++) 
				formElement[x].selected = value[x];
			break;

		default: formElement.value = value; break;
	}
}

function getElementValue(formElement){
	if(formElement.length != null) var type = formElement[0].type;
	if((typeof(type) == 'undefined') || (type == 0)) var type = formElement.type;

	switch(type){
		case 'undefined': return;

		case 'radio':
			for(var x=0; x < formElement.length; x++) 
				if(formElement[x].checked == true)
			return formElement[x].value;

		case 'select-multiple':
			var myArray = new Array();
			for(var x=0; x < formElement.length; x++) 
				if(formElement[x].selected == true)
					myArray[myArray.length] = formElement[x].value;
			return myArray;

		case 'checkbox': return formElement.checked;
	
		default: return formElement.value;
	}
}

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

function callrefresh(){
	var sURL = unescape(window.location.pathname);
	window.location.href = sURL;
}

function moveOnMax(field,nextFieldID){
  if(field.value.length >= field.maxLength){
    document.getElementById(nextFieldID).focus();
  }
}

function addreturn(e, field){
	/*var characterCode;
	var nameme = field.name
	var textchange = document.getElementById(nameme+"_f");
	
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);
	
  	if(e && e.which){           // NN4 specific code
    	e = e
    	characterCode = e.which
  	}else {
    	e = event
    	characterCode = e.keyCode // IE specific code
  	}
  	if (characterCode == 13){
		textchange.value += '<br />';
	}else{
		if (characterCode == 8){
			setTimeout(function() {
				var thetext = field.value;
				textchange.value = thetext.replace('\n','<br />');
			}, 250);
		}else{
			textchange.value += character;
		}
	}*/
}

function setformat(){
	var fields = new Array("legal_description", "if_gated_community", "advance_scheduling", "other_delivery_address", "additional_information", "delivery_address_other", "provide_contact_name", "coverage_areas");
	for(i=0;i<=fields.length-1;i++){
		var who = fields[i];
		if(document.getElementById(who)){
			var field = document.getElementById(who);
			var nameme = field.name
			var textchange = document.getElementById(nameme+"_f");
			
			var thetext = textchange.value;
			field.value = thetext.replace(/<br \/>/g, '\n');
			//alert(field.value);
			//textchange.value ="";
		}
	}
}

function setvalue(field){
	var nameme = field.name
	var textchange = document.getElementById(nameme+"_f");
	
	var thetext = field.value;
	textchange.value = thetext;//thetext.replace(/\n/g,'<br />');
	//alert(textchange.value);
	//alert(nameme+"_f");
}

///  Wforms

// wForms - a javascript extension to web forms.
// see http://www.formassembly.com/wForms
// This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>

function wHELPERS() {};

// addEvent adapated from http://ejohn.org/projects/flexible-javascript-events/
// and  Andy Smith's (http://weblogs.asp.net/asmith/archive/2003/10/06/30744.aspx)
wHELPERS.prototype.addEvent = function(obj, type, fn) {
	if(!obj) { return; }
	
	if (obj.attachEvent) {
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
		obj.attachEvent( 'on'+type, obj[type+fn] );
	} else if(obj.addEventListener) {			
		obj.addEventListener( type,fn, false );
	} else {
		var originalHandler = obj["on" + type]; 
		if (originalHandler) { 
		  obj["on" + type] = function(e){originalHandler(e);fn(e);}; 
		} else { 
		  obj["on" + type] = fn; 
		} 
	}
}

wHELPERS.prototype.removeEvent = function(obj, type, fn) {
	if (obj.detachEvent) {
		if(obj[type+fn]) {
			obj.detachEvent( 'on'+type, obj[type+fn] );
			obj[type+fn] = null;
		}
	} else if(obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else {
		obj["on" + type] = null;
	}
}

// Returns the event's source element 
wHELPERS.prototype.getSourceElement = function(e) {	
	if(!e) e = window.event;	
	if(e.target)
		var srcE = e.target;
	else
		var srcE = e.srcElement;
	if(!srcE) return null;
	if(srcE.nodeType == 3) srcE = srcE.parentNode; // safari weirdness		
	if(srcE.tagName.toUpperCase()=='LABEL' && e.type=='click') { 
		// when clicking a label, firefox fires the input onclick event
		// but the label remains the source of the event. In Opera and IE 
		// the source of the event is the input element. Which is the 
		// expected behavior, I suppose.		
		if(srcE.getAttribute('for')) {
			srcE = document.getElementById(srcE.getAttribute('for'));
		}
	}
	return srcE;
}

// Cancel the default execution of an event.
wHELPERS.prototype.preventEvent = function(e) {
	if (!e) e = window.event;
	if (e.preventDefault) e.preventDefault();
	else e.returnValue = false;
	return false;
}

// Cancel the propagation of the event
wHELPERS.prototype.stopPropagation = function(e) {
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

// Generates a random ID
wHELPERS.prototype.randomId = function () {
	var seed = (new Date()).getTime();
	seed = seed.toString().substr(6);
	for (var i=0; i<6;i++)
		seed += String.fromCharCode(48 + Math.floor((Math.random()*10)));
	return "id-" + seed;
}

// Activating an Alternate Stylesheet (thx to: http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=27)
// Use this to activate a CSS Stylesheet that shouldn't be used if javascript is turned off.
// The stylesheet rel attribute should be 'alternate stylesheet'. The title attribute MUST be set.
wHELPERS.prototype.activateStylesheet = function(sheetref) {
	if(document.getElementsByTagName) {
		var ss=document.getElementsByTagName('link');
	} else if (document.styleSheets) {
		var ss = document.styleSheets;
	}
	for(var i=0;ss[i];i++ ) {
		if(ss[i].href.indexOf(sheetref) != -1) {
			ss[i].disabled = true;
			ss[i].disabled = false;			
		}
	}
}

// hasClass
wHELPERS.prototype.hasClass = function(element,className) {
	if(element && element.className) {
		if((' ' + element.className + ' ').indexOf(' ' + className +' ') != -1) {
			return true;
		}
	}
	return false;
}
wHELPERS.prototype.hasClassPrefix = function(element,className) {
	if(element && element.className) {
		if((' ' + element.className).indexOf(' ' + className) != -1) {
			return true;
		}
	}
	return false;
}
	wHELPERS.prototype.hasIdPrefix = function(element,idPrefix) {
		if(element && element.id) {
			if(element.id.indexOf(idPrefix) != -1) {
				return true;
			}
		}
		return false;
	}


// getTop / getLeft  
// Returns pixel coordinates from the top-left window corner.
wHELPERS.prototype.getTop = function(obj) {
	var cur = 0;
	if(obj.offsetParent) {		
		while(obj.offsetParent) {
			if((new wHELPERS()).getComputedStyle(obj,'position') == 'relative' ) {
				// relatively postioned element
				return cur;
			}
			cur+=obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	return cur;
}
wHELPERS.prototype.getLeft = function(obj) {
	var cur = 0;
	if(obj.offsetParent) {		
		while(obj.offsetParent) {
			if((new wHELPERS()).getComputedStyle(obj,'position') == 'relative' ) {
				// relatively postioned element
				return cur;
			}
			cur+=obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	return cur;
}

wHELPERS.prototype.getComputedStyle = function(element, styleName) {
	if(window.getComputedStyle) {
		return window.getComputedStyle(element,"").getPropertyValue(styleName);
	} else if(element.currentStyle) {	
		return element.currentStyle[styleName];
	}
	return false;
}
// backward compatibility
	var wHelpers = wHELPERS;   


   /* 
	* MISC FUNCTIONS 
   /* ------------------------------------------------------------------------------------------ */

// Push implementation for IE5/mac
if (!Array.prototype.push) { 
	Array.prototype.push = function() { 
		for (var i = 0; i < arguments.length; ++i) { 
			this[this.length] = arguments[i]; 
		} 
		return this.length; 
	}; 
}


  if(wHELPERS) {
	  var wFORMS = { 
	  
	  debugLevel     : 0, /* 0: Inactive, 1+: Debug Level */
	  
	  helpers        : new wHELPERS(),     
	  behaviors      : {},
	  onLoadComplete : new Array(),  /* stack of functions to call once all behaviors have been applied */
	  processedForm  : null,
	  
	  onLoadHandler  : function() {
		  for(var behaviorName in  wFORMS.behaviors) {
			   wFORMS.debug('wForms/loaded behavior: ' + behaviorName);
		  }
		 
		  for (var i=0;i<document.forms.length;i++) {
			  wFORMS.debug('wForms/initialize: '+ (document.forms[i].name || document.forms[i].id) );
			  	wFORMS.processedForm = document.forms[i];
			  wFORMS.addBehaviors(document.forms[i]);
		  }
	  },
	  
	  addBehaviors : function (node) {
		 if(!node) return;
		 
		 var deep = arguments[1]?arguments[1]:true;
		 if(!node.nodeType) {
			 // argument is not a node. probably an id string. 
			 // (typeof not used for IE5/mac compatibility)
			 node = document.getElementById(node);
		 }
			if(!node || node.nodeType!=1) return;
			
			deep=(arguments.length>1)?arguments[1]:true;	
				   
			wFORMS._addBehaviors(node, deep);					
		  },
		  
	  _addBehaviors : function (node, deep) {
		  if(node.getAttribute('rel')=='no-behavior') {
		  	return false;
		  }
		
		 // Process element nodes only
		 if(node.nodeType == 1) { 
			  for(var behaviorName in wFORMS.behaviors) {
				  wFORMS.behaviors[behaviorName].evaluate(node);
			  }
			 
			  if(deep) {
				  for (var i=0, l=node.childNodes.length, cn=node.childNodes; i<l; i++) {
				  	 if(cn[i].nodeType==1)
					 	wFORMS._addBehaviors(cn[i], deep);
				  }
			  }
			  
			  if(node.tagName.toUpperCase() == 'FORM') {
				  // wFORMS.debug('wForms/processed: ' + node.id);
				  // run the init stack
				  for (var i=0;i<wFORMS.onLoadComplete.length;i++) {
					  wFORMS.onLoadComplete[i]();
				  }
				  // empty the stack					  
				  if(wFORMS.onLoadComplete.length > 0) {
					  wFORMS.onLoadComplete = new Array();
				  }
			  }
		  }
	  },
	  
	  hasBehavior: function(behaviorName) {
		  if(wFORMS.behaviors[behaviorName]) return true;
		  return false;
	  },
	  
	  /* 
	   * DEBUG FUNCTIONS 
	   * ------------------------------------------------------------------------------------------ */
	  debug : function(txt) { 
		msgLevel = arguments[1] || 10; 	// 1 = least importance, X = most important
		
		if(wFORMS.debugLevel > 0 && msgLevel >= wFORMS.debugLevel) {
			if(!wFORMS.debugOutput)
				wFORMS.initDebug();
			if(wFORMS.debugOutput)
				wFORMS.debugOutput.innerHTML += "<br />" + txt;
		}
	  },
	  
	  initDebug : function() {
		var output = document.getElementById('debugOutput');
		if(!output) {
			output = document.createElement('div');
			output.id = 'debugOutput';
			output.style.position   = 'absolute';
			output.style.right      = '10px';
			output.style.top        = '10px';
			output.style.zIndex     = '300';
			output.style.fontSize   = 'x-small';
			output.style.fontFamily = 'courier';
			output.style.backgroundColor = '#DDD';
			output.style.padding    = '5px';
			if(document.body) // if page fully loaded
				wFORMS.debugOutput = document.body.appendChild(output);
		}
		if(wFORMS.debugOutput)
			wFORMS.debugOutput.ondblclick = function() { this.innerHTML = '' };
	}
  };
  
  wFORMS.NAME     = "wForms";
  wFORMS.VERSION  = "2.0";
  wFORMS.__repr__ = function () {
	return "[" + this.NAME + " " + this.VERSION + "]";
  };
  wFORMS.toString = function () {
	return this.__repr__();
  };
 
 
  // For backward compatibility
  wFORMS.utilities = wFORMS.helpers;
  var wf           = wFORMS; 
  wf.utilities.getSrcElement				= wFORMS.helpers.getSourceElement;
  wf.utilities.XBrowserPreventEventDefault	= wFORMS.helpers.preventEvent;
  
  // Initializations:
  
  // Attach JS only stylesheet.
  wFORMS.helpers.activateStylesheet('wforms-jsonly.css');
  // Parse document and apply wForms behavior
  wFORMS.helpers.addEvent(window,'load',wFORMS.onLoadHandler);
} 

// ------------------------------------------------------------------------------------------
// Repeat Behavior
// ------------------------------------------------------------------------------------------
   if(wFORMS) {
		// Component properties 
		wFORMS.className_repeat 			= "repeat";
		wFORMS.className_delete 			= "removeable";
		wFORMS.className_duplicateLink 		= "duplicateLink";
		wFORMS.className_removeLink 		= "removeLink";
		wFORMS.className_preserveRadioName  = "preserveRadioName";		
		wFORMS.idSuffix_repeatCounter		= "-RC";
		wFORMS.idSuffix_duplicateLink		= "-wfDL";									 
		wFORMS.preserveRadioName			= false;									 // if true, Repeat behavior will preserve name attributes for radio input. 
		wFORMS.limitSwitchScope				= true;									 	 // if true, Repeat behavior will limit the scope of nested switches.
		
		if(!wFORMS.arrMsg){
			wFORMS.arrMsg 	= new Array();
		wFORMS.arrMsg[0] 					= "Duplicate"; 					 // repeat link
		wFORMS.arrMsg[1] 					= "Will duplicate this question or section." // title attribute on the repeat link 
		wFORMS.arrMsg[2] 					= "Remove"; 								 // remove link
		wFORMS.arrMsg[3] 					= "Will remove this question or section." 	 // title attribute on the remove link
		
		wFORMS.behaviors['repeat'] = {
			
			onRepeat: null, /* Function to run after the element is repeated */
			onRemove: null, 	/* Function to run after the element is removed  */
			allowRepeat: null, /* Function for fine control on repeatable section */
			
		   	// ------------------------------------------------------------------------------------------
		   	// evaluate: check if the behavior applies to the given node. Adds event handlers if appropriate
		   	// ------------------------------------------------------------------------------------------
			evaluate: function(node) {
				
				// Repeatable element
				if(wFORMS.helpers.hasClass(node, wFORMS.className_repeat)) {
					//wFORMS.debug('evaluate/repeat: '+ node.id,3);
				   
					 if(!node.id) 
						node.id = wFORMS.helpers.randomId();
						
					// Check if we have a 'repeat' link
					var repeatLink = document.getElementById(node.id + wFORMS.idSuffix_duplicateLink);
					if(!repeatLink) {				
						// create the repeat link
						repeatLink = wFORMS.behaviors['repeat'].createRepeatLink(node.id);
												
						// find where to insert the link
						if(node.tagName.toUpperCase()=="TR") {
							// find the last TD
							var n = node.lastChild;	
							while(n && n.nodeType != 1)  
								n = n.previousSibling;
							if(n && n.nodeType == 1) 
								n.appendChild(repeatLink);
							// Else Couldn't find the TD. Table row malformed ?
						} else
							node.appendChild(repeatLink);
					}
					// Add hidden counter field if necessary
					var counterField = document.getElementById(node.id + wFORMS.idSuffix_repeatCounter);
					if(!counterField) {
						// IE Specific :-(
						if(document.all && !window.opera) { 
							// see http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/name_2.asp
							var counterFieldId = node.id + wFORMS.idSuffix_repeatCounter;
							if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") == -1) // IE5 Mac
								counterField   = document.createElement("INPUT NAME=\"" + counterFieldId + "\"");
							else
								counterField   = document.createElement("<INPUT NAME=\"" + counterFieldId + "\"></INPUT>"); 					
							counterField.type  ='hidden';
							counterField.id    = counterFieldId; 
							counterField.value = "1";
						}
						else {
							counterField = document.createElement("INPUT"); 
							counterField.setAttribute('type','hidden'); // hidden
							counterField.setAttribute('value','1');
							counterField.setAttribute('name', node.id + wFORMS.idSuffix_repeatCounter);
							counterField.setAttribute('id', node.id + wFORMS.idSuffix_repeatCounter); 
						}
						
						// get the form element						
						var form = node.parentNode;
						while(form && form.tagName.toUpperCase() != "FORM")
							form = form.parentNode;
						
						form.appendChild(counterField);
					}
					
					// Add event handler			
					wFORMS.helpers.addEvent(repeatLink,'click',wFORMS.behaviors['repeat'].duplicateFieldGroup);			
				}	
		 	  	// ------------------------------------------------------------------------------------------
				// Removeable element
				if(wFORMS.helpers.hasClass(node, wFORMS.className_delete)) {
					var removeLink = wFORMS.behaviors['repeat'].createRemoveLink();
					// find where to insert the link
					if(node.tagName.toUpperCase()=="TR") {
						// find the last TD
						var n = node.lastChild;	
						while(n && n.nodeType != 1)  
							n = n.previousSibling;
						if(n && n.nodeType == 1) 
							n.appendChild(removeLink);
						// Else Couldn't find the TD. Table row malformed ?
					} else
						node.appendChild(removeLink);
				}	
           	},
			createRepeatLink: function(id) {
				var repeatLink = document.createElement("a"); 
				var spanNode = document.createElement("span");  // could be used for CSS image replacement 
				var textNode = document.createTextNode(wFORMS.arrMsg[0]);
				repeatLink.id = id + wFORMS.idSuffix_duplicateLink;	
				repeatLink.setAttribute('href',"#");	
				repeatLink.className = wFORMS.className_duplicateLink;			
				repeatLink.setAttribute('title', wFORMS.arrMsg[1]);	
				spanNode.appendChild(textNode); 
				repeatLink.appendChild(spanNode); 
				return repeatLink;
			},
			createRemoveLink: function() {
				var removeLink = document.createElement("a");
				var spanNode   = document.createElement("span");  // could be used for CSS image replacement 
				var textNode   = document.createTextNode(wFORMS.arrMsg[2]);
				removeLink.setAttribute('href',"#");	
				removeLink.className = wFORMS.className_removeLink;
				removeLink.setAttribute('title',wFORMS.arrMsg[3]);	
				spanNode.appendChild(textNode); 
				removeLink.appendChild(spanNode);
				wFORMS.helpers.addEvent(removeLink,'click',wFORMS.behaviors['repeat'].removeFieldGroup);
				return removeLink;
			},
		   	duplicateFieldGroup: function(e) {
		   					
				var element  = wFORMS.helpers.getSourceElement(e);
				if(!element) element = e
				
				// override of the wFORMS.preserveRadioName property using a class on the repeat link.
				var preserveRadioName = wFORMS.helpers.hasClass(element,wFORMS.className_preserveRadioName) ? true : wFORMS.preserveRadioName;
				//wFORMS.debug('preserveRadioName='+preserveRadioName);
				
				// Get Element to duplicate.				
				while (element && !wFORMS.helpers.hasClass(element,wFORMS.className_duplicateLink)) {
					element = element.parentNode;
				}	
				var idOfRepeatedSection = element.id.replace(wFORMS.idSuffix_duplicateLink,"");
				var element = document.getElementById(idOfRepeatedSection); 
				
				
				if (element) {
					var wBehavior = wFORMS.behaviors['repeat']; // shortcut
					
					// Check if we have a custom function that prevents the repeat
					if(wBehavior.allowRepeat) {						
						if(!wBehavior.allowRepeat(element)) return false;
					}
					
					// Extract row counter information
					counterField = document.getElementById(element.id + wFORMS.idSuffix_repeatCounter);
					if(!counterField) return; // should not happen.
					var rowCount = parseInt(counterField.value) + 1;
					// Prepare id suffix
					var suffix = "-" + rowCount.toString()
					// duplicate node tree 
					var dupTree = wBehavior.replicateTree(element, null, suffix, preserveRadioName);  //  sourceNode.cloneNode(true); 
					// find insert point in DOM tree (after existing repeated element)
					var insertNode = element.nextSibling;
					
					while(insertNode && 
						 (insertNode.nodeType==3 ||       // skip text-node that can be generated server-side when populating a previously repeated group 
						  wFORMS.helpers.hasClass(insertNode,wFORMS.className_delete))) {						
						insertNode = insertNode.nextSibling;
					}
					element.parentNode.insertBefore(dupTree,insertNode);	 // Buggy rendering in IE5/Mac
					// if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") == -1)			
					//
					
					// the copy is not duplicable, it's removeable
					dupTree.className = element.className.replace(wFORMS.className_repeat,wFORMS.className_delete);
					// Save new row count 			
					document.getElementById(element.id + wFORMS.idSuffix_repeatCounter).value = rowCount;
					// re-add wFORMS behaviors
					wFORMS.addBehaviors(dupTree);
					
					if(wBehavior.onRepeat)
						wBehavior.onRepeat(element,dupTree);
				}				
				
				return wFORMS.helpers.preventEvent(e);
			},
			
		   	removeFieldGroup: function(e) { 
				var element  = wFORMS.helpers.getSourceElement(e);
				if(!element) element = e
				// Get Element to remove.
				var element = element.parentNode;
				while (element && !wFORMS.helpers.hasClass(element,wFORMS.className_delete)) {
					element = element.parentNode;
				}	
				element.parentNode.removeChild(element);
				if(wFORMS.behaviors['repeat'].onRemove)
						wFORMS.behaviors['repeat'].onRemove(element);
				return wFORMS.helpers.preventEvent(e);
			},	
			
			removeRepeatCountSuffix: function(str) {
				return str.replace(/-\d+$/,'');
			},
	
			replicateTree: function(element,parentElement, idSuffix, preserveRadioName) {
				
				// Duplicating TEXT-NODE (do not copy value of textareas)
				if(element.nodeType==3) { 
					if(element.parentNode.tagName.toUpperCase() != 'TEXTAREA')
						var newElement = document.createTextNode(element.data); 
				} 
				// Duplicating ELEMENT-NODE
				else if(element.nodeType==1) { 
					
					// Do not copy repeat/remove links
					if(wFORMS.helpers.hasClass(element,wFORMS.className_duplicateLink) ||
					   wFORMS.helpers.hasClass(element,wFORMS.className_removeLink)) 							
						return null; 
					// Exclude duplicated elements of a nested repeat group
					if(wFORMS.helpers.hasClass(element,wFORMS.className_delete)) 
						return null; 
					// Adjust row suffix id if we find a nested repeat group 
					if(wFORMS.helpers.hasClass(element,wFORMS.className_repeat) && parentElement!=null)
						idSuffix = idSuffix.replace('-','__');
					
					if(!document.all || window.opera) { 
						// Common Branch
						var newElement = document.createElement(element.tagName); 
					} else {
						// IE Branch 
						// see http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/name_2.asp						
						var tagHtml = element.tagName;
						
						if(element.name) 					
							if (element.tagName.toUpperCase() == "INPUT" && 
								element.type.toLowerCase()    == "radio" && preserveRadioName)
								tagHtml += " NAME='" + element.name + "' ";
							else
								tagHtml += " NAME='" + wFORMS.behaviors['repeat'].removeRepeatCountSuffix(element.name) + idSuffix + "' ";
						if(element.type) {
							tagHtml += " TYPE='" + element.type + "' ";
						}
						if(element.selected) 
							tagHtml += " SELECTED='SELECTED' ";
						if(element.checked)
							tagHtml += " CHECKED='CHECKED' ";
	
						if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") == -1) // IE5 Mac
							var newElement = document.createElement(tagHtml);
						else
							var newElement = document.createElement("<" + tagHtml + "></"+ element.tagName + ">"); 
						try { newElement.type = element.type; } catch(e) {}; // nail it down for IE5 ?, breaks in IE6
						
					}
				 
					// duplicate attributes										
					for(var i=0; i< element.attributes.length; i++) {
						var attribute = element.attributes[i];
						
						// Get attribute value. 
						if(	attribute.specified || // in IE, the attributes array contains all attributes in the DTD
							attribute.nodeName.toLowerCase() == 'value' ) { // attr.specified buggy in IE?  
							// Add the row suffix if necessary.
							if(	attribute.nodeName.toLowerCase() == "id" || 
								attribute.nodeName.toLowerCase() == "name" ||

								attribute.nodeName.toLowerCase() == "for") {
															
								if(wFORMS.hasBehavior('hint') && 
								   attribute.nodeValue.indexOf(wFORMS.idSuffix_fieldHint) != -1)  {
									//leave the field hint suffix at the end of the id.
									var value = attribute.nodeValue;
									value= wFORMS.behaviors['repeat'].removeRepeatCountSuffix(value.substr(0,value.indexOf(wFORMS.idSuffix_fieldHint))) + idSuffix + wFORMS.idSuffix_fieldHint;
								}
								else {
									if(element.tagName.toUpperCase()=="INPUT" && 
									   element.getAttribute('type',false).toLowerCase()=="radio" &&
									   attribute.nodeName.toLowerCase() == "name" && 
									   preserveRadioName) {
										var value = attribute.nodeValue;						
									}
									else {
										// var value = wFORMS.behaviors['repeat'].removeRepeatCountSuffix(attribute.nodeValue) + idSuffix;
										var value = attribute.nodeValue + idSuffix;
									}
								}
							} else {
								// Do not copy the value attribute for text/password/file input
								if(attribute.nodeName.toLowerCase() == "value" &&
								   element.tagName.toUpperCase()=='INPUT'      &&  
								  (element.type.toLowerCase() == 'text'     || 
								   element.type.toLowerCase() == 'password' || 
								   element.type.toLowerCase() == 'hidden' ||
								   element.type.toLowerCase() == 'file')) 
									var value='';   
								// Do not copy the switch behavior's 'event handled' flag, stored in the rel attribute
								else if(attribute.nodeName.toLowerCase() == "rel" && 
										attribute.nodeValue.indexOf('wfHandled') != -1) {
									var value = attribute.nodeValue.replace('wfHandled','');
								} else 
									var value = attribute.nodeValue;
							}
							// Create attribute and assign value
							switch(attribute.nodeName.toLowerCase()) {
								case "class":
									newElement.className = value; 
									break;
								case "style": // inline style attribute (fix for IE)
									if(element.style && element.style.cssText) 
										newElement.style.cssText = element.style.cssText; 
									break;								
								case "onclick": // inline event handler (fix for IE)
									newElement.onclick     = element.onclick;							
									break;							
								case "onchange":							
									newElement.onchange    = element.onchange;							
									break;							
								case "onsubmit":
									newElement.onsubmit    = element.onsubmit;							
									break;							
								case "onmouseover":							
									newElement.onmouseover = element.onmouseover;							
									break;							
								case "onmouseout":							
									newElement.onmouseout  = element.onmouseout;							
									break;							
								case "onmousedown":
									newElement.onmousedown = element.onmousedown;							
									break;							
								case "onmouseup":
									newElement.onmouseup   = element.onmouseup;							
									break;							
								case "ondblclick":
									newElement.ondblclick  = element.ondblclick;							
									break;							
								case "onkeydown":
									newElement.onkeydown   = element.onkeydown;							
									break;							
								case "onkeyup":
									newElement.onkeyup     = element.onkeyup;							
									break;							
								case "onblur": 
									newElement.onblur      = element.onblur;							
									break;							
								case "onfocus":
									newElement.onfocus     = element.onfocus;							
									break;
								default:
									newElement.setAttribute(attribute.name, value, 0);
							}
						}
					}				
				}
				if(parentElement && newElement) 
					parentElement.appendChild(newElement);
				for(var i=0; i<element.childNodes.length;i++) {
					wFORMS.behaviors['repeat'].replicateTree(element.childNodes[i],newElement,idSuffix, preserveRadioName);
				}
				return newElement;
			}
       } // End wFORMS.behaviors['repeat']
		}
   }
  