﻿/// <reference path="jquery-vsdoc.js" />
/// <reference path="Tesla.Library.js" />

 
var Valida = new Object();


Valida.isValid = function (id, objErro)
{
    ///<summary>
    /// Efetua a validação dos objetos contendo as  classes "validaErro"
    /// e para validações específicas acrescentar as classes "validaEmail","validaDDD" ou "validaTelefone"
    ///</summary>

    var error = false;
    var localObjErro = null;
    var idCheck = '.validaErro';
    if (id != undefined && id != null)
        idCheck = id + " " + idCheck;

    $(idCheck).each(function (index)
    {
        var sucesso = true;
        var valor = '';
        if ($(this).is(":input[type='checkbox']"))
            sucesso = $(this).is(':checked');
        else //if ($(this).is(':input'))
        {
            valor = $.trim($(this).val());
            if (valor.length == 0)
                sucesso = false;
        }


        if ($(this).hasClass("validaEmail"))
            sucesso &= Valida.isEmail($(this).val());

        if ($(this).hasClass("validaDDD"))
            sucesso &= Valida.isDDD($(this).val());

        if ($(this).hasClass("validaTelefone"))
            sucesso &= Valida.isTelefone($(this).val());

        if (sucesso == false)
        {
            if (localObjErro == null)
                localObjErro = $(this);
            error = true;
            $(this).addClass("error");
        }
        else
            $(this).removeClass("error");
    });

    objErro.FirstObjError = localObjErro;
    objErro.Valid = !error;
    return !error;
}

Valida.isEmail = function (email)
{
    var ret = false;
    if (email != undefined && email != null && email.length > 0 && email.match('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$'))
    ret = true;
    return ret;
}

Valida.isDDD = function (ddd)
{
    if (ddd == "")
        return false;

    if (isNaN(ddd) || ddd.length != 2)
        return false;

    return true;
}

Valida.isTelefone = function (fone)
{
    if (fone == "")
        return false;
    if (isNaN(fone) || (fone.length != 7 && fone.length != 8))
        return false;

    return true;
}

Valida.isNumero = function (e)
{
    var tecla = (window.event) ? event.keyCode : e.which;
    if ((tecla > 47 && tecla < 58))
        return true;
    else
    {
        if ((tecla != 8) && (tecla != 13))
            return false;
        else
            return true;
    }
}

function GetCookie(name)
{
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}

