// ********************************************************************************* //
// Form Validation Scipt by DiJ8 Ltd. For more scripts visit www.dij8.com            //
//                                                                                   //
// Use of this script is free as long as this comment stays as it is and at the top. //
//                                                                                   //
// The behaviour of this script is by no means guaranteed to work as expected and    //
// DiJ8 Ltd takes no responsibility for its use.                                     //
// ********************************************************************************* //

// ********************************************************************************* //
//                                DIRECTIONS OF USE                                  //
// To use this script validated form field names require a particular format and     //
// validated fields need a title parameter.                                          //
//                                                                                   //
// The form tag must use an "onSubmit" parameter in the format                       //
// onSubmit="return validate(this);"                                                 //
//                                                                                   //
// All validated fields use the title parameter to show the user a friendly name in  //
// the error alert to show which field has failed.                                   //
//                                                                                   //
// Validated fields require the name to be in the format x#_fieldname                //
// where x is the field type, # is a number with 1 meaning it is compulsory, and     //
// the _ is required as a seperator. The fieldname can be any name you choose.       //
// e.g. t1_UserName, e1_UserEmail, d0_BirthDate, et c.                               //
//                                                                                   //
// Field types are as follows:                                                       //
// t = text      (used in text type inputs)                                          //
// e = email     (used in text type inputs)                                          //
// n = number    (used in text type inputs, includes phone number seperators)        //
// d = date      (used in text type inputs)                                          //
// p = password  (used in password type inputs)                                      //
// h = hidden    (used for DHTML edit boxes where hidden field is checked)           //
// s = select    (used for select tags)                                              //
// r = radio     (used for radio type inputs)                                        //
// f = file      (used in file type inputs)                                          //
// c = checkbox  (used in checkbox type inputs)                                      //
// x = number    (used in text type inputs, numeric only values)                     //
//                                                                                   //
// Text type inputs include inputs with the types text, password and hidden.         //
// Text validation can also be used in textarea tags.                                //
// Password checks passwords match. Second field has same name less prefix "p1_".    //
// Password also does text validation. Only first field needs title.                 //
// Select type inputs with options that do not count must have a value of nothing.   //
// e.g. <option value="">--- PLEASE SELECT AN OPTION---</option>                     //
// Radio type inputs must have the same name for all radio buttons within the group. //
// Inputs of type file also include a second compulsory option (2) for a hidden      //
// field listing an existing field value. The hidden field must have the same name   //
// as the file input less the three leading validation characters (f2_)              //
// ********************************************************************************* //

