var PLACE_AREA       = "areaTexto";
var PLACE_TEXT_CSS   = "tamanhoTexto";
var PLACE_DEGUSTACAO = "degustacao";
var PLACE_BANNER     = "bannerLateral";
var PLACE_LINKS      = "linksPatrocinados";
var CK_NAME          = "ExamePersonalizacaoFontSize";
var CK_ACTIVE        = null;
var USER_ID          = null;
var TEXT_SIZE_DEFAULT = "11px";

var CSS_STR = new Array (
"#areaTexto p {font-size: 9px !important; line-height: 14px !important}\n" +
"#areaTexto td {font-size: 9px !important; line-height: 14px !important}\n" +
"#areaTexto th {font-size: 9px !important; line-height: 14px !important}\n" +
"#areaTexto ul {font-size: 9px !important; line-height: 14px !important}\n" +
"#areaTexto ol {font-size: 9px !important; line-height: 14px !important}\n" +
"#areaTexto dl {font-size: 9px !important; line-height: 14px !important}\n" +
"#areaTexto caption {font-size: 9px !important; line-height: 14px !important}\n" +
"#areaTexto h6 {font-size: 9px !important; line-height: 15px !important}\n" +
"#areaTexto h4 {font-size: 9px !important; line-height: 15px !important}\n" +
"#areaTexto .inicioTexto {line-height: 14px !important}\n",
"#areaTexto p {font-size: 11px !important; line-height: 15px !important}\n" +
"#areaTexto td {font-size: 11px !important; line-height: 15px !important}\n" +
"#areaTexto th {font-size: 11px !important; line-height: 15px !important}\n" +
"#areaTexto ul {font-size: 11px !important; line-height: 15px !important}\n" +
"#areaTexto ol {font-size: 11px !important; line-height: 15px !important}\n" +
"#areaTexto dl {font-size: 11px !important; line-height: 15px !important}\n" +
"#areaTexto caption {font-size: 11px !important; line-height: 15px !important}\n" +
"#areaTexto h6 {font-size: 11px !important}\n" +
"#areaTexto h4 {font-size: 11px !important}\n",
"#areaTexto p {font-size: 13px !important; line-height: 18px !important}\n" +
"#areaTexto td {font-size: 13px !important; line-height: 18px !important}\n" +
"#areaTexto th {font-size: 13px !important; line-height: 18px !important}\n" +
"#areaTexto ul {font-size: 13px !important; line-height: 18px !important}\n" +
"#areaTexto ol {font-size: 13px !important; line-height: 18px !important}\n" +
"#areaTexto dl {font-size: 13px !important; line-height: 18px !important}\n" +
"#areaTexto caption {font-size: 13px !important; line-height: 18px !important}\n" +
"#areaTexto h6 {font-size: 13px !important; line-height: 18px !important}\n" +
"#areaTexto h4 {font-size: 13px !important; line-height: 18px !important}\n"+
"#areaTexto .inicioTexto {line-height: 18px !important}\n");

var LETTERS = new Array( new Array( "9px", "tamanhoTextoPequenoOn", "tamanhoTextoPequenoOff", "Pequeno", "14px" ),
                         new Array( "11px", "tamanhoTextoMedioOn", "tamanhoTextoMedioOff", "Medio", "15px" ),
                         new Array( "13px", "tamanhoTextoGrandeOn", "tamanhoTextoGrandeOff", "Grande", "18px" ) );

var STYLE = null;
/**
 * Retorna um array com todos os elementos de document que possuam a
 * classe indicada em "clsName".
 *
 * @param {String} clsName
 */
function getElementsByClassName( clsName ) {
    var elements = ( document.all ) ? document.all : document.getElementsByTagName( "*" );

    clsName     = clsName.replace( /\-/g, "\\-" );
    var oRegExp = new RegExp( "\\b" + clsName + "\\b" );
    var buffer  = new Array();
    var oElement;

    for ( var i=0; i<elements.length; i++ ) {
        oElement = elements[i];
        if ( oRegExp.test( oElement.className ) ) {
            buffer.push( oElement );
        }
    }

    return buffer;
}

/**
 * Retorna o tamanho da fonte a ser redimensionada de acordo com o conteudo
 * gravado no cookie. Caso o valor do cookie seja nulo, o tamanho da fonte e
 * definido como 11px.
 *
 * @param {String} name
 */
function getCookie( name ) {
    var ckValue = readCookie( name );
    return ( ckValue != null ) ? ckValue : "11px";
}

/**
 * Cria o container de personalizacao da fonte, ou seja, o div que
 * contem as imagens para redimensionamento da fonte.
 */
function createLettersArea() {
if (document.getElementById( PLACE_AREA )) {
    var area = document.getElementById( PLACE_AREA );

    var nodeLetters = document.createElement( "div" );
    nodeLetters.setAttribute( "id", PLACE_TEXT_CSS );
    nodeLetters.className = PLACE_TEXT_CSS;
    nodeLetters.innerHTML = updatePlaceHolder();
    area.insertBefore( nodeLetters, area.childNodes.item(0) );
}
}

