﻿// A ORDEM DE FUNCIONAMENTO DOS METODOS DA NOVA BUSCA É A SEGUINTE:
//
// buscarDados
// requisitarBusa
// TratarDados
//
// ASHX
// SearchVideo (dll)
//
// TratarDados
// MontaResultados
// MontaTabela (x60)
// brtimg

// JScript source code

//TODO: Função que pega URL e joga valores nos campos de pesquisa
//Não está pronta. Fazer...
function imgFotosCD(idCD)
{
    //var idIdioma = (document.getElementById('ctl00_publicidade_lingua_port').checked) ? 1 : 3;
    var idIdioma = (document.getElementById('ctl00_cd_lingua_port').checked ? 1 : 3);
    var somenteCd = (document.getElementById('ctl00_somente_cd').checked) ? '1' : '0' ;
    var criativo = (document.getElementById('ctl00_editorial_tipo_criativo').checked) ? 1 : 0;
    var newsearch = Math.random() * 1000000;
    var indicePaginacao = document.getElementById('ctl00_paginacao').selectedIndex;
    var NumeroFotos = document.getElementById('ctl00_paginacao').options[indicePaginacao].value;
   	var preco = document.getElementById('ctl00_preco').options[document.getElementById('ctl00_preco').selectedIndex].value;

    paginaBusca = '../dotnet/SearchResult.ashx?' +
        'newsearch=' + newsearch + '&' +
        'pchave=__' + idCD +'&' +
        'numerodefotos=' +  NumeroFotos + "&" +
        'produtodc=&' +
        'produtorf=&' +
        'pb=&' +
        'ilustracao=&' +
        'usopesq=&' +
        'modelrelease=0&' +
        '__idssinonimo=&' +
        'TipoConsulta=&' +
        'id_colecao_dc=&' +
        'id_colecao_rf=&' +
        'id_colecao_dcrf=&' +
        'plano=&' +
        'ckCdRf=&' +
        '__hotgrid=False&' +
        '__origem=&' +
        'bav=false&' +
        '__pagina=1'+'&' +
        'buscarresultado=false&' +
        'ck_download=&' +
        'oripesq=&' +
        'editorial=&' +
        'publicidade=&' +
        'rangedata=&' +
        'datapesquisa=&' +
        'menuId='+ MenuId + '&' +
        'idIdioma=' + idIdioma + '&' +
        'clarificar=&' +
        'isClarificar=&' +
        'somenteCd=&' +
        'pessoas=&' +
        'categoria=&' +
        'criativo=' + criativo + '&' +
		'preco=' + preco + '&' +
        'nowait=1';

    var sCook = "Idioma=" + idIdioma.toString(); 
    document.cookie = sCook;

    EnviarPedido(paginaBusca, TratarDados, parametros, 'GET');
}

//Função para criar o HTTPREQUEST
function ReturnAjax()
{
      var ajax = false;
    try
      {
        ajax = new XMLHttpRequest();
    }
      catch(ee)
      {
          
        try
            {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
        }
            catch(e)
            {
            try{
                ajax = new ActiveXObject("Microsoft.XMLHTTP");
            }
                  catch(E)
                  {
                ajax = false;
            }
        }
    }
    
    return ajax;
}
/**
 * Função que faz uma requisição via ajax
 * url = Página que gerará os resultados
 * func = Função javascript que tratará os dados retornados
 * valores = parametros a serem passados no formato var1=valor1&var2=valor2&varN=valorN
 * tipo = Indica se a requisição é via POST ou GET
 */
function EnviarPedido(url, func, valores, tipo, NoHistory,StopInterval)
{    
    if(url.length > 0)
    {
        if(!ajax)
        {
            alert('Seu browser não suporta ajax!');
            return;
        }
        else// Se houver algum pedido ajax em andamento, aborta.
            AbortAjax();
        if(!tipo)
            tipo = 'POST';
        if(valores == '')
            valores = null;
      
        if(document.all)
            url = UrlEncode(url);
        
        pedido_busy = true;        
        ajax.open(tipo, url, true);
        UltimaUrl = url;
          
          
        //TIAGO  
        //GetElements();
        
        // Para envio via POST
        if(tipo == 'POST')
            ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
        
        // Limpa o cache para novas requisições
        ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        ajax.setRequestHeader("Pragma", "no-cache");
        // Chama a função que vai tratar os dados
        ajax.onreadystatechange = func;
        //Envia os dados
        ajax.send(valores);
          
        if(NoHistory != true)
        {
            if(StopInterval != true)
            {   
                dhtmlHistory.add(UltimaUrl);
            }
        }
        
        if(StopInterval != true)
            clearInterval(intervalo);
        
        var Pag = parseInt(url.substr(url.indexOf('__pagina=') +9,2).replace('&',''));//Pega o número da página pesquisada
        if(Pag > 0)
            pagina = Pag;
        if (url.indexOf("@@")> -1 )
        { document.getElementById('ctl00_pesquisa_campo').value =  document.getElementById('ctl00_pesquisa_campo').value;
        }
        else
            {

            //    Adicionado provisoriamente -> Tiago (Chleba)
	        if(document.all) //ie
		        document.getElementById('ctl00_pesquisa_campo').value = QueryStringInUrl(UrlDecode(UltimaUrl),'pchave').replace('!!','');
	        else //mozila
		        document.getElementById('ctl00_pesquisa_campo').value = QueryStringInUrl(UltimaUrl,'pchave').replace('!!','');
          }
      }
}

function AbortAjax()
{
    //if(ajax)
    //    if(ajax.readyState != 0)
            ajax.abort();
}

function imgSerie(codSerie)
{
    OcultarDivsGerenciar();
    ExibirDivMenu('PainelCarregando'); 
    
    document.getElementById('PainelLegenda').style.display = 'none';
    document.getElementById("tabelaResultado").style.display = 'none';
    document.getElementById('ctl00_DvTblResultado').style.display = 'none';
    document.getElementById('ctl00_DvTblResultado').scrollTop = 0;
    
    LimpaTabela(); 
   
    var idIdioma = (document.getElementById('ctl00_publicidade_lingua_port').checked) ? 1 : 3;
    var somenteCd = (!document.getElementById('ctl00_publicidade_layout').checked) ? '0' : '1';
    var newsearch = Math.random() * 1000000;
    var indicePaginacao = document.getElementById('ctl00_paginacao').selectedIndex;
    var NumeroFotos = document.getElementById('ctl00_paginacao').options[indicePaginacao].value;

    paginaBusca = '../dotnet/SearchResult.ashx?' +
        'newsearch=' + newsearch + '&' +
        'pchave=@@' + codSerie + '&' +
        'numerodefotos=' +  NumeroFotos + "&" +
        /*'produtodc=&' +
        'produtorf=&' +
        'pb=&' +
        'ilustracao=&' +
        'usopesq=&' +
        'modelrelease=0&' +
        '__idssinonimo=&' +
        'TipoConsulta=&' +
        'id_colecao_dc=&' +
        'id_colecao_rf=&' +
        'id_colecao_dcrf=&' +
        'plano=&' +
        'ckCdRf=&' +
        '__hotgrid=False&' +
        '__origem=&' +
        'bav=false&' +
        '__pagina=' + pagina + '&' +
        'buscarresultado=false&' +
        'ck_download=&' +
        'oripesq=&' +
        'editorial=&' +
        'publicidade=&' +
        'rangedata=&' +
        'datapesquisa=&' +
        'menuId=false&' +*/
        'idIdioma=' + idIdioma + '&' +/*
        'clarificar=&' +
        'isClarificar=&' +
        'somenteCd=&' +
        'pessoas=&' +
        'categoria=&' 
        'criativo=' + criativo + '&' +*/
        'nowait=1';
        
        //paginaBusca = '../dotnet/SearchResult.ashx?newsearch=628555.2007338513&pchave=carro&numerodefotos=60&produtodc=dc&produtorf=rf&pb=&ilustracao=&usopesq=&modelrelease=0&__idssinonimo=&TipoConsulta=&id_colecao_dc=0&id_colecao_rf=0&id_colecao_dcrf=&plano=0&orientacao=&ckCdRf=&__hotgrid=False&__origem=&bav=false&__pagina=1&buscarresultado=false&ck_download=&oripesq=1&editorial=false&publicidade=true&rangedata=9999&datapesquisa=&menuId=117&idIdioma=1&clarificar=&isClarificar=false&somenteCd=0&pessoas=&categoria=&criativo=0&nowait=1'    
    /*   
        var sCook = "Idioma=" + idIdioma.toString(); 
        document.cookie = sCook;
    */
   
    EnviarPedido(paginaBusca, TratarDados, parametros, 'GET');
    buscarClarificador = false;    
}

