

(function($){
	
	var opts, objs;
	
    $.fn.validate = function(settings){
		
		opts = jQuery.extend({imgCorrect:	0, imgWrong:	0, validf: false},settings);
		objs = this;
		
		$.fn.validate.initialize();
		return this.each(function(){
			ob = $(this).find(':input[valcode]');
			$(this).submit(function(){ $(this).validate.checkForm(this); return opts.validf;});
			
			ob.each(function(){
				$(this).blur(function(){ $(this).validate.checkField(this); $('#sam-validate').hide(); return false; });
				$(this).focus(function(){ info = $(this).validate.checkField(this); $(this).validate.showToolTip(this,info); return false; });
				switch(this.tagName.toLowerCase())
				{
					case 'input':
					case 'textarea': $(this).keyup(function(){ info = $(this).validate.checkField(this); $(this).validate.showToolTip(this,info); return false; });
										break;
					case 'select': $(this).change(function(){ info = $(this).validate.checkField(this); $(this).validate.showToolTip(this,info); return false; });
										break;
				}
			});
		});

	};
	
	$.fn.validate.checkForm = function(obj){
		ob = $(obj).find(':input[valcode]');
		ob.each(function(){
			info = $(this).validate.checkField(this);
			clas = $(this).parent().attr('class');
			str = '';
			title = this.getAttribute('title');
			for(i=0;i<info.length;i++){
				if(!info[i][1])
					str += $(this).validate.getErrorMessage(info[i][0],title) +'\n';
			}
			if(str!=''){
				alert(str);
				this.focus();
				opts.validf = false;
				return false;
			}			
			opts.validf = true;
			return true;
		});
	};
	
	$.fn.validate.initialize = function(){
		$('body').append('<div id="sam-validate"><div><div><div id="sam-validate-in"></div></div></div></div>');		
	};
	
	
	$.fn.validate.checkField = function(obj){
		switch(obj.tagName.toLowerCase())
		{
			case 'input': rval = this.checkInputField(obj); break;
			case 'select': rval = this.checkInputField(obj); break;
			case 'textarea': break;
		}
		return rval;
		
	};
	
	$.fn.validate.checkInputField = function(obj){
		var keys = obj.getAttribute('valcode').split('_');
		var info = [];
		if($.inArray('b',keys)>=0 && obj.value==''){ info.push(new Array('',true)); this.displayInfo(obj,true); return info; }
		
		var valid = true;
		var flag = true;
		
		for(i=0;i<keys.length;i++){
			switch(keys[i]){
				case '!b': valid = !this.isEmpty(obj.value); break;
				case 's': valid = this.isString(obj.value); break;
				case 'e': valid = this.isEmail(obj.value); break;
				case 'no': valid = this.isNumber(obj.value); break;
				case 'sel': valid = this.isSelected(obj); break;
				case 'ck': valid = this.isChecked(obj); break;
				default:
						str = keys[i];
						if(str.substring(0,3)=='pas')
							valid = this.confirmPassword(obj,str.substring(3,str.length));
						break;
			}
			
			if(!valid) flag=false;
			info.push(new Array(keys[i],valid));
		}
		this.displayInfo(obj,flag);
		return info;
	};
	
	$.fn.validate.showToolTip = function(obj,info){
		var spos = $(obj).parent().position();
		var title = obj.getAttribute('title');
		$('#sam-validate-in').empty();
		for(i=0;i<info.length;i++){
			if(info[i][1]) cls = 'info_ok'; else cls = 'info_err';
			$('#sam-validate-in').append('<a class="'+cls+'">'+ this.getErrorMessage(info[i][0],title) +'</a>');
		}		
		$('#sam-validate').stop();
		$('#sam-validate').css({top: spos.top, left: spos.left + $(obj).parent().width()+15}).show();
	};
	
	$.fn.validate.displayInfo = function(obj,status){
		if(status){
			$(obj).parent().removeClass('info_err').addClass('info_ok'); return true;
		}else{
			$(obj).parent().removeClass('info_ok').addClass('info_err'); return false;
		}
	};
	
	
	
	$.fn.validate.isEmpty = function(str){ if($.trim(str)=='') return true; else return false; };
	$.fn.validate.isString = function(str){
		var test = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
		if (!str.match(test)) return true; else return false;
	};
	$.fn.validate.isEmail = function(str){
		var test = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!str.match(test)) return false; else return true;
	};
	$.fn.validate.isSelected = function(obj){
		if (obj.value!='') return true; else return false;
	};
	
	$.fn.validate.isChecked = function(obj){
		if (obj.checked) return true; else return false;
	};
	
	$.fn.validate.confirmPassword = function(obj,str){
		obj2 = $('#'+str);
		if (obj.value==obj2.attr('value')) return true; else return false;
		
	}
	
	$.fn.validate.isNumber = function(str){
		var test = /^\d+$/;
		if (!str.match(test)) return false; else return true;
	};
	
	$.fn.validate.getErrorMessage = function(code,title){
		var str ='';		
		switch(code){			
			case '!b': str = title + ' can not be empty'; break;
			case 's': str = 'no special characters allowed'; break;
			case 'e': str = title + ' must be a valid email';	 break;
			case 'no': str = title + ' must be a valid number';	 break;
			case 'sel': str = 'Select a ' + title;	 break;	
			case 'ck': str = 'Please check "' + title + '" checkbox';	 break;	
			default:
					if(code.substring(0,3)=='pas')
						str = 'Password mismatched';	 break;	
		}
		return str;
	}
	
	
})(jQuery);

/*

 username: function(o) {
          var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(user)) {
             doValidate(o);
            } else {
             doError(o,'no special characters allowed');
            };
        },
        password: function(o) {
          var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(pass)) {
             doValidate(o);
            } else {
             doError(o,'no special characters allowed');
            };
        },
        email: function(o) {
          var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
           if (o.value.match(email)) {
              doSuccess(o);
            } else {
              doError(o,'not a valid email');
            };
        },
        dob: function(o) {
          var dob  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
            if (o.value.match(dob)) {
              doSuccess(o);
            } else {
              doError(o,'not a valid date');
            };
        }

*/

$(document).ready(function () {							
    $('form.samvalidate').validate();
	
});