/**
 * Cria o container do banner da materia.
 */
function createBannerArea() {
    var nodeBanner = document.createElement( "div" );
    nodeBanner.setAttribute( "id", PLACE_BANNER );
    nodeBanner.className = PLACE_BANNER;
    getElementsByClassName( "relacionadas" )[0].appendChild( nodeBanner );

    var txtPublicidade = document.createElement( "h5" );
    txtPublicidade.innerHTML = "Publicidade";
    nodeBanner.appendChild( txtPublicidade );

    try {
        var content = document.getElementById( "loadPublicidade" );
        content.style.display = "block";
        nodeBanner.appendChild( content );
        content.style.display = "block";
    } catch( e ) {}
}

/**
 * Cria o container dos links patrocinados.
 */
function createLinksPatrocinados() {
    var nodeLinks = document.createElement( "div" );
    nodeLinks.setAttribute( "id", PLACE_LINKS );
    nodeLinks.className = PLACE_LINKS;
    getElementsByClassName( "relacionadas" )[0].appendChild( nodeLinks );

    var nodeAbaLinks = document.createElement( "div" );
    nodeAbaLinks.setAttribute( "id", "aba" );
    nodeAbaLinks.className = "aba";
    nodeLinks.appendChild( nodeAbaLinks );

    try {
        var content = document.getElementById( "loadLinksPatrocinados" );
        content.removeChild( content.getElementsByTagName( "h1" )[0] );
        nodeLinks.appendChild( content );
        content.style.display = "block";
    } catch( e ) {}
}

/**
 * Cria o container do credito da foto.
 */
function createCreditoFoto() {
    var nodeCredito = document.createElement( "div" );
    nodeCredito.setAttribute( "id", "creditoFoto" );

    try {
        var area = getElementsByClassName( "boxImagem" )[0];

        if ( area.getElementsByTagName( "h4" )[0] ) {
            nodeCredito.innerHTML = area.getElementsByTagName( "h4" )[0].innerHTML;
            area.insertBefore( nodeCredito, area.childNodes.item(0) );
        }
    } catch( e ) {}
}

/**
 * Altera o posicionamento da fonte (credito) da materia.
 */
function modifyFonteMateria() {
    try {
        //Obtem o noh do credito (fonte) da materia
        var nodeFonte = getElementsByClassName( "inicioTexto" )[0];
        //Se existir...
        if (nodeFonte != null) {
            //Cria um novo codigo HTML para exibi-la
            var fonteMateria   = 
            "<span class='inicioTexto'" +
            " style='visibility: visible; font: normal 9px/14px Verdana;'>" + 
            nodeFonte.innerHTML + 
            "</span>";
            //Obtem o primeiro paragrafo do texto (depois do credito (fonte) da materia)
            var firstParagraph = nodeFonte.nextSibling;
            //Enquanto nao existir um texto, passa para o proximo elemento...           
            while ( firstParagraph != null && isElementEmpty(firstParagraph) ) {                
                firstParagraph = firstParagraph.nextSibling;                
            }
            //Se o primeiro paragrafo for diferente de null e o elemento nao for vazio...
            if (firstParagraph != null 
                && !isElementEmpty(firstParagraph) 
                && firstParagraph.innerHTML != null) {
                //Remove o elemento fonte da materia da antiga posicao
                document.getElementById( PLACE_AREA ).removeChild( nodeFonte );
                //Inclui o novo código HTML para exibir de forma correta o credito (primeiro paragrafo).
                firstParagraph.innerHTML = fonteMateria + firstParagraph.innerHTML;
            }
            //Senao, simplesmente exibe na posicao corrente.
            nodeFonte.style.visibility = 'visible';
        }
    } catch( e ) {
        //Senao, simplesmente exibe na posicao corrente.
        if (nodeFonte != null && nodeFonte.style != null &&
            nodeFonte.style.visibility != null) {
            nodeFonte.style.visibility = 'visible';
        }
    }
}

/**
 * Verifica se o elemento esta com o texto vazio (innerHTML)
 */
function isElementEmpty(el) {
    if (el == null) {
        return true;
    } else if (el.innerHTML == null) {
        
        if (el.nodeValue == null || trimText(el.nodeValue) == "") {
            return true;
        }
        return false;
    } else {
        return (trimText(el.innerHTML) == "");
    }
}

/**
 * Retira os espaços em branco do texto a esquerda e a direita
 * @param t - Texto a ser modificado.
 */
function trimText( t ) {
    var text = t;
    //text = text.replace("&nbsp;"," ");
    text = text.replace("\n"," ");
    text = text.replace("\r"," ");
    text = text.replace("\t"," ");
    text = text.replace("\b"," ");  
    //Retira os espacos em branco a esquerda
    while (text.length > 0 && (text.charAt(0) == ' ' || text.charCodeAt(0) == 160)) {
        text = text.substr(1);
    } 
    //Retira os espacos em branco a direita
    while (text.length > 0 && (text.charAt(text.length - 1) == ' ' || text.charCodeAt(text.length - 1) == 160)) {
        text = text.substr(0, text.length - 1);
    } 
    return text;
}


