/*************************************
 * Configura o jQuery para detectar se ja possui o localStorage
 *************************************/
$.support.localStorage = typeof(window.localStorage) != 'undefined';

/*************************************
 * Configura o jQuery para detectar o Chrome e o firefox
 *************************************/
$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
$.browser.firefox = /firefox/.test(navigator.userAgent.toLowerCase());

/*************************************
 * Detecta o release do browser.
 *************************************/
if ($.browser.msie) {
    var r = /\\sMSIE\\s\/([\d.]+);/.exec(navigator.userAgent);
    if (r) $.browser.release = parseFloat(r[1]);
}
if ($.browser.firefox) {
    var r = /Firefox\/([\d.]+)/.exec(navigator.userAgent);
    if (r) $.browser.release = parseFloat(r[1]);
}
if ($.browser.chrome) {
    var r = /Chrome\/([\d.]+)/.exec(navigator.userAgent);
    if (r) $.browser.release = parseFloat(r[1]);
}

/*************************************
 * Objeto guarda variáveis globais do portal
 *************************************/
var PortalConfig = {
    Storage : {
        STORAGE_CONTENT_LEFT_ORDER : "STORAGE-CONTENT-LEFT-ORDER"
        ,STORAGE_CONTENT_RIGHT_ORDER : "STORAGE-CONTENT-RIGHT-ORDER"
        ,TIME_ALIVE_365_DAYS : new Date(new Date().getTime() + (365 * 24 * 60 * 60 * 1000))/*365 dias*/
    }
};

/*************************************
 * Objeto centraliza a parte de persistência de dados do lado client.
 * Devido ao mal funcionamento de cookies no Chrome, foi implementado
 * a gravação no localStorage que é uma implementação do HTML5 disponível a partir do chrome 4+, FF 3.5+ e IE8+.
 *************************************/
var PortalStorage = {
    settings : {key: '', data:null}
    , put : function(config) {
        if (this.isSupport()) {
            window.localStorage.setItem(config.key, config.data);
        } else {
            $.cookie(config.key, config.data, { path: (config.path ? '/' : config.path), expires: PortalConfig.Storage.TIME_ALIVE_365_DAYS});
        }
    }
    , get : function(config) {
        if (this.isSupport()) {
            return window.localStorage.getItem(config.key);
        } else {
            return $.cookie(config.key);
        }
    }
    , isSupport : function() {
        return ($.support.localStorage && (($.browser.chrome && $.browser.release >= 4)
                || ($.browser.firefox && $.browser.release >= 3.5)
                || ($.browser.msie && $.browser.release >= 8)));
    }
    , remove : function (config) {
        if (this.isSupport()) {
            return window.localStorage.removeItem(config.key);
        } else {
            return $.cookie(config.key, null, { path: (config.path ? '/' : config.path)});
        }
    }
};

function changeStyle(title) {
    var lnks = document.getElementsByTagName('link');
    for (var i = lnks.length - 1; i >= 0; i--) {
        if (lnks[i].getAttribute('rel').indexOf('style') > -1 && lnks[i].getAttribute('title')) {
            lnks[i].disabled = true;
            if (lnks[i].getAttribute('title') == title) lnks[i].disabled = false;
        }
    }
    jQuery.cookie("style", title, {path: "/"});
}