function imgSimilar(idFoto)
{
    OcultarDivsGerenciar();
    ExibirDivMenu('PainelCarregando');  
    
    document.getElementById('ctl00_DvTblResultado').scrollTop = 0;
    document.getElementById('ctl00_DvTblResultado').style.display = 'none';
    document.getElementById('PainelLegenda').style.display = 'none';
    document.getElementById("tabelaResultado").style.display = 'none';
    
    LimpaTabela();
   
    var idIdioma = (document.getElementById('ctl00_publicidade_lingua_port').checked) ? 1 : 3;
    var somenteCd = (!document.getElementById('ctl00_publicidade_layout').checked) ? '0' : '1';
    var newsearch = Math.random() * 1000000;
    var indicePaginacao = document.getElementById('ctl00_paginacao').selectedIndex;
    var NumeroFotos = document.getElementById('ctl00_paginacao').options[indicePaginacao].value;
	var preco = document.getElementById('ctl00_preco').options[document.getElementById('ctl00_preco').selectedIndex].value;

    paginaBusca = '../dotnet/SearchResult.ashx?' +
        'newsearch=' + newsearch + '&' +
        'pchave=--' + idFoto + ' e nao '+ pBusca.toLowerCase()  +'&' +
        'numerodefotos=' +  NumeroFotos + "&" +
        'produtodc=&' +
        'produtorf=&' +
        'pb=&' +
        'ilustracao=&' +
        'usopesq=&' +
        'modelrelease=0&' +
        '__idssinonimo=&' +
        'TipoConsulta=&' +
        'id_colecao_dc=&' +
        'id_colecao_rf=&' +
        'id_colecao_dcrf=&' +
        'plano=&' +
        'ckCdRf=&' +
        '__hotgrid=False&' +
        '__origem=&' +
        'bav=false&' +
        '__pagina=' + pagina + '&' +
        'buscarresultado=false&' +
        'ck_download=&' +
        'oripesq=&' +
        'editorial=&' +
        'publicidade=&' +
        'rangedata=&' +
        'datapesquisa=&' +
        'menuId=false&' +
        'idIdioma=' + idIdioma + '&' +
        'clarificar=&' +
        'isClarificar=&' +
        'somenteCd=&' +
        'pessoas=&' +
        'categoria=&' +
        'criativo=' + criativo + '&' +
		'preco=' + criativo + '&' +
        'nowait=1';

    var sCook = "Idioma=" + idIdioma.toString(); 
    document.cookie = sCook;

    EnviarPedido(paginaBusca, TratarDados, parametros, 'GET');
    buscarClarificador = false;
}

function TratarDadosPanther()
{
    if(ajax.readyState == 4)
    {
        if(ajax.status == 200)
        {
            var response = ajax.responseText;
            if(response.indexOf('^') > -1)
            {
                var dados = response.split('^');
                
                
                var Qtd = parseInt(dados[0]);
                if(Qtd > 4150)
                {
                    Qtd = 4150
                }
               
                var elemPagina = document.getElementById('Pagina');
                var elemPaginaBottom = document.getElementById('PaginaBottom');
                
                TotalDePaginas = parseInt(Math.ceil(Qtd / 50));
                PaginaAtual = pagina;
                
                document.getElementById('PaginaAtual').innerHTML = pagina;
                document.getElementById('PaginaFinal').innerHTML = TotalDePaginas;
                document.getElementById('PaginaAtualBottom').innerHTML = pagina;
                document.getElementById('PaginaFinalBottom').innerHTML = TotalDePaginas;
                document.getElementById('cachekey').value = '';

                if(pagina == TotalDePaginas || pagina > TotalDePaginas)
                {
                    elemPagina.value = '1';
                    elemPaginaBottom.value = '1';
                }
                else
                {
                    elemPagina.value = pagina + 1;
                    elemPaginaBottom.value = pagina + 1;
                }

                LimpaTabela();
              
                if(Qtd == 4150)
                {
                    document.getElementById('NumeroTotalFotos').innerHTML = '4150+' ;
                    document.getElementById('NumeroTotalFotosBottom').innerHTML = '4150+';
                }
                else
                {
                    document.getElementById('NumeroTotalFotos').innerHTML = Qtd;
                    document.getElementById('NumeroTotalFotosBottom').innerHTML = Qtd;
                }
                                                                
                document.getElementById('PainelResultados').style.display = 'block';
                

                // Dados da Busca

                var dadosBusca = dados[1];

                imagens = dadosBusca.split('~');
                var cont = imagens.length;
                var dadosImagens;

                fim = imagens.length - 1;
                FOTOSPORLINHA = 4;

                intTotalLinhas = parseInt(Math.ceil((fim  + 1) / FOTOSPORLINHA));
                primLinhas = true;

                intColuna = 0;
                intLinha = 0;
                intRegistro = 0;

                MontaResultadosPanther(imagens);


                    
                document.getElementById('PainelResultadosBottom').style.display = 'block';
                      
                if(pagina == 1)
                {
                    document.getElementById('LinkAnterior').style.visibility = 'hidden';
                    if(TotalDePaginas > 1)
                    {
                        document.getElementById('LinkProximo').style.visibility = 'visible';
                    }
                    else
                    {
                        document.getElementById('LinkProximo').style.visibility = 'hidden';
                    }
                    document.getElementById('LinkAnteriorBottom').style.visibility = 'hidden';
                    if(TotalDePaginas > 1)
                    {
                        document.getElementById('LinkProximoBottom').style.visibility = 'visible';
                    }
                    else
                    {
                        document.getElementById('LinkProximoBottom').style.visibility = 'hidden';
                    } 
                                   
                }
                else if(pagina == TotalDePaginas)
                {
                    document.getElementById('LinkAnterior').style.visibility = 'visible';
                    document.getElementById('LinkProximo').style.visibility = 'hidden';
                    document.getElementById('LinkAnteriorBottom').style.visibility = 'visible';
                    document.getElementById('LinkProximoBottom').style.visibility = 'hidden';
                }
                else
                {
                    document.getElementById('LinkAnterior').style.visibility = 'visible';
                    document.getElementById('LinkProximo').style.visibility = 'visible';
                    document.getElementById('LinkAnteriorBottom').style.visibility = 'visible';
                    document.getElementById('LinkProximoBottom').style.visibility = 'visible';
                }
            }
            else
            {
                //if(response.indexOf('ERR:') > -1)
                //    alert(response);
                var errResponse  
                if(response.indexOf('ERR:') > -1)
                {
                    errResponse = '<li>' + response + '<br /></li>';
                }                    
                else
                {
                    errResponse = '';
                }
                    
                document.getElementById('PainelResultados').style.display = 'none';                      
                document.getElementById('PainelResultadosBottom').style.display = 'none';
                document.getElementById('Clarificador').style.display = 'none';
                document.getElementById('ConteudoDinamico').innerHTML = '' +
                '<div style="padding: 0px 43px;"><table border="0">' +
                    '<tr>' +
                        '<td class="Estilo16">Sua pesquisa não retornou nenhuma imagem.<br />' +
                            '<ul>' +
                                        errResponse+       
                                       '<li>Verifique se você digitou a(s) palavra(s) corretamente;<br /></li>' +
                                       '<li>Se digitou muitas palavras ao mesmo tempo, tente pesquisar algumas por vez.<br />' +
                                       'Assim você poderá excluir qual delas não existe em nosso vocabulário;<br /></li>' +
                                       '<li>Faça a mesma coisa com frases. Ex: criança comendo cachorro-quente não retornou nada. Tente ' +
                                       'primeiro cachorro-quente. Se vierem muitas imagens, tente comendo cachorro-quente e assim ' +
                                       'por diante;<br /></li>' +
                                       '<li>Combinações booleanas (E, OU, NÃO) podem não resultar imagens. Verifique se as combinou corretamente;<br /></li>' +
                                       '<li>Caso tenha dúvidas, leia nossas <a href="http://beta.latinstock.com.br/br/ajudanet/indexacaobr.aspx"> dicas </a> ou ligue para (5511) 3097 3000 e converse com nossos atendentes. Nosso sistema permite recuperar palavras que não retornaram nenhuma imagem. Logo teremos a possibilidade de inseri-las, caso ilustre alguma imagem que possamos ter. Nossa preocupação é fazer com que a sua pesquisa seja precisa obtendo os melhores resultados do seu trabalho.</li>' +
                            '</ul></td>' +
                        '</tr>' +
                    '</table></div>';
            }
            document.getElementById('PainelCarregando').style.display = 'none';
            ExibirDivMenu('ConteudoDinamico');
        }
        else
        {
            var headers = ajax.getAllResponseHeaders();
            document.getElementById('PainelResultados').style.display = 'none';                      
            document.getElementById('PainelResultadosBottom').style.display = 'none';
            document.getElementById('Clarificador').style.display = 'none';
            document.getElementById('ConteudoDinamico').innerHTML = '' +
            '<div style="padding: 0px 43px;"><table border="0">' +
                '<tr>' +
                    '<td class="Estilo16">Sua pesquisa não retornou nenhuma imagem.<br />' +
                        '<ul>' +
                                   '<li> Erro: ' + ajax.status + ': ' + ajax.statusText + '<br /></li>' +
                                   '<li>' + headers + '<br /></li>' +
                                   '<li>Verifique se você digitou a(s) palavra(s) corretamente;<br /></li>' +
                                   '<li>Se digitou muitas palavras ao mesmo tempo, tente pesquisar algumas por vez.<br />' +
                                   'Assim você poderá excluir qual delas não existe em nosso vocabulário;<br /></li>' +
                                   '<li>Faça a mesma coisa com frases. Ex: criança comendo cachorro-quente não retornou nada. Tente ' +
                                   'primeiro cachorro-quente. Se vierem muitas imagens, tente comendo cachorro-quente e assim ' +
                                   'por diante;<br /></li>' +
                                   '<li>Combinações booleanas (E, OU, NÃO) podem não resultar imagens. Verifique se as combinou corretamente;<br /></li>' +
                                   '<li>Caso tenha dúvidas, leia nossas <a href="http://beta.latinstock.com.br/br/ajudanet/indexacaobr.aspx"> dicas </a> ou ligue para (5511) 3097 3000 e converse com nossos atendentes. Nosso sistema permite recuperar palavras que não retornaram nenhuma imagem. Logo teremos a possibilidade de inseri-las, caso ilustre alguma imagem que possamos ter. Nossa preocupação é fazer com que a sua pesquisa seja precisa obtendo os melhores resultados do seu trabalho.</li>' +
                        '</ul></td>' +
                    '</tr>' +
                '</table></div>';
            document.getElementById('PainelCarregando').style.display = 'none';
            ExibirDivMenu('ConteudoDinamico');                
        }
    }
}

