﻿nie = (navigator.appName.indexOf("Microsoft") == -1);

function el(id) {
    return document.getElementById(id);
}

function getel(doc, id) {
    return doc.getElementById(id);
}

function getElementsById(sId) {
    var outArray = new Array();

    if (typeof (sId) != 'string' || !sId) {
        return outArray;
    };

    if (document.evaluate) {
        var xpathString = "//*[@id='" + sId.toString() + "']"
        var xpathResult = document.evaluate(xpathString, document, null, 0, null);
        while ((outArray[outArray.length] = xpathResult.iterateNext())) { }
        outArray.pop();
    }
    else if (document.all) {

        if (document.all[sId])
            for (var i = 0, j = document.all[sId].length; i < j; i += 1) {
            outArray[i] = document.all[sId][i];
        }

    } else if (document.getElementsByTagName) {

        var aEl = document.getElementsByTagName('*');
        for (var i = 0, j = aEl.length; i < j; i += 1) {

            if (aEl[i].id == sId) {
                outArray.push(aEl[i]);
            };
        };

    };

    if ((outArray.length == 0) && (el(sId)))
        outArray[0] = el(sId);

    return outArray;
}

function clickLink(linkId) {
    eval(el(linkId).href);
}

function getAjax() {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType("text/html; charset=windows-1252");
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!http_request) {
        alert('Desculpe, seu navegador é incompatível com este recurso.');
        return false;
    }
    return http_request;
}

function element_top(el) {
    var et = 0
    while (el) {
        et += el.offsetTop
        el = el.offsetParent
    }
    return et
}

function element_left(el) {
    var et = 0
    while (el) {
        et += el.offsetLeft
        el = el.offsetParent
    }
    return et
}

function matriz(n) {
    this.length = n
    for (var i = 0; i < n; i = i + 1) {
        this[i] = ''
    }
}

function showProgressImage(id) {
    pimg = el(id);
    pimg.style.visibility = 'visible';
    pimg.src = pimg.src;
}

var reqs = [];

function saveReqObjs(req, objs) {
    reqs.length++;
    i = reqs.length - 1;
    reqs[i] = new matriz(2);
    reqs[i].req = req;
    reqs[i].objects = objs;
}

function loadReqObjs(req) {
    for (i = 0; i < reqs.length; i++)
        if (req == reqs[i].req)
        return reqs[i].objects;
}

function startFlash(flash, quality, width, height, menu, loop, id) {
    this.flash = flash;
    this.quality = quality;
    this.width = width;
    this.height = height;
    this.menu = menu;
    this.loop = loop;
    this.id = id;
    this.writeFlash = writeFlash;
}

function writeFlash() {
    with (this) {
        document.writeln('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="' + width + '" height="' + height + '" id="' + id + '">');
        document.writeln('<param name="movie" value="' + flash + '">');
        document.writeln('<param name="quality" value="' + quality + '">');
        document.writeln('<param name="menu" value="' + menu + '">');
        document.writeln('<param name="loop" value="' + loop + '">');
        document.writeln('<param name="wmode" value="transparent" />');
        document.writeln('<embed src="' + flash + '" width="' + width + '" height="' + height + '" loop="' + loop + '" quality="' + quality + '" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" menu="' + menu + '"></embed>');
        document.writeln('</object>');
    }
}

function buscaFocus(txt, f) {
    def = 'título, autor ou palavra chave';
    if (f) {
        if (txt.value == def)
            txt.value = '';
        txt.className = 'text';
    }
    else {
        if (txt.value == '') {
            txt.value = def;
            txt.className = 'value'
        }
    }
}

function selArea(area) {
    ma = el('ma' + (area));
    if (ma)
        ma.className = 'ativo';
}

carregandoNoticias = 0;
function carregaMaisNoticias() {
    carregandoNoticias = 1;
    url = htmlBase + 'controles/noticiasAjax.aspx?pg=' + (noticiasPg + 1) + '&idSiteAreaSecao=' + (noticiasIdSiteAreaSecao) + '&idMaior=' + (noticiasIdMaior) + "&destaques=" + (noticiasDestaques) + "&edh=" + (noticiasEDH) + "&p=" + (noticiasBusca);
    carregarEm(el('lnkMais'), el('divEnviando'), el('imgLoading'), el('noticiasPg' + (noticiasPg + 1)), url, '', 'carregarMaisNoticiasOk()');
}