$(function() {
    var leftOrder = PortalStorage.get({key: PortalConfig.Storage.STORAGE_CONTENT_LEFT_ORDER});
    var rightOrder = PortalStorage.get({key: PortalConfig.Storage.STORAGE_CONTENT_RIGHT_ORDER});

    if (leftOrder) {//Recupera a posição dos elementos
        var array = leftOrder.split("|");
        var items = array[1].split(",");
        for (var k in items) $("#" + array[0]).append($("#" + items[k]));
    }

    if (rightOrder) {//Recupera a posição dos elementos
        var array = rightOrder.split("|");
        var items = array[1].split(",");
        for (var k in items) $("#" + array[0]).append($("#" + items[k]));
    }

    $("#content-left, #content-right").sortable({
        connectWith: '.connected',
        handle: 'h1',
        revert: true,
        update: function() {//Grava a posição dos elementos no client
            var divs = $(this).sortable("toArray");
            var obj = {};
            for (var key in divs) obj[$("#" + divs[key]).parent().attr('id')] = divs;

            var strObjectRepresentation = '';
            for (var k in obj) strObjectRepresentation = k + "|" + obj[k];

            var name = "STORAGE-" + ($(this).attr('id')).toUpperCase() + "-ORDER";
            PortalStorage.put({key: name, data: strObjectRepresentation});
        }
    }).disableSelection();

});
$(function() {
    var drawer = jQuery.cookie("accdrawer");
    if (drawer === undefined || drawer === null) {
        drawer = false;
    } else {
        drawer = parseInt(jQuery.cookie("accdrawer"));
    }
    $("#menu").accordion({
        active: drawer,
        collapsible: true,
        autoHeight: false,
        header: 'a.head',
        icons: {
            header: "item",
            headerSelected: "item-selected"
        },
        change: function(event, ui) {
            var index = jQuery(this).find("a.head").index(ui.newHeader[0]);
            if (index > -1) {
                jQuery.cookie("accdrawer", index, {path: "/"});
            } else {
                jQuery.cookie("accdrawer", null, {path: "/"});
            }
            jQuery.cookie("accdrawer2", null, {path: "/"});
            jQuery.cookie("accdrawer3", null, {path: "/"});
        }
    });
});