function getCookieVal(offset)
{
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}
var dataEmpreendimentos = new Array();
var Compare = {
    init: function (num)
    {
        this.AtualizarBotoes(0);
        this.AtualizarMenu();
        this.Enviar();
        $("#botao-compare-detalhes").click(function ()
        {
            var data = $("div.botao-compare #idEmpreendimento").val();

            if ($(this).hasClass("selected"))
            {
                Compare.Remover(data);
            }
            else
            {
                Compare.Adicionar(data);
            }
            Compare.AtualizarBotoes(0);
        });
    },

    initCompareBusca: function ()
    {
        var idsEmpreendimentos = GetCookie('EsserCompare');
        if (idsEmpreendimentos != null && idsEmpreendimentos != "")
        {
            var url = "/busca/compare/" + idsEmpreendimentos;

            var listaEmpreendimentos = $.getJSON(url, function (data)
            {
                if (idsEmpreendimentos != null && idsEmpreendimentos.length > 0)
                {
                    idsEmpreendimentos = idsEmpreendimentos.split(",");
                    $("div.conteudo-compare a.bt-comparar-imoveis").fadeIn();
                    for (var c = 0; c <= 2; c++)
                    {
                        if (idsEmpreendimentos[c] != null)
                        {
                            $("div.conteudo-compare div.key-" + c).html("<span class='bairro'>" + data[c].Bairro + "</span><span>" + data[c].Nome + "</span>");
                            $("div.conteudo-compare div.key-" + c).removeClass("empty");
                        }
                        else
                        {
                            $("div.conteudo-compare div.key-" + c).html("");
                            $("div.conteudo-compare div.key-" + c).addClass("empty");
                        }
                    }
                }
            });
        }
        else
        {
            $("div.conteudo-compare a.bt-comparar-imoveis").fadeOut();
            for (c = 0; c <= 2; c++)
            {
                $("div.conteudo-compare div.key-" + c).html("");
                $("div.conteudo-compare div.key-" + c).addClass("empty");
            }
        }
    },

    Enviar: function (num)
    {
        if (num == 1)
            $("#divCompare").click();

        $("#divCompare").click(function ()
        {
            var idsCookies = Compare.PegarCookie();
            if (idsCookies != null)
            {
                $("#hndCookie").val(idsCookies.toString());
                $("#form-compare").submit();
            }
            else
            {
                return false;
            }
        });
    },

    PegarCookie: function ()
    {
        var idsEmpreendimentos = GetCookie('EsserCompare');
        if ((idsEmpreendimentos == null) || (idsEmpreendimentos == ""))
        {
            return null;
        }
        else
        {
            idsEmpreendimentos = idsEmpreendimentos.split(",");
            return idsEmpreendimentos;
        }
    },

    Adicionar: function (idEmpreendimento, numBusca)
    {
        if ($(".botao-compare-" + idEmpreendimento).hasClass("selected"))
        {
            Compare.Remover(idEmpreendimento);
            Compare.AtualizarBotoes(idEmpreendimento);
            this.initCompareBusca();
        }
        else
        {
            var idsCookies = this.PegarCookie();
            if (idsCookies == null) { idsCookies = []; }
            dataEmpreendimentos[idsCookies.length - 1] = idEmpreendimento + "," + "teste";
            if (idsCookies.length >= 3)
            {
                alert("Você já tem 3 imóveis selecionados para fazer a comparação.")
                return;
            }
            if (jQuery.inArray(idEmpreendimento, idsCookies) == -1)
            {
                idsCookies.push(idEmpreendimento);
            }
            document.cookie = "EsserCompare" + "=" + idsCookies.join(",") + ";path=/";
            if (numBusca == 1)
            {
                this.AtualizarBotoes(idEmpreendimento);
                this.initCompareBusca();
            }
            else
                this.AtualizarBotoes(0);
            this.AtualizarMenu();
        }
    },

    Remover: function (idEmpreendimento)
    {
        var idsCookies = this.PegarCookie();
        this.Limpar();
        if (idsCookies == null) { return null; }
        for (var c = 0; c < idsCookies.length; c++)
        {
            if (idsCookies[c] == idEmpreendimento) { idsCookies.splice(c, 1); }
        }
        document.cookie = "EsserCompare" + "=" + idsCookies.join(",") + ";path=/";
        this.AtualizarMenu();
        return idsCookies;
    },

    Limpar: function ()
    {
        document.cookie = "EsserCompare" + "=" + null + ";path=/";
    },

    AtualizarBotoes: function (idEmpreendimentoBusca)
    {
        var idsCookies = this.PegarCookie();
        if (idsCookies == null) { idsCookies = []; }

        $.each($(".botao-compare"), function ()
        {
            if (idEmpreendimentoBusca != 0)
                var data = $("div.botao-compare #idEmpreendimento-" + idEmpreendimentoBusca).val();
            else
                var data = $("div.botao-compare #idEmpreendimento").val();
            if (jQuery.inArray(String(data), idsCookies) == -1)
            {
                $(".botao-compare-" + data).removeClass("selected");
                return false;
            }
            else
            {
                $(".botao-compare-" + data).addClass("selected");
                return false;
            }
        });
    },
    AtualizarBotoesBusca: function ()
    {
        var idsEmpreendimentos = GetCookie('EsserCompare');
        if (idsEmpreendimentos != null && idsEmpreendimentos.length > 0)
        {
            idsEmpreendimentos = idsEmpreendimentos.split(",");
            for (var c = 0; c <= 2; c++)
            {
                if (idsEmpreendimentos[c] != null)
                {
                    $.each($(".botao-compare"), function ()
                    {
                        var data = $("div.botao-compare #idEmpreendimento-" + idsEmpreendimentos[c]).val();
                        if (jQuery.inArray(String(data), idsEmpreendimentos) == -1)
                        {
                            $(".botao-compare-" + data).removeClass("selected");
                            return false;
                        }
                        else
                        {
                            $(".botao-compare-" + data).addClass("selected");
                            return false;
                        }
                    });
                }
            }
        }
    },
    AtualizarMenu: function ()
    {
        var idsCookies = this.PegarCookie();

        if (idsCookies != null)
        {
            $("#divCompare span").html(idsCookies.length);
            $("#divCompare").removeClass("disabled");
            $("#divCompare").click(function () { Compare.Enviar(); });
        } else
        {
            $("#divCompare").addClass("disabled");
            $("#divCompare span").html("0");
            $("#divCompare").click(function () { Compare.Enviar(); });
        }
    }
}