function carregarMaisNoticiasOk() {
    noticiasPg++;
    if (el('divUltima'))
        el('divMais').style.display = 'none'
    showTwittersIn(el('noticiasPg' + (noticiasPg)));
    showXIframes();
    carregandoNoticias = 0;
}

function carregaNoticiasHome(destaques) {
    url = htmlBase + 'controles/noticiasAjax.aspx?pg=1&idSiteAreaSecao=' + (noticiasIdSiteAreaSecao) + '&idMaior=' + (0) + "&destaques=" + (destaques) + "&edh=" + (destaques);
    id = 'progressoNoticiasHome';
    pg = el(id) ? el(id) : window.frames['atividades'].el(id);
    id = 'imgLoadingNoticiasHome';
    img = el(id) ? el(id) : window.frames['atividades'].el(id);
    carregarEm(null, pg, img, null, url, 'carregaNoticiasHomeGetDest()', 'carregaNoticiasHomeOk(' + (destaques) + ')');
}

function carregaNoticiasHomeGetDest() {
    if (window.top.exibindoMyPointHome) {
        el('conteudoNoticias').innerHTML = window.top.conteudoNoticiasHome;
        window.top.exibindoMyPointHome = 0;
    }
    return el('noticiasMain');
}

function carregaNoticiasHomeOk(destaques) {

    el('lnkNoticiasDestaques').className = destaques ? 'active' : '';
    el('lnkNoticiasTodas').className = !destaques ? 'active' : '';
    
    noticiasPg = 1;
    noticiasIdMaior = 0;
    noticiasIdSiteAreaSecao = 0;
    noticiasBusca = '';
    noticiasDestaques = destaques;
    noticiasEDH = destaques;
    
    if (el('divUltima'))
        el('divMais').style.display = 'none'

    carregaBanners('noticiasHome');
    
    showTwittersIn(el('noticiasMain'));
    showXIframes();
}

function carregaMypointHome() {
    window.top.conteudoNoticiasHome = el('conteudoNoticias').innerHTML;
    el('conteudoNoticias').innerHTML = '<iframe src="' + htmlBase + 'mypoint/mp.controles/atividadesUsuario.aspx?home=1&geral=1&tamanhoPagina=50&paginacao=0" width=600 height=1000 scrolling=no frameborder=0 id=atividades name=atividades></iframe>';
    window.top.exibindoMyPointHome = 1;
}

function showTwittersIn(dv) {
    ancs = dv.getElementsByTagName('A');
    for (i = 0; i < ancs.length; i++) {
        anc = ancs[i];
        if (anc.className == 'twitter-share-button') {
            try {
                tweet_button = new twttr.TweetButton(anc);
                tweet_button.render();
            }
            catch (e) {
            }
        }
    }
}

function carregaUltimosComentarios(pg) {
    url = htmlBase + 'controles/ultimasAtividadesAjax.aspx?pg=' + (pg) + '&coment=1';
    carregarEm(null, el('progressoTagsECms'), el('imgLoadingTagsECms'), el('tagsEComentarios'), url, '', '');
    el('lnkUltimosComentarios').className = 'active';
    el('lnkRecomendadas').className = '';
    document.body.focus();
    gravaCookie('cx1', 1);
}

function carregaAtividadesMP(pg) {
    url = htmlBase + 'controles/ultimasAtividadesAjax.aspx?pg=' + (pg);
    carregarEm(null, el('progressoAtividadesMP'), el('imgLoadingAtividadesMP'), el('boxAtividadesMP'), url, '', '');
    document.body.focus();
}

function carregaRecomendadas(pg) {
    url = htmlBase + 'controles/recomendadasAjax.aspx?pg=' + (pg); 
    carregarEm(null, el('progressoTagsECms'), el('imgLoadingTagsECms'), el('tagsEComentarios'), url, '', '');
    el('lnkUltimosComentarios').className = '';
    el('lnkRecomendadas').className = 'active';
    document.body.focus();
    gravaCookie('cx1', 3);
}

