/**
* jQuery.ScrollTo - Easy element scrolling using jQuery.
* Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 5/25/2009
* @author Ariel Flesler
* @version 1.4.2
*
* http://flesler.blogspot.com/2007/10/jqueryscrollto.html
*/
; (function (d) { var k = d.scrollTo = function (a, i, e) { d(window).scrollTo(a, i, e) }; k.defaults = { axis: 'xy', duration: parseFloat(d.fn.jquery) >= 1.3 ? 0 : 1 }; k.window = function (a) { return d(window)._scrollable() }; d.fn._scrollable = function () { return this.map(function () { var a = this, i = !a.nodeName || d.inArray(a.nodeName.toLowerCase(), ['iframe', '#document', 'html', 'body']) != -1; if (!i) return a; var e = (a.contentWindow || a).document || a.ownerDocument || a; return d.browser.safari || e.compatMode == 'BackCompat' ? e.body : e.documentElement }) }; d.fn.scrollTo = function (n, j, b) { if (typeof j == 'object') { b = j; j = 0 } if (typeof b == 'function') b = { onAfter: b }; if (n == 'max') n = 9e9; b = d.extend({}, k.defaults, b); j = j || b.speed || b.duration; b.queue = b.queue && b.axis.length > 1; if (b.queue) j /= 2; b.offset = p(b.offset); b.over = p(b.over); return this._scrollable().each(function () { var q = this, r = d(q), f = n, s, g = {}, u = r.is('html,body'); switch (typeof f) { case 'number': case 'string': if (/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)) { f = p(f); break } f = d(f, this); case 'object': if (f.is || f.style) s = (f = d(f)).offset() } d.each(b.axis.split(''), function (a, i) { var e = i == 'x' ? 'Left' : 'Top', h = e.toLowerCase(), c = 'scroll' + e, l = q[c], m = k.max(q, i); if (s) { g[c] = s[h] + (u ? 0 : l - r.offset()[h]); if (b.margin) { g[c] -= parseInt(f.css('margin' + e)) || 0; g[c] -= parseInt(f.css('border' + e + 'Width')) || 0 } g[c] += b.offset[h] || 0; if (b.over[h]) g[c] += f[i == 'x' ? 'width' : 'height']() * b.over[h] } else { var o = f[h]; g[c] = o.slice && o.slice(-1) == '%' ? parseFloat(o) / 100 * m : o } if (/^\d+$/.test(g[c])) g[c] = g[c] <= 0 ? 0 : Math.min(g[c], m); if (!a && b.queue) { if (l != g[c]) t(b.onAfterFirst); delete g[c] } }); t(b.onAfter); function t(a) { r.animate(g, j, b.easing, a && function () { a.call(this, n, b) }) } }).end() }; k.max = function (a, i) { var e = i == 'x' ? 'Width' : 'Height', h = 'scroll' + e; if (!d(a).is('html,body')) return a[h] - d(a)[e.toLowerCase()](); var c = 'client' + e, l = a.ownerDocument.documentElement, m = a.ownerDocument.body; return Math.max(l[h], m[h]) - Math.min(l[c], m[c]) }; function p(a) { return typeof a == 'object' ? a : { top: a, left: a} } })(jQuery);


var msg = "";

function Tags(palavra) {
    var strTexto = "";
    $(document).ready(function () {
        $("#texto p").each(function () {
            $(this).html($(this).text().replace(palavra, "<span style='background-color:#FF0'>" + palavra + "</span>"));
        });
    });
}
//EXPAND MAPA
$(document).ready(function () {
    $(".mapa_imoevis").hide();
    $(".abrirmapa").click(function () {
        $(this).next(".mapa_imoevis").slideToggle(200);
    });
    var open = false;
    $('.bt_prestar').click(function () {
        if (!open) {
            $('.form_prestar').show();
            open = true;
        } else {
            $('.form_prestar').hide();
            open = false;
        }
    });
});

// Expansão Mapa
$(function () {
    $("#trigger").click(function (event) {
        event.preventDefault();
        $("#mapa").slideToggle();
    });
    $("#mapa a").click(function (event) {
        event.preventDefault();
        $("#mapa").slideUp();
    });

    $('#tabInterna').show();
});
//Expand Financiamento
$(document).ready(function () {
    $(".txt_caixa").hide().filter(':first').show();
    $(".msg_head").click(function ()//click
    {
        $(this).next(".txt_caixa").slideToggle(400);
    });
});

//Expand Mapa do Site
$(document).ready(function () {
    $(".txt_caixa2").hide().filter(':first').show();
    $(".msg_head2").mouseover(function ()//click
    {
        $(this).next(".txt_caixa2").slideToggle(0);
    });
});

//CAROUSEL
jQuery(document).ready(function () {

    jQuery('#mycarouselEmp').jcarousel({ scroll: 1 });
    jQuery('#mycarouselPlantas').jcarousel({ scroll: 1 });
    jQuery('#mycarouselAmbientes').jcarousel({ scroll: 1 });
    jQuery('#mycarouselFaereas').jcarousel({ scroll: 1 });
    jQuery('#mycarouselLocalizacao').jcarousel({ scroll: 1 });
    jQuery('#mycarouselcozinha').jcarousel({ scroll: 1 });
    jQuery('#mycarouselquartos').jcarousel({ scroll: 1 });
    jQuery('#mycarouselbanheiros').jcarousel({ scroll: 1 });
    jQuery('#mycarouselsala').jcarousel({ scroll: 1 });
    jQuery('#mycarouselexterno').jcarousel({ scroll: 1 });

    //############################### MARCOS NOVO CARROUSEL #####################
    //cristiano: alteração na montagem da aba todos 
    function carrossel(tipo, tam) {
        $('#destaqueHome' + tipo).jcarousel({
            scroll: 1,
            size: tam
        });
    }

    //busca a class utilizada para definir a ordenação da aba "Todos" e retorna o indice de ordenação.
    function ordemTodosIndices(val) {
        var strRetorno = "0";
        var arrClassName = val.toString().split(" ");
        var pos = 0;
        for (var i = 0; i < arrClassName.length; i++) {
            pos = arrClassName[i].indexOf("ordem_todos");
            if (pos > -1) {
                if (arrClassName[i].length > 11) //ordem_todos -> 11 carac.
                {
                    strRetorno = arrClassName[i].replace("ordem_todos", "");
                }
                break;
            }
        }
        return strRetorno;
    }

    function sortNumber(a, b) {
        return a - b;
    }

    //Carousel Load
    $('#destaquesTipo li a').each(function (i) {
        var tipo = $(this).attr('class');
        var qtd = $('#destaquematriz').find('li.' + tipo).length;
        $('#destaquematriz').after('<div id="caixa' + tipo + '"><ul id="destaqueHome' + tipo + '" class="jcarousel-skin-imoveis"></ul></div>');
        if (tipo == "todos_carousel_home") {
            var tmpIndices = "|45|"; //para remover itens não ordenados
            var tmp = "";
            var obj = $('#destaquematriz').find('li.' + tipo);
            for (var i = 0; i < qtd; i++) {
                tmp = "|" + ordemTodosIndices(obj[i].className) + "|";
                if (tmpIndices.indexOf(tmp) == -1) {
                    tmpIndices += tmp;
                }
            }

            tmpIndices = tmpIndices.replace("|45|", ""); //para remover itens não ordenados 'ordem_todos45' (default.aspx.cs ln:512)
            //tmpIndices = tmpIndices.replace("|99|", ""); //para remover itens abrangentes 'ordem_todos99', para serem ordenados por último
            var qtdItens = 0;
            if (tmpIndices.length > 0) {
                var arrOrdemTmp = tmpIndices.substr(1, tmpIndices.length - 2).split("||");
                var arrOrdem = new Array(arrOrdemTmp.length);
                for (var i = 0; i < arrOrdemTmp.length; i++) {
                    arrOrdem[i] = parseInt(arrOrdemTmp[i]);
                }
                arrOrdem = arrOrdem.sort(sortNumber);

                //força a qtdItens sempre ser 8
                //qtdItens = (arrOrdem.length <= 8 ? arrOrdem.length : 8);
                qtdItens = arrOrdem.length;

                for (var i = 0; i < qtdItens; i++) {
                    if ($('#destaquematriz li.ordem_todos' + arrOrdem[i])) {
                        $('#destaquematriz li.ordem_todos' + arrOrdem[i]).clone(true).appendTo('#destaqueHome' + tipo);
                    }
                }
            }

            //se a quantidade de itens for menor que 8, ele completa com os abrangentes 
            //if (qtdItens < 8) {

            //completa os itens da aba 'Todos', com itens carregados em outras abas utilizando como base a 
            //class 'vazioX' (default.aspx.cs).
            var qtdComp = (8 - qtdItens);
            if (qtdComp > qtd) {
                qtdComp = qtd - qtdItens;
            }

            var qtdLiTodos45 = $('#destaquematriz').find('li.ordem_todos45').length;
            $('#destaquematriz').find('li.ordem_todos45').clone(true).slice(0, qtdComp).appendTo('#destaqueHome' + tipo);

            //Força os abrangentes a ficar por último.
            var qtdLiTodos45 = $('#destaqueHome' + tipo).find('li.ordem_todos45').length;
            var qtdLiTodos99 = $('#destaquematriz').find('li.ordem_todos99').length;
            if (qtdLiTodos99 > 0) {
                $('#destaquematriz').find('li.ordem_todos99').clone(true).slice(0, (8 - qtdLiTodos45)).appendTo('#destaqueHome' + tipo);
            }

            //Atualiza contador de total de itens da aba 'Todos'.
            qtd = $('#destaqueHome' + tipo).find('li').length;
            if (document.getElementById('ctl00_cph_todos')) {

                var soma = parseInt($('input[id*="hdnLanc"]').val()) + parseInt($('input[id*="hdnPreLanc"]').val()) + parseInt($('input[id*="hdnSemiPront"]').val()) + parseInt($('input[id*="hdnPront"]').val());

                if (soma) {
                    $('#ctl00_cph_todos').text("(" + soma + ")");

                    $('#lanc').text("(" + $('input[id*="hdnLanc"]').val() + ")");
                    $('#prelanc').text("(" + $('input[id*="hdnPreLanc"]').val() + ")");
                    $('#semipront').text("(" + $('input[id*="hdnSemiPront"]').val() + ")");
                    $('#prontos').text("(" + $('input[id*="hdnPront"]').val() + ")");
                }
                else {
                    document.getElementById('ctl00_cph_todos').innerHTML = "(" + qtd + ")";
                }
            }
            //}
        }
        else {
            $('#destaquematriz li.' + tipo).clone(true).appendTo('#destaqueHome' + tipo);
        }

        carrossel(tipo, qtd);

    });
    $('#destaquematriz').remove();

    //Tabs
    $('ul#destaquesTipo').tabs();
    $('ul.tabCarouselHoME a').click(function () {
        $('ul.tabCarouselHoME a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    }).filter(':first').click();


    //REMOVE ABAS QUE NÃO TEM CONTEUDO NA HOME BY MARCOS
    //cristiano: alteração na verificação de existência de itens a serem exibidos.

    var lancamento = -1;
    var pronto = -1;
    var pre = -1;
    var semi = -1;

    //lancamentos
    lancamento = $('ul#destaqueHomelanc_carousel_home').find('li.lanc_carousel_home').length;
    /*$('div#destaqueHome ul#destaqueHomelanc_carousel_home li').each(function (i) {
    lancamento = i;
    });*/

    if (lancamento <= 0) {

        $('div.tabsHome #ctl00_cph_liLancamento').remove();
        //$('div.tabsHome #ctl00_cph_liLancamento').find('a').remove();

        if (document.getElementById("ctl00_cph_hlkLancamento")) {
            document.getElementById("ctl00_cph_hlkLancamento").className = "pre_lancamento";
        }
    }

    //pre
    pre = $('ul#destaqueHomepre_carousel_home').find('li.pre_carousel_home').length;
    /*$('div#destaqueHome ul#destaqueHomepre_carousel_home li').each(function (i) {
    pre = i;
    });*/
    if (pre <= 0) {

        $('div.tabsHome ul#caixapre_carousel_home').remove();
        $('div.tabsHome #liPreLancamento a').remove();

        if (lancamento <= 0) {
            if (document.getElementById("ctl00_cph_hlkLancamento")) {
                document.getElementById("ctl00_cph_hlkLancamento").className = "semiprontos";
            }
        }
    }

    //semi-prontos
    semi = $('ul#destaqueHomesemi_carousel_home').find('li.semi_carousel_home').length;
    /*$('div#destaqueHome ul#destaqueHomesemi_carousel_home li').each(function (i) {
    semi = i;
    });*/
    if (semi <= 0) {

        $('div.tabsHome ul#caixasemi_carousel_home').remove();
        $('div.tabsHome #liSemiProntos a').remove();

        if (pre <= 0 && lancamento <= 0) {
            if (document.getElementById("ctl00_cph_hlkLancamento")) {
                document.getElementById("ctl00_cph_hlkLancamento").className = "prontospramorar";
            }
        }
    }

    //prontos
    pronto = $('ul#destaqueHomeprontos_carousel_home').find('li.prontos_carousel_home').length;
    /*$('div#destaqueHome ul#destaqueHomeprontos_carousel_home li').each(function (i) {
    pronto = i;
    });*/
    if (pronto <= 0) {
        $('div.tabsHome ul#caixaprotnos_carousel_home').remove();
        $('div.tabsHome #liProntos a').remove();
    }
});

//ABAS INTERNAS
jQuery(document).ready(function () {
    var emp = -1;
    var pla = -1;
    var amb = -1;
    var aer = -1;
    var loc = -1;

    //fotos do imovel
    $('div.tabsInt div#empinterna ul li div').each(function (i) {
        emp = i;
    });
    if (emp < 0) {
        $('div.tabsInt div#empinterna').remove();
        $('div.tabsInt #liEmp a').remove();
        $('div.tabsInt ul.tabsIntNavigation a').removeClass('selected');
        $('div.tabsInt ul.tabsIntNavigation li#liPlan a').addClass(' selected');
        $('div.tabsInt #plantas').show();
    }

    //plantas
    $('div.tabsInt div#plantas ul li div').each(function (i) {
        pla = i;
    });
    if (pla < 0) {
        $('div.tabsInt div#plantas').remove();
        $('div.tabsInt #liPlan a').remove();
        if (emp < 0 && pla < 0) {
            $('div.tabsInt ul.tabsIntNavigation a').removeClass('selected');
            $('div.tabsInt ul.tabsIntNavigation li#liAmb a').addClass(' selected');
            $('div.tabsInt #ambientes').show();
        }
    }
    //ambientes
    $('div.tabsInt div#ambientes ul li div').each(function (i) {
        amb = i;
    });
    if (amb < 0) {
        $('div.tabsInt div#ambientes').remove();
        $('div.tabsInt #liAmb a').remove();
        if (emp < 0 && pla < 0 && amb < 0) {
            $('div.tabsInt ul.tabsIntNavigation a').removeClass('selected');
            $('div.tabsInt ul.tabsIntNavigation li#liAer a').addClass(' selected');
            $('div.tabsInt #faereas').show();
        }
    }
    //fotos aéreas
    $('div.tabsInt div#faereas ul li div').each(function (i) {
        aer = i;
    });
    if (aer < 0) {
        $('div.tabsInt div#faereas').remove();
        $('div.tabsInt #liAer a').remove();
        if (emp < 0 && pla < 0 && amb < 0 && aer < 0) {
            $('div.tabsInt ul.tabsIntNavigation a').removeClass('selected');
            $('div.tabsInt ul.tabsIntNavigation li#liLoc a').addClass(' selected');
            $('div.tabsInt #localizacao').show();
        }
    }
    //localizacao
    $('div.tabsHome div#localizacao ul li div').each(function (i) {
        loc = i;
    });
    if (loc < 0) {
        $('div.tabsHome div#localizacao').remove();
        $('div.tabsHome #liLoc a').remove();
    }
});

//TABS Carousel Interna_Empreendimento
$(function () {
    var tabContainers = $('div.tabsInt > div');
    tabContainers.hide().filter(':first').show();
    $('div.tabsInt ul.tabsIntNavigation a').click(function () {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.tabsInt ul.tabsIntNavigation a').removeClass('selectedInt');
        $(this).addClass('selectedInt');
        return false;
    }).filter(':first').click();
});
//TABS Carousel Interna_Acabamento
$(function () {
    var tabContainers = $('div.tabsIntAC > div');
    tabContainers.hide().filter(':first').show();
    $('div.tabsIntAC ul.tabsIntACNavigation a').click(function () {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.tabsIntAC ul.tabsIntACNavigation a').removeClass('selectedInt');
        $(this).addClass('selectedInt');
        return false;
    }).filter(':first').click();
});
//tabs busca
$(function () {
    var tabContainers = $('div.tabs > div');
    tabContainers.hide().filter(':first').show();
    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    }).filter(':first').click();
});
//tabs busca voltar_cep
$(function () {
    var tabContainers = $('div.tabs > div');
    tabContainers.hide().filter(':first').show();
    $('div..bt_voltar_a a').click(function () {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.tabs ul.tabNavigation a#b_cep').removeClass('selected');
        $('div.tabs ul.tabNavigation a#b_rapida').addClass('selected');
        return false;
    }).filter(':first').click();
});
//tabs busca voltar_emp
$(function () {
    var tabContainers = $('div.tabs > div');
    tabContainers.hide().filter(':first').show();
    $('div..bt_voltar_b a').click(function () {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.tabs ul.tabNavigation a#b_emp').removeClass('selected');
        $('div.tabs ul.tabNavigation a#b_rapida').addClass('selected');
        return false;
    }).filter(':first').click();
});
//tabs busca voltar_avancada
$(function () {
    var tabContainers = $('div.tabs > div');
    tabContainers.hide().filter(':first').show();
    $('div..bt_voltar_c a').click(function () {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.tabs ul.tabNavigation a#b_avancada').removeClass('selected');
        $('div.tabs ul.tabNavigation a#b_rapida').addClass('selected');
        return false;
    }).filter(':first').click();
});

//dock
$(document).ready(function () {
    //Tooltip
    $('#linkTooltip').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        extraClass: "right"
    });
    //jqDock
    var opts = {
        align: 'middle',
        size: 64,
        distance: 100,
        coefficient: 1.5,
        labels: 'bc',
        duration: 150//,
        //source: function(i){ return this.src.replace(/gif$/,'png'); }
    };
    $('#dock').jqDock(opts);
});

