function CalcKeyCode(aChar) {
  var character = aChar.substring(0,1);
  var code = aChar.charCodeAt(0);
  return code;
}

function checkNumber(val) {
  var strPass = val.value;
  var strLength = strPass.length;
  var lchar = val.value.charAt((strLength) - 1);
  var cCode = CalcKeyCode(lchar);
 

  /* Check if the keyed in character is a number
     do you want alphabetic UPPERCASE only ?
     or lower case only just check their respective
     codes and replace the 48 and 57 */

  if (cCode < 48 || cCode > 57 ) {
    var myNumber = val.value.substring(0, (strLength) - 1);
    val.value = myNumber;
  }
  return false;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function IsEmpty(aTextField) {
	if ((aTextField.value.length==0) || (aTextField.value==null)) {
    	return true;
 		}
 	else { return false; }
}

function CheckIfTextIsEmpty(str) {
 	if (str == '') 
 	{
  		return true;
 	}
	return false;
}

function checkIfDropdownSelected(choice) {
  //alert('choice' + choice);
  if (choice == 0) {
     return false;
  }
  return true;
}

function validate_checkbox_list(element_input_name) {
	var x=document.getElementsByName(element_input_name);
	
	for(i=0;i<x.length;i++)
	{
		if (x[i].checked)
			return true;
	}
	return false;
}

function CheckIfPhoneIsLegit(str) {
 	if (str == '') {
  		//return "Please enter a phone number.<br>";
  		return false;
 	}
 	
 	var stripped = str.replace(/[\(\)\.\-\ ]/g, '');
	//strip out acceptable non-numeric characters
	if (isNaN(parseInt(stripped))) {
	   //return "The phone number contains illegal characters.<br>";
	   return false;
	}
 	
	return true;
}

function IsEmailLegit (emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) 
	{
		// alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	for (i=0; i<user.length; i++) 
	{
		if (user.charCodeAt(i)>127) 
		{
			// alert("Ths username contains invalid characters.");
			//return "Invalid e-mail address.<br>";
			return false;
		}
	}
	for (i=0; i<domain.length; i++) 
	{
		if (domain.charCodeAt(i)>127) 
		{
			// alert("Ths domain name contains invalid characters.");
			return false;
		}
	}

	if (user.match(userPat)==null) 
	{
		// alert("The username doesn't seem to be valid.");
		return false;
	}

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) 
	{
		for (var i=1;i<=4;i++) 
		{
			if (IPArray[i]>255) 
			{
				// alert("Destination IP address is invalid!");
				return false;
			}
		}
		return true;
	}

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) 
	{
		if (domArr[i].search(atomPat)==-1) 
		{
			// alert("The domain name does not seem to be valid.");
			return false;
		}
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) 
	{
		// alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}

	if (len<2) 
	{
		// alert("This address is missing a hostname!");
		return false;
	}

	return true;
}

function remove_non_numeric(o)
{
	o.value=o.value.replace(/([^0-9])/g,'');
}

function remove_bad_email_chars(o)
{
	if(o.value.length>0)
		o.value=o.value.replace(/[^a-z0123456789_.@-A-Z]+/g, '').toLowerCase();
}

function remove_non_alphanumeric(o)
{
	if(o.value.length>0)
	o.value=o.value.replace(/[^a-z0123456789_A-Z?-?]+/g, '').toLowerCase();
}

function validate_field(type, element_name, msg)
{
	message = '&nbsp;';
	display = '';
	ret_val=true;
	switch (type)
  	{
    	case 'text': 
    	{ 
    		if (CheckIfTextIsEmpty(eval('document.frm_details.' +element_name+ '.value'))==true)
			{display = '';message = msg;ret_val = false;}break;
    	}
    	
    	case 'phone':
    	{
    		if (CheckIfPhoneIsLegit(eval('document.frm_details.' +element_name+ '.value'))==false)
    		{display = '';message = msg;ret_val = false;}break;
    	}
    	
    	case 'email':
    	{
    		if (IsEmailLegit(eval('document.frm_details.' +element_name+ '.value'))==false)
    		{display = '';message = msg;ret_val = false;}break;
    	}
    	
    	case 'dropdown':
    	{
    		if (checkIfDropdownSelected(eval('document.frm_details.' +element_name+ '.value'))==false)
    		{display = '';message = msg;ret_val = false;}break;
    	}
    	
    	case 'checkbox':
    	{
    		if (eval('document.frm_details.' +element_name+ '.checked')==false)
    		{display = '';message = msg;ret_val = false;}break;
    	}
    	case 'checkboxlist':
    	{
    		if (validate_checkbox_list(element_name)==false)
			{;display = '';message = msg;ret_val = false;}break;
    	}
  	}
	
	document.getElementById(element_name + '_message').style.display = display;
	document.getElementById(element_name + '_message_row').style.display = display;
   	document.getElementById(element_name + '_message').innerHTML = message;
	
	return ret_val;
}

