var navegador = navigator.appName;
var liberaDiv;

var hintVerticalOffset = 0;
function showHint(bit, tit, texto, offsetV)
{
    var hint = document.getElementById("TxtHint");
    var iframe = document.getElementById("iframe");
    if (bit)
    {
        if (!isNaN(parseInt(offsetV)))
            hintVerticalOffset = parseInt(offsetV);
        else
            hintVerticalOffset = 0;

        liberaDiv = true;

        if (navegador=="Microsoft Internet Explorer")
        {
            getXY();
            hint.innerHTML = '<div class="hintConteudoIE">'+texto+'</div>';
            iframe.style.height = hint.offsetHeight + "px";
            iframe.style.width = hint.offsetWidth + "px";
            iframe.style.visibility = "visible";
        }
        else
        {
            hint.innerHTML = '<div class="hintConteudoNS">'+texto+'</div>';
        }
        hint.style.visibility = "visible";
    }
    else
    {
        liberaDiv = false;
        hint.style.visibility = "hidden";
        iframe.style.visibility = "hidden";
    }
}

function init() {
    
    if (window.event && event.MOUSEMOVE) {
        document.captureEvents(event.MOUSEMOVE);
    }
    document.onmousemove = getXY;

    mostraDivAreaAtuacao();
    ajustaDivResultado();
    setScrollPosition();
    
}

function ajustaDivResultado(){
    var div = document.getElementById("divResultado");
    if(div)
    {
        if (navegador=="Microsoft Internet Explorer")
        {
            div.style.width = "99%";
        }
        else
        {
            div.style.width = "775px";
        }
    }

    div = document.getElementById("divGlossario");
    if(div)
    {
        if (navegador=="Microsoft Internet Explorer")
        {
            div.style.width = "99%";
        }
        else
        {
            div.style.width = "772px";
        }
    }

    div = document.getElementById("divResultadoAgrupado");
    if(div)
    {
        if (navegador=="Microsoft Internet Explorer")
        {
            div.style.width = "98%";
        }
        else
        {
            div.style.width = "774px";
        }
    }
}

function getXY(e)
{
    var scrollLeft = window.pageXOffset ? window.pageXOffset
                  : document.documentElement && document.documentElement.scrollLeft >= document.body.scrollLeft ? document.documentElement.scrollLeft
                  : document.body.scrollLeft;
    var scrollTop = window.pageYOffset ? window.pageYOffset
                  : document.documentElement && document.documentElement.scrollTop >= document.body.scrollTop ? document.documentElement.scrollTop
                  : document.body.scrollTop;


    if(navegador=="Microsoft Internet Explorer"){
    x = event.clientX + scrollLeft;
    y = event.clientY + scrollTop;
    }else{
    x = e.pageX;
    y = e.pageY;

    }
    y += hintVerticalOffset;

    if (liberaDiv) {
        document.getElementById("TxtHint").style.left = x + 10 + "px";
        document.getElementById("TxtHint").style.top = y + 23 + "px";
        document.getElementById("iframe").style.left = x + 10 + "px";
        document.getElementById("iframe").style.top = y + 23 + "px";
    }
}

function setNumPaginaLink(idElemento,valor){
    document.getElementById(idElemento).value = valor;
    return true;
}

function setValue(valor,nomeObjDestino){
    document.getElementById(nomeObjDestino).value = valor;
}

function mostraDivOper(){    
    if(document.getElementById("consulta:buscaOper:0").checked){
        document.getElementById("divOperadoras").style.display = "block";
    }else{
        document.getElementById("divOperadoras").style.display = "none";
    }

}

function mostraDivPreLiq(){

    if(document.getElementById("consulta:tipoPortabilidade:0").checked || document.getElementById("consulta:tipoPortabilidade:1").checked){
        document.getElementById("divLabelRegistroOperadora").style.display = "block";
        document.getElementById("divLabelRegistroPlano").style.display = "block";
        document.getElementById("divRegistroPlano").style.display = "block";
        document.getElementById("divAvancar").style.display = "block";
    }

    if(document.getElementById("consulta:tipoPortabilidade:0").checked){
        document.getElementById("divRegistroOperadora").style.display = "block";
        document.getElementById("divSelectOper").style.display = "none";
    }else if(document.getElementById("consulta:tipoPortabilidade:1").checked){
        document.getElementById("divSelectOper").style.display = "block";
        document.getElementById("divRegistroOperadora").style.display = "none";
    }

}

