var idComboCidadeVizinha;

$(document).ready(function() {
    var checkBoxesComparacao    = $('input:checkbox[id*="chkComparacao_"]');
    var divsComparacao          = $('div[id*="imgComparar_"]');
    var ancorasComparacao       = $('a[id*="ancoraComparar"][title*="Comparar"]');

    checkBoxesComparacao.click(Comparacao_AoClicar);
    divsComparacao.click(Comparacao_AoClicar);
    ancorasComparacao.click(ExecutarComparacao_AoClicar);

    divsComparacao.mouseover(function() {
        $(this).css('cursor', 'pointer');
    });

    if (checkBoxesComparacao.length > 0) GerarLinkComparacao();
});

function AtivarCidadeText(txtCidade, cboEstado) 
{
    var comboEstado = document.getElementById(cboEstado);

    if (comboEstado.value != null && comboEstado.value != '')
        document.getElementById(txtCidade).disabled = false;
    else
        document.getElementById(txtCidade).disabled = true;
}

function VerificarCheckCidadeVizinha(chk,cbo,cboEstado,txtCidade,chkUsados) 
{	
	idComboCidadeVizinha = cbo;
	
	var chkbox = document.getElementById(chk); 
	var cboBox = document.getElementById(cbo);
	var comboEstado = document.getElementById(cboEstado);
	var textoCidade = document.getElementById(txtCidade);
	
	if(chkbox != null && cboBox != null)
	{	
		if (comboEstado.value != null &&
			comboEstado.value != '' &&
			textoCidade.value != null &&
			textoCidade.value.trim() != '')
		{
			if(chkbox.checked) 
			{
				cboBox.disabled  = false;
				WebMotors.ssComum.ssServicos.InformacaoCidades.FindCidadeVizinhas(comboEstado.value, textoCidade.value, FindCidadeVizinhas_OnComplete, FindCidadeVizinhas_OnError, FindCidadeVizinhas_OnTimeOut);
			}
			else
			{   
				limpaCombo(idComboCidadeVizinha);
				cboBox.disabled  = true;
			}
		}
		else
		{
			limpaCombo(idComboCidadeVizinha);
			chkbox.checked = false;
			document.getElementById(cbo).selectedIndex = 0;
			cboBox.disabled  = true;
		}
	}
}

function AtualizarUF(controleAutoComplete, valor) {
    var controle = $find(controleAutoComplete);

    if (controle != null && controle != undefined) {
        controle.set_contextKey(valor);
    }
}	

function FindCidadeVizinhas_OnComplete(list)
{
	if (list)
	{
	    limpaCombo(idComboCidadeVizinha);
		var e = document.getElementById(idComboCidadeVizinha);
        var selectedValueOption = null;
		for (i = 1; i <= list.length; i++)
		{
		    var item = list[i-1];
            var listItemName = item.name;
            var listItemValue = item.value;
            var listItemIsDefaultValue = item.isDefaultValue;
            var optionElement = new Option(listItemName, listItemValue);
            if (listItemIsDefaultValue) 
                selectedValueOption = optionElement;

            e.options[e.options.length] = optionElement;
        }
        
        if (selectedValueOption)
            selectedValueOption.selected = true;

        var comboboxLimitesVizinhas = $('select[id*="ddlBuscarCidade"]');
        var comboboxCidadesVizinhas = $('select[id*="cboDistancia"]');
        var queryString             = window.location.href.split('?')[1];

        if (queryString != null && queryString != undefined) {
            var arrayQueryString = queryString.split('&');

            for (var contador = 0; contador < arrayQueryString.length; contador++) {
                var chave = arrayQueryString[contador].split('=')[0];
                var valor = arrayQueryString[contador].split('=')[1];

                if (chave.toUpperCase() == 'DISTANCIACIDADESVIZINHAS') {
                    comboboxLimitesVizinhas.val(valor);
                }

                if (chave.toUpperCase() == 'DISTANCIA') {
                    comboboxCidadesVizinhas.val(valor);
                }
            }
        }             
	}
	else
		alert(msg);
}

