function cpf(cpf) {
        if ((cpf == "11111111111") || (cpf == "22222222222") ||
            (cpf == "33333333333") || (cpf == "44444444444") ||
            (cpf == "55555555555") || (cpf == "66666666666") ||
            (cpf == "77777777777") || (cpf == "88888888888") ||
            (cpf == "99999999999") || (cpf == "00000000000")) {
                return false;
        } else {
                var i = new Number(0);
                var soma=i, posicao=i, dv_informado=i, dv=i, c=i, d=i, p=i;
                var digito = new Array(11);
                for(i=0; i < cpf.length; i++) digito[i] = parseInt(cpf.charAt(i));
                dv_informado = parseInt(cpf.substring(9,11),10);
                for(c=8,d=9,p=10; (c<=9) ; c++,d++,p++) {
                        for (i=0, soma=0, posicao=p; i<=c; i++) {
                                soma = soma + digito[i] * posicao;
                                posicao = posicao - 1;
                        }
                        digito[d] = (soma % 11);
                        digito[d] = (digito[d] < 2) ? 0 : 11 - digito[d];
                }
                dv = digito[9] * 10 + digito[10];
                if (dv != dv_informado) {return false;}
        }
        return true;
}

function cnpj(cnpj) {
        var j = 5, k = 6;
        var soma1=0, soma2=0;
        var digito = new Array(11);
        for(i=0; i < cnpj.length; i++) digito[i] = parseInt(cnpj.charAt(i));
        for(var i = 0; i < 13; i++, k--, j--) {
                j = (j == 1) ? 9 : j;
                k = (k == 1) ? 9 : k;
                soma2 += digito[i] * k;
                if(i < 12) {soma1 += digito[i] * j;}
        }
        var digit1 = (soma1 % 11 < 2) ? 0 : 11 - soma1 % 11;
        var digit2 = (soma2 % 11 < 2) ? 0 : 11 - soma2 % 11;
        if(digito[12] != digit1 || digito[13] != digit2) {return false;}
        return true;
}










////////////////////////////////////////////////////////////////////////////////
function propagandaJanela() {
    var mydiv = document.getElementById("propaganda");
    if(mydiv) {
        if (document.readyState == undefined || document.readyState == "complete" || document.readyState == "interactive") {
            mydiv.style.left = ((f_clientWidth() + f_scrollLeft())/2 - 568/2) + "px";
            mydiv.style.top = (f_clientHeight() + f_scrollTop() + 18) + "px";
            ajustaPosicaoJanela();
        } else setTimeout('propagandaJanela();', 1000);
    }
}
function fechaPropaganda( node ) {
    var mydiv = document.getElementById("propaganda");
    mydiv.parentNode.removeChild(mydiv);
}
var ajustaPosicao = false;
function ajustaPosicaoJanela() {
    if (ajustaPosicao) {
        var mydiv = document.getElementById("propaganda");
        if (mydiv) {
            mydiv.style.visibility = "visible";
            mydiv.style.display = "block";
            var leftFinal = (f_clientWidth() + f_scrollLeft())/2 - 568/2;
            var topFinal = (f_clientHeight() + f_scrollTop()) - 144;
            var leftNow = parseInt(mydiv.style.left.toString().split("px")[0]);
            var topNow = parseInt(mydiv.style.top.toString().split("px")[0]);
            var leftSize = leftFinal - leftNow;
            var topSize = topFinal - topNow;
            if (leftSize) mydiv.style.left = ( leftNow + (leftSize / 5) ) + "px";
            if (topSize) mydiv.style.top = ( topNow + (topSize / 5) ) + "px";
            setTimeout("ajustaPosicaoJanela();", 40);
        }
    } else ajustaPosicao = true;
}
function f_clientWidth()  {return f_filterResults ( window.innerWidth  ? window.innerWidth  : 0, document.documentElement ? document.documentElement.clientWidth  : 0, 0 );}
function f_clientHeight() {return f_filterResults ( window.innerHeight ? window.innerHeight : 0, document.documentElement ? document.documentElement.clientHeight : 0, 0 );}
function f_scrollLeft()   {return f_filterResults ( window.pageXOffset ? window.pageXOffset : 0, document.documentElement ? document.documentElement.scrollLeft   : 0, document.body ? document.body.scrollLeft : 0 );}
function f_scrollTop() 	  {return f_filterResults ( window.pageYOffset ? window.pageYOffset : 0, document.documentElement ? document.documentElement.scrollTop    : 0, document.body ? document.body.scrollTop  : 0 );}
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel))) n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
setTimeout('propagandaJanela();', 4000);
////////////////////////////////////////////////////////////////////////////////










