/**
 * Kniznica RForm
 *
 * Obsahuje triedu RForm, ktora sluzi na validaciu poli formulara,
 * a funkcie rPrint(objekt) a rAlert(objekt) na testovacie vypisy objektov.
 *
 * Kniznica RForm je zavisla na kniznici Prototype (otestovane s verziou 1.5.0),
 * ktora je takisto OpenSource, volne k dispozicii na http://www.prototypejs.org.
 *
 *
 * Rain - PHP Object Oriented Framework
 *
 * Copyright (C) 2005 - 2007  Oto Komiňák (www.oto.kominak.sk)
 *
 *
 * LICENSE:
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA
 *
 * @package     Rain
 * @author      Oto Komiňák
 * @copyright   2005-2007 Oto Komiňák
 * @link        http://www.oto.kominak.sk
 * @license     http://www.opensource.org/licenses/lgpl-license.php GNU LGPL
 * @version     1.0
 * @since       1.0
 * @filesource
 */



function RForm(objName, formName) {

    this.objName  = objName;
    this.formName = formName;

    this.fields         = new Array;
    this.errors         = 0;
    this.modified       = false;
    this.watchingUnload = false;

    this.regex = {
        "empty":        /^\s*$/,
        "email":        /^[^@]+@[^@.]+\.[^@]*\w\w$/,
        "mobile":       /^0[0-9]{2,3} [0-9]{3} [0-9]{3}$/,
        //"mobileIntl":   /^\+[0-9]{2,3} [0-9]{3} [0-9]{3}$/,
        "phone":        /^\+?[0-9\ ]+$/
    };


    this.setHandlers = function() {
        for (name in this.fields) {
            if (!name) continue;
            input = $(name);
            div   = input.parentNode;

            eval("input.onchange = function() { " + this.objName + ".validateField(this); };");

            children = div.getElementsByTagName("span");
            if (children.length >= 1) {
                this.fields[name].spanText = children[0].innerHTML;
            }
        }
    }


    this.watchUnload = function () {
        if (watchUnload) {
            this.watchingUnload = true;
            eval(
                "window.onunload = function() { " +
                "   if ((" + this.objName + ".modified) && (confirm(I18N.RForm.leaveUnsaved))) { " +
                "       $(\"" + this.formName + "\").submit(); " +
                "   } " +
                "}"
            );
        }
    }


    this.setStatus = function(div, ok, message) {
        div.removeClassName("input-ok");
        div.removeClassName("input-error");
        if (ok) {
            div.addClassName("input-ok");
        } else {
            div.addClassName("input-error");
            this.errors += 1;
        }

        // Span element, ktory obsahuje informacie o validite input boxu
        children = div.getElementsByTagName("span");
        if (children.length >= 1) {
            $(children[0]).update(message);
        }

        return ok;
    }


    this.validateField = function(input) {
        // Nastavenia z pola this.fields relevantne pre tento div
        field = this.fields[input.id];

        // Volanie uzivatelskeho handleru
        if (field.onchange) {
            field.onchange();
            field = this.fields[input.id];
        }

        // Div element, ktory obsahuje label, input a span
        div = input.parentNode;

        // Hodnota pola bez medzier na zaciatku a na konci
        value = trim(input.value);

        this.modified = true;

        //if (this.regex.empty.test(input.value)) {
        if (value == "") {
            return this.setStatus(div, !field.required, field.spanText);
            if (field.required) {
                return this.setStatus(div, false, I18N.RForm.error);
            } else {
                return this.setStatus(div, true, I18N.RForm.optional);
            }
        }

        if (this.regex[field.type]) {
            if (this.regex[field.type].test(value)) {
                return this.setStatus(div, true, I18N.RForm.ok);
            } else {
                messageId = "error";
                switch (field.type) {
                    case "email": messageId = "wrongEmail";     break;
                    case "phone": messageId = "error";          break;
                }
                return this.setStatus(div, false, I18N.RForm[messageId]);
            }
        }

        if (field.type == "regex") {
            if (field.regex.test(value)) {
                return this.setStatus(div, true, I18N.RForm.ok);
            } else {
                return this.setStatus(div, false, I18N.RForm.error);
            }
        }

        if (field.type == "text") {
            if ((field.min != null) && (value.length < field.min)) {
                return this.setStatus(div, false, I18N.RForm.minLength + " " + field.min);
            }
            if ((field.max != null) && (value.length > field.max)) {
                return this.setStatus(div, false, I18N.RForm.maxLength + " " + field.max);
            }
            return this.setStatus(div, true, I18N.RForm.ok);
        }

        if (field.type == "integer") {
            regex = /^-?[0-9]+/;
            if (!regex.test(value)) {
                return this.setStatus(div, false, I18N.RForm.wrongInteger);
            }
            n = parseInt(value);
            if ((field.min != null) && (n < field.min)) {
                return this.setStatus(div, false, I18N.RForm.min + " " + field.min);
            }
            if ((field.max != null) && (n > field.max)) {
                return this.setStatus(div, false, I18N.RForm.max + " " + field.max);
            }
            return this.setStatus(div, true, I18N.RForm.ok);
        }

        return true;
    }


    this.validateAllFields = function (showAlert) {
        this.errors = 0;

        if (this.watchingUnload) {
            window.onunload = function() { }
        }

        for (name in this.fields) {
            if (!name) continue;
            input = $(name);
            input.onchange(input);
        }

        if (this.errors > 0) {
            if (showAlert) {
                alert(I18N.RForm.checkForm);
            }
            return false;
        } else {
            return true;
        }
    }

}