function validate(theform) {
  var sendok=true;
  var errmsg = "There are problems with the form.\nPlease fix the following fields.\n\n";
  var errone = "";
  for (v=0;v<theform.length;v++) {
    strVType = theform[v].id.substring(0,3)
    if (strVType.substring(2,3)=="_") {
      vType = strVType.substring(0,1).toLowerCase()
      cType = strVType.substring(1,2)
      switch(vType) {
        case "t" :
          errcode = textvalidator(theform[v],cType);
          break;
        case "e" :
          errcode = emailvalidator(theform[v],cType);
          break;
        case "n" :
          errcode = numbervalidator(theform[v],cType);
          break;
        case "d" :
          errcode = datevalidator(theform[v],cType);
          break;
        case "p" :
          errcode = passwordvalidator(theform,theform[v],cType);
          break;
        case "h" :
          if (theform[v].value.length<18&&cType==1) {errcode = "Required field";}
          else {errcode = textvalidator(theform[v],cType);}
          break;
        case "s" :
          errcode = selectvalidator(theform[v],cType);
          break;
        case "r" :
          errcode = radiovalidator(theform[v],cType);
          break;
        case "f" :
          errcode = filevalidator(theform[v],cType);
          break;
        case "c" :
          errcode = checkboxvalidator(theform[v],cType);
          break;
        case "x" :
          errcode = checknumeric(theform[v],cType);
          break;
      }
      if (errcode!=true) {sendok=false;errmsg=errmsg+theform[v].title+" - " + errcode + "\n";if(errone==""){errone=theform[v].name}}
    }
  }
  if (!sendok) {
    alert(errmsg);
    if (errone.substring(0,1).toLowerCase()=="r") {errone += "[0]"}
    else {var errType = eval("theform."+errone+".type").toLowerCase()}
    if (errone.substring(0,1).toLowerCase()!="h") {
      if (errType!="radio"&&errType!="select-one"&&errType!="select-multiple"&&errType!="checkbox") {eval("theform."+errone+".select()");}
      eval("theform."+errone+".focus()");
    }
  }
  return sendok
}
function textvalidator(field, compulsary) {
  var textok = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ0123456789~!@#$£%^&*™()-_+=[]{};:'‘’“”–…,.·<>?|/\\ \"\t\r\n\f";
  var allvalid = true;
  everythingok = true;
  if (field.value == "" && compulsary == 1) {
    return "Required field";
  }
  else if (field.value.length > 0) {
    var errorchr
    for (i = 0;  i < field.value.length;  i++) {
      ch = field.value.charAt(i);
      for (j = 0;  j < textok.length;  j++)
      if (ch == textok.charAt(j))
        break;
      if (j == textok.length) {
        errorchr = ch
        allvalid = false;
        break;
      }
    }
    if (!allvalid) {
      return "Character " + errorchr + " is not allowed";
    }
    else {return true}
  }
  else {return true;}
}
function emailvalidator(field, compulsary) {
  var allvalid = true;
  if (field.value == "" && compulsary == 1) {
    return "Email address required";
  }
  else if (field.value.length > 0) {
    var errorchr
    if (window.RegExp) {
      var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
      var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
      var reg1 = new RegExp(reg1str);
      var reg2 = new RegExp(reg2str);
      if (!reg1.test(field.value) && reg2.test(field.value)) {var allvalid = true;}
      else {errorchr = "Invalid format";var allvalid = false;}
    } else {
      var emailok = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ0123456789-@.'#£$()<>-_\t\r\n\f";
      if (!validlength(field.value, 5)) {allvalid = false;}
      if (field.value.indexOf ('@') < 1) {allvalid = false;}
      if (field.value.lastIndexOf ('.') < (field.value.indexOf ('@') + 2)) {allvalid = false;}
      if (field.value.lastIndexOf ('.') > (field.value.length - 4)) {allvalid = false;}
      for (i = 0;  i < field.value.length;  i++) {
        ch = field.value.charAt(i);
        for (j = 0;  j < emailok.length;  j++)
        if (ch == emailok.charAt(j))
          break;
        if (j == emailok.length) {
          errorchr = "Character " + ch + " is not allowed";
          allvalid = false;
          break;
        }
      }
    }
    if (!allvalid) {
      return errorchr;
    }
    else {return true}
  }
  else {return true;}
}
function numbervalidator(field, compulsary) {
  var numberok = "0123456789-/()+. ";
  var allvalid = true;
  everythingok = true;
  if (field.value == "" && compulsary == 1) {
    return "Number required";
  }
  else if (field.value.length > 0) {
    var errorchr
    for (i = 0;  i < field.value.length;  i++) {
      ch = field.value.charAt(i);
      for (j = 0;  j < numberok.length;  j++)
      if (ch == numberok.charAt(j))
        break;
      if (j == numberok.length) {
        errorchr = ch
        allvalid = false;
        break;
      }
    }
    if (!allvalid) {
      return "Character " + errorchr + " is not allowed";
    }
    else {return true}
  }
  else {return true}
}
function datevalidator(field,compulsary) {
  if (field.value == "" && compulsary == 1) {
    return "Date required";
  } else if (field.value != "") {
    return isDate(field.value)
  } else {
    return true
  }
}
function passwordvalidator(theform, field, compulsary) {
  if (field.value == "" && compulsary == 1) {
    return "Required field";
  }
  var p2 = field.name.substring(3)
  if (field.value!=eval("theform."+p2+".value")) {return "Passwords must match"}
  return textvalidator(field,compulsary)
}
function selectvalidator(field, compulsary) {
  if (field.multiple && compulsary == 1 && field.selectedIndex<0) {
    return "Selection required"
  } else if (compulsary == 1 && field[field.selectedIndex].value=="") {
    return "Selection required"
  } else {return true}
}
var radioname
function radiovalidator(field, compulsary) {
  if(field.name!=radioname) {
    formname = field.form
    radioname = field.name
    if (compulsary == 1) {
    	var webcomplete=false
    	for (j=0;j<eval("formname."+radioname+".length");j++) {
    		if (eval("formname."+radioname+"[j].checked")) {webcomplete=true}
    	}
    	if(!webcomplete) {return "Selection required"}
    	else {return true}
    }
    else {return true}
  }
  else {return true}
}
function filevalidator(field, compulsary) {
  if (compulsary == 1) {if (field.value == "") {return "File required";} else {return true}}
  else if (compulsary == 2) {
    var existingfile = eval("document."+field.form.name+"['"+field.name.substring(3)+"'].value")
    if (field.value == "" && existingfile == "") {return "File required";} else {return true}
  }
  else {return true}
}
function checkboxvalidator(field, compulsary) {
  if(!field.checked && compulsary == 1) {
    return "Must be checked"
  }
  else {return true}
}
function checknumeric(field, compulsary) {
  if((field.value == "" && compulsary == 1) || isNaN(field.value)) {
    return "Number required"
  }
  else {return true}
}
function isDate(datevalue,maxyear,minyear) {
  var thedate = datevalue.replace(/\\|-/g,"/")
	var div1=thedate.indexOf("/")
	var div2=thedate.indexOf("/",div1+1)
  if (div1==-1||div2==-1) {return "use only / \\ or - for dividing values"}
  var dateday = thedate.substring(0,div1)
  if (dateday.substring(0,1)==0) {dateday=dateday.substring(1)}
  dateday = parseInt(dateday)
  var datemonth = thedate.substring(div1+1,div2)
  if (datemonth.substring(0,1)==0) {datemonth=datemonth.substring(1)}
  datemonth = parseInt(datemonth)
  var dateyear = thedate.substring(div2+1)
  dateyear = (dateyear.length<3)?(dateyear.length==1)?parseInt(200+dateyear):(parseInt(dateyear)<35)?parseInt(20+dateyear):parseInt(19+dateyear):parseInt(dateyear)
  if (isNaN(dateday) || isNaN(datemonth) || isNaN(dateyear)) {return "invalid format"}
  var maxdays = daysInMonths(datemonth,dateyear)
  if (datemonth<1||datemonth>12) {return "month value is not valid"}
  if (dateday<1||dateday>maxdays) {return "day value is not valid for chosen month"}
  if (maxyear) {if (dateyear>maxyear) {return "year value can not be later than " + maxyear}}
  if (minyear) {if (dateyear<minyear) {return "year value can not be earlier than " + minyear}}
  if (dateyear==0) {return "year value is not valid"}
  return true
}
function daysInMonths(m,yr) {
  switch (m) {
    case 4 || 6 || 9 || 11 :
      return 30
      break
    case 2 :
      return daysInFebruary(yr)
      break
    default :
      return 31
  }
}
function daysInFebruary(year){
  return (((year%4==0)&&((!(year%100==0))||(year%400==0)))?29:28);
}
function maxlen(field,size) {
  if (field.value.length>size) {
    return "Maximum length exceeded by " + (field.value.length-size) + " characters."
  } else {
    return true
  }
}