var AtendimentoOnline = {
    init: function ()
    {
        $("#pop-atendimento-online").hide();
    },
    initTime: function ()
    {
        var cookieCorretorOnline = GetCookie('EsserChatOnline');
        if (cookieCorretorOnline == null)
        {
            window.setTimeout(function ()
            {
                var exdate = new Date();
                exdate.setDate(exdate.getDate() + (365 * 20));
                document.cookie = "EsserChatOnline" + "=" + 'Corretor Online;expires=' + exdate.toUTCString() + ";path=/";
                TagsGA.posicao = 'timer';
                AtendimentoOnline.open();
            }, 180000);
        }
    },
    open: function ()
    {
        jQuery("#pop-atendimento-online").dialog({
            draggable: false,
            resizable: false,
            dialogClass:'dialog-default pop-atendimento-online',
            width: '512',
            height: '522',
            modal: true
        });
        $("#btnAtendimento_online_enviar").show();
    }
}

var AtendimentoEmail = {
    init: function ()
    {
        $("#pop-atendimento-email").hide();
    },
    open: function ()
    {
        $("#pop-atendimento-email").dialog({
            draggable: false,
            resizable: false,
            dialogClass: 'dialog-default',
            width: '525',
            height: '590',
            modal: true
        });
        $("div.error-atendimento-email").hide();
        $("div.confirm-atendimento-email").hide();
        $("div.wait-atendimento-email").hide();
        $("#btnAtendimento_email_enviar").show();
    }
}

