var checkform_debug=false;

function CheckForm(contid, formname, outputdivid, outputanchor)
{
	var xmlhttp=false;
	var outputdiv;
	
	if(outputdivid) {
		outputdiv=document.getElementById(outputdivid);
		if(outputdiv) {
			outputdiv.innerHTML="Processing....";
		}
		if(outputanchor) {
			location.hash=outputanchor;
		}
	}
	document.body.style.cursor='wait';
	
	/*Build the info to send*/
	var cont=document.getElementById(contid);
	var paramstring=GetParams(cont, formname);
	
	var xmlhttp=false;
   
   if (window.XMLHttpRequest){
      // If Firefox, IE7+, Safari, etc: Use native object
      xmlhttp = new XMLHttpRequest()
   }
   else
   {
      if (window.ActiveXObject){   
	      try {
  		      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 	      } catch (e) {
  		      try {
   			      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  		      } catch (E) {
   			      xmlhttp = false;
  		      }
	      }
      }
   }
          
	if(!xmlhttp) {
		alert("Sorry! At the moment this website requires a modern browser (at the very least IE6 but Firefox would be ideal)");
		document.body.style.cursor='';
		return;
	}
	
	xmlhttp.onreadystatechange =function(){GotResponse(xmlhttp, outputdiv);};
			
	xmlhttp.open('POST', 'checkform.php', true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", paramstring.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(paramstring);
}

function GetParams(cont, formname)
{
	var string="form="+encodeURIComponent(formname);
	var i;
	
	var inputs=cont.getElementsByTagName('input');
	for (i=0; i<inputs.length ; i++) {
		if("text" == inputs[i].type || "hidden" == inputs[i].type || "password" == inputs[i].type) {
			string += ("&"+encodeURIComponent(inputs[i].name)+"="+encodeURIComponent(inputs[i].value));
		} else if ("checkbox" == inputs[i].type && inputs[i].checked) {
			string += ("&"+encodeURIComponent(inputs[i].name)+"="+encodeURIComponent(inputs[i].value));
		}
	}
	var selects=cont.getElementsByTagName('select');
	for (i=0; i<selects.length ; i++) {
		string += ("&"+encodeURIComponent(selects[i].name)+"="+encodeURIComponent(selects[i].value));
	}
	var textareas=cont.getElementsByTagName('textarea');
	for (i=0; i<textareas.length ; i++) {
		string += ("&"+encodeURIComponent(textareas[i].name)+"="+encodeURIComponent(textareas[i].value));
	}

	if(checkform_debug) {
		alert("sending:"+string);	
	}
	return string;
}

function GotResponse(xmlhttp,outputdiv)
{
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200 ) {
			if(checkform_debug) {
				alert("received: "+xmlhttp.responseText);	
			}

			if(!xmlhttp.responseXML) {
				alert("Communication with the server failed. Please try later");
			} else {
				var firsterrornode=xmlhttp.responseXML.getElementsByTagName('error')[0];
			
				if(firsterrornode) {
					ProcessFormErrors(xmlhttp.responseXML,outputdiv);
				} else {
					var formsuccessnode=xmlhttp.responseXML.getElementsByTagName('success')[0];
			
					if(formsuccessnode) {
						ProcessFormSuccess(formsuccessnode,outputdiv,xmlhttp.responseXML);
					}
				}
			}
		} else {
			alert("Server Error, please try again later.");
		}
		document.body.style.cursor='';
		xmlhttp=false;
	}
}


//This function processes a formsuccess element sent in return to a well-formed form submission
//This has two key attributes:
//   location - an url
//   method   - one of goto (jump straight to the url)
//                     script - run some javascript
//                     post - build a form from the child params and submit ir
function ProcessFormSuccess(SuccessNode, OutputDiv, FullResponse)
{
   var newlocation;
   
   if(   SuccessNode.getAttribute('method') == 'goto'
      || SuccessNode.getAttribute('method') == 'post') {
      newlocation = getTextContent(SuccessNode.getElementsByTagName('location')[0]);
   }

   if(SuccessNode.getAttribute('method') == 'goto') {
      if(checkform_debug) {
	      alert('About to change page to: '+   newlocation);
      }
      window.location = newlocation;
      return;
   }
   
   if(SuccessNode.getAttribute('method') == 'script') {
      document.lastSuccessResponse = FullResponse; //Store for scripts in response that need it
      var scripts=SuccessNode.getElementsByTagName('script');
      
      for(var i=0; i< scripts.length ; i++) {
         var thescript = getTextContent(scripts[i]);
         if(checkform_debug) {
	         alert('about to run:'+thescript);
         }
         eval(thescript);
      }
      OutputDiv.innerHTML="";
      document.lastSuccessResponse = null;
      return;
   }
	var newform=document.createElement('form');
	newform.method='post';
	newform.action=newlocation;
	
	var params=SuccessNode.getElementsByTagName('param');
	
	for(var i=0; i< params.length ; i++) {
		var paramid=params[i].firstChild.nodeValue;
		var paramnode=document.getElementById(paramid);
		var newnode;
		
		if(paramnode) {
			newnode=paramnode.cloneNode(true);
		} else {
			newnode=document.createElement('input');
			newnode.type="hidden";
			newnode.id=paramid;
			newnode.name=paramid;
		}
		
		var newvalue=params[i].getAttribute('value');
		if(newvalue != null) {
			newnode.value=newvalue;
		}
		newform.appendChild(newnode);
	}
	var hiddendiv=document.createElement('div');
	hiddendiv.style.display="none";
	
	document.body.appendChild(hiddendiv);
	hiddendiv.appendChild(newform);
//GetParams(newform, 'test');	
	newform.submit();
}

function ProcessFormErrors(ErrorsNode, OutputDiv)
{
	if(OutputDiv)OutputDiv.innerHTML="";

	var errors=ErrorsNode.getElementsByTagName('error');
	var doneanchor=false;
	
	for(var i=0; i< errors.length ; i++) {
		var location = errors[i].getAttribute('location');
		var errortext= "Internal Error";
		
		if(errors[i].firstChild) {
			errortext=errors[i].firstChild.nodeValue;
		}
		
		var locationnode;
		
		if(location && (locationnode=document.getElementById(location))) {
			locationnode.innerHTML=errors[i].firstChild.nodeValue;

			var newclass;
			if(newclass = errors[i].getAttribute('class')) {
				locationnode.className=newclass;
			}
		} else {
			window.alert(errortext);
		}
		
		if(!doneanchor) {
			var anchor = errors[i].getAttribute('anchor');
			if(anchor) {
				location.hash=anchor;
				doneanchor=true;
			}
		}
	}
	
	var noerrors=ErrorsNode.getElementsByTagName('noerror');
	
	for(var i=0; i< noerrors.length ; i++) {
		var location = errors[i].getAttribute('location');
		var locationnode;
		if(location && (locationnode=document.getElementById(location))) {
			locationnode.innerHTML='';
		}
	}
}

//getTextContent is passed an XML DOM Element Node and returns the
//text content. In IE that's .text in other browsers it's .textContent
function getTextContent(elemNode)
{
   var trimmed = '';
   var untrimmed = '';
   
   if(elemNode.textContent) {
      untrimmed =  elemNode.textContent;
   }
   if(elemNode.text) {
      untrimmed = elemNode.text;
   }
   trimmed = untrimmed.replace(/^\s+|\s+$/g, '') ;
   return trimmed;
}

