(function($) {
    /*
    Validation Singleton
    */
    var Validation = function() {
        
        var rules = {
            
			email : {
				check: function( inputField ) {
				value = getValue( inputField );
                   if(value)
                     return testPattern(value,".+@.+\..+");
                   return true;
               },
				msg : "Enter a valid e-mail address.",
				hint : 'aa11@provider.com'
			
            },

            url : {

				check: function( inputField ) {
				value = getValue( inputField );

                   if( value )
                   		return testPattern(value,"https?://(.+\.)+.{2,4}(/.*)?");
						return false;
               },
				msg : "Enter a valid URL.",
				hint : 'http(s)://websitename.com'
            },

            required : {
				check: function( inputField ) {
				value = getValue( inputField );
                   if(value.length > 0 ){
                       return true;
					}
                   else {
                       return false;
					}
               },
               msg : "This field is required.",
            }
        }

		var getValue = function( field ){
			return field.val();
		}
		
        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];
            }
        }

    }


   
    /* 
    Form factory 
    */
    var Form = function(form) {
			
        var fields = [];
		this.myForm = form;
        form.find("input[validation], textarea[validation]").each(function() {
			
			var tmpField = new Field(this);
            fields.push( tmpField );
        });

        this.fields = fields;
    }

    Form.prototype = {

        validate : function() {

            for(field in this.fields) {

					this.fields[field].validate();
            }
        },

        isValid : function() {
            var valid = true;
			for(field in this.fields) {
				valid = this.fields[field].field.valid && valid;
            }
			return valid;
		},

		submitForm : function() {
			var data = this.myForm.serialize();
			if( $.siteController ){
				data = 'frompage=' + $.siteController.contentId + '&' + data;
			}
			$.ajax({
				'url' : "content/entry.php",
				'type' : 'POST',
				'data' : data,
				success : function( response ){
		     			console.log( response );
		   				}
				});

		}

    }
    

	var Image = function( obj ){
		//statics
		this.imageDir = "style/images/validation_icons/";
		this.defType = 'required';
		this.defImage = 'def.png';
		// variables
		this.field = obj.field;

		this.imageStateDir = function(){
				var types = this.field.attr("validation").split(" ");
				for( type in types) {
					if( types[type] !== this.defType ){
						return this.imageDir + types[type] + '/';
					}
				}
			return this.imageDir + this.defType + '/';

		};
		
		this.validStates = {
				'true'	: 'oke.png',
				'false'	: 'nok.png',
				'undefined' : 'unk.png',
				'null' : this.defImage
			};
		
		this.getsrc = function(){
				if( this.field.val() === '' && this.field.required === false ){
					return  this.imageDir + 'empty.png';
				}
				return  this.imageStateDir() + this.validStates[ this.field.valid ];
			};
				
		this.addImage();
		
	}

	Image.prototype = {
		addImage : function(){
				
				this.image = document.createElement( 'IMG' );
				this.image.id = this.field[0].id + '_fb';
				this.image.src = this.getsrc();
				this.field.parent().append( this.image );
				this.image.validStates = this.validStates;
				this.image = $( this.image );
				return this;
		},
		
		imageType : function(){ 
			var obj = this,
			types = obj.field.attr("validation").split(" ");		
            for (var type in types) {
				if( type !== obj.defType ){
					return type;
				}
			}
			return obj.defType;
		},

		Update : function() {
				var src = this.getsrc();
				$( this.image ).fadeOut( 150 , function() {
								$( this ).attr( { 'src' : src });
												}).fadeIn( 100 );

		}

	}
	
    /* 
    Field factory 
    */
    var Field = function( field ) {
        this.field = $(field);
        this.field.valid = null;
        this.field.required = false;
        this.attach("blur");
		this.setRequired();
		this.feedBackImage = new Image( this );
    }

    Field.prototype = {
     
        attach : function( event ) {
       
			var obj = this;
			obj.field.bind( event ,function() {
				return obj.validate();
			});
        },
		
		setRequired : function() {
			var obj = this,
                field = obj.field,
                types = field.attr("validation").split(" ");
            for (var type in types) {
				if( types[type] === 'required' ){
					field.required = true;
				}
			return types;
			}
		},
			
        validate : function() {
            
			var field = this.field,
				types = this.setRequired(),
                container = field.parent(),
                errors = [];
			// set valid to true before checking the actual input
			this.field.valid = true;
            for (var type in types) {
				
				var rule = $.Validation.getRule(types[type]);
				this.field.valid = rule.check( field ) && this.field.valid;
				if( this.field.valid === false ) {
					this.feedBackImage.image.bind( 'mouseover' , function(){
						$( '#formerror' ).html( $( this ).attr( 'title' ) );
					});
					this.feedBackImage.image.attr( {
													'title' : rule.msg,
													'alt' : rule.msg
													} );
				}
			}
		this.feedBackImage.Update();
		}
    }

    /* 
    Validation extends jQuery prototype
    */
    $.extend($.fn, {
        
        validation : function() {
            
            var validator = new Form($(this));
            $.data($(this)[0], 'validator', validator);
            
            $(this).bind("submit", function(e) {
                validator.validate();
                e.preventDefault();
				if( validator.isValid() ) {
					validator.submitForm();
                }
				else{
					$( '#formerror' ).html( 'vul de velden correct in!' );
					return false;
				}
            });
        },

        validate : function() {
            var validator = $.data($(this)[0], 'validator');
            validator.validate();
            return validator.isValid();
            
        }
    });
	$.Validation = new Validation();
})(jQuery);