function RCookie() {

    this.getCookie = function (name)  {
        var start = document.cookie.indexOf( name + "=" );
        var len = start + name.length + 1;
        if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
            return null;
        }
        if ( start == -1 ) return null;
        var end = document.cookie.indexOf( ';', len );
        if ( end == -1 ) end = document.cookie.length;
        return unescape( document.cookie.substring( len, end ) );
    }


    this.setCookie = function (name, value, expires, path, domain, secure) {
        var today = new Date();
        today.setTime( today.getTime() );
        if ( expires ) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date( today.getTime() + (expires) );
        document.cookie = name+'='+escape( value ) +
            ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
            ( ( path ) ? ';path=' + path : '' ) +
            ( ( domain ) ? ';domain=' + domain : '' ) +
            ( ( secure ) ? ';secure' : '' );
    }

    this.deleteCookie = function (name, path, domain) {
        if ( getCookie( name ) ) document.cookie = name + '=' +
                ( ( path ) ? ';path=' + path : '') +
                ( ( domain ) ? ';domain=' + domain : '' ) +
                ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
    }
}


function rAlert(obj) {
    alert(rDump(obj, "", false, "", 0));
}


function rPrint(obj) {
    document.write("<div style=\"text-align: left\"><pre>" + rDump(obj, "", true, "", 0) + "</pre></div>");
}


function rDump(obj, name, html, indent, depth) {
    var nl = "\n";

    if (depth > 10) {
        return indent + name + ": <Maximum Depth Reached>" + nl;
    }

    if (typeof obj == "object") {
        var child = null;
        var output = indent + name + nl;
        indent += html ? "&nbsp;&nbsp;&nbsp;&nbsp;" : "    ";

        for (var item in obj) {
            try {
                child = obj[item];
            } catch (e) {
                child = "<Unable to Evaluate>";
            }
            if (typeof child == "object") {
                output += rDump(child, item, html, indent, depth + 1);
            } else {
                output += indent + item + ": " + child + nl;
            }
        }
        return output;

    } else {
        return obj;
    }
}


function rOpenImage(url) {
    window.open(url, 'w', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=660,height=660');
}




var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread



// Trim leading/trailing whitespace off string

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}


// Delayed focus setting to get around IE bug

function setFocusDelayed() {
    glb_vfld.focus();
}


