﻿function Validator(){
this.elmEmphasizeCss='invalid';
this.accessElementById=false;
this.validate=validate;
this.testVal=testVal;
this.emphasize=emphasize;
this.add=add;
this.elements=new Array();
this.informMessage='';
this.showInformMessage=true;
this.emphasizeInvalidFields=true;
this.clear=clear;
this.owner=self;

//predefined reguler expressions
this.regexExps=new Array();
this.regexExps['email']=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
this.regexExps['ascii']=/^[0-9A-Za-z]*$/;
this.regexExps['int']=/^(\d)*$/;
this.regexExps['username']=/[0-9A-Za-z]{5,20}/;
this.regexExps['password']=/[0-9A-Za-z]{5,}/;
this.regexExps['date']=/(0[1-9]|[12][0-9]|3[01])[.|/](0[1-9]|1[012])[.|/](19|20)\d{2,2}/;
this.regexExps['search']=/(\b\w{3,}\b)+/;


function clear(){
    this.elements=new Array();
    this.informMessage='';
}        
function Element(){
    this.id;
    this.regex;
    this.message;
    this.isRequired;
}

function add(id,regex,isRequired,message){
var e=new Element();
    e.id=id;
    e.regex=regex;
    e.isRequired=isRequired;
    e.message=message;
    this.elements.push(e);
}
function testVal(value,exp){
  
    if(!isEmpty(this.regexExps[exp]))
        exp=this.regexExps[exp];
    
    return (isEmpty(value) || exp.test(value));
};

function validate(fields){
    var invalidFileds=new Array();
    var vCount=1;
    for(var i=0;i<this.elements.length;i++){
       try{
        var vFlag=false;
        
        var e=this.elements[i];
        var elm=this.accessElementById?$(e.id):_$(e.id)[0];

        if(e.isRequired && ((elm.tagName.toLowerCase()=='select' && getVal(e.id,false)==-1 ) || isEmpty(elm.value))){
              this.emphasize(elm,i);
              invalidFileds.push(e);
              vFlag=true;
            } 
        if(!isEmpty(e.regex) && !this.testVal(elm.value,e.regex)){
            this.emphasize(elm,i);
            invalidFileds.push(e);
            vFlag=true;
        }
        if(vFlag){
            if(vCount>1)this.informMessage+='<br/>';
            this.informMessage+=vCount +'. ' + e.message;
            vCount++;
            }
      }catch(e){}
    }
    
    if(this.showInformMessage && !isEmpty(this.informMessage))
        this.owner.msgBox(this.informMessage,culture.term('validationFailedHeader'),null,null,null,300,null,'left');
    this.clear();    
return invalidFileds.length>0?invalidFileds:false;
};

function emphasize(elm,eIndex){
    try{
    if(this.emphasizeInvalidFields){
              
        var tmpBg;
        if(elm.className.indexOf(this.elmEmphasizeCss)==-1) {
            tmpBg=elm.className;
            setClass(elm,tmpBg +' '+ this.elmEmphasizeCss);
            
        elm.onfocus=function(){  setClass(elm,tmpBg); this.onfocus=null;};
        }
    }
    }catch(e){}
};
};
var validator=new Validator();
