/**
* Lightweight validation plugin.
* Tamas Gal - 09.01.2010
* 
* Example: <input type="text" name="email" validation="required email" />
* Usage: $("#myForm").validation();
* CSS formating: through the errorlist class
*/

(function($) {
    var Validation = function() {
        var rules = {
           
            email : {
               check: function(value) {
                   if(value) return testPattern(value,".+@.+\..+");
                   return true;
               },
               msg : "Az email cím hibás vagy nem valós."
            },
            number : {
               check: function(value) {
                   if(value) return testPattern(value,"[0-9]+");
                   return true;
               },
               msg : "A mezőben csak számok lehetnek."
            },
            decimal : {
                check: function(value) {
                    if(value) return testPattern(value,"[0-9.,]+");
                    return true;
                },
                msg : "A mezőben csak valós szám lehet (tizedesponttal vagy -vesszővel)."
             },
            containsdigit : {
                check: function(value) {
                    if(value) {
                    	return (value.search(/\d+/) > -1);
                    }
                    return true;
                },
                msg : "A mezőnek tartalmaznia kell számot is."
             },
            url : {
               check : function(value) {
                   if(value) return testPattern(value,"https?://(.+\.)+.{2,4}(/.*)?");
                   return true;
               },
               msg : "Az URL nem valós."
            },
            selected : {
            	check : function(value) {
            		if(value == 'Válasszon') return false;
            		else return true;
            	},
            	msg : "Kérem válasszon!"
            },
            date : {
            	check : function(value) {
            		if(value) return testPattern(value,"(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])");
            		return true;
            	},
            	msg : "A dátum nem valós!"
            },
            required : {             
               check: function(value) {
                   if(value) return true;
                   else return false;
               },
               msg : "Kötelező mező."
            }
        };
        var testPattern = function(value, pattern) {
            var regExp = new RegExp("^"+pattern+"$","");
            return regExp.test(value);
        };
        return {
            addRule : function(name, rule) {
                rules[name] = rule;
            },
            getRule : function(name) {
                return rules[name];
            }
        };
    };
    
    /** 
    * Bind to form
    */
    var Form = function(form) {
        var fields = [];
        form.find("input[validation], textarea[validation], select[validation]").each(function() {
            fields.push(new Field(this));
        });
        this.fields = fields;
    }
    Form.prototype = {
        validate : function() {
            for(field in this.fields) {              
                this.fields[field].validate();
            }
        },
        isValid : function() {
            for(field in this.fields) {
                if(!this.fields[field].valid) {
                    this.fields[field].field.focus();
                    return false;
                }
            }
            return true;
        }
    }
    
    /**
    * Bind to fields
    */
    var Field = function(field) {
        this.field = $(field);
        this.valid = false;
        this.attach("change");
    }
    Field.prototype = {
        attach : function(event) {
            var obj = this;
            if(event == "change") {
                obj.field.bind("change",function() {
                    return obj.validate();
                });
            }
            if(event == "keyup") {
                obj.field.bind("keyup",function(e) {
                    return obj.validate();
                });
            }
        },
        validate : function() {
            var obj = this,
                field = obj.field,
                errorClass = "errorlist",
                errorlist = $(document.createElement("ul")).addClass(errorClass),
                types = field.attr("validation").split(" "),
                container = field.parent(),
                errors = []; 
            field.next(".errorlist").remove();
            for (var type in types) {
                var rule = $.Validation.getRule(types[type]);
                if(!rule.check(field.val())) {
                    container.addClass("error");
                    errors.push(rule.msg);
                }
            }
            if(errors.length) {
                obj.field.unbind("keyup")
                obj.attach("keyup");
                field.after(errorlist.empty());
                for(error in errors) {
                    errorlist.append("<li>"+ errors[error] +"</li>");        
                }
                obj.valid = false;
            } 
            else {
                errorlist.remove();
                container.removeClass("error");
                obj.valid = true;
            }
        }
    }
    
    /** 
    * Extend the jQuery with validation
    */
    $.extend($.fn, {
        validationOnSubmit : function() { //Form checking binded to submit
            var validator = new Form($(this));
            $.data($(this)[0], 'validator', validator);
            $(this).bind("submit", function(e) {
                validator.validate();
                if(!validator.isValid()) {
                    e.preventDefault();
                }
            });
        },
		validation : function() { //Inline Form checking
            var validator = new Form($(this));
            $.data($(this)[0], 'validator', validator);
            validator.validate();
            return validator.isValid();
        },
        validate : function() { //Inline field checking
            var validator = $.data($(this)[0], 'validator');
            validator.validate();
            return validator.isValid();
        }
    });
    $.Validation = new Validation();
})(jQuery);