function setfocus(vfld) {
    glb_vfld = vfld;
    setTimeout('setFocusDelayed()', 100);
}


// Display warn/error message in HTML element
// commonCheck routine must have previously been called

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
    // setting an empty string can give problems if later set to a 
    // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
    // simply use a space, but IE demands something more, like a non-breaking space.)
    var dispmessage;
    if (emptyString.test(message)) 
        dispmessage = String.fromCharCode(nbsp);        
    else    
        dispmessage = message;

    var elem = document.getElementById(fld);
    elem.firstChild.nodeValue = dispmessage;    
    
    elem.className = msgtype;     // set the CSS class to adjust appearance of message
}


// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)

var proceed = 2;  

function commonCheck(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
    if (!document.getElementById) 
        return true;    // not available on this browser - leave validation to the server
    var elem = document.getElementById(ifld);
    if (!elem.firstChild)
        return true;    // not available on this browser 
    if (elem.firstChild.nodeType != node_text)
        return true;    // ifld is wrong type of node    

    if (emptyString.test(vfld.value)) {
        if (reqd) {
            msg(ifld, "error", form_locale[lang]["required"]);    
            setfocus(vfld);
            return false;
        }
        else {
            if (reqd) msg(ifld, "info", form_locale[lang]["ok"]);     // OK
            else msg(ifld, "info-nreq", form_locale[lang]["optional"]);     // OK
                
            return true;    
        }
    }
    return proceed;
}


// Validate if something has been entered
// Returns true if so 

function validatePresent(vfld,   // element to be validated
                         ifld)   // id of element to receive info/error msg
{
    var stat = commonCheck(vfld, ifld, true);
    if (stat != proceed) return stat;

    msg(ifld, "info", form_locale[lang]["ok"]);
    return true;
}


function validateStr(vfld, ifld, reqd, min, max) {
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var errlevel = "error";
  if (!reqd) errlevel = "warn";
  
  if (tfld.length < min) {
      msg(ifld, errlevel, form_locale[lang]["min_length"] + ": " + min);
      setfocus(vfld);
      return false;
  } else if (tfld.length > max) {
      msg(ifld, errlevel, form_locale[lang]["max_length"] + ": " + max);
      setfocus(vfld);
      return false;
  }

  msg(ifld, "info", form_locale[lang]["ok"]);

  return true;
}


function validateStr2(vfld, ifld, reqd, min, max) {
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var errlevel = "error";
  if (!reqd) errlevel = "warn";

} 



// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)

function validateEmail(vfld,   // element to be validated
                       ifld,   // id of element to receive info/error msg
                       reqd)   // true if required
{
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg(ifld, "error", form_locale[lang]["wrong_email"]);
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg(ifld, "warn", form_locale[lang]["strange_email"]);
  else {
      msg(ifld, "info", form_locale[lang]["ok"]);
  }
  return true;
}


function validateDate(vfld,   // element to be validated
                      ifld,   // id of element to receive info/error msg
                      reqd)   // true if required
{
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var format = /^[0-3][0-9]\.[0-1][0-9]\.[1-2][0-9]{3}$/
  if (!format.test(tfld)) {
    msg(ifld, "error", form_locale[lang]["format"] + ": " + form_locale[lang]["dd_mm_yyyy"]);
    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "info", form_locale[lang]["ok"]);

  return true;
}


function validateICO(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  // nn nnn nnn, nnnnnnnn

  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var format = /^[0-9]{2} ?[0-9]{3} ?[0-9]{3}$/
  if (!format.test(tfld)) {
    msg(ifld, "error", "Nesprávne IČO");
    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "info", "OK");

  return true;
}


