
/* From scottandrew.com via simon.incutio.com */
function addEvent(obj, evType, fn, useCapture){
  if (obj && obj.addEventListener) {
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj && obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    // alert('Handler could not be attached');
    return false;
  }
}


// fetch xml file
var xmlDoc;
function importXML(url, func) {
	xmlDoc = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			xmlDoc = new XMLHttpRequest();
        } catch(e) {
			xmlDoc = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	xmlDoc = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		xmlDoc = false;
        	}
		}
    }
	if(xmlDoc) {
		xmlDoc.onreadystatechange = processReqChange;
		xmlDoc.open("GET", url, true);
		xmlDoc.send("");
	}
}


function processReqChange() {
    // only if req shows "loaded"
    if (xmlDoc.readyState == 4) {
        // only if "OK"
        if (xmlDoc.status == 200) {
            parseFormXml();
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                xmlDoc.statusText);
        }
    }
}

// parse form
function parseFormXml()
{
	form = document.getElementById(xmlDoc.responseXML.documentElement.getAttribute('id'));
	xmlDoc = xmlDoc.responseXML;
	// external lib check
	if(form === null){
		// prototype
		if(typeof Prototype !== 'undefined'){
			form = $(xmlDoc.documentElement.getAttribute('id'));
		}
	}
	//onsubmit, form is checked
	if(!addEvent(form, 'submit', checkForm, false)){ // if using an image as submit
		addEvent(form, 'click', checkForm, false); // look for click event instead
	}
	validators = new Array();
	elements = xmlDoc.getElementsByTagName('element');
	//create element validator objects and add to array
	for (var i = 0; i < elements.length; i++)
	{
		val = new ElementValidator(elements[i]);
		validators[val.id] = val;
		//onblur check validity
		addEvent(val.element, 'blur', onblurCheck, false); // change blur
	}
}

//called on form submit; cycle through make sure all elements are valid
function checkForm(event)
{
	var pass = true;
	for (var i in validators)
	{
		// External librairies such as Prototype will often extend properties and functions on to our elements, this check makes sure we only get valid elements.        
		if(typeof validators[i].check != 'undefined'){            
			validators[i].check();            
			if(validators[i].valid == false) {
				pass = false;            
			}
		}
	}
	if (pass == false)
	{
		message = 'You have not completed this form correctly.\n';
		message += 'Please go back and review your answers.';
		if(showAlert){ alert(message); }
		//stop form submittal
		//ie event model
		if(document.all)
		{
			event.returnValue = false;
		}
		//standard w3c model - moz
		else
		{
			event.preventDefault();
		}
	}
}

//get document name and calculate xml document to be imported
function getXmlUrl() {
	
	// Build 631
	var d = new Date();
	var randts = d.getTime();
	url = phppath + pageName + '?rand=' + randts;
	//alert(url);
	return url;
	
	// legacy
	var url = window.location.href;
	// if it ends with a get query, remove the query
	url = url.split('?')[0];
	// remove any anchor links
	url = url.split('#')[0];
	//Grab the filename
	if(url.match(/\w+\.[a-zA-Z0-9]+$/) !== null){
		//Replace filename.extension with filename.xml
		url = url.match(/\w+\.[a-zA-Z0-9]+$/).toString();
	} else {
		url = 'index.php';
	}
	var dot = url.lastIndexOf('.');
	// 631 mod_rewrite protection
	if(dot == -1){
		dot =  url.length;
	}
	url = url.substring(0, dot);
	// Build 623 - added random seed
	var d = new Date();
	var randts = d.getTime();
	url = phppath + url + '.xml?rand=' + randts;
	//alert(url);
	return url;
}

function onblurCheck(event)
{
	//ie
	if(document.all)
	{
		id = event.srcElement.getAttribute('id');
	}
	//moz
	else
	{
		id = this.getAttribute('id');
	}
	validators[id].check();
}

