// arrRequiredIds only holds the text fields so that they can be validated onblur. Other input types will be validated on submit
var arrRequiredIds = new Array();// associative array that holds element ids (just for consistancy) as the key
//arrRequiredIds['Element ID'] = new Array(valid,"Error Message", "Type of validation" ,min chars(exclusive), max chars(exclusive), defaultValidity);
arrRequiredIds['name'] = new Array(false,'The first name specified is not valid.','noVal', 2, 51, false);
arrRequiredIds['street'] = new Array(false,'The street name specified is not valid.','noVal', 0, 76, false);
arrRequiredIds['company'] = new Array(false,'The company name specified is not valid.','noVal', 0, 255, false);
arrRequiredIds['city'] = new Array(false,'The city specified is not valid.','noVal', 0, 255, false);
arrRequiredIds['state'] = new Array(false,'The first state specified is not valid.','state', 1, 3, false);
arrRequiredIds['zip'] = new Array(false,'The zip code specified is not valid.','zip', 4, 6, false);
arrRequiredIds['email'] = new Array(false,'The email specified is not valid.','email', 0, 51, false);
arrRequiredIds['phone'] = new Array(false,'The phone specified is not valid.','phone', 9, 15, false);
arrRequiredIds['ip'] = new Array(true,'The IP specified is not valid.','ip', 5, 16, true);
arrRequiredIds['dateMessage'] = new Array(false,'The date and message specified is not valid.','noVal', 0, 1000, false);


function onLoad() // Tie event handlers with form elements
{
   document.getElementById('name').onblur = onTextFieldBlur;
   document.getElementById('street').onblur = onTextFieldBlur;
   document.getElementById('company').onblur = onTextFieldBlur;
   document.getElementById('city').onblur = onTextFieldBlur;
   document.getElementById('state').onblur = onTextFieldBlur;
   document.getElementById('zip').onblur = onTextFieldBlur;
   document.getElementById('email').onblur = onTextFieldBlur;
   document.getElementById('phone').onblur = onTextFieldBlur;
   document.getElementById('ip').onblur = onTextFieldBlur;
   document.getElementById('dateMessage').onblur = onTextFieldBlur;
   
   document.getElementById('reset').onclick = onResetClick;
   
}


function onTextFieldBlur(e)
{
   var event = e || window.event;
   var target = event.target || event.srcElement;
   
   var strErrMsg = '';
   var boolIsValid = false;
   var strValue = target.value;
   strValue = trim(strValue);
   if (strValue.length < 1)
   {
      arrRequiredIds[target.id][0] = arrRequiredIds[target.id][5]; // Set controls validity to default validity
	  if (arrRequiredIds[target.id][0] == true)
	  {
	  target.className = '';
      }
	  return;
   }
   
   if (target.id != 'email')
   {
      strValue = strValue.replace(strValue.substr(0, 1), strValue.substr(0, 1).toUpperCase());
   }
   
   if (target.id == 'state')
   {
	   strValue = strValue.toUpperCase();
   }
   
   
   
   var tempStrValue = '';
   if (strValue.split(' ').length > 1 && target.id != 'dateMessage')
   {
	   for (var i = 0; i < strValue.split(' ').length; i++)
	   {
		   if (strValue.split(' ')[i] != '')
		   {
			   if(i != strValue.split(' ').length - 1)
			   {
				   
				   tempStrValue += strValue.split(' ')[i].replace(strValue.split(' ')[i].substr(0, 1), strValue.split(' ')[i].substr(0, 1).toUpperCase()) + ' ';
			   }
			   else
			   {
				   tempStrValue += strValue.split(' ')[i].replace(strValue.split(' ')[i].substr(0, 1), strValue.split(' ')[i].substr(0, 1).toUpperCase());
			   }
		   }
	   }
   strValue = tempStrValue;
   }
   
   if (strValue.length > arrRequiredIds[target.id][3] && strValue.length < arrRequiredIds[target.id][4])
   {
      boolIsValid = isValid(arrRequiredIds[target.id][2] , strValue);
      if (boolIsValid) 
      {
         target.className = '';
         target.value = strValue;
         arrRequiredIds[target.id][0] = true;   
      }
      else
      {
         target.className = 'blue_border';
		 strErrMsg = arrRequiredIds[target.id][1];
         target.value = strValue;
         arrRequiredIds[target.id][0] = false;
      }
   
   } 
   else
   {
      target.className = 'blue_border';
	  strErrMsg = target.id.replace(target.id.substr(0, 1), target.id.substr(0, 1).toUpperCase()) + ' must be more than '+ arrRequiredIds[target.id][3] +' characters and less than '+ arrRequiredIds[target.id][4] +' characters.';
      arrRequiredIds[target.id][0] = false;
   }
   
   if (strErrMsg.length > 0 && target.value.length > 0)
   {
      document.getElementById('form_error_msg').innerHTML = strErrMsg;
	  timer.stop();
	  timer.start();
   }
   
}

function onResetClick()
{
   document.getElementById('form_error_msg').innerHTML = '';
   for (elementIndex in document.getElementsByTagName('input'))
   {  
      var element = document.getElementsByTagName('input')[elementIndex];
      if (element) // IE returns a list that starts with an undefined 0 index.
	   {
          if (element.type == 'text') // All text elements' value should be set to an empty string
         {
             element.value = '';
			 arrRequiredIds[element.id][0] = arrRequiredIds[element.id][5];
           }
         element.className = ''; // All input elements class set to empty string TODO: parse for red_border
      }
   }
   document.getElementById('dateMessage').value = '';
   document.getElementById('dateMessage').className = '';

}

function onSubmitClick()
{
   var formIsValid = true;
   for (requiredIndex in arrRequiredIds) 
   {
      if (arrRequiredIds[requiredIndex][0] == false) {
         formIsValid = false;
            
         // Just in case the user never clicked in that particular text field set the required fields style
         document.getElementById(requiredIndex).className = 'blue_border';
      }
   }
   if (formIsValid) 
   {   
      // Give the go ahead to submit the form
     return true;
   } 
   else
   {

	  document.getElementById('form_error_msg').innerHTML = 'The fields marked in blue are required.';
	  timer.stop();
	  timer.start();
	  return false;
   }
}

var display_timer = function(delay, callback){
    this.isRunning = false;
    this.hndl = null;
    this.delay = 0;
    this.callback = null;

    this.start = function(){
        if(!this.isRunning){
            this.hndl = setTimeout(this.callBackFunc.bind(this), this.delay);
            this.isRunning = true;
        }
    };

    this.stop = function(){
        if(this.isRunning){
            clearTimeout(this.hndl);
            this.hndl = null;
            this.isRunning = false;
        }
    };

    this.setDelay = function(d){
        this.delay = d * 1000;
    };

    this.setCallback = function(c){
        this.callback = c;
    };

    this.callBackFunc = function(){
        if(this.isRunning){
            this.isRunning = false;
            this.hndl = null;
            eval(this.callback);
        }
    };

    this.setCallback(callback);
    this.setDelay(delay);
};

var timer = new display_timer(4, 'document.getElementById("form_error_msg").innerHTML = ""');


window.onunload = onResetClick; //TODO: Revalidate the text fields. For now just call reset function
window.onload = onLoad;