function gravaCookie(nome, valor) {
    var expire = new Date();
    expire.setTime(new Date().getTime() + 3600000 * 24 * 5000);
    document.cookie = nome + '=' + (valor) + ';expires=' + expire.toGMTString() + ';domain=' + domain;
}

function carregaDezMais(tipo) {
    url = htmlBase + 'controles/dezMaisAjax.aspx?tipoDezMais=' + (tipo);
    carregarEm(null, el('progressoDezMais'), el('imgLoadingDezMais'), el('dezMais'), url, '', '');
    el('lnkDezMaisLidos').className = tipo == 'lidos' ? 'active' : '';
    el('lnkDezMaisComentados').className = tipo == 'comentados' ? 'active' : '';
    el('lnkDezMaisAvaliados').className = tipo == 'avaliados' ? 'active' : '';
    document.body.focus();
}

function carregarEm(botao, progresso, imgProgresso, destination, url, getdestinationfunction, onsucess) {
    if (botao)
        botao.style.display = 'none';
    if (progresso)
        progresso.style.display = 'block';
    if (imgProgresso)
        setTimeout('showProgressImage(\'' + imgProgresso.id + '\')', 100);

    req = getAjax();

    saveReqObjs(req, [botao, progresso, destination, getdestinationfunction, onsucess]);
    
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            objs = loadReqObjs(req);
            botao = objs[0];
            progresso = objs[1];
            destination = objs[2];
            getdestinationfunction = objs[3];
            onsucess = objs[4];
            if (botao)
                botao.style.display = 'block';
            if (progresso)
                progresso.style.display = 'none';
            if (req.status == 200) {
                if ((req.responseText.length < 9) || (req.responseText.indexOf('<!--ok-->') < 0))
                    alert(req.responseText)
                else {
                    if (!destination && getdestinationfunction)
                        destination = eval(getdestinationfunction);
                    destination.innerHTML = req.responseText;
                    eval(onsucess);
                }
            }
            else {
                alert('Desculpe, ocorreu uma falha técnica interna durante o processamento de sua solicitação. Por favor tente novamente em alguns instantes.');
            }
        }
    }

    req.open('GET', url, true);
    req.send(null);
}

function carregaBanners(filtro) {
    el('ifBanners').src = htmlBase + 'controles/bannersAjax.aspx?r=' + (Math.random()) + '&f=' + filtro;
}

