var TEXT_COMENTARIOS = new Array();
var QTDE_COMENTARIOS = 0;
var AVISO_TIMEOUT    = "";
var MAX_RESULTS_PAGE = 10;
var TEXT_MAX_LENGTH  = 400;

/**
 * Exibe mensagem "tooltip" de aviso.
 */
function showAviso() {
    clearTimeout( AVISO_TIMEOUT );

    document.getElementById( "tooltipComentar" ).style.display = "block";
}

/**
 * Esconde mensagem "tooltip" de aviso apos um tempo determinado.
 */
function blockAviso() {
    AVISO_TIMEOUT = setTimeout( "document.getElementById( 'tooltipComentar' ).style.display = 'none'", 600 );
}

/**
 * Cria mensagem "tooltip" de aviso.
 */
function showToolTipComentario() {
    var tooltip = document.createElement( "span" );
    tooltip.setAttribute( "id", "tooltipComentar" );
    tooltip.setAttribute( "onmouseover", function() { showAviso(); } );
    tooltip.setAttribute( "onmouseout", function() { blockAviso(); } );
    tooltip.style.display = "none";

    tooltip.innerHTML = "Para inserir um coment&aacute;rio voc&ecirc; precisa estar autenticado. Use os campos no alto da p&aacute;gina para informar seus dados.";

    try {
        var boxServicos = document.getElementById( "boxServicos" );
        boxServicos.appendChild( tooltip );
    } catch( e ) {}
}

/**
 * Exibe formulario para inclusao de comentarios.
 */
function showFormComentario() {
    var servicos      = document.getElementById( "servicos" );
    var frmComentario = document.getElementById( "formulario" );

    if ( logado() ) {
        if ( frmComentario.style.display != "block" ) {
            frmComentario.style.display = "block";
        }

        if ( frmComentario.style.display == "block" && QTDE_COMENTARIOS <= 1 ) {
            document.getElementById( "boxServicos" ).style.display = "none";
        }

        servicos.removeChild( servicos.getElementsByTagName( "h4" )[0] );
    } else {
        showServicos( false );
        showComentarios( false );
    }
}

/**
 * Exibe os servicos responsaveis pela listagem e inclusao de comentarios.
 * @param {Boolean} exibeTodos Flag para exibicao de comentarios.
 */
function showServicos( exibeTodos ) {
    var area     = document.getElementById( "areaTexto" );
    var servicos = document.getElementById( "servicos" );
    var counter  = 0;

    servicos.innerHTML = "";

    if ( document.getElementById( "formulario" ).style.display != "block" ) {
        var titulo = getContentMetaTagByName( "title" );
        titulo = ( titulo.length > 32 && QTDE_COMENTARIOS > 1 ) ? titulo.substring( 0, 32 ) + "..." : titulo;

        var txtComentario = document.createElement( "h4" );
        txtComentario.innerHTML = ( logado() )
                              ? "<a href='javascript:showFormComentario()'>Comentar \"" + titulo + "\"</a>"
                              : "<a onmouseout='blockAviso()' onmouseover='showAviso()' class='inativo'>Comentar \"" + titulo + "\"</a>";

        servicos.appendChild( txtComentario );
        counter++;
    }

    if ( QTDE_COMENTARIOS > 1 ) {
        var txtTotal = document.createElement( "h4" );
        txtTotal.innerHTML = ( exibeTodos )
                             ? "<a href='javascript:showComentarios( false )'>Fechar coment&aacute;rios</a>"
                             : "<a href='javascript:showComentarios( true )'>Ver todos os coment&aacute;rios (total: " + QTDE_COMENTARIOS + ")</a>";

        servicos.appendChild( txtTotal );
        counter++;
    }

    if ( counter == 0 )  {
        document.getElementById( "boxServicos" ).style.display = "none";
    }
}

/**
 * Exibe os comentarios, paginacao e outras informacoes relacionadas.
 * @param {Boolean} exibeTodos Flag para exibicao de comentarios.
 */