//Element Validator object
function ElementValidator(node)
{
	this.id = node.getAttribute('id');
	this.element = document.getElementById(this.id);
	this.valid = true;
	this.min = node.getAttribute('min');
	this.max = node.getAttribute('max');
	this.req = node.getAttribute('req') == "true";
	this.regs = new Array();
	regexes = node.getElementsByTagName('regex');
	for (var i = 0; i < regexes.length; i++ )
	{
		//grab text inside regex tag(s)
		this.regs[i] = new RegExp(regexes[i].childNodes[0].nodeValue);
	}
	err = node.getElementsByTagName('error')[0];
	if (err != null)
	{
		this.error = err.childNodes[0].nodeValue;
	}
	else
	{
		this.error = null;
	}
	this.name = node.getAttribute('name');
	this.sameAs = node.getAttribute('sameas');
	//get reference to element node that value should equal
	if (this.sameAs != null)
	{
		this.sameAs = document.getElementById(this.sameAs);
	}
	
	// enclosing elt 
	if(this.element !== null){        
		this.parentClass = this.element.parentNode.className;    
	} 

	
	this.check = function()
  	{
	   	//confirmation value. Must be same as confirming value + valid for confirming value's rules
		type = this.element.getAttribute('type');
	
	// process non-text elements, itterate through
	switch(type) {
		case 'checkbox' :
			element_name = this.element.name;
			form_name = this.element.form.id;
			element_id = this.element.id;
			var x=document.getElementsByName(element_name);
			
			if((this.req == false)){
				this.makeValid();
				return;
			}
			
			// default false
			pass = false;
			for(i=0; i < x.length; i++){
				
				var chk = x[i].checked;
				if(this.req && chk  == true){
					pass = true;
					this.makeValid();
					return;
				} else if((this.req == false) && (chk == false)){
					this.makeInvalid(this.reqErrMsg());
					return;
				}
			}
			if(pass == true){
				pass = true;
				this.makeValid();
				return;
			} else {
				this.makeInvalid(this.reqErrMsg());
				return;
			}
			break;
		case 'radio' :
			element_name = this.element.name;
			form_name = this.element.form.id;
			element_id = this.element.id;
			var x=document.getElementsByName(element_name);
			
			if((this.req == false)){
				this.makeValid();
				return;
			}
				
			// default false
			pass = false;
			for(i=0; i < x.length; i++){
				
				var chk = x[i].checked;
				if(this.req && chk  == true){
					pass = true;
					this.makeValid();
					return;
				} else if((this.req == false) && (chk == false)){
					this.makeInvalid(this.reqErrMsg());
					return;
				} 
			}
			if(pass == true){
				pass = true;
				this.makeValid();
				return;
			} else {
				this.makeInvalid(this.reqErrMsg());
				return;
			}
			break;

		
	}
	//
   	if (this.sameAs != null)
   	{
   		if (this.element.value == this.sameAs.value)
   		{
				if(validators[this.sameAs.getAttribute('id')].valid == true)
				{
	   			this.makeValid();
				}
				else
				{
					// This is triggered if a user hasn't filled in the first element of a same-as block
					var otherName = validators[this.sameAs.getAttribute('id')].name;
					this.makeInvalid('Your ' + otherName + ' is not correct.');
					// You can change this message to something else if need be, for example:
					//this.makeInvalid('Please fill out ' + otherName + ' first.');
				}
   		}
   		else
   		{
				var otherName = validators[this.sameAs.getAttribute('id')].name;
				var msg = 'This value must be identical to your ' + otherName + '.';
   			this.makeInvalid(msg);
   		}
   	}
   	else
   	{
   		var val = this.element.value;
   		//first check for required
   		if(this.req && val == "")
   		{
   			this.makeInvalid(this.reqErrMsg());
   			return;
   		}
			//if not required and no value, is valid
			else if((this.req == false) && (val == ""))
			{
				this.makeValid();
				return;
			}
   		//check for length
   		if((this.min != null && val.length < this.min) ||
   			(this.max != null && val.length > this.max))
   		{
   			this.makeInvalid(this.lenErrMsg());
   			return;
   		}
   		//check that it matches at least one supplied regex, if any supplied
   		if(this.regs.length > 0)
   		{
   			var pass = false;
   			for (var i = 0; i < this.regs.length; i++)
   			{
   				if (this.regs[i].test(val))
   				{
   					pass = true;
   					break;
   				}
   			}
   			if (pass == false)
   			{
   				this.makeInvalid(this.error);
   				return;
   			}
   		}
   		//passed all tests
   		this.makeValid();
   	}
  }
	
	this.lenErrMsg = function ()
	{
		var cap = this.name.substring(0,1).toUpperCase();
		var capName = cap + this.name.substring(1, this.name.length);
		if (this.min != null && this.max != null)
		{
			ret = capName + ' must be between ' + this.min + ' and ';
			ret += this.max +  ' characters.';
			return ret;
		}
		else if (this.min != null)
		{
			return capName + ' must be more than ' + this.min + ' characters.';
		}
		else //max, no min
		{
			return capName + ' must be less than ' + this.max + ' characters.';
		}
	};
	
	this.reqErrMsg = function()
  {
  	letter = this.name.substring(0, 1);
  	switch (letter)
  	{
  	case 'a':
  	case 'e':
  	case 'i':
  	case 'o':
  	case 'u':
  		word = 'an';
  		break;
  	default:
  		word = 'a';
  		break;
  	}
  	
  	// Build 584
  	val = this.name.replace(/_/g, " ");
  	
  	// Build 586
  	if(showDefault){
  		return 'You must supply ' + word + ' ' + val + '.';
  	} else {
  		return this.error;
  	}
  	
  };
	
	this.makeInvalid = function(errMsg)
  {
  	this.element.parentNode.className = this.parentClass + " error";
  	//insert error message
  	//if already invalid will have an error message already
  	if (this.valid == false)
  	{
  		errorNode = document.getElementById(this.id + 'errmsg');
		if(showMessage) { textNode = document.createTextNode(errMsg); } else { textNode = document.createTextNode(''); }
  		//childnodes[0] is the old error text
  		errorNode.replaceChild(textNode, errorNode.childNodes[0]);
  	}
  	else
  	{
  		//create and add to <li> a span with an error message
  		span = document.createElement('span');
  		span.className = "errormsg";
  		span.setAttribute("id", this.id + "errmsg");
		br = document.createElement('br');
		if(showMessage) { textNode = document.createTextNode(errMsg); } else { textNode = document.createTextNode(''); }
		//span.appendChild(br);
  		span.appendChild(textNode);
  		this.element.parentNode.appendChild(span);
  	}
  	this.valid = false;
  }
	
	this.makeValid = function()
  {
  	//remove error message if there
  	if(this.valid == false)
  	{
  		errorNode = document.getElementById(this.id + 'errmsg');
  		this.element.parentNode.removeChild(errorNode);
  	}
  	this.valid = true;
  	this.element.parentNode.className = this.parentClass;
  }
}

