// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
function isPhoneNumber(str){
  var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
  return re.test(str);
}
// returns true if the string is a valid email
function isEmail(str){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)){
		return true;
	}else{
		return false;
	}
}

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail ID")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

 		 return true					
	}


// returns true if the string is empty
function isEmpty(str){
  return (str == null) || (str.length == 0);
}

// validate the form
function validateForm(f){
	var errors = '';
	var i,e,t,n,v;
	var alertStr;
	for(i=0; i < f.elements.length; i++){
		e = f.elements[i];
		t = e.type;
		n = e.name;
		v = e.value;
		nametest = n.toLowerCase();
		if(t == 'text' || t == 'Text' || t == 'textarea' || t == 'Textarea'){
			v = validated(v);
			f.elements[i].value = v;
			if(nametest.indexOf("email") != -1){
				if(!isEmail(v)){
					errors += n+' is not a valid email.\n'; continue;
				}
			}
			if(nametest.indexOf("phone") != -1){
				if(!isPhoneNumber(v)){
					errors += n+' is not a valid US phone number.\n'; continue;
				}
			}
			if (e.required){
				if (isEmpty(v)){ 
					errors += n+' cannot be empty.\n'; continue;
				}
			}else{
				continue;
			}
		}
	}
	if(errors != '') {
		//alert(errors);
		return false;
	}
	return true;
}
function validated(string) {
    for (var i=0, output='', invalid="[]{}<>'\""; i<string.length; i++)
       if (invalid.indexOf(string.charAt(i)) != -1){
	   }else{
          output += string.charAt(i);
	   }
    return output;
} 