$(function() {
    var drawer2 = jQuery.cookie("accdrawer2");
    if (drawer2 === undefined || drawer2 === null) {
        drawer2 = false;
    } else {
        drawer2 = parseInt(jQuery.cookie("accdrawer2"));
    }

    $("#menu ul li ul").accordion({
        active: drawer2,
        collapsible: true,
        autoHeight: false,
        header: 'a.sub-head',
        change: function(event, ui) {

            var index = jQuery(this).find("a.sub-head").index(ui.newHeader[0]);
            if (index > -1) {
                jQuery.cookie("accdrawer2", index, {path: "/"});
            } else {
                jQuery.cookie("accdrawer2", null, {path: "/"});
            }
            jQuery.cookie("accdrawer3", null, {path: "/"})
        }
    });
});
$(function() {
    var drawer3 = jQuery.cookie("accdrawer3");
    if (drawer3 === undefined || drawer3 === null) {
        drawer3 = false;
    } else {
        drawer3 = parseInt(jQuery.cookie("accdrawer3"));
    }

    $("#menu ul li ul li ul li").accordion({
        active: drawer3,
        collapsible: true,
        autoHeight: false,
        header: 'a.sub-sub-head',
        change: function(event, ui) {
            var index = jQuery(this).parent().find("a.sub-sub-head").index(this);
            if (index > -1) {
                jQuery.cookie("accdrawer3", index, {path: "/"});
            } else {
                jQuery.cookie("accdrawer3", null, {path: "/"});
            }
        }
    });
});
$(function() {
    $("#text ul.sub").accordion({
        active: false,
        collapsible: true,
        autoHeight: false,
        header: 'a.section'
    });
});
$(function() {
    $("a#button").click(function () {
        $("#customization").toggle("blind", 500);
        return false;
    });
    $("#customization").hide();
});
$(function() {
    $("#show-noticias, #noticias a.button").click(function () {
        $("#noticias").toggle("highlight", 500, function() {
            var valor = $('#noticias').is(':visible');
            jQuery.cookie("noticias", valor, {path: "/", expires: PortalConfig.Storage.TIME_ALIVE_365_DAYS});
        });
        return false;
    });
    $("#show-destaques, #destaques a.button").click(function () {
        $("#destaques").toggle("highlight", 500, function() {
            var valor = $('#destaques').is(':visible');
            jQuery.cookie("destaques", valor, {path: "/", expires: PortalConfig.Storage.TIME_ALIVE_365_DAYS});
        });
        return false;
    });
    $("#show-acompanhamento-processual, #acompanhamento-processual a.button").click(function () {
        $("#acompanhamento-processual").toggle("highlight", 500, function() {
            var valor = $('#acompanhamento-processual').is(':visible');
            jQuery.cookie("acompanhamento-processual", valor, {path: "/", expires: PortalConfig.Storage.TIME_ALIVE_365_DAYS});
        });
        return false;
    });
    $("#show-pesquisa-jurisprudencia, #pesquisa-jurisprudencia a.button").click(function () {
        $("#pesquisa-jurisprudencia").toggle("highlight", 500, function() {
            var valor = $('#pesquisa-jurisprudencia').is(':visible');
            jQuery.cookie("pesquisa-jurisprudencia", valor, {path: "/", expires: PortalConfig.Storage.TIME_ALIVE_365_DAYS});
        });
        return false;
    });
    $("#show-comarcas-municipios, #comarcas-municipios a.button").click(function () {
        $("#comarcas-municipios").toggle("highlight", 500, function() {
            var valor = $('#comarcas-municipios').is(':visible');
            jQuery.cookie("comarcas-municipios", valor, {path: "/", expires: PortalConfig.Storage.TIME_ALIVE_365_DAYS});
        });
        return false;
    });
    $("#show-diario, #diario a.button").click(function () {
        $("#diario").toggle("highlight", 500, function() {
            var valor = $('#diario').is(':visible');
            jQuery.cookie("diario", valor, {path: "/", expires: PortalConfig.Storage.TIME_ALIVE_365_DAYS});
        });
        return false;
    });
    $("#show-portal-advogado, #portal-advogado a.button").click(function () {
        var value = $("#portal-advogado").toggle("highlight", 500, function() {
            var valor = $('#portal-advogado').is(':visible');
            jQuery.cookie("portal-advogado", valor, {path: "/", expires: PortalConfig.Storage.TIME_ALIVE_365_DAYS});
        });
        return false;
    });
    $("#reset").click(function () {
        $("#noticias, #destaques, #acompanhamento-processual, #pesquisa-jurisprudencia, #comarcas-municipios, #diario").fadeIn();
        return false;
    });
});
$(function() {
    $("#iframe").dialog({
        bgiframe: true,
        autoOpen: false,
        modal: true,
        width: 400,
        height: 300
    });
    $("#iframeNoticias").dialog({
        bgiframe: true,
        autoOpen: false,
        modal: true,
        width: 700,
        height: 430
    });
    $('a.button').click(function() {
        $('#iframe').dialog('open');
    });
    $('a.buttonNoticias').click(function() {
        $('#iframeNoticias').dialog('open');
    });
});

/**
 * Increase and Decrease Font Size.
 */