function mostraDivAreaAtuacao(){
    var isAbrengenciaIndiferenteChecked = false;
    var isAbrengenciaNacionalChecked = false;
    var isAbrengenciaGrupoEstadosChecked = false;
    var isAbrengenciaEstadualChecked = false;
    var isAbrengenciaGrupoMunicipiosChecked = false;
    var isAbrengenciaMunicipalChecked = false;

    if(document.getElementById("consulta:tipoAbrangencia:0"))
    {
        isAbrengenciaIndiferenteChecked = document.getElementById("consulta:tipoAbrangencia:0").checked;
        isAbrengenciaNacionalChecked = document.getElementById("consulta:tipoAbrangencia:1").checked;
        isAbrengenciaGrupoEstadosChecked = document.getElementById("consulta:tipoAbrangencia:2").checked;
        isAbrengenciaEstadualChecked = document.getElementById("consulta:tipoAbrangencia:3").checked;
        isAbrengenciaGrupoMunicipiosChecked = document.getElementById("consulta:tipoAbrangencia:4").checked;
        isAbrengenciaMunicipalChecked = document.getElementById("consulta:tipoAbrangencia:5").checked;

        if(isAbrengenciaNacionalChecked){

            document.getElementById("divNacional").style.display = "block";
            document.getElementById("divGrupoEstados").style.display = "none";
            document.getElementById("divEstadual").style.display = "none";
            document.getElementById("divGrupoMunicipios").style.display = "none";
            document.getElementById("divMunicipal").style.display = "none";
        }
        else if(isAbrengenciaEstadualChecked){

            document.getElementById("divNacional").style.display = "none";
            document.getElementById("divGrupoEstados").style.display = "none";
            document.getElementById("divEstadual").style.display = "block";
            document.getElementById("divGrupoMunicipios").style.display = "none";
            document.getElementById("divMunicipal").style.display = "none";
        }
        else if(isAbrengenciaGrupoEstadosChecked){

            document.getElementById("divNacional").style.display = "none";
            document.getElementById("divGrupoEstados").style.display = "block";
            document.getElementById("divEstadual").style.display = "none";
            document.getElementById("divGrupoMunicipios").style.display = "none";
            document.getElementById("divMunicipal").style.display = "none";
        }
        else if(isAbrengenciaMunicipalChecked){

            document.getElementById("divNacional").style.display = "none";
            document.getElementById("divGrupoEstados").style.display = "none";
            document.getElementById("divEstadual").style.display = "none";
            document.getElementById("divGrupoMunicipios").style.display = "none";
            document.getElementById("divMunicipal").style.display = "block";
        }
        else if(isAbrengenciaGrupoMunicipiosChecked || isAbrengenciaIndiferenteChecked){

            document.getElementById("divNacional").style.display = "none";
            document.getElementById("divGrupoEstados").style.display = "none";
            document.getElementById("divEstadual").style.display = "none";
            document.getElementById("divGrupoMunicipios").style.display = "block";
            document.getElementById("divMunicipal").style.display = "none";
        }
    }
}

function getCoOperadora(coOperadora){
    document.getElementById("consulta:coOperadora").value = coOperadora;
    return true;
}


function getNumeroRegistro(numeroRegistro){
    document.getElementById("consulta:numeroRegistro").value = numeroRegistro;
    return true;
}

function getIdPlano(id){
    document.getElementById("consulta:idPlano").value = id;
    return true;
}

function dump(o)
{
    var d = "";
    for (var e in o)
        d += e + ": " + o[e] + "\n";
    return d;
}

function validarInfoOperadora(){
    if((!document.getElementById("consulta:rdOperadora:0").checked &&
      !document.getElementById("consulta:rdOperadora:1").checked &&
      !document.getElementById("consulta:rdOperadora:2").checked) ||
       document.getElementById("consulta:codigoInfoOperadora").value == null ||
       document.getElementById("consulta:codigoInfoOperadora").value.trim() == ""){

        alert("É necessário informar o tipo e o campo da pesquisa para filtrar a operadora.");
        return false;
    }
return true;    
}