function validate_form() 
{
	ret_val=true;
	if(ret_val ==  true){
		ret_val &= validate_field('text', 'username', 'Please choose a username');
	}
	ret_val &= validate_field('dropdown', 'who_am_i', 'Please select what type of user you are');
	if (document.frm_details.who_am_i.value=='other')
		ret_val &= validate_field('text', 'other_text', 'Please specify what type of user you are');
	
	var usr_mess = document.getElementById("username_message").innerHTML
  	if(usr_mess.length > 6)
  	{
  		document.getElementById("username_message").style.display = '';
    		//document.getElementById("username_message").innerHTML = "Username is already taken";
    		ret_val=false;
  	}
  	
  	
	ret_val &= validate_field('text', 'password', 'Please choose a password');
	ret_val &= validate_field('text', 'first_name', 'Please fill in your first name');
	ret_val &= validate_field('text', 'last_name', 'Please fill in your last name');
	ret_val &= validate_field('email', 'email', 'Please fill in a valid email');
	ret_val &= validate_field('dropdown', 'country', 'Please select your country');
	if ((document.frm_details.country.value=='USA') && (document.frm_details.who_am_i.value!='') && (document.frm_details.who_am_i.value!='other') && (document.frm_details.who_am_i.value!='parent') && (document.frm_details.who_am_i.value!='home_educators')) {
		ret_val &= validate_field('text', 'school_zip', 'Please fill in your school\'s zip');
		
		if ( (getObject('school_name')!=null) && (getObject('school_name')!='undefined') ) 
		{
			ret_val &= validate_field('dropdown', 'school_name', 'Please select your school');
			if (document.frm_details.school_name.value=='other')
				ret_val &= validate_field('text', 'school_other', 'Please specify your school');
		}
		
	
	}
	if ((document.frm_details.who_am_i.value!='') && (document.frm_details.who_am_i.value!='other') && (document.frm_details.who_am_i.value!='parent') && (document.frm_details.who_am_i.value!='home_educator')) {
		ret_val &= validate_field('checkboxlist', 'tech_setup', 'Please indicate your technology setup');
	}
	//if ((document.frm_details.country.value=='USA') && ((document.frm_details.who_am_i.value=='other') || (document.frm_details.who_am_i.value=='parent') || (document.frm_details.who_am_i.value=='home_educator'))) {
	//	ret_val &= validate_field('dropdown', 'state', 'Please select your state');
	//}
	if ((document.frm_details.country.value=='USA') && ((document.frm_details.school_zip.value!='') || (document.frm_details.who_am_i.value=='other') || (document.frm_details.who_am_i.value=='parent') || (document.frm_details.who_am_i.value=='home_educator'))) {
		ret_val &= validate_field('dropdown', 'state', 'Please select your state');
	}
	ret_val &= validate_field('checkboxlist', 'grade_range', 'Please check your grade range');	
	ret_val &= validate_field('checkboxlist', 'bp_products', 'Please check which BrainPOP products you use');
	ret_val &= validate_field('dropdown', 'referred_by', 'Please select how you heard about BrainPOP Educators');
	
	var bp_account_mess = document.getElementById("bp_password_message").innerHTML
	if(bp_account_mess.length > 6)
	{
		document.getElementById("bp_password_message_row").style.display = '';
		//document.getElementById("username_message").innerHTML = "Username is already taken";
		ret_val=false;
  	}
	ret_val &= validate_field('checkbox', 'terms', 'Please confirm that you agree to the user agreement, privacy policy and terms of use');	
	ret_val &= validate_field('checkbox', 'age_terms', 'Please confirm that you are over 18 years old');	
	
	document.getElementById('form_head').focus();
	getObject('form_head').scrollIntoView(true);
  	return ret_val;
}

function compare_passwords()
{
	if (document.frm_details.confirm_password.value != "" && document.frm_details.password.value!="" ){
		if (document.frm_details.confirm_password.value != document.frm_details.password.value){
			document.getElementById("confirm_password_message").innerHTML='<span style="color: red;">?????? ?????? ?????? ?????? ???? ????<br></span>'
		}
		else{
			document.getElementById("confirm_password_message").innerHTML=''
		}
	}
}