/*************************************
 * Seletor por regex
 *************************************/
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}
/*************************************
 * Função para verificar a existência de elemento(s)  (giulianocosta@gmail.com)
 *************************************/
jQuery.fn.exists = function(){return ($(this).length > 0);}
/*************************************
 * Configura o jQuery para detectar se ja possui o localStorage
 *************************************/
$.support.localStorage = function(){
	try {
		return (('localStorage' in window) && window['localStorage'] !== null)
		&& window.localStorage.getItem !== null && window.localStorage.removeItem !== null && window.localStorage.setItem !== null;
	} catch(e){return false;}
}

/*************************************
 * 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]);
}
/**
 * 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
        }
        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;
    }
};
/*********************************
 * Carrega o Script do Google Analytics Assincronamente.
 * Giuliano Costa (giulianocosta@gmail.com)
 *************************************/
(function($){
	$.startGA = function(accountId) {
		//check whether to use an unsecured or a ssl connection:
	    var host = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	    var src = host + 'google-analytics.com/ga.js';
	    $.ajax({//load the Google Analytics javascript file:
	        type: 'GET',
	        url: src,
	        success: function() {
				if (typeof pageTracker != undefined) {//the ga.js file was loaded successfully, set the account id:
		            pageTracker = _gat._getTracker(accountId);
					//track the pageview:
		            pageTracker._trackPageview();
				}
	        }
			, error: function() {
				//the ga.js file wasn't loaded successfully:
	            throw "Unable to load ga.js; _gat has not been defined.";
	        }
			, dataType: 'script'
			, cache: true
			, ifModified: true
	   });
	}
})(jQuery);
/*********************************
 Brazilian initialisation for the jQuery UI date picker plugin.
 Written by Leonildo Costa Silva (leocsilva@gmail.com).
 *************************************/
jQuery(function($) {
	if($.datepicker) {
		$.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];
    }
});
/*********************************
 * Retorna um número randomico entre dois valores (giulianocosta@gmail.com)
 *************************************/
Math.randomRange = function (minVal, maxVal, floatVal){
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
}
/*************************************
 * 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(config && config.data == null) {
			this.remove(config);
        } else {
			if ($.support.localStorage()) {
	            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) {
		var key = (typeof(config) === 'object' ? config.key : config);
        if ($.support.localStorage()) {
            return window.localStorage.getItem(key);
        } else {
            return $.cookie(key);
        }
    }
    , remove : function (config) {
		var key = (typeof(config) === 'object' ? config.key : config);
        if ($.support.localStorage()) {
            return window.localStorage.removeItem(key);
        } else {
            return $.cookie(key, null, { path: (config.path ? '/' : config.path)});
        }
    }
};

function changeStyle(title) {
	if($('link#normalCss').exists()){
		var h = $('link#normalCss').attr('href');
		var css = '&c=contrast.css';
		if(title == 'contrast' && h.indexOf('contrast') == -1){
			h += css;
			$('link#normalCss').attr('href', h);
			PortalStorage.put({key: 'style', data: 'contrast'});
		} else if(title == 'normal' && h.indexOf('contrast') > -1) {
			h = h.replace(css, '');
			$('link#normalCss').attr('href', h);
			PortalStorage.remove('style');
		}
	}
}

function preparePortlets() {
	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();
	
	$("#customization a[id!='reset']").each(function(){
		var id = this.id.replace("show-", "");
		var target = '#' + id + ' a.button';
		
		$(target).click(function(){
			$('#' + id).toggle(function(){
				var valor = $(this).is(':visible');
				PortalStorage.put({key : id, data: valor});
			});
		});
		$(this).click(function(){
			$(target).trigger('click');
		});
		
		var isVisible = PortalStorage.get(id);
		if (!(isVisible === undefined || isVisible === null)) {
	        if (isVisible == "false") {
	            $(target).trigger('click');
	        }
	    }
	});

    $("#reset").click(function () {
        $("#noticias, #destaques, #acompanhamento-processual, #pesquisa-jurisprudencia, #comarcas-municipios, #diario")
		.each(function(){
			PortalStorage.remove(this.id);
			$(this).show();
		});
        return false;
    });
}

function initMenu(){
	var arr = ["#menu", "#menu ul li ul", "#menu ul li ul li ul li"];
	var clsH = ['head', 'sub-head', 'sub-sub-head'];
	var h = 'head';

	for(var k in arr){
		var conf = {
	        active: false,
	        collapsible: true,
	        autoHeight: false,
	        header: 'a.' + h,
			change: function (e, ui) {
				for(var i in clsH) {
					if(ui.newHeader.hasClass(clsH[i]) || ui.oldHeader.hasClass(clsH[i])){
						PortalStorage.put({key: 'mnu_depth' + i, data: ui.newHeader.text()});
					}
				}
			}
	    };

		if(k == 0) conf.icons = {header: "item", headerSelected: "item-selected"};

		$(arr[k]).accordion(conf);

		h = 'sub-' + h;
	}

	for(var i = 0; i < clsH.length; i++){
		var tmp = PortalStorage.get('mnu_depth' + i)
		if(!(tmp === undefined || tmp === null || tmp === '')) {
			$('a.' + clsH[i] + ':contains("' + tmp + '")').trigger('click');
		}
	}
}

$(function() {
    $("#text ul.sub").accordion({
        active: false,
        collapsible: true,
        autoHeight: false,
        header: 'a.section'
    });
});

/**
 * Increase and Decrease Font Size.
 */
