/*
	General syntax Check 4 Javascript
	Crossing Channels NL, 2004
*/

/*
functions
	<input> is input field
	
: input check functions
	: General
	function checkSyntax(input, regex, example, message)
	function checkEmpty(input, message)
	function checkNumber(input, message)
	function checkLength(input,lenMin, lenMax,message)
	function checkDate(input)
	function checkDateOtherFocus(input, otherFocus)
	function checkTime(input)

	: specific implementations	
	function checkPassword(input)
	function checkEmail(input)
	function checkCreditCard(input)
	function checkPhone(input)
	function checkPostcode(input)

: focus functions
	function setFocus(input)
	function focusFirstField()
	function focusFirstEmptyField()

: misc functions
	function trim(str)

*/

var failedinput = null;  
var nav4 = window.Event ? true : false;

function setFocus(input)
{ // zet (voorzichtig) de focus op het veld
  if (allSyntaxOk() || input==failedinput)
  {            
    if (input.select) input.select();
    input.focus();
  }
}        

function trim(str)
{ // verwijder overtollige spaties voor en achter
  return str.replace(/^[ ]+|[ ]+$/g,"");
}

function trimInput(input)
{
  input.value = trim(input.value);
  return true;
}

function checkSyntax(input, regex, example, message)
{ // controleer de syntax volgens de regexp (plus voorbeeld hoe het wel moet)
  // een "leeg" invoerveld is ook OK!
  if (!errorBusyElsewhere(input))
  {
    input.value = trim(input.value);
    if (input.value != "" && !regex.test(input.value))
    { 
      errMessage(message,example);                                    
      setFocus(input);
      return false;
    }
    else
    {
      clearError();
      return true;
    }
  }
  return false;
}              

function checkEmpty(input, message)
{ // is veld leeg (op spaties na?)
  if (!errorBusyElsewhere(input))
  {
     msg = "Dit veld dient ingevuld te worden!";
     if (message != null) { msg = message; }
     reEmpty=/^[ 	]*$/; // NB: spaties & tabs
     if (reEmpty.test(input.value))
     {  errMessage(msg);
        setFocus(input);
        return true;
     }   
     else
     {
       clearError();
       return false;
     }
  }
  return false;
}

function checkNumber(input, message)
{
 // geldig nummer? (verwijder spaties)
  input.value = trim(input.value);
  msg = "Dit veld dient een nummer te bevatten!";
  if (message != null) { msg = message; }
  return checkSyntax(input, /^[0-9]+$/, "12", msg);
}

function checkLength(input,lenMin, lenMax,message)
{
  if (input.value.length >= lenMin && input.value.length <= lenMax)
  { return true; }
  else
  { errMessage(message);
    setFocus(input);
    return false;
  }
}

function checkPassword(input)
{ // is dit een geldig wachtwoord?
  var reAlfa = /[a-z]/i;
  var reNum  = /[0-9]/;
  if (!reAlfa.test(input.value) || !reNum.test(input.value))
  { errMessage("Een wachtwoord moet cijfers en letters bevatten");
    setFocus(input);
    return false;
  }

  return (checkLength(input,3,12,"Lengte van het wachtwoord moet minimaal 3 lang zijn en maximaal 12!"));
}


function checkEmail(input)
{ // is dit een geldig e-mail adres?
  return checkSyntax(input,/^([a-z0-9_-]+\.)*[a-z0-9_-]+@([a-z0-9_-]+\.)+([a-z]{2,})$/i, "mijn.adres@provider.nl", "Het email adres is niet correct ingevuld!");
}
  
function checkCreditCard(input)
{ // geldig credit card nummer? (verwijder spaties en punten)
  input.value = input.value.replace(/[ .]/g,"");
  return checkSyntax(input, /^[0-9]{16}$/, "1234567890123456","Het creditcardnummer is niet correct ingevuld!");
}

function checkPhone(input)
{ // geldig telefoonnummer?
  return checkSyntax(input, /^[0-9() +-]+$/, "(030) - 1234567","Het telefoonnummer is niet correct ingevuld!");
}

function checkPostcode(input)
{ // geldige postcode?
  return checkSyntax(input, /^[0-9]{4}[ ]*[a-z]{2}$/i, "3605 AB","De postcode is niet correct ingevuld!");
}

