/*
first_name*
last_name*
email*
company
phone*
address
city*
state*
zip*
interest
description
*/

var min_three_sec = false;
var status_message = "Please wait, processing request.";

//these are required.  Will be checking to make sure they
//are populated properly.
var errorOn_firstname = false;
var errorOn_lastname = false;
var errorOn_email = false;
var errorOn_emailconform = false;
var errorOn_phone = false;
var errorOn_phoneconform = false;
var errorOn_city = false;
var errorOn_state = false;
var errorOn_zip = false;

//redish color for required fields
var errorColor = "#e7a8a1";

//yellow tint for required fields
var requiredFieldColor = "#ffffa0";
	
	
/**
* DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/
// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;


//animation code for the loaderPanel
var showLoaderPanel_anim; 
var hideLoaderPanel_anim;

//animation code for the buttons
var buttonsDown_anim;
var buttonsUp_anim;

function validateFields() {

	//used as a flag to prevent further execution in this function.
	var stop_code = false;

	errorOn_firstname = false;
	errorOn_lastname = false; 
	errorOn_email = false;
	errorOn_emailconform = false;
	errorOn_phone = false;
	errorOn_phoneconform = false;
	errorOn_city = false;
	errorOn_state = false;
	errorOn_zip = false;
	
	//Check to make sure if the required fields are filled out.  If they are not filled
	//invoke indicateRequiredFields()
	var cForm =document.getElementById("cForm");
	for (var i=0; i< cForm.length; i++)
	{
		var itemid = cForm.elements[i].id;
		var itemvalue = cForm.elements[i].value;

		if(((itemid == "first_name") || (itemid == "last_name") || (itemid == "email") || (itemid == "phone")|| (itemid == "city")|| (itemid == "state")|| (itemid == "zip"))&&((itemvalue == '')||(itemvalue == null)||(itemvalue == "off")))
		{
			stop_code = true;
			
			switch(itemid)
			{
				case "first_name":
						errorOn_firstname = true;
					break;
				case "last_name":
						errorOn_lastname = true;
					break;
				case "email":
						errorOn_email = true;
					break;
				case "phone":
						errorOn_phone = true;
					break;	
				case "city":
						errorOn_city = true;
					break;	
				case "state":
						errorOn_state = true;
					break;	
				case "zip":
						errorOn_zip = true;	
					break;					
			}
		}
		
		//validate email via javascript
		if(itemid == "email"){
			var vE = validateEmail(itemvalue);
			if(!vE){
				stop_code = true;
				errorOn_emailconform = true;
			}
		}
		
		//validate phonenumber via javascript
		if(itemid == "phone"){
			var vP = validatePhoneNumber(itemvalue);
			if(!vP){
				stop_code = true;
				errorOn_phoneconform = true;
			}
		}
		
		if(itemid == "zip"){
			var vZ = validateZip(itemvalue);
			
			if(!vZ){
			   stop_code = true;
			   errorOn_zip = true;	
			}
		}
	}//ends for-loop
	
	
	
	//a flag to prevent the app from further execution.
	if(!stop_code)
	{
		loaderPanel("SHOW");
	}else{
		indicateRequiredFields();
	}
}

function loaderPanel(action)
{
	
	if(action == "SHOW"){
		disableSubmit();
		showLoaderPanel();		
	}else{
		resetForm();
	}
}

function showLoaderPanel()
{
	var obj= document.getElementById("loadPanel");
	obj.style.display = "block";
	
	/**
	* animate the 'buttons' out 
	*/
	buttonsDown_anim.animate();
	
	
	/**
	* animate the 'loadPanel' 
	*/	
	showLoaderPanel_anim.animate();
	
	//set the miniunm time the email will be completed.
	setTimeout("nullifyParam()",4000);
}
//callback function for the setTimeout()
function nullifyParam()
{
	renderStatusMessage(null);
}