var increase = 0.05;
var min = -0.5;
var normal = 1.0;
var max = 1.5;

function pxToEm(v) {
	var value = 0.0;
	try {value = parseFloat(v)}catch(e){return 0.0;}
	if(isNaN(value)) return 0.0;
	value *= 0.0625;

	return Math.round(value * Math.pow(10, 2)) / Math.pow(10, 2);
}

function changeFontSize(inc) {
	$('div').each(function(){
		if($(this).hasClass('interna') || $(this).hasClass('module') || $(this).attr('id') == 'text') {
			var size = 1.0;
			var fs = $(this).css('fontSize');

			if (fs) {
				if(fs.indexOf('px') > -1) {
					size = pxToEm(parseFloat(fs.replace("px", "")));
				} else {
					size = parseFloat(fs.replace("em", ""));
				}
			}
			size += inc;
			$(this).css({fontSize: size + 'em'});
		}
	});
}

function changeFactor(v, t) {
	var size =  v;
	if(size == null) size = increase;
	else {
		size = parseFloat(size);
		if(t){
			size += increase
			if(size == 0) size += increase;
		} else {
			size -= increase
			if(size == 0) size -= increase;
		}
	}
	size = Math.round(size * Math.pow(10, 2)) / Math.pow(10, 2);
	
	return size;
}
function increaseFontSize() {
	var size = changeFactor(PortalStorage.get('fontSize'), true);
	if(size < max) {
		changeFontSize(increase);
		PortalStorage.put({key: 'fontSize', data: size});
	}
}
function decreaseFontSize() {
	var size = changeFactor(PortalStorage.get('fontSize'), false);
	if(size > min) {
		changeFontSize(increase * -1);
		PortalStorage.put({key: 'fontSize', data: size});
	}
}
function actualizeFontSize() {
	var size = PortalStorage.get('fontSize');

	if(size != null) {
		size = parseFloat(size);
		if(size != normal && size < max && size > min) changeFontSize(size);
	}
}

function resetFontSize() {
	PortalStorage.remove('fontSize');
    location.reload();
}

