$(document).ready( function(){

	/***
	*
	*	Funções 
	*	Desenvolvido por Diego Marques
	*
	*	Índice:
	*
	*	Log para Debug............................: 21
	*	Redimencionar por classe..................: 43
	*	Link Ativo................................: 68
	*	Blank.....................................: 80
	*	Preload automático de imagens.............: 94
	*	Classe Voltar.............................: 204
	*	Tira bordas do Flash no IE................: 217
	*
	****/

	/***
	*	:: Log para Debug ::
	*	:: Diego Marques -  ::
	*	:: 2007 ::
	*	ex:
	*		l("testando");
	*
	*	OBS: Funciona apenas no Firefox com o plugin Firebug.
	***/
	//l = function(x){ if(window.console) console.log(x); }
	l = function(x){
		var consoleIE = false
		if(window.console){
			console.log(x);
		}else if(consoleIE){
			if(!$("#dmDebug").is("div")){
				$("body").append("<div id=\"dmDebug\" style=\"width:"+($(window).width()-50+"px")+"; border:1px solid #000; position:absolute; bottom:0; left:0; height:150px; overflow:auto; filter:alpha(opacity=80); font-size:12px; padding:5px; font-family:Tahoma, Arial, Helvetica, sans-serif; background:#fff; z-index:99999;\"></div>");
			}
			$("#dmDebug").append("<p style=\"margin:0; border-bottom:1px dashed #000; color: #000; font-weight: bold;\">"+x+"</p>");
		}
	}
	
	/***
	*	:: Redimencionar por classe ::
	*	:: Diego Marques -  ::
	*	:: 2007 ::
	*
	*	Redimenciona um elemente setando uma classe para ele.
	*	ex:
	*		<div class="width150">teste</div>
	*		<div class="height5050">teste</div>
	***/
	$("*[@class*=width]").each(function(){
		var dmClasses = $(this).attr("class").split(" ");
		$.each(dmClasses, function(i,n){
			if(n.indexOf("width") != -1){ dmTamanho = dmClasses[i].replace("width",""); }
		});
		$(this).css("width",dmTamanho+"px");
	});
	$("*[@class*=height]").each(function(){
		var dmClasses = $(this).attr("class").split(" ");
		$.each(dmClasses, function(i,n){
			if(n.indexOf("height") != -1){ dmTamanho = dmClasses[i].replace("height",""); }
		});
		$(this).css("height",dmTamanho+"px");
	});

	/***
	*	:: Link Ativo ::
	*	:: Diego Marques -  ::
	*	:: 2007 ::
	*
	*	Adiciona a classe "ativo" para o link que tiver o destino (href) identico à pagina aberta
	***/
	dmPaginaAtivo = window.location+"";
	dmPaginaAtivo = dmPaginaAtivo.split("/").pop();
	if(dmPaginaAtivo != "")
		$("a[@href="+dmPaginaAtivo+"]").addClass("ativo");
		
	/***
	*	:: Blank ::
	*	:: Diego Marques -  ::
	*	:: 2007 ::
	*
	*	Abre um link em uma nova janela.
	*	ex:
	*		<a href="http://www.diegomarqu.es/" title="Diego Marques" class="blank"></a>
	***/
	$(".blank").click(function(){
		window.open($(this).attr("href"));
		return false;
	});
	
	/***
	*	:: Classe Voltar ::
	*	:: Diego Marques -  ::
	*	:: 2007 ::
	*
	*	Adiciona um evento em um objeto que volta no histórico no navegador
	*	Ex.: <a href="javascript:void(0);" title="voltar" class="voltar">voltar</a>
	***/
	$(".voltar").click(function(){
		window.history.go(-1);
		return false;
	});

	/***
	*	:: Tira bordas do Flash no IE ::
	*	:: Diego Marques -  ::
	*	:: 2008 ::
	*
	*	Retira as bordas pontilhadas do flash no Internet Explorer
	*	Ex.: 	$("#flash").addFlash({
	*				src: "swf/banner2.swf",
	*				width: 584,
	*				height: 201,
	*				title: ""
	*			});
	***/
	$.extend({
		addFlash: {
			version: 1.1,
			autor: "Diego Marques - ",
			defaults: {
				src: "",
				width: 100,
				height: 50,
				title: "",
				quality: "high",
				menu: "false",
				wmode: "transparent"
			}
		}
	});
	$.fn.extend({
		addFlash: function(options){
			options = $.extend({}, $.addFlash.defaults, options);
			return this.each(function(){
				if(options.src != ""){
					var flash = '<object type="application/x-shockwave-flash" data="'+options.src+'?clicktag=./" width="'+options.width+'" height="'+options.height+'" tabindex="0" title="'+options.title+'">'
					flash += '<param name="movie" value="'+options.src+'?clicktag=./" />'
					flash += '<param name="quality" value="'+options.quality+'" />'
					flash += '<param name="menu" value="'+options.allowFullScreen+'" />'
					flash += '<param name="wmode" value="'+options.wmode+'" />'
					flash += '<p>Para visualizar este conteúdo corretamente, é necessário ter o <a title="Clique para instalar o flash player" href="http://www.macromedia.com/shockwave/download/alternates/" rel="nofollow">Flash Player</a> instalado.</p>'
					flash += '</object>'
					var id = $(this).attr("id");
					var conteudo = document.getElementById(id)
					conteudo.innerHTML = flash
				}
			});
		}
	});
	
	/***
	*	:: Exibe div de bloqueio ::
	*	:: Diego Marques - Agência DMK ::
	*	:: 2007 ::
	*
	*	Função que abre uma div cobrindo toda a tela bloqueando o site, com função de callback.
	*	ex:
	*		bloqueia({ speed: "slow", bgcolor: "#000" });
	*		bloqueia({ speed: "slow", evento: "fim" });
	*
	*	OBS: Nescessário plugin Dimension.
	***/
	bloqueia = function(options,callback){
		var defaults = {
			id: "bloqueio",
			evento: "inicio",
			bgColor: "#000",
			opacity: "0.5",
			speed: "normal",
			zIndex: "100"
		}
		options = $.fn.extend({},defaults,options);
		
		if((options.id == "" || options.id == "bloqueio") && !$("#bloqueio").is("div")) $("body").append("<div id=\"bloqueio\" style=\"display:none\"></div>");

		var altura = $(document).height() > $(window).height() ? $(document).height() : $(window).height();
		
		if(options.evento == "inicio"){
			$("#"+options.id).css({
				background:options.bgColor,
				height:altura,
				left:"0",
				opacity:options.opacity,
				position:"absolute",
				top:"0",
				width:"100%",
				zIndex:options.zIndex
			}).fadeIn(options.speed, function(){ if(typeof(callback) != "undefined"){ callback(); } });
			$(window).resize(function(){
				altura = $(document).height() > $(window).height() ? $(document).height() : $(window).height();
				$("#"+options.id).css({height:altura});
			});
		}else{
			$("#"+options.id).fadeOut(options.speed, function(){ if(typeof(callback) != "undefined"){ callback(); } });
		}
	}
	
	// Alinhamento da div
	$.fn.extend({
		absoluteCenter: function(options, speed, callback){
			var defaults = {
				autor: "Diego Marques",
				dellay: 100,
				limitTop: 0,
				limitRight: 0,
				limitBottom: 0,
				limitLeft: 0,
				limit: null,
				animation: true
			}
			options = $.extend({}, defaults, options);
			
			if(options.limit != null){
				if(typeof(options.limit) == "object"){
					options.limitTop = typeof(options.limit[0]) != "undefined" ? options.limit[0] : options.limitTop;
					options.limitRight = typeof(options.limit[1]) != "undefined" ? options.limit[1] : options.limitRight;
					options.limitBottom = typeof(options.limit[2]) != "undefined" ? options.limit[2] : options.limitBottom;
					options.limitLeft = typeof(options.limit[3]) != "undefined" ? options.limit[3] : options.limitLeft;
				}else{
					options.limitTop = options.limit;
					options.limitRight = options.limit;
					options.limitBottom = options.limit;
					options.limitLeft = options.limit;
				}
			}
			
			speed = typeof(speed) == "undefined" ? "fast" : speed;
			
			return this.each(function(){

				var obj = this;
				var timeOut = null;
				
				var ajustaScroll = function(){
					
					if($(obj).css("display") == "none") $(window).unbind("scroll",ajustaScroll).unbind("resize",ajustaScroll);
					
					var altura = parseInt($(obj).outerHeight());
					var largura = parseInt($(obj).outerWidth());
					
					var limiteC = parseInt($(obj).css("top"));
					var limiteB = limiteC + altura;
					var limiteE = parseInt($(obj).css("left"));
					var limiteD = limiteE + largura;
					
					var scrollTop = parseInt($(window).scrollTop());
					var scrollLeft = parseInt($(window).scrollLeft());
					var janelaAltura = parseInt($(window).height());
					var janelaLargura = parseInt($(window).width());
					
					var documentoAltura = parseInt($("body").outerHeight());
					var documentoLargura = parseInt($(document).width());
					
					var top = janelaAltura > altura
						? parseInt(scrollTop + (( janelaAltura / 2 ) - parseInt(altura / 2)))
						: scrollTop < (limiteC - options.limitTop)
							? scrollTop + options.limitTop
							: (scrollTop + janelaAltura) > (limiteB + options.limitBottom)
								? scrollTop - (altura - janelaAltura) - options.limitBottom
								: limiteC
					;
					top = (top + altura) > documentoAltura ? documentoAltura - altura : top;
					
					var left = janelaLargura > largura
						? parseInt(scrollLeft + (( janelaLargura / 2 ) - parseInt(largura / 2)))
						: scrollLeft < (limiteE - options.limitLeft)
							? scrollLeft + options.limitLeft
							: (scrollLeft + janelaLargura) > (limiteD + options.limitRight)
								? scrollLeft - (largura - janelaLargura) - options.limitRight
								: limiteE
					;
					left = (left + largura) > documentoLargura ? documentoLargura - largura : left;

					if(options.animation){
						clearTimeout(timeOut);
						timeOut = setTimeout(function(){
							$(obj).animate({top:top+"px",left:left+"px"},speed,function(){ if(typeof(callback) != "undefined") callback(); });
						},options.dellay);
					}else{
						$(obj).css({top:top+"px",left:left+"px"});
					}
				}
				ajustaScroll();
				
				if(options.animation) $(window).scroll(ajustaScroll).resize(ajustaScroll);
			});
		}
	});
	
// Tree List //
	$(".treeList").each(function(){
		$(".hide",this).prev("a").click(function(){
			$(this).next(".hide").slideToggle("slow");
		});
	});
});
/***
*	:: Log para Debug ::
*	:: Diego Marques ::
*	:: 2007 ::
*
*	l(<Mensagem>,<true ou false para IE>);
*
*	Exibe um log para Debug.
*	ex:
*		l("testando");
*		l("testando",true);
***/
function l(x,consoleIE){
    consoleIE = typeof (consoleIE) == "undefined" ? false : consoleIE;
    if (window.loadFirebugConsole) window.loadFirebugConsole();
	if(window.console){
	    console.log(x);
	} else if (window._firebug) {
	    _firebug.log(x);
	}else if(consoleIE){
		if(!$("#dmDebug").is("div"))
			$("body").append("<div id=\"dmDebug\" style=\"width:"+($(window).width()-50+"px")+"; border:1px solid #000; position:absolute; bottom:0; left:0; height:150px; overflow:auto; filter:alpha(opacity=80); font-size:12px; padding:5px; font-family:Tahoma, Arial, Helvetica, sans-serif; background:#fff; z-index:99999;\"></div>");
		$("#dmDebug").append("<p style=\"margin:0; border-bottom:1px dashed #000; color: #000; font-weight: bold;\">"+x+"</p>").scrollTop(9999);
	}
}