//this happens when the the data has been sent but nothing is heard back from the server.
function failedParam()
{
	renderStatusMessage("failed");
}


//callabck function when the animations are complete for the submition.
function sendData ()
{

	//var initial = true;
	
	var posData = new String();  
	
	var cForm =document.getElementById("cForm");
	
/*
	var cForm =document.getElementById("cForm");
	for (var i=0; i< cForm.length; i++)
	{
		var itemid = cForm.elements[i].id;
		var itemvalue = cForm.elements[i].value;

		if((itemid!="reset")&&(itemid!="submit")&&(itemid!="loader"))
		{
			// convert (&, +, =) to string equivs. Needed so URL encoded POST won't choke.
			
			itemvalue = itemvalue.replace(/&/g,"**am**");
			itemvalue = itemvalue.replace(/=/g,"**eq**");
			itemvalue = itemvalue.replace(/\+/g,"**pl**");
			
			if(initial){
				initial = false;
				posData = itemid+"="+itemvalue;
			}else{
				posData = posData+"@"+itemid+"="+itemvalue;	
			}
		}
	}
*/

	
	var first_name 		= document.getElementById('first_name').value;
	var last_name 		= document.getElementById('last_name').value;
	var email 			= document.getElementById('email').value;
	var company 		= document.getElementById('company').value;
	var phone 			= document.getElementById('phone').value;


	var street 			= document.getElementById('address').value;
	if(street == "")
		street = "n/a";
		
		
	var city 			= document.getElementById('city').value;
	var state 			= document.getElementById('state').value;
	var zip 			= document.getElementById('zip').value;
	var countree 		= document.getElementById('country').value;

	var interest		= document.getElementById('00N60000001Old3').value;
	
	var description 	= document.getElementById('contact_description').value;	

	
	posData = "first_name="+first_name+
			  "&last_name="+last_name+
			  "&email="+email+
			  "&company="+company+
			  "&phone="+phone+
			  "&street="+street+
			  "&city="+city+
			  "&state="+state+
			  "&zip="+zip+
			  "&country="+countree+
			  "&00N60000001Old3="+interest+
			  "&description="+description;
			  
	//loacted in the xmlHTTP.js file
	loadXMLPosDoc("../assets/php/xmlHttpRequest.php?contact=true&xml=true", posData);
}

/**
* These methods below are graphical methods, that change the appearence
* of the view.  It is invoked from the 'validateFields' method.
*/
function indicateRequiredFields()
{
	if(errorOn_firstname)
		document.getElementById("first_name").style.backgroundColor = errorColor;
		
	if(errorOn_lastname){
		document.getElementById("last_name").style.backgroundColor = errorColor;
	}

	if(errorOn_email){
		document.getElementById('email').style.backgroundColor = errorColor;
	}

	if(errorOn_phone){
		document.getElementById('phone').style.backgroundColor = errorColor;
	}
	
	if(errorOn_city){
		document.getElementById('city').style.backgroundColor = errorColor;
	}
	
	if(errorOn_state){
		if(!document.getElementById('state').disabled){
			document.getElementById('state').style.backgroundColor = errorColor;
		}
	}
	
	if(errorOn_zip){
		if(!document.getElementById('zip').disabled){
			document.getElementById('zip').style.backgroundColor = errorColor;
		}
	}

	//bring out the alert box.
	if(errorOn_emailconform && errorOn_phoneconform)
	{
		document.getElementById('email').style.backgroundColor = errorColor;
		document.getElementById('phone').style.backgroundColor = errorColor;
		alert('Please fill in the required fields that are now highlighted in red;\n -The email address that was submitted is not conformed correctly to continue.\n -The phone number does not have the minimal length to continue.');
		
	}else if(errorOn_emailconform || errorOn_phoneconform){
		
		if(errorOn_emailconform){
			document.getElementById('email').style.backgroundColor = errorColor;
			alert('Please fill in the required field(s) that is now highlighted in red; \n -The email address that was submitted is not conformed correctly to continue.');
		}
			
		if(errorOn_phoneconform){
			document.getElementById('phone').style.backgroundColor = errorColor;
			alert('Please fill in the required field(s) that is now highlighted in red; \n -The phone number does not have the minimal length to continue.');		
		}		
	}else { 
		alert('Please fill in the required field(s) that is now highlighted in red.')
	};
}