var min = 0.5;
var max = 1.5;
function increaseFontSize() {
    var p = document.getElementsByTagName("div");
    $('div.module')
    for (i = 0; i < p.length; i++) {
        if (p[i].className == 'interna' || p[i].className == 'module' || p[i].id == 'text') {
            if (p[i].style.fontSize) {
                var s = parseFloat(p[i].style.fontSize.replace("em", ""));
            } else {
                var s = 1.0;
                // if(p[i].className=='module') { var s = 1.0; } else { var s = 1.0; }
            }
            if (p[i].className == 'module') {
                jQuery.cookie("fontSizeHome", (s + 0.05), {path: "/"});
            } else {
                jQuery.cookie("fontSize", (s + 0.05), {path: "/"});
            }
            jQuery.cookie("fontSize", (s + 0.05), {path: "/"});

            if (s < max) {
                s += 0.05;
            }
            p[i].style.fontSize = s + "em"
        }
    }
}
function decreaseFontSize() {
    var p = document.getElementsByTagName("div");
    for (i = 0; i < p.length; i++) {
        if (p[i].className == 'interna' || p[i].className == 'module' || p[i].id == 'text') {
            if (p[i].style.fontSize) {
                var s = parseFloat(p[i].style.fontSize.replace("em", ""));
            } else {
                var s = 1.0;
                // if(p[i].className=='module') { var s = 1.0; } else { var s = 1.0; }
            }
            if (p[i].className == 'module') {
                jQuery.cookie("fontSizeHome", (s - 0.05), {path: "/"});
            } else {
                jQuery.cookie("fontSize", (s - 0.05), {path: "/"});
            }
            jQuery.cookie("fontSize", (s - 0.05), {path: "/"});
            if (s > min) {
                s -= 0.05;
            }
            p[i].style.fontSize = s + "em"
        }
    }
}
function actualizeFontSize(tipo) {
    var p = document.getElementsByTagName("div");
    for (i = 0; i < p.length; i++) {
        if (p[i].className == 'interna' || p[i].id == 'text' || p[i].className == 'module') {
            p[i].style.fontSize = s + "em";
        }
    }
}
function resetFontSize(tipo) {
    s = 1.0;
    jQuery.cookie("fontSize", s, {path: "/"});
    actualizeFontSize(tipo);
}
$(function() {
    // font Size Actualice
    if (jQuery.cookie("fontSize") != null) {
        s = parseFloat(jQuery.cookie("fontSize"));
        actualizeFontSize("inner");
    }

    if (! (jQuery.cookie("style") === undefined || jQuery.cookie("style") === null)) {
        changeStyle(jQuery.cookie("style"));
    }

    if (!(jQuery.cookie("noticias") === undefined || jQuery.cookie("noticias") === null)) {
        if (jQuery.cookie("noticias") == "false") {
            $("#show-noticias").click();
        }
    }
    if (!(jQuery.cookie("destaques") === undefined || jQuery.cookie("destaques") === null)) {
        if (jQuery.cookie("destaques") == "false") {
            $("#show-destaques").click();
        }
    }
    if (!(jQuery.cookie("acompanhamento-processual") === undefined || jQuery.cookie("acompanhamento-processual") === null)) {
        if (jQuery.cookie("acompanhamento-processual") == "false") {
            $("#show-acompanhamento-processual").click();
        }
    }
    if (!(jQuery.cookie("pesquisa-jurisprudencia") === undefined || jQuery.cookie("pesquisa-jurisprudencia") === null)) {
        if (jQuery.cookie("pesquisa-jurisprudencia") == "false") {
            $("#show-pesquisa-jurisprudencia").click();
        }
    }
    if (!(jQuery.cookie("comarcas-municipios") === undefined || jQuery.cookie("comarcas-municipios") === null)) {
        if (jQuery.cookie("comarcas-municipios") == "false") {
            $("#show-comarcas-municipios").click();
        }
    }
    if (!(jQuery.cookie("diario") === undefined || jQuery.cookie("diario") === null)) {
        if (jQuery.cookie("diario") == "false") {
            $("#show-diario").click();
        }
    }
});

function setIframeTitle(titulo) {
    $("span.ui-dialog-title").text(titulo);
}

function voltaPaginaTop() {
    if (self.pageYOffset) // all except Explorer
    {
        window.scroll(0, 0);
    }
    else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
    {
        window.scrollTo(0, 0);
    }
    else if (document.body) // all other Explorers
        {
            window.scrollTo(0, 0);
        }
}

/**
 * Functions Five Last Links
 */