function FindCidadeVizinhas_OnTimeOut(arg)
{
	alert("Ocorreu Timeout na busca de marcas no servidor.");
}

function FindCidadeVizinhas_OnError(arg)
{
	alert("Ocorreu erro na busca de marcas no servidor: " + arg._message);
}
function LimparCidade(txtBox)
{
	document.getElementById(txtBox).value = '';
}

function limpaCombo(combo)
{
	if (document.getElementById(combo) != null)
		document.getElementById(combo).options.length = 0;
}

// BUFI PE 20110106
function disableCheckBox(checkUsados, checkNovos, checkCarroRevendedor, checkParticular, cboQuilometro, cboQuilometroate, wcwmNecessidade)
{
    
    // Desabilita o checkbox Particular
    if (!document.getElementById(checkUsados).checked) 
    {
        document.getElementById(checkParticular).checked = false;
        document.getElementById(checkParticular).disabled = true;
        document.getElementById(cboQuilometro).disabled = true;
        document.getElementById(cboQuilometro).value = '';
        document.getElementById(cboQuilometroate).disabled = true;
        document.getElementById(cboQuilometroate).value = '';
    }
    else 
    {
        document.getElementById(checkParticular).disabled = false;
        document.getElementById(cboQuilometro).disabled = false;
        document.getElementById(cboQuilometroate).disabled = false;
    }
    // Desabilita o checkbox Novos
    if (!document.getElementById(checkCarroRevendedor).checked)
    {
        document.getElementById(checkNovos).checked = false;
        document.getElementById(checkNovos).disabled = true;
    }
//    else 
//    {
//        document.getElementById(checkNovos).disabled = false;
//        document.getElementById(checkNovos).checked = true;
//    }

    if (wcwmNecessidade) {
        disableNovosUsados(checkUsados, checkNovos, wcwmNecessidade); //BUFI JFL 20110118
    }
}
//TODO: BUFI-57 MRO 20110123
function disableCheckBoxNSOC(chkUsados, chkNovos, chkLojas, chkConcessionaria, chkParticular, lblParticular, lblNovos) 
{
    // Desabilita o checkbox Particular
    if (!document.getElementById(chkUsados).checked) 
    {
        document.getElementById(chkParticular).checked = false;
        document.getElementById(chkParticular).disabled = true;

        document.getElementById(lblParticular).style.color = "#666666";
    }
    else 
    {
        document.getElementById(chkParticular).disabled = false;
        document.getElementById(lblParticular).style.color = "#000000";
    }
    // Desabilita o checkbox Novos
    if (!document.getElementById(chkLojas).checked && !document.getElementById(chkConcessionaria).checked) 
    {
        document.getElementById(chkNovos).checked = false;
        document.getElementById(chkNovos).disabled = true;
        document.getElementById(chkUsados).checked = true;
        document.getElementById(chkUsados).disabled = false;
        document.getElementById(chkParticular).disabled = false;

        document.getElementById(lblParticular).style.color = "#000000";
        document.getElementById(lblNovos).style.color      = "#666666";
    }
    else 
    {
        document.getElementById(chkNovos).disabled = false;
        document.getElementById(lblNovos).style.color = "#000000";
    }
    if (!document.getElementById(chkLojas).checked && !document.getElementById(chkConcessionaria).checked && !document.getElementById(chkParticular).checked) 
    {
        document.getElementById(chkNovos).checked = true;
        document.getElementById(chkNovos).disabled = false;
        document.getElementById(chkUsados).checked = true;
        document.getElementById(chkUsados).disabled = false;
        document.getElementById(chkLojas).checked = true;
        document.getElementById(chkLojas).disabled = false;
        document.getElementById(chkConcessionaria).checked = true;
        document.getElementById(chkConcessionaria).disabled = false;
        document.getElementById(chkParticular).checked = true;
        document.getElementById(chkParticular).disabled = false;

        document.getElementById(lblParticular).style.color = "#000000";
        document.getElementById(lblNovos).style.color = "#000000";
    }
}