function showComentarios( exibeTodos ) {
    if ( !document.getElementById( "totalComentarios" ) ) {
        var nodeComentarios = document.createElement( "div" );
        nodeComentarios.setAttribute( "id", "totalComentarios" );
        nodeComentarios.innerHTML = "<h2>Coment&aacute;rios</h2>&nbsp;(total: <strong>" + QTDE_COMENTARIOS + "</strong>)";

        try {
            var comentarios = document.getElementById( "comentarios" );

            if ( comentarios.childNodes.length == 0 ) {
                comentarios.appendChild( nodeComentarios );
            } else {
                comentarios.insertBefore( nodeComentarios, comentarios.childNodes.item(0) );
            }
        } catch( e ) {}
    }

    if ( exibeTodos && QTDE_COMENTARIOS > 1 ) {
        if ( QTDE_COMENTARIOS > MAX_RESULTS_PAGE ) {
            document.getElementById( "paginacao" ).style.display = "block";
        }

        pag.prepare( "paginacao", MAX_RESULTS_PAGE );
        getElementsByIdAndClassName( "comentarios", "texto" )[0].style.borderBottom  = "1px solid #F0F0F0";
        getElementsByIdAndClassName( "comentarios", "texto" )[0].style.paddingBottom = "10px";
    } else {
        document.getElementById( "paginacao" ).style.display     = "none";
        document.getElementById( "paginacaoDown" ).style.display = "none";

        for ( var i=0; i<QTDE_COMENTARIOS; i++ ) {
            if ( i == 0 ) {
                getElementsByIdAndClassName( "comentarios", "texto" )[i].style.display       = "block";
                getElementsByIdAndClassName( "comentarios", "texto" )[i].style.borderBottom  = "none";
                getElementsByIdAndClassName( "comentarios", "texto" )[i].style.paddingBottom = "5px";
            } else {
                getElementsByIdAndClassName( "comentarios", "texto" )[i].style.display = "none";
            }
        }
    }

    document.getElementById( "comentarios" ).style.display = "block";
    showServicos( exibeTodos );
}

/**
 * Verifica a quantidade de caracteres no campo de comentario.
 * @param {Object} element Nome do campo.
 */
function verificarQtdeCaracteres( element ) {
    if ( element.value.length > TEXT_MAX_LENGTH ) {
        element.value = element.value.substring( 0, TEXT_MAX_LENGTH );
    }
}

/**
 * Valida o formulario e realiza a inclusao do comentario em materia.
 */
function incluirComentario() {
    var frm   = document.comentarioForm;
    var texto = trim( frm.texto.value );

    frm.urlRetorno.value = document.location.href;

    PalavraProibidaAjaxController.verificaTexto( texto, function( resultado ) {
        if ( logado() ) {
            if ( texto == "" ) {
                alert( "Por favor, preencha o campo coment\u00E1rio!" );
                frm.texto.focus();
                return false;
            } else if ( texto.length > TEXT_MAX_LENGTH ) {
                alert( "Por favor, o campo coment\u00E1rio deve aceitar no m\u00E1ximo " + TEXT_MAX_LENGTH + " caracteres!" );
                frm.texto.focus();
                return false;
            } else {
                if ( resultado ) {                    
                    var action = frm.action;
                    if ( action.indexOf('fwa.abril.com.br') > -1 ) {
                    	frm.submit();
                    } else {
                    	postAjax(frm);
                    }
                } else {
                    alert( "N\u00E3o foi poss\u00EDvel publicar sua mensagem, pois ela cont\u00E9m termos ou frases inadequadas.\nPor favor, revise seu texto." );
                    return false;
                }
            }
        } else {
            alert("Para inserir um coment\u00E1rio voc\u00EA precisa estar autenticado.\nUse os campos no alto da p\u00E1gina para informar seus dados.");
            document.getElementById( "formulario" ).style.display = "none";
            showComentarios( false );
        }
    } );
}

/**
 * Obtem o status da request
 **/
function getReadyState() {
	if (httpRequest.readyState == 4) {
	      if (httpRequest.status == 200) {
			    //OK!
	      } else {
	           //mark Error
	      }
	}
}

/**
 * Post HTML to Ajax
 **/
function postAjax(form) {
	url = form.action;
	parameters = "";
	for (i = 0; i < form.elements.length; i++) {
		if ( parameters == "" ) {
			parameters = encodeURI(form.elements[i].name) +
				"=" + encodeURI(form.elements[i].value);
		} else {
			parameters += "&" + encodeURI(form.elements[i].name) +
				"=" + encodeURI(form.elements[i].value);
		}
	}
	httpRequest = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			// set type accordingly to anticipated content type
			httpRequest.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
		}
	}
	if (!httpRequest) {
		alert('Ajax not ready');
		return false;
	}
	// httpRequest.onreadystatechange = getReadyState;
	httpRequest.open('POST', url, true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpRequest.setRequestHeader("Content-length", parameters.length);
	httpRequest.setRequestHeader("Connection", "close");
	httpRequest.send(parameters);

	setTimeout("document.location.reload()",2000);
}


/**
 * Remove espacos em branco do inicio e fim de uma string.
 * @param {String} texto Texto a ser formatado.
 */
