var nbsp = 160;
var node_text = 3;
var emptyString = /^\s*$/
var glb_vfld;

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};


function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
  valfield.setAttribute('class', 'error');
}

function msg(fld,msgtype,message)
{

  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;
};


var proceed = 2;

function commonCheck(vfld, ifld, reqd, minLength, maxLength)
{
  if (!document.getElementById) return true;
  
  var elem = document.getElementById(ifld);

  if (!elem.firstChild) return true;

  if (elem.firstChild.nodeType != node_text) return true;

  if(minLength > 0)
  {

    if(vfld.value.length < minLength)
    {
       msg(ifld, "error", "Bł±d. Minimalna długo¶ć wpisu to" + minLength + "!");
       setfocus(vfld);
       return false;
    }
  }
    
  if(maxLength > 0)
  {
    if(vfld.value.length > maxLength)
    {
       msg(ifld, "error", "Bł±d. Maksymalna długo¶ć wpisu to " + maxLength + "!");
       setfocus(vfld);
       return false;
    }
  }

  if (emptyString.test(vfld.value))
  {
    if (reqd) 
    {
      msg (ifld, "error", "Bł±d. Wypełnij puste pole.");
      setfocus(vfld);
      return false;
    }
    else
    {
      //vfld.setAttribute('class', '');
      msg (ifld, "warn", "");
      return true;
    }
  }



  return proceed;
}

function validatePresent(vfld, ifld)
{
  var stat = commonCheck (vfld, ifld, true, 0, 0);
  if (stat != proceed) return stat;

  msg (ifld, "warn", "");
  vfld.setAttribute("class", "");
  return true;
};

function validatePresent(vfld, ifld, minLength, maxLength)
{
  var stat = commonCheck (vfld, ifld, true, minLength, maxLength);
  if (stat != proceed) return stat;

  msg (ifld, "warn", "");
  vfld.setAttribute("class", "");
  return true;
};


function validateDate(vfld,ifld,reqd)
{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;
  var tfld = trim(vfld.value);
  var d1 = /^[12][09][0-9][0-9]+[-]+[01][0-9]+[-]+[0-3][0-9]$/
  if (!d1.test(tfld))
  {
    msg (ifld, "error", "Wpisz prawidłow± datę w formacie: RRRR-MM-DD");
    setfocus(vfld);
    return false;
  }

  var d2 = /^[12][09][0-9][0-9]+[-]+[1][3-9]+[-]+[0-3][0-9]$/
  if (d2.test(tfld))
  {
    msg (ifld, "error", "Rok ma 12 miesięcy!");
    setfocus(vfld);
    return false;
  }



  var d3 = /^[12][09][0-9][0-9]+[-]+[01][0-9]+[-]+[3][3-9]$/
  if (d3.test(tfld))
  {
    msg (ifld, "error", "Miesi±c nie ma tylu dni!");
    setfocus(vfld);
    return false;
  }
  else
  {
    vfld.setAttribute("class", "");
    msg (ifld, "warn", "");
    return true;
  }

};

function validateFloat(vfld,ifld)
{

  var stat = commonCheck (vfld, ifld, true);

  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var d1 = /^([0-9]+)+[.]+([0-9]+)$/
  if (!d1.test(tfld))
  {
    msg (ifld, "error", "Wpisz prawidłow± liczbę w formacie ułamka dziesiętnego rodzielonego kropk± ( . )");
    setfocus(vfld);
    return false;
  }
  else
  {
    vfld.setAttribute("class", "");
    msg (ifld, "warn", "");
    return true;
  }

};

function validateInt(vfld,ifld,ifld2,reqd)
{

  var stat = commonCheck (vfld, ifld, true);

  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var d1 = /^([0-9]+)$/
  if (!d1.test(tfld))
  {
    msg (ifld, "error", "Wpisz prawidłow± liczbę bez liter i znaków przestankowych. ");
    if(ifld2) msg (ifld2, "error", " *");
    setfocus(vfld);
    return false;
  }
  else
  {
    //vfld.setAttribute("class", "");
    msg (ifld, "warn", "");
    return true;
  }

};