function TratarDados()
{
//  document.getElementById('PagNavegacao').style.display = 'none';
    if(ajax.readyState == 4)
    {
        if(ajax.status == 200)
        {
            var response = ajax.responseText;
            if(response.indexOf('^') > -1)
            {
                var dados = response.split('^');
                
                // Dados do Cabeçalho
                var cab = dados[0];
                // Separa os dados do cabeçalho
                var dadosCab = dados[0].split('¨');
                
                // Monta o cabeçalho
                //{0}  Número total de fotos
                //{1}  Número total de páginas
                //{2}  Número de fotos por página
                //{3}  Indica se é um redirecionamento ou não
                //{4}  Hash da página
                //{5}  País do usuário
                //{6}  Se é para exibir lista de palavras a clarificar
                //{7}  Palavras a clarificar
                //{8}  A busca da Corbis foi On-Line ou Off-Line
                //{9}  Codigo do CD
                //{10} Pesquisa por Código
                        
                IdPais = dadosCab[5];
                
                var elemPagina = document.getElementById('Pagina');
                var elemPaginaBottom = document.getElementById('PaginaBottom');
                TotalDePaginas = dadosCab[1];
                PaginaAtual = pagina;
                
                document.getElementById('PaginaAtual').innerHTML = pagina;
                document.getElementById('PaginaFinal').innerHTML = dadosCab[1];
                document.getElementById('PaginaAtualBottom').innerHTML = pagina;
                document.getElementById('PaginaFinalBottom').innerHTML = dadosCab[1];
                document.getElementById('cachekey').value = dadosCab[4];

                if(pagina == dadosCab[1] || pagina > dadosCab[1])
                {
                    elemPagina.value = '1';
                    elemPaginaBottom.value = '1';
                }
                else
                {
                    elemPagina.value = pagina + 1;
                    elemPaginaBottom.value = pagina + 1;
                }

                LimpaTabela();

                if(dadosCab[0] > 4140)
                {
                    if (document.getElementById('ctl00_cenas').checked)
                    {
                        document.getElementById('NumeroTotalFotos').innerHTML = dadosCab[0];
                        document.getElementById('NumeroTotalFotosBottom').innerHTML = dadosCab[0];
                    }
                    else
                    {
                        document.getElementById('NumeroTotalFotos').innerHTML = '4140+' ;
                        document.getElementById('NumeroTotalFotosBottom').innerHTML = '4140+';
                    }
                }
                else
                {
                    if(dadosCab[0] == 4140)
                    {
                        document.getElementById('NumeroTotalFotos').innerHTML = '4140+' ;
                        document.getElementById('NumeroTotalFotosBottom').innerHTML = '4140+';
                    }
                    else
                    {
                        document.getElementById('NumeroTotalFotos').innerHTML = dadosCab[0];
                        document.getElementById('NumeroTotalFotosBottom').innerHTML = dadosCab[0];
                    }
                }
                
                if(dadosCab[8] == 1)
                {
                    document.getElementById('NumeroTotalFotos').innerHTML = '*' + document.getElementById('NumeroTotalFotos').innerHTML;
                    document.getElementById('NumeroTotalFotosBottom').innerHTML = '*' + document.getElementById('NumeroTotalFotosBottom').innerHTML;
                }
                      
                document.getElementById('PainelResultados').style.display = 'block';
                var teste = dadosCab[7];

                // INICIO - CLARIFICADOR
                // Existe palavras clarificadas, código que monta o clarificador

                if(clarificar == '' && dadosCab[6] == '1')
                {
                    var color = '';
                    var icone = '';
                    if (MenuId == EnumMenu.Home)
                    {
                        color = '#0EA1BB';
                        icone = 'seta.gif';
                    }
                    if (MenuId == EnumMenu.Publicidade)
                    {
                        color = '#F98800';
                        icone = 'seta_publi.gif';
                    }
                    if (MenuId == EnumMenu.Editorial)
                    {
                        color = '#F53B00'
                        icone = 'seta_ed.gif';
                    }
                    if (MenuId == EnumMenu.Cenas)
                    {
                        color = '#099A21';
                        icone = 'seta_cena.gif';
                    }
                    if (MenuId == EnumMenu.Cd)
                    {
                        color = '#DD0085';
                        icone = 'seta_cd.gif';
                    }
                    if (MenuId == EnumMenu.Dam)
                    {
                        color = '#DB33FF';
                        icone = 'seta_dam.gif';
                    }

                    var palavra = document.getElementById('ctl00_pesquisa_campo').value;
                  
                    var htmlClarificador = 
                    '<table width="934" border="0" class="search_bottom_pag" cellpadding="0" cellspacing="0" style="border-top:1px solid #c6c6c6;">'+
                        '<tr>'+
                            '<td width="560px" height="20">'+
                                '<table width="100%" border="0" cellspacing="0" cellpadding="0">'+
                                    '<tr>'+
                                        '<td height="20"><strong>CLASSIFICAÇÕES</strong></td>'+
                                        '<td height="20" width="20" align="center"><img src="../../templates/img/pt-br/'+ icone +'" alt="" /></td>';

                    dadosCab[7] = dadosCab[7].substring(1);
                    dadosCab[7] = dadosCab[7].substring(0, dadosCab[7].length - 1);
                    var i, j;

                    if(dadosCab[7].indexOf("~") > -1)
                        palavrasPartes = dadosCab[7].split("~"); // Palavras Originais
                    else
                        palavrasPartes = new Array(dadosCab[7]);

                    var PalavrasSeparadas;
                    var partesPalavras;
                    var contID = 0;

                    if (palavrasPartes.length > 1)
                    {
                        partesPalavras = palavrasPartes[0].split("|");
                        htmlClarificador += '<td height="20" width="60" class="antibutton"><span style="color:'+ color +';">'+ partesPalavras[0] +'</span></td>';
                        
                        palavrasSeparadas = partesPalavras[1].split("´");
                        for(j = 0; j < palavrasSeparadas.length; j++)
                        { 
                            if(palavrasSeparadas[j] != '')
                            {
                                var auxPalavra = palavrasSeparadas[j];
                                auxPalavra = auxPalavra.substring(0,1).toUpperCase() + auxPalavra.substring(1, palavrasSeparadas[j].length);
                                nomesRadio[contID] = 'clarificadorID' + contID;
                                htmlClarificador +=
                                    '<td height="20" width="10" align="right"><input type="radio" name="clarificador'+ i +'" id="clarificadorID'+ contID +'" value="'+ palavrasSeparadas[j] +'"/></td>'+
                                    '<td height="20">'+ auxPalavra +'</td>';
                                contID++;
                            }
                        }
                        if (palavrasSeparadas.length < 3 || (palavrasSeparadas[2] == '' && palavrasSeparadas[2] != null) )
                            htmlClarificador += '<td height="20" width="10">&nbsp;</td><td height="20" width="180">&nbsp;</td>';
                                    
                        htmlClarificador += '</tr>';
                        
                        for(i = 1; i < palavrasPartes.length; i++)
                        {
                            htmlClarificador += 
                            '<tr>'+
                                '<td height="20">&nbsp;</td>'+
                                '<td height="20" width="20" align="center"><img src="../../templates/img/pt-br/'+ icone +'" alt="" /></td>';

                            partesPalavras = palavrasPartes[i].split("|");
                            htmlClarificador += '<td height="20" width="60" class="antibutton"><span style="color:'+ color +';">'+ partesPalavras[0] +'</span></td>';

                            palavrasSeparadas = partesPalavras[1].split("´");
                            for(j = 0; j < palavrasSeparadas.length; j++)
                            { 
                                if(palavrasSeparadas[j] != '')
                                {
                                    var auxPalavra = palavrasSeparadas[j];
                                    auxPalavra = auxPalavra.substring(0,1).toUpperCase() + auxPalavra.substring(1, palavrasSeparadas[j].length);
                                    nomesRadio[contID] = 'clarificadorID' + contID;
                                    htmlClarificador +=
                                        '<td height="20" width="10" align="right"><input type="radio" name="clarificador'+ i +'" id="clarificadorID'+ contID +'" value="'+ palavrasSeparadas[j] +'"/></td>'+
                                        '<td height="20">'+ auxPalavra +'</td>';
                                    contID++;
                                }
                            }
                            if (palavrasSeparadas.length < 3 || (palavrasSeparadas[2] == '' && palavrasSeparadas[2] != null) )
                                htmlClarificador += '<td height="20" width="10">&nbsp;</td><td height="20" width="180">&nbsp;</td>';

                            htmlClarificador += '</tr>';
                        }
                        htmlClarificador +=
                                    '</table>'+
                                '</td>'+
                                '<td width="34px" height="20">&nbsp;</td>'+
                                '<td height="20" class="antibutton">'+
                                    '<img src="../../templates/img/pt-br/'+ icone +'" alt="" />&nbsp;&nbsp;'+
                                    '<a href="javascript:" id="Buscar" style="color:'+ color +';" onclick="document.getElementById(\'Clarificador\').display=\'none\'; pagina=1; buscarClarificador=true; RequisitarBusca();">BUSCAR NOVAMENTE</a>'+
                                '</td>'+
                            '</tr>'+
                        '</table>';
                    }
                    else
                    {
                        for(i = 0; i < palavrasPartes.length; i++)
                        {
                            partesPalavras = palavrasPartes[i].split("|");
                            htmlClarificador += '<td height="20" width="60" class="antibutton"><span style="color:'+ color +';"">'+ partesPalavras[0] +'</span></td>';
                            
                            palavrasSeparadas = partesPalavras[1].split("´");
                            for(j = 0; j < palavrasSeparadas.length; j++)
                            { 
                                if(palavrasSeparadas[j] != '')
                                {
                                    var auxPalavra = palavrasSeparadas[j];
                                    auxPalavra = auxPalavra.substring(0,1).toUpperCase() + auxPalavra.substring(1, palavrasSeparadas[j].length);
                                    nomesRadio[contID] = 'clarificadorID' + contID;
                                    htmlClarificador +=
                                        '<td width="25" height="20" align="right"><input type="radio" name="clarificador'+ i +'" id="clarificadorID'+ contID +'" value="'+ palavrasSeparadas[j] +'" onclick="document.getElementById(\'Clarificador\').display=\'none\'; pagina=1; buscarClarificador=true; RequisitarBusca();" /></td>'+
                                        '<td height="20">'+ auxPalavra +'</td>';
                                    contID++;
                                }
                            }
                            if (palavrasSeparadas.length < 3 || (palavrasSeparadas[2] == '' && palavrasSeparadas[2] != null) )
                                htmlClarificador += '<td height="20" width="20">&nbsp;</td><td height="20" width="180">&nbsp;</td>';
                        }

                        htmlClarificador +=
                                        '</tr>'+
                                    '</table>'+
                                '</td>'+
                                '<td width="34px" height="20">&nbsp;</td>'+
                                '<td height="20">&nbsp;</td>'+
                            '</tr>'+
                        '</table>';
                    }

                    document.getElementById('Clarificador').innerHTML = htmlClarificador;
                    document.getElementById('Clarificador').style.display = 'block';
                }
                else
                    document.getElementById('Clarificador').style.display = 'none';
                    
                // FIM - CLARIFICADOR

                if (dadosCab[9] != null)
                {
                    var ParametrosCDMostraCapa = dadosCab[9];
                    if (ParametrosCDMostraCapa != '')
                    {
                        ParametrosCDMostraCapa = MostraCapaCD(ParametrosCDMostraCapa);
                        
                        document.getElementById('PainelCapaCD').innerHTML = ParametrosCDMostraCapa;
                        document.getElementById('PainelCapaCD').style.display = 'block';
                    }
                    else
                        document.getElementById('PainelCapaCD').style.display = 'none';
                }
                else
                    document.getElementById('PainelCapaCD').style.display = 'none';

                // Dados da Busca
                var dadosBusca = dados[1].substring(0, dados[1].length - 1);

                imagens = dadosBusca.split('~');
                var cont = imagens.length;
                var dadosImagens;

                fim = imagens.length - 1;
                FOTOSPORLINHA = 4;

                intTotalLinhas = parseInt(Math.ceil((fim  + 1) / FOTOSPORLINHA));
                primLinhas = true;

                intColuna = 0;
                intLinha = 0;
                intRegistro = 0;

                MontaResultados(dadosCab[10]);
                      
                document.getElementById('PainelResultadosBottom').style.display = 'block';
                      
                if(pagina == 1)
                {
                    document.getElementById('LinkAnterior').style.visibility = 'hidden';
                    if(dadosCab[1] > 1)
                        document.getElementById('LinkProximo').style.visibility = 'visible';
                    else
                        document.getElementById('LinkProximo').style.visibility = 'hidden';

                    document.getElementById('LinkAnteriorBottom').style.visibility = 'hidden';

                    if(dadosCab[1] > 1)
                        document.getElementById('LinkProximoBottom').style.visibility = 'visible';
                    else
                        document.getElementById('LinkProximoBottom').style.visibility = 'hidden';
                }
                else if(pagina == dadosCab[1])
                {
                    document.getElementById('LinkAnterior').style.visibility = 'visible';
                    document.getElementById('LinkProximo').style.visibility = 'hidden';
                    document.getElementById('LinkAnteriorBottom').style.visibility = 'visible';
                    document.getElementById('LinkProximoBottom').style.visibility = 'hidden';
                }
                else
                {
                    document.getElementById('LinkAnterior').style.visibility = 'visible';
                    document.getElementById('LinkProximo').style.visibility = 'visible';
                    document.getElementById('LinkAnteriorBottom').style.visibility = 'visible';
                    document.getElementById('LinkProximoBottom').style.visibility = 'visible';
                }                
            }
            else
            {
                //if(response.indexOf('ERR:') > -1)
                //    alert(response);
                var errResponse  
                if(response.indexOf('ERR:') > -1)
                {
                    errResponse = '<li>' + response + '<br /></li>';
                }                    
                else
                {
                    errResponse = '';
                }
                    
                document.getElementById('PainelResultados').style.display = 'none';                      
                document.getElementById('PainelResultadosBottom').style.display = 'none';
                document.getElementById('Clarificador').style.display = 'none';
                document.getElementById('ConteudoDinamico').innerHTML = '' +
                '<div style="padding: 0px 43px">' +
                    '<table border="0" style="font-size: 12px">' +
                    '<tr>' +
                        '<td class="Estilo16"><br />Sua pesquisa não retornou nenhuma imagem.<br /><br /><br />' +
                            '<ul>' +
                                errResponse+    
                                '<li>Verifique se você digitou a(s) palavra(s) corretamente;<br /><br /><br /></li>' +
                                '<li>Contate-nos para obter assistência gratuita a pesquisas. A nossa equipe de pesquisa pode te ajudar a encontrar aquilo que procura. Nosso atendimento está à sua disposição de segunda à sexta das 9:00 às 19:00 pelos telefones 11 3097 3000 e 0800 122 666 ou pelo e-mail <a href="mailto:atendimento@latinstock.com.br">atendimento@latinstock.com.br</a><br /><br /><br /></li>' +
                                '<li>Se digitou muitas palavras ao mesmo tempo, tente pesquisar algumas por vez.<br />Assim você poderá excluir qual delas não existe em nosso vocabulário;<br /><br /><br /></li>' +
                                '<li>Faça a mesma coisa com frases. Ex: criança comendo cachorro-quente não retornou nada. Tente primeiro cachorro-quente. Se vierem muitas imagens, tente comendo cachorro-quente e assim por diante;<br /><br /><br /></li>' +
                                '<li>Combinações booleanas (E, OU, NÃO) podem não resultar imagens. Verifique se as combinou corretamente;<br /><br /><br /></li>' +
                                '<li>Caso tenha dúvidas, leia nossas <a href="http://www.latinstock.com.br/br/ajudanet/indexacaobr.aspx">dicas</a> ou ligue para 11 3097 3000 e converse com nossos atendentes. Nosso sistema permite recuperar as palavras pesquisadas que não retornam resultado para que nossa equipe possa revisar nosso conteúdo e refinar a indexação de nossas imagens. Nossa preocupação é fazer com que a sua pesquisa seja precisa obtendo os melhores resultados do seu trabalho.<br /><br /><br /></li>' +
                            '</ul>' +
                        '</td>' +
                    '</tr>' +
                    '</table>' +
                '</div>';
            }
            document.getElementById('PainelCarregando').style.display = 'none';
            ExibirDivMenu('ConteudoDinamico');
        }
    }
}