function trim( texto ) {
    return texto.replace( /^\s+/g,'' ).replace( /\s+$/g,' ' );
}

/**
 * Retorna um array com todos os elementos de "elementId" que possuam a classe indicada em "clsName".
 * @param {String} clsName Nome da classe onde os elementos serao procurados.
 * @param {String} elementId Id do elemento a ser procurado.
 */
function getElementsByIdAndClassName( elementId, clsName ) {
    var area     = document.getElementById( elementId );
    var elements = ( area.all ) ? area.all : area.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;
}

/**
 * Inicializa e carrega as configuracoes padroes.
 */
function initComentarios() {
    if ( document.getElementById( "paginaComentarios" ) ) {
        if ( document.getElementById( "comentarios" ) ) {
            TEXT_COMENTARIOS = getElementsByIdAndClassName( "comentarios", "texto" );
            QTDE_COMENTARIOS = TEXT_COMENTARIOS.length;

            try {
                var frm = document.comentarioForm;
                frm.txtNome.value = pass.getUsuario()[1];
            } catch( e ) {}

            showComentarios( false );
            showToolTipComentario();
        } else {
            document.getElementById( "paginaComentarios" ).style.display = "none";
        }
    }
}



/**
 * Lista de atributos do objeto Paginacao.
 */
Paginacao = function () {
    this.Paginacao = Paginacao;
    this.name      = "Paginacao";
    this.version   = "1.0v";
    this.total     = 0;
    this.qtdepag   = 0;
    this.obj       = null;
    this.regs      = 0;
    this.atualPage = 0;
}

var paginacao = Paginacao.prototype;

/**
 * Realiza os calculos necessarios para a exibicao da paginacao dos comentarios.
 * @param {String} obj Id do elemento onde sera exibida a paginacao.
 * @param {Integer} pages Qtde de comentarios por pagina.
 */
paginacao.prepare = function( obj, pages ) {
    this.total   = parseInt( QTDE_COMENTARIOS );
    this.qtdepag = parseInt( this.total / pages );
    var resto    = parseInt( this.total % pages );
    this.regs    = pages;
    this.obj     = document.getElementById( obj );

    if ( resto > 0 ) this.qtdepag++;

    for ( var i=0; i<this.total; i++ ) {
        TEXT_COMENTARIOS[i].style.display = "block";
    }

    if ( QTDE_COMENTARIOS > MAX_RESULTS_PAGE ) {
        this.pages(0);
    }
}

paginacao.back = function( page ) {
    if ( page > 0 ) {
        return "<li><a href=\"javascript:pag.goBack();\">Anterior</a></li> ";
    }

    return "";
}

paginacao.next = function( page ) {
    if ( page < ( this.qtdepag - 1 ) ) {
        return " <li><a href=\"javascript:pag.goNext();\">Pr&oacute;ximo</a></li>";
    }

    return "";
}

paginacao.pages = function( page ) {
    var text = "<p>P&aacute;ginas:</p><ul>";

    //text += this.back( page );

    for ( var i=0; i<this.qtdepag; i++ ) {
        text += ( i == page )
                ? "<li><a href=\"javascript:pag.goPage(" + i + ");\" class=\"paginaAtual\">"
                : "<li><a href=\"javascript:pag.goPage(" + i + ");\">";

        text += ( i + 1 ) + "</a></li>";
        text += ( i == ( this.qtdepag - 1 ) ) ? "" : "|";
    }

    //text += this.next( page );
    text += "</ul>";

    this.obj.innerHTML = ( this.qtdepag > 1 ) ? text : "";

    this.display( page );
}

paginacao.display = function( page ) {
    this.atualPage = page;
    var ini = ( page ) * this.regs;
    var end = ( page + 1 ) * this.regs;

    for ( var i=0; i<this.total; i++ ) {
        TEXT_COMENTARIOS[i].style.display = "none";
    }

    for ( i=ini; i<end; i++ ) {
        if ( TEXT_COMENTARIOS[i] ) {
            TEXT_COMENTARIOS[i].style.display = "block";
        }
    }

    var paginacaoDown = document.getElementById( "paginacaoDown" );
    paginacaoDown.innerHTML = document.getElementById( "paginacao" ).innerHTML;
    paginacaoDown.style.display = "block";
}

paginacao.goBack = function() {
    this.pages( this.atualPage - 1 );
}

paginacao.goNext = function() {
    this.pages( this.atualPage + 1 );
}

paginacao.goPage = function( page ) {
    this.pages( page );
}


var pag = new Paginacao();
