//Coding standards:
//  all errors should be displayed by using showError().
//All 'private function' names start with 'chkFrm_'


//Defaults
var strDefaultError = "U heeft niet alle verplichte velden ingevuld."

//This variable will hold verion info, so make sure it is updates each time a change is made
//This version info will be shown when CTRL + ALT + SHIFT + V is pressed
var checkFrmVersion = "f1.4.3.9"
var arSupportedTypes = new Array()
arSupportedTypes[0] = "hh:mm"
arSupportedTypes[1] = "dd/mm/yyyy"
arSupportedTypes[2] = "mm/dd/yyyy"
arSupportedTypes[3] = "text"
arSupportedTypes[4] = "email"
arSupportedTypes[5] = "numeric"
arSupportedTypes[6] = "alphanumeric"
arSupportedTypes[7] = "dutchzip"
arSupportedTypes[8] = "floatingnumber"
arSupportedTypes[9] = "twodecimalnumber"
arSupportedTypes[10] = "phonenumber"
arSupportedTypes[11] = "radio"
arSupportedTypes[12] = "select"
arSupportedTypes[13] = "dd-mm-yyyy"
arSupportedTypes[14] = "yyyy-mm-dd hh:mm:ss"


function checkFrm(objFrm) {
  var strLastCheckedRadio = "" //Hold the name of the radiobutton which was last checked 
  var i,k
  
  //Loop through form collection
  for (i=0;i<objFrm.length;i++) {
    var objField = objFrm[i]
    var strValue = objFrm[i].value
    var bRequired;
	var bOptional;
	var objSelect;
    var re //will hold the regular expression to use
    
    //Get custom Attributes
    var strRequired = chkFrm_getCustomAttibute(objField,"formRequired").toLowerCase();
    var strType = chkFrm_getCustomAttibute(objField,"formType").toLowerCase();

    //set default values if no values are received
    strType = (strType.length==0) ? "text" : strType;
    bRequired = (strRequired=="true");
    bOptional = (strRequired=="optional");
    
    if ((bRequired) || (bOptional)) {
      //Perform check if this field is required OR if it is optional and filled.
      if (!(bOptional) || ((bOptional) && (strValue.length!=0)))
      {
        //Check the type of validation to perform     
        switch (strType) {
          case "yyyy-mm-dd hh:mm:ss" :
            re = /^([1-2][0-9][0-9][0-9])-([0-1][0-9])-([0-3][0-9]) ([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/;
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
			
            break;
          case "hh:mm" :
            //check if time is valid
            re = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/;
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "dd/mm/yyyy" :
            //check if date is valid conform DD/MM/YYYY
            //If D or M is supplied, a preceding 0 will be automatically added.
            //YYYY should have four digits
            //allowed separation chars: '/','-','.',' '(space)
            //All separation chars will be replaced by a '/'
            chkFrm_formatDate((objField));
            //read new value
            strValue = objField.value
            strValue = objField.value
            if (chkFrm_CheckDate(strValue,'dd/mm/yyyy')== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "dd-mm-yyyy" :
            //check if date is valid conform DD/MM/YYYY
            //If D or M is supplied, a preceding 0 will be automatically added.
            //YYYY should have four digits
            //allowed separation chars: '/','-','.',' '(space)
            //All separation chars will be replaced by a '/'
            chkFrm_formatDate((objField));
            //read new value
            strValue = objField.value
            strValue = objField.value
            if (chkFrm_CheckDate(strValue,'dd-mm-yyyy')== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "mm/dd/yyyy" :
            //check if date is valid conform MM/DD/YYYY
            //If D or M is supplied, a preceding 0 will be automatically added.
            //YYYY should have four digits
            //allowed separation chars: '/','-','.',' '(space)
            //All separation chars will be replaced by a '/'
            chkFrm_formatDate((objField));
            //read new value
            strValue = objField.value
            if (chkFrm_CheckDate(strValue,'mm/dd/yyyy')== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "text" :
            //check if the field is not empty
            if (strValue.length == 0 ){
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "email" :
            //check if the email address is valid
            re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "numeric" :
            //only numeric entries are allowed
            re = /^[0-9]+$/;
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "alphanumeric" :
            //only alphanumeric characters (a-z AND A-Z) are allowed, no special characters
            re = /^[a-zA-Z\s]+$/; 
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "dutchzip" :
            chkFrm_formatDutchZip(objField);
            //read new value
            strValue = objField.value
            re = /^[0-9]{4}\s{0,1}[a-zA-Z]{2}$/; 
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "zip" :
            chkFrm_formatDutchZip(objField);
            //read new value
            strValue = objField.value
            re = /^[0-9]{4}\s{0,1}[a-zA-Z]{0,2}$/; 
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "floatingnumber" :
            //number started with - or +
            //and one decimal sign . or ,
            re = /^[-+]?\d*[\.\,]?\d+$/; 
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "twodecimalnumber" :
            //one . or , as decimal seperator, other chars only 0-9
            //two decimals max
  
            re = /^\d+[\.\,]?\d{1,2}$/; 
            if (chkFrm_doRegularExpression(re,strValue)== false) {
              chkFrm_showError(objField);
              return false;
            }
            break;
          case "phonenumber" :
            //only NUMERIC KEYS, (, ) , * , +, -,# and spaces are allowed
            re = /^[\d\(\)\-\+\*\# ]+$/; 
            if (chkFrm_doRegularExpression(re,strValue)== false) 
			{
              chkFrm_showError(objField);
              return false;
            }
			if (strValue.length<10)
			{
              chkFrm_showError(objField);
              return false;
			}
            break;
          case "radio" :
            //Get radio collection, use getElementsByName or names with a | or & in them will cause an error
            objRadio = document.getElementsByName(objField.name)
            if (objField.name != strLastCheckedRadio) {
              //This radiobuttongroup is not checked yet
              strLastCheckedRadio = objField.name;
              if (!(chkFrm_isOneRadioButtonSelected(objRadio))) {
                //No radio button in the group is selected
                chkFrm_showError(objField);
                return false;
              }
            }
          case "select" :
            //Get select collection, use getElementsByName or names with a | or & in them will cause an error
			if (objField.selectedIndex==0) 
			{
				chkFrm_showError(objField);
				return false;
			}
            break;
        }
      }      
    }
  }
  return true;
}

function chkFrm_getCustomAttibute(objItem,strAttribName) {
  //return the attribute with the specified name if it exists, else return '';
  var strReturn = (objItem.getAttribute(strAttribName)) ? objItem.getAttribute(strAttribName) : '';
  return strReturn;
}

function chkFrm_doRegularExpression(re, strWhat) {
  return (re.test(strWhat) == true);
}

function chkFrm_formatDutchZip(objField) {
  //remove all spaces
  objField.value = objField.value.replace(/ /g,'')
  //upperCase value
  objField.value = objField.value.toUpperCase();
}

function chkFrm_formatDate(objField) {
  //replace all spaces, dots and stripes with a slash '/'
  objField.value = objField.value.replace(/[\. \-]/g,'/')
  var arValue = objField.value.split("/")
  var strTmpvalue = '';
  var i;
  if (arValue.length == 3) {
    //two slashes are found
    //Make sure the values have a preceding 0, except the last element
    for (i=0;i<arValue.length-1;i++){
      if (arValue[i].length < 2) {
        arValue[i] = '0' + arValue[i]
      }
    }
    //The last element should have 4 characters (==year)
    while (arValue[arValue.length-1].length < 4) {
      //Ad an x until the length is at least 4 chars
      arValue[arValue.length-1] = 'x' + arValue[arValue.length-1]
    }
    
    //save array data into a string
    for (i=0;i<arValue.length;i++){
      strTmpvalue += arValue[i] + '/'
    }
    //Remove last slash
    if (strTmpvalue.substr(strTmpvalue.length-1,1)=='/') {
      strTmpvalue = strTmpvalue.substr(0,strTmpvalue.length-1)
    }
    
    //Show altered value 
    objField.value = strTmpvalue;
  }
}


function chkFrm_showError(objField) {

  var strErrorMsg = chkFrm_getCustomAttibute(objField,"formErrormsg");
  strErrorMsg = (strErrorMsg.length==0) ? strDefaultError : strErrorMsg;
  //RF 24-02-2003: First give the alert, else focus() and select() might fail.
  alert (strErrorMsg);
  try {
    //try to set focus AND select
    objField.focus();
    objField.select();
  }
  catch (e) {
  }
}

function chkFrm_isOneRadioButtonSelected(objRadio) {
  //objRadio is the radio button collection, not one specific field!!
  var bOneIsChecked = false
  for (k=0;k<objRadio.length;k++){
    if (objRadio[k].checked) {
      bOneIsChecked = true;
      break;
    }
  }
  return (bOneIsChecked);
} 

function chkFrm_CheckDate(strDatum, strFormat){
  //Input: 
  //  strDatum: Date string to check, use / a delimiter
  //  strFormat: either 'dd/mm/yyyy' OR 'mm/dd/yyyy'
  var datDate, strNewDate = ""
  var strDate_mmddyyyy

  //Create  a string conform mm/dd/yyyy
  switch (strFormat.toLowerCase()) {
    case ('dd-mm-yyyy') :
      var arTmp = strDatum.split("-")
      if (arTmp.length == 3) {
        //two slashes are found
        strDate_mmddyyyy = arTmp[1] + '/' + arTmp[0] + '/' + arTmp[2]
      } else {
        strDate_mmddyyyy = ''
      }
      break;
    case ('dd/mm/yyyy') :
      var arTmp = strDatum.split("/")
      if (arTmp.length == 3) {
        //two slashes are found
        strDate_mmddyyyy = arTmp[1] + '/' + arTmp[0] + '/' + arTmp[2]
      } else {
        strDate_mmddyyyy = ''
      }
      break;
    case ('mm/dd/yyyy'):
      strDate_mmddyyyy = strDatum
      break;
  }

  //Perform datecheck on DD/MM/YYYY string
  datDate = new Date(strDate_mmddyyyy)
  
  //NOTE :getMonth is zero based
  if( ( datDate.getMonth() + 1 ) < 10 ){strNewDate += "0"}
  strNewDate += ( datDate.getMonth() + 1 ) + "/"
  if( datDate.getDate() < 10 ){strNewDate += "0"}
  strNewDate += datDate.getDate() + "/"
  strNewDate += datDate.getFullYear()

  if( ( strNewDate == strDate_mmddyyyy ) && ( strNewDate.length == 10 ) ){
    return true
  } else{
    return false
  }
}

//***Version info will be shown when CTRL + ALT + SHIFT + V is pressed
try {
  document.onkeydown = chkFrm_showVersion;
} catch(e) {
}

function chkFrm_showVersion() {
  //Show version info
  //CTRL & ALT & SHIFT & V
  try {
    //This will only work in IE
    if ((event.keyCode==86) &&  (event.altLeft==true) && (event.ctrlLeft==true) && (event.shiftLeft==true)) { 
      var strMsg = "<b>form form validator</b><br><br>version:&nbsp;" + checkFrmVersion +'<br><br><b>Supported types</b>:<br>'
      for (i = 0;i<arSupportedTypes.length;i++) {
        strMsg += arSupportedTypes[i] + '<br>'
      }
      var objChkFrmWin = window.open("","chkWindow","height=430,width=330,top=0,left=0,status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes")
      objChkFrmWin.document.open();
      objChkFrmWin.document.write(strMsg);
      objChkFrmWin.document.close();
      objChkFrmWin.focus();
    }
    
  } catch (e) {
  }
}
//***End Version info 

  