function disableCheckBoxNovos_PlacaApVeic(chkUsados, chkNovos, chkPlacaFinalPlaca12, chkPlacaFinalPlaca34, chkPlacaFinalPlaca56, chkPlacaFinalPlaca78, chkPlacaFinalPlaca90, chkUnicoDono, chkGarantiaFabrica, chkAlienado) 
{
    if (!document.getElementById(chkUsados).checked && document.getElementById(chkNovos).checked) {
        document.getElementById(chkPlacaFinalPlaca12).checked = false;
        document.getElementById(chkPlacaFinalPlaca12).disabled = true;
        document.getElementById(chkPlacaFinalPlaca34).checked = false;
        document.getElementById(chkPlacaFinalPlaca34).disabled = true;
        document.getElementById(chkPlacaFinalPlaca56).checked = false;
        document.getElementById(chkPlacaFinalPlaca56).disabled = true;
        document.getElementById(chkPlacaFinalPlaca78).checked = false;
        document.getElementById(chkPlacaFinalPlaca78).disabled = true;
        document.getElementById(chkPlacaFinalPlaca90).checked = false;
        document.getElementById(chkPlacaFinalPlaca90).disabled = true;
        document.getElementById(chkUnicoDono).checked = false;
        document.getElementById(chkUnicoDono).disabled = true;
        document.getElementById(chkGarantiaFabrica).checked = false;
        document.getElementById(chkGarantiaFabrica).disabled = true;
        document.getElementById(chkAlienado).checked = false;
        document.getElementById(chkAlienado).disabled = true;

        document.getElementById('spanUnicoDono').style.color       = '#666666';
        document.getElementById('spanGarantiaFabrica').style.color = '#666666';
        document.getElementById('spanAlienado').style.color        = '#666666';
    }
    else {
        document.getElementById(chkPlacaFinalPlaca12).disabled  = false;
        document.getElementById(chkPlacaFinalPlaca34).disabled  = false;
        document.getElementById(chkPlacaFinalPlaca56).disabled  = false;
        document.getElementById(chkPlacaFinalPlaca78).disabled  = false;
        document.getElementById(chkPlacaFinalPlaca90).disabled  = false;
        document.getElementById(chkUnicoDono).disabled          = false;
        document.getElementById(chkGarantiaFabrica).disabled    = false;
        document.getElementById(chkAlienado).disabled           = false;

        document.getElementById('spanUnicoDono').style.color       = '#000000';
        document.getElementById('spanGarantiaFabrica').style.color = '#000000';
        document.getElementById('spanAlienado').style.color        = '#000000';     
    }
}

