/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Amit Wadhwa :: http://amitwadhwa.fcpages.com/javascript.com/formvalidator.html */

function checkThisForm(formname, submitbutton, errors) {
  if (errors == '') {
    eval('document.'+formname+'.'+submitbutton+'.disabled=true');
    eval('document.'+formname+'.submit()');
  } else {
    alert(errors);
  }
}

function checkText(formname, textboxname, displaytext) {
  var localerror = '';
  if(Trim(eval('document.'+formname+'.'+textboxname+'.value'))=='') {
    localerror =  '- '+displaytext+' is Required.\n';
  } else localerror = '';
  return localerror;
}

function checkNum(formname, textboxname, displaytext) {
  var localerror = '';
  if(isNaN(eval('document.'+formname+'.'+textboxname+'.value'))) {
    localerror =  '- '+displaytext+' Should Be A Number With No Spaces.\n';
  } else localerror = '';
  return localerror;
}

function checkSpaces(formname, textboxname, displaytext) {
  var valid = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'; // define valid characters
  var localerror = '';
  if(!isValid(Trim(eval('document.'+formname+'.'+textboxname+'.value')), valid)) {
    localerror =  '- '+displaytext+' Should Not Contain Spaces.\n';
  } else localerror = '';
  return localerror;
}

function checkSelect(formname, selectboxname, displaytext) {
  var localerror = '';
  if(eval('document.'+formname+'.'+selectboxname+'.selectedIndex')==0) {
    localerror =  '- '+displaytext+' is Required.\n';
  } else localerror = '';
  return localerror;
}

function getRadio(formname, radioname) {
  for (var i=0; i < eval('document.'+formname+'.'+radioname+'.length'); i++) {
    if (eval('document.'+formname+'.'+radioname+'[i].checked')) {
      var rad_val = eval('document.'+formname+'.'+radioname+'[i].value');
      return rad_val;
    }
  }
}

function checkRadio(formname, radioname, displaytext) {
  var localerror = '';
  var rad_val    = '';
  for (var i=0; i < eval('document.'+formname+'.'+radioname+'.length'); i++) { //check every radio button by that name
    if (eval('document.'+formname+'.'+radioname+'[i].checked'))  { //if it is checked
      rad_val += '-';
      }	else rad_val += '';
      }
    if (rad_val=='') {
      localerror =  '- '+displaytext+' is Required.\n';
    }
  return localerror;
}

function checkEmail(formname, textbox, displaytext) {
	var localerror = '';
	if(Trim(eval('document.'+formname+'.'+textbox+'.value')) == "") {
    localerror =  '- '+displaytext+' is Required.\n';
  	} else {
		if(!Validate_Email_Address(Trim(eval('document.'+formname+'.'+textbox+'.value')))) {
		localerror =  '- The email address you entered in is not spelled correctly.\n';
		} else localerror = '';
	}
	return localerror;
}

function autoComplete (field, select, property) {
/*onKeyUp="autoComplete(this,this.form.selectboxname,'value',false)" - add this to textbox where you are typing*/
  var found = false;
  for (var i = 0; i < select.options.length; i++) {
    if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
      found=true; break;
    }
  }
  if (found) {
    select.selectedIndex = i;
  } else {
    select.selectedIndex = -1;
  }
  if (field.createTextRange) {
    if (!found) {
      field.value=field.value.substring(0,field.value.length-1);
      return;
    }
    var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
    if (cursorKeys.indexOf(event.keyCode+";") == -1) {
      var r1 = field.createTextRange();
      var oldValue = r1.text;
      var newValue = found ? select.options[i][property] : oldValue;
      if (newValue != field.value) {
        field.value = newValue;
        var rNew = field.createTextRange();
        rNew.moveStart('character', oldValue.length) ;
        rNew.select();
      }
    }
  }
}

function Trim(s) {
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r')) {
    s = s.substring(1,s.length);
  }
  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r')) {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function isValid(string,allowed) {
//  var valid = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // define valid characters
    for (var i=0; i< string.length; i++) {
      if (allowed.indexOf(string.charAt(i)) == -1) return false;
    }
    return true;
}

