/*
  validate.js for utf-8 script v1.62
  include file for form validation purposes at client side
  Authors: Xtian, TheGismo
  Copyright (c)2001-2009 by OmanBros.com. All rights reserved.
  Last update: 28.10.2009

  Contents:
	function isEmpty
	function isWhitespace
	function stripCharsNotInBag
	function isNumeric
	function isDecimal
	function isEmail
	function isCreditCard
	function isVisaCard
	function isMasterCard
	function isDinersClub
	function isAmericanExpress
	function isCreditCardMatch
	function isDateTime
	function validateForm
*/

var lo_letters="abcdefghijklmnopqrstuvwxyz"
var up_letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var letters=up_letters+lo_letters
var whitespaces=" \t\n\r"
var digits="0123456789"
var decimals=digits+",-"	//German representation like "-10,67"
var en_decimals=digits+".-"	//English representation like "-10.67"
var chk_optional=true		//alias, used if empty check is not obligatory
/*
  Following constants are used for different languages.
  More languages may follow!
*/
var lang_german=0,		//used for German representations
    lang_english=1,		//used for English representations
    lang_german_you=2,		//used for German representations (2nd person singular)
    lang_hungarian=3,		//used for Hungarian representations
    lang_italian=4		//used for Italian representations
/*
  Following constants are used for CheckInput types.
*/
var chk_text=0,			//text, non whitespace, non empty
    chk_num=1,			//numeric, non whitespace, non empty
    chk_num_opt=2,		//numeric, optional
    chk_dec=3,			//decimal, non whitespace, non empty
    chk_dec_opt=4,		//decimal, optional
    chk_email=5,		//email, non whitespace, non empty
    chk_email_opt=6,		//email, optional
    chk_box=7,			//radio[x] or checkbox, checked
    chk_datetime=8,		//year,month,day,hour,minute,second
    chk_datetime_opt=9,		//year,month,day,hour,minute,second, optional
    chk_sel=10,			//selected (index>0)
//credit cards
    chk_credit_all=100,		//credit card, all known types
    chk_credit_all_opt=101,	//credit card, all known types, optional
    chk_credit_visa=102,	//credit card, Visa
    chk_credit_visa_opt=103,	//credit card, Visa, optional
    chk_credit_master=104,	//credit card, MasterCard
    chk_credit_master_opt=105,	//credit card, MasterCard, optional
    chk_credit_diners=106,	//credit card, Diner's Club
    chk_credit_diners_opt=107	//credit card, Diner's Club, optional
    chk_credit_amex=108,	//credit card, American Express
    chk_credit_amex_opt=109	//credit card, American Express, optional

/* -------------------------------------------------------------------
  function isEmpty

  Checks whether string s is empty.
*/
function isEmpty(s) {
  return ((s==null)||(s.length==0))
}

/* -------------------------------------------------------------------
  function isWhitespace

  Returns true if string s is empty or contains only whitespace chars.
*/
function isWhitespace(s) {
var i
  // Is s empty?
  if (isEmpty(s)) return true
  // Search through string's characters one by one
  // until we find a non-whitespace character
  // if we do, return false; if we don't, return true
  for (i=0;i<s.length;i++) if (whitespaces.indexOf(s.charAt(i))==-1) return false
  return true
}

/* -------------------------------------------------------------------
  function stripCharsNotInBag

  Removes all characters from string s NOT contained in string bag.
*/
function stripCharsNotInBag(s,bag) {
var i,ch,txt=""
  // Search through string's characters one by one
  // If character is in bag, append to txt
  for (i=0;i<s.length;i++) if (bag.indexOf(s.charAt(i))!=-1) txt+=s.charAt(i)
  return txt
}

/* -------------------------------------------------------------------
  function isNumeric

  Returns true if all chars in string s comply to the chars in digits.
  If opt is set to optional (=true), then s is not checked for whitespaces.
*/
function isNumeric(s,opt) {
var i
  // is s whitespace or empty?
  if (!opt&&isWhitespace(s)) return false
  // Now checking if all chars are contained in digits
  for (i=0;i<s.length;i++) if (digits.indexOf(s.charAt(i))==-1) return false
  return true
}