//TODO: BUFI MRO 20110112
function carregarComboAnoDeAte(checkUsados, checkNovos, cboAno, cboAnoAte, anoInicial) 
{
    // Carrega os combos de Ano de e Ano Até se o Carro é apenas Novo
    document.getElementById(cboAno).options.length = 0;
    document.getElementById(cboAnoAte).options.length = 0;
    var data = new Date();
    if (document.getElementById(checkNovos).checked && !document.getElementById(checkUsados).checked) 
    {
        var newOption = new Option(data.getFullYear() + 1);
        document.getElementById(cboAno).options[1] = newOption;
        var newOption = new Option(data.getFullYear());
        document.getElementById(cboAno).options[2] = newOption;
        var newOption = new Option(data.getFullYear() - 1);
        document.getElementById(cboAno).options[3] = newOption;        
        var newOption = new Option(data.getFullYear() + 1);
        document.getElementById(cboAnoAte).options[1] = newOption;
        var newOption = new Option(data.getFullYear());
        document.getElementById(cboAnoAte).options[2] = newOption;
        var newOption = new Option(data.getFullYear() - 1);
        document.getElementById(cboAnoAte).options[3] = newOption;
    }
    else 
    {
        var Contador = 1;
        for (i = data.getFullYear() + 1; i >= anoInicial; i--) 
        {
            var newOption = new Option(i);
            var newOptionFinal = new Option(i);
            document.getElementById(cboAno).options[Contador] = newOption;
            document.getElementById(cboAnoAte).options[Contador] = newOptionFinal;
            Contador = Contador + 1;            
        }
    }
    var newOption = new Option("", "");
    document.getElementById(cboAno).options[0] = newOption;
    document.getElementById(cboAno).selectedIndex = 0;
    var newOptionFinal = new Option("", "");
    document.getElementById(cboAnoAte).options[0] = newOptionFinal;
    document.getElementById(cboAnoAte).selectedIndex = 0;

    var comboboxAnoDe   = $('select[id*="cboBuscaAno"]');
    var comboboxAnoAte  = $('select[id*="cboBuscaAnoAte"]');
    var queryString = window.location.href.split('?')[1];

    if (queryString != null && queryString != undefined) {
    	var arrayQueryString = queryString.split('&');
    	var valorAnoDe = '';
    	var valorAnoAte = '';

        for (var contador = 0; contador < arrayQueryString.length; contador++) {
            var chave = arrayQueryString[contador].split('=')[0];
            var valor = arrayQueryString[contador].split('=')[1];

            if (chave.toUpperCase() == 'ANOATE') {
            	valorAnoAte = valor;
            }

            if (chave.toUpperCase() == 'ANODE') {
            	valorAnoDe = valor;
            }

            if (chave.toUpperCase() == 'ANOINICIAL') {
            	valorAnoDe = valor;
            }

            if (chave.toUpperCase() == 'ANOFINAL') {
            	valorAnoAte = valor;
            }
        }

        comboboxAnoDe.val(valorAnoDe);
        comboboxAnoAte.val(valorAnoAte);
    }
}

function Comparacao_AoClicar(evento) {
    var checkboxClicado = (this.id.substring(0, 3) == 'chk');

    if (checkboxClicado) {
        var idCheckbox = '#' + this.id;
        $(idCheckbox)[0].checked = !$(idCheckbox)[0].checked;
    }
    else {
        var codigoAnuncio   = this.id.substring(12);
        var nomeCheckbox    = 'chkComparacao_' + codigoAnuncio;
        var nomeDiv         = this.id;
        
        if (codigoAnuncio.length > 0) {
            var objetoDiv       = jQuery('#' + nomeDiv);
            var objetoCheckbox  = jQuery('#' + nomeCheckbox);

            objetoCheckbox[0].checked = !objetoCheckbox[0].checked;

            if (objetoCheckbox[0].checked) {
                objetoDiv.removeClass('box-compare');
                objetoDiv.removeClass('box-compare-selected');
                objetoDiv.addClass('box-compare-selected');
            }
            else {
                objetoDiv.removeClass('box-compare');
                objetoDiv.removeClass('box-compare-selected');
                objetoDiv.addClass('box-compare');
            }

            GerarLinkComparacao();
        }
    }
}

function GerarLinkComparacao() {
    var anunciosSelecionados    = jQuery('input:checked[id*="chkComparacao_"]');
    var ancorasComparacao       = jQuery('a[id*="ancoraComparar"][title*="Comparar"]');
    var queryString             = '';

    if (anunciosSelecionados.length > 0) {
        jQuery.each(anunciosSelecionados, function(indice, anuncioCheckbox) {
            var separador       = (indice > 0) ? '&' : '?';
            var codigoAnuncio   = anuncioCheckbox.id.substring(14);
            var indiceAnuncio   = indice + 1;        
 
            queryString += separador + 'codigoAnuncio' + indiceAnuncio + '=' + codigoAnuncio;
        });
    }

    var queryStringAtual    = window.location.href.split('?')[1];
    var motos               = (window.location.href.split('?')[0].split('/')[5].substring(0, 4) == 'moto');
    var tipoVeiculo         = '';

    if (motos)
        tipoVeiculo = 'moto';
    else
        tipoVeiculo = 'carro';

    queryStringAtual = (queryStringAtual != null && queryStringAtual != undefined) ? queryStringAtual : '';
    
    queryString += ((queryString.length > 0) ? "&" : "?") + queryStringAtual;

    ancorasComparacao.attr('href', semHTTPS + sitePath + 'compra/' + tipoVeiculo + 'sResultadoComparacao/' + tipoVeiculo + 's-resultado-comparacao.aspx' + queryString);
}

