var VALIDATE_REQUIRED	= "VALIDATE_REQUIRED";
var VALIDATE_EMAIL 		= "VALIDATE_EMAIL";
var VALIDATE_PHONE		= "VALIDATE_PHONE";
var VALIDATE_ZIP_CODE	= "VALIDATE_ZIP_CODE";
var VALIDATE_NUMBER		= "VALIDATE_NUMBER";
var VALIDATE_DATE		= "VALIDATE_DATE";

var EMAIL_MASK			= "name@website.com";
var DATE_MASK			= "yyyy-mm-dd";
var ZIP_CODE_MASK		= "99999";
var PHONE_MASK			= "(999) 999-9999";
/**
 * gTLD = Generic top-level domain
 * ccTLD= Country code top-level domain
 * Both list can be found at  in http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains
 */
var gTLD			= "aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel"
var ccTLD			= "ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw";

function doFormValidation(form){
	var elementToValidate;
	var validation;	
	for(field in fieldToValidate){
		elementToValidate = form.elements[field];
		//elementToValidate	= document.getElementById(field);
		if( field == 'CLCPin_array'){
			continue;
		}		
		for( i in  fieldToValidate[field] ){
			validation	= fieldToValidate[field][i];
			if ( validation == 'CLCPin_array'){
				continue;
			}
			switch(validation){
				case VALIDATE_REQUIRED:					
					if  (! validateNotEmpty(elementToValidate.value) ){
						inlineMsg(elementToValidate.id,'Field is required',2);
						return false;
					}
				break;
				case VALIDATE_EMAIL:
					if (validateNotEmpty(elementToValidate.value) && !validateEmail(elementToValidate.value) ){
						inlineMsg(elementToValidate.id,'Email is not correct.<br> Ex. robert@company.com',2);
						return false;
					}
				break;
				case VALIDATE_PHONE:
					if (validateNotEmpty(elementToValidate.value) && ! validateUSPhone(elementToValidate.value) ){
						inlineMsg(elementToValidate.id,'Phone is not correct. <br>Ex. (212) 736-5000 or (212)736-5000',2);
						return false;
					}
				break;
				case VALIDATE_ZIP_CODE:					
					if (validateNotEmpty(elementToValidate.value) && ! validateZipcode(elementToValidate.value) ){
						inlineMsg(elementToValidate.id,'Zipcode is not correct.<br>Ex. 94910 or K1A 0B1',2);
						return false;
					}
				break;
				case VALIDATE_DATE:					
					if (validateNotEmpty(elementToValidate.value) && ! validateDate(elementToValidate.value) ){
						inlineMsg(elementToValidate.id,'Date is not correct, It should be yyyy-mm-dd.<br>Ex. 2007-12-24',2);
						return false;
					}
				break;
				case VALIDATE_NUMBER:
					if  ( ! validateNotEmpty(elementToValidate.value) ){
						inlineMsg(elementToValidate.id,'As the field is numeric it is required',2);
						return false;
					}
					if ( ! validateNumeric(elementToValidate.value) ){
						inlineMsg(elementToValidate.id,'Number is required',2);
						return false;
					}
				break;				 
			}						
				
		}
				
	}
	return true;
}


// START OF MESSAGE SCRIPT //

var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

function showToolTip(string,autohide ) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
 // var targetheight = targetdiv.offsetHeight;
  //var targetwidth = targetdiv.offsetWidth;
  //var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  //var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  //msg.style.top = topposition + 'px';
  //msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}
// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "images/msg_arrow.gif"; 
}

//AUTHOR: Karen Gayda

//DATE: 03/24/2000
function validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
//var objRegExp  = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;
//var objRegExp  = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
//REGULAR expression at http://www.regular-expressions.info/email.html
//var objRegExp	= /"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|"+ gTLD +"|" + ccTLD+ ")\b";
  //check for valid email
  strValue = trimAll(strValue);
  if ( strValue == EMAIL_MASK){
  	return false;
  }  
  var objRegExp	= /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))$/i;
  return objRegExp.test(strValue);
}

function validateZipcode( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid zipcode pattern.
  
  Ex. 99999 or 99999-9999

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.


*************************************************/
  var objRegExp  	= /(^\d{5}$)|(^\d{5}-\d{4}$)/;
  var objRegExp_CA  = /^([a-ceghj-npr-tv-zA-CEGHJ-NPR-TV-Z]){1}[0-9]{1}[a-ceghj-npr-tv-zA-CEGHJ-NPR-TV-Z]{1}\s?[0-9]{1}[a-ceghj-npr-tv-zA-CEGHJ-NPR-TV-Z]{1}[0-9]{1}$/;
  strValue = trimAll(strValue);
  if ( strValue == ZIP_CODE_MASK){
  	return false;
  }
  //validates US postal code 99999
  if ( objRegExp.test(strValue) ){
  		return true;
  }
  //validates canadian postal code K1A 0B1
  if ( objRegExp_CA.test(strValue) ){
  		return true;
  }
  return false;
  
}

function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. (999) 999-9999 or (999)999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  strValue = trimAll(strValue);
  if ( strValue == PHONE_MASK){
  	return false;
  }
  var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;

  //check for valid us phone with or without space between
  //area code
  return objRegExp.test(strValue);
}

function  validateNumeric( strValue ) {
  strValue = trimAll(strValue);
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

  //check for numeric characters
  return objRegExp.test(strValue);
}


function  validateDate( strValue ) {
	strValue = trimAll(strValue);
	if ( strValue == DATE_MASK){
  		return false;
  	}
  	var objRegExp  =   /^\d{4}(\-)\d{1,2}\1\d{1,2}$/;
  	//check for valid date
  	if(objRegExp.test(strValue)){
	  	dateArray	= strValue.split("-");
	  	if( dateArray[1] > 12 ){
	  		return false;
	  	}
	  	if( dateArray[2] > 31 ){
	  		return false;
	  	}else{
	  		return true;
	  	}
	  }else{
	  	return false;
	  }  
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

function rightTrim( strValue ) {
/************************************************
DESCRIPTION: Trims trailing whitespace chars.

PARAMETERS:
   strValue - String to be trimmed.

RETURNS:
   Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;

      if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
  return strValue;
}

function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.

PARAMETERS:
   strValue - String to be trimmed

RETURNS:
   Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;

      if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}