function mostraBanner(target, code) {
    if (el(target))
        el(target).innerHTML = code;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

var elementosFonte = '';
var fonteMinTxt = 'O texto já está no tamanho mínimo!';
var fonteMaxTxt = 'O texto já está no tamanho máximo!';
function fonte(aumenta) {

    // default
    dif = Number(readCookie('fonte_agr'));

    els = elementosFonte.split(',');

    for (i = 0; i < els.length; i++) {

        if (els[i].substr(0, 1) == '_') {
            dfs = getElementsById(els[i].substr(1, els[i].length - 1));
        }
        else
            dfs = [el(els[i])];

        for (xx = 0; xx < dfs.length; xx++) {
            df = dfs[xx];
            if (!df)
                continue;
            def = Number(df.getAttribute('default-font', 0));
            if (aumenta > -1) {
                size = Number(df.style.fontSize.substr(0, df.style.fontSize.length - 2));
                dif = size - def;
            }
            else {
                dif = Number(readCookie('fonte_agr'));
                size = def + dif;
            }
            //alert(els[i] + ' default: ' + (def) + ' atual: ' + (size));

            if (aumenta > -1) {
                if ((dif <= 0) && !aumenta) {
                    alert(fonteMinTxt);
                    return;
                }
                if ((dif >= 4) && aumenta) {
                    alert(fonteMaxTxt);
                    return;
                }
                if (aumenta)
                    size++;
                else
                    size--;
            }

            dif = size - def;

            df.style.fontSize = (size) + "px";
        }
    }

    var expire = new Date();
    expire.setTime(new Date().getTime() + 3600000 * 24 * 5000);
    document.cookie = 'fonte_agr' + "=" + escape((dif) + '') + ";expires=" + expire.toGMTString() + ";path=/";
}

function starOver(isover, star) {
    x = Number(star.id.substr(9, 1));
    for (i = 1; i <= 5; i++) {
        s = el('aval_star' + (i));
        if ((i <= x) && (isover))
            s.className = 'star-hover';
        else
            s.className = i <= aval ? 'star-acesa' : 'star-apagada';
    }
}

var msgrepetir = 'Desculpe, ocorreu uma falha técnica durante o atendimento à sua solicitação.\n\nPor favor tente repetir a operação.\n\nSe o erro persistir, tente fechar seu navegador e abrí-lo novamente, ou entre em contato conosco.';

function avalia(idnsas, nota) {

    url = htmlBase + 'controles/registraAvaliacao.aspx?idn=' + (idnsas) + '&nota=' + (nota) + '&rnd=' + (Math.random());
    req = getAjax();

    el('imgEnvAval').style.display = 'block';

    req.onreadystatechange = function() {
        if (this.readyState == 4) {
            el('imgEnvAval').style.display = 'none';
            if ((this.status == 200) && (this.responseText.length >= 2)) {
                if (this.responseText.substr(0, 2) == 'OK')
                    alert('Sua avaliação foi registrada! Obrigado!');
                else if (this.responseText.substr(0, 2) == 'JA')
                    alert('Sua avaliação já está registrada, e só é permitido um voto por notícia. Obrigado!');
                else if (this.responseText.substr(0, 5) == 'LOGAR')
                    window.location = htmlBase + 'mypoint/cadastro.aspx';
            }
            else {
                alert(msgrepetir);
            }
        }
    }

    req.open('GET', url, true);
    req.setRequestHeader("Connection", "close");
    req.send(null);
}

function contaCaracter(campoVC, caracterN, limiteN) {
    if (campoVC.value.length > limiteN) {
        campoVC.value = campoVC.value.substring(0, limiteN);
    } else {
        el(caracterN).innerHTML = limiteN - campoVC.value.length;
    }
}

function gravaComentarioNoticia(idnsas) {
    txt = el('txtComentario').value;

    if (txt.length < 2) {
        alert('Por favor preencha seu comentário!');
        el('txtComentario').focus();
        return;
    }

    btn = el('enviarComentBT');

    btn.style.display = 'none';
    el('divEnviandoComent').style.display = 'block';
    setTimeout('showProgressImage(\'imgLoadingComent\')', 100);

    url = htmlBase + 'controles/noticiaRegistraComentario.aspx';
    poststr = "txt=" + encodeURIComponent(txt) + "&idnsas=" + idnsas;

    if (el('chkAutorizacao') && (el('chkAutorizacao').checked))
        poststr += "&auth=1";

    if (el('chkFuturos') && (el('chkFuturos').checked))
        poststr += "&futuros=1";

    req = getAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            el('enviarComentBT').style.display = 'block';
            el('divEnviandoComent').style.display = 'none';
            if (req.status == 200) {
                if (req.responseText.substr(0, 5) == 'LOGAR')
                    window.location = htmlBase + 'mypoint/cadastro.aspx';
                else if (req.responseText.substr(0, 2) != "ok")
                    alert(req.responseText)
                else {
                    el('comentTxt').style.display = 'none';
                    el('comentOk').style.display = 'block';
                    el('txtComentario').value = '';
                }
            }
            else {
                alert(msgrepetir);
            }
        }
    }

    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    // http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // http_request.setRequestHeader("Content-length", poststr.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(poststr);
}

function carregaMaisComentarios() {
    url = htmlBase + 'controles/comentariosNoticiaAjax.aspx?pg=' + (comentariosPg + 1) + '&idSiteAreaSecao=' + (comentariosIdSiteAreaSecao) + '&idNoticia=' + (comentariosIdNoticia);
    carregarEm(el('lnkMais'), el('divEnviando'), el('imgLoading'), null, url, 'carregaMaisComentariosGetDest()', 'carregaMaisComentariosOk()');
}