function boxMsg(msg,tipo) {
	$("#boxMsg").remove();
	if(tipo=='sucesso'){
		$("body").append("<div id=\"boxMsg\" class=\"boxMsg-sucesso\" style=\"display:none;\"><div class=\"wrap\"><span>" + msg + "</span><a href=\"javascript:void()\" title=\"Fechar\">Fechar</a></div></div>");
	}else{
		$("body").append("<div id=\"boxMsg\" style=\"display:none;\"><div class=\"wrap\"><span>" + msg + "</span><a href=\"javascript:void()\" title=\"Fechar\">Fechar</a></div></div>");
	}
	$("#boxMsg").stop().fadeIn("fast", function(){ setTimeout(function() { escondeBoxMsg(); }, 10000); }).live("click", function() { escondeBoxMsg(); });
}
function escondeBoxMsg() {
	$("#boxMsg").animate({'top':'-200px'}, function() { $(this).remove(); });
}

$(document).ready(function() {
    /***
    *	:: Validação Genérica ::
    *	:: Diego Marques ::
    *	:: 2008 ::
    *
    *	Validação genérica para formulários. Para adicionar uma validação em um campo, atribuir a classe
    *	"validar" e no atributo "title", acrescentar as regras.
    *
    *	Regras:
    *	-------
    *		min:<inteiro>
    *			Quantidade mínima de caracteres.
    *			{min:1}
    *
    *		max:<inteiro>
    *			Quantidade máxima de caracteres
    *			{max:5}
    *
    *		igualA:<string>
    *			Igual a valor de um outro campo ou a string
    *			{igualA:'teste'} ou {igualA:'#texte'}
    *		
    *		diferenteDe:<string>
    *			Diferente do valor de um outro campo ou a string
    *			{diferenteDe:'teste'} ou {diferenteDe:'#texte'}
    *		
    *		tipo:<string>
    *			Define o tipo obrigatório
    *			"inteiro" / "int": Numérico inteiro
    *			"email" / "e-mail": E-mail
    *			"data": Data tipo dd/mm/aaaa
    *			"obrigatório": Preenchimento obrigatório
    *
    *	Ex.:
    *	----
    *		<input id="teste" name="teste" type="text" class="validar" title="Teste{min:5,tipo:'email',max:50,diferenteDe:'exemplo@dominio.com.br'}" />
    *
    *	Métodos:
    *	--------
    *		validar.init()
    *			Inicializa a validação aplicando os eventos.
    *		validar.form(<string opcional>)
    *			Executa a validação em um determinado formulário.
    *		validar.campos(<objetos>)
    *			Executa a validação em um conjunto de objetos específicos.
    ***/
    validar = {
        autor: "Diego Marques - 2010",
        versao: "2.20.4.10",

        // Variáveis
        timeout: setTimeout("", 1),

        // Inicialização
        init: function() {
            // Campo
            $(".validar").each(function() {
                var regras = eval("[" + $(this).attr("title").replace(/^[^\{]+/, "") + "]")[0];
                $(this).attr("title", $(this).attr("title").replace(/{[^\{]+$/, ""));

                this.validar_regras = regras;

                $(this).not(".calendario").unbind('blur', validar.campo).blur(validar.campo);

				// Máscaras
                if (typeof (regras) != "undefined" && typeof (regras.mascara) != "undefined") {
                    switch (regras.mascara) {
                        case "R$": $(this).maskMoney({ symbol: "R$", decimal: ",", thousands: "." }); break;
                        case "$": $(this).maskMoney({ symbol: "$", decimal: ",", thousands: "." }); break;
                        default: $(this).mask(regras.mascara); break;
                    }
                }
            });

            // Formulário
            $("form:not(.naoValidar) input.validar:first-child").each(function() {
                $(this).parents("form:first").unbind('submit', validar.form).submit(validar.form);
            });
        },

        // Valida o campo
        campo: function(obj) {
            obj = $(this).is(":input") ? $(this) : $(obj);
            var valido = true;

            if (obj.hasClass("validar") && obj.is(":visible") ? obj.is("select") ? obj.children().length > 0 : true : false) {
                $.each(obj[0].validar_regras, function(c, v) {
                    if (c != "mascara") {
                        valido = validar.executa_regra[c](obj, v);
                        if (!valido) {
                            validar.exibeMsg(obj);
                            return false;
                        } else {
                            var tipo = obj.attr('type');
                            obj.removeClass("frm-erro").addClass("frm-ok");
                        }
                    }
                });
                if (valido)
                    validar.escondeMsg();
            }

            return valido;
        },

        // Valida formulário
        form: function(obj) {
            try {
                if ($(this).is("form"))
                    obj = $(this);
            } catch (e) {
                if ($(obj).is("form"))
                    obj = $(obj);
            }
            var valido;
            $(".validar", obj).each(function() {
                valido = validar.campo(this);
                return valido;
            });
            return valido;
        },

        // Valida um array de campos
        campos: function(obj) {
            var valido;
            $(obj).each(function() {
                valido = validar.campo(this);
                return valido;
            });
            return valido;
        },

        // Executa uma regra de validação
        executa_regra: {

            // Quantidade mínima de caracteres
            min: function(obj, regra) {
                var r = $(obj).val().length >= parseInt(regra);
                $(obj)[0].msg = r ? null : "deve ser preenchido com no mínimo <strong>" + regra + "</strong> caracteres.";
                return r;
            },

            // Quantidade máxima de caracteres
            max: function(obj, regra) {
                //var r = $(obj).val().length <= parseInt(regra);
                //$(obj)[0].msg = r ? null : "deve ser preenchido com no máximo <strong>" + regra + "</strong> caracteres.";
                $(obj).val($(obj).val().substring(0, regra));               
                return true;
            },

            // Maior que inteiro ou data
            maiorQue: function(obj, regra) {
                var valor = $(obj).val();
                var r;
                if (typeof (regra) == "number") {
                    l(typeof (regra));
                    r = valor > regra;
                    l(valor > regra);
                } else {
                    if (regra == "hoje") {
                        var hoje = new Date();
                        hoje = hoje.getDate() + "/" + (hoje.getMonth() + 1) + "/" + hoje.getFullYear();
                        r = dmDate.dateDiff(hoje, validar.valor) < 0;
                    }
                }
                $(obj)[0].msg = r ? null : "deve ser maior que <strong>" + (regra == "hoje" ? hoje : regra) + "</strong>.";
                return r;
            },

            // Igual a campo ou string
            igualA: function(obj, regra) {
                var valor = $(obj).val();
                var r;
                regra = regra.indexOf("#") == -1 ? regra : $(regra).val();
                r = regra == valor;
                $(obj)[0].msg = r ? null : "não foi preenchido corretamente.";
                return r;
            },

            // Diferente de campo ou string
            diferenteDe: function(obj, regra) {
                var valor = $(obj).val();
                var r;
                regra = regra.indexOf("#") == -1 ? regra : $(regra).val();
                r = regra != valor;
                $(obj)[0].msg = r ? null : "não foi preenchido corretamente.";
                return r;
            },

            // Obrigatorio                                                                                             
            obrigatorio: function(obj, regra) {
                if (regra) {
                    r = $(obj).val() == null ? false : $(obj).val().length > 0;
                    $(obj)[0].msg = r ? null : "é de preenchimento obrigatório.";
                } else {
                    r = true;
                }
                return r;
            },

            // Definições de tipos
            tipo: function(obj, regra) {
                var valor = $(obj).val();
                var r, msg;

                if (valor != "") {
                    switch (regra) {

                        // Numérico inteiro                                                                                                                                             
                        case "inteiro": case "int":
                            var expressao = /^\d+$/;
                            r = expressao.test(valor)
                            msg = "deve ser preenchido com um <strong>número inteiro</strong>.";
                            break;

                        // E-mail                                                                                                                                             
                        case "email": case "e-mail":
                            var expressao = /^[a-zA-Z0-9]{1}([\._a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+){1,3}$/;
                            r = expressao.test(valor);
                            msg = "não é um <strong>e-mail válido</strong>.";
                            break;

                        // Data tipo dd/mm/aaaa                                                                                                                                             
                        case "data":
                            var expressao = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)\d{2}$/;
                            r = expressao.test(valor);
                            msg = "não é uma data válida, utilize o formato <strong>dd/mm/aaaa</strong>.";
                            break;

                        // CPF                                                                                                                                              
                        case "cpf": case "CPF":
                            var cpf = valor.replace(/[^0-9]/g, "");
                            if (cpf.length >= 11) {
                                if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") {
                                    r = false;
                                } else {
                                    var a = [];
                                    var b = new Number;
                                    var c = 11;
                                    for (i = 0; i < 11; i++) {
                                        a[i] = cpf.charAt(i);
                                        if (i < 9) b += (a[i] * --c);
                                    }
                                    if ((x = b % 11) < 2) { a[9] = 0; } else { a[9] = 11 - x; }
                                    b = 0;
                                    c = 11;
                                    for (y = 0; y < 10; y++) b += (a[y] * c--);
                                    if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11 - x; }
                                    r = ((cpf.charAt(9) == a[9]) && (cpf.charAt(10) == a[10]));
                                }
                            } else {
                                r = false;
                            }
                            msg = "é um número de CPF invalido!";
                            break;

                        // CNPJ                                                                                                                                              
                        case "cnpj": case "CNPJ":
                            var cnpj = valor.replace(/[^0-9]/g, "");
                            if (cnpj.length >= 14) {
                                var a = [];
                                var b = new Number;
                                var c = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
                                for (i = 0; i < 12; i++) {
                                    a[i] = cnpj.charAt(i);
                                    b += a[i] * c[i + 1];
                                }
                                if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11 - x }
                                b = 0;
                                for (y = 0; y < 13; y++) {
                                    b += (a[y] * c[y]);
                                }
                                if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11 - x; }
                                r = ((cnpj.charAt(12) == a[12]) && (cnpj.charAt(13) == a[13]));
                            } else {
                                r = false;
                            }
                            msg = "é um número de CNPJ inválido.";
                            break;
                    }
                } else {
                    r = true;
                }
                $(obj)[0].msg = r ? null : msg;
                return r;
            }
        },

        exibeMsg: function(obj) {
            clearTimeout(validar.timeout);
            $(obj).removeClass("frm-ok").addClass("frm-erro"); //.focus();
            var tipo = obj.attr('type');
            var msg = "O campo <strong>\"" + $(obj).attr("title") + "\"</strong> " + $(obj)[0].msg // Mensagem
            l(msg);

            $("#boxMsg").remove();
            $("body").append("<div id=\"boxMsg\" style=\"display:none;\"><div class=\"wrap\"><span>" + msg + "</span><a href=\"javascript:void()\" title=\"Fechar\">Fechar</a></div></div>");
            $("#boxMsg").stop().fadeIn("fast", function() {
                clearTimeout(validar.timeout);
                validar.timeout = setTimeout(function() { validar.escondeMsg(); }, 10000);
            }).click(validar.escondeMsg);
        },

        escondeMsg: function() {
            clearTimeout(validar.timeout);
            $("#boxMsg").animate({ 'top': '-200px' }, function() { $(this).remove(); });
        }
    }
    validar.init();
});

