/**
 * jQuery.fn.verify
 *
 * - url        The URL to send the POST/GET AJAX request to
 * - verifying  The CSS class to toggle while verification is taking place
 * - valid      The CSS class to toggle if verification is successful
 * - invalid    The CSS class to toggle if verification fails
 * - method     Set to either get or post
 * 
 * The url should expect to receive either a GET or POST variable named 
 * 'value'. In that will be the value of the input this is attached to. It 
 * should then respond with either '1' or '0'. '1' means that the value is 
 * valid, while '0' (or any non '1' response) means the value is invalid.
 * 
 * Additionally, the classes verifying + 'Parent', valid + 'Parent', and
 * invalid + 'Parent' are toggled appropriately. This allows you to add a
 * background icon to the container element if you so wish for instance.
 * 
 * @author      Joe Stump <joe@joestump.net>
 * @param       string      url
 * @param       array       options
 */
jQuery.fn.verify = function(url, options) {
    $(this).attr('autocomplete', 'off');

    function reset(input) {
        $("*[valid='"+$(input).attr('valid')+"']").removeClass(input.settings.verifying)
                .removeClass(input.settings.valid)    
                .removeClass(input.settings.invalid);

        $("*[valid='"+$(input).attr('valid')+"']").parent().removeClass(input.settings.verifying + 'Parent')
                         .removeClass(input.settings.valid + 'Parent')
                         .removeClass(input.settings.invalid + 'Parent');
    }

    function response(res, input, params) {
		reset(input);
		var err='', info='';
		if (res){
			x = new Array();
			x=res.split('|');
			err=x[0];
			info=x[1];
			if (!info){
				info='';
			}
			if (info[0]=='['){
				var arrinfo = eval('(' + info + ')');
				info='';
				for (vr in arrinfo){
					info=info + arrinfo[vr].cidade + ', ';
				}
			}
			if (x[2]){
				$(input).val(x[2]);
			}
		}
		if (params.valid=='uf'){ // preencher o autocomplete do campo cidade
			//$('#cidade').show();
			//$('#cidade').val('').setOptions({data: arrinfo});
			//$('#cidade').setOptions({data: arrinfo});
			//$('#infogeral').html(info);
			//info='';
		}
		if (params.valid=='reservas'){
			$('#feedbackcontainer').show('normal');
		}

		if (params.valid=='captchareply'){ // isso fará que o button não envie o form se tiver erro na digitação do anti-spam
			if (err && $('#captchareply').val()!='anti-spam' ){
				$("#submitform").attr("disabled","disabled");
			}else{
				if (info!='' && info=='ok') {
					info='';
					$('#captchareplycontainer').hide();
					$('#imgcaptchareply').hide();
				}
				$('#submitform').removeAttr("disabled");
			}
		}

		$('#verify_err_'+$(input).attr('valid')).html(err);
		if (info!='notyet'){
			$('#verify_info_'+$(input).attr('valid')).html(info);
		}

		if (err>''||info=='notyet') {
			info=(info=='notyet'?'':info);
            $("*[valid='"+$(input).attr('valid')+"']").addClass(input.settings.invalid);
            $("*[valid='"+$(input).attr('valid')+"']").parent().addClass(input.settings.invalid + 'Parent');
        } else {
			$("*[valid='"+$(input).attr('valid')+"']").addClass(input.settings.valid);
            $("*[valid='"+$(input).attr('valid')+"']").parent().addClass(input.settings.valid + 'Parent');
        }
    }

    this.each(function() {
        var settings = jQuery.extend({
            url         : url,
            verifying   : "",
            valid       : "",
            invalid     : "",
            method      : "get"
        }, options || {});
        
        this.timer    = undefined;
        this.settings = settings;
		var input;
        $(this).keyup(function() {

			if (this.timer) {
                clearTimeout(this.timer);
                this.timer = undefined
            }

            if (this.value.length == 0) {
                reset(this);
                return;
            }

            input = this;
            this.timer = setTimeout(function() {
                params = {
                    id      : $(input).attr('id'),
                    value   : $(input).val(),
					valid	: $(input).attr('valid')
                };
				if (input=='uf'){
					$('#cidade').hide();
				}
                $(input).addClass(input.settings.verifying);
                if (input.settings.method == "get") {
                    $.get(input.settings.url, params, function(result) {
                        response(result, input, params);
                    });
                } else {
                    $.post(input.settings.url, params, function(result) {
                        response(result, input, params);
                    });
                }
            }, 1500);
        });
		$(this).blur( function() {
			$(this).keyup();
		});
		$(this).keyup();		
    });

    return this;
};