function carregaMaisComentariosGetDest() {
    if (comentariosPg == 0)
        return el('comentariosContent0');
    else {
        return el('comentariosPg' + (comentariosPg + 1));
    }
}

function carregaMaisComentariosOk() {
    comentariosPg++;
    if (el('divUltima'))
        el('divMais').style.display = 'none'
}

function showTwitters() {
    loadjscssfile("http://platform.twitter.com/widgets.js", "js");
}

function showXIframes() {
    ifrs = document.getElementsByTagName('IFRAME');
    for (i = 0; i < ifrs.length; i++) {
        ifr = ifrs[i];
        xsrc = ifr.getAttribute('xsrc', 0);
        if (ifr.getAttribute('src', 0) == 'about:blank')
            ifr.src = xsrc;
    }
}

function loadjscssfile(filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

function bodyLoad() {
    setTimeout('showXIframes()', 3000);
}

function noticiasAuto() {
    t = element_top(el('lnkMais'));
    y1 = document.body.scrollTop;
    y2 = document.documentElement.scrollTop;
    y = y1 > y2 ? y1 : y2;
    w = document.documentElement.clientHeight;
    th = document.documentElement.scrollHeight > document.body.scrollHeight ? document.documentElement.scrollHeight : document.body.scrollHeight;
    j = t - y - w;
    if ((th > 2000) && (j >= 200) && (j <= 700) && (!carregandoNoticias))
        carregaMaisNoticias();
    setTimeout('noticiasAuto()', 500);
}

// *********************************************************************************************************************

activeMenu = 0;
areaAtiva = 0;

function abreMenu(e, id) {
    sub = el('sub' + id);
    if (sub) {
        window.isOverButton = id;
        window.isOverMenu = 0;
        showmenu(e, sub, id);
    }
}

function fechaMenu(id, subitens) {
    if ((id > 0) && (id == window.isOverButton)) {
        window.isOverButton = 0;
        delayhidemenu();
    }
}

var ie5 = document.all && !window.opera
var ns6 = document.getElementById

function iecompattest() {
    return (document.compatMode && document.compatMode.indexOf("CSS") != -1) ? document.documentElement : document.body
}

function showmenu(e, which, id) {
    hidemenu();
    src = el('ma' + id);
    src.className = 'sub';
    activeMenu = id;
    if (!document.all && !document.getElementById)
        return
    clearhidemenu()

    window.menuobj = which;
    window.menuobj.style.left = 0;
    window.menuobj.style.width = '';
    w = window.menuobj.offsetWidth;
    window.menuobj.style.left = (src.offsetLeft) + 'px';
    w2 = window.menuobj.offsetWidth;

    if ((w2 < w) || (src.offsetLeft + w2 > el('menu-wrapper').offsetWidth)) {
        window.menuobj.style.left = 0;
        window.menuobj.style.left = (src.offsetLeft + src.offsetWidth - window.menuobj.offsetWidth) + 'px';
    }
    else if (w2 < src.offsetWidth) {
        window.menuobj.style.width = (src.offsetWidth - 2) + 'px';
    }

    window.menuobj.style.visibility = "visible"

    return false;
}

function contains_ns6(a, b) {
    while (b.parentNode)
        if ((b = b.parentNode) == a)
        return true;
    return false;
}

function hidemenu() {
    if (window.menuobj) {
        window.menuobj.style.visibility = "hidden"
        el('ma' + activeMenu).className = (activeMenu == areaAtiva ? 'ativo' : 'menu-item');
    }
}

function dynamichide(e) {
    if (!window.isOverButton) {
        if (ie5 && !window.menuobj.contains(e.toElement))
            hidemenu()
        else if (ns6 && e.currentTarget != e.relatedTarget && !contains_ns6(e.currentTarget, e.relatedTarget))
            hidemenu()
    }
}

function delayhidemenu() {
    if (!window.isOverMenu) {
        window.delayhide = setTimeout("hidemenu()", 500)
    }
}

function clearhidemenu() {
    clearTimeout(window.delayhide)
}

if (ie5 || ns6)
    document.onclick = hidemenu

/* ----------------------------------------------- */