function RequisitarBuscaNoPag(pagScroll,BloqRequisitad,idDiv)
{

    idDiv = 1;
    //Se a barra de rolagem estiver em movimento, espera ela parar, e chama a função no ponto em que parou.
    if(!processando)
    {
        processando = true;
        
        PagRequisitada = pagScroll;
        BloqRequisitado = BloqRequisitad;
        
        var newsearch = Math.random() * 1000000;    
        var tmp = StringBusca + '&newsearch=' + newsearch +
        '&__pagina=' + pagScroll +
        '&posicaonapagina=' + idDiv;
        
        EnviarPedido(tmp, TratarDadosNoPag, parametros, 'GET', false, true);
    }
    else
    {
        if(PagRequisitada != pagScroll || BloqRequisitado != BloqRequisitad)
        {
            AbortAjax();
            processando = false;
        }
    }
}

function GeraThumbsBrancos(QtdLinhas)
{
    document.getElementById("tabelaResultado").style.display = 'block'; 
    
    var table = document.getElementById("tabelaResultado");
    var rowCount = table.rows.length;

    for(j=rowCount; j < rowCount + QtdLinhas; j++)
    {
        var row = table.insertRow(j);        
        ContPag+= 4;

        var cell = row.insertCell(0);          
        cell.innerHTML = "<TABLE width=178 height=\"308\" border=0> <tr><td></td></tr></TABLE>";  
        
        var cell1 = row.insertCell(1);   
        cell1.innerHTML = "<TABLE width=178 height=\"308\" border=0> <tr><td></td></tr></TABLE>";  
        
        var cell2 = row.insertCell(2);   
        cell2.innerHTML = "<TABLE width=178 height=\"308\" border=0> <tr><td></td></tr></TABLE>";  
            
        var cell3 = row.insertCell(3);   
        cell3.innerHTML = "<TABLE width=178 height=\"308\" border=0> <tr><td></td></tr></TABLE>";  
    }
}