/***
*	:: Função de Ajax ::
*	:: Diego Marques ::
*	:: 2008 ::
*
*	Função que executa um ajax.
*	Opções:
*		arquivo:<string>
*			Qual arquivo será chamado com ou sem extenção, a extenção padrão é .asp.
*		acao:<string>
*			Envia uma variável GET com nome padrão de "acao".
*		querystring:<string>
*			Envia dados obrigatoriamente via querystring, ex.: "id=1&produto=teste"
*		dados:<string ou objeto>
*			Envia dados via get ou post, dependendo do método de envio, ex.: "id=1&produto=teste" ou {id:1,produto:"teste"}.
*		carregando:<inteiro>
*			Tipo de carregando, padrão: 1.
*		aoIniciar:<função>
*			Executa função ao iniciar a requisição ajax.
*		aoConcluir:<função>
*			Executa função ao concluir a requisição ajax.
*		formulario:<seletor css>
*			Recupera os dados dos campos de um formulário e envia.
*		retornarEm:<seletor css>
*			Retorna dados para um determinado objeto.
*		metodo:<string>
*			Método de envio dos dados, get ou post, padrão: "GET".
*		caminho:<string>
*			Caminho que será chamado o arquivo, padrão: "biblioteca/ajax/".
*
*	ex:
*		ajax({
*			arquivo: "produtos.asp",
*			acao: "listarProdutos",
*			aoConcluir: function(retorno){
*				if(retorno != "erro"){
*					$("#tabela").html(retorno);
*				}
*			}
*		});
***/
function ajax(opcoes){
	
	// Valores padrão das opções e variáveis
	opcoes = $.extend({}, {
		arquivo: "",
		acao: "",
		querystring: "",
		dados: "",
		carregando: 2,
		aoIniciar: "",
		aoConcluir: "",
		aoFalhar: "",
		formulario: "",
		retornarEm: "",
		metodo: "get",
		tipoDados: "html",
		erro: false,
		caminho: "ajax/",
		mostraErros: function(){ if(opcoes.erro != false) alert("Um erro ocorreu!\n\nPor favor, contate o administrador deste sistema e informe o seguinte erro:\n\n\"" + opcoes.erro + "\""); }
	}, opcoes);
	var er, dados;
	
	// Verificação de erros
	if(opcoes.arquivo == "") opcoes.erro = "Não foi informado o arquivo para ser carregado.";
	
	if(!opcoes.erro){
		// Caminho do arquivo
		er = /(\.php|\.asp|\.aspx|\.htm|\.html|\.js|\.jsp)/;
		opcoes.arquivo = !er.test(opcoes.arquivo) ? opcoes.arquivo += ".asp" : opcoes.arquivo;
		
		// Ação
		opcoes.arquivo = opcoes.acao != "" ? opcoes.arquivo + "?acao=" + opcoes.acao : opcoes.arquivo;

		// Get
		var contra_senha = "contra_senha=" + $("#contra_senha").val();
		opcoes.querystring = opcoes.querystring == "" ? contra_senha : "&" + contra_senha;
		opcoes.arquivo = opcoes.querystring != "" ? opcoes.arquivo.indexOf("?") != -1 ? opcoes.arquivo + "&" + opcoes.querystring : opcoes.arquivo + "?" + opcoes.querystring : opcoes.arquivo;
		
		// Dados
		dados = opcoes.formulario != "" ? $(opcoes.formulario).is("form") ? $(opcoes.formulario).serializeArray()[0] : "" : "";
		dados = opcoes.dados != "" ? $.merge(opcoes.dados, dados) : dados;

		// Método get ou post
		opcoes.metodo = opcoes.formulario != "" ? $(opcoes.formulario).is("form") ? typeof($(opcoes.formulario).attr("method")) != "undefined" ? $(opcoes.formulario).attr("method") : opcoes.metodo : opcoes.metodo : opcoes.metodo;

		// Carregando
		var ajaxCarregando = function(acao) {

		    if (acao == "inicio") {
		        // Carregando - Início
		        switch (opcoes.carregando) {
		            case 1:
		                var now = new Date();
		                $("#log span.tipo1")
							.html("[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] " + "Carregando dados...")
							.css({
							    background: "url(imagens/carregando5.gif) no-repeat 0 center",
							    paddingLeft: "20px"
							})
						;
		                bloqueia({
		                    bgColor: "url(imagens/blank.gif)",
		                    cursor: "wait",
		                    animate: false
		                });
		                break;
		            case 2:
		                break;
		        }
		    } else {
		        // Carregando - Fim
		        switch (opcoes.carregando) {
		            case 1:
		                bloqueia({
		                    evento: "fim",
		                    animate: false
		                });
		                var now = new Date();
		                $("#log span.tipo1")
							.html("[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] " + "Concluído!")
							.css({
							    background: "none",
							    paddingLeft: "0"
							})
						;
		                break;
		            case 2:
		                break;
		        }
		    }
		}
		ajaxCarregando("inicio");
		
		// Executa o ajax
		var debugErros = false;
		$.ajax({
		    url: opcoes.caminho + opcoes.arquivo,
		    type: opcoes.metodo,
		    data: dados,
		    dataType: opcoes.tipoDados,
		    beforeSend: function() { if (typeof (opcoes.aoIniciar) == "function") opcoes.aoIniciar(); },
		    success: function(retorno) {
		        if (retorno == "nao_logado" || retorno == '"nao_logado"') {
		            alert("Acesso não autorizado!");
		            window.location.href = window.location.href;
		        } else if (retorno == "nao_autorizado" || retorno == '"nao_autorizado"') {
		            alert("Você não está autorizado a executar esta ação.\n\nPara mais informações, entre em contato com o administrador do sistema.");
		            if (opcoes.aoFalhar != "") opcoes.aoFalhar(XMLHttpRequest); // Ao falhar
		        } else {
		            if (opcoes.retornarEm != "") $(opcoes.retornarEm).html(retorno); // Retornar em
		            ajaxCarregando("fim"); // Carregando
		            if (typeof (opcoes.aoConcluir) == "function") opcoes.aoConcluir(retorno); // Ao concluir
		        }
		    },
		    error: function(XMLHttpRequest) {
		        if (opcoes.aoFalhar != "") opcoes.aoFalhar(XMLHttpRequest); // Ao falhar
		        if (debugErros) {
		            try {
		                var regExp = new RegExp('(<body)(.|\n|\f|\r|\t|\v|\s| )*', 'gim');
		                var texto = XMLHttpRequest.responseText;
		                if (texto != null) {
		                    texto = texto.match(regExp) == null ? "" : texto.match(regExp)[0];
		                    regExp = new RegExp('(.|\n|\f|\r|\t|\v|\s| )*(\/body>)', 'gim');
		                    texto = texto.match(regExp) == null ? "" : texto.match(regExp)[0];
		                    texto = texto.replace(/<(\/)?body(.)*>/g, "").replace(/(<(\/)?script[^>]*>)/g, "<!--$1-->");
		                }
		                var div = $('<div title="Clique para fechar">');
		                //bloqueia();
		                $(div)
							.css({
							    border: "1px solid #000",
							    position: "absolute",
							    top: "100px",
							    left: "50%",
							    height: "500px",
							    width: "770px",
							    margin: "0 0 0 -392px",
							    padding: "10px",
							    background: "#fff url(imagens/erro-ajax-bg.jpg) no-repeat center",
							    cursor: "pointer",
							    zIndex: "999999",
							    display: "none"
							})
							.html(texto)
							.prepend('<a href="javascript:void(0);" title="Fechar" style="float:right;">X Fechar</a>')
							.click(function() {
							    $(this).fadeOut('fast');
							    //bloqueia({ evento: "fim" });
							});
		                $("body").append(div);
		                $("*", div).css("position", "static");
		                $(div).fadeIn('fast');
		            } catch (e) {
		                opcoes.erro = "Erro ao acessar o arquivo remoto.";
		                //opcoes.mostraErros();
		                ajaxCarregando("fim"); // Carregando
		            }
		        } else {
		            opcoes.erro = "Erro ao acessar o arquivo remoto.";
		            //opcoes.mostraErros();
		            ajaxCarregando("fim"); // Carregando
		        }
		    }
		});
	}

	// Exibe mensagem de erro caso ocorra
	opcoes.mostraErros();
}