function validateDate2(vfld, date, type, date1)  // validate date z okienkami dialogowymi
{                      //** vfld - walidowane pole
		       //** date - data zakonczenia zlecenia
		       //** date1 - drugie pole bedace w relacji z walidowanym

  //var stat = commonCheck (vfld, ifld, reqd);

  //if (stat != proceed) return stat;
  var tfld = trim(vfld.value);
  var d1 = /^[12][09][0-9][0-9]+[-]+[01][0-9]+[-]+[0-3][0-9]$/
  if (!d1.test(tfld))
  {
    alert("Wpisz prawidłow± datę w formacie: RRRR-MM-DD");
    return false;
  }

  var d2 = /^[12][09][0-9][0-9]+[-]+[1][3-9]+[-]+[0-3][0-9]$/
  if (d2.test(tfld))
  {
    alert("Rok ma 12 miesięcy!");
    return false;
  }


  if (date != null)
  {
       
       var tmp = new Array();
       
       tmp = tfld.split('-');
       var d1 = new Date(tmp[0], tmp[1]-1, tmp[2]);
       d1 = (d1.getTime() - d1.getMilliseconds())/1000;

       tmp = date.split('-');
       var d2 = new Date(tmp[0], tmp[1]-1, tmp[2]);
       d2 = (d2.getTime() - d2.getMilliseconds())/1000;

       if(d1 > d2 && type == "z")
       {
             if( confirm("UWAGA! Data zakończenia zadania przekracza datę zakończenia zlecenia! \n Aby zmienić DATĘ ZAKOŃCZENIA ZLECENIA naci¶nij [OK].") ) {return true;}
             else {return false;}
       }
       if(d1< d2 && type == "r")
       {
              alert("Data rozpoczęcia zadania jest mniejsza od daty rozpoczęcia zlecenia!");
              return false;
       }

       if(date1 != null)
       {

                tmp = date1.value.split('-');
                var d3 = new Date(tmp[0], tmp[1]-1, tmp[2]);

		d3 = (d3.getTime() - d3.getMilliseconds())/1000;


		if(d1 < d3 && type == "z" )
                {
                      alert("Data zakończenia zadania nie może być mniejsza niż data jego rozpoczęcia!");
                      return false;
                }
                if(d1 > d3 && type == "r" )
                {
                      alert("Data rozpoczęcia zadania nie może być większa niż data jego zakończenia!");
                      return false
                }


       }
  }
  
  
  var d3 = /^[12][09][0-9][0-9]+[-]+[01][0-9]+[-]+[3][3-9]$/
  if (d3.test(tfld))
  {
    alert("Miesi±c nie ma tylu dni!");
    return false;
  }
  else
  {
    //vfld.setAttribute("class", "");
    msg (ifld, "warn", "");
    return true;
  }



};



// -----------------------------------------
//            commonCheck2
// Common code for checkbox validation routines to
// check for older / less-equipped browsers
// Returns true (validation passed) or
//         proceed (don't know yet)
// -----------------------------------------

var proceed = 2;

function commonCheck2   (vfld,   // element to be validated
                         ifld)   // id of element to receive info/error msg
{
  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

  msg (ifld, "warn", "");  // clear any previous error message
  return proceed;
}


// -----------------------------------------
//            validateCheckbox
// Validate that the correct number of checkboxes has been checked.
// Returns true if valid (and also if could not be executed because
// of old browser)
// -----------------------------------------

function validateCheckbox  (vfld,   // checkboxes to be validated
                            ifld,   // id of element to receive info/error msg
                            nr,     // number of checkboxes to be checked. >=2
                            cond)   // condition: -1 = less than or equal to nr
                                    //             0 = equal to nr (default)
                                    //             1 = greater than or equal to nr
{
  if (!nr || nr<1) {
    alert('Programming error in validateCheckbox: nr<2');
       // for nr=1 use radio buttons or validateConfirm
    return true;
  }
  if (!cond) cond = 0;

  var stat = commonCheck2(vfld, ifld);
  if (stat != proceed) return stat;

  // count how many boxes have been checked by the reader
  var count = 0;
  for (var j=0; j<vfld.length; j++)
     if (vfld[j].checked) count++;

  if (count==nr) return true;
  if (count<nr && cond==-1) return true;
  if (count>nr && cond==1)  return true;

  // if we get here then the validation has failed

  var suffix='';
  if (count>1) suffix='es';

  var errorMsg;

  if (count<nr) errorMsg = 'Tylko ' + count + ' ' + suffix + ' zanznaczono: ' + nr + ' wymagane';
  if (count>nr) errorMsg = '' + count + ' zanzaczono: maksimum ' + nr + ' dopuszczonych';
  if (count==0) errorMsg = 'Proszę wybrać pole';

  
  msg (ifld, "error", errorMsg);
  return false;
}

function validateText(vfld, ifld, minLength, maxLength, expr)
{


  if(!validatePresent(vfld, ifld, minLength, maxLength)) return false;

  var tfld = vfld.value;

  switch(expr)
  {
        case 1: 
                var ex = /^([-._A-Z0-9a-z]*)$/; //** kod klienta
          break;
        case 2:
                var ex = /^([- .¶Ľ±ńćęóżł¦¬ŃĆĘˇÓŻŁ,_A-Z0-9a-z]*)$/; //** nazwa firmy
          break;
  }

  
  if (!ex.test(tfld))
  {
    msg (ifld, "error", "Niedozwolony znak.");
    setfocus(vfld);
    return false;
  
  }
  else
  {
    msg (ifld, "warn", "");
    //vfld.setAttribute("class", "");
    return true;
  }

};

function validateEmail(vfld, ifld, reqd)
{
  if(!validatePresent(vfld, ifld, 0, 0)) return false;

  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = vfld.value;

  var ex = /^([A-Za-z0-9.-_]{2,})(@)([A-Za-z0-9.-_]{2,})(.)([a-z]{2,4})$/;



  
  if (!ex.test(tfld))
  {
    msg (ifld, "error", "Błędny e-mail");
    setfocus(vfld);
    return false;
  
  }
  else
  {
    msg (ifld, "warn", "");
    vfld.setAttribute("class", "");
    return true;
  }

};
