// ----------------------------------------------------------------------
// Javascript form validation routines.
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
//
// Update Oct 2005: minor tidy-up: unused parameter removed
//
// Update Jun 2006: minor improvements to variable names and layout
// ----------------------------------------------------------------------
// Adding some stuff I've used throughout the years to this script:
// This script will undo any form styles that browsers add for required fields
//-----------------------------------------------------------------------------
if(window.attachEvent)
    window.attachEvent("onload",setListeners);

  function setListeners(){
    inputList = document.getElementsByTagName("INPUT");
    for(i=0;i<inputList.length;i++){
      inputList[i].attachEvent("onpropertychange",restoreStyles);
      inputList[i].style.backgroundColor = "";
    }
    selectList = document.getElementsByTagName("SELECT");
    for(i=0;i<selectList.length;i++){
      selectList[i].attachEvent("onpropertychange",restoreStyles);
      selectList[i].style.backgroundColor = "";
    }
  }
  function restoreStyles(){
    if(event.srcElement.style.backgroundColor != "")
      event.srcElement.style.backgroundColor = "";
  }
 //--------------------------------------------------------------------------
 // This script will make divisions appear and disappear
 //--------------------------------------------------------------------------
 function changeDiv(the_div,the_change)
{
  var the_style = getStyleObject(the_div);
  if (the_style != false)
  {
    the_style.display = the_change;
  }
}
function getStyleObject(objectId) {
  if (document.getElementById && document.getElementById(objectId)) {
    return document.getElementById(objectId).style;
  } else if (document.all && document.all(objectId)) {
    return document.all(objectId).style;
  } else {
    return false;
  }
}
 //--------------------------------------------------------------------------
 // This script will create nifty submit rollover
 //--------------------------------------------------------------------------
var submitRolls = new Object();


	function submitroll(src, oversrc, name)
	{
		this.src=src;
		this.oversrc=oversrc;
		this.name=name;
		this.alt="Submit Query";
		this.write=submitroll_write;
	}

	function submitroll_write()
	{
		var thisform = 'document.forms[' + (document.forms.length - 1) + ']';
		submitRolls[this.name] = new Object();
		submitRolls[this.name].over = new Image();
		submitRolls[this.name].over.src = this.oversrc;
		submitRolls[this.name].out = new Image();
		submitRolls[this.name].out.src = this.src;

		document.write(
			'<A onMouseOver="if (document.images)document.images[\'' + this.name + "'].src=submitRolls['" + this.name + '\'].over.src"' + 
			' onMouseOut="if (document.images)document.images[\'' + this.name + "'].src=submitRolls['" + this.name + '\'].out.src"' + 
			' HREF="javascript:'
					);
		if (this.sendfield)
		{
			if (! this.sendvalue)
				this.sendvalue = 1;
			document.write(thisform, ".elements['", this.sendfield, "'].value='", this.sendvalue, "';");
		}
		

		document.write(thisform + '.submit();void(0);"');
		if (this.msg)document.write(' onClick="return confirm(\'' , this.msg, '\')"');
		document.write('>');
		document.write('<IMG SRC="' + this.src + '" ALT="' + this.alt + '" BORDER=0 NAME="' + this.name + '"');
		if (this.height)document.write(' HEIGHT=' + this.height);
		if (this.width)document.write(' WIDTH='  + this.width);
		if (this.otheratts)document.write(' ' + this.otheratts);
		document.write('></A>');
		
	}


function ParseChar(sStr, sChar)
{
if (sChar.length == null)
{
zChar = new Array(sChar);
}
else zChar = sChar;

for (i=0; i<zChar.length; i++)
{
sNewStr = "";

var iStart = 0;
var iEnd = sStr.indexOf(sChar[i]);

while (iEnd != -1)
{
sNewStr += sStr.substring(iStart, iEnd);
iStart = iEnd + 1;
iEnd = sStr.indexOf(sChar[i], iStart);
}
sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);

sStr = sNewStr;
}

return sNewStr;
}

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread

// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}


// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}


// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// --------------------------------------------

var proceed = 2;  

function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem.firstChild) return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text) return true;  // infofield is wrong type of node  

  if (emptyString.test(valfield.value)) {
    if (required) {
	  msg (infofield, "cls_error", "Required");  
      setfocus(valfield);
      return false;
    }
    else {
	  msg (infofield, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}

// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;
  
  msg (infofield, "warn", "");  
  return true;
}

// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "cls_error", "Invalid E-mail Address");
    setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) 
    msg (infofield, "warn", "Unusual e-mail address - check if correct");
  else
    msg (infofield, "warn", "");
  return true;
}


// --------------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function validateTelnr  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/  ;
  if (!telnr.test(tfld)) {
    msg (infofield, "cls_error", "Invalid Phone Number");
    setfocus(valfield);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (infofield, "cls_error", "" + numdigits + " Digits - Too Short");
    setfocus(valfield);
    return false;
  }

  if (numdigits>14)
    msg (infofield, "cls_error", numdigits + " Digits - Check if Correct");
  else { 
    if (numdigits<10)
      msg (infofield, "cls_error", "Only " + numdigits + " Digits - Check if Correct");
    else
      msg (infofield, "warn", "");
  }
  return true;
}



// Only script specific to this form goes here.
// General-purpose routines are in a separate file.
function validateOnSubmit() {
var elem;
var errs=0;
// execute all element validations in reverse order, so focus gets
// set to the first one in error.
if (!validateTelnr  (document.forms.demo.telnr, 'inf_telnr', true)) errs += 1;
if (!validateAge    (document.forms.demo.age,   'inf_age',  false)) errs += 1;
if (!validateEmail  (document.forms.demo.email, 'inf_email', true)) errs += 1;
if (!validatePresent(document.forms.demo.from,  'inf_from'))        errs += 1;

if (errs>1)  alert('There are fields which need correction before sending');
if (errs==1) alert('There is a field which needs correction before sending');

return (errs==0);
};  

function validateForm(name,email,message)
{
    
    var validated = false;
    
    if(document.getElementById("from") != null && document.getElementById("email") != null && document.getElementById("message") != null)
    {
        
        var name = document.getElementById("from");
        var email = document.getElementById("email");
        var message = document.getElementById("message");
        
        if (name.value != "" && email.value != "" && message.value != "")
        {
            validated = true;
        }
    }
    
    
    if(!validated)
    {
        alert("There are errors with the form, please correct them before continuing");
    }
    else 
    {
    document.getElementById("contactForm").submit();
    //alert("Apparently it worked");
    }
}
