$(document).ready(function () {
    //Carrega o Google Analytics
    try {
        var pageTracker = _gat._getTracker("UA-5522457-1");
        pageTracker._initData(); pageTracker._trackPageview();
    } catch (e) { }

    //Abre links externos em novas abas
    $("a").click(function () {
        if ($(this).attr("href") != undefined && ($(this).attr("href").indexOf("http://") == 0 || $(this).attr("href").indexOf("https://") == 0 || $(this).attr("href").indexOf("mailto://") == 0)) {
            window.open($(this).attr("href"));

            return false;
        }
    });

    //Cria botão default para busca
    $("#topo-busca input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).parent().find("input[type=image]").click();
            return false;
        }
    });

    //Aplica efeito slide up e down para cada item do menu principal
    $("#menu ul li").find("ul").parent().each(function () {
        $(this).hover(
            function () {
                if ($(this).children("ul").queue().length <= 1)
                    $(this).children("ul").slideDown(200);
            },
            function () {
                $(this).children("ul").slideUp(100);
            });
    });
    $("#menu>ul").find("ul").css({ display: 'none', visibility: 'visible' });
    $("#menu ul li a").click(function () { if ($(this).attr("href") == "#") return false; });

    //Cria menu lateral retrátil
    $("ul.menu-lateral:first").accordion({
        autoHeight: false,
        navigation: true,
        active: $.cookie("menuLateralActiveIndex") == null ? 0 : parseInt($.cookie("menuLateralActiveIndex")),
        change: function (event, ui) {
            //Grava em um cookie o item ativo
            $.cookie("menuLateralActiveIndex", $(this).accordion("option", "active"))
        }
    });

    //Formata a nuvem de tags
    if ($(".tagcloud").length) {
        $(".tagcloud").tagcloud({ type: "list", colormin: "f8a7ab", colormax: "ed2e38" });
    }

    //Aplica mascaras
    $("p input[id*=textboxLogin], p input[id*=textboxUser], input[id*=textboxCpf]").mask("999.999.999-99");
    $("p input[id*=textboxTelefone]").mask("(99)9999-9999");
    $("p input.textbox-date, .data").mask("99/99/9999");

    //Aplica efeitos jQuery UI
    $(".form").tabs();
    $(".search-tabs").tabs({ cookie: { expires: 30} });
    $(".buttonset").buttonset();
    $("input[type=button]").button();
    $("input[type=submit]").button();
    $(".data, p input.textbox-date").datepicker({ closeText: 'Fechar',
        prevText: '&#x3c;Anterior',
        nextText: 'Pr&oacute;ximo&#x3e;',
        currentText: 'Hoje',
        monthNames: ['Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
        monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
        dayNames: ['Domingo', 'Segunda-feira', 'Ter&ccedil;a-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sabado'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        changeMonth: true,
        changeYear: true,
        yearRange: 'c-100:c+10'
    });

    //Acrescenta confirmação em todos os botões com a classe duplicate
    $("input.duplicate").click(function (e) {
        return confirm(e, "Confirma a duplicação dos itens selecionados?");
    });

    //Acrescenta confirmação em todos os botões com a classe delete
    $("input.delete").click(function (e) {
        return confirm(e, "Confirma a exclusão dos itens selecionados?\nATENÇÃO: Esta ação é irreversível");
    });

    //Cria botão default para formulários
    $(".login input, .filters input, .filters select, .form input, .form select").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).parents(".login, .filters, .form").find("input[type=submit]:first").click();
            return false;
        }
    });

    //Aplica efeito para filtros
    $("a.filters").button({ icons: { primary: null, secondary: "ui-icon-triangle-1-s"} }).addClass("ui-button-text-icons").appendTo("div.grid p.toolbar");
    $("div.filters").appendTo("div.grid p.toolbar");
    $("a.filters").unbind();
    $("a.filters").click(function () {
        var filters = $(this).parent().children("div.filters");

        $(this).blur();

        if (filters.css("display") == "none") {
            $(this).button({ icons: { primary: null, secondary: "ui-icon-triangle-1-n"} }).addClass("ui-button-text-icons");

            filters.slideDown(200);
            filters.find("input:first").focus();
        }
        else {
            $(this).button({ icons: { primary: null, secondary: "ui-icon-triangle-1-s"} }).addClass("ui-button-text-icons");

            filters.slideUp(200);
        }
    });

    //Insere o ckeditor para edição html
    if ($("p.html").length) {
        //Esconde o textarea e mostra mensagem enquanto carrega os scripts
        $("p.html").append("<em>Carregando editor HTML...</em>");
        $("p.html textarea").css("display", "none");

        //Define o base path do ckeditor
        window.CKEDITOR_BASEPATH = '/ckeditor/';

        //Carrega o CKEditor por demanda
        $.getScript('/ckeditor/ckeditor.js', function () {
            //Define a configuração do editor
            var config = {
                toolbar:
                    [
                        ["Templates", "Image", "Table", "HorizontalRule"],
			            ["Bold", "Italic", "Strike"],
			            ["JustifyLeft", "JustifyCenter", "JustifyRight"],
			            ["NumberedList", "BulletedList"],
			            ["Outdent", "Indent", "Blockquote"],
                        ["Undo", "Redo"],
                        ["Cut", "Copy", "Paste"],
			            ["Link", "Unlink"],
                        ["Format"],
                        ["Source"]
		            ],
                forcePasteAsPlainText: true,
                templates_files: ["/ckeditor-templates/templates.js"],
                format_tags: "p;h1;h2;h3;div",
                filebrowserBrowseUrl: "/gestao-de-conteudo/gerenciador-de-arquivos",
                filebrowserWindowWidth: 545,
                filebrowserWindowHeight: 545,
                filebrowserWindowFeatures: 'resizable=no,scrollbars=no',
                disableObjectResizing: true,
                scayt_autoStartup: false,
                templates_replaceContent: false,
                toolbarCanCollapse: false,
                resize_enabled: false,
                htmlEncodeOutput: true
            };

            //Inicializa editor para cada campo html            
            $("p.html textarea").each(function () {
                //Remove as intancias do editor caso elas já existam
                if (CKEDITOR.instances[$(this).attr("id")] != null)
                    CKEDITOR.remove(CKEDITOR.instances[$(this).attr("id")]);

                //Inicializa o editor
                CKEDITOR.replace($(this).attr("id"), config);
            });

            //Personaliza os dialogos do CKEDITOR
            CKEDITOR.on("dialogDefinition", function (e) {
                var name = e.data.name;
                var definition = e.data.definition;

                if (name == "link") {
                    definition.minHeight = "0";
                    definition.getContents("info").remove("linkType");
                    definition.removeContents("target");
                    definition.removeContents("advanced");
                }
                else if (name == "image") {
                    definition.minHeight = "0";
                    definition.getContents("info").get("txtUrl")["validate"] = null;
                    definition.getContents("info").get("txtWidth").onChange = function () { if (this.getValue() != "") this.setValue(""); }
                    definition.getContents("info").get("txtHeight").onChange = function () { if (this.getValue() != "") this.setValue(""); }
                    definition.getContents("info").elements[2]["style"] = "display:none;";
                    definition.removeContents("Link");
                    definition.removeContents("advanced");
                }
                else if (name == "table" || name == "tableProperties") {
                    definition.minHeight = "0";
                    definition.getContents("info").get("txtCols")["default"] = "3";
                    definition.getContents("info").get("txtRows")["default"] = "3";
                    definition.getContents("info").get("txtCellPad")["default"] = "5";
                    definition.getContents("info").get("txtCellSpace")["default"] = "0";
                    definition.getContents("info").remove("txtBorder");
                    definition.getContents("info").remove("cmbAlign");
                    definition.getContents("info").remove("txtWidth");
                    definition.getContents("info").remove("cmbWidthType");
                    definition.getContents("info").remove("txtHeight");
                    definition.getContents("info").remove("cmbHeightType");
                    definition.getContents("info").remove("htmlHeightType");
                    definition.getContents("info").elements[0].children[0].children[2].html = "";
                    definition.getContents("info").elements[0].children[1].children[2].html = "";
                }
                else if (name == "creatediv" || name == "editdiv") {
                    definition.minHeight = "0";
                    definition.getContents("info").elements[1] = definition.getContents("advanced").elements[0].children[1];
                    definition.getContents("info").elements[0]["style"] = "display:none;";
                    definition.removeContents("advanced");
                }
            });

            //Remove mensagem de carga do editor
            $("p.html em").remove()
        });
    }
});