String.prototype.trim = function() {
var a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};

function validarFiltro(){

    
    if(document.getElementById("consulta:municipio_contratacao").value == null ||
            document.getElementById("consulta:municipio_contratacao").value == ""){
        alert("É necessário informar local de contratação do plano(Estado e Município).");

        return  false;
    }
    if(!document.getElementById("consulta:tipoAbrangencia:0").checked &&
       !document.getElementById("consulta:tipoAbrangencia:1").checked &&
       !document.getElementById("consulta:tipoAbrangencia:2").checked &&
       !document.getElementById("consulta:tipoAbrangencia:3").checked &&
       !document.getElementById("consulta:tipoAbrangencia:4").checked &&
       !document.getElementById("consulta:tipoAbrangencia:5").checked){
        alert("É necessário informar 1 (uma) Abrangência para efetuar a pesquisa.");
        return false;
    }

    if(document.getElementById("consulta:tipoAbrangencia:0").checked){
       if( document.getElementById("consulta:uf_municipios_selecionados").length == 0){
           alert("É necessário informar 1 (um) ou mais municípios para efetuar a pesquisa.");
           return false;
       }
    }

    if(document.getElementById("consulta:tipoAbrangencia:2").checked){
       if( document.getElementById("consulta:uf_municipios_selecionadosGrupoEstados").length == 0){
           alert("É necessário informar 1 (um) ou mais estados para efetuar a pesquisa.");
           return false;
       }
    }
    if( document.getElementById("consulta:tipoAbrangencia:3").checked ){
       if( document.getElementById("consulta:uf_municipios_selecionadosEstadual").length == 0){
           alert("É necessário informar 1 (um) estado para efetuar o filtro.");
           return false;
       }
    }

    if(document.getElementById("consulta:tipoAbrangencia:4").checked){
       if( document.getElementById("consulta:uf_municipios_selecionados").length == 0){
           alert("É necessário informar 1 (um) ou mais municípios para efetuar a pesquisa.");
           return false;
       }
    }
    if( document.getElementById("consulta:tipoAbrangencia:5").checked ){
       if( document.getElementById("consulta:uf_municipios_selecionadosMunicipal").length == 0){
           alert("É necessário informar 1 (um) município para efetuar a pesquisa.");
           return false;
       }
    }

   if(!document.getElementById("consulta:Amb_Hos_Obs_Odo").checked &&
       !document.getElementById("consulta:Amb_Hos").checked &&
       !document.getElementById("consulta:Amb").checked &&
       !document.getElementById("consulta:Amb_Hos_Obs").checked &&
       !document.getElementById("consulta:Amb_Odo").checked &&
       !document.getElementById("consulta:Hos").checked &&
       !document.getElementById("consulta:Amb_Hos_Odo").checked &&
       !document.getElementById("consulta:Hos_Obs").checked &&
       !document.getElementById("consulta:Odo").checked &&
       !document.getElementById("consulta:Hos_Obs_Odo" ).checked &&
       !document.getElementById("consulta:Hos_Odo").checked){

          alert("É necessário informar 1 (um) ou mais Tipos de Cobertura para efetuar a pesquisa.");
          return false;
   }

    if(!document.getElementById("consulta:acomodacao:0").disabled){
        if(!document.getElementById("consulta:acomodacao:0").checked &&
          !document.getElementById("consulta:acomodacao:1").checked &&
          !document.getElementById("consulta:acomodacao:2").checked){
            alert("É necessário informar 1 (um) Tipo de Acomodação para efetuar a pesquisa.");
            return false;
        }
    }

    if(!document.getElementById("consulta:fator_moderador:0").checked &&
      !document.getElementById("consulta:fator_moderador:1").checked &&
      !document.getElementById("consulta:fator_moderador:2").checked){
        alert("É necessário informar 1 (uma) opção de Fator Moderador para efetuar a pesquisa.");
        return false;
    }

    if(!document.getElementById("consulta:contratacao:0").disabled){
        if(!document.getElementById("consulta:contratacao:0").checked &&
          !document.getElementById("consulta:contratacao:1").checked &&
          !document.getElementById("consulta:contratacao:2").checked){

        alert("É necessário informar 1 (um) Tipo de Contratação para efetuar a pesquisa.");
        return false;
        }
    }

    if(!document.getElementById("consulta:faixa_preco_1").disabled){
        if(!document.getElementById("consulta:faixa_preco_1").checked &&
          !document.getElementById("consulta:faixa_preco_2").checked &&
          !document.getElementById("consulta:faixa_preco_3").checked &&
          !document.getElementById("consulta:faixa_preco_4").checked &&
          !document.getElementById("consulta:faixa_preco_5").checked){
            alert("É necessário informar 1 (uma) ou mais Faixas de Preço para efetuar a pesquisa.");
            return false;
        }
    }

    if (document.getElementById("consulta:capcha").value == ""){
        alert("Digite o texto da imagem para efetuar a consulta!");
        return false;
    }

    if(document.getElementById("consulta:buscaOper:0") != null){
        if(document.getElementById("consulta:buscaOper:0").checked){
            if( document.getElementById("consulta:operadorasSelecionadas").length == 0){
               alert("Você não terminou de preencher o filtro por operadora. Este critério será ignorado!");
           }
        }
    }

    setTimeout(mostrarPanelLoading, 100);
    getScrollPositionCapcha();
    
    

    return true;
}