/* -------------------------------------------------------------------
  function isDecimal

  Returns true if all chars in string s comply to the chars in decimals.
  If opt is set to optional (=true), then s is not checked for whitespaces.
  If lang is omitted or set to lang_german (=0) then the German representation
  of decimal numbers is used, otherwise, set to lang_english (=1), the English
  representation is used.
*/
function isDecimal(s,opt,lang) {
var i,ch,first=false,sep=false
  // is s whitespace or empty?
  if (!opt&&isWhitespace(s)) return false
  // Now checking if all chars are contained in decimals
  for (i=0;i<s.length;i++) {
    ch=s.charAt(i)
    if (!lang||(lang==lang_german)) {
      if (decimals.indexOf(ch)==-1) return false
    } else {
      if (en_decimals.indexOf(ch)==-1) return false
    }
    if (first&&(ch=="-")) return false
    if (sep&&((ch==",")||(ch=="."))) return false
    if (!first) first=true
    if (!sep) sep=((ch==",")||(ch=="."))
  }
  return true
}

/* -------------------------------------------------------------------
  function isEmail

  Checks if s is properly formatted as email
  It must be at least "x@yy.zz".
  If opt is set to optional (=true), then s is not checked for whitespaces.
*/
function isEmail(s,opt) {
var s1,pos,pos2
  // is s whitespace or empty?
  if (isWhitespace(s)) if (!opt) return false; else return true
  // look for "@"; email name must be at least 1 char long
  pos=s.indexOf("@");
  if (pos<1) return false
  //check if there is only one "@"
  s1=stripCharsNotInBag(s,"@")
  if (s1.length!=1) return false
  // look for "."; domain name must be at least 2 chars long
  pos2=s.lastIndexOf(".");
  if ((pos2==-1)||(pos2<pos+3)) return false
  // there must be at least 2 characters after the "."
  if (s.length<=pos2+2) return false
  return true
}

/* -------------------------------------------------------------------
  function isCreditCard

  Gets a string s representing a credit card number and
  returns true, if the credit card number passes the Luhn Mod-10 test,
  otherwise false is returned.
*/
function isCreditCard(s) {
var sum=0,mul=1,len=s.length
  // Encoding only works on cards with less than 19 digits
  if (len>19) return false
  for (i=len-1;i>=0;i--) {
    var result=parseInt(s.charAt(i),10)*mul
    if (result>=10) sum+=(result%10)+1; else sum+=result
    if (mul==1) mul++; else mul--
  }
  if ((sum%10)==0) return true
  return false
}

/* -------------------------------------------------------------------
  function isVisaCard

  Gets a string s representing a credit card number and
  returns true, if the credit card number is a valid VISA number,
  otherwise false is returned.
  Sample number: 4111 1111 1111 1111 (16 digits)
*/
function isVisaCard(s) {
  if (((s.length==16)||(s.length==13))&&(s.charAt(0)*1==4)) return isCreditCard(s)
  return false
}

/* -------------------------------------------------------------------
  function isMasterCard

  Gets a string s representing a credit card number and
  returns true, if the credit card number is a valid MasterCard number,
  otherwise false is returned.
  Sample number: 5500 0000 0000 0004 (16 digits)
*/
function isMasterCard(s) {
  var dig1=s.charAt(0),dig2=s.charAt(1)
  if ((s.length==16)&&(dig1*1==5)&&(dig2*1>=1)&&(dig2*1<=5)) return isCreditCard(s)
  return false
}

/* -------------------------------------------------------------------
  function isDinersClub

  Gets a string s representing a credit card number and
  returns true, if the credit card number is a valid Diner's Club number,
  otherwise false is returned.
  Sample number: 30000000000004 (14 digits)
*/
function isDinersClub(s) {
  var dig1=s.charAt(0),dig2=s.charAt(1)
  if ((s.length==14)&&(dig1*1==3)&&((dig2*1==0)||(dig2*1==6)||(dig2*1==8))) return isCreditCard(s)
  return false
}