//the javascript validation.  There is one on the server in the PHP script. 
function validateEmail(email) 
{
	var db = 0;
	/*
	if (email == '') {
	   //if (db) alert('email address is mandatory');
	   return false;
	}*/
	if (email == '') return false;
	var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
	for (i=0; i<invalidChars.length; i++) {
	   if (email.indexOf(invalidChars.charAt(i),0) > -1) {
		  //if (db) alert('email address contains invalid characters');
		  return false;
	   }
	}
	for (i=0; i<email.length; i++) {
	   if (email.charCodeAt(i)>127) {
		  //if (db) alert("email address contains non ascii characters.");
		  return false;
	   }
	}
	
	var atPos = email.indexOf('@',0);
	if (atPos == -1) {
	   //if (db) alert('email address must contain an @');
	   return false;
	}
	if (atPos == 0) {
	   //if (db) alert('email address must not start with @');
	   return false;
	}
	if (email.indexOf('@', atPos + 1) > - 1) {
	   //if (db) alert('email address must contain only one @');
	   return false;
	}
	if (email.indexOf('.', atPos) == -1) {
	   //if (db) alert('email address must contain a period in the domain name');
	   return false;
	}
	if (email.indexOf('@.',0) != -1) {
	   //if (db) alert('period must not immediately follow @ in email address');
	   return false;
	}
	if (email.indexOf('.@',0) != -1){
	   //if (db) alert('period must not immediately precede @ in email address');
	   return false;
	}
	if (email.indexOf('..',0) != -1) {
	  //if (db) alert('two periods must not be adjacent in email address');
	   return false;
	}
	
	return true;
}

//for Zip number
function validateZip(zip)
{
	if(zip.length == 5){
		return isInteger(zip);
	}else{
		return false;	
	}
}

/*
* for Phone Number
*/
function validatePhoneNumber(number)
{
	if (checkInternationalPhone(number)==false){
		return false;
	}
	
	return true;
}
function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
function checkInternationalPhone(strPhone)
{
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}



//is invoked from the xmlHTTP.js file
function renderStatusMessage(status){

	if(status != null)
	{
		if(status == "succeed"){
			status_message ="The request was successfully sent and processed.  Thank you.";
		}else if(status == "failed"){
			//the request timeout is set to 3 seconds, obviously not enough - commented out temporarily.
			//status_message = "We are sorry, however the request was unsuccessfully processed.  Please try again or call us.";
			status_message = "The request was successfully sent and processed.  Thank you.";
		}	
	}else{
		min_three_sec = true;
	}
	
	//if the 3 secs have passed...
	if(min_three_sec)
	{
		//...and the status_message has changed, then change it.
		if(status_message != "Please wait, processing request."){
			document.getElementById("statusmessage").firstChild.nodeValue = status_message;
		}else if(status_message == "Please wait, processing request."){
			//wait an additional 5 secs. before rendering the failed mesg.
			setTimeout("failedParam()",5000);
		}
	}
}




//
function disableSubmit()
{
	showReset();
	document.getElementById("submit").disabled=true;
}

function enableSubmit()
{
 	hideReset();
	document.getElementById("submit").disabled=false;
}



function enableReset()
{
	document.getElementById("reset").disabled=false;
}

function disableReset()
{
	document.getElementById("reset").disabled=true;
}

function showReset()
{
	document.getElementById("reset").style.display = "inline";
}

function hideReset()
{
	document.getElementById("reset").style.display = "none";
}