importXML(getXmlUrl(), parseFormXml);


function cntMCEChars(w, eid, mx) {
	var y = w.length;
	document.getElementById('count_' + eid).innerHTML = y;
	document.getElementById('left_' + eid).innerHTML = (mx - y);
	if (y > mx) {
		document.getElementById(eid + '_err').innerHTML = "Too many characters!";
	} else {
		document.getElementById(eid + '_err').innerHTML = "";
	}
}

function cntChars(w, eid, mx) {
	var y = w.value.length;
	document.getElementById('count_' + eid).innerHTML = y;
	document.getElementById('left_' + eid).innerHTML = (mx - y);
	if (y > mx) {
		document.getElementById(eid + '_err').innerHTML = "Too many characters!";
	} else {
		document.getElementById(eid + '_err').innerHTML = "";
	}
}

function cntMCEWords(w, eid, mx) {
	var y = w;
	var r = 0;
	a = y.replace(/\s/g, ' ');
	a = a.split(' ');
	for (z = 0; z < a.length; z++) {
		if (a[z].length > 0)
			r++;
	}
	document.getElementById('count_' + eid).innerHTML = a.length;
	document.getElementById('left_' + eid).innerHTML = (mx - a.length);
	if (a.length > mx) {
		document.getElementById(eid + '_err').innerHTML = "Too many words!";
	} else {
		document.getElementById(eid + '_err').innerHTML = "";
	}
}

function cntWords(w, eid, mx) {
	var y = w.value;
	var r = 0;
	a = y.replace(/\s/g, ' ');
	a = a.split(' ');
	for (z = 0; z < a.length; z++) {
		if (a[z].length > 0)
			r++;
	}
	document.getElementById('count_' + eid).innerHTML = a.length;
	document.getElementById('left_' + eid).innerHTML = (mx - a.length);
	if (a.length > mx) {
		document.getElementById(eid + '_err').innerHTML = "Too many words!";
	} else {
		document.getElementById(eid + '_err').innerHTML = "";
	}
}