var tempoCabecalho = null;
var transicaoAtiva = false;

function iniciarTransicaoCabecalho(){
	tempoCabecalho = $.interval(mudarFotoCabecalho, 4000);
	transicaoAtiva = true;
}

function mudarFotoCabecalho() {
	var proximo = $("#cabecalho-paginas .selected").next();
	if (proximo.html() == null){
		proximo = $("#cabecalho-paginas ul li:first-child");
	}
	mudarFotoCabecalhoClick(proximo);
}

function mudarFotoCabecalhoClick(elemento) {
	if (!elemento.hasClass("selected")){
		var numero = elemento.html();
		var anterior = $("#cabecalho-foto div.selected");
		var indice_anterior = anterior.children("input[type=hidden]").val();
		var indice_atual = $("#cabecalho-container-" + numero).children("input[type=hidden]").val();

		if (indice_anterior > indice_atual) {
			$("#cabecalho-container-" + numero).css("z-index","1").show();
			anterior.css("z-index","3").fadeOut("slow",function(){
				anterior.css("z-index","1").removeClass("selected");
				$("#cabecalho-container-" + numero).addClass("selected");
			});
		} else {
			$("#cabecalho-container-" + numero).css("z-index","3").fadeIn("slow", function(){
				anterior.removeClass("selected").hide();
				$("#cabecalho-container-" + numero).css("z-index","1").addClass("selected");
			});
		}

		$("#cabecalho-paginas ul li.selected").removeClass("selected");
		elemento.addClass("selected");
	}
}

function verificarErroForm(elemento){
    if (elemento.hasClass('obr')) {
        if (elemento[0].tagName == 'SELECT') {
            if (elemento.val() == '') {
                elemento.addClass('text-erro');
                if (elemento.width() > 200) {
                    var option = elemento.find('option:selected');
                    if (option.val() == '') {
                        option.html('Preenchimento Obrigatório');
                    }
                }
                return false;
            }
        } else {
            if (elemento.val() == '' && elemento.html() == '') {
                elemento.addClass('text-erro');
                if (elemento.width() > 200) {
                    elemento.val('Preenchimento Obrigatório');
                }
                return false;
            }
        }
    }
    elemento.removeClass('text-erro');
    return true;
}

function removerErroForm(elemento){
    if (elemento.hasClass('text-erro')) {
        if (elemento[0].tagName == 'SELECT') {
            elemento.find('option:selected').html('');
        } else {
            if (elemento.val() == 'Preenchimento Obrigatório') {elemento.val('');}
        }
        elemento.removeClass('text-erro');
    }
}

function ajustarCabecalho(){
	var largura = $(window).width();
	//$("#body").width((largura <= 776 ? "780px" : "auto"));
	$("#body").width((largura <= 975 ? "960px" : "auto"));
	$("#corpo-mg").width((largura <= 975 ? "575px" : "100%"));
	if (largura <= 975) {$("#corpo").css("border-right",((975-largura)-200) > 0 ? ((975-largura)-200) + "px solid #fff" : "0");}
	else {$("#corpo").css("border-right","200px solid #fff");}
}

function corFundoAzul(elemento){
	elemento.css("background-color","#e4f4ff");
	elemento.css("border-color","#3666d4");
}

function corFundoCinza(elemento){
	elemento.css("background-color","#f5f5f5");
	elemento.css("border-color","#bfbfbf");
}

function fundoBotaoOver(elemento){elemento.css("background-image","url("+dir_img+"pmrg-coluna-esq-bg-over.gif)");}

function fundoBotaoNormal(elemento){elemento.css("background-image","url("+dir_img+"pmrg-coluna-esq-bg.gif)");}