function year2K(input, border, message)
{
  // if yy>border: add 1900 (85 -> 1985); else add 2000 ( 01 -> 2001 )
  if (!errorBusyElsewhere(input))
  {
    if (isNaN(parseInt(input.value, 10)) || parseInt(input.value,10) != input.value)
    {
      msg = "Dit is geen goed jaartal!";
      if (message != null) { msg = message; }
      errMessage(msg);
      setErrorFocus(input);
      return false;
    }
    else
    {
      if(input.value<100)
      {
        if (input.value>border) { input.value = parseInt(input.value,10) + 1900 }
        else { input.value = parseInt(input.value,10) + 2000 }
      }        
      clearError();
      return true;
    }
  }  
  return false;
}

function checkDate(input)
{
  if (checkSyntax(input, /^([0-9]{1,2})[\/-]([0-9]{1,2})[\/-]([0-9]{4})$/, "21/09/2000"))
  {
    if (input.value != "")
    {
       var dt= new Date();
       var year  = RegExp.$3; 
       var month = RegExp.$2; 
       var day   = RegExp.$1; 
       dt.setFullYear(year, month-1, day);
       if (dt.getFullYear() != year || dt.getMonth()+1 != month || dt.getDate()!=day)
       { 
         errMessage("Dit is geen correcte datum");
         setErrorFocus(input);
         return false; 
       }
       input.value = fillNumber(parseInt(day,10), 2) + "-" + fillNumber(parseInt(month,10), 2) + "-" + year;
    }   
    return true;
  }
  return false;
}

function checkDateOtherFocus(input, otherFocus)
{
  if (checkSyntax(input, /^([0-9]{1,2})[\/-]([0-9]{1,2})[\/-]([0-9]{4})$/, "21/09/2000"))
  {
    if (input.value != "")
    {
       var dt= new Date();
       var year  = RegExp.$3; 
       var month = RegExp.$2; 
       var day   = RegExp.$1; 
       dt.setFullYear(year, month-1, day);
       if (dt.getFullYear() != year || dt.getMonth()+1 != month || dt.getDate()!=day)
       { 
         errMessage("Dit is geen correcte datum");
         setErrorFocus(otherFocus);
         return false; 
       }
       input.value = fillNumber(parseInt(day,10), 2) + "-" + fillNumber(parseInt(month,10), 2) + "-" + year;
    }   
    return true;
  }
  return false;
}

function checkDay(input,message)
{
  msg = "De dag is niet correct ingevuld!";
  if (message != null) { msg = message; }
  if (checkSyntax(input, /^[0-9]{1,2}$/, "9", message))
  {
    if (input.value != "")
    {
       day = parseInt(input.value,10);
       if ((day < 1) || (day > 31)) 
       { 
         errMessage(msg);
         setErrorFocus(input);
         return false; 
       }
       input.value = fillNumber(input.value,2);  
       return true;
    } 
  }
  return false;
}

function checkMonth(input, message)
{
  msg = "De maand is niet correct ingevuld!";
  if (message != null) { msg = message; }
  if (checkSyntax(input, /^[0-9]{1,2}$/, "9", message))
  {
    if (input.value != "")
    {  month = parseInt(input.value,10);
       if ((month < 1) || (month > 12)) 
       { 
         errMessage(msg);
         setErrorFocus(input);
         return false; 
       }
       input.value = fillNumber(input.value,2);
       return true;
    }  
  }
  return false;
}

function checkTime(input)
{
  return checkSyntax(input, /^[0-2][0-9]:[0-5][0-9]$/, "09:00");
}   

function fillNumber(iNum, iSize)
{
  var sNum = iNum + "";
  while (sNum.length < iSize) { sNum = "0" + sNum; }
  return sNum
}

function encodeForm(frm)
{
  for (var i=0; i<frm.length; i++)
  {
    var typ = frm.elements[i].type;
    if (typ=="text" || typ=="textarea") // ignore password inputs!
    {
      var input = frm.elements[i]
      input.value = input.value.replace(/\&/g,"~");
    }
  }
}

function decodeAllForms()
{
  var frm;
  var typ;
  var inp;
  var i,j;
  for (i=0; i<document.forms.length; i++)
  { var frm = document.forms[i];
    for (j=0; j<frm.length; j++)
    { typ = frm.elements[j].type;
      if (typ=="text" || typ=="textarea") // ignore password inputs!
      { inp = frm.elements[j];
        inp.value = inp.value.replace(/\~/g,"&");
      }
    }
  }
}

function focusFirstField()
{ // set focus on first input of first form (if any)
  // to be called after the page has loaded, for example in the "onLoad" handler
  var input;
  for (var i=0; i<document.forms.length; i++)
  {
    for (var j=0; j<document.forms[i].length; j++)
    {
      input=document.forms[i].elements[j];
      if (input.type=="text" || input.type=="password" || input.type=="textarea")
      {
        if (input.select) input.select();
	input.focus();
	return true;
      }
    }
  }
  // no (usable) field found
  return true;
}

