/*
Form validation functions
Copyright (c) 2002-2008 Ylab, www.ylab.nl
20081215:YC:suggestCountry()
*/
function errormsg(errorcode, guiName, val){
  var msg = errormessages[errorcode];
  msg = msg.replace(/%g/, guiName);
  msg = msg.replace(/%v/, val);
  alert(msg);
}

function isNotNull(field, guiName, f){
  //validates if a field contains a value
  //field: input element text|hidden
  //guiName: fieldname to communicate with user
  if (!field){debugAlert("Het veld '"+guiName+"' bestaat niet.");}
  if ((!field.value) || (field.value == "")){
    errormsg('errMissing', guiName);
    setFocus(field, f);
    return false;
  }
  return true;
}

function radioIsChecked(field, guiName, f){
  //validates if a field contains a value
  //field: input element text|hidden
  //guiName: fieldname to communicate with user
  if (!field){debugAlert("Het veld '"+guiName+"' bestaat niet.");}
  if (!field.length){debugAlert("Het veld '"+guiName+"' is geen radiogroup.");}
  if (field.type && field.type=='radio' && field.checked){
    return true;
  }
  for(var i=0; i< field.length; i++){
    if(field[i].checked){
      return true;
    }
  }
  errormsg('errMissing', guiName);
  setFocus(field[0], f);
  return false;
}

function isEmail(field, guiName, f){
  //validates if a textbox contains a valid email address
  var str = field.value;
  if (!str) return true;
  var at = str.indexOf('@');
  if ( (at < 2) || (str.indexOf('.',at+1) < 4) )
  {
    errormsg('errEmail', guiName)
    setFocus(field, f);
    return false;
  }
  return true;
}

function isPhone (field, guiName, f){
  //validates if a textbox contains a valid ten digit phone number
  var str = field.value;
  var num = "";

  if (!str) return true;

  var ar = str.match(/\d+/g);
  for (var i=0; i< ar.length; i++){
    num += ar[i];
  }
  if (num.charAt(0)!="0" || num.charAt(1)=="0" || num.length != 10) {
    errormsg('errPhone', guiName)
    setFocus(field, f);
    return false;
  }
  return true;
}
var c=0;
function isInRange(field, guiName, minval, maxval, f){
  //validates if a field contains a value with a certain range
  if (!field.value) return true;
  if ((minval != null) && (field.value <= minval)){
    errormsg('errMinVal', guiName, minval);
  }
  else if ((maxval != null) && (field.value > maxval)){
    errormsg('errMaxVal', guiName, maxval);
  }
  else{
    return true;
  }
  setFocus(field, f);
  return false;
}

function hasMinLen(field, guiName, minlen, f){
  //validates if a field contains a value with a certain length
  //field: input element text|hidden
  //guiName: fieldname to communicate with user
  if (!field.value) return true;
  if (field.value.length < minlen)  {
    errormsg('errMinLen', guiName, minlen);
    setFocus(field, f);
    return false;
  }
  return true;
}
function hasMaxLen(field, guiName, maxlen, f){
  //validates if a field contains a value with a certain length
  //field: input element text|hidden
  //guiName: fieldname to communicate with user
  if (!field.value) return true;
  if (field.value.length > maxlen)  {
    errormsg('errMaxLen', guiName, maxlen);
    setFocus(field, f);
    return false;
  }
  return true;
}
function isDate(field, guiName, f){
  if (!field.value) return true;
  d = strToDate(field.value);
  if (!d){
    errormsg('errDate', guiName);
    setFocus(field, f);
    return false;
  }
  return true;
}

function isSofinumber(field, guiName, f){
  if (!field.value) return true;
  var reSofi = /(\d)(\d)(\d)(\d).?(\d)(\d).?(\d)(\d)(\d)/;
  var isValid = false;
  var numbers;
  var lSom = 0;

  if (reSofi.test(field.value)){
    //11 test
    numbers = (field.value.match(reSofi));
    for (i=1;i<9;i+=1){
      lSom += (numbers[i] * (9-(i-1)));
    }
    isValid = (((lSom -= numbers[9]) % 11) == 0)
  }
  if (!isValid){
    errormsg('errInvalid', guiName);
    setFocus(field, f);
  }
  return (isValid);
}

function isLater(field, fieldStart, guiName, f){
  if (!field.value || !fieldStart.value) return true;//don't validate empty fields
  if (strToDate(field.value) < strToDate(fieldStart.value)){
    errormsg('errLater', guiName, fieldStart.value);
    setFocus(field, f);
    return false;
  }
  return true;
}

function isBeforeDate(field, refDate){
  if (!field.value) return false;//don't validate empty fields
  d = strToDate(field.value);
  return (d < refDate);
}

function isAfterDate(field, refDate){
  if (!field.value) return false;//don't validate empty fields
  d = strToDate(field.value);
  return (d > refDate);
}

function isEUmember(value){
  //exception for NL
  var euCountries = ['at', 'be', 'bg', 'cy', 'cz', 'de', 'dk', 'ee', 'el', 'es', 'eu', 'fi', 'fr', 'gb', 'gr', 'hu', 'ie', 'it', 'lt', 'lu', 'lv', 'mt', 'nl', 'pl', 'pt', 'ro', 'se', 'si', 'sk'];
  var isNL = value=='nl';

  return euCountries.in_array(value) && !isNL;
}