/* -------------------------------------------------------------------
  function isAmericanExpress

  Gets a string s representing a credit card number and
  returns true, if the credit card number is a valid American Express number,
  otherwise false is returned.
  Sample number: 370000000000002 (15 digits)
*/
function isAmericanExpress(s) {
  var dig1=s.charAt(0),dig2=s.charAt(1)
  if ((s.length==15)&&(dig1*1==3)&&((dig2*1==4)||(dig2*1==7))) return isCreditCard(s)
  return false
}

/* -------------------------------------------------------------------
  function isCreditCardMatch

  This function takes a ctype and a num and checks if the
  number fits the respective card type (true is returned), otherwise
  false is returned.
  num is a literal string and is stripped to digits!
  ctype may be one of the following values:
	chk_credit_visa(_opt)		for Visa cards
	chk_credit_master(_opt)		for MasterCard cards
	chk_credit_diners(_opt)		for Diner's Club cards
	chk_credit_amex(_opt)		for American Express cards
  ctype may be omitted to check for all known cards!
*/
function isCreditCardMatch(num,ctype) {
  if ((ctype==chk_credit_all_opt)||(ctype==chk_credit_visa_opt)||(ctype==chk_credit_master_opt)||
      (ctype==chk_credit_diners_opt)||(ctype==chk_credit_amex_opt)) {if (isWhitespace(num)) return true}
  num=stripCharsNotInBag(num,digits)
  if ((ctype==chk_credit_visa)||(ctype==chk_credit_visa_opt)) {if (!isVisaCard(num)) return false}
  else if ((ctype==chk_credit_master)||(ctype==chk_credit_master_opt)) {if (!isMasterCard(num)) return false}
  else if ((ctype==chk_credit_diners)||(ctype==chk_credit_diners_opt)) {if (!isDinersClub(num)) return false}
  else if ((ctype==chk_credit_amex)||(ctype==chk_credit_amex_opt)) {if (!isAmericanExpress(num)) return false}
  else if (!isVisaCard(num)&&!isMasterCard(num)&&!isDinersClub(num)&&!isAmericanExpress(num)) return false
  return true
}

/* -------------------------------------------------------------------
  function isDateTime

  Checks if date and time values are correct.
  If opt is set to optional (=true), then there is no check for whitespaces.
  The rest are variable arguments in the following order:
  y ... year
  m ... month
  d ... day
  h ... hour
  n ... minute
  s ... second
  If an argument shall not be checked it can be set to -1 or should be
  omitted (of course, i.e. day cannot be omitted if hour is used!)
  If none of the variable arguments are given, the function returns true.
*/
function isDateTime(opt) {
var a,b,i,args=isDateTime.arguments,argslen=args.length
  // if there are no further arguments...
  if (argslen==1) return true
  // is whitespace or empty?
  if (opt) {
    empty=true
    for (i=1;i<argslen;i++) if (!isWhitespace(args[i])) {empty=false; break}
    if (empty) return true
  }
  for (i=1;i<argslen;i++) if ((args[i]!=-1)&&!isNumeric(args[i],opt)) return false
  // check leap year, if no year (=-1) -> isLeapYear is false!
  // year must not be < 1 and > 9999
  a=args[1]
  if ((a!=-1)&&(a<1)||(a>9999)) return false
  i=(a!=-1)&&((a%400==0)||(a%100!=0)&&(a%4==0)) // leap year
  if (argslen>2) { // month exists
    // check month, must not be < 1 and > 12
    a=args[2]
    if ((a!=-1)&&(a<1)||(a>12)) return false
    if (argslen>3) { // day exists
      // check day depending on month and leap year (i)
      // if no month -> day must not be < 1 and > 31
      b=args[3]
      if (b!=-1) {
        switch (a*1) {
          case 2: if ((b<1)||(i&&(b>29))||(!i&&(b>28))) return false; break
          case 4:; case 6:; case 9:; case 11: if ((b<1)||(b>30)) return false; break
          default: if ((b<1)||(b>31)) return false
        }
      }
      if (argslen>4) { // hour exists
        // check hour, must not be > 23
        a=args[4]
        if ((a!=-1)&&(a>23)) return false
        if (argslen>5) { // minute exists
          // check minute, must not be > 59
          a=args[5]
          if ((a!=-1)&&(a>59)) return false
          if (argslen>6) { // second exists
            // check second, must not be > 59
            a=args[6]
            if ((a!=-1)&&(a>59)) return false
          } // if argslen > 6
        } // if argslen > 5
      } // if argslen > 4
    } // if argslen > 3
  } // if argslen > 2
  return true
}