var AtendimentoTelefone = {
    init: function ()
    {
        $("#pop-atendimento-telefone").hide();
    },
    open: function ()
    {
        $("#pop-atendimento-telefone").dialog({
            draggable: false,
            resizable: false,
            dialogClass: 'dialog-default',
            width: '525',
            height: '590',
            modal: true
        });
        $("div.error-atendimento-telefone").hide();
        $("div.confirm-atendimento-telefone").hide();
        $("div.wait-atendimento-telefone").hide();
        $("#btnAtendimento_telefone_enviar").show();
    }
}


    var CadastroTemplate =
    {
        "Id": -1,
        "TipoCadastro": 0,
        "Nome": '',
        "TelefoneComercial": '',
        "TelefoneResidencial": '',
        "Celular": '',
        "Email": '',
        "Endereco": '',
        "Bairro": '',
        "CEP": '',
        "Cidade": '',
        "Estado": '',
        "TipoImovel": '',
        "FaixaMetragem": '',
        "QtdadeDormitorio": '',
        "TipoContatoId": '',
        "AceitaContato": '',
        "Interesse": '',
        "Empreendimento": '',
        "Mensagem": '',
        "Remetente": '',
        "EmailRemetente": '',
        "Destinatario": '',
        "EmailDestinatario": '',
        "Campanha": '',
        "CampanhaOrigem": '',
        clone: function (o)
        {
            function c(o)
            {
                for (var i in o)
                {
                    this[i] = o[i];
                }
            }
            return new c(o);
        },
        create: function (option)
        {
            this.reset();
            if (option != undefined && option != null)
            {
                if (option.Id != undefined)
                    this.Id = option.Id;
                if (option.Nome != undefined)
                    this.Nome = option.Nome;
                if (option.TelefoneComercial != undefined)
                    this.TelefoneComercial = option.TelefoneComercial;
                if (option.TelefoneResidencial != undefined)
                    this.TelefoneResidencial = option.TelefoneResidencial;
                if (option.Celular != undefined)
                    this.Celular = option.Celular;
                if (option.Email != undefined)
                    this.Email = option.Email;
                if (option.Endereco != undefined)
                    this.Endereco = option.Endereco;
                if (option.Bairro != undefined)
                    this.Bairro = option.Bairro;
                if (option.CEP != undefined)
                    this.CEP = option.CEP;
                if (option.Cidade != undefined)
                    this.Cidade = option.Cidade;
                if (option.Estado != undefined)
                    this.Estado = option.Estado;
                if (option.TipoImovel != undefined)
                    this.TipoImovel = option.TipoImovel;
                if (option.FaixaMetragem != undefined)
                    this.FaixaMetragem = option.FaixaMetragem;
                if (option.QtdadeDormitorio != undefined)
                    this.QtdadeDormitorio = option.QtdadeDormitorio;
                if (option.TipoContatoId != undefined)
                    this.TipoContatoId = option.TipoContatoId;
                if (option.AceitaContato != undefined)
                    this.AceitaContato = option.AceitaContato;
                if (option.Interesse != undefined)
                    this.Interesse = option.Interesse;
                if (option.Empreendimento != undefined)
                    this.Empreendimento = option.Empreendimento;
                if (option.Mensagem != undefined)
                    this.Mensagem = option.Mensagem;
                if (option.Remetente != undefined)
                    this.Remetente = option.Remetente;
                if (option.EmailRemetente != undefined)
                    this.EmailRemetente = option.EmailRemetente;
                if (option.Destinatario != undefined)
                    this.Destinatario = option.Destinatario;
                if (option.EmailDestinatario != undefined)
                    this.EmailDestinatario = option.EmailDestinatario;
                if (option.Campanha != undefined)
                    this.Campanha = option.Campanha;
                if (option.CampanhaOrigem != undefined)
                    this.CampanhaOrigem = option.CampanhaOrigem;
            }
            return this.clone(this);
        },
        reset: function ()
        {
            this.Id = -1;
            this.Nome = '';
            this.TelefoneComercial = '';
            this.TelefoneResidencial = '';
            this.Celular = '';
            this.Email = '';
            this.Endereco = '';
            this.Bairro = '';
            this.CEP = '';
            this.Cidade = '';
            this.Estado = '';
            this.TipoImovel = '';
            this.FaixaMetragem = '';
            this.QtdadeDormitorio = '';
            this.TipoContatoId = 0;
            this.AceitaContato = '';
            this.Interesse = '';
            this.Empreendimento = '';
            this.Mensagem = '';
            this.Remetente = '';
            this.EmailRemetente = '';
            this.Destinatario = '';
            this.EmailDestinatario = '';
            this.Campanha = '';
            this.CampanhaOrigem = '';
        }
    }

function EnviaCadastro(option, callbackCad)
{
    var cadastro = JSON.ToString(CadastroTemplate.create(option));
    var urlContato = "/contato/";
    
    $.ajax({
        cache: false,
        dataType: 'json',
        type: 'POST',        
        data: cadastro,
        contentType: 'application/json; charset=utf-8',
        url: urlContato,
        success: callbackCad,
    });
}