$(document).ready(function(){

    $("#barra-servicos").submit(function(){
        if($("#barra-pmrg-destino").val() != "") {
            window.open($("#barra-pmrg-destino").val());
        }
        return false;
    });

    if ($.browser.msie && $.browser.version < 7){
        ajustarCabecalho();
        $(window).wresize(ajustarCabecalho);
        $(".text").css("height","30px");
        $(".textarea,.text").focus(function(){corFundoAzul($(this));});
        $(".textarea,.text").blur(function(){corFundoCinza($(this));});
        $(".textarea,.text").hover(function(){corFundoAzul($(this));},function(){corFundoCinza($(this));});
        $(".botao").hover(function(){fundoBotaoOver($(this));},function(){fundoBotaoNormal($(this));});
    }

    $("a.ext").click(function(){window.open($(this).attr("href"));return false;});

    $("#coluna-esq ul.menu li a.item").click(function(){
        var imagem = $(this).children("img");
        var submenu = $(this).next();
        if (submenu.is("ul")){
            if (submenu.css("display") == "none"){
                if ($("#coluna-esq .selected")){
                    $("#coluna-esq .selected").prev().children("img").attr("src",dir_img+"pmrg-coluna-esq-mais.gif");
                    $("#coluna-esq .selected").slideUp("normal").removeClass("selected");
                }
                submenu.slideDown("normal").addClass("selected");
                imagem.attr("src",dir_img + "pmrg-coluna-esq-menos.gif");
            } else {
                submenu.slideUp("normal").removeClass("selected");
                imagem.attr("src",dir_img + "pmrg-coluna-esq-mais.gif");
            }
            return false;
        }
    });

    $("#cabecalho-paginas ul li").click(function(){
        $.clear(tempoCabecalho);
        mudarFotoCabecalhoClick($(this));
        transicaoAtiva = false;
    });

    $("#cabecalho-paginas,#cabecalho-foto").hoverIntent(function(){
        $.clear(tempoCabecalho);
        transicaoAtiva = false;
    },function(){
        $.clear(tempoCabecalho);
        iniciarTransicaoCabecalho();
    });

    $("#cabecalho").mouseout(function(){
        if (transicaoAtiva == false){iniciarTransicaoCabecalho();}
    });

    $("#cabecalho-container-1 img").load(function(){
        iniciarTransicaoCabecalho();
    });
    
// Date Time Picker
$('.datepicker').datepicker({
    dateFormat: 'dd/mm/yyyy'
}).mask('99/99/9999');
$('.timepicker').timepicker({
    hourGrid: 4,
    minuteGrid: 10
}).mask('99:99');
$('.datetimepicker').datetimepicker({
    hourGrid: 4,
    minuteGrid: 10,
    dateFormat: 'dd/mm/yyyy'
}).mask('99/99/9999');
    
// LOGIN
    $("#login-sair").click(function(){
       $("#login-task").val("logout");
       $("#form-login").submit();
    });
    $("input[name=cpf]").focus(function(){
        $(this).unmask();
        $(this).val( $(this).val().replace(/\D/g,"") );
    });
    $("input[name=cpf]").blur(function() {
        var cpfCnpj = $(this).val().replace(/\D/g,"");
        if( cpfCnpj.length > 0 ) {
            if( cpfCnpj.length == 11 ) {
                if( cpf(cpfCnpj) ) {
                    $(this).mask("999.999.999-99");
                    if($(this).attr("id")=="login-usuario") $("#login-senha").focus();
                } else {
                    alert("Este CPF não é válido!");
                    $(this).val("");
                }
            } else if( cpfCnpj.length == 14 ) {
                if( cnpj(cpfCnpj) ) {
                    $(this).mask("99.999.999/9999-99");
                    if($(this).attr("id")=="login-usuario") $("#login-senha").focus();
                } else {
                    alert("Este CNPJ não é válido!");
                    $(this).val("");
                }
            } else {
                alert("Este número não é válido!");
                $(this).val("");
            }
        }
    });
// LOGIN - FIM

    // Painel Eletronico
    $('#painel-eletronico ul.marquee').marquee();
    $("#painel-eletronico").css('background','url("'+dir_img+'pmrg-coluna-esq-bg2.gif") repeat-x scroll 0px -30px transparent');
    $("#painel-eletronico div ul.marquee").mouseover(function() {
        $("#painel-eletronico").css('background','url("'+dir_img+'pmrg-coluna-esq-bg2.gif") repeat-x scroll 0px 0px transparent');
    }).mouseout(function(){
        $("#painel-eletronico").css('background','url("'+dir_img+'pmrg-coluna-esq-bg2.gif") repeat-x scroll 0px -30px transparent');
    });


    // CAPTCHA
    $('#captcha-refresh').click(function(){
        var pos = $('#captcha-imagem').attr('src').indexOf('sid=') + 4;
        $('#captcha-imagem').attr('src', $('#captcha-imagem').attr('src').substring(0, pos) + Math.random() );
    });
    $('#captcha-play').click(function(){//function(e){
        var pos = $('#captcha-imagem').attr('src').indexOf('sid=');
        //e.preventDefault();  //stop the browser from following
        window.location.href =  $('#captcha-imagem').attr('src').substring(0, pos) + 'acao=play';
    });

    $.fn.media.defaults.flvPlayer = dir_site + '/templates/js/mediaplayer.swf';
    $('a.media').media({width:450, height:380});
    
// Fim  -  $(document).ready
});

jQuery.fn.center = function () {
        this.css('position','absolute');
        this.css('top', ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + 'px');
        this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');
        return this;
}