$(function() {

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

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
    var showLine = false;
	var count = 0;
	var ps = PortalStorage;
	var urlPre = "5url_";
	var tltPre = "5tlt_";

	// Show Last Five URL's
	while(count++ < 5){
		var url = ps.get(urlPre + count);
		var tlt = ps.get(tltPre + count);

		if (url) {
	        $("#oneclick option:eq(" + count + ")")
			.attr("value", url)
			.attr("title", tlt)
			.text(tlt.split("|")[0]);
	        showLine = true;
	    } else {
	        $("#oneclick option:eq(" + count + ")").remove();
	    }
	}

    if (!showLine) $("#oneclick option:eq(" + count + ")").remove();

    // Save news URLs, only if not repeat
    if (ps.get(urlPre + "1") != window.location) {
        ps.put({key: urlPre + "5", data: ps.get(urlPre + "4")});
        ps.put({key: urlPre + "4", data: ps.get(urlPre + "3")});
        ps.put({key: urlPre + "3", data: ps.get(urlPre + "2")});
        ps.put({key: urlPre + "2", data: ps.get(urlPre + "1")});
        ps.put({key: urlPre + "1", data: window.location});

        ps.put({key: tltPre + "5", data: ps.get(tltPre + "4")});
        ps.put({key: tltPre + "4", data: ps.get(tltPre + "3")});
        ps.put({key: tltPre + "3", data: ps.get(tltPre + "2")});
        ps.put({key: tltPre + "2", data: ps.get(tltPre + "1")});
        ps.put({key: tltPre + "1", data: titlePage});
    }
}


/*********************************
 * Rola os destaques da capa (giulianocosta@gmail.com)
 *************************************/
function rolarDestaquesCapa(start) {
	var numPerPage = 5;

	$("ul#listDestaquesCapa").fadeOut(1000, function(){
		var li = $("li", $(this)).hide().get();
		var count = 0;
		var excedente = 0;
		while(count++ < numPerPage){
			if(start >= li.length) {
				excedente = numPerPage - count;
				start = 0;
			}
			$(li[start++]).show();
		}
		if(excedente > 0) {
			$("ul#listDestaquesCapa")
			.prepend($("ul#listDestaquesCapa > li:not(:regex(css:display, ^none$)):gt("+excedente+")"));
			start += excedente;
		}
		
		$("ul#listDestaquesCapa").fadeIn(2000);
		setTimeout('rolarDestaquesCapa(' + start + ')', 6000);
	});
}
/*********************************
 * Chamado ao carregar (giulianocosta@gmail.com)
 *************************************/
$(document).ready(function(){
	var styleName = PortalStorage.get('style');
	if(styleName != null ) changeStyle(styleName);

	initMenu();

	preparePortlets();

	actualizeFontSize();
	
	setLastFiveLinks();

	$("a#button").click(function () {
     		$("#customization").toggle("blind", 500);
        	return false;
	});

	if($("ul#listDestaquesCapa").exists()) {
		rolarDestaquesCapa(Math.randomRange(0, $("ul#listDestaquesCapa > li").length, 0));
	}
	
	$("a[href!='#'][title='']").each(function(){
		$(this).attr('title', function(i, t){
			return $(this).text();
		});
	});
	
	
	$("#linkPrintPage").click(function(){//Adiciona o evento de impressão para a versão de impressao do site
		if($("#iframe").exists()) {
			$.get('/site/system/modules/com.br.workroom.tjrs/elements/proxyExternalUrl.jsp', { url: $("#iframe").attr('src') }, function(data) {
				//Evita a quebra de pagina em impressoes com iframe
				$("a, td", $("#iframe").hide().parent().html(data)).css({color: '#000000', border: '0'});
				print();
			});
		} else {
			print();
		}
	});
	initSliderDestaques();
});

/* ************************************
   SLIDER DA COLUNA DE DESTAQUES
 ************************************ */
function initSliderDestaques(){
	var speed = 3000;
	var run = setInterval(rotate, speed);	
	var item_width = $('#destaques-figuras li').outerWidth(); 
	var left_value = item_width * (-1); 
        

	$('#destaques-figuras li:first').before($('#destaques-figuras li:last'));
	$('#destaques-figuras ul').css({'left' : left_value});
	$('#ant').click(function() {
         
		var left_indent = parseInt($('#destaques-figuras ul').css('left')) + item_width;
          
		$('#destaques-figuras ul:not(:animated)').animate({'left' : left_indent}, 200,function(){    
		          	
			$('#destaques-figuras li:first').before($('#destaques-figuras li:last'));           
			$('#destaques-figuras ul').css({'left' : left_value});
		
		});
          
		return false;
            
	});

	$('#prox').click(function() {

		var left_indent = parseInt($('#destaques-figuras ul').css('left')) - item_width;

		$('#destaques-figuras ul:not(:animated)').animate({'left' : left_indent}, 200, function () {

			$('#destaques-figuras li:last').after($('#destaques-figuras li:first'));                 	
			$('#destaques-figuras ul').css({'left' : left_value});
		
		});

		return false;
		
	});        

	$('#destaques-figuras').hover(
		
		function() {
			clearInterval(run);
		}, 
		function() {
			run = setInterval('rotate()', speed);	
		}
	); 
}
function rotate() {
	$('#prox').click();
}

function vaiLink(url){
	window.open(url);
}