function abrePaginaSucesso(url){
    document.location.href = url;
}

/**
 * Verifica se uma data especificada como parâmetro como uma
 * String no formato DD/MM/YYYY é uma data válida, e retorna
 * true caso afirmativo, e false caso contrário.
 *
 *
 */
function verificarData(strData)
{

    // Formato padrão de data no Brasil DD/MM/YYYY
	var data_PT_BR = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

	// verifica se está no formato
	if (!strData.match(data_PT_BR))
		return false;

	var partes = strData.split('/');
	var dia = parseInt(partes[0], 10);
	var mes = parseInt(partes[1], 10);
	var ano = parseInt(partes[2], 10);

	// Testa ano bissexto
	var bissexto = false;
	if ((ano%4==0) && ((ano%100!=0) || (ano%400==0)))
		bissexto = true;

	// Ano deve ser entre 1 e 12
	if (mes < 1 || mes > 12)
		return false;

	var diasMes = {1:	31,					// Janeiro
					2:	bissexto ? 29 : 28,	// Fevereiro
					3:	31,					// Março
					4:	30,					// Abril
					5:	31,					// Maio
					6:	30,					// Junho
					7:	31,					// Julho
					8:	31,					// Agosto
					9:	30,					// Setembro
					10:	31,					// Outrubro
					11:	30,					// Novembro
					12:	31};				// Dezembro

	// verifica o dia valido para cada mes
	if (dia < 1 || dia > diasMes[mes])
		return false;

	return true;
}



/**
 * Verifica se uma data especificada como parâmetro é uma data válida no periodo
 * desde o ano base especificado até a data atual, e retorna
 * true caso afirmativo, e false caso contrário.
 * Assume que a data informada é consistente e no formato dd/mm/aaaa.
 *
 */
function validaDataPeriodo(strData,anoBase)
{
	
	var partes = strData.split('/');
	var dia = parseInt(partes[0], 10);
	var mes = parseInt(partes[1], 10);
	var ano = parseInt(partes[2], 10);

     
    // Testa limite inferior.
    if(ano < anoBase)
        return false;

    // Testa se data é maior que a data atual.
    var dataAtual = new Date();
    var mesAtual = dataAtual.getMonth() + 1;
    var diaAtual = dataAtual.getDate();
    var anoAtual = dataAtual.getFullYear();
   
    if(ano > anoAtual)
        return false;

    if(ano == anoAtual){
        
        if(mes > mesAtual)
           return false;
        
        if(mes == mesAtual)
           if(dia > diaAtual) 
                return false;
    }

	return true;
}

function getScrollPosition(){
    document.getElementById("consulta:scroll").value = "1";
    document.getElementById("consulta:scrollPositionX").value = window.pageXOffset ? window.pageXOffset
                  : document.documentElement && document.documentElement.scrollLeft >= document.body.scrollLeft ? document.documentElement.scrollLeft
                  : document.body.scrollLeft;
    document.getElementById("consulta:scrollPositionY").value = window.pageYOffset ? window.pageYOffset
                  : document.documentElement && document.documentElement.scrollTop >= document.body.scrollTop ? document.documentElement.scrollTop
                  : document.body.scrollTop;
}