function EnviaCadastroAtendimento(option, callbackCad)
{
    var cadastro = JSON.ToString(CadastroTemplate.create(option));
    var urlContato = "/contato/";

    $.ajax({
        cache: false,
        dataType: 'json',
        type: 'POST',
        data: cadastro,
        contentType: 'application/json; charset=utf-8',
        url: urlContato,
        success: callbackCad,
        async: false
    });
}

var Busca =
{
    cache: {},
    lastXhr: {},
    init: function (id)
    {
        $(id).autocomplete({
            minLength: 2,
            source: function (request, response)
            {
                var term = request.term;
                if (term in Busca.cache)
                {
                    response(Busca.cache[term]);
                    return;
                }
                var url = "/busca/auto/" + term;

                Busca.lastXhr = $.getJSON(url, request,
                    function (data, status, xhr)
                    {
                        Busca.cache[term] = data;
                        if (xhr === Busca.lastXhr)
                        {
                            response(data);
                        }
                    });
            }
        });
    }
}

function opitionGrup(inputValue, campo){
    campo.find('.opcoes ul li').click(function (){
        var valorOption = $(this).text();
        $(inputValue).val(valorOption);
        campo.find('p').text(valorOption);
        campo.find('.opcoes').hide();
        campo.find('button').removeClass('ativo');
        campo.find('p').removeClass('ativo');
    });
   
    campo.find('.exibeCampo').click(function () {
        if ($(this).hasClass('ativo')){
            campo.find('button').removeClass('ativo');
            campo.find('p').removeClass('ativo');
            campo.find('.opcoes').hide();
        } else{
            campo.find('button').addClass('ativo');
            campo.find('p').addClass('ativo');
            campo.find('.opcoes').show();
        }
    });
};

function clickPage(e) {
    var ev = e || window.event;
    var target = ev.target || ev.srcElement, title = target.title;
    if (target.className != "selecione" && $(target).parents('.selecione').size() == 0) {
        if ($('.exibeCampo').hasClass('ativo')) {
            $('.selecione').find('button').removeClass('ativo');
            $('.selecione').find('p').removeClass('ativo');
            $('.selecione').find('.opcoes').hide();
        };
    } else {
        if (target.className == "selecione") {
            $(target).addClass('temp_select');
        } else {
            $(target).parents('.selecione').addClass('temp_select');
        }

        $('.selecione:not(.temp_select)').find('button').removeClass('ativo');
        $('.selecione:not(.temp_select)').find('p').removeClass('ativo');
        $('.selecione:not(.temp_select)').find('.opcoes').hide();

        $('.temp_select').removeClass('temp_select');
    }
}

document.onclick = clickPage;



function CorretorOnlineFixo() {
    var right = parseInt(($(window).width() - $('#container').width()) / 2) - 150;
    $('#corretor_online_right').css('right', right + 'px');
    $('#corretor_online_right').css('visibility', 'visible');
}

jQuery(document).ready(function ()
{
    Busca.init('#busca');
    AtendimentoOnline.init();
    AtendimentoOnline.initTime();
    AtendimentoEmail.init();
    AtendimentoTelefone.init();
    Compare.init();
    CorretorOnlineFixo();

    opitionGrup('#tipoTelefoneAtendimentoEmail', $('.campoTipoTelefoneAtendimentoEmail'));
    opitionGrup('#selEstado', $('.campoEstado'));
    opitionGrup('#selTipoImovel', $('.campoTipoTel'));
    opitionGrup('#selFaixaMetragem', $('.campoFaixaMetragem'));
    opitionGrup('#qdtDormitorios', $('.campoQdtDormitorios'));

    opitionGrup('#minRoom', $('.campoDormitorios'));
    opitionGrup('#minSuite', $('.campoSuite'));
    opitionGrup('#minGarage', $('.campoGaragem'));
    opitionGrup('#status', $('.campoStatusGroup'));

});

var Origem =
{
    Campanha: '',
    CampanhaOrigem: ''
}

$(window).resize(function () {
    CorretorOnlineFixo();
});