function validateDIC(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var format = /^[0-9]{3} ?[0-9]{3} ?[0-9]{4}\/?[0-9]{0,4}$/
  if (!format.test(tfld)) {
    msg(ifld, "error", "Nesprávne DIČ");
//    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "info", "OK");

  return true;
}


function validateZIP(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  // nnn nn, nnnnn

  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var zip = /^[0-9]{3} ?[0-9]{2}$/
  if (!zip.test(tfld)) {
    msg(ifld, "error", "Nesprávne PSČ");
    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "info", "OK");

  return true;
}


// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +

function validatePhone(vfld,   // element to be validated
                       ifld,   // id of element to receive info/error msg
                       reqd)   // true if required
{
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^[0-9]{4} [0-9]{3} [0-9]{3}$/
  if (!telnr.test(tfld)) {
    msg(ifld, "error", form_locale[lang]["wrong_phone"]);
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg(ifld, "error", form_locale[lang]["wrong_phone"]);
    setfocus(vfld);
    return false;
  }


//  if (numdigits>14)
//    msg (ifld, "warn", numdigits + " digits - check if correct");
//  else { 
//    if (numdigits<10)
//      msg (ifld, "warn", "Only " + numdigits + " digits - check if correct");
    else
      msg (ifld, "info", form_locale[lang]["ok"]);
//  }

  return true;
};



// Validate person's age
// Returns true if OK 

function validateAge(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg(ifld, "error", "ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>110) msg(ifld, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg(ifld, "warn", "Bit young for this, aren't you?");
    else        msg(ifld, "warn", "");
  }
  return true;
}


function validateInt(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]+$/
  if (!ageRE.test(tfld)) {
    msg(ifld, "error", form_locale[lang]["wrong_number"]);
    setfocus(vfld);
    return false;
  }

  msg (ifld, "info", form_locale[lang]["ok"]);
  return true;
}


function validateInt2(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd,   // true if required
                     min, max)
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]+$/
  if (!ageRE.test(tfld)) {
    msg(ifld, "error", form_locale[lang]["wrong_number"]);
    setfocus(vfld);
    return false;
  }

  if ((max != "x") && (tfld > max)) {
    msg (ifld, "error", form_locale[lang]["maximum"] + ": " + max);
    setfocus(vfld);
    return false;
  }

  if ((min != "x") && (tfld < min)) {
    msg (ifld, "error", form_locale[lang]["minimum"] + ": " + min);
    setfocus(vfld);
    return false;
  }

  msg (ifld, "info", "OK");
  return true;
}


function validateFloat(vfld,   // element to be validated
                       ifld,   // id of element to receive info/error msg
                       reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var floatRE = /^[0-9]*[.]?[0-9]+$/
  if (!floatRE.test(tfld)) {
    msg(ifld, "error", form_locale[lang]["wrong_float"]);
    setfocus(vfld);
    return false;
  }

  msg (ifld, "info", "OK");
  return true;
}


function directValidateInt2(vfld,   // element to be validated
                            min, max)
{
  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]+$/
  if (!ageRE.test(tfld)) {
    alert("Neplatné číslo!");
    setfocus(vfld);
    return false;
  }

  if ((max != "x") && (tfld > max)) {
    alert("Maximum: " + max);
    setfocus(vfld);
    return false;
  }

  if ((min != "x") && (tfld < min)) {
    alert("Minimum: " + min);
    setfocus(vfld);
    return false;
  }

  return true;
}


function openWin(img) {
    window.open(img, 'w', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=660,height=660');
}


function openWinWH(img, w, h) {
    window.open(img, 'w', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width='+w+',height='+h);
}


function openWinWHScroll(img, w, h) {
    window.open(img, 'w', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+w+',height='+h);
}


function toggleVisibility(d) {
    elem = document.getElementById(d);
    if (elem.style.visibility == 'hidden') elem.style.visibility = 'visible';
    else elem.style.visibility = 'hidden';
}


function setVisibility(d, vis) {
    elem = document.getElementById(d);
    if (vis) elem.style.visibility = 'visible';
    else     elem.style.visibility = 'hidden';
}

function setDisplay(d, vis, disp, none) {
    elem = document.getElementById(d);
    if (vis) elem.style.display = disp;
    else     elem.style.display = none;
}