function ValidaCPF(source, arguments) {
    var cpf = arguments.Value;
    var soma;
    var resto;
    soma = 0;

    cpf = cpf.replace(".", "");
    cpf = cpf.replace(".", "");
    cpf = cpf.replace("-", "");

    if ((cpf == "00000000000") || (cpf == "11111111111") ||
       (cpf == "22222222222") || (cpf == "33333333333") ||
       (cpf == "44444444444") || (cpf == "55555555555") ||
       (cpf == "66666666666") || (cpf == "77777777777") ||
       (cpf == "88888888888") || (cpf == "99999999999"))
        arguments.IsValid = false;

    for (i = 1; i <= 9; i++)
        soma = soma + parseInt(cpf.substring(i - 1, i)) * (11 - i);

    resto = (soma * 10) % 11;

    if ((resto == 10) || (resto == 11))
        resto = 0;

    if (resto != parseInt(cpf.substring(9, 10)))
        arguments.IsValid = false;

    soma = 0;

    for (i = 1; i <= 10; i++)
        soma = soma + parseInt(cpf.substring(i - 1, i)) * (12 - i);

    resto = (soma * 10) % 11;

    if ((resto == 10) || (resto == 11))
        resto = 0;

    if (resto != parseInt(cpf.substring(10, 11)))
        arguments.IsValid = false;
}