/**
 * Altera a propriedade float do primeiro p.sep do DIV "areaTexto"
 * caso existe imagem na materia - bug no IE
 */
function ajustaMateriaSemFoto() {
    try {
        var firstSep = $$('div#areaTexto p.sep')[0];
        if (firstSep && firstSep.nextSibling.className == 'boxImagem') {
            firstSep.style.styleFloat = 'none';
    }
    } catch( e ) {}
}




function createMarginText() {
    try {
        var area = getElementsByClassName( "linksPatrocinados" )[0];
        var node = null;
        do {
            area = area.nextSibling;
        } while ( area == null || area.tagName == null || area.tagName == "" );
        if (navigator.userAgent.indexOf("MSIE") > 0) { 
            if (area.tagName.toUpperCase() != "H4" ) {
               var node = document.createElement( "h4" );
               node.style.marginTop = "0px";
               //node.style.paddingTop = "3px";               
               document.getElementById("areaTexto").insertBefore(node, area);
            } 
        } 
    } catch( e ) {}
}




/**
 * Compara o valor armazenado no cookie de personalizacao e define
 * o estilo das imagens de redimensionamento da fonte.
 */
function updatePlaceHolder() {
    CK_ACTIVE = getCookie( CK_NAME );
    if (CK_ACTIVE == null) {
        CK_ACTIVE = "11px";
    }
    var content = "<h5>Tamanho da fonte:</h5>";

    for (var i=0; i<LETTERS.length; i++){
        content += ( CK_ACTIVE == LETTERS[i][0] )
                       ? "<a href='javascript:void(0);' id='" + LETTERS[i][1] + "' onclick='updateFont(\"" + LETTERS[i][0] + "\");'><span>" + LETTERS[i][3] + " | </span></a>"
                       : "<a href='javascript:void(0);' id='" + LETTERS[i][2] + "' onclick='updateFont(\"" + LETTERS[i][0] + "\");'><span>" + LETTERS[i][3] + " | </span></a>";
    }

    return content;
}

/**
 * Altera o tamanho da fonte de todo o conteudo pertencente ao escopo
 * da materia. Todas as tags HTML especificadas em "elements"
 * deverao ser modificadas.
 *
 * @param {String} fontSize
 */
function updateFont( fontSize ) {
    if (createCookie != null) {
        createCookie( CK_NAME, fontSize, null );
    }
    if (STYLE == null) {
        STYLE = document.createElement("style");
        STYLE.setAttribute("type", "text/css");
        STYLE.setAttribute("id","estiloFonte");
    }
    for (i = 0; i< 3; i++) {
        if (CSS_STR[i].indexOf(fontSize)>=0) {
            if(STYLE.styleSheet){// IE
               STYLE.styleSheet.cssText = CSS_STR[i];
            } else {// w3c
               var cssText = CSS_STR[i];
               STYLE.innerHTML = cssText;
            }
            break;
        }
    }
    document.getElementsByTagName('head').item(0).appendChild(STYLE);
    if (document.getElementById( PLACE_TEXT_CSS ) != null) {
        document.getElementById( PLACE_TEXT_CSS ).innerHTML = updatePlaceHolder();
        updateDataUser();
    }
}

/**
 * Grava a personalizacao do usuario autenticado no Banco de Dados.
 */
function updateDataUser() {
    if ( logado() ) {
        PersonalizacaoController.saveUserPreferences( [{chave:"tamanho.fonte",preferenciaUsuarioId:USER_ID,valor:CK_ACTIVE}] );
    }
}

/**
 * Carrega as configuracoes padroes.
 * Os links patrocinados e a area de personalizacao do tamanho da fonte
 * serao exibidos somente quando o conteudo de degustacao nao existir.
 */
function init() {
    if ( ( document.getElementById( PLACE_AREA ) ) && ( !document.getElementById( PLACE_DEGUSTACAO ) ) ) {
        //ajustaMateriaSemFoto();
        modifyFonteMateria();
        loadFont();
    }
    try {
        // Inicializa o servico de comentarios (@see comentarios.js)
        createMarginText();
        initComentarios();
    } catch( e ) {}
}


function loadFont() {
    if (canal != 'degustacao') {
        try {
            if ( logado() ) {
                PersonalizacaoController.loadUserPreferences( function( prefs ) {
                    var fontSize = getCookie( CK_NAME );
                    for ( var i=0; i<prefs.length; i++ ) {
                        if ( prefs[i].chave == "tamanho.fonte" ) {
                            USER_ID = prefs[i].preferenciaUsuarioId;
                            fontSize = prefs[i].valor;
                            break;
                        }
                    }
                    updateFont( fontSize );
                } );
            } else {
                CK_ACTIVE = getCookie( CK_NAME );
                updateFont( CK_ACTIVE );
            }
        } catch( e ) {
            updateFont( TEXT_SIZE_DEFAULT );
        }
    }
}


addLoadEvent( init );

loadFont();