function ExecutarComparacao_AoClicar(evento) {
    var anunciosSelecionados    = $('input:checked[id*="chkComparacao_"]');
    var queryString             = '';

    if (anunciosSelecionados.length < 2) {
        tb_showThickbox('Quantidade Insuficiente', '#TB_inline?width=256&amp;height=153&amp;inlineId=modalQuantidadeMinimaComparacoes', false, 'aspnetForm');
        return false;
    }
    else if (anunciosSelecionados.length > 5) {
        tb_showThickbox('Quantidade Excedida', '#TB_inline?width=207&amp;height=153&amp;inlineId=modalQuantidadeMaximaComparacoes', false, 'aspnetForm');
        return false;
    }
}

// BUFI JFL 20110115
function disableNovosUsados(checkUsados, checkNovos, wcwmNecessidade) 
{
    var chkNecessidade = wcwmNecessidade; // BUFI JFL 20110115
    var lblNecessidade = wcwmNecessidade; // BUFI JFL 20110115
    var idCarroDeColecionador = '2000009'; // BUFI JFL 20110115
    var bolCarroDeColecionador;

    bolCarroDeColecionador = !document.getElementById(checkUsados).checked && document.getElementById(checkNovos).checked; // BUFI JFL 20110115

    chkNecessidade += '__idChk_'; // BUFI JFL 20110115
    chkNecessidade += idCarroDeColecionador; // BUFI JFL 20110115
    lblNecessidade += '__idLbl_'; // BUFI JFL 20110115
    lblNecessidade += idCarroDeColecionador; // BUFI JFL 20110115

    document.getElementById(chkNecessidade).disabled = bolCarroDeColecionador; // BUFI JFL 20110115

    if (bolCarroDeColecionador && document.getElementById(chkNecessidade).checked) {
        WebmotorsSelecionarCheck('ctl00_ConteudoCompraMaster_Necesidade__idHdn_hdnValor', '2000009', 'checkboxUsados', 'ctl00_ConteudoCompraMaster_Necesidade__idChk_2000009');
    }
    
    if (bolCarroDeColecionador)
        document.getElementById('ctl00_ConteudoCompraMaster_Necesidade__idLbl_2000009').style.color = '#666666';                                  
    else
        document.getElementById('ctl00_ConteudoCompraMaster_Necesidade__idLbl_2000009').style.color = '#000000';                                  
}
function OrdenarResultados(ddl1, ddl2, URL, ordemAtual) {
    var valorOrdem = jQuery('#' + ddl1).val();
    if (valorOrdem != 'OP') {
        var qs = new Querystring();
        qs.set('Ordem', valorOrdem);
        qs.set('pagina', 1);
        try {
            document.location.href = document.location.protocol + '//' + document.location.hostname + document.location.pathname + decodeURI(qs.toString());
        } catch (e) {
            document.location.href = document.location.protocol + '//' + document.location.hostname + document.location.pathname + unescape(qs.toString());
        }
    } else
        jQuery('#' + ddl2).val(valorOrdem);
}
//TODO: BUFI-60 MRO 20110119
function ConfigurarBold(cboMarcaPref1, cboMarcaPref2, cboMarcaPref3, cboMarcaNPref1, cboMarcaNPref2, cboMarcaNPref3,
                        spanSemPreferencia, spanMarcas, spanMarcaPreferida, spanMarcaNDesejada, rbMarcaPreferida,
                        rbMarcaNPreferida, rbSemPreferencia, rbMarcas) 
{
    if ((document.getElementById(rbMarcaPreferida).checked || document.getElementById(rbMarcaNPreferida).checked) && !document.getElementById(rbMarcas).checked && document.getElementById(rbSemPreferencia).checked) 
    {
        if (document.getElementById(spanSemPreferencia).style.fontWeight == "bold")
        {
            document.getElementById(rbMarcas).checked = true;
        }
        if (document.getElementById(spanSemPreferencia).style.fontWeight != "bold") 
        {
            document.getElementById(rbMarcaPreferida).checked = false;
            document.getElementById(rbMarcaNPreferida).checked = false;
            document.getElementById(rbMarcas).checked = false;
        }
    }
    if (document.getElementById(rbMarcaPreferida).checked || document.getElementById(rbMarcaNPreferida).checked) 
    {
        document.getElementById(rbSemPreferencia).checked = false;
        document.getElementById(rbMarcas).checked = true;
    }
    if (document.getElementById(rbMarcaPreferida).checked && !document.getElementById(rbSemPreferencia).checked) 
    {
        document.getElementById(cboMarcaNPref1).disabled = true;
        document.getElementById(cboMarcaNPref1).selectedIndex = "0";
        document.getElementById(cboMarcaNPref2).disabled = true;
        document.getElementById(cboMarcaNPref2).selectedIndex = "0";
        document.getElementById(cboMarcaNPref3).disabled = true;
        document.getElementById(cboMarcaNPref3).selectedIndex = "0";
        document.getElementById(spanMarcaPreferida).style.fontWeight = "bold";
        document.getElementById(spanMarcaNDesejada).style.fontWeight = "normal";
        document.getElementById(spanMarcaNDesejada).style.color = "black";
        document.getElementById(spanMarcas).style.color = "black";
        document.getElementById(spanMarcas).style.fontWeight = "bold";
        document.getElementById(rbMarcas).checked = true;
        document.getElementById(rbSemPreferencia).checked = false;
    }
    else if (document.getElementById(rbMarcaNPreferida).checked && !document.getElementById(rbSemPreferencia).checked) 
    {
        document.getElementById(cboMarcaPref1).disabled = true;
        document.getElementById(cboMarcaPref1).selectedIndex = "0";
        document.getElementById(cboMarcaPref2).disabled = true;
        document.getElementById(cboMarcaPref2).selectedIndex = "0";
        document.getElementById(cboMarcaPref3).disabled = true;
        document.getElementById(cboMarcaPref3).selectedIndex = "0";
        document.getElementById(spanMarcaPreferida).style.fontWeight = "normal";
        document.getElementById(spanMarcaPreferida).style.color = "black";
        document.getElementById(spanMarcaNDesejada).style.fontWeight = "bold";
        document.getElementById(spanMarcas).style.color = "black";
        document.getElementById(spanMarcas).style.fontWeight = "bold";
        document.getElementById(rbMarcas).checked = true;
        document.getElementById(rbSemPreferencia).checked = false;
    }
    if (document.getElementById(rbSemPreferencia).checked && (document.getElementById(rbMarcaPreferida).checked || document.getElementById(rbMarcaNPreferida).checked)) 
    {
        document.getElementById(rbMarcaNPreferida).checked = false;
        document.getElementById(rbMarcaPreferida).checked = false;
        document.getElementById(rbMarcas).checked = false;
    }
    if (document.getElementById(rbSemPreferencia).checked && !document.getElementById(rbMarcaPreferida).checked && !document.getElementById(rbMarcaNPreferida).checked) 
    {
        document.getElementById(spanSemPreferencia).style.fontWeight = "bold";
        document.getElementById(spanMarcas).style.fontWeight = "normal";
        document.getElementById(spanMarcaPreferida).style.fontWeight = "normal";
        document.getElementById(spanMarcaNDesejada).style.fontWeight = "normal";
        document.getElementById(spanMarcaPreferida).style.color = "black";
        document.getElementById(spanMarcaNDesejada).style.color = "black";        
        document.getElementById(cboMarcaPref1).selectedIndex = "0";
        document.getElementById(cboMarcaPref2).selectedIndex = "0";
        document.getElementById(cboMarcaPref3).selectedIndex = "0";
        document.getElementById(cboMarcaPref1).disabled = true;
        document.getElementById(cboMarcaPref2).disabled = true;
        document.getElementById(cboMarcaPref3).disabled = true;
        document.getElementById(cboMarcaNPref1).selectedIndex = "0";
        document.getElementById(cboMarcaNPref2).selectedIndex = "0";
        document.getElementById(cboMarcaNPref3).selectedIndex = "0";
        document.getElementById(cboMarcaNPref1).disabled = true;
        document.getElementById(cboMarcaNPref2).disabled = true;
        document.getElementById(cboMarcaNPref3).disabled = true;
        document.getElementById(spanMarcas).style.color = "black";
        document.getElementById(spanMarcas).style.fontWeight = "normal";
    }
    else if (document.getElementById(rbMarcas).checked) 
    {
        document.getElementById(spanSemPreferencia).style.fontWeight = "normal";
        document.getElementById(spanMarcas).style.fontWeight = "bold";
    }
}