function strToDate(s){
  //dates are expected as dd-mm-yyyy or yyyy-dd-mm
  var dmY = new RegExp("([0-3]?[0-9]{1})[^[0-9]]*([0-1]?[0-9]{1})[^[0-9]]*([0-9]{4})");
  var Ymd = new RegExp("([0-9]{4})[^[0-9]]*([0-1]?[0-9]{1})[^[0-9]]*([0-3]?[0-9]{1})");
  if (result = s.match(dmY)){
    if (result[1] > 31){return false;}
    if (result[2] > 12){return false;}
    return (new Date(result[3], result[2]-1, result[1]));
  }
  else if (result = s.match(Ymd)){
    if (result[3] > 31){return false;}
    if (result[2] > 12){return false;}
    return (new Date(result[1], result[2]-1, result[3]));
  }
  return false;
}

function strToTime(s){
  //time is expected as hh:mm
  if (!isNaN(s) && s <= 24){s += ":00";}
  if (s == "24:00"){return (new Date(0,0,0,24,0));}
  var r = new RegExp("([0-2]?[0-9]{1})[^[0-9]]*([0-5]?[0-9]{1})");
  var result = s.match(r);
  if (!result){
    var r = new RegExp("([0-2]?[0-9]{1})([0-5]?[0-9]{1})");
    var result = s.match(r);
  }
  if (!result){return false;}
  if (result[1] > 23){return false;}
  if (result[2] > 59){return false;}
  return (new Date(0,0,0,result[1], result[2]));
}

function leadingZero(s){
  return ((s < 10) ? "0" : "") + s;
}

function setFocus(field, f){
  try{
    if (f){f = new Function(f); f();}
    field.focus();
  }
  catch(ex){}
}

function addRow(btn, fldId, rowId){
  //btn: the 'Add Row' button or hyperlink
  //fld: field containg the row counter
  //rowId: prefix for the id of the tablerow
  fld = id2object(fldId);
  if(!fld){return;}

  var n = fld.value;
  var tr = document.getElementById(rowId + n);
  if (tr){
    tr.style.display = "block";
    //increase counter
    fld.value = ++n;
    tr = document.getElementById(rowId + n);
  }
  if (!tr){
    btn.style.display = "none";
  }
}

function trackChanges(){
  if (!this.form.changedFields){this.form.changedFields = new Array();}
  if ((this.type == "checkbox") || (this.type == "radio")){
    var changed = (this.checked != this.defaultChecked);
    this.parentNode.style.color = (changed) ? '#0000BB' : '#000000';
  }
  else{
    var changed = (this.value != this.defaultValue);
    this.style.color = (changed) ? '#0000BB' : '#000000';
  }
  for (var i=0; i<this.form.changedFields.length; i++){
    if (this.form.changedFields[i] == this.name){
      if (!changed){
        //remove this field from array
        this.form.changedFields.splice(i,1);
      }
      changed = null;
      break;
    }
  }
  if (changed){
    //add field to array
    this.form.changedFields.push(this.name);
  }
}
function initTrackChanges(frmId){
  frm = id2object(frmId);
  if (!frm){return;}
  frm.defaultStatus = window.status;
  for (var i=0; i< frm.elements.length; i++){
    if (frm.elements[i].name){addEvent(frm.elements[i], "onchange", trackChanges);}
  }
}

function formChanged(frmId){
  frm = id2object(frmId);
  if (frm && frm.onsave){frm.onsave();}
  if (!frm || !frm.changedFields) return false;
  return (frm.changedFields.length > 0);
}

function ignoreNonNumKey(e){
  //keypress
  //opera: keycode: 0, charcode= ascii
  //other: keycode: ascii, charcode= null
  var evt = e || window.event;

  if(evt.charCode != undefined){
    //opera
    if(evt.charCode == 0){
      return true;//no character key
    }
    cde = evt.charCode;
  }
  else{
    cde = evt.keyCode;
  }
  //accept 0::9
  if (cde < 48 || cde > 57){
    //suppres
    if(window.event){
      window.event.returnValue = false;
    }
    return false;
  }
}

function suggestCountry(inp, cbo){
	var sTld, sEmail = inp.value;
	var iPos = sEmail.lastIndexOf('.');
	if(iPos != -1){
		var sTld = sEmail.substring(iPos+1);
		if(cbo.selectedIndex==0){
			cbo.value = sTld.length == 2 ? sTld : 'us';
		}
	}
}

//Number.toFixed, is not supported by IE5.0
if (!Number.prototype.toFixed){
  Number.prototype.toFixed = function(decimals){
    // default to zero decimal digits
    var decDigits = (isNaN(decimals) || decimals < 0) ? 0 : decimals;
    var k = Math.pow(10, decDigits);
    var fixedNum = Math.round(parseFloat(this) * k) / k;
    var sFixedNum = new String(fixedNum);
    var aFixedNum = sFixedNum.split(".");

    var i = (aFixedNum[1]) ? aFixedNum[1].length : 0;
    // append decimal point if needed
    if ((i == 0) && (decDigits)) { sFixedNum += "."; }
    // append zeros if needed
    while (i < decDigits) {
      sFixedNum += "0";
      i++;
    }
    return sFixedNum;
  }
}