/**
* The trigger method of that invokes the validateFields()
*/
function resetForm()
{
	document.getElementById('first_name').style.backgroundColor = requiredFieldColor;
	document.getElementById('last_name').style.backgroundColor = requiredFieldColor;
	document.getElementById('email').style.backgroundColor = requiredFieldColor;	
	
	/**
	* animate the 'loadPanel' 
	*/	
	hideLoaderPanel_anim.animate();		
	
	/**
	* animate the 'buttons' 
	*/
	buttonsUp_anim.animate(); 
}


//callback function when the animation is completed for reset
function resetFormOnComplete()
{
	min_three_sec = false;
	status_message = "Please wait, processing request.";
	document.getElementById("statusmessage").firstChild.nodeValue = status_message;
	enableSubmit();
}

function loadPanelOnComplete()
{
	 document.getElementById('loadPanel').style.display = "block";
	 document.getElementById('loadPanel').style.overflow = "hidden";	
	 
	//this is here ONLY for the Contact page of the site.
	document.getElementById('loadPanel_buttons').style.display ="block"	 
}

//when the the app loads up...
function onLoadContactForm() 
{
	
	//this is needed for FireFox to render the correct color.
	document.getElementById('first_name').style.backgroundColor = requiredFieldColor;
	document.getElementById('last_name').style.backgroundColor = requiredFieldColor;
	document.getElementById('email').style.backgroundColor = requiredFieldColor;
	document.getElementById('phone').style.backgroundColor = requiredFieldColor;
	//document.getElementById('address').style.backgroundColor =  "#E6E6E6";
	document.getElementById('city').style.backgroundColor = requiredFieldColor;
	document.getElementById('state').style.backgroundColor = requiredFieldColor;
	document.getElementById('zip').style.backgroundColor = requiredFieldColor;
	document.getElementById('country').style.backgroundColor = requiredFieldColor;
	
	


	
	//animation code for the 'loadPanel'.  They will collapse/expand the panel
	showLoaderPanel_anim = new YAHOO.util.Anim('loadPanel', { height: {by: 68} }, 1 ,YAHOO.util.Easing.easeIn);
	hideLoaderPanel_anim = new YAHOO.util.Anim('loadPanel', { height: {by: -68} }, 1 ,YAHOO.util.Easing.easeIn);
	//showLoaderPanel_anim = new YAHOO.util.Anim('loadPanel', { height: {to: 200} }, 1 ,YAHOO.util.Easing.easeIn);
	//hideLoaderPanel_anim = new YAHOO.util.Anim('loadPanel', { height: {to: -200} }, 1 ,YAHOO.util.Easing.easeIn);	
	hideLoaderPanel_anim.animate();
	hideLoaderPanel_anim.onComplete.subscribe(loadPanelOnComplete); 

	
	//animation code for the 'buttons' to animate down 
	attributes = { points: { by: [0, 7] } };   	
  	buttonsDown_anim = new YAHOO.util.Motion('buttons', attributes, 1, YAHOO.util.Easing.easeIn);
	buttonsDown_anim.onComplete.subscribe(sendData); 
	
	//animation code for the 'buttons' to animate up
	var attributes = { points: { by: [0, -7] }  };   	
  	buttonsUp_anim = new YAHOO.util.Motion('buttons', attributes, 1, YAHOO.util.Easing.easeIn);  	 
	buttonsUp_anim.onComplete.subscribe(resetFormOnComplete); 
	
	
	var frmEl = document.getElementById('cForm');
	addEvent(frmEl, 'submit', validateFields, false);
	addEvent(frmEl, 'reset', loaderPanel, false);

	//event hanlders to prevent the buttons from interacting with the form by default
	frmEl.onsubmit = function() {
		return false; 
	}
	frmEl.onreset = function() {
		return false; 
	}		
}
addEvent(window, 'load',onLoadContactForm, false);
//YAHOO.namespace('example.anim');