function gravaCookie(id, sigla, nome, url) {
    var date = new Date();
    date.setTime(date.getTime() + (355 * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = "UF=" + sigla + expires + "; path=/";
    document.cookie = "idEstado=" + id + expires + "; path=/";
    document.cookie = "Estado=" + nome + expires + "; path=/";
    document.getElementById("mapa").style.display = 'none';
    location.href = '/' + url;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


// FACEBOX
//jQuery(document).ready(function($) {
//    $('a[rel*=facebox]').facebox()
//}) 

function abrir(strMensagem) {
    $(document).ready(function () {
        jQuery.facebox(strMensagem);
    })
}


function validaBuscaRapida() {
    msg = "";
    if (document.getElementById("ctl00_ddlCidade").value == "0") {
        msg = "Selecione uma Cidade para realizar a busca!";
    }
    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}
function validaBuscaCep() {
    msg = "";
    if (document.getElementById("ctl00_txtInicioCep").value == "" || document.getElementById("ctl00_txtFimCep").value == "") {
        msg = "Preencha o CEP corretamente para realizar a busca!";
    }
    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}
function validaBuscaEmpreendimento() {
    msg = "";
    if (document.getElementById("ctl00_txtPalavraBusca").value == "") {
        msg = "Preencha o Nome do empreendimento ou uma palavra-chave para realizar a busca!";
    }
    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}
function validaBuscaCepLoja() {
    msg = "";
    //valida se preencheu cep corretamente
    if (document.getElementById("ctl00_cph_tbLojaCep").value != "" || document.getElementById("ctl00_cph_tbLojaCepDig").value != "") {
        if (document.getElementById("ctl00_cph_tbLojaCep").value == "" || document.getElementById("ctl00_cph_tbLojaCepDig").value == "") {
            msg = "Preencha o CEP corretamente para realizar a busca!";
        }
    }
    //valida se selecionou ddlProximidade e não preencheu CEP
    if (document.getElementById("ctl00_cph_ddlProximidade").value != "0" && document.getElementById("ctl00_cph_tbLojaCep").value == "") {
        msg = "Preencha o CEP corretamente para realizar a busca!";
    }
    //Nenhum campo preenchido
    if (document.getElementById("ctl00_cph_ddlEstado").value == "0" && document.getElementById("ctl00_cph_tbLojaCep").value == "") {
        msg = "Selecione um filtro para a busca";
    }
    //Todos os campos preenchidos
    if (document.getElementById("ctl00_cph_ddlEstado").value != "0" && document.getElementById("ctl00_cph_tbLojaCep").value != "") {
        msg = "A busca aceita as seguintes combina&ccedil;&otilde;es: Estado + cidade ou Cep + Raio proximidade.";
    }


    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}
function validaBuscaAvancada() {
    msg = "";
    if (document.getElementById("ctl00_ddlEstadoAvancado").value == "0" && document.getElementById("ctl00_txtInicioCepAvancado").value == "" && document.getElementById("ctl00_txtPalavraAvancada").value == "") {
        msg = "Selecione uma localiza&ccedil;&atilde;o ou preencha o campo CEP ou uma palavra-chave para realizar a busca!";
    }
    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}

function validaDddETel(ddd, tel, valorDdd, valorTel) {
    var retorno = 0;

    if ((document.getElementById(ddd).value != "" && document.getElementById(ddd).value != valorDdd) && (document.getElementById(tel).value != "" && document.getElementById(tel).value != valorTel)) {
        retorno = 1;
    }
    return retorno;
}

function validaCadastrese() {
    msg = "";

    if (Trim(document.getElementById("ctl00_cph_txtNome").value) == "") {
        document.getElementById("ctl00_cph_txtNome").value = Trim(document.getElementById("ctl00_cph_txtNome").value);
        msg = "Preencha o campo <strong>Nome</strong>!<br />";
    }

    if (document.getElementById("ctl00_cph_rblPais_0").checked == false && document.getElementById("ctl00_cph_rblPais_1").checked == false) {
        msg += "Selecione o local onde sua <strong>resid&ecirc;cia est&aacute; localizada</strong>.<br />";
    }
    else if (document.getElementById("ctl00_cph_rblPais_1").checked == true) {
        var ddi, ddd, tel;

        ddi = document.getElementById("ctl00_cph_txtDdi").value;
        ddd = document.getElementById("ctl00_cph_txtDdd").value;
        tel = document.getElementById("ctl00_cph_txtTelefone").value;
        ddi = ddi.replace('-', '');
        ddd = ddd.replace('-', '');
        tel = tel.replace('-', '');

        if (ddi == "" || ddi == "DDI") {
            msg += "Preencha o campo <strong>Ddi</strong>!<br />";
        }
        else if (!Number(ddi)) {
            document.getElementById("ctl00_cph_txtDdi").value = "DDI";
            msg += "Campo <strong>DDI Inv&aacute;lido!</strong><br />";
        }
        else if (ddi.length != 2) {
            document.getElementById("ctl00_cph_txtDdi").value = "DDI";
            msg += "Campo <strong>DDI Inv&aacute;lido!</strong><br />";
        }

        if ((ddd == "" || ddd == "DDD")) {
            msg += "Preencha o campo <strong>Ddd</strong>!<br />";
        }
        else if (!Number(ddd)) {
            document.getElementById("ctl00_cph_txtDdd").value = "DDD";
            msg += "Campo <strong>DDD Inv&aacute;lido!</strong><br />";
        }
        else if (ddd.length != 2) {
            document.getElementById("ctl00_cph_txtDdd").value = "DDD";
            msg += "Campo <strong>DDD Inv&aacute;lido!</strong><br />";
        }

        if ((tel == "" || tel == "FONE")) {
            msg += "Preencha o campo <strong>Telefone</strong>!<br />";
        }
        else if (!Number(tel)) {
            document.getElementById("ctl00_cph_txtTelefone").value = "FONE";
            msg += "Campo <strong>Telefone Inv&aacute;lido!</strong><br />";
        }
        else if (tel.length != 8) {
            document.getElementById("ctl00_cph_txtTelefone").value = "FONE";
            msg += "Campo <strong>Telefone Inv&aacute;lido!</strong><br />";
        }
    }
    else if (document.getElementById("ctl00_cph_rblPais_0").checked == true) {

        var dddCel, dddTel, CelBr, TelBr;

        dddCel = document.getElementById("ctl00_cph_txtDddCel").value;
        CelBr = document.getElementById("ctl00_cph_txtTelefoneCel").value;
        dddTel = document.getElementById("ctl00_cph_txtDdd").value;
        TelBr = document.getElementById("ctl00_cph_txtTelefone").value;

        dddCel = dddCel.replace('-', '');
        CelBr = CelBr.replace('-', '');
        dddTel = dddTel.replace('-', '');
        TelBr = TelBr.replace('-', '');

        if ((validaDddETel("ctl00_cph_txtDddCel", "ctl00_cph_txtTelefoneCel", "DDD", "FONE") == 0) && (validaDddETel("ctl00_cph_txtDdd", "ctl00_cph_txtTelefone", "DDD", "FONE") == 0)) {
            msg += "Preencha um <strong>Telefone com Ddd para contato!</strong>!<br />";
        }
        else if (validaDddETel("ctl00_cph_txtDddCel", "ctl00_cph_txtTelefoneCel", "DDD", "FONE") == 0) {
            document.getElementById("ctl00_cph_txtDddCel").value = "DDD";
            document.getElementById("ctl00_cph_txtTelefoneCel").value = "FONE";
        }
        else if (validaDddETel("ctl00_cph_txtDdd", "ctl00_cph_txtTelefone", "DDD", "FONE") == 0) {
            document.getElementById("ctl00_cph_txtDdd").value = "DDD";
            document.getElementById("ctl00_cph_txtTelefone").value = "FONE";
        }


        if (((dddTel == "" || dddTel == "DDD") && (TelBr == "" || TelBr == "FONE")) && ((dddCel == "" || dddCel == "DDD") && (CelBr == "" || CelBr == "FONE"))) {
            msg += "Preencha um <strong>Telefone com Ddd para contato!</strong>!<br />";
        }
        else {
            //validação de celular
            if (dddCel != "" && dddCel != "DDD") {
                var ddd = /^[1-9]{2}$/;
                if (!ddd.test(dddCel)) {
                    document.getElementById("ctl00_cph_txtDddCel").value = "DDD";
                    msg += "Campo <strong>DDD Celular Inv&aacute;lido!</strong><br />";
                }
                else if (!Number(dddCel)) {
                    document.getElementById("ctl00_cph_txtDddCel").value = "DDD";
                    msg += "Campo <strong>DDD Celular Inv&aacute;lido!</strong><br />";
                }
                else if (dddCel.length != 2) {
                    document.getElementById("ctl00_cph_txtDddCel").value = "DDD";
                    msg += "Campo <strong>DDD Celular Inv&aacute;lido!</strong><br />";
                }
            }
            else {
                document.getElementById("ctl00_cph_txtDddCel").value = "DDD";
            }

            if (CelBr != "" && CelBr != "FONE") {
                var celular = /^[5-9]{1}[0-9]{7}$/;
                if (!celular.test(CelBr)) {
                    document.getElementById("ctl00_cph_txtTelefoneCel").value = "FONE";
                    msg += "Campo <strong>Telefone Celular Inv&aacute;lido!</strong><br />";
                }
                else if (!Number(CelBr)) {
                    document.getElementById("ctl00_cph_txtTelefoneCel").value = "FONE";
                    msg += "Campo <strong>Telefone Celular Inv&aacute;lido!</strong><br />";
                }
                else if (CelBr.length != 8) {
                    document.getElementById("ctl00_cph_txtTelefoneCel").value = "FONE";
                    msg += "Campo <strong>Telefone Celular Inv&aacute;lido!</strong><br />";
                }
            }
            else {

                document.getElementById("ctl00_cph_txtTelefoneCel").value = "FONE";
            }

            //validação de Telefone Fixo
            if (dddTel != "" && dddTel != "DDD") {
                var ddd = /^[1-9]{2}$/;
                if (!ddd.test(dddTel)) {
                    document.getElementById("ctl00_cph_txtDdd").value = "DDD";
                    msg += "Campo <strong>DDD Inv&aacute;lido!</strong><br />";
                }
                else if (!Number(dddTel)) {
                    document.getElementById("ctl00_cph_txtDdd").value = "DDD";
                    msg += "Campo <strong>DDD Inv&aacute;lido!</strong><br />";
                }
                else if (dddTel.length != 2) {
                    document.getElementById("ctl00_cph_txtDdd").value = "DDD";
                    msg += "Campo <strong>DDD Inv&aacute;lido!</strong><br />";
                }
            }
            else {
                document.getElementById("ctl00_cph_txtDdd").value = "DDD";
            }

            if (TelBr != "" && TelBr != "FONE") {
                var celular = /^[5-9]{1}[0-9]{7}$/;
                if (celular.test(TelBr)) {
                    document.getElementById("ctl00_cph_txtTelefone").value = "FONE";
                    msg += "Campo <strong>Telefone Fixo Inv&aacute;lido!</strong><br />";
                }
                else if (!Number(TelBr)) {
                    document.getElementById("ctl00_cph_txtTelefone").value = "FONE";
                    msg += "Campo <strong>Telefone Fixo Inv&aacute;lido!</strong><br />";
                }
                else if (TelBr.length != 8) {
                    document.getElementById("ctl00_cph_txtTelefone").value = "FONE";
                    msg += "Campo <strong>Telefone Fixo Inv&aacute;lido!</strong><br />";
                }
            }
            else {
                document.getElementById("ctl00_cph_txtTelefone").value = "FONE";
            }


        }
    }

    if (document.getElementById("ctl00_cph_txtEmail").value == "") {
        msg += "Preencha o campo <strong>E-mail</strong>!<br />";
    }
    else {
        if (!VerificaEmail(document.getElementById("ctl00_cph_txtEmail").value)) {
            msg += "<strong>E-mail inv&aacute;lido</strong>!<br />";
        }
    }
    if (document.getElementById("ctl00_cph_txtMensagem").value == "") {
        msg += "Preencha o campo <strong>Mensagem</strong>!<br />";
    }
    if (document.getElementById("ctl00_cph_rblContato_0").checked == false && document.getElementById("ctl00_cph_rblContato_1").checked == false) {
        msg += "Selecione uma forma de <strong>receber nosso Contato!</strong><br />";
    }

    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}

function validaNovidades() {
    msg = "";
    if (document.getElementById("ctl00_cph_txtNome").value == "") {
        msg = "Preencha o campo <strong>Nome</strong>!<br />";
    }

    if (document.getElementById("ctl00_cph_txtEmail").value == "") {
        msg += "Preencha o campo <strong>E-mail</strong>!<br />";
    }
    else {
        if (!VerificaEmail(document.getElementById("ctl00_cph_txtEmail").value)) {
            msg += "<strong>E-mail inv&aacute;lido</strong>!<br />";
        }
    }

    if (document.getElementById("ctl00_cph_txtDddCelular").value == "" && document.getElementById("ctl00_cph_txttelefoneCelular").value != "") {
        msg += "Preencha o campo <strong>Ddd do telefone Celullar</strong>!<br />";
    }
    if (document.getElementById("ctl00_cph_txtDddCelular").value != "" && document.getElementById("ctl00_cph_txttelefoneCelular").value == "") {
        msg += "Preencha o campo <strong>telefone Celullar</strong>!<br />";
    }
    if (document.getElementById("ctl00_cph_txtDddResidencial").value == "" && document.getElementById("ctl00_cph_txtTelefoneResidencial").value != "") {
        msg += "Preencha o campo <strong>Ddd do telefone Residencial</strong>!<br />";
    }
    if (document.getElementById("ctl00_cph_txtDddResidencial").value != "" && document.getElementById("ctl00_cph_txtTelefoneResidencial").value == "") {
        msg += "Preencha o campo <strong>telefone Residencial</strong>!<br />";
    }
    if (document.getElementById("ctl00_cph_txtDddComercial").value == "" && document.getElementById("ctl00_cph_txtTelefoneComercial").value != "") {
        msg += "Preencha o campo <strong>Ddd do telefone Comercial</strong>!<br />";
    }
    if (document.getElementById("ctl00_cph_txtDddComercial").value != "" && document.getElementById("ctl00_cph_txtTelefoneComercial").value == "") {
        msg += "Preencha o campo <strong>telefone Comercial</strong>!<br />";
    }

    if (document.getElementById("ctl00_cph_txtDddCelular").value == "" && document.getElementById("ctl00_cph_txttelefoneCelular").value == "" && document.getElementById("ctl00_cph_txtDddResidencial").value == "" && document.getElementById("ctl00_cph_txtTelefoneResidencial").value == "" && document.getElementById("ctl00_cph_txtDddComercial").value == "" && document.getElementById("ctl00_cph_txtTelefoneComercial").value == "") {

        msg += "Preencha um <strong>Telefone com Ddd para contato</strong>!<br />";
    }
    else {

        var dddCelular, telCelular, dddResidencial, telResidencial, dddComercial, telComercial;

        dddCelular = document.getElementById("ctl00_cph_txtDddCelular").value;
        telCelular = document.getElementById("ctl00_cph_txttelefoneCelular").value;
        dddResidencial = document.getElementById("ctl00_cph_txtDddResidencial").value;
        telResidencial = document.getElementById("ctl00_cph_txtTelefoneResidencial").value;
        dddComercial = document.getElementById("ctl00_cph_txtDddComercial").value;
        telComercial = document.getElementById("ctl00_cph_txtTelefoneComercial").value;

        dddCelular = dddCelular.replace('-', '');
        telCelular = telCelular.replace('-', '');
        dddResidencial = dddResidencial.replace('-', '');
        telResidencial = telResidencial.replace('-', '');
        dddComercial = dddComercial.replace('-', '');
        telComercial = telComercial.replace('-', '');


        if ((validaDddETel("ctl00_cph_txtDddCelular", "ctl00_cph_txttelefoneCelular", "", "") == 0) && (validaDddETel("ctl00_cph_txtDddResidencial", "ctl00_cph_txtTelefoneResidencial", "", "") == 0) && (validaDddETel("ctl00_cph_txtDddComercial", "ctl00_cph_txtTelefoneComercial", "", "") == 0)) {
            msg += "Preencha um <strong>Telefone com Ddd para contato!</strong>!<br />";
        }
        else if (validaDddETel("ctl00_cph_txtDddCelular", "ctl00_cph_txttelefoneCelular", "", "") == 0) {
            document.getElementById("ctl00_cph_txtDddCelular").value = "";
            document.getElementById("ctl00_cph_txttelefoneCelular").value = "";
        }
        else if (validaDddETel("ctl00_cph_txtDddResidencial", "ctl00_cph_txtTelefoneResidencial", "", "") == 0) {
            document.getElementById("ctl00_cph_txtDddResidencial").value = "";
            document.getElementById("ctl00_cph_txtTelefoneResidencial").value = "";
        }
        else if (validaDddETel("ctl00_cph_txtDddComercial", "ctl00_cph_txtTelefoneComercial", "", "") == 0) {
            document.getElementById("ctl00_cph_txtDddComercial").value = "";
            document.getElementById("ctl00_cph_txtTelefoneComercial").value = "";
        }

        if (dddCelular != "" || telCelular != "") {

            //validação de DDD celular
            var ddd = /^[1-9]{2}$/;

            //validação de Telefone celular
            var celular = /^[5-9]{1}[0-9]{3}[0-9]{4}$/;

            if (!ddd.test(dddCelular)) {
                document.getElementById("ctl00_cph_txtDddCelular").value = '';
                msg += "Campo <strong>DDD Inv&aacute;lido!</strong><br />";
            }
            else if (!Number(dddCelular)) {
                document.getElementById("ctl00_cph_txtDddCelular").value = '';
                msg += "Campo <strong>DDD Celular Inv&aacute;lido!</strong><br />";
            }
            else if (dddCelular.length != 2) {
                document.getElementById("ctl00_cph_txtDddCelular").value = '';
                msg += "Campo <strong>DDD Celular Inv&aacute;lido!</strong><br />";
            }

            if (!celular.test(telCelular)) {
                document.getElementById("ctl00_cph_txttelefoneCelular").value = '';
                msg += "Campo <strong>Celular Inv&aacute;lido!</strong><br />";
            }
            else if (!Number(telCelular)) {
                document.getElementById("ctl00_cph_txttelefoneCelular").value = '';
                msg += "Campo <strong>Telefone Celular Inv&aacute;lido!</strong><br />";
            }
            else if (telCelular.length != 8) {
                document.getElementById("ctl00_cph_txttelefoneCelular").value = '';
                msg += "Campo <strong>Telefone Celular Inv&aacute;lido!</strong><br />";
            }
        }

        if (dddResidencial != "" || telResidencial != "") {
            //Residencial
            if (dddResidencial != "" || telResidencial != "") {
                if (!Number(dddResidencial)) {
                    document.getElementById("ctl00_cph_txtDddResidencial").value = '';
                    msg += "Campo <strong>DDD Residencial Inv&aacute;lido!</strong><br />";
                }
                else if (dddResidencial.length != 2) {
                    document.getElementById("ctl00_cph_txtDddResidencial").value = '';
                    msg += "Campo <strong>DDD Residencial Inv&aacute;lido!</strong><br />";
                }

                if (!Number(telResidencial)) {
                    document.getElementById("ctl00_cph_txtTelefoneResidencial").value = '';
                    msg += "Campo <strong>Telefone Residencial Inv&aacute;lido!</strong><br />";
                }
                else if (telResidencial.length != 8) {
                    document.getElementById("ctl00_cph_txtTelefoneResidencial").value = '';
                    msg += "Campo <strong>Telefone Residencial Inv&aacute;lido!</strong><br />";
                }
            }
        }

        if (dddComercial != "" || telComercial != "") {
            //Comercial
            if (dddComercial != "" || telComercial != "") {
                if (!Number(dddComercial)) {
                    document.getElementById("ctl00_cph_txtDddComercial").value = '';
                    msg += "Campo <strong>DDD Comercial Inv&aacute;lido!</strong><br />";
                }
                else if (dddComercial.length != 2) {
                    document.getElementById("ctl00_cph_txtDddComercial").value = '';
                    msg += "Campo <strong>DDD Comercial Inv&aacute;lido!</strong><br />";
                }

                if (!Number(telComercial)) {
                    document.getElementById("ctl00_cph_txtTelefoneComercial").value = '';
                    msg += "Campo <strong>Telefone Comercial Inv&aacute;lido!</strong><br />";
                }
                else if (telComercial.length != 8) {
                    document.getElementById("ctl00_cph_txtTelefoneComercial").value = '';
                    msg += "Campo <strong>Telefone Comercial Inv&aacute;lido!</strong><br />";
                }
            }
        }
    }

    //cidades de interesse
    inttotal = document.getElementById("ctl00_cph_hndTotalCidade").value;
    var contador = 0;
    for (i = 0; i < inttotal; i++) {
        if (document.getElementById("ctl00_cph_cblCidades_" + i).checked == true) {
            contador++;
        }
    }
    if (contador == 0) {
        msg += "Selecione a(s) <strong>Cidade(s) de interesse</strong>!<br />";
    }
    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}


function validaFale() {
    msg = "";
    if (document.getElementById("ctl00_cph_txtNome").value == "") {
        msg = "Preencha o campo <strong>Nome</strong>!<br />";
    }

    if (document.getElementById("ctl00_cph_txtEmail").value == "") {
        msg += "Preencha o campo <strong>E-mail</strong>!<br />";
    }
    else {
        if (!VerificaEmail(document.getElementById("ctl00_cph_txtEmail").value)) {
            msg += "<strong>E-mail inv&aacute;lido</strong>!<br />";
        }
    }
    if (document.getElementById("ctl00_cph_rblPais_0").checked == false && document.getElementById("ctl00_cph_rblPais_1").checked == false) {
        msg += "Selecione o local onde sua <strong>resid&ecirc;cia est&aacute; localizada</strong>.<br />";
    }
    else {
        if (document.getElementById("ctl00_cph_rblPais_0").checked == true) {
            if (document.getElementById("ctl00_cph_ddlEstados").value == "0") {
                msg += "Selecione o <strong>Estado</strong> onde mora!<br />";
            }
            if (document.getElementById("ctl00_cph_ddlCidades").value == "0") {
                msg += "Selecione a <strong>Cidade</strong> onde mora!<br />";
            }
        }
        if (document.getElementById("ctl00_cph_rblPais_1").checked == true) {
            if (document.getElementById("ctl00_cph_txtPais").value == "") {
                msg += "Preencha o campo <strong>Pa&iacute;s</strong> onde mora!<br />";
            }
            if (document.getElementById("ctl00_cph_txtEstado").value == "") {
                msg += "Preencha o campo <strong>Estado</strong> onde mora!<br />";
            }
            if (document.getElementById("ctl00_cph_txtCidade").value == "") {
                msg += "Preencha o campo <strong>Cidade</strong> onde mora!<br />";
            }
        }
    }


    if (document.getElementById("ctl00_cph_rblPais_0").checked == true) {

        if (document.getElementById("ctl00_cph_txtDddCelular").value == "" && document.getElementById("ctl00_cph_txttelefoneCelular").value != "") {
            msg += "Preencha o campo <strong>Ddd do telefone Celullar</strong>!<br />";
        }

        if (document.getElementById("ctl00_cph_txtDddCelular").value != "" && document.getElementById("ctl00_cph_txttelefoneCelular").value == "") {
            msg += "Preencha o campo <strong>telefone Celullar</strong>!<br />";
        }

        if (document.getElementById("ctl00_cph_txtDddResidencial").value == "" && document.getElementById("ctl00_cph_txtTelefoneResidencial").value != "") {
            msg += "Preencha o campo <strong>Ddd do telefone Residencial</strong>!<br />";
        }
        if (document.getElementById("ctl00_cph_txtDddResidencial").value != "" && document.getElementById("ctl00_cph_txtTelefoneResidencial").value == "") {
            msg += "Preencha o campo <strong>telefone Residencial</strong>!<br />";
        }
        if (document.getElementById("ctl00_cph_txtDddComercial").value == "" && document.getElementById("ctl00_cph_txtTelefoneComercial").value != "") {
            msg += "Preencha o campo <strong>Ddd do telefone Comercial</strong>!<br />";
        }
        if (document.getElementById("ctl00_cph_txtDddComercial").value != "" && document.getElementById("ctl00_cph_txtTelefoneComercial").value == "") {
            msg += "Preencha o campo <strong>telefone Comercial</strong>!<br />";
        }

        if (document.getElementById("ctl00_cph_txtDddCelular").value == "" && document.getElementById("ctl00_cph_txttelefoneCelular").value == "" && document.getElementById("ctl00_cph_txtDddResidencial").value == "" && document.getElementById("ctl00_cph_txtTelefoneResidencial").value == "" && document.getElementById("ctl00_cph_txtDddComercial").value == "" && document.getElementById("ctl00_cph_txtTelefoneComercial").value == "") {

            msg += "Preencha um <strong>Telefone com Ddd para contato</strong>!<br />";
        }
        else {

            var dddCelular, telCelular, dddResidencial, telResidencial, dddComercial, telComercial;

            dddCelular = document.getElementById("ctl00_cph_txtDddCelular").value;
            telCelular = document.getElementById("ctl00_cph_txttelefoneCelular").value;
            dddResidencial = document.getElementById("ctl00_cph_txtDddResidencial").value;
            telResidencial = document.getElementById("ctl00_cph_txtTelefoneResidencial").value;
            dddComercial = document.getElementById("ctl00_cph_txtDddComercial").value;
            telComercial = document.getElementById("ctl00_cph_txtTelefoneComercial").value;

            dddCelular = dddCelular.replace('-', '');
            telCelular = telCelular.replace('-', '');
            dddResidencial = dddResidencial.replace('-', '');
            telResidencial = telResidencial.replace('-', '');
            dddComercial = dddComercial.replace('-', '');
            telComercial = telComercial.replace('-', '');


            if ((validaDddETel("ctl00_cph_txtDddCelular", "ctl00_cph_txttelefoneCelular", "", "") == 0) && (validaDddETel("ctl00_cph_txtDddResidencial", "ctl00_cph_txtTelefoneResidencial", "", "") == 0) && (validaDddETel("ctl00_cph_txtDddComercial", "ctl00_cph_txtTelefoneComercial", "", "") == 0)) {
                msg += "Preencha um <strong>Telefone com Ddd para contato!</strong>!<br />";
            }
            else if (validaDddETel("ctl00_cph_txtDddCelular", "ctl00_cph_txttelefoneCelular", "", "") == 0) {
                document.getElementById("ctl00_cph_txtDddCelular").value = "";
                document.getElementById("ctl00_cph_txttelefoneCelular").value = "";
            }
            else if (validaDddETel("ctl00_cph_txtDddResidencial", "ctl00_cph_txtTelefoneResidencial", "", "") == 0) {
                document.getElementById("ctl00_cph_txtDddResidencial").value = "";
                document.getElementById("ctl00_cph_txtTelefoneResidencial").value = "";
            }
            else if (validaDddETel("ctl00_cph_txtDddComercial", "ctl00_cph_txtTelefoneComercial", "", "") == 0) {
                document.getElementById("ctl00_cph_txtDddComercial").value = "";
                document.getElementById("ctl00_cph_txtTelefoneComercial").value = "";
            }

            if (dddCelular != "" || telCelular != "") {

                //validação de DDD celular
                var ddd = /^[1-9]{2}$/;

                //validação de Telefone celular
                var celular = /^[5-9]{1}[0-9]{3}[0-9]{4}$/;

                if (!ddd.test(dddCelular)) {
                    document.getElementById("ctl00_cph_txtDddCelular").value = '';
                    msg += "Campo <strong>DDD Inv&aacute;lido!</strong><br />";
                }
                else if (!Number(dddCelular)) {
                    document.getElementById("ctl00_cph_txtDddCelular").value = '';
                    msg += "Campo <strong>DDD Celular Inv&aacute;lido!</strong><br />";
                }
                else if (dddCelular.length != 2) {
                    document.getElementById("ctl00_cph_txtDddCelular").value = '';
                    msg += "Campo <strong>DDD Celular Inv&aacute;lido!</strong><br />";
                }

                if (!celular.test(telCelular)) {
                    document.getElementById("ctl00_cph_txttelefoneCelular").value = '';
                    msg += "Campo <strong>Celular Inv&aacute;lido!</strong><br />";
                }
                else if (!Number(telCelular)) {
                    document.getElementById("ctl00_cph_txttelefoneCelular").value = '';
                    msg += "Campo <strong>Telefone Celular Inv&aacute;lido!</strong><br />";
                }
                else if (telCelular.length != 8) {
                    document.getElementById("ctl00_cph_txttelefoneCelular").value = '';
                    msg += "Campo <strong>Telefone Celular Inv&aacute;lido!</strong><br />";
                }
            }

            if (dddResidencial != "" || telResidencial != "") {
                //Residencial
                if (dddResidencial != "" || telResidencial != "") {
                    if (!Number(dddResidencial)) {
                        document.getElementById("ctl00_cph_txtDddResidencial").value = '';
                        msg += "Campo <strong>DDD Residencial Inv&aacute;lido!</strong><br />";
                    }
                    else if (dddResidencial.length != 2) {
                        document.getElementById("ctl00_cph_txtDddResidencial").value = '';
                        msg += "Campo <strong>DDD Residencial Inv&aacute;lido!</strong><br />";
                    }

                    if (!Number(telResidencial)) {
                        document.getElementById("ctl00_cph_txtTelefoneResidencial").value = '';
                        msg += "Campo <strong>Telefone Residencial Inv&aacute;lido!</strong><br />";
                    }
                    else if (telResidencial.length != 8) {
                        document.getElementById("ctl00_cph_txtTelefoneResidencial").value = '';
                        msg += "Campo <strong>Telefone Residencial Inv&aacute;lido!</strong><br />";
                    }
                }
            }

            if (dddComercial != "" || telComercial != "") {
                //Comercial
                if (dddComercial != "" || telComercial != "") {
                    if (!Number(dddComercial)) {
                        document.getElementById("ctl00_cph_txtDddComercial").value = '';
                        msg += "Campo <strong>DDD Comercial Inv&aacute;lido!</strong><br />";
                    }
                    else if (dddComercial.length != 2) {
                        document.getElementById("ctl00_cph_txtDddComercial").value = '';
                        msg += "Campo <strong>DDD Comercial Inv&aacute;lido!</strong><br />";
                    }

                    if (!Number(telComercial)) {
                        document.getElementById("ctl00_cph_txtTelefoneComercial").value = '';
                        msg += "Campo <strong>Telefone Comercial Inv&aacute;lido!</strong><br />";
                    }
                    else if (telComercial.length != 8) {
                        document.getElementById("ctl00_cph_txtTelefoneComercial").value = '';
                        msg += "Campo <strong>Telefone Comercial Inv&aacute;lido!</strong><br />";
                    }
                }
            }
        }
    }
    else if (document.getElementById("ctl00_cph_rblPais_1").checked == true) {
        var ddiResidencial, dddResidencial, telResidencial, ddiComercial, dddComercial, telComercial;

        ddiResidencial = document.getElementById("ctl00_cph_txtDdiResidencial").value;
        dddResidencial = document.getElementById("ctl00_cph_txtDddResidencial").value;
        telResidencial = document.getElementById("ctl00_cph_txtTelefoneResidencial").value;
        ddiComercial = document.getElementById("ctl00_cph_txtddiComercial").value;
        dddComercial = document.getElementById("ctl00_cph_txtDddComercial").value;
        telComercial = document.getElementById("ctl00_cph_txtTelefoneComercial").value;

        ddiResidencial = ddiResidencial.replace('-', '');
        dddResidencial = dddResidencial.replace('-', '');
        telResidencial = telResidencial.replace('-', '');
        ddiComercial = ddiComercial.replace('-', '');
        dddComercial = dddComercial.replace('-', '');
        telComercial = telComercial.replace('-', '');

        if ((validaDddETel("ctl00_cph_txtDddResidencial", "ctl00_cph_txtTelefoneResidencial", "", "") == 0) && (validaDddETel("ctl00_cph_txtDddComercial", "ctl00_cph_txtTelefoneComercial", "", "") == 0)) {
            msg += "Preencha um <strong>Telefone com Ddd para contato!</strong>!<br />";
        }
        else if (validaDddETel("ctl00_cph_txtDddResidencial", "ctl00_cph_txtTelefoneResidencial", "", "") == 0) {
            document.getElementById("ctl00_cph_txtDddResidencial").value = "";
            document.getElementById("ctl00_cph_txtTelefoneResidencial").value = "";
        }
        else if (validaDddETel("ctl00_cph_txtDddComercial", "ctl00_cph_txtTelefoneComercial", "", "") == 0) {
            document.getElementById("ctl00_cph_txtDddComercial").value = "";
            document.getElementById("ctl00_cph_txtTelefoneComercial").value = "";
        }

        if (ddiResidencial == "" && dddResidencial == "" && telResidencial == "" && ddiComercial == "" && dddComercial == "" && telComercial == "") {
            msg += "Preencha um <strong>Telefone com Ddd para contato</strong>!<br />";
        }
        else {

            //Residencial
            if (ddiResidencial != "" || dddResidencial != "" || telResidencial != "") {
                if (!Number(ddiResidencial)) {
                    document.getElementById("ctl00_cph_txtDdiResidencial").value = '';
                    msg += "Campo <strong>DDI Residencial Inv&aacute;lido!</strong><br />";
                }
                else if (ddiResidencial.length != 2) {
                    document.getElementById("ctl00_cph_txtDdiResidencial").value = '';
                    msg += "Campo <strong>DDI Residencial Inv&aacute;lido!</strong><br />";
                }

                if (!Number(dddResidencial)) {
                    document.getElementById("ctl00_cph_txtDddResidencial").value = '';
                    msg += "Campo <strong>DDD Residencial Inv&aacute;lido!</strong><br />";
                }
                else if (dddResidencial.length != 2) {
                    document.getElementById("ctl00_cph_txtDddResidencial").value = '';
                    msg += "Campo <strong>DDD Residencial Inv&aacute;lido!</strong><br />";
                }

                if (!Number(telResidencial)) {
                    document.getElementById("ctl00_cph_txtTelefoneResidencial").value = '';
                    msg += "Campo <strong>Telefone Residencial Inv&aacute;lido!</strong><br />";
                }
                else if (telResidencial.length != 8) {
                    document.getElementById("ctl00_cph_txtTelefoneResidencial").value = '';
                    msg += "Campo <strong>Telefone Residencial Inv&aacute;lido!</strong><br />";
                }
            }

            //Comercial
            if (ddiComercial != "" || dddComercial != "" || telComercial != "") {
                if (!Number(ddiComercial)) {
                    document.getElementById("ctl00_cph_txtddiComercial").value = '';
                    msg += "Campo <strong>DDI Comercial Inv&aacute;lido!</strong><br />";
                }
                else if (ddiComercial.length != 2) {
                    document.getElementById("ctl00_cph_txtddiComercial").value = '';
                    msg += "Campo <strong>DDI Comercial Inv&aacute;lido!</strong><br />";
                }

                if (!Number(dddComercial)) {
                    document.getElementById("ctl00_cph_txtDddComercial").value = '';
                    msg += "Campo <strong>DDD Comercial Inv&aacute;lido!</strong><br />";
                }
                else if (dddComercial.length != 2) {
                    document.getElementById("ctl00_cph_txtDddComercial").value = '';
                    msg += "Campo <strong>DDD Comercial Inv&aacute;lido!</strong><br />";
                }

                if (!Number(telComercial)) {
                    document.getElementById("ctl00_cph_txtTelefoneComercial").value = '';
                    msg += "Campo <strong>Telefone Comercial Inv&aacute;lido!</strong><br />";
                }
                else if (telComercial.length != 8) {
                    document.getElementById("ctl00_cph_txtTelefoneComercial").value = '';
                    msg += "Campo <strong>Telefone Comercial Inv&aacute;lido!</strong><br />";
                }
            }
        }
    }

    //cidades de interesse
    inttotal = document.getElementById("ctl00_cph_hndTotalCidade").value;
    var contador = 0;
    for (i = 0; i < inttotal; i++) {
        if (document.getElementById("ctl00_cph_cblCidades_" + i).checked == true) {
            contador++;
        }
    }
    if (contador == 0) {
        msg += "Selecione a(s) <strong>Cidade(s) de interesse</strong>!<br />";
    }

    if (document.getElementById("ctl00_cph_rblContato_0").checked == false && document.getElementById("ctl00_cph_rblContato_1").checked == false) {
        msg += "Selecione uma forma de <strong>receber nosso Contato!</strong><br />";
    }

    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}

function validaFormBusca() {

    msg = "";
    if (document.getElementById("ctl00_cph_txtNome").value == "") {
        msg = "Preencha o campo <strong>Nome</strong>!<br />";
    }

    if (document.getElementById("ctl00_cph_txtEmail").value == "") {
        msg += "Preencha o campo <strong>E-mail</strong>!<br />";
    }
    else {
        if (!VerificaEmail(document.getElementById("ctl00_cph_txtEmail").value)) {
            msg += "<strong>E-mail inv&aacute;lido</strong>!<br />";
        }
    }

    if (document.getElementById("ctl00_cph_txtDddResidencial").value == "" || document.getElementById("ctl00_cph_txtDddResidencial").value == "DDD") {
        msg += "Preencha o campo <strong>Ddd</strong>!<br />";
    }
    if (document.getElementById("ctl00_cph_txtTelefoneResidencial").value == "" || document.getElementById("ctl00_cph_txtTelefoneResidencial").value == "FONE") {
        msg += "Preencha o campo <strong>Telefone</strong>!<br />";
    }

    if (document.getElementById("ctl00_cph_rblContato_0").checked == false && document.getElementById("ctl00_cph_rblContato_1").checked == false) {
        msg += "Selecione uma forma de <strong>receber nosso Contato!</strong><br />";
    }

    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
}

function PopChatDT(url, cidade, bairro, origem) {
    var popchat = window.open("http://www.mrv.com.br/corretores/chat/" + url + "?cidade=" + cidade + "&bairro=" + bairro + "&cod=" + (new Date().getTime()) + "&origem=" + origem, "Pop_Chat", "top=25,left=50,width=505,height=590,scrollbars=no,resizable=yes");
    //var popchat = window.open("http://mrv.opencorporate.com.br/corretores/chat/" + url + "?cidade=" + cidade + "&bairro=" + bairro + "&cod=" + (new Date().getTime()) + "&origem=" + origem, "Pop_Chat", "top=25,left=50,width=505,height=590,scrollbars=no,resizable=yes");
    popchat.focus();
}

var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail2 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail3 = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail = reEmail3;
function VerificaEmail(stremail) {
    if (reEmail.test(stremail)) {
        return true;
    } else if (stremail != null && stremail != "") {
        return false
    }
}

//marca checbox
function MarcaCheckBox(total, campo, local) {
    inttotal = document.getElementById(total).value;
    for (i = 0; i < inttotal; i++) {
        if (local.checked) {
            document.getElementById(campo + i).checked = true;
        }
        else {
            document.getElementById(campo + i).checked = false;
        }
    }
}

var _font_min = 10;
var _font_max = 18;
var _tags = ['div', 'p', 'h1', 'h2', 'span', 'a', 'i', 'b', 'li', 'td', 'strong', 'f5', 'dd'];
function Aumentar(idDiv) {
    // validacoes      
    var e_corpo_noticia = document.getElementById(idDiv);
    if (typeof (e_corpo_noticia) != 'object') return;
    var atual_size = e_corpo_noticia.style.fontSize;
    // apanhando o tamanho atual
    if (!atual_size) atual_size = 14;
    else atual_size = parseInt(atual_size.replace('px'));
    if (atual_size >= _font_max) return;
    modificar_geral(e_corpo_noticia, atual_size + 1);
}

function Diminuir(idDiv) {
    var e_corpo_noticia = document.getElementById(idDiv);
    if (typeof (e_corpo_noticia) != 'object') return;
    var atual_size = e_corpo_noticia.style.fontSize;
    if (!atual_size) atual_size = 14;
    else atual_size = parseInt(atual_size.replace('px'));
    if (atual_size <= _font_min) return;
    modificar_geral(e_corpo_noticia, atual_size - 1);
}

function modificar_geral(el, size) {
    el.style.fontSize = size + 'px';
    var tags = _tags;
    for (var i in tags) {
        var l_els = el.getElementsByTagName(tags[i]);
        for (var i = 0; i < l_els.length; i++) {
            l_els[i].style.fontSize = size + 'px';
        }
    }

}

//TEXTO JURIDICO
function exibir() {
    document.getElementById("text_juridico").style.display = "block";
}
function esconder() {
    document.getElementById("text_juridico").style.display = "none";
}
function exibir2() {
    document.getElementById("text_juridico2").style.display = "block";
}
function esconder2() {
    document.getElementById("text_juridico2").style.display = "none";
}

// Zoom
function def() {
    $('.ui-slider-handle').css({ 'left': '10px' });
}
var id;
var newvalorz;
var left_i;
var left_f;
var left_final;
function inicializer() {
    $(document).ready(function () {

        document.getElementById('fancy_right').onclick = function () { def(); };
        document.getElementById('fancy_right_ico').onclick = function () { def(); };
        document.getElementById('fancy_left').onclick = function () { def(); };
        document.getElementById('fancy_left_ico').onclick = function () { def(); };
        $('a#fancy_left, a#fancy_right').css('display', 'block'); $('span#fancy_right_ico').css('right', '20px'); $('span#fancy_left_ico').css('left', '20px');
        $('#fancy_close').click(function () { $('.imagem_zoom').remove(); });

        $(document).bind('keydown.fb', function (e) {
            if (e.keyCode == 37 || e.keyCode == 39) {
                $('.ui-slider-handle').css({ 'left': '10px' });
            }

        });

        $(document).bind('keydown.fb', function (e) {
            if (e.keyCode == 27) {
                $('.imagem_zoom').remove();
            }
        });

        $('#fancy_content').mouseleave(function () {
            $('#fancy_img').css({ 'left': '0', 'top': '0' });
        })

    })

    $('#fancy_img').css({ 'left': '0', 'top': '0', 'position': 'relative' });
    $('#fancy_content').css({ 'overflow': 'hidden' });
    $('#fancy_outer').append('<div class="imagem_zoom" style="display:none;"><div class="ui-icon ui-icon-circle-minus gzoombutton" onClick="zoom_menos();" >&nbsp;</div><div class="gzoomSlider"><div class="delimiter"> <a class="ui-slider-handle"></a></div></div><div class="ui-icon ui-icon-circle-plus gzoombutton" onClick="zoom_mais();">&nbsp;</div></div>');

    $('.imagem_zoom').show();
    altura = $('#fancy_outer').css('height');
    largura = $('#fancy_outer').css('width');

    $('.ui-slider-handle').mousedown(function () { left_i = $('.ui-slider-handle').css('left'); if (left_i > 90) { left_i = 90 } else if (left_i <= 11) { left_i = 10; $('#fancy_img').animate({ 'height': '+=' + altura, 'width': '+=' + largura }, 1); } });
    $('.ui-slider-handle').mouseup(function () { left_f = $('.ui-slider-handle').css('left'); if (left_i > 90) { left_i = 90 } else if (left_i <= 11) { left_i = 10; $('#fancy_img').animate({ 'height': '+=' + altura, 'width': '+=' + largura }, 1); } });
    $('.delimiter').mouseleave(function () { left_f = $('.ui-slider-handle').css('left'); $('.ui-slider-handle').trigger('mouseup'); });

    $('.ui-slider-handle').draggable({ containment: ".delimiter", scroll: false, axis: "x", stop: function (event, ui) {
        if (parseInt(left_f) > parseInt(left_i)) {
            left_final = parseInt(left_f) - parseInt(left_i);
            arredonda(left_final);
            $('#fancy_img').animate({ 'height': '+=' + newvalorz * 10, 'width': '+=' + newvalorz * 10 }, 500);
        }
        else if (parseInt(left_f) < parseInt(left_i)) {
            left_final_volta = parseInt(left_i) - parseInt(left_f);
            arredonda(left_final_volta);
            $('#fancy_img').animate({ 'height': '-=' + newvalorz * 10, 'width': '-=' + newvalorz * 10 }, 500);
        }
        else {
            $('#fancy_img:amimate').stop();
        }
    }
    });

    $('#fancy_content').mousemove(function (e) {
        var divWidth = $('#fancy_content').width();
        var divHeight = $('#fancy_content').height();
        var igW = $('#fancy_img').width();
        var igH = $('#fancy_img').height();
        var dOs = $('#fancy_content').offset();
        var leftPan = (e.pageX - dOs.left) * (divWidth - igW) / (divWidth + 2);
        var topPan = (e.pageY - dOs.top) * (divHeight - igH) / (divHeight + 2);

        $('#fancy_img').css({ left: leftPan, top: topPan });
    });

}

function zoom_mais() {
    $('.ui-icon-circle-plus').attr('onClick', '').css('cursor', 'default');
    $('.ui-icon-circle-minus').attr('onClick', '').css('cursor', 'default');

    vReal = parseInt($('.ui-slider-handle').css('left')) + 20;
    vRealz = vReal - parseInt($('.ui-slider-handle').css('left'));

    arredonda(vRealz);

    if ((parseInt($('.ui-slider-handle').css('left')) < 90) && (vReal <= 90)) {
        $('.ui-slider-handle').animate({ left: '+=20' }, 500);
        $('#fancy_img').animate({ 'height': '+=' + newvalorz * 10, 'width': '+=' + newvalorz * 10 }, 500, function () { $('.ui-icon-circle-plus').attr('onClick', 'zoom_mais()').css('cursor', 'pointer'); $('.ui-icon-circle-minus').attr('onClick', 'zoom_menos()').css('cursor', 'pointer'); });

    }
    else if ((vReal > 90) && (parseInt($('.ui-slider-handle').css('left')) < 90)) {
        vAbsoluto = 90 - parseInt($('.ui-slider-handle').css('left'));
        $('.ui-slider-handle').animate({ left: '+=' + vAbsoluto }, 500);
        $('#fancy_img').animate({ 'height': '+=' + newvalorz * 10, 'width': '+=' + newvalorz * 10 }, 500, function () { $('.ui-icon-circle-plus').attr('onClick', 'zoom_mais()').css('cursor', 'pointer'); $('.ui-icon-circle-minus').attr('onClick', 'zoom_menos()').css('cursor', 'pointer'); })
    }
    else {
        $('.ui-slider-handle:animate').stop();
        $('.ui-icon-circle-plus').attr('onClick', 'zoom_mais()').css('cursor', 'pointer'); $('.ui-icon-circle-minus').attr('onClick', 'zoom_menos()').css('cursor', 'pointer');
    }

}

function zoom_menos() {
    $('.ui-icon-circle-plus').attr('onClick', '').css('cursor', 'default');
    $('.ui-icon-circle-minus').attr('onClick', '').css('cursor', 'default');

    vReal = parseInt($('.ui-slider-handle').css('left')) - 20;
    vRealz = parseInt($('.ui-slider-handle').css('left')) - vReal;
    arredonda(vRealz);

    if ((parseInt($('.ui-slider-handle').css('left')) > 10) && (parseInt(vReal) > 10)) {
        $('.ui-slider-handle').animate({ left: '-=20' }, 500);
        $('#fancy_img').animate({ 'height': '-=' + newvalorz * 10, 'width': '-=' + newvalorz * 10 }, 500, function () { $('.ui-icon-circle-plus').attr('onClick', 'zoom_mais()').css('cursor', 'pointer'); $('.ui-icon-circle-minus').attr('onClick', 'zoom_menos()').css('cursor', 'pointer'); });

    }
    else if ((vReal <= 10) && (parseInt($('.ui-slider-handle').css('left')) > 10)) {
        vAbsoluto = parseInt($('.ui-slider-handle').css('left')) - 10;
        $('.ui-slider-handle').animate({ left: '-=' + vAbsoluto }, 500);
        $('#fancy_img').animate({ 'height': '-=' + vAbsoluto * 10, 'width': '-=' + vAbsoluto * 10 }, 500, function () { $('.ui-icon-circle-plus').attr('onClick', 'zoom_mais()').css('cursor', 'pointer'); $('.ui-icon-circle-minus').attr('onClick', 'zoom_menos()').css('cursor', 'pointer'); })
    }
    else {
        $('.ui-slider-handle:animate').stop();
        $('.ui-icon-circle-plus').attr('onClick', 'zoom_mais()').css('cursor', 'pointer'); $('.ui-icon-circle-minus').attr('onClick', 'zoom_menos()').css('cursor', 'pointer');
    }

}


function arredonda(valor) {

    valor1 = parseInt(valor) / 10;
    newvalor = valor1.toString().split(".");

    if ((valor1 == 1) && (newvalor[1] >= 0)) {
        newvalor[0] = parseInt(newvalor[0]);
        newvalorz = newvalor[0] + '0';
    }
    else if ((newvalor[0] == 9) && (newvalor[1] >= 0)) {
        newvalor[0] = parseInt(newvalor[0]);
        newvalorz = newvalor[0] + '0';
    }
    else {

        if (newvalor[1] >= 5) {
            newvalor[0] = (parseInt(newvalor[0]) + 1);
        }
        else {
            newvalor[0] = parseInt(newvalor[0]);
        }
        newvalorz = newvalor[0] + '0';
    }

}



//EXPAND FINANCIAMENTO
$(document).ready(function () {
    $(".abrir2").hide();
    $(".abrir").click(function () {
        $(this).next(".abrir2").slideToggle(1);
    });
    //$('div .tabsInt div.conteudo_carouselInt ul li a').attr('title').style.display = 'none';
    //
});


//###################### NOVOS COMBOS DE BUSCA MARCOS ##########################################

var currentKeyDrop = null;
var currentADrop = null;
var currentIndex = null;
var currentLetter = null;
var frase = [];

function keyDropdown(e) {
    // Enter
    if (e.which == 13)
        return selectDropItem();

    // Arrow keys
    /*
    if ( e.keyCode == 40 || e.keyCode == 38 )
    return moveDropItem( e );
    */

    var letra = String.fromCharCode(e.which).toUpperCase();

    /*
    frase.push( letra );
    var fraseStr = frase.join(''),
    fraseLength = frase.length,
    achou = false;
    */

    var fraseStr = letra,
		fraseLength = fraseStr.length,
		items = [],
		achou = false;

    if (currentLetter != letra) {
        currentLetter = letra;
        currentIndex = -1;
    }

    currentKeyDrop.next().children().each(function () {
        var a = $(this).children(),
			text = a.text(),
			textUpper = text.toUpperCase();

        if (textUpper.substr(0, fraseLength) == fraseStr) {
            /*
            achou = true;
            currentADrop = a;
            a.html( markText( text, fraseStr ) );
            a.parent().addClass( 'buscaListaSelect' );
            */
            achou = true;
            items.push(a);
        }
    });

    if (achou) {
        if (currentADrop)
            currentADrop.parent().removeClass('buscaListaSelect');

        currentIndex++;
        if (currentIndex >= (items.length))
            currentIndex = 0;

        currentADrop = items[currentIndex];
        currentADrop.parent().addClass('buscaListaSelect');
        currentADrop.parent().parent().scrollTo(currentADrop);
    }
    else
        clearDrop();

    return e.preventDefault();
}

function clearDrop() {
    frase = [];
    if (currentADrop != null) {
        currentADrop.parent().removeClass('buscaListaSelect');
        currentADrop = null;

        /*
        currentKeyDrop.next().children().each( function()
        {
        var a = $(this).children(),
        text = a.text();
        a.html( text );
        });
        */
    }

    if (currentKeyDrop)
        currentKeyDrop.next().hide();
}

function selectDropItem() {
    if (currentADrop) {
        var href = currentADrop.attr('href'),
			js = 'javascript:';

        currentADrop.trigger('click');
        if (href.substring(0, js.length) == js)
            href = href.substring(js.length, href.length);
        eval(href);
    }

    clearDrop();
    setTimeout('$(".buscaLista").hide();', 300);
}

function markText(text, subText) {
    var sL = subText.length,
		s1 = text.substr(0, sL),
		s2 = text.substr(sL);
    text = '<span class="marked">' + s1 + '</span>' + s2;
    return text;
}

function moveDropItem(e) {
    var a = currentADrop,
		ul = currentKeyDrop,
		i = 0,
		e = 0,
		up = (e.keyCode == 40);


    ul.next().children().each(function () {
        if ($(this).children().text() == a.text()) {
            e = i;
        }
        i++;
    });

    e = (up ? e-- : e++);
    if (e < 1) e = 1;
    else if (e > i) e = i;

    clearDrop();
    /*
    console.log( "A:", a, " up ", up );
    currentADrop = a;
    */
}

$(document).ready(function () {
    //Busca Rapida
    listar('', 'Estado', 'Rapida', '', '', '', '', '', '');

    $('#rapida a[href="javascript:void(0);"]:eq(0), #avancada a[href="javascript:void(0);"]:eq(0)').addClass('active');
    $('#rapida a[href="javascript:void(0);"], #avancada a[href="javascript:void(0);"] , #busca_tel a[href="javascript:void(0);"]').click(function () {
        var obj = $(this);

        obj.next().css('display', 'block');

        // Adiciona um listener para o pressinamento de tecla
        $('body').bind('keypress', keyDropdown);
        currentKeyDrop = obj;

        //oculta drop
        obj.bind("mouseleave", function () {
            $(this).next().css('display', 'none');
            $('body').unbind('keypress', keyDropdown);
            clearDrop();

        });

        //mostra drop
        obj.next().bind("mouseenter", function () {
            $(this).css('display', 'block');
            $('body').bind('keypress', keyDropdown);
        });

        //MARCOS ROBERTO - 2011-10-06 #################################################################################
        //DEMANDA - 13014
        //MUDANÇA PARA FECHAR NO CLICK SOMENTE NO ESTADO E CIDADE
        var completaId = "";
        if ($(this).next().attr('id').indexOf('listaEstado') > -1 || $(this).next().attr('id').indexOf('listaCidade') > -1) {
            completaId = "click";
        }
        //EVENTO FECHAR SIMULADOR DE COMBOS

        obj.next().bind("mouseleave " + completaId, function () {
            $(this).css('display', 'none');
            $('body').unbind('keypress', keyDropdown);
            clearDrop();
        });
        //FIM MUDANÇA ##################################################################################################

        $('ul a').click(function () {
            var tipo; // = $('ul.used a').parent().parent().attr('id');
            if (document.getElementById('avancada').style.display == 'none') { tipo = 'Rapida'; } else { tipo = 'Avancada'; }

            var quem = $(this).parent().parent().attr('id');
            var cidade = $('a#linkCidade' + tipo).attr('class');
            var bairro = $('a#linkBairro' + tipo).attr('class');
            var produto = $('a#linkProduto' + tipo).attr('class');
            var tipologia = $('a#linkTiplogia' + tipo).attr('class');
            var faixa = $('a#linkFaixa' + tipo).attr('class');
            var metragem = $('a#linkMetragem' + tipo).attr('class');
            var rev = $(this).attr('rev');

            if (quem == 'listaEstado' + tipo) {

                $('a#linkCidade' + tipo).attr({ rel: '' });
                $('a#linkCidade' + tipo).text('Cidade');

                $('a#linkCidade' + tipo).removeClass('active');
                $('ul#listaCidade' + tipo).remove();
                $('a#linkCidade' + tipo).after('<ul id="listaCidade' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Selecione um Estado</a></li></ul>');
                //bairro				
                $('a#linkBairro' + tipo).attr({ rel: '' });
                $('a#linkBairro' + tipo).removeClass('active');
                $('a#linkBairro' + tipo).text('Bairro');
                $('ul#listaBairro' + tipo).remove();
                $('a#linkBairro' + tipo).after('<ul id="listaBairro' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Selecione uma Cidade</a></li></ul>');
                //produto
                $('a#linkProduto' + tipo).attr({ rel: '' });
                $('a#linkProduto' + tipo).removeClass('active');
                $('a#linkProduto' + tipo).text('Produto');
                $('ul#listaProduto' + tipo).remove();
                $('a#linkProduto' + tipo).after('<ul id="listaProduto' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Selecione um Estado</a></li></ul>');
                //tipologia
                $('a#linkTipologia' + tipo).attr({ rel: '' });
                $('a#linkTipologia' + tipo).removeClass('active');
                $('a#linkTipologia' + tipo).text('Tipologia');
                $('ul#listaTipologia' + tipo).remove();
                $('a#linkTipologia' + tipo).after('<ul id="listaTipologia' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Selecione um Estado</a></li></ul>');
                //faixa de preço
                $('a#linkFaixa' + tipo).attr({ rel: '' });
                $('a#linkFaixa' + tipo).removeClass('active');
                $('a#linkFaixa' + tipo).text(unescape(decodeURIComponent('Faixa de Pre%C3%A7o')));
                $('ul#listaFaixa' + tipo).remove();
                $('a#linkFaixa' + tipo).after('<ul id="listaFaixa' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Selecione um Estado</a></li></ul>');

                if (tipo == 'Avancada') {
                    //metragem
                    $('a#linkMetragem' + tipo).attr({ rel: '' });
                    $('a#linkMetragem' + tipo).removeClass('active');
                    $('a#linkMetragem' + tipo).text('Metragem');
                    $('ul#listaMetragem' + tipo).remove();
                    $('a#linkMetragem' + tipo).after('<ul id="listaMetragem' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                }
                //}
            }
            if (quem == 'listaCidade' + tipo) {

                //Bairro
                $('a#linkBairro' + tipo).attr({ rel: '' });
                $('a#linkBairro' + tipo).removeClass('active');
                $('a#linkBairro' + tipo).text('Bairro');
                $('ul#listaBairro' + tipo).remove();
                $('a#linkBairro' + tipo).after('<ul id="listaBairro' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Selecione uma Cidade</a></li></ul>');
                //Produto
                $('a#linkProduto' + tipo).attr({ rel: '' });
                $('a#linkProduto' + tipo).removeClass('active');
                $('a#linkProduto' + tipo).text('Produto');
                $('ul#listaProduto' + tipo).remove();
                $('a#linkProduto' + tipo).after('<ul id="listaProduto' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todos</a></li></ul>');

                //tipologia
                $('a#linkTipologia' + tipo).attr({ rel: '' });
                $('a#linkTipologia' + tipo).removeClass('active');
                $('a#linkTipologia' + tipo).text('Tipologia');
                $('ul#listaTipologia' + tipo).remove();
                $('a#linkTipologia' + tipo).after('<ul id="listaTipologia' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                //faixa de preço
                $('a#linkFaixa' + tipo).attr({ rel: '' });
                $('a#linkFaixa' + tipo).removeClass('active');
                $('a#linkFaixa' + tipo).text(unescape(decodeURIComponent('Faixa de Pre%C3%A7o')));
                $('ul#listaFaixa' + tipo).remove();
                $('a#linkFaixa' + tipo).after('<ul id="listaFaixa' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');

                if (tipo == 'Avancada') {
                    //metragem
                    $('a#linkMetragem' + tipo).attr({ rel: '' });
                    $('a#linkMetragem' + tipo).removeClass('active');
                    $('a#linkMetragem' + tipo).text('Metragem');
                    $('ul#listaMetragem' + tipo).remove();
                    $('a#linkMetragem' + tipo).after('<ul id="listaMetragem' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                }

            }
            if (quem == 'listaBairro' + tipo) {
                //Produto				 
                $('a#linkProduto' + tipo).attr({ rel: '' });
                $('a#linkProduto' + tipo).removeClass('active');
                $('a#linkProduto' + tipo).text('Produto');
                $('ul#listaProduto' + tipo).remove();
                $('a#linkProduto' + tipo).after('<ul id="listaProduto' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todos</a></li></ul>');

                //tipologia
                $('a#linkTipologia' + tipo).attr({ rel: '' });
                $('a#linkTipologia' + tipo).removeClass('active');
                $('a#linkTipologia' + tipo).text('Tipologia');
                $('ul#listaTipologia' + tipo).remove();
                $('a#linkTipologia' + tipo).after('<ul id="listaTipologia' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                //faixa de preço
                $('a#linkFaixa' + tipo).attr({ rel: '' });
                $('a#linkFaixa' + tipo).removeClass('active');
                $('a#linkFaixa' + tipo).text(unescape(decodeURIComponent('Faixa de Pre%C3%A7o')));
                $('ul#listaFaixa' + tipo).remove();
                $('a#linkFaixa' + tipo).after('<ul id="listaFaixa' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');

                if (tipo == 'Avancada') {
                    //metragem
                    $('a#linkMetragem' + tipo).attr({ rel: '' });
                    $('a#linkMetragem' + tipo).removeClass('active');
                    $('a#linkMetragem' + tipo).text('Metragem');
                    $('ul#listaMetragem' + tipo).remove();
                    $('a#linkMetragem' + tipo).after('<ul id="listaMetragem' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                }
            }

            if (quem == 'listaProduto' + tipo) {

                //tipologia
                $('a#linkTipologia' + tipo).attr({ rel: '' });
                $('a#linkTipologia' + tipo).removeClass('active');
                $('a#linkTipologia' + tipo).text('Tipologia');
                $('ul#listaTipologia' + tipo).remove();
                $('a#linkTipologia' + tipo).after('<ul id="listaTipologia' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                //faixa de preço
                $('a#linkFaixa' + tipo).attr({ rel: '' });
                $('a#linkFaixa' + tipo).removeClass('active');
                $('a#linkFaixa' + tipo).text(unescape(decodeURIComponent('Faixa de Pre%C3%A7o')));
                $('ul#listaFaixa' + tipo).remove();
                $('a#linkFaixa' + tipo).after('<ul id="listaFaixa' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');

                if (tipo == 'Avancada') {
                    //metragem
                    $('a#linkMetragem' + tipo).attr({ rel: '' });
                    $('a#linkMetragem' + tipo).removeClass('active');
                    $('a#linkMetragem' + tipo).text('Metragem');
                    $('ul#listaMetragem' + tipo).remove();
                    $('a#linkMetragem' + tipo).after('<ul id="listaMetragem' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                }
            }
            if (quem == 'listaTipologia' + tipo && tipologia == 'linkLista active used') {

                //faixa de preço
                $('a#linkFaixa' + tipo).attr({ rel: '' });
                $('a#linkFaixa' + tipo).removeClass('active');
                $('a#linkFaixa' + tipo).text(unescape(decodeURIComponent('Faixa de Pre%C3%A7o')));
                $('ul#listaFaixa' + tipo).remove();
                $('a#linkFaixa' + tipo).after('<ul id="listaFaixa' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');

                if (tipo == 'Avancada') {
                    //metragem
                    $('a#linkMetragem' + tipo).attr({ rel: '' });
                    $('a#linkMetragem' + tipo).removeClass('active');
                    $('a#linkMetragem' + tipo).text('Metragem');
                    $('ul#listaMetragem' + tipo).remove();
                    $('a#linkMetragem' + tipo).after('<ul id="listaMetragem' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                }
            }
            if (quem == 'listaFaixa' + tipo) {

                if (tipo == 'Avancada') {
                    //metragem
                    $('a#linkMetragem' + tipo).attr({ rel: '' });
                    $('a#linkMetragem' + tipo).removeClass('active');
                    $('a#linkMetragem' + tipo).text('Metragem');
                    $('ul#listaMetragem' + tipo).remove();
                    $('a#linkMetragem' + tipo).after('<ul id="listaMetragem' + tipo + '" class="buscaLista" style="display: none;"><li><a href="javascript:;">Todas</a></li></ul>');
                }
            }
        });
    });

    //Busca Avancada
    listar('0', 'Estado', 'Avancada', '', '', '', '', '', '');
    $('ul.opt a').click(function () {
        var titulo = $(this).attr('title');
        var relative = $(this).attr('rel');
        $(this).parent().parent().prev().text(titulo);
        $(this).parent().parent().prev().attr({ rel: relative });
    });
});

function listar(id, tipo, busca, idestado, idcidade, idbairro, idproduto, idtipologia, idfaixa) {

    var strUrlScript = window.location;
    if (strUrlScript.toString().indexOf('imoveis.') > -1) {
        strUrlScript = "/";
    }
    else {
        strUrlScript = "";
    }

    $('#lista' + tipo + busca).remove();
    $('#link' + tipo + busca).after('<ul id="lista' + tipo + busca + '" class="buscaLista" style="display: none;"></ul>');

    if (busca == 'Avancada') {
        $('#itensLazer').load(strUrlScript + 'itens.aspx?e=' + idestado + '&c=' + idcidade + '&b=' + idbairro + '&p=' + idproduto, {}, function () { });
    }

    $('#lista' + tipo + busca).load(strUrlScript + 'vars.aspx?id=' + id + '&e=' + idestado + '&c=' + idcidade + '&b=' + idbairro + '&p=' + idproduto + '&t=' + idtipologia + '&f=' + idfaixa + '&tipo=' + tipo + '&busca=' + busca, {}, function () {

        $('a', this).click(function () {
            var titulo = $(this).attr('title');
            var relative = $(this).attr('rel');
            if (relative == '0') {
                $('#link' + tipo + busca).text(titulo);
                $('#link' + tipo + busca).attr({ rel: relative });
            } else {
                $('#link' + tipo + busca).text(titulo);
                $('#link' + tipo + busca).addClass('used');
                $('#link' + tipo + busca).attr({ rel: relative });
                $('#lista' + tipo + busca).addClass('used');
                $('#lista' + tipo + busca).next().filter('a').addClass('active');
            }
        });
    });
}

//################################################################################################################
//Função criada por Marcos Roberto
//Descrição: esta função foi criada para tratar os valores das listas multipla-escolha de bairros, produtos, etc...
//Demanda: 13014
//2011-10-10
function MarcaCampos(lista, todos, campo) {

    var strEstado;
    var strCidade;
    var strBairro = '';
    var strProduto = '';
    var strTipologia = '';
    var strFaixa = '';
    var strMetragem = '';
    var contador = 0;
    var tipoBusca;

    //verifica o tipo de busca Rapida ou Avançada
    if (document.getElementById('avancada').style.display == 'none') { tipoBusca = 'Rapida'; } else { tipoBusca = 'Avancada'; }

    //default, definido no modo antigo
    strEstado = $('a#linkEstado' + tipoBusca).attr('rel');
    strCidade = $('a#linkCidade' + tipoBusca).attr('rel');

    //Efetua o foreach para verificar os campos marcados
    $('#' + lista + ' input').each(function () {
        //marca ou desmarca todos
        if (todos) {
            $(this).attr('checked', $(campo).attr('checked'));
        }

        //elimina o primeiro checkbox (Todos itens)
        if (contador > 0) {

            if ($(this).attr('checked') == true) {
                //bairro
                if (lista.indexOf('Bairro') > -1) {
                    strBairro += $(this).val() + ',';
                }
                //produto
                if (lista.indexOf('Produto') > -1) {
                    strProduto += $(this).val() + ',';
                }
                //produto
                if (lista.indexOf('Tipologia') > -1) {
                    strTipologia += $(this).val() + ',';
                }

                if (lista.indexOf('Faixa') > -1) {
                    strFaixa += $(this).val() + ',';
                }

                if (lista.indexOf('Metragem') > -1) {
                    strMetragem += $(this).val() + ',';
                }
            }
        }
        contador++;
    });

    //TRATA AS VARIÁVEIS DE ACORDO COM O COMBO SELECIONADO
    //Bairro
    if (lista.indexOf('Bairro') > -1) {
        if (strBairro.length > 0) {
            strBairro = strBairro.substring(0, strBairro.length - 1);
            $('a#linkBairro' + tipoBusca).attr({ rel: strBairro });
        }
        //chama o método para preencher itens filhos
        listar(strBairro, 'Produto', tipoBusca, strEstado, strCidade, '' + strBairro + '', '' + strProduto + '', '' + strTipologia + '', '' + strFaixa + '');
        listar(strBairro, 'Tipologia', tipoBusca, strEstado, strCidade, '' + strBairro + '', '' + strProduto + '', '' + strTipologia + '', '' + strFaixa + '');
        listar(strBairro, 'Faixa', tipoBusca, strEstado, strCidade, '' + strBairro + '', '' + strProduto + '', '' + strTipologia + '', '' + strFaixa + '');
    }
    else {
        //pega valor armazenado no rel do link Bairro
        strBairro = $('a#linkBairro' + tipoBusca).attr('rel');
    }

    //Produto
    if (lista.indexOf('Produto') > -1) {
        if (strProduto.length > 0) {
            strProduto = strProduto.substring(0, strProduto.length - 1);
            $('a#linkProduto' + tipoBusca).attr({ rel: strProduto });
        }
        listar(strBairro, 'Tipologia', tipoBusca, strEstado, strCidade, '' + strBairro + '', '' + strProduto + '', '' + strTipologia + '', '' + strFaixa + '');
        listar(strBairro, 'Faixa', tipoBusca, strEstado, strCidade, '' + strBairro + '', '' + strProduto + '', '' + strTipologia + '', '' + strFaixa + '');
    }
    else {
        strProduto = $('a#linkProduto' + tipoBusca).attr('rel');
    }

    //Tipologia
    if (lista.indexOf('Tipologia') > -1) {
        if (strTipologia.length > -1) {
            strTipologia = strTipologia.substring(0, strTipologia.length - 1);
            $('a#linkTipologia' + tipoBusca).attr({ rel: strTipologia });
        }
        listar(strBairro, 'Faixa', tipoBusca, strEstado, strCidade, '' + strBairro + '', '' + strProduto + '', '' + strTipologia + '', '' + strFaixa + '');
    }
    else {
        strTipologia = $('a#linkTipologia' + tipoBusca).attr('rel');
    }
    //Faixa de Preço
    if (lista.indexOf('Faixa') > -1) {
        if (strFaixa.length > 0) {
            strFaixa = encodeURIComponent(strFaixa.substring(0, strFaixa.length - 1));
            $('a#linkFaixa' + tipoBusca).attr({ rel: strFaixa });
        }
    }
    else {
        strFaixa = $('a#linkFaixa' + tipoBusca).attr('rel');
    }
    //Metragem
    if (lista.indexOf('Metragem') > -1) {
        if (strMetragem.length > 0) {
            strMetragem = strMetragem.substring(0, strMetragem.length - 1);
            $('a#linkMetragem' + tipoBusca).attr({ rel: strMetragem });
        }
    }

    //ITENS ESPECÍFICOS DA AVANÇADA
    if (tipoBusca == "Avancada") {
        $('#itensLazer').load('/itens.aspx?e=' + strEstado + '&c=' + strCidade + '&b=' + strBairro + '&p=' + strProduto, {}, function () { });
        if (lista.indexOf('Metragem') == -1) {
            listar(strBairro, 'Metragem', tipoBusca, strEstado, strCidade, '' + strBairro + '', '' + strProduto + '', '' + strTipologia + '', '' + strFaixa + '');
        }
    }
}
//MANTEM O CHECKBOX SELECIONADO APÓS REALIZAR A BUSCA
function mantemCheckado(idCombo, valorCheck) {

    var valorunico = valorCheck.split(',');
    $('#' + idCombo + ' input').each(function () {
        for (var i = 0; i < valorunico.length; i++) {
            if (valorunico[i] == $(this).val()) {
                $(this).attr('checked', true);
            }
        }
    });
}
//################################################################################################################

function enviarBusca(tipo) {

    var msg = "";
    var estado = $('a#linkEstado' + tipo).attr('rel');

    if (estado.length <= 0) {
        estado = '0';
    }
    var cidade = $('a#linkCidade' + tipo).attr('rel');

    //NOVA PROGRAMAÇÃO PARA MARCAR QUANTOS ITENS QUIZER USANDO CHECKBOX ####################################
    //MARCOS ROBERTO - 2011-10-06
    //DEMANDA - 13014
    var bairro = ""; // old = $('a#linkBairro' + tipo).attr('rel');
    $('#listaBairro' + tipo + ' input').each(function (i) {
        if (this.checked) {
            bairro += this.value + ',';
        }
    });
    if (bairro.length > 1) { bairro = bairro.substr(0, bairro.length - 1); }
    //Tipologias
    var tipologia = ""; // $('a#linkTipologia' + tipo).attr('rel');
    $('#listaTipologia' + tipo + ' input').each(function (i) {
        if (this.checked) {
            tipologia += this.value + ',';
        }
    });
    if (tipologia.length > 1) { tipologia = tipologia.substr(0, tipologia.length - 1); }
    //Produtos

    var produto = ""; // $('a#linkProduto' + tipo).attr('rel');
    $('#listaProduto' + tipo + ' input').each(function (i) {
        if (this.checked) {
            produto += this.value + ',';
        }
    });
    if (produto.length > 1) { produto = produto.substr(0, produto.length - 1); }

    //Faixa de Preço
    var faixa = ""; // $('a#linkFaixa' + tipo).attr('rel');
    $('#listaFaixa' + tipo + ' input').each(function (i) {
        if (this.checked) {
            faixa += this.value + ',';
        }
    });
    if (faixa.length > 1) { faixa = faixa.substr(0, faixa.length - 1); }

    var metragem = "";
    $('#listaMetragem' + tipo + ' input').each(function (i) {
        if (this.checked) {
            metragem += this.value + ',';
        }
    });
    if (metragem.length > 1) { metragem = metragem.substr(0, metragem.length - 1); }
    //FIM NOVA PROGRAMAÇÃO ########################################################################################

    var cep = "";
    if (tipo == 'Avancada') {
        //valida se preencheu cep corretamente
        if (document.getElementById("ctl00_txtInicioCepAvancado").value != "" || document.getElementById("ctl00_txtFimCepAvancado").value != "") {
            if (document.getElementById("ctl00_txtInicioCepAvancado").value == "" || document.getElementById("ctl00_txtFimCepAvancado").value == "") {
                msg = "Preencha o CEP corretamente para realizar a busca!";
            }
            else {
                cep = document.getElementById("ctl00_txtInicioCepAvancado").value + document.getElementById("ctl00_txtFimCepAvancado").value;
            }
        }
    }

    if (msg != "") {
        msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
        abrir(msg);
        return false;
    }
    if (tipo == 'Avancada') {
        var palavra = document.getElementById("ctl00_txtPalavraAvancada").value;
        var suite = 0;
        if (document.getElementById("ctl00_chkSuite").checked) { suite = 1; }
        var cobertura = 0;
        if (document.getElementById("ctl00_chkCobertura").checked) { cobertura = 1; }
        var areapriv = 0;
        if (document.getElementById("ctl00_chkArea").checked) { areapriv = 1; }


        var itens = "";
        $('#itensLazer input').each(function (i) {
            if (this.checked) {
                itens += this.value + ',';
            }
        });
        //itens de lazer
        if (itens.length > 1) { itens = itens.substr(0, itens.length - 1); }
    }

    var url = "";
    var strUrlScript = window.location;


    if (tipo == 'Rapida') {
        if (strUrlScript.toString().indexOf('imoveis.') > -1) {
            url = '/busca.aspx?e=' + estado + '&c=' + cidade + '&b=' + bairro + '&p=' + produto + '&t=' + tipologia + '&f=' + faixa + '&tb=R';
        }
        else {
            url = 'http://imoveis.mrv.com.br/busca.aspx?e=' + estado + '&c=' + cidade + '&b=' + bairro + '&p=' + produto + '&t=' + tipologia + '&f=' + faixa + '&tb=R';
        }

        if (estado == "0" || estado == "") {
            msg = "Selecione um Estado para realizar a busca!";
        }
        if (msg != "") {
            msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
            abrir(msg);
            return false;
        }
        else {
            window.location.href = url;
        }
    }
    else {
        if (strUrlScript.toString().indexOf('imoveis.') > -1) {
            url = '/busca.aspx?e=' + estado + '&c=' + cidade + '&b=' + bairro + '&p=' + produto + '&t=' + tipologia + '&f=' + faixa + '&m=' + metragem + '&tb=A&cep=' + cep + '&palavra=' + palavra + '&suite=' + suite + '&area=' + areapriv + '&cobertura=' + cobertura + '&itens=' + itens;
        }
        else {
            url = 'http://imoveis.mrv.com.br/busca.aspx?e=' + estado + '&c=' + cidade + '&b=' + bairro + '&p=' + produto + '&t=' + tipologia + '&f=' + faixa + '&m=' + metragem + '&tb=A&cep=' + cep + '&palavra=' + palavra + '&suite=' + suite + '&area=' + areapriv + '&cobertura=' + cobertura + '&itens=' + itens;
        }
        if ((estado == "0" || estado == "") && cep == "" && palavra == "") {
            msg = "Selecione um Estado ou uma palavra-chave para realizar a busca!";
        }
        msg = "";
        //Estado e cep juntos
        if ((estado != "0") && cep != "") {
            msg = "A busca aceita as seguintes combina&ccedil;&otilde;es: Estado + cidade + Bairro ou Cep(somente).";
        }

        if (msg != "") {
            msg = "<h2 class='Aamerelo Aalerta'>Aten&ccedil;&atilde;o:</h2>\n<p>" + msg + "</p>";
            abrir(msg);
            return false;
        }
        else {
            window.location.href = url;
        }
    }
}

function BuscaNuvenDeTags(estado, cidade, bairro, produto, tipologia, faixa) {

    var strUrlScript = window.location.href;

    if (strUrlScript.toString().indexOf('imoveis.') > -1) {
        strUrlScript = "/";
    }
    else {
        strUrlScript = "";
    }

    //    url = '/busca.aspx?e=' + estado + '&c=' + cidade + '&b=' + bairro + '&p=' + produto + '&t=' + tipologia + '&f=' + faixa + '&tb=R';
    url = 'http://imoveis.mrv.com.br/busca.aspx?e=' + estado + '&c=' + cidade + '&b=' + bairro + '&p=' + produto + '&t=' + tipologia + '&f=' + faixa + '&tb=R';

    window.location.href = url;
}

function NuvemDeTags() {

    if ($('.palavras_mais_buscadas')) {
        $('.palavras_mais_buscadas').html('');

        var arr = new Array();
        var cont = 0;
        var htmlStr = "";
        //(($("#linkEstadoRapida").attr('rel') == $(this).attr("rel")) ? 5 : $.randomBetween(1, 3))

        $("#listaEstadoRapida > li > a").each(function (i) {
            if ($(this).attr("rel") != "" && $(this).attr("rel") != "0" && $("#linkEstadoRapida").attr('rel') == $(this).attr("rel")) {
                htmlStr += "<a href=\"javascript:;\" onclick=\"return BuscaNuvenDeTags('" + $(this).attr("rel") + "',0,0,0,0,0);\"><span class='t" + 5 + "'> " + $(this).attr("title") + " </span></a>";
            }
        });

        $("#rapida #listaCidadeRapida > li > a").each(function (i) {
            if ($(this).attr("rel") != "" && $(this).attr("rel") != "0") {
                htmlStr += "<a href=\"javascript:;\" onclick=\"return BuscaNuvenDeTags('" + $("#linkEstadoRapida").attr("rel") + "','" + $(this).attr("rel") + "',0,0,0,0);\"><span class='t" + $.randomBetween(1, 4) + "'> " + $(this).attr("title") + " </span></a>";
            }
        });

        $("#rapida #listaBairroRapida > li > label").each(function (i) {
            if ($(this).find("input:checkbox").val() != "0" && $(this).text() != "") {
                htmlStr += "<a href=\"javascript:;\" onclick=\"return BuscaNuvenDeTags('" + $("#linkEstadoRapida").attr("rel") + "','" + $("#linkCidadeRapida").attr("rel") + "','" + $(this).find("input:checkbox").val() + "',0,0,0);\"><span class='t" + $.randomBetween(1, 4) + "'> " + $(this).text() + " </span></a>";

            }
        });

        $("#rapida #listaProdutoRapida > li > label").each(function (i) {
            if ($(this).find("input:checkbox").val() != "0" && $(this).text() != "") {
                htmlStr += "<a href=\"javascript:;\" onclick=\"return BuscaNuvenDeTags('" + $("#linkEstadoRapida").attr("rel") + "','" + $("#linkCidadeRapida").attr("rel") + "','" + $("#linkBairroRapida").attr("rel") + "','" + $(this).find("input:checkbox").val() + "',0,0);\"><span class='t" + $.randomBetween(1, 2) + "'> " + $(this).text() + " </span></a>";
            }
        });

        $("#rapida #listaTipologiaRapida > li > label").each(function (i) {
            if ($(this).find("input:checkbox").val() != "0" && $(this).text() != "") {
                htmlStr += "<a href=\"javascript:;\" onclick=\"return BuscaNuvenDeTags('" + $("#linkEstadoRapida").attr("rel") + "','" + $("#linkCidadeRapida").attr("rel") + "','" + $("#linkBairroRapida").attr("rel") + "','" + $("#linkProdutoRapida").attr("rel") + "','" + $(this).find("input:checkbox").val() + "',0);\"><span class='t" + $.randomBetween(1, 3) + "'> " + $(this).text() + " </span></a>";
            }
        });

        $("#rapida #listaFaixaRapida > li > label").each(function (i) {
            if ($(this).find("input:checkbox").val() != "0" && $(this).text() != "") {
                htmlStr += "<a href=\"javascript:;\" onclick=\"return BuscaNuvenDeTags('" + $("#linkEstadoRapida").attr("rel") + "','" + $("#linkCidadeRapida").attr("rel") + "','" + $("#linkBairroRapida").attr("rel") + "','" + $("#linkProdutoRapida").attr("rel") + "','" + $("#linkTipologiaRapida").attr("rel") + "','" + $(this).find("input:checkbox").val() + "');\"><span class='t" + $.randomBetween(1, 4) + "'> " + $(this).text() + " </span></a>";
            }
        });

        $('.palavras_mais_buscadas').html(htmlStr);
    }
}

function VerTodos(status, cidade) {
    var estado = readCookie('UF')

    if (document.getElementById("ctl00_cph_hlkLancamento")) {

        switch (status) {
            case 0:
                document.getElementById("ctl00_cph_hlkLancamento").className = "todos";
                document.getElementById("ctl00_cph_hlkLancamento").href = "/busca.aspx?e=" + estado + "&c=" + cidade;
                break;

            case 1:
                document.getElementById("ctl00_cph_hlkLancamento").className = "lancamento";
                document.getElementById("ctl00_cph_hlkLancamento").href = "/busca.aspx?e=" + estado + "&status=" + status + "&c=" + cidade;
                break;

            case 2:
                document.getElementById("ctl00_cph_hlkLancamento").className = "prontospramorar";
                document.getElementById("ctl00_cph_hlkLancamento").href = "/busca.aspx?e=" + estado + "&status=" + status + "&c=" + cidade;
                break;

            case 3:
                document.getElementById("ctl00_cph_hlkLancamento").className = "semiprontos";
                document.getElementById("ctl00_cph_hlkLancamento").href = "/busca.aspx?e=" + estado + "&status=" + status + "&c=" + cidade;
                break;

            case 12:
                document.getElementById("ctl00_cph_hlkLancamento").className = "pre_lancamento";
                document.getElementById("ctl00_cph_hlkLancamento").href = "/busca.aspx?e=" + estado + "&status=" + status + "&c=" + cidade;
                break;


        }
    }
}

function movewindow() {
    this.scroll(0, 0);
}


$(document).ready(function ($) {

    $('#ctl00_txtPalavraBusca').click(function () {
        if ($(this).val() == 'Buscar por Palavra chave')
            $(this).val('');
    });

    $('#ctl00_cph_txtBuscaRegulamento').click(function () {
        if ($(this).val() == 'Busca por regulamentos')
            $(this).val('');
    });

    $('.menu li').hover(function () {
        $('.menu li a').removeClass('active');
        menuOption = $(this).attr('class');
        //        $('.conteudo').removeClass('imoveisAVenda').removeClass('investidores').removeClass('institucional').removeClass('clientes');
        //        $('.conteudo').addClass(menuOption);
        $(this).find('a').addClass('active');
    })

});


function pop(url) {
    var pag = window.open(url, 'Pop', 'width=800,height=600');
    pag.focus();
}
var amp_foto_rec;
function ampliacaoFoto(amp_foto) {
    amp_foto_rec = amp_foto;
}

function maskNumeros(nome) {
    $("input[id*='" + nome + "']").bind("keyup blur focus", function (e) {
        e.preventDefault();
        var expre = /[A-Za-z\.\§\£\@\`\Ž\^\~\'\"\!\?\#\$\%\š\¬\_\+\=\.\,\:\;\<\>\|\°\ª\º\]\[\{\}\\ \)\(\*\&\-\/\\]/g;

        // REMOVE OS CARACTERES DA EXPRESSAO ACIMA
        if ($(this).val().match(expre))
            $(this).val($(this).val().replace(expre, ''));
    });
}

function Trim(str) { return str.replace(/^\s+|\s+$/g, ""); }