/*
This is for email only
*/

/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Francis Cocharrua :: http://scripts.franciscocharrua.com/ */

function Validate_String(string, return_invalid_chars) {
  valid_chars = '1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  invalid_chars = '';
  if(string == null || string == '')
     return(true);

  //For every character on the string.   
  for(index = 0; index < string.length; index++) {
    char = string.substr(index, 1);                        
     
    //Is it a valid character?
    if(valid_chars.indexOf(char) == -1) {
      //If not, is it already on the list of invalid characters?
      if(invalid_chars.indexOf(char) == -1) {
        //If it's not, add it.
        if(invalid_chars == '')
          invalid_chars += char;
        else
          invalid_chars += ', ' + char;
      }
    }
  }
            
  //If the string does not contain invalid characters, the function will return true.
  //If it does, it will either return false or a list of the invalid characters used
  //in the string, depending on the value of the second parameter.
  if(return_invalid_chars == true && invalid_chars != '') {
    last_comma = invalid_chars.lastIndexOf(',');
    if(last_comma != -1)
      invalid_chars = invalid_chars.substr(0, $last_comma) + 
      ' and ' + invalid_chars.substr(last_comma + 1, invalid_chars.length);
    return(invalid_chars);
    }
  else
    return(invalid_chars == ''); 
}


function Validate_Email_Address(email_address) {
  //Assumes that valid email addresses consist of user_name@domain.tld
  at = email_address.indexOf('@');
  dot = email_address.indexOf('.',at);

  if(at == -1 || 
    dot == -1 || 
    dot <= at + 1 ||
    dot == 0 || 
    dot == email_address.length - 1)
    return(false);
     
  user_name = email_address.substr(0, at);
  domain_name = email_address.substr(at + 1, email_address.length);                  

  if(Validate_String(user_name) === false || 
    Validate_String(domain_name) === false)
    return(false);                     

  return(true);
}

/*
======================================
===== now a script for passwords =====
======================================
*/

function checkPassword(formname,password,password2) {
	var localerror = '';
	var pw1 = Trim(eval('document.'+formname+'.'+password+'.value'));
	var pw2 = Trim(eval('document.'+formname+'.'+password2+'.value'));
	// check for a value in both fields.
	if (pw1 == '' || pw2 == '') {
	localerror = '- a Password is Required.';
	}
	if (pw1 != pw2) {
	localerror = '- You did Not Enter the Same Password Twice.';
	}
	return localerror;
}

function checkNewPassword(formname,password,password2) {
	var localerror = '';
	var pw1 = Trim(eval('document.'+formname+'.'+password+'.value'));
	var pw2 = Trim(eval('document.'+formname+'.'+password2+'.value'));
	// check for a value in both fields.
	if (pw1 != '' || pw2 != '') {	
		if (pw1 != pw2) {
		localerror = '- You did Not Enter the Same Password Twice.';
		}
	}
	return localerror;
}

/*
======================================
=====    ncheck file uploads     =====
======================================
*/
function checkFile(formname, fileText, extArray, required, requiredtext,errortext) {
  allowSubmit = false;
  file = eval('document.'+formname+'.'+fileText+'.value');
  var localerror = '';
  
  if (required == false && file == "") {
	localerror = '';
  } else if (required == true && file == "") {
  	localerror =  '- '+requiredtext+' is Required.\n';
  } else if (file.indexOf("'") > 0) {
  	localerror =  '- The file you are trying to upload has a comma (\') in the name. Rename the file without a comma and try again.\n';
  } else {
    while (file.indexOf("\\") != -1)
      file = file.slice(file.indexOf("\\") + 1);
      ext = file.slice(file.indexOf(".")).toLowerCase();
      for (var i = 0; i < extArray.length; i++) {
        if (extArray[i] == ext) { allowSubmit = true; break; }
      }
	  
    if (allowSubmit) {
      localerror += '';
    } else {
      localerror = "Please only upload "+errortext+" files that end in types:  " 
      + (extArray.join("  ")) + "\nPlease select a new "
      + "file to upload and submit again.\n\n";
    }
  }
  
  return localerror;
}