function TratarDadosNoPag()
{    
    if(ajax.readyState == 4)
      {
          if(ajax.status == 200)
            {
                  var response = ajax.responseText;
                  if(response.indexOf('^') > -1)
                  {
                      var dados = response.split('^');
                      var cab = dados[0];
                      var dadosCab = dados[0].split('¨');
                      var IdPaiss = dadosCab[5];
                      var dadosBusca = dados[1].substring(0, dados[1].length - 1);
                      var imagenss = dadosBusca.split('~');
                      var cont = imagenss.length;


                document.getElementById("tabelaResultado").style.display = 'block'; 
                var table = document.getElementById("tabelaResultado");
                var indiceCell = 0;                
                var SubPagina =  (BloqRequisitado -1) *20;
                if(SubPagina < 0)
                    SubPagina = 0;

                var BlocoGeral = (PagRequisitada * 3) -3 + BloqRequisitado;
                var indiceRow = ((((BlocoGeral -1) * 20))/4);                
                var arrayLength = imagenss.length;
                //BlocosCarregados[BlocoGeral]=1;    
                var strResultado = '';
                
                try
                {                
                    for(i=SubPagina; i< SubPagina+20; i++ )
                    {
                        if(i>=arrayLength)
                        {
                            //Se já chegou na ultima imagem. Apago os Thumbs Brancos restantes        
                            var lastRow = table.rows.length; 
            
                            while (lastRow >= indiceRow +1) 
                            { 
                                table.deleteRow(lastRow - 1);  
                                lastRow = table.rows.length; 
                            }                    
                            break;                    
                        }

                        strResultado = '<td width="215" align="left">';
                        var dadosImagens = imagenss[i].split('¨');

                        if (document.getElementById('ctl00_cenas').checked) //se for video
                            strResultado += MontaTabelaVideo(dadosImagens, IdPaiss);
                        else if(document.getElementById('ctl00_somente_cd').checked && somenteFotos == 0)  //se for cd
                            strResultado += MontaTabelaCD(dadosImagens, IdPaiss);
                        else //se for imagens normais
                            strResultado += MontaTabela(dadosImagens, IdPaiss);
                        strResultado += '</td>';
                        
                        var row = table.rows[indiceRow];
                        var cell = row.cells[indiceCell];
                        cell.innerHTML = strResultado;
                        
                        if(indiceCell > 2)
                        {
                            indiceRow++;
                            indiceCell = 0;
                        }
                        else
                        {
                            indiceCell++;
                        }
                    }
                    BlocosCarregados[BlocoGeral]=1;
                }
                catch(e)
                {
                    BlocosCarregados[BlocoGeral] = null;                
                }

                verificaImagensSelecionadas();
                controlaVisibilidadeIcones();

                processando = false;
                pedido_busy = false;
            }
        }
    }
}

function StopTheClock()
{
    if(timerRunning)
        clearTimeout(timerID);
        
    timerRunning = false;
}