function openPopUpCentro(url, vwidth, vheight) {
    /* banner aymore */
    //alteração feita para corrigir o popup versões na busca
    if (!(vwidth == 333))
        vheight = 155;

    if (url.indexOf('Canal') == '-1') {
        //alteração feita para corrigir o popup versões na busca
        if (!(vwidth == 333))
            vwidth = 282;
        if (!(vheight == 380))
            vheight = 233;
    }
    //alteração feita para corrigir o popup versões na busca
    if (!(vheight == 380))
        vwidth = 282;

    //pega a resolução do visitante
    w = screen.width;
    h = screen.height;

    //divide a resolução por 2, obtendo o centro do monitor
    meio_w = w / 2;
    meio_h = h / 2;

    //diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
    altura2 = vheight / 2;
    largura2 = vwidth / 2;
    meio1 = meio_h - altura2;
    meio2 = meio_w - largura2;

    window.open(url, '', 'toolbar=0,menubar=0,width=' + vwidth + ',height=' + vheight + ',top=' + meio1 + ',left=' + meio2 + ',scroolbar=0');
}

jQuery.fn.exists = function(){return jQuery(this).length>0;}

IntervalBusca = {
	chkCidade : '', txtCidade : '', cboEstado : '', cboCidadesVizinhas : '',
	numInterval : 0,
	init : function(){
		this.chkCidade = jQuery("input[name$='chkCidadeVizinha']:checkbox");
		this.txtCidade = jQuery("input[name$='txtCidade']");
		this.cboEstado = jQuery("[name$='cboEstado']");
		this.cboCidadesVizinhas = (jQuery("[name$='cboCidadesVizinhas']").exists()) ? jQuery("[name$='cboCidadesVizinhas']") : jQuery("[name$='cboDistancia']");
		if (this.chkCidade.exists() && this.txtCidade.exists() && this.cboEstado.exists()) {
			this.AddEvento();
			this.AddInterval();
		}
	},
	Verifica : function(){
		if (this.txtCidade.val() != ''){
			this.MarcaCheck();
			this.Zera();
			this.Busca();
		}
	},
	AddInterval : function(){ this.numInterval = window.setInterval('IntervalBusca.Verifica()', 500); },
	AddEvento : function(){
		this.txtCidade.keypress(function(){ IntervalBusca.Zera(); });
		this.txtCidade.change(function(){ 
			IntervalBusca.MarcaCheck(); 
			if (IntervalBusca.txtCidade.val() != '') IntervalBusca.Zera(); else IntervalBusca.AddInterval();
			IntervalBusca.Busca(); 
		});
	},
	MarcaCheck : function() { this.chkCidade.attr('checked', 'checked'); },
	Busca : function(){ VerificarCheckCidadeVizinha(this.chkCidade.attr('id'), this.cboCidadesVizinhas.attr('id'), this.cboEstado.attr('id'), this.txtCidade.attr('id')) },
	Zera : function(){ window.clearInterval(this.numInterval); this.numInterval = 0; }
}

jQuery(window).load(function(){ IntervalBusca.init(); });