function setLastFiveLinks() {

    var titlePage = document.title.split("|");
    var showLine = false;
    var i = 1;

    // Show Last Five URL's
    if (jQuery.cookie("TJRS_lasturl1")) {
        $("#oneclick option:eq(" + i + ")").attr("value", jQuery.cookie("TJRS_lasturl1")).text(jQuery.cookie("TJRS_lasturltitle1"));
        showLine = true;
        i++;
    } else {
        $("#oneclick option:eq(" + i + ")").remove();
    }

    if (jQuery.cookie("TJRS_lasturl2")) {
        $("#oneclick option:eq(" + i + ")").attr("value", jQuery.cookie("TJRS_lasturl2")).text(jQuery.cookie("TJRS_lasturltitle2"));
        showLine = true;
        i++;
    } else {
        $("#oneclick option:eq(" + i + ")").remove();
    }

    if (jQuery.cookie("TJRS_lasturl3")) {
        $("#oneclick option:eq(" + i + ")").attr("value", jQuery.cookie("TJRS_lasturl3")).text(jQuery.cookie("TJRS_lasturltitle3"));
        showLine = true;
        i++;
    } else {
        $("#oneclick option:eq(" + i + ")").remove();
    }

    if (jQuery.cookie("TJRS_lasturl4")) {
        $("#oneclick option:eq(" + i + ")").attr("value", jQuery.cookie("TJRS_lasturl4")).text(jQuery.cookie("TJRS_lasturltitle4"));
        showLine = true;
        i++;
    } else {
        $("#oneclick option:eq(" + i + ")").remove();
    }

    if (jQuery.cookie("TJRS_lasturl5")) {
        $("#oneclick option:eq(" + i + ")").attr("value", jQuery.cookie("TJRS_lasturl5")).text(jQuery.cookie("TJRS_lasturltitle5"));
        showLine = true;
        i++;
    } else {
        $("#oneclick option:eq(" + i + ")").remove();
    }

    if (showLine == false) {
        $("#oneclick option:eq(" + i + ")").remove();
    }

    // Save news URLs, only if not repeat
    if (jQuery.cookie("TJRS_lasturl1") != window.location) {
        jQuery.cookie("TJRS_lasturl5", jQuery.cookie("TJRS_lasturl4"), {path: "/"});
        jQuery.cookie("TJRS_lasturl4", jQuery.cookie("TJRS_lasturl3"), {path: "/"});
        jQuery.cookie("TJRS_lasturl3", jQuery.cookie("TJRS_lasturl2"), {path: "/"});
        jQuery.cookie("TJRS_lasturl2", jQuery.cookie("TJRS_lasturl1"), {path: "/"});
        jQuery.cookie("TJRS_lasturl1", window.location, {path: "/"});

        jQuery.cookie("TJRS_lasturltitle5", jQuery.cookie("TJRS_lasturltitle4"), {path: "/"});
        jQuery.cookie("TJRS_lasturltitle4", jQuery.cookie("TJRS_lasturltitle3"), {path: "/"});
        jQuery.cookie("TJRS_lasturltitle3", jQuery.cookie("TJRS_lasturltitle2"), {path: "/"});
        jQuery.cookie("TJRS_lasturltitle2", jQuery.cookie("TJRS_lasturltitle1"), {path: "/"});
        jQuery.cookie("TJRS_lasturltitle1", titlePage[0], {path: "/"});
    }
}
$(function() {
    setLastFiveLinks();
});


/**
 * Cookie plugin
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 31 * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*********************************
 Brazilian initialisation for the jQuery UI date picker plugin.
 Written by Leonildo Costa Silva (leocsilva@gmail.com).
 *************************************/
jQuery(function($) {
    $.datepicker.regional['pt-BR'] = {
        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','Sábado'],
        dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
        dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 0,
        buttonText: "Selecione uma data...",
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['pt-BR']);
});
/*********************************
 * Recupera a parametros de chamadas via GET. Giuliano Costa (giulianocosta@gmail.com)
 *************************************/
$.extend({
    getUrlVars: function() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    , getUrlVar: function(name) {
        return $.getUrlVars()[name];
    }
});
