$(document).ready(function() {

    //////////
    // Ajax //
    //////////
    // Opnião
    $(".opiniao ul li a").click(function() {
        var opniao = $(this).text();
        var nota = $(this).attr("rel");
        var id = $("#idConteudo").val();
        var tabela = $("#idConteudo").attr("name").split("|")[0];
        var campo = $("#idConteudo").attr("name").split("|")[1];
        $.post("ajax.asp?funcao=opniao", {
            opniao: opniao,
            nota: nota,
            conteudo: id,
            tabela: tabela,
            campo: campo
        }, function(resposta) {
            $(".opiniao").css({ width: "270px" }).html("Obrigado pelo seu voto!").addClass("alerta");
            alert("Obrigado pelo seu voto!");
        });
    });

    // Logoff
    $(".logoff").click(function() {
        $.post("ajax.asp?funcao=logoff",
			function(resposta) {
			    alert("Logoff efetuado com sucesso!");
			    location.href = "index.asp";
			}
		);
    });

    // Calendário
    var ajaxCalendario = function() {
        $("#calendario div").css({ height: "auto" });
        $("#calendario caption a").click(function() {
            $("#calendario div").css({ height: $("#calendario div").height() + "px" }).children().hide();
            $.post("ajax.asp?funcao=calendario&" + $(this).attr("rel"),
				function(resposta) {
				    $("#calendario div").html(resposta);
				    ajaxCalendario();
				}
			);
        });
    }
    ajaxCalendario();

    /////////////
    // Corners //
    /////////////
    $(".box1").corner("15px br bl");
    $(".box2").corner("20px");
    $(".box_controle").clone().insertAfter("#ordenacao");
    $(".box_controle").corner("10px");

    //////////////////////////
    // Indicação para amigo //
    //////////////////////////
    $(".abreForm").click(function() {
        var formulario = $(this).attr("rel");
        if (formulario != "comentario") {
            bloqueia({}, function() {
                $("#" + formulario)
					.css({ display: "block", opacity: "0" })
					.absoluteCenter({ limit: [30, 0, 30, 0], animation: false })
					.css({ display: "none", opacity: "1" })
					.fadeIn("fast")
					.absoluteCenter({ limit: [30, 0, 30, 0] });
            });
        } else {
            $(window).scrollTop($(document).height());
            $("#form_comentario").slideToggle('slow');
        }
    });
    $(".divForm a.fechar").click(function() {
        $(this).parents(".divForm").fadeOut("fast", function() {
            bloqueia({ evento: "fim" });
        });
    });

    //////////////////////
    // Tamanho do Texto //
    //////////////////////
    $("#tamanhoTexto a").click(function() {

        var direcao = $(this).text();

        var atual = $("body").attr("class");
        atual = typeof (atual) == "undefined" ? 1 : parseInt(atual.replace("tamanho", ""));

        var novo = direcao == "A+"
			? atual < 3 ? atual + 1 : 3
			: atual > 1 ? atual - 1 : 1
		;

        $("body").removeClass("tamanho" + atual).addClass("tamanho" + novo);

        $("#tamanhoTexto a").css({ color: "#000", cursor: "pointer" });
        if (novo == 3) $(this).css({ color: "#aaa", cursor: "default" });
        else if (novo == 1) $(this).css({ color: "#aaa", cursor: "default" });
    });
    $("#tamanhoTexto a:eq(1)").css({ color: "#aaa", cursor: "default" });

    /////////////
    // Tabelas //
    /////////////
    // Zebra
    $(".zebra").each(function() {
        $("tbody tr", this).each(function(i) {
            if (i % 2 == 1) {
                $(this).children().addClass("zebra");
            }
        });
    });

    // Destaca Célula
    $(".destacaCelula").each(function() {
        $("tbody td, tbody th", this).hover(function() {
            $(this).addClass("destacaCelula");
        }, function() {
            $(this).removeClass("destacaCelula");
        });
    });

    // Destaca Linha
    $(".destacaLinha").each(function() {
        $("tbody tr", this).hover(function() {
            $(this).children().addClass("destacaLinha");
        }, function() {
            $(this).children().removeClass("destacaLinha");
        });
    });

    ///////////////////////////
    // Adicionar a Favoritos //
    ///////////////////////////
    $(".addFav").click(function() {
        if (document.all) {
            if (window.confirm("Quer adicionar este site ao seu Favoritos?")) window.external.AddFavorite(location.href, document.title);
        } else {
            alert("Use CTRL+D para adicionar este site ao seu Favoritos!");
        }
    });

    /////////////////
    // Formulários //
    /////////////////

    // Data de nescimento do formulário de cadastro
    verificaNascimento = function(obj) {
        var valor = $(obj).val().split("/");
        valor = parseInt(valor[2] + valor[1] + valor[0] + "");

        var hoje = new Date();
        var ano = String(hoje.getYear() < 2000 ? hoje.getYear() + 1900 : hoje.getYear());
        var mes = hoje.getMonth() + 1;
        mes = mes < 10 ? "0" + String(mes) : String(mes);
        var dia = hoje.getDate();
        dia = dia < 10 ? "0" + String(dia) : String(dia);
        hoje = parseInt(ano + mes + dia);

        if ($(obj).val().length > 1) {
            validar.obj = $(obj);
            validar.valor = $(obj).val();
            validar.valido = false;

            if (valor >= hoje) {
                $(validar.obj).removeClass("form_ok").addClass("form_erro");
                validar.nome = $(validar.obj).attr("title");
                validar.msg = "deve ser menor que a data atual!";
                validar.exibeMsg();
                $("#DDATANASC").focus();
                return false;
            } else {
                $(validar.obj).removeClass("form_erro").addClass("form_ok");
                return true;
            }
        }
    }
    $("#DDATANASC").mask("99/99/9999").blur(function() {
        verificaNascimento($(this));
    });
    $("#frmcaduser").submit(function() {
        return verificaNascimento($("#DDATANASC"));
    });

    //////////////////
    // Exibir alert //
    //////////////////
    if ($("#showAlert").is("input")) {
        alert($("#showAlert").val());
        $("#showAlert").remove();
    }

    //////////////////
    // Meu Cadastro //
    //////////////////
    // Motivacional
    $("input[name='motivacional']").click(function() {
        var acao = $(this).val();
        $(this).parent().next().children("input").each(function() {
            this.checked = acao == "sim" ? true : false;
        });
    });
    $("#mot_domingo").parent().children("input").each(function() {
        if (!$("#mot_sim").get(0).checked) {
            $("#mot_nao").get(0).checked = this.checked == true ? false : true;
            $("#mot_sim").get(0).checked = this.checked == true ? true : false;
        }
    });

    // Remover conta
    $("#remove_conta").click(function() {
        if (this.checked && confirm("Deseja realmente remover esta conta do DiabeteNet?")) {
            alert("Para concluir a remoção da conta, clique em atualizar cadastro.");
        } else {
            this.checked = false;
        }
    });

    // Alteração de e-mail
    var CEMAILoriginal = $("#CEMAIL").val();
    $("#meuCadastro").submit(function() {

        var CEMAILnovo = $("#CEMAIL").val();

        if (CEMAILoriginal != CEMAILnovo) {
            if (confirm("ATENÇÃO!\n\nApós a alteração do e-mail, seu acesso ficará bloqueado até que uma nova verificação seja feita neste novo e-mail.\n\nVocê realmente deseja alterar o e-mail?")) {
                $(this).append('<input id="alterar_email" name="alterar_email" type="hidden" value="sim" />');
                return true;
            } else {
                return false;
            }
        }

    });

    // Selects
    $(".selectOutros").change(function() {
        if (this.value == "99") {
            $(this).parent().next().slideDown("slow").children("input").addClass("validar");
        } else {
            $(this).parent().next().slideUp("slow").children("input").removeClass("validar");
        }
    });
    $("#CRELACAODIABETESOUTROS, #CCOMOCONHECEUOUTROS").removeClass("validar");

    ///////////////////////
    // Imprimir conteúdo //
    ///////////////////////
    if ($(".imprimirConteudo").is("a")) {
        window.print();
        $(".imprimirConteudo").click(function() {
            if (window.print()) window.print();
        });
    } else {
        $("#imprimirConteudo").attr("target", "_blank");
    }

    //////////
    // Abas //
    //////////
    dmAbas = {
        autor: "Diego Marques - 2008",

        // Variáveis
        ativo: 0,

        // Inicialização
        init: function() {
            $(".interna ul.abas a").each(function(i) {
                $(this).click(function() {
                    dmAbas.muda(i);
                });
            });
        },

        // Muda aba
        muda: function(alvo) {
            if (alvo != dmAbas.ativo) {

                dmAbas.ativo = alvo;

                $(".interna ul.abas a.ativo").removeClass("ativo");
                $(".interna ul.abas a:eq(" + alvo + ")").addClass("ativo");

                $(".interna div.abas div.ativo").removeClass("ativo").slideUp("slow");
                $(".interna div.abas div:eq(" + alvo + ")").addClass("ativo").slideDown("slow");
            }
        }
    }
    dmAbas.init();

    /////////////
    // Abinhas //
    /////////////
    $(".abinhas a").each(function(i) {
        $(this).click(function() {
            $("a.ativo", $(this).parent().parent()).removeClass("ativo");
            $(this).addClass("ativo")
            $(this).parent().parent().siblings(":visible").hide();
            $(this).parent().parent().siblings(":eq(" + i + ")").show();
        });
    });

    if ($("#banner_2").attr("class") == "roche_old") {
        /////////////////////
        // Banner Roche 1 //
        ///////////////////
        $("#banner_2").addFlash({
            src: "banner/roche.swf",
            width: 468,
            height: 60,
            title: "Clique e saiba mais"
        });
    } else if ($("#banner_2").attr("class") == "roche") {
        /////////////////////
        // Banner Roche 2 //
        ///////////////////
        $("#banner_2").css({ background: "url(imagens/roche_468x60.gif) no-repeat 0 0", width: "468px", height: "60px", cursor: "pointer" }).click(function() {
            window.open("http://www.diabetenet.com.br/redir.asp?link=http://www.meujeitonanodeveravida.com.br");
        });
    } else {
        //////////////////////
        // Banner Mediatall //
        //////////////////////
        $("#banner_2").addFlash({
            src: "banner/mediatall.swf",
            width: 728,
            height: 90,
            title: "Clique e saiba mais"
        });
    }

});