function StartTheTimer()
{
    if (secs==0)
    {
        RequisitaThumbsVisiveis();
        timerID = self.Interval("InitializeTimer()", delay);
    }
    else
    {
        self.status = secs;
        secs = secs - 1;
        timerRunning = true;
        timerID = self.Interval("StartTheTimer()", delay);
    }
}

function MontaResultadosPanther(pesqCodigo)
{
    document.getElementById('ctl00_DvTblResultado').scrollTop = 0;
    document.getElementById('ctl00_DvTblResultado').style.display = 'block';
    document.getElementById('PainelLegenda').style.display = 'block';
    
    document.getElementById("ConteudoDinamico").innerHTML = '';
    document.getElementById("ConteudoDinamico").display = 'none';    
    document.getElementById("tabelaResultado").style.display = 'block';
    
    var table = document.getElementById("tabelaResultado");
    var indiceCell = 0;
    
    var indiceRow = 0;
    var indiceCell = 0;
    
    var strResultado = '';
    
    for(i=0; i< imagens.length; i++ )
    {
        if(i >= imagens.length)
        {
            //Se já chegou na ultima imagem. Apago os Thumbs Brancos restantes        
            var lastRow = table.rows.length; 
            
            if (document.getElementById('ctl00_cenas').checked)
            {
                while (lastRow > indiceRow)
                { 
                    table.deleteRow(lastRow - 1);  
                    lastRow = table.rows.length; 
                }
                break;
            }
            else
            {
                while (lastRow > indiceRow + 1)
                { 
                    table.deleteRow(lastRow - 1);
                    lastRow = table.rows.length; 
                }
                break;
            }
        }
            
        strResultado = '<td width="215" align="left">';

        var dadosImagens = imagens[i].split('¨');
            
        strResultado += MontaTabelaPanther(dadosImagens,i + 1);
            
        strResultado += '</td>';        
        
        if(table.rows.length == 0)
        {
            var QtdLinhas = Math.ceil(imagens.length / 4);
            GeraThumbsBrancos(QtdLinhas);     
        }
        var row = table.rows[indiceRow];
        var cell = row.cells[indiceCell];
        cell.innerHTML = strResultado;
        
        if(indiceCell > 2)
        {
            indiceRow++;
            indiceCell = 0;
        }
        else
        {
            indiceCell++;
        }
    }      
    processando = false;    
}

function MontaResultados(pesqCodigo)
{
    document.getElementById('ctl00_DvTblResultado').scrollTop = 0;
    document.getElementById('ctl00_DvTblResultado').style.display = 'block';
    document.getElementById('PainelLegenda').style.display = 'block';
    
    document.getElementById("ConteudoDinamico").innerHTML = '';
    document.getElementById("ConteudoDinamico").display = 'none';    
    document.getElementById("tabelaResultado").style.display = 'block';
    
    var table = document.getElementById("tabelaResultado");
    var indiceCell = 0;
    
    var indiceRow = 0;
    var indiceCell = 0;
    
    var strResultado = '';
    
    for(i=0; i< imagens.length; i++ )
    {
        if(i >= imagens.length)
        {
            //Se já chegou na ultima imagem. Apago os Thumbs Brancos restantes        
            var lastRow = table.rows.length; 
            
            if (document.getElementById('ctl00_cenas').checked)
            {
                while (lastRow > indiceRow)
                { 
                    table.deleteRow(lastRow - 1);  
                    lastRow = table.rows.length; 
                }
                break;
            }
            else
            {
                while (lastRow > indiceRow + 1)
                { 
                    table.deleteRow(lastRow - 1);
                    lastRow = table.rows.length; 
                }
                break;
            }
        }
            
        strResultado = '<td width="215" align="left">';
        var dadosImagens = imagens[i].split('¨');

        var SomenteFotosCKD = document.getElementById('ctl00_somente_cd').checked;
        if(UltimaUrl.indexOf("cdResult.ashx") > 0)
            SomenteFotosCKD = true;

        if(document.getElementById('ctl00_somente_cd').checked && UltimaUrl.indexOf("SearchResult.ashx") > 0)
            cdClicado = 1;
        
        if (document.getElementById('ctl00_cenas').checked) //se for video
            strResultado += MontaTabelaVideo(dadosImagens, IdPais);
        else if( SomenteFotosCKD && somenteFotos == 0 && cdClicado == 0)  //se for cd
            strResultado += MontaTabelaCD(dadosImagens, IdPais);
        else // se forem imagens normais
            strResultado += MontaTabela(dadosImagens, IdPais, 0,pesqCodigo);
            
        strResultado += '</td>';
        var indicePaginacao = document.getElementById('ctl00_paginacao').selectedIndex;
        var NumeroFotos = document.getElementById('ctl00_paginacao').options[indicePaginacao].value;

        if(table.rows.length == 0)
        {
            var QtdLinhas = Math.ceil(imagens.length / 4);
            GeraThumbsBrancos(QtdLinhas);     
        }
        var row = table.rows[indiceRow];
        var cell = row.cells[indiceCell];
        cell.innerHTML = strResultado;

        if(indiceCell > 2)
        {
            indiceRow++;
            indiceCell = 0;
        }
        else
        {
            indiceCell++;
        }
    }

    cdClicado = 0;
    processando = false;

    BlocosCarregados[1]=1;
    BlocosCarregados[2]=1;
    BlocosCarregados[3]=1;
 
    // Mostra mesa de luz
    if(document.getElementById('log').value == '1')
    {   
        document.getElementById('iframeMesa').src = '../mesadeluznet/mesaimagem.aspx';
        document.getElementById('divMesaLuz').style.display = 'block';
        if (pagina == 1)
            min();
    }
    else
        document.getElementById('divMesaLuz').style.display = 'none';

    verificaImagensSelecionadas();
    controlaVisibilidadeIcones();
}