function focusFirstEmptyField()
{ // set focus on first EMPTY input of first form (if any)
  // to be called after the page has loaded, for example in the "onLoad" handler
  var input;
  for (var i=0; i<document.forms.length; i++)
  {
    for (var j=0; j<document.forms[i].length; j++)
    {
      input=document.forms[i].elements[j];
      if (input.type=="text" || input.type=="password" || input.type=="textarea")
      {
	if (input.value.length == 0)
	{
          if (input.select) input.select();
	  input.focus();
	  return true;
	}
      }
    }
  }
  // no (usable) field found
  return true;
}

function getNextInput(thisinput)
{                      
  var foundthis = false;
  for (var i=0; i<thisinput.form.length; i++)
  {
    if (thisinput.form.elements[i] == thisinput)
    {                   
      foundthis = true;
      continue;
    }
    if (foundthis)
    {                                     
      var typ = thisinput.form.elements[i].type;
      if (typ == "text" || typ == "password")    
      {
        return thisinput.form.elements[i];
      }
    }
  }  
  return null;
}


function nextOnEnter(e)
{
  var key;
  var thisinput;
  if (nav4)
  { // Navigator 4.0x
    key = e.which;
    thisinput=e.target;
  }
  else
  { // Internet Explorer 4.0x
    if (e.type == "keypress")
    { // the user entered a character
      key = e.keyCode;
    }
    else
    {
      key = e.button;
    }
    thisinput=e.srcElement;    
  }

  if (e.type == "keypress" && key==13)
  {
    var nextinput = getNextInput(thisinput);
    if (nextinput!=null)
    {
      if ((thisinput.onchange && thisinput.onchange()) ||
          (thisinput.onblur   && thisinput.onblur()))
      {
	if (nextinput.select) nextinput.select();
	nextinput.focus();
      }
      return false;     //otherwise ie will submit the form on enter
    }
    else
    {
      //removes enter char
      if (isNaN(thisinput.value.charCodeAt(thisinput.value.length-1)))
      {  thisinput.value = thisinput.value.subst(0,thisinput.value.length-2); }

      // if no onSubmit handler: submit now
      // else check handler first
      // Note: "onsubmit" should perform check and return true/false, not submit
      if(thisinput.form.onsubmit == null || thisinput.form.onsubmit())
      {
        thisinput.form.submit();
      }
    }
    return false;
  }
  return true;
}

function errorBusyElsewhere(input)
{ // is al een andere input fout?
  return ((failedinput!=null) && (failedinput!=input) && (failedinput.form==input.form))
}
                 
function allSyntaxOk()
{ // is alle (gecheckte) syntax ok?
  return failedinput==null;
}      

function clearError()
{ // verwijder error markering
  failedinput = null;
}

function setErrorFocus(input)
{ // zet error markering
  failedinput = input;
  setFocus(input);
}

function errMessage(message,example)
{
   var msg = "Dit veld is niet correct ingevuld!";
   if (message != null) { msg = message; }
   if (example != null) { msg = msg + "\nVoorbeeld: " + example; }                            
   alert(msg);
}

function checkPINCard(input)
{ // is dit een correct PIN pas nummer?
  input.value=input.value.toUpperCase();
  return checkSyntax(input,/^[0-9]{3}[A-Z][0-9]{3}$/, "012J345","Het nummer van de giropas is niet correct ingevuld!");
}

function checkGiroAccount(input)
{ // geldig gironummer? (verwijder spaties)
  input.value = trim(input.value);
  return checkSyntax(input, /^[0-9]+$/, "1234567","Het gironummer is niet correct ingevuld!");
}

function checkIPpart(part)
{ // check deel van IP adres (tussen de puntjes): moet tussen 0 en 255 zijn
  var n = parseInt(part,10);
  return (n>=0 && n<=255);
}

function checkIPnumber(input)
{ // is dit een correct IP-nummer?
  var ok = checkSyntax(input, /^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/, "194.151.1.101","Het ip-nummer is niet correct ingevuld!");
  if (!ok) return false;
  if (input.value=="") return true;

  // ok is true
  ok = checkIPpart(RegExp.$1) && checkIPpart(RegExp.$2) && 
       checkIPpart(RegExp.$3) && checkIPpart(RegExp.$4);
  if (!ok)
  {
    errMessage("In een IP adres staan alleen waarden tussen 0 en 255","194.151.1.101");
    setErrorFocus(input);
    return false;
  }
  else
    return true;
}