// JavaScript Document
addLoadListener(initSignupForm);
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
//form funcition
function initSignupForm()
{
	var inputNodes = document.getElementsByTagName('input');
	for (var i=0; i<inputNodes.length; i++)
	{
		//var pattern = new RegExp("");
		if (inputNodes[i].className == "buttonSubmit")
		{
			inputNodes[i].onclick = formValidation;
		}
	}
}
//this function validates all the different values
function formValidation()
{
	//get all the values
	var data1 = trim(document.frmUpdates.fldFirst.value);
	var data2 = trim(document.frmUpdates.fldLast.value);
	var data3 = trim(document.frmUpdates.fldEmail.value);
	var errorMessager = document.getElementById('errMsg');
	var errorMSGText = "";
	var all_good = true;
	//reset all the classes to normal
	document.frmUpdates.fldFirst.className = 'textInput';
	document.frmUpdates.fldLast.className = 'textInput';
	document.frmUpdates.fldEmail.className = 'textInputE';
	//validate values one by one and set the error messages
	//validate first name
	if (data1 == "first name...")
	{
		data1 = "";
	}
	if (data2 == "last name...")
	{
		data2 = "";
	}
	if (emptyString.test(data1)) 
  	{
		//msg (infofield, "error", "All fields are required.");
		errorMSGText = "First name field is required.\n";
		all_good = false;
		document.frmUpdates.fldFirst.className += ' errMarker';
		//setfocus(valfield);
		//return false;
  	}
	if (emptyString.test(data2)) 
  	{
		//msg (infofield, "error", "All fields are required.");
		errorMSGText += "Last name field is required.\n";
		all_good = false;
		document.frmUpdates.fldLast.className += ' errMarker';
		//setfocus(valfield);
		//return false;
  	}
	//validate last name
	//validate email
	var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
	var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/ 
	if (!email.test(data3) && !email2.test(data3)) {
		//msg ('errMsg', "error", "Please enter a valid e-mail address.");
		errorMSGText += "Please enter a valid e-mail address.";
		all_good = false;
		setfocus(document.frmUpdates.fldEmail);
		document.frmUpdates.fldEmail.className += ' errMarker';
		//return false;
	}
	if (all_good)
	{
		//errorMessager.removeNode;
		formSubmition();
	}else
	{
		msg ('errMsg', 'error', errorMSGText);
		return false;
	}
	
}
//this function submits the form to the PHP script
function formSubmition()
{
	var content = getContent();
	//send data
	//info that gets submited
	var xhr;
	try{
		xhr = new XMLHttpRequest();
	} catch (error)
	{
		try
		{
			xhr = new ActiveXObject('Microsoft.XMLHTTP');
		} catch (error)
		{
			xhr = null;
		}
	}
	if (xhr != null)
	{
		
		//alert(content);
		//open xhr
		xhr.open('POST', 'includes/form_action.php?t=ajax', true);
		//send feedback to the user
		//var notify = this.parentNode;
		var notify = document.getElementById('formHolder');
		//var nextDiv = notify.nextSibling;
		//alert(notify);
		notify.className += " status";
		notify.innerHTML = "sending...";
		//nextDiv.innerHTML = "";
		
		//set the header
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		//ready state change
		xhr.onreadystatechange = function()
		{
			//if request was completed
			if (xhr.readyState == 4)
			{
				if (xhr.status == 200 || xhr.status == 304)
				{
					//nextDiv.innerHTML = "";
					//alert(nextDiv.className);
					//response from the server
					notify.innerHTML = "Thank you for submitting your information.";
					
				} else
				{
					//something went wrong
					//notify.className += " status";
					notify.innerHTML = "Sorry, something went wrong.";
				}
			}
			
		};
		
		//send it
		xhr.send(content);
		return false;
	}
	return true;
}
//gets the content for all the fields that will be submited
function getContent()
{
	var data1 = trim(document.frmUpdates.fldFirst.value);
	var data2 = trim(document.frmUpdates.fldLast.value);
	var data3 = trim(document.frmUpdates.fldEmail.value);
	var data = "fldFirst="+ data1 +"&fldLast="+ data2 +"&fldEmail="+ data3;
	return data;
}
//load page listener function
function addLoadListener(fn)
{
	if (typeof window.addEventListener != 'undefined')
	{
		window.addEventListener('load', fn, false);
	}else if (typeof document.addEventListener != 'undefined')
	{
		document.addEventListener('load', fn, false);
	}else if (typeof window.attachEvent != 'undefined')
	{
		window.attachEvent('onload', fn);
	} else
	{
		var oldfn = window.onload;
		if (typeof window.onload != 'function')
		{
			window.onload = fn;
		} else
		{
			window.onload = function()
			{
				oldfn();
				fn();
			};
		}
	}
}

// --------------------------------------------
//               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, "error", "ERROR: not a valid 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;
}
// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}
// --------------------------------------------
//            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, "error", "All fields are required.");  
      setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}
// --------------------------------------------
//                  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
}
// --------------------------------------------
//                  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 );
}
