
/*
 * iBLOG 2005
 *
 * Form validation
 */
 
// this function flashes specified object 3x
var _saved_obj = null;
var _saved_cnt = 0;
function _tmp_flashObject(obj) {
  if (obj!=null) _saved_obj = obj;
  else obj = _saved_obj;
  
  if (_saved_cnt%2==1) obj.style.backgroundColor = '#FFA0A0';
  else {
    if (obj.type=='file') obj.style.backgroundColor = '';
    else obj.style.backgroundColor = '#FFF3F3';
  }
  
  if (_saved_cnt>5) {
    _saved_cnt = 0;
    _saved_obj = null;
    return;
  }
  _saved_cnt++;
  window.setTimeout('_tmp_flashObject(null)', 60);
}
 
 
//some basic validation functions
function trim(val) {
  return val.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2');
}
// string is empty
function is_empty(val) {
  return (trim(val)=='');
}
// contains only alpha characters
function is_alpha(val) {
  return (val.match(/^([_A-Z0-9]+)$/i)!=null);
}
// string is email
function is_email(val) {
  return (val.match(/^([_A-Z0-9-\.]+)@([_A-Z0-9-\.]+)$/i)!=null);
}
// string is url
function is_url(val) {
  return (val.match(/^((http|https|ftp):\/\/|www)[a-z0-9\-\._]+\/?[a-z0-9_\.\-\?\+\/~=&#;,]*[a-z0-9\/]{1}$/i)!=null);
}


// validator
function ValidatorFormItem(id, func, msg)
{
  this.id = id;
  this.func = func.toLowerCase();
  this.msg = msg;
}

function validator_add(id, func, msg) {
  this.items[this.items.length] = new ValidatorFormItem(id, func, msg);
}

function validator_exec() {
  if (!document.getElementById) return true;
  msg = '';
  obj = null;
  for(i=0;i<this.items.length;i++) {
    if (msg!='') break;
    obj = document.getElementById(this.items[i].id);
    if (this.items[i].func.substr(0,6)=='minlen') {
      minlen = Math.round(this.items[i].func.substr(7,32));
      tlen = trim(obj.value).length;
      if (tlen>0&&tlen<minlen) msg = this.items[i].msg;
    } else if (this.items[i].func.substr(0,7)=='compare') {
      cid = document.getElementById(this.items[i].func.substr(8,33));
      if (cid&&cid.value!=obj.value) msg = this.items[i].msg;
    } else switch (this.items[i].func) {
      case 'email':
      case 'mail':
        if (!is_email(obj.value)) msg = this.items[i].msg;
        break;
      case 'link':
      case 'url':
        if (!is_url(obj.value)) msg = this.items[i].msg;
        break;
      case 'link2':
      case 'url2':
        if (!is_empty(obj.value)&&!is_url(obj.value)) msg = this.items[i].msg;
        break;
      case 'req':
        if (is_empty(obj.value)) msg = this.items[i].msg;
        break;
      case 'alpha':
        if (!is_alpha(obj.value)) msg = this.items[i].msg;
        break;
    }
  }
  if (msg!='') {
    obj.style.backgroundColor = '#FFA0A0'
    alert(msg);
    obj.focus();
    _tmp_flashObject(obj);
    return false;
  }
  return true;
}

function Validator() {
  this.items = new Array();
  this.add = validator_add;
  this.exec = validator_exec;
  this.validate = validator_exec;
}