function ParseUrl(URL)
{
    // ------------------------------------------------------------------------------------------------------------------
    // FORMULARIO AVANCADO
    // ------------------------------------------------------------------------------------------------------------------

    var UrlDecoded = UrlDecode(URL);

    if(document.all) //ie
       document.getElementById('ctl00_pesquisa_campo').value = QueryStringInUrl(UrlDecode(URL),'pchave');
    else //mozila
       document.getElementById('ctl00_pesquisa_campo').value = QueryStringInUrl(URL,'pchave');
    document.getElementById('ctl00_cenas').checked = (UrlDecoded.indexOf('SearchVideoResult.ashx') >= 0); //checkbox

    document.getElementById('ctl00_somente_cd').checked = (UrlDecoded.indexOf('cdResult.ashx') >= 0); //checkbox   //&somente_cd=0
    if (document.getElementById('ctl00_somente_cd').checked == true)
    {
        document.getElementById('ctl00_cd_lingua_port').checked = (QueryStringInUrl(UrlDecoded, 'idIdioma') == 1); //radiobutton
        document.getElementById('ctl00_cd_lingua_eng').checked = (QueryStringInUrl(UrlDecoded, 'idIdioma') == 3); //radiobutton

        // DropDownList Publicidade SomenteCD
        var cboPublicidadeSomenteCD = document.getElementById('ctl00_publicidade_somentecd');
        var arrayPublicidadeSomenteCD = QueryStringInUrl(UrlDecoded, 'tg').split(',');

        for (var i = 0; i < cboPublicidadeSomenteCD.length; i++)
            cboPublicidadeSomenteCD.options[i].selected = false;

        if (arrayPublicidadeSomenteCD.length == 1 && arrayPublicidadeSomenteCD == '')
            cboPublicidadeSomenteCD.options[0].selected = true; //todas
        else
        {
            for (i = 0; i < arrayPublicidadeSomenteCD.length; i++)
            {
                for (var j = 0; j < cboPublicidadeSomenteCD.length; j++)
                {
                    if (arrayPublicidadeSomenteCD[i] == cboPublicidadeSomenteCD.options[j].value)
                        cboPublicidadeSomenteCD.options[j].selected = true;
                }
            }
        }

        // DropDownList Publicidade Categorias
        var Categoria = QueryStringInUrl(UrlDecoded, 'categoria');
        if (Categoria != undefined)
        {
            var cboPublicidadeCategorias = document.getElementById('ctl00_publicidade_categorias');
            for (i = 0; i < cboPublicidadeCategorias.length; i++)
                cboPublicidadeCategorias.options[i].selected = false;
            cboPublicidadeCategorias.options[Categoria].selected = true;
        }
        else
            cboPublicidadeCategorias.options[0].selected = true;

        // DropDownList Ordem Alfabética
        var Letra = QueryStringInUrl(UrlDecoded, 'letra');
        var cboLetra = document.getElementById('ctl00_publicidade_ordemAlfabetica');
        for (i = 0; i < cboLetra.length; i++)
        {
            if (Letra == cboLetra.options[i].value)
                cboLetra.options[i].selected = true;
        }
    }

    if (document.getElementById('ctl00_cenas').checked == false && document.getElementById('ctl00_somente_cd').checked == false)
    {
        document.getElementById('ctl00_paginacao').options[0].selected = (QueryStringInUrl(UrlDecoded, 'numerodefotos') == 36); //dropdownlist
        document.getElementById('ctl00_paginacao').options[1].selected = (QueryStringInUrl(UrlDecoded, 'numerodefotos') == 60); //dropdownlist
        document.getElementById('ctl00_paginacao').options[2].selected = (QueryStringInUrl(UrlDecoded, 'numerodefotos') == 90); //dropdownlist
        document.getElementById('ctl00_paginacao').options[3].selected = (QueryStringInUrl(UrlDecoded, 'numerodefotos') == 180); //dropdownlist

        // dropDownList Busca  
        var Busca = QueryStringInUrl(UrlDecoded, 'TipoConsulta')
        if (Busca == "")
            Busca = 0;
        document.getElementById('ctl00_busca_boolean').options[Busca].selected = true;

        // Listbox Plano
        if (QueryStringInUrl(UrlDecoded, 'plano') >= 0 && QueryStringInUrl(UrlDecoded, 'plano') <= 7)
        {
            var Plano = QueryStringInUrl(UrlDecoded, 'plano');
            var lboPlano = document.getElementById('ctl00_plano');

            for (i = 0; i < lboPlano.length; i++)
            {
                if (lboPlano.options[i] != null)
                    lboPlano.options[i].selected = false;
            }
            if (lboPlano.options[Plano] != null)
                lboPlano.options[Plano].selected = true;
        }

        // CheckBoxes Orientação
        document.getElementById('ctl00_orientacao_horizontal').checked = (QueryStringInUrl(UrlDecoded, 'orientacao').indexOf('H') >= 0); //checkbox
        document.getElementById('ctl00_orientacao_vertical').checked = (QueryStringInUrl(UrlDecoded, 'orientacao').indexOf('V') >= 0); //checkbox
        document.getElementById('ctl00_orientacao_panoramica').checked = (QueryStringInUrl(UrlDecoded, 'orientacao').indexOf('P') >= 0); //checkbox
        document.getElementById('ctl00_orientacao_quadrada').checked = (QueryStringInUrl(UrlDecoded, 'orientacao').indexOf('Q') >= 0); //checkbox

        // CheckBoxes Estilo             
        document.getElementById('ctl00_estilo_pb').checked = (QueryStringInUrl(UrlDecoded, 'pb') == 1);
        document.getElementById('ctl00_estilo_ilustracao').checked = (QueryStringInUrl(UrlDecoded, 'ilustracao') == 1);
      
        // DropDownList Pessoas 
        var Pessoas = QueryStringInUrl(UrlDecoded, 'pessoas');
        if (Pessoas == '')
            Pessoas = '0';
        if (Pessoas >= 0 && Pessoas <= 7)    
        {
            var ddlPessoas = document.getElementById('ctl00_pessoas');
            ddlPessoas.options[Pessoas].selected = true;
        }

        // Checkbox SearchAll
        document.getElementById('ctl00_search_all').checked = (QueryStringInUrl(UrlDecoded, 'publicidade') == 'true' && QueryStringInUrl(UrlDecoded, 'editorial') == 'true');
        
        // Sessão Publicidade
        if (QueryStringInUrl(UrlDecoded, 'publicidade') == 'true')
            document.getElementById('ctl00_publicidade').checked = true;
                
        document.getElementById('ctl00_publicidade_lingua_port').checked = (QueryStringInUrl(UrlDecoded, 'idIdioma') == 1); //radiobutton  
        document.getElementById('ctl00_publicidade_lingua_eng').checked = (QueryStringInUrl(UrlDecoded, 'idIdioma') == 3); //radiobutton
        
        document.getElementById('ctl00_publicidade_DC').checked = (QueryStringInUrl(UrlDecoded, 'produtodc') == 'dc'); //checkbox
        document.getElementById('ctl00_publicidade_port_RF').checked = (QueryStringInUrl(UrlDecoded, 'ck_download') == 1); //checkbox

        document.getElementById('ctl00_publicidade_RF').checked = (QueryStringInUrl(UrlDecoded, 'produtorf') == 'rf'); //checkbox
        document.getElementById('ctl00_publicidade_layout').checked = (QueryStringInUrl(UrlDecoded, 'pchave').indexOf('!!') >= 0);          
        
        // ListBox Coleções DC 
        var cboColecoes_dc = document.getElementById('ctl00_publicidade_colecoes_dc');
        var arrayColecoes_dc = QueryStringInUrl(UrlDecoded, 'id_colecao_dc').split(',');

        for (i = 0; i < cboColecoes_dc.length; i++)
            cboColecoes_dc.options[i].selected = false;
        if (arrayColecoes_dc.length == 1 && arrayColecoes_dc == '')
            cboColecoes_dc.options[0].selected = true; //todas
        else
        {
            for (i = 0; i < arrayColecoes_dc.length; i++)
            {
                for (j = 1; j < cboColecoes_dc.length; j++)
                {
                    if (arrayColecoes_dc[i] == cboColecoes_dc.options[j].value)
                        cboColecoes_dc.options[j].selected = true;
                }
            }
        }
        
        // ListBox Coleções RF    
        var cboPublicidadeColecoesRF = document.getElementById('ctl00_publicidade_colecoesRF');
        var arrayColecoesRF = QueryStringInUrl(UrlDecoded, 'id_colecao_rf').split(',');  
        
        for (i = 0; i < cboPublicidadeColecoesRF.length; i++)
            cboPublicidadeColecoesRF.options[i].selected = false;

        if (arrayColecoesRF.length == 1 && arrayColecoesRF == '')
            cboPublicidadeColecoesRF.options[0].selected = true; //todas
        else
        {
            for (i = 0; i < arrayColecoesRF.length; i++)
            {
                for (j = 0; j < cboPublicidadeColecoesRF.length; j++)
                {
                    if (arrayColecoesRF[i] == cboPublicidadeColecoesRF.options[j].value)
                        cboPublicidadeColecoesRF.options[j].selected = true;
                }
            }
        }
        
        // Sessão Editorial
        document.getElementById('ctl00_editorial').checked = (QueryStringInUrl(UrlDecoded, 'editorial') == 'true');

        /// ListBox Coleções DC RF
        var cboEditorialList = document.getElementById('ctl00_editorial_list') //listbox
        var arrayEditorial = QueryStringInUrl(UrlDecoded, 'id_colecao_dcrf').split(',');
        
        for (i = 0; i < cboEditorialList.length; i++)
            cboEditorialList.options[i].selected = false;

        if (arrayEditorial.length == 1 && arrayEditorial == '')
            cboEditorialList.options[0].selected = true;
        else
        {
            for (i = 0; i < arrayEditorial.length; i++)
            {
                for (j = 0; j < cboEditorialList.length; j++)
                {
                    if (arrayEditorial[i] == cboEditorialList.options[j].value)
                        cboEditorialList.options[j].selected = true;
                }
            }
        }

        // Date DropDownList
        var Date = QueryStringInUrl(UrlDecoded, 'rangedata');
        var cboDate = document.getElementById('ctl00_editorial_date');
        cboDate.disable = false;
        for (i = 0; i < cboDate.length; i++)
        {
            if (Date == cboDate.options[i].value)
                cboDate.options[i].selected = true;
        }
        
        // txtDataEspecifica
        if (Date == "1000")
        {
            document.getElementById('ctl00_data_especifica').visible = true;
            document.getElementById('ctl00_data_especifica').value = QueryStringInUrl(UrlDecoded, 'datapesquisa');
        }

        // categoria 
        var Categoria = QueryStringInUrl(UrlDecoded, 'categoria');
        
        if (Categoria != undefined)
        {
            document.getElementById('ctl00_editorial_tipo_animais').checked = (Categoria.indexOf('1') >= 0); //checkbox  
            document.getElementById('ctl00_editorial_tipo_arte').checked = (Categoria.indexOf('2') >= 0); //checkbox    
            document.getElementById('ctl00_editorial_tipo_ciencia').checked = (Categoria.indexOf('3') >= 0); //checkbox
            document.getElementById('ctl00_editorial_tipo_entretenimento').checked = (Categoria.indexOf('4') >= 0); //checkbox
            document.getElementById('ctl00_editorial_tipo_esporte').checked = (Categoria.indexOf('5') >= 0); //checkbox
            document.getElementById('ctl00_editorial_tipo_gastronomia').checked = (Categoria.indexOf('6') >= 0); //checkbox
            document.getElementById('ctl00_editorial_tipo_historia').checked = (Categoria.indexOf('7') >= 0); //checkbox
            document.getElementById('ctl00_editorial_tipo_noticias').checked = (Categoria.indexOf('8') >= 0); //checkbox
            document.getElementById('ctl00_editorial_tipo_viagens').checked = (Categoria.indexOf('9') >= 0); //checkbox
            document.getElementById('ctl00_editorial_tipo_criativo').checked = (QueryStringInUrl(UrlDecoded, 'criativo') == '1'); //checkbox
        }
    }

    // ------------------------------------------------------------------------------------------------------------------
    // FORMULARIO AJAX
    // ------------------------------------------------------------------------------------------------------------------

    if (QueryStringInUrl(UrlDecoded, 'publicidade') == 'true')
        document.getElementById('ctl00_publicidade_search_ajax').checked = true;

    document.getElementById('ctl00_publicidade_port_ajax').checked = (QueryStringInUrl(UrlDecoded, 'idIdioma') == 1); //radiobutton  
    document.getElementById('ctl00_publicidade_eng_ajax').checked = (QueryStringInUrl(UrlDecoded, 'idIdioma') == 3); //radiobutton

    document.getElementById('ctl00_publicidade_port_DC_ajax').checked = (QueryStringInUrl(UrlDecoded, 'produtodc') == 'dc'); //checkbox
    document.getElementById('ctl00_publicidade_port_RF_ajax').checked = (QueryStringInUrl(UrlDecoded, 'produtorf') == 'rf'); //checkbox

    document.getElementById('ctl00_editorial_ajax').checked = (QueryStringInUrl(UrlDecoded, 'editorial') == 'true'); //checkbox

    if (Categoria != undefined)
    {
        document.getElementById('ctl00_editorial_tipo_animais2').checked = (Categoria.indexOf('1') >= 0); //checkbox  
        document.getElementById('ctl00_editorial_tipo_arte2').checked = (Categoria.indexOf('2') >= 0); //checkbox    
        document.getElementById('ctl00_editorial_tipo_ciencia2').checked = (Categoria.indexOf('3') >= 0); //checkbox
        document.getElementById('ctl00_editorial_tipo_entretenimento2').checked = (Categoria.indexOf('4') >= 0); //checkbox
        document.getElementById('ctl00_editorial_tipo_esporte2').checked = (Categoria.indexOf('5') >= 0); //checkbox
        document.getElementById('ctl00_editorial_tipo_gastronomia2').checked = (Categoria.indexOf('6') >= 0); //checkbox
        document.getElementById('ctl00_editorial_tipo_historia2').checked = (Categoria.indexOf('7') >= 0); //checkbox
        document.getElementById('ctl00_editorial_tipo_noticias2').checked = (Categoria.indexOf('8') >= 0); //checkbox
        document.getElementById('ctl00_editorial_tipo_viagens2').checked = (Categoria.indexOf('9') >= 0); //checkbox
        document.getElementById('ctl00_editorial_tipo_criativo2').checked = (QueryStringInUrl(UrlDecoded, 'criativo') == '1'); //checkbox
    }

    var Date = QueryStringInUrl(UrlDecoded, 'rangedata');
    var cboDate = document.getElementById('ctl00_editorial_date_ajax');
    cboDate.disable = false;
    for (i = 0; i < cboDate.length; i++)
    {
        if (Date == cboDate.options[i].value)
            cboDate.options[i].selected = true;
    }

    if (Date == "1000")
    {
        document.getElementById('ctl00_data_especifica_ajax').visible = true;
        document.getElementById('ctl00_data_especifica_ajax').value = QueryStringInUrl(UrlDecoded, 'datapesquisa');
    }

    document.getElementById('ctl00_search_all_ajax').checked = (QueryStringInUrl(UrlDecoded, 'publicidade') == 'true' && QueryStringInUrl(UrlDecoded, 'editorial') == 'true'); //checkbox
    document.getElementById('ctl00_cenas_ajax').checked = (UrlDecoded.indexOf('SearchVideoResult.ashx') >= 0); //checkbox

    // ------------------------------------------------------------------------------------------------------------------
    // HABILITA OS COMPONENTES (DISABLE = FALSE)
    // ------------------------------------------------------------------------------------------------------------------
    
    document.getElementById('ctl00_paginacao').disabled = false;
    document.getElementById('ctl00_busca_boolean').disabled = false;
    document.getElementById('ctl00_plano').disabled = false;
    document.getElementById('ctl00_orientacao_horizontal').disabled = false;
    document.getElementById('ctl00_orientacao_vertical').disabled = false;
    document.getElementById('ctl00_orientacao_panoramica').disabled = false;
    document.getElementById('ctl00_orientacao_quadrada').disabled = false;
    document.getElementById('ctl00_estilo_pb').disabled = false;
    document.getElementById('ctl00_estilo_ilustracao').disabled = false;
    document.getElementById('ctl00_pessoas').disabled = false;
    document.getElementById('ctl00_search_all').disabled = false;

    document.getElementById('ctl00_publicidade').disabled = false;
    document.getElementById('ctl00_publicidade_lingua_port').disabled = false;
    document.getElementById('ctl00_publicidade_lingua_eng').disabled = false;
    document.getElementById('ctl00_publicidade_DC').disabled = false;
    document.getElementById('ctl00_publicidade_port_RF').disabled = false;
    document.getElementById('ctl00_publicidade_RF').disabled = false;
    document.getElementById('ctl00_publicidade_layout').disabled = false;
    document.getElementById('ctl00_editorial').disabled = false;
    document.getElementById('ctl00_editorial_date').disabled = false;
    document.getElementById('ctl00_data_especifica').disabled = false;

    document.getElementById('ctl00_editorial_tipo_animais').disabled = false;
    document.getElementById('ctl00_editorial_tipo_arte').disabled = false;
    document.getElementById('ctl00_editorial_tipo_ciencia').disabled = false;
    document.getElementById('ctl00_editorial_tipo_criativo').disabled = false;
    document.getElementById('ctl00_editorial_tipo_entretenimento').disabled = false;
    document.getElementById('ctl00_editorial_tipo_esporte').disabled = false;
    document.getElementById('ctl00_editorial_tipo_gastronomia').disabled = false;
    document.getElementById('ctl00_editorial_tipo_historia').disabled = false;
    document.getElementById('ctl00_editorial_tipo_noticias').disabled = false;
    document.getElementById('ctl00_editorial_tipo_viagens').disabled = false;

    document.getElementById('ctl00_cenas').disabled = false;
    document.getElementById('ctl00_somente_cd').disabled = false;
    document.getElementById('ctl00_cd_lingua_port').disabled = false;
    document.getElementById('ctl00_cd_lingua_eng').disabled = false;
    document.getElementById('ctl00_publicidade_colecoes_dc').disabled = false;
    document.getElementById('ctl00_publicidade_colecoesRF').disabled = false;
    document.getElementById('ctl00_editorial_list').disabled = false;
    document.getElementById('ctl00_publicidade_somentecd').disabled = false;
    document.getElementById('ctl00_publicidade_categorias').disabled = false;
    document.getElementById('ctl00_publicidade_ordemAlfabetica').disabled = false;
}