/* -------------------------------------------------------------------
  function validateForm

  Checks if defined fields of a form f are valid.
  If lang is omitted or set to lang_german (=0) then the output text
  is displayed in German, otherwise, if set to lang_english (=1), English
  text is displayed. The language identifier is also significant for
  decimal reresentations! More languages may follow!
  The formula of the following unlimited parameter triplets are
  defined as: ,<fieldname>,<fielddesc>,<type> where:
  <fieldname>	is the name of the input field, a string literal!
  		ATTENTION:
  		if chk_datetime or chk_datetime_opt is defined
  		then this formula actually may change to <fieldnames>
  		separated by semicolons:
  		<year>[;<month>][;<day>][;<hour>][;<minute>][;<second>]
  		The field names are all represented by one string literal
  		(i.e. "fyear;fmonth;fday" or ";;;doc_hour;f_minute", latter
  		means, that year, month and day are not checked at all).
  		For further information see function isDateTime!
  <fielddesc>   is the readable language specific description of the field
                according to the text preceeding the input field, which the
                user may see, a string literal!
  <type>	is one of the following values (as described under
		constants at the beginning):
		chk_text
		chk_num
		chk_num_opt
		chk_dec
		chk_dec_opt
		chk_email
		chk_email_opt
		chk_box
		chk_datetime
		chk_datetime_opt
		chk_sel
		chk_credit_all
		chk_credit_all_opt
		chk_credit_visa
		chk_credit_visa_opt
		chk_credit_master
		chk_credit_master_opt
		chk_credit_diners
		chk_credit_diners_opt
		chk_credit_amex
		chk_credit_amex_opt
  Optional values (_opt) might be empty, the others must not be empty.
  Non-empty fields are checked for proper syntax and values as appropriate.
*/
function validateForm(f,lang) {
if (document.forms) cf=document.forms.length; else cf=0
if (cf > 0) {
  i = cf
  var formname=""
  while (i > 0 && formname != f.name) {
    i--
    formname=document.forms[i].name
  }
} else var formname=f.name
var fromsubmit=f.onsubmit && f.onsubmit.toString().indexOf("validateForm")>0 && formname == f.name
var fromaction=f.action && f.action.indexOf("validateForm")>0
var i,fail,args=validateForm.arguments,argslen=args.length
var dt=new Array(-1,-1,-1,-1,-1,-1)
  if ((argslen>2)&&((argslen-2)%3==0)) {
    if (!lang || lang==lang_german) {
      var
        txt='Sie haben keinen Text in das Eingabefeld %s eingegeben!',
        num='Sie haben keine gültige Zahl in das Eingabefeld %s eingegeben!',
        dec='Sie haben keine gültige Dezimalzahl in das Eingabefeld %s eingegeben!',
        email='Sie haben keine gültige Emailadresse in das Eingabefeld %s eingegeben!',
        box='Sie haben das Eingabefeld %s nicht markiert!',
        credit='Sie haben keine gültige Kreditkartennummer in das Eingabefeld %s eingegeben!\n'+
               'Unterstützte Karten sind: Visa, MasterCard, Diner\'s Club, American Express',
        date='Sie haben einen ungültigen Wert für %s eingegeben!',
        sel='Sie haben keinen Eintrag aus dem Auswahlfeld %s ausgewählt!',
        stdtxt='\n\nEine korrekte Eingabe ist für die weitere Bearbeitung erforderlich!'
    } else if (lang==lang_german_you) {
      var
        txt='Du hast keinen Text in das Eingabefeld %s eingegeben!',
        num='Du hast keine gültige Zahl in das Eingabefeld %s eingegeben!',
        dec='Du hast keine gültige Dezimalzahl in das Eingabefeld %s eingegeben!',
        email='Du hast keine gültige Emailadresse in das Eingabefeld %s eingegeben!',
        box='Du hast das Eingabefeld %s nicht markiert!',
        credit='Du hast keine gültige Kreditkartennummer in das Eingabefeld %s eingegeben!\n'+
               'Unterstützte Karten sind: Visa, MasterCard, Diner\'s Club, American Express',
        date='Du hast einen ungültigen Wert für %s eingegeben!',
        sel='Du hast keinen Eintrag aus dem Auswahlfeld %s ausgewählt!',
        stdtxt='\n\nEine korrekte Eingabe ist für die weitere Bearbeitung erforderlich!'
    } else if (lang==lang_hungarian) {
      var
        txt='Nem írt szöveget a megfelelõ %s mezõbe!',
        num='Nem írt érvényes számot a megfelelõ %s mezõbe!',
        dec='Nem irt érvényes tizedes számot a megfelelõ %s mezõbe!',
        email='Nem írt érvényes E-mail címet a megfelelõ %s mezõbe!',
        box='Nem jelölte ki a megfelelõ %s mezõt!',
        credit='Nem írt érvényes bankszámlaszámot a megfelelõ %s mezõbe!\n'+
               'Elfogadott kártyák: Visa, MasterCard, Diner\'s Club, American Express',
        date='Egy érvénytelen összeget írt a mefelelõ %s mezõbe!',
        sel='Nem választott ki témát a %s választékunkból!',
        stdtxt='\n\nA korrekt bejegyzés a feltétele a további feldolgozásnak!'
    } else if (lang==lang_italian) {
      var
        txt='Non ha inserito nessun testo nel campo di immissione %s!',
        num='Non ha inserito nessun numero valido nel campo di immissione %s!',
        dec='Non ha inserito nessun numero decimale valido nel campo di immissione %s!',
        email='Non ha inserito nessun indirizzo di e-mail valido nel campo di immissione %s!',
        box='Non ha evidenziato il campo di immissione %s!',
        credit='Non ha inserito nessun numero di carta di credito valido nel campo di immissione %s!\n'+
               'Le carte sostenute sono: Visa, MasterCard, Diner\'s Club, American Express',
        date='Ha inserito un valore non valido per %s!',
        sel='Non ha scelto nessuna registrazione dall\'ambito di scelta %s!',
        stdtxt='\n\nUn\'immissione corretta è necessaria per l\'ulteriore lavorazione!'
    } else {
      var
        txt='You did not enter a text into the input field %s!',
        num='You did not enter a valid number into the input field %s!',
        dec='You did not enter a valid decimal number into the input field %s!',
        email='You did not enter a valid email address into the input field %s!',
        box='You did not mark the input field %s!',
        credit='You did not enter a valid credit card number into the input field %s!\n'+
               'Supported cards are: Visa, MasterCard, Diner\'s Club, American Express',
        date='You have entered an invalid value for %s!',
        sel='You did not choose an entry from the select field %s!',
        stdtxt='\n\nA correct input is required for further processing!'
    } //if (lang)
    for (i=2;i<argslen;i+=3) {
      var fn=args[i], fd=args[i+1], tp=args[i+2]
      if ((tp==chk_num)||(tp==chk_num_opt))
        var line='fail=!isNumeric(f.'+fn+'.value,(tp==chk_num_opt))',atxt=num
      else if ((tp==chk_dec)||(tp==chk_dec_opt))
        var line='fail=!isDecimal(f.'+fn+'.value,(tp==chk_dec_opt),lang)',atxt=dec
      else if ((tp==chk_email)||(tp==chk_email_opt))
        var line='fail=!isEmail(f.'+fn+'.value,(tp==chk_email_opt))',atxt=email
      else if (tp==chk_box)
        var line='fail=!f.'+fn+'.checked',atxt=box
      else if (tp==chk_sel)
        var line='fail=f.'+fn+'.selectedIndex<1',atxt=sel
      else if ((tp==chk_credit_all)||(tp==chk_credit_all_opt)||
               (tp==chk_credit_visa)||(tp==chk_credit_visa_opt)||
               (tp==chk_credit_master)||(tp==chk_credit_master_opt)||
               (tp==chk_credit_diners)||(tp==chk_credit_diners_opt)||
               (tp==chk_credit_amex)||(tp==chk_credit_amex_opt))
           var line='fail=!isCreditCardMatch(f.'+fn+'.value,tp)',atxt=credit
      else if ((tp==chk_datetime)||(tp==chk_datetime_opt)) {
        var idx=0,idx2=0,j=0,k=0,temp=""
      	while (idx2!=-1) {
      	  idx2=fn.indexOf(";",idx)
      	  if (idx2<0) temp=fn.slice(idx); else temp=fn.slice(idx,idx2)
      	  if (!isEmpty(temp)) {dt[j]=temp; k=j}
      	  idx=idx2+1; j++
      	}
      	fn=dt[k]
        var line='fail=!isDateTime((tp==chk_datetime_opt)'
        for (idx=0;idx<dt.length;idx++) if (dt[idx]!=-1) line+=',f.'+dt[idx]+'.value'; else line+=',-1'
        line+=')'
        var atxt=date
      } else var line='fail=isWhitespace(f.'+args[i]+'.value)',atxt=txt
      eval(line)
      if (fail) {alert(atxt.replace(/%s/i,'<'+fd+'>')+stdtxt); eval('f.'+fn+'.focus()'); break}
    } //for
    if (fail) if (fromsubmit || (!fromsubmit && !fromaction)) return false; else return
  } else {
    if (!lang||(lang==lang_german))
      alert('<validateForm> wurde mit einer unzureichenden Anzahl von Parametern aufgerufen!\n'+
            'Formular <'+f.name+'> wird nicht übermittelt werden!\n\n'+
            'Bitte informieren Sie den Webmaster dieser Site über diesen Fehler!')
    else if (lang==lang_german_you)
      alert('<validateForm> wurde mit einer unzureichenden Anzahl von Parametern aufgerufen!\n'+
            'Formular <'+f.name+'> wird nicht übermittelt werden!\n\n'+
            'Bitte informiere den Webmaster dieser Site über diesen Fehler!')
    else if (lang==lang_hungarian)
      alert('<validateForm> az elégtelen paraméterek miatt jelent meg!\n'+
            'A nyomtatvány <'+f.name+'> nem átadható!\n\n'+
            'Kérem tájékoztassa a Webmastert ennek az oldalnak a hibájáról!')
    else if (lang==lang_italian)
      alert('<validateForm> è stato chiamato con un numero insufficiente da parametri!\n'+
            'Modulo <'+f.name+'> non sarà trasmesso!\n\n'+
            'Per favore informi il Webmaster di Site su questo errore!')
    else
      alert('<validateForm> was called with an improper number of arguments!\n'+
            'Form <'+f.name+'> will not be submitted!\n\n'+
            'Please inform the webmaster of this site about this error!')
    if (fromsubmit || (!fromsubmit && !fromaction)) return false; else return
  } //if incorrect argslen
  if (fromaction && f.validated_action) {
    f.action = f.validated_action.value
    f.submit()
  } else if (fromaction && f.mail_validated_action) {
    f.action = f.mail_validated_action.value
    f.submit()
  }
  if (fromsubmit || (!fromsubmit && !fromaction)) return true
} //function validateForm