function getScrollPositionCapcha(){
    document.getElementById("consulta:scroll").value = "0";
    document.getElementById("consulta:scrollPositionXCapcha").value = window.pageXOffset ? window.pageXOffset
                  : document.documentElement && document.documentElement.scrollLeft >= document.body.scrollLeft ? document.documentElement.scrollLeft
                  : document.body.scrollLeft;
    document.getElementById("consulta:scrollPositionYCapcha").value = window.pageYOffset ? window.pageYOffset
                  : document.documentElement && document.documentElement.scrollTop >= document.body.scrollTop ? document.documentElement.scrollTop
                  : document.body.scrollTop;
 
}

function setScrollPosition(){

    if(document.getElementById("consulta:scrollPositionX")){
        var x = document.getElementById("consulta:scrollPositionX").value;
        var y = document.getElementById("consulta:scrollPositionY").value;
        window.scroll(x, y);
        document.getElementById("consulta:scroll").value = "0";
    }
}

function limparScrollPosition(){
    if(document.getElementById("consulta:scrollPositionX")){
        window.scroll(0,0);
    }
}

function validaRadioHome(){
   if (! document.consulta.radioHome[0].checked && ! document.consulta.radioHome[1].checked &&
       ! document.consulta.radioHome[2].checked && ! document.consulta.radioHome[3].checked){
        alert("Por favor selecione a consulta desejada !");
        return false;
   }
   return true;
}

function noHistoryBack(){
    userAgent = navigator.userAgent.toLowerCase();
    function noBack(){
        window.history.forward()
    }
    noBack();
    //Somente p/ o firefox.
    if (userAgent.indexOf("firefox") > 0){
        window.onload = noBack;
        window.onpageshow = function(evt){if(evt.persisted)noBack()}
        window.onunload = function(){void(0)}
    }
}

function finalizarFiltro(){
    
   if(document.getElementById("consulta:scroll").value == "0"){
       var xmlhttp;

        if (window.XMLHttpRequest)
        {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {        // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET", "ServletUtil", true);
        xmlhttp.send(null);
        limparScrollPosition();
    }
}

var iframeLoading   = null;
var divLoading = null;

function mostrarPanelLoading(){
    if (iframeLoading == null)
        criarPanelLoading();

    iframeLoading.style.visibility   = "visible";
    divLoading.style.visibility = "visible";
    limparScrollPosition();
}
function esconderPanelLoading(){
    iframeLoading.style.visibility   = "hidden";
    divLoading.style.visibility = "hidden";
}
function criarPanelLoading(){
    var scrollTop = f_scrollTop();
    var viewport  = getViewPort();

    iframeLoading = document.createElement("iframe");
    with(iframeLoading){
        frameborder = "0";
        src = "about:blank";
        id = "iPopup";
        name = "iPopup";
        style.backgroundColor = "white";
        style.position = "absolute";
        style.width = (getViewPort().width - 4) + "px";
        style.height = (getPageSize()-5)+"px";
        style.opacity = "0.5";
        style.filter = "alpha(opacity=50)";
        style.visibility = "hidden";
        style.top = 0;
        style.zIndex = 10000;
    }

    divLoading = document.createElement("div");
    with(divLoading){
        id = "divPopup";
        style.position = "absolute";
        style.width = "100%";
        style.visibility = "hidden";
        style.height = (viewport.height)+'px';
        style.top   = scrollTop + "px";
        style.textAlign = "center";
        style.zIndex = 10001;
        innerHTML = '<table width="100%" height="100%" border="0"><tr><td valign="center" align="center" style="color:#006400;font-size:15px;"><img alt="Pesquisando..." src="Images/loader.gif" /><br/><b>Pesquisando...</b></td></tr></table>';
    }
    document.body.appendChild(iframeLoading);
    document.body.appendChild(divLoading);
    
}
function getViewPort(){

    var viewportwidth;
    var viewportheight;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

    if (typeof window.innerWidth != 'undefined')
    {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
    {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
    }

    // older versions of IE

    else
    {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
       viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }

    return {width:viewportwidth, height:viewportheight};

} 

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;
}

function getPageSize(){
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    return pageHeight;
}
