/*
 * jquery.verify
 * 
 * Author: Mattias Ormestad (based by the code by Joe Stump <joe@joestump.net>)
 * Website: http://www.iconscience.se
 *
 */
 
(function($) {
    $.fn.verify = function(options) {
        var settings = jQuery.extend({
            verifying   : "verifying",
            valid       : "valid",
            invalid     : "invalid"
        }, options || {});
        
        return this.each(function() {
        	$(this).attr('novalidate');
			var verifyFields = $(this).find('input[type!="submit"][type!="button"][type!="file"], textarea');
			
			verifyFields.each(function() {
		        this.timer    = undefined;
		        this.settings = settings;
		
		        doVerify(this);
		        $(this).keyup(function() { doVerify(this); });
			});
        });
    };

	function doVerify(that) {
        if (that.timer) {
            clearTimeout(that.timer);
            that.timer = undefined
        }

        if (that.value.length == 0 && $(that).attr('required') == false) {
            reset(that);
            return false;
        }

        that.timer = setTimeout(function() {
            params = {
            	validatemethod	: "ajax",
                name			: $(that).attr('name'),
                type			: $(that).attr('type'),
                required		: $(that).attr('required'),
                value			: $(that).val() 
            };

            $(that).addClass(that.settings.verifying);
            
            $.post(that.settings.url, params, function(result) {
                response(result, that);
            });
        }, 1000);
	}

    function reset(input) {
        var nameArray = $(input).attr('name').split(':');
        var varname = nameArray[0];
    	$('span#' + varname).remove();
    	
        $(input).removeClass(input.settings.verifying)
                .removeClass(input.settings.valid)    
                .removeClass(input.settings.invalid);
    }

    function response(response, input) {
        reset(input);

        var varname = $.parseJSON(response).varname;
        var errormessage = $.parseJSON(response).error;
        var validated = $.parseJSON(response).validated;
        var errorbox = '<span class="error" id="' + varname + '">' + errormessage + '</span>';

        if (validated == 1) {
            $(input).addClass(input.settings.valid);
        } else {
            $(input).addClass(input.settings.invalid);
            $(input).after(errorbox);
        }
    }
})(jQuery);
