a.filter('numero', function () {
    return function (input) {
        var str = input + '';
        str = str.replace(/\D/g, '');
        return str;
    };
});

a.directive('newsLetter',function(){
    return {
        restrict: 'AE',
        scope: { modelo: '@', componentes:'=?'}, 
        template:'<div ng-include="url"></div>',
        controller:function($scope, $timeout, $element, $http)
        {
            $scope.urlabsoluta=window.urlabsoluta;
            $scope.url=window.urlabsoluta+"componentes/newsletter/newsletter_"+$scope.modelo+"/newsletter.html";
            $scope.new={email:''};
            $scope.enviar = function(news)
            {
                $http.post($scope.urlabsoluta+'atendimentos/newsletter', news).then(function(r){
                    $scope.new={email:''};
                });
            }
        }
    }
});



a.directive('usoDeCookie',function(){
    return {
      restrict: "AE",
      // scope: { modelo: '@', componentes:'=?'},
      template:
        '<div class="cookie" ng-if="!disable">Usamos cookies para permitir que o nosso website funcione corretamente, para personalizar o conteúdo e anúncios, para proporcionar funcionalidades das redes sociais e para analisar o nosso tráfego. Também partilhamos informação com os nossos parceiros das redes sociais, de publicidade e de analítica sobre o seu uso do nosso website. <a ng-click="setCookie()">Aceitar cookies</a></div><style>.cookie{position:fixed;bottom:0px;left:0px;width:100%;z-index: 99999999;background: white;padding: 15px 40px;font-size: 15px;}</style>',
      controller: function($scope) {
        function setCookie(name, value, days) {
          var expires = "";
          if (days) {
            var date = new Date();
            date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
            expires = "; expires=" + date.toUTCString();
          }
          document.cookie = name + "=" + (value || "") + expires + "; path=/";
        }
        function getCookie(name) {
          var cookies = document.cookie.split(";");
          for (i in cookies) {
            var c = cookies[i].split("=");
            if (c[0].trim() === name) return c[1].trim();
          }
          return null;
        }

        if (getCookie("usodecookie")) $scope.disable = true;

        $scope.setCookie = function() {
          $scope.disable = true;
          setCookie("usodecookie", true, 366);
        };
      }
    };
});


/* INICIO DIRETIVA THUMB IMOVEL */
a.directive('thumbImovel',function(){
    return {
        restrict: 'AE',
        scope: { modelo: '=?', imovel: '=?', idReal: '=?', referencia: '=?', filtro: '@?', semimagem: '=?', componentes: '=?', componente:'=?', atualiza:'=?'},          
        template:'<div ng-include="url"></div>',
        controller:function($scope, $timeout, $element, $compile, $rootScope, utils)
        {
            $scope.favoritos=$rootScope.favoritos;
            $scope.adicionaFavorito =$rootScope.adicionaFavorito;
            $scope.moedas = {
                'USD': '$', // US Dollar
                'EUR': '€', // Euro
                'GBP': '£', // British Pound Sterling
                'INR': '₹', // Indian Rupee
                'JPY': '¥', // Japanese Yen
                'R$' : 'R$'
            };

            $scope.exibeVideo = false;

            $scope.playVideo = function(){
                
                var makeIframe = "<iframe ";
                makeIframe += "src='https://www.youtube.com/embed/"+$scope.imovel.midia.videos[0]+"?rel=0&autoplay=1' ";
                makeIframe += "frameborder='0' allow='autoplay; encrypted-media' allowfullscreen='allowfullscreen' mozallowfullscreen='mozallowfullscreen' msallowfullscreen='msallowfullscreen' oallowfullscreen='oallowfullscreen' webkitallowfullscreen='webkitallowfullscreen' style='width: 100%; height: 170px'> </iframe>";

                var content = $compile(makeIframe)($scope);
                $element[0].querySelector('.area-video').append(content[0]);
                
                $scope.exibeVideo = true;
            }

            $timeout(function() {
                $scope.url = window.urlabsoluta+'componentes/thumb_imovel/thumb_imovel'+$scope.modelo+'.html';   
            }, 1);   
            
            $scope.abreImovel = function(imovel, href)
            {
                var url = window.trataImovel(imovel).url;
                if(!href) window.open(url, '_self');
                return url;
            }

            $scope.urlcustomizar = window.urlcustomizar;


        }
    }
});


/*a.directive('thumbImovel',function(){
    return {
        restrict: 'AE',
        transclude: true,
        scope: { modelo: '=?', imovel: '=?', idReal: '=?', referencia: '=?'},          
        templateUrl: window.urlabsoluta+'componentes/thumb_imovel/thumb_imovel1.html',
        controller:function($scope, $timeout)
        {   
            $scope.moedas = {
                'USD': '$', // US Dollar
                'EUR': '€', // Euro
                'GBP': '£', // British Pound Sterling
                'INR': '₹', // Indian Rupee
                'JPY': '¥', // Japanese Yen
                'R$' : 'R$'
            };

            // $timeout(function() {
            //     $scope.url = window.urlabsoluta+'componentes/thumb_imovel/thumb_imovel'+$scope.modelo+'.html';   
            // }, 1);   

            // $(window).load(function() {
            //     $scope.url = window.urlabsoluta+'componentes/thumb_imovel/thumb_imovel'+$scope.modelo+'.html';   
            //     $scope.$digest();   
            // });     

        }
    }
});
*/

/* FIM DIRETIVA THUMB IMOVEL */

/* INICIO DIRETIVA THUMB LANÇAMENTO */

a.directive('thumbLancamento',function(){
    return {
        restrict: 'AE',
        scope: { modelo: '@?', lancamento: '=?', idReal: '=?', semimagem: '=?'},          
        template:'<div ng-include="url"></div>',
        controller:function($scope, $timeout)
        {   
            // $timeout(function() {
            //     $scope.url = window.urlabsoluta+'componentes/thumb_lancamento/thumb_lancamento'+$scope.modelo+'.html'; 
            // }, 400);   

            // $(window).load(function() {
                setTimeout(function(){
                    $scope.url = window.urlabsoluta+'componentes/thumb_lancamento/thumb_lancamento'+$scope.modelo+'.html'; 
                    $scope.$digest();
                },200);
            // }); 

            $scope.urlcustomizar = window.urlcustomizar;
        }
    }
});

/* FIM DIRETIVA THUMB LANÇAMENTO */

/* INICIO DIRETIVA INFO IMOVEL */

a.directive('infoImovel',function(){
    return {
        restrict: 'AE',
        scope: { modelo: '=?', key: '=?', imovel: '=?', infoAberta: "=?", mostraLink: "=?", mostraiptu:"=?", componente:'=?'},          
        template:'<div ng-include="url"></div>',
        controller:function($scope, $timeout, $http, vcRecaptchaService)
        {   

            $scope.moedas = {
                'USD': '$', // US Dollar
                'EUR': '€', // Euro
                'GBP': '£', // British Pound Sterling
                'INR': '₹', // Indian Rupee
                'JPY': '¥', // Japanese Yen
                'R$' : 'R$'
            };
            
            $scope.atendimento = {};
            // $timeout(function() {               
            //     $scope.url = window.urlabsoluta+'componentes/info_imovel/info_imovel'+$scope.modelo+'.html';   
            // }, 600); 

            $(window).load(function() {
                
                if($scope.modelo) $scope.url = window.urlabsoluta+'componentes/info_imovel/info_imovel'+$scope.modelo+'.html';
                $scope.$digest();   
            }); 

            $scope.novoAtendimento = function(){

                $scope.atendimento.imovel = $scope.imovel;
                $scope.atendimento.url=document.URL;
                $scope.ativacao = true;

                $http.post('atendimentos/novoApi',{cliente:$scope.atendimento,busca:window.localStorage.getItem("buscaJson")}).then(function(a)
                {
                    if(!a.data.ok)
                    {
                        $.post('https://turbo.gestaoreal.com.br/exportacao/NovoAtendimento', $scope.atendimento).then(function(a)
                        {
                            $scope.finaliza(a.atendimento.ok);
                            $scope.$digest();
                            $scope.ativacao = false;
                        }); 
                    }else{
                        $scope.finaliza(a.data.ok);
                        $scope.ativacao = false;
                    }                                
                });
            }

            $scope.setResponse = function (response) {
                $scope.response = response;
            };
        
            $scope.setWidgetId = function (widgetId) {
                $scope.widgetId = widgetId;
            };
        
            $scope.cbExpiration = function() {
                vcRecaptchaService.reload($scope.widgetId);
                $scope.response = null;
            };
        
            $scope.submit = function (tipo) {
                var valid;
        
                $http.post(window.urlabsoluta+'formularios/validarRecaptcha', {response: $scope.response}).then(function(r){
                    valid = r.data;
                    
                    if (valid === 'true' || valid === true) {
                        $scope.novoAtendimento(tipo); 
                    } else {
                        swal({   title: "Erro!", confirmButtonColor:"#DF1F31",  text: "Captcha inválido! Por favor, tente novamente.",   type: "error",   confirmButtonText: "Voltar" });
                        // In case of a failed validation you need to reload the captcha
                        // because each response can be checked just once
                        vcRecaptchaService.reload($scope.widgetId);
                    }
                });        
            };
            
            $scope.finaliza = function(ok)
            {
                if(ok == 1){
                    swal({   title: "Enviado com sucesso!", confirmButtonColor:"#FF4A34", text: "Entraremos em contato assim que possível!", type: "success",   confirmButtonText: "Ok" });
                    $scope.areamaisinfo=false; 
                    $scope.atendimento={nome:'', email:'', texto:'', numero:''};

                } else {
                    swal({   title: "Erro!", confirmButtonColor:"#FF4A34", text: "Não conseguimos enviar sua mensagem, por favor, tente novamente!",   type: "error",   confirmButtonText: "Voltar" });
                }

            }
        }
    }
});

/* FIM DIRETIVA INFO IMOVEL */

/* INICIO DIRETIVA CORRETOR IMOVEL */

a.directive('corretorImovel',function(){
    return {
        restrict: 'AE',
        scope: { modelo: '=?', objCorretor: '=?'},          
        template:'<div ng-include="url"></div>',
        controller:function($scope, $timeout)
        {   
            // $scope.modelo=1;
            // $timeout(function() {
            //     $scope.url = window.urlabsoluta+'componentes/corretor_imovel/corretor_imovel'+$scope.modelo+'.html';   
            // }, 600);  

            $(window).load(function() {
                $scope.url = window.urlabsoluta+'componentes/corretor_imovel/corretor_imovel'+$scope.modelo+'.html';
                $scope.$digest();   
            });  
        }
    }
});

/* FIM DIRETIVA CORRETOR IMOVEL */

/* INICIO DIRETIVA CORRETOR ONLINE */

a.directive('corretor',function(){
    return {
        restrict: 'AE',
        transclude: true,
        scope: { link: '=?', modelo:"=?", texto:"=?"},  
        templateUrl: window.urlabsoluta+'componentes/corretor_online/corretor_online.html',
  
        controller:function($scope)
        {

            function PopupCenter(url, title, w, h) {
                // Fixes dual-screen position                         Most browsers      Firefox
                var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
                var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

                var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
                var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

                var left = ((width / 2) - (w / 2)) + dualScreenLeft;
                var top = ((height / 2) - (h / 2)) + dualScreenTop;
                var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

                // Puts focus on the newWindow
                if (window.focus) {
                    newWindow.focus();
                }
            }
            

            $( window ).scroll(function() {
                if ($(this).scrollTop()<66) { 
                    $(".chat1").css("top", 70);
                } else {                
                    $(".chat1").css("top", 0);
                }
            });

            $scope.abrirCorretor = function(){
                PopupCenter($scope.link,'xtf','400','430');
                /*window.open($scope.link,'_blank');*/
            }

        }
    }
});

a.directive('corretorMobile',function(){
    return {
        restrict: 'AE',
        transclude: true,
        scope: { link: '=?', redes: '=?', texto:"=?", modelo: '=?', versao: '=?', whatsapp:'=?', atendimento:'=?', id:'@', imovel: '=?'},
        template:'<div ng-include="url"></div>',  
        controller:function($scope)
        {
            $scope.urlabsoluta = window.urlabsoluta;
            $scope.styleCSS = $scope.urlabsoluta+"css/producao/corretor_online_mobile1.min.css?id="+$scope.versao;

            $scope.linkMobileAll = true;

            $scope.url =  $scope.urlabsoluta+'componentes/corretor_online_mobile/corretor_online_mobile_'+$scope.modelo+'/corretor_online_mobile.html';

            function PopupCenter(url, title, w, h) {
                // Fixes dual-screen position                         Most browsers      Firefox
                var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
                var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

                var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
                var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

                var left = ((width / 2) - (w / 2)) + dualScreenLeft;
                var top = ((height / 2) - (h / 2)) + dualScreenTop;
                var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

                // Puts focus on the newWindow
                if (window.focus) {
                    newWindow.focus();
                }
            }

            $scope.abrirCorretor = function(){
                PopupCenter($scope.link,'xtf','400','430');
            }

            $scope.fecharWhats = function() {
                $scope.abrirAtendimento = false;
            }

            $scope.abrirWhats = function() {
                $scope.pagina = window.location.pathname.split("/")[1];


                if ($scope.pagina == "comprar" || $scope.pagina == "alugar" || $scope.pagina == "permuta")
                {
                    $scope.whatsNome        = $scope.whatsapp.busca.nome;
                    $scope.whatsNumero      = $scope.whatsapp.busca.numero;
                    $scope.whatsTitulo      = $scope.whatsapp.busca.titulo;
                    $scope.whatsAtendimento = $scope.whatsapp.busca.atendimento;
                }
                else if ($scope.pagina == "imovel")
                {
                    $scope.whatsNome        = $scope.whatsapp.imovel.nome;
                    $scope.whatsNumero      = $scope.whatsapp.imovel.numero;
                    $scope.whatsTitulo      = $scope.whatsapp.imovel.titulo;
                    $scope.whatsAtendimento = $scope.whatsapp.imovel.atendimento;
                }
                else if ($scope.pagina == "lancamento-imobiliario")
                {
                    $scope.whatsNome        = $scope.whatsapp.lancamento.nome;
                    $scope.whatsNumero      = $scope.whatsapp.lancamento.numero;
                    $scope.whatsTitulo      = $scope.whatsapp.lancamento.titulo;
                    $scope.whatsAtendimento = $scope.whatsapp.lancamento.atendimento;
                }
                else
                {
                    $scope.whatsNome        = $scope.whatsapp.home.nome;
                    $scope.whatsNumero      = $scope.whatsapp.home.numero;
                    $scope.whatsTitulo      = $scope.whatsapp.home.titulo;
                    $scope.whatsAtendimento = $scope.whatsapp.home.atendimento;
                }

                if($scope.atendimento) {
                    $scope.abrirAtendimento = true;
                } else {
                    if ($scope.imovel){
                        window.open('https://api.whatsapp.com/send?phone=55'+$scope.whatsNumero+'&text=Olá%20'+$scope.whatsNome+',%20pode%20me%20ajudar%20com%20o%20imóvel%20'+$scope.imovel.sigla+'?%20','_blank');
                    }else{
                        window.open('https://api.whatsapp.com/send?phone=55'+$scope.whatsNumero+'&text=Olá%20'+$scope.whatsNome+',%20pode%20me%20ajudar?%20','_blank');
                    }
                }
            }

            $scope.montaEspacoLink = function()
            {        
                setTimeout(function(){
                    var barra = $(".barra-corretor-online-mobile").width() + 5;
                    var ref = $(".barra-corretor-online-mobile__redes").width() + $(".barra-corretor-online-mobile__corretoronline").width();

                    if(barra < ref)
                    {
                        $scope.linkMobile = true;
                        $scope.linkMobileAll = false;
                    }
                    else
                    {
                        $scope.linkMobile = false;
                        $scope.linkMobileAll = true;
                    }

                    $(".barra-corretor-online-mobile").css("opacity","1");

                    $scope.$digest();
                },1000);
            }

            $scope.montaEspacoLink();

            $scope.abrirLinkMobileAll = function()
            {
                $scope.linkMobileAll = !$scope.linkMobileAll;
            }
        }
    }
});

/* FIM DIRETIVA CORRETOR ONLINE */

/* INICIO DIRETIVA ÁREA  DO CLIENTE */

a.directive('areaCliente',function(){
    return {
        restrict: 'AE',
        transclude: true,
        scope: { link: '=?', modelo:"=?", texto:"=?", locgestao:"=?"},  
        templateUrl: window.urlabsoluta+'componentes/area_cliente/area_cliente.html',
  
        controller:function($scope, $sce)
        {   
            $scope.areacliente = false;
            $scope.link = false;
            $scope.$watch("link",function(a,b){
                if($scope.link) $scope.link = $sce.trustAsResourceUrl($scope.link);
            });

            $scope.fechaAreaCliente = function(){
                $scope.areacliente = false;
            }

            $scope.abreArea = function(){
                if ($scope.locgestao && $scope.locgestao == true){
                    $scope.areacliente = true;
                }else{
                    window.location.href = $scope.link;
                }
            }
        }
    }
});

/* FIM DIRETIVA ÁREA DO CLIENTE */

/* INÍCIO DIRETIVA CHAT MESSENGER */

a.directive('chatMessenger', function(){
    return{
        restrict: 'AE',

        scope: {
            pageId: '=?',
            cor: '=?',
            txtUserLogged: '=?',
            txtUserNotLogged: '=?', 
            modoExibicao: '=?',
            delay: '=?',
            home: '=?',
            busca: '=?',
            imovel: '=?',
            lancamento: '=?'
        },

        templateUrl: window.urlabsoluta + 'componentes/chat_messenger/chat-messenger.html',
        
        controller:function($scope){
                                    
            $scope.urlabsoluta = window.urlabsoluta;
            
            window.fbAsyncInit = function() {
                FB.init({
                    // appId            : '339952119918654',
                    autoLogAppEvents : true,
                    xfbml            : true,
                    version          : 'v3.2'
                });
            };
            
            (function(d, s, id) {

                var js, fjs = d.getElementsByTagName(s)[0];
        
                if (d.getElementById(id)) return;
        
                js = d.createElement(s); js.id = id;
        
                // js.src = 'https://connect.facebook.net/pt_BR/sdk/xfbml.customerchat.js#xfbml=1&version=v2.12&autoLogAppEvents=1';

                js.src = 'https://connect.facebook.net/pt_BR/sdk/xfbml.customerchat.js';
        
                fjs.parentNode.insertBefore(js, fjs);
        
            }(document, 'script', 'facebook-jssdk'));
            
        }
    }
});

/* FIM DIRETIVA CHAT MESSENGER */

/* INÍCIO DIRETIVA POPUP */

a.directive('popup', function(){
    return{
        restrict: 'AE',
        templateUrl: window.urlabsoluta + 'componentes/popup/popup.html',
        scope:{
            url: '=?',
            imagem: '=?',
            idimob: '=?',
            fecha: '=?'
        },
        controller:function($scope)
        {
            $scope.config=window.config;
        }
    }
});

/* FIM DIRETIVA POPUP */


a.directive('btnFavoritos',function(){
    return {
        restrict: 'AE',
        templateUrl: window.urlabsoluta+'componentes/favoritos/favoritos.html'
    }
});

/* INICIO DIRETIVA WHATSAPP */

a.directive('whats',function(){
    return {
        restrict: 'AE',
        transclude: true,
        scope: { nome: '=?', numero:'=?', atendimento:'=?', titulo:'=?', imovel:'=?', lancamento:'=?', unidade : '@?', altura:'@?', versaoSweet:'='},  
        templateUrl: window.urlabsoluta+'componentes/whatsapp/whatsapp.html',

        controller:function($scope, $element)
        {
            

            $scope.fechar = function() {
                $scope.abrirAtendimento = false;
            }

            $scope.abrir = function() {
                if($scope.atendimento) {
                    $scope.abrirAtendimento = true;
                } else {
                    if ($scope.imovel){
                        window.open('https://api.whatsapp.com/send?phone=55'+$scope.numero+'&text=Olá%20'+$scope.nome+',%20pode%20me%20ajudar%20com%20o%20imóvel%20'+$scope.imovel.sigla+'?%20','_blank');
                    }else if ($scope.lancamento){
                        window.open('https://api.whatsapp.com/send?phone=55'+$scope.numero+'&text=Olá%20'+$scope.nome+',%20pode%20me%20ajudar%20com%20o%20lançamento%20'+$scope.lancamento.nome+'?%20','_blank');
                    }else{
                        window.open('https://api.whatsapp.com/send?phone=55'+$scope.numero+'&text=Olá%20'+$scope.nome+',%20pode%20me%20ajudar?%20','_blank');
                    }
                }
            }


            var x = 0;

            $('.botao-whats').mouseover(function(){
                $('.botao-whats').removeClass('whatsAberto');
            });

            setInterval(function(){
            if(x == 1){
                $('.botao-whats').removeClass('whatsAberto');
                x = 0;
                return;
            }

            if(x==0){
                $('.botao-whats').addClass('whatsAberto');         
                x = 1;
            }
        
            }, 5000);
        }
    }
});

/* FIM DIRETIVA WHATSAPP */ 
  
/* INICIO DIRETIVA ATENDIMENTO */
  
  a.directive('atendimentoGestao', function($http){
    return{
      restrict: 'AE',
      transclude: true,
      scope: { nome: '=?', numero:'=?', email:'@?', mensagem:'@?', imovel:'=?', lancamento:'=?', fechar:'=', unidade:'=?', versaoSweet:'='},  
      templateUrl: window.urlabsoluta+'componentes/form_atendimento/form_atendimento.html',
      controller:function($scope, $http){

        window.urlApi="https://turbo.gestaoreal.com.br/";
        
        $scope.atend = {};

        $scope.novoAtendimento = function() {  

            $scope.ativacao = true;
            
            var textoImovel="";
            if($scope.imovel) {
                $scope.atend.midia= $scope.imovel.imobiliaria.nome;
                $scope.atend.imovel= $scope.imovel;  
                textoImovel=" com o imóvel "+$scope.imovel.sigla;          
            } else if($scope.lancamento){
                $scope.atend.midia= $scope.lancamento.imobiliaria.nome;
                $scope.atend.lancamento= $scope.lancamento;  
                textoImovel=" com o lançamento "+$scope.lancamento.nome;          
            }
            $scope.escolheSweet = {
                sw1: function() {
                    swal({   title: "Atendimento enviado com sucesso!", confirmButtonColor:"#323232", text: "Clique no botão abaixo para enviar uma mensagem pelo Whatsapp", type: "success",   confirmButtonText: "Ok" },
                        function() {
                            window.open('https://api.whatsapp.com/send?phone=55'+$scope.numero+'&text=Olá%20'+$scope.nome+',%20pode%20me%20ajudar'+textoImovel+'?%20','_blank');
                    });
                },
                sw2: function() {
                    swal({   title: "Atendimento enviado com sucesso!", confirmButtonColor:"#323232", text: "Clique no botão abaixo para enviar uma mensagem pelo Whatsapp", type: "success",   confirmButtonText: "Ok" }).then(function(){
                        window.open('https://api.whatsapp.com/send?phone=55'+$scope.numero+'&text=Olá%20'+$scope.nome+',%20pode%20me%20ajudar'+textoImovel+'?%20','_blank');
                    });
                }
            }

        
            if(!$scope.atend.nome) {         
                swal({   title: "Por favor, digite o seu nome",  confirmButtonColor:"#A8A9AE", confirmButtonText: "Ok" });
                return false;
            }
        
            if(!$scope.atend.numero) {         
                swal({   title: "Por favor, digite o seu telefone",  confirmButtonColor:"#A8A9AE", confirmButtonText: "Ok" });
                return false;
            }
        
            if(!$scope.atend.email) {         
                swal({   title: "Por favor, digite o seu e-mail",  confirmButtonColor:"#A8A9AE", confirmButtonText: "Ok" });
                return false;
            }
      
            if($scope.imovel){
                $scope.atend.id = $scope.imovel._id;
                $scope.atend.imovel = {'_id' : $scope.atend.id};
                $scope.atend.url= document.URL;
                $scope.atend.midia="WhatsApp";
                var url = window.urlApi+'exportacao/NovoAtendimento';                
            }else if($scope.lancamento){
                $scope.atend.id = $scope.lancamento._id;
                $scope.atend.url= document.URL;
                $scope.atend.midia="WhatsApp";
                $scope.atend.texto += "\n\n"+"Empreendimento: "+$scope.lancamento.nome+"\n"+"Link: "+$scope.atend.url;
                var url = 'atendimentos/novoEmp';                
            }else{
                $scope.atend.unidade = $scope.unidade;
                $scope.atend.cod_imob = window.config.imobiliaria;
                $scope.atend.midia="WhatsApp";
                var url='https://turbo.gestaoreal.com.br/exportacao/NovoAtendimentoSemImovel';              
            }

            $http.post('atendimentos/novoApi',{cliente:$scope.atend,busca:window.localStorage.getItem("buscaJson")}).then(function(a)
            {
                if(!a.data.ok)
                {
                    $.post(url, $scope.atend).then(function(a) 
                    {
                        $scope.finaliza(a);
                        $scope.$apply();

                        $scope.ativacao = false;
                    });
                }else{
                    $scope.finaliza(a.data.ok);

                    $scope.ativacao = false;
                }                                
            });
        }

        $scope.finaliza= function(ok)
        {
            if(ok){

                switch ($scope.versaoSweet) {
                    case 1:
                    $scope.escolheSweet.sw1();
                        break;

                    case 2:
                    $scope.escolheSweet.sw2();
                        break;
                
                    default:
                        break;
                }
                $scope.atend={nome:'', email:'', id:'', texto:'', numero:''};
                $scope.fechar();

            } else {        
                swal({   title: "Erro!", confirmButtonColor:"#323232", text: "Não conseguimos enviar sua mensagem, por favor, tente novamente!",   type: "error",   confirmButtonText: "Voltar" });
            } 

            $scope.areamaisinfo=false;

        }  
      }
    }  
  });

/* FIM DIRETIVA ATENDIMENTO */

/* INICIO DIRETIVA ROYAL SLIDER */

a.directive('royalSlide',function(){
    return {
        restrict: 'AE',
        transclude: true,
        scope: { obj: '=?', modelo: '=?', tipo:"@?", idImob:"=?", proxant:"=?", size:"=?", config:'='},  
        template:'<div ng-include="url"></div>',        
  
        // thumb_horizontal
        // thumb_vertical
        // sem_thumb

        controller:function($scope, $timeout, $rootScope, utils)
        {   
            
            $scope.favoritos=$rootScope.favoritos;
            $scope.adicionaFavorito =$rootScope.adicionaFavorito;
            
            if (!$scope.size){
                $scope.size = "fit-if-smaller";
            }

            switch($scope.tipo){
                case 'home':
                    $scope.url = window.urlabsoluta+'componentes/royalSlide/royalSlideHome.html'; 
                break;

                case 'imovel':
                    $scope.url = window.urlabsoluta+'componentes/royalSlide/royalSlide1.html'; 
                break;

                case 'lancamento':
                    $scope.url = window.urlabsoluta+'componentes/royalSlide/royalSlide2.html'; 
                break;
            }

            $scope.urlcustomizar = window.urlcustomizar;



            function startRoyal(){
                // bullets
                 if ($scope.modelo == "bullets"){
                    $('#gallery').royalSlider({
                        fullscreen: {
                            enabled: false,
                        },
                        autoPlay: {
                            enabled: true,
                            pauseOnHover: true,
                            stopAtAction: false,
                            delay: 3000
                        },
                        controlNavigation: 'bullets',
                        autoScaleSlider: false, 
                        autoScaleSliderWidth: 1200,     
                        autoScaleSliderHeight: 100,
                        loop: true,
                        imageScaleMode: 'fit-if-smaller',
                        navigateByClick: true,
                        numImagesToPreload:2,
                        arrowsNav:false,
                        keyboardNavEnabled: true,
                        fadeinLoadedSlide: true,
                        globalCaption: false,
                        globalCaptionInside: false,
                        thumbs: {
                            appendSpan: true,
                            firstMargin: true,
                            paddingBottom: 4
                        }
                    });
                }

                // thumb_horizontal
                if ($scope.modelo == "thumb_horizontal"){
                    $('#gallery').royalSlider({
                        fullscreen: {
                            enabled: true,
                            nativeFS: true
                        },
                        
                        controlNavigation: 'thumbnails',
                        autoScaleSlider: false, 
                        autoScaleSliderWidth: 1200,     
                        autoScaleSliderHeight: 100,
                        loop: false,
                        imageScaleMode: $scope.size,
                        navigateByClick: true,
                        numImagesToPreload:2,
                        arrowsNav:true,
                        arrowsNavAutoHide: true,
                        arrowsNavHideOnTouch: true,
                        keyboardNavEnabled: true,
                        fadeinLoadedSlide: true,
                        globalCaption: false,
                        globalCaptionInside: false,
                        thumbs: {
                            appendSpan: true,
                            firstMargin: true,
                            paddingBottom: 4
                        }
                    });
                }

                // sem thumb
                if ($scope.modelo == "sem_thumb"){
                    $('#gallery').addClass("visibleNearby");
                    $('#gallery').royalSlider({
                        fullscreen: {
                            enabled: true,
                            nativeFS: true
                        },
                        
                        autoScaleSlider: false, 
                        autoScaleSliderWidth: 1200,     
                        autoScaleSliderHeight: 100,
                        loop: false,
                        imageScaleMode: 'fit-if-smaller',
                        navigateByClick: true,
                        numImagesToPreload:2,
                        arrowsNavAutoHide: true,
                        arrowsNavHideOnTouch: true,
                        updateSliderSize : true,
                        fadeinLoadedSlide: true,       
                        keyboardNavEnabled: true,
                        controlNavigation: false,
                        addActiveClass: true,
                        globalCaption: false,
                        globalCaptionInside: false,
                        arrowsNav: true,
                        visibleNearby: {
                            enabled: true,
                            centerArea: 0.5,
                            center: true,
                            breakpoint: 650,
                            breakpointCenterArea: 0.64,
                            navigateByCenterClick: true
                        }
                    });
                }

                // thumb vertical
                if ($scope.modelo == "thumb_vertical"){

                    if(!$scope.size) $scope.size = 'fill';

                    $('#gallery').royalSlider({
                        fullscreen: {
                          enabled: true,
                          nativeFS: true
                        },
                        controlNavigation: 'thumbnails',
                        thumbs: {
                          orientation: 'vertical',
                          paddingBottom: 0,
                          spacing: 0,
                          appendSpan: true
                        },
                            autoPlay: {
                            enabled: true,
                            delay: 5000,
                            pauseOnHover: true
                        },
                        transitionType:'fade',
                        imageScaleMode: $scope.size,
                        imageScalePadding: 4,
                        loop: true,
                        spacing: 1,
                        arrowsNav: true,
                        keyboardNavEnabled: true
                    }).data("royalSlider"); // assign the RS to a variable

                        mySliderInstance.ev.on('rsExitFullscreen', function(event) {


                    });
                }
            }


            if($scope.proxant == false){
                $(window).on('load', function () {
                    $timeout(function() {
                        startRoyal();
                    }, 1000);
                });                
            } else {
                $timeout(function() {
                    startRoyal();
                }, 1000);
            }
            
        }
    }
});

/* FIM DIRETIVA ROYAL SLIDER */

/* INICIO DIRETIVA AGENDAR VISITA */

a.directive('agendarVisita',function(){
    return {
        restrict: 'AE',
        scope: { imovel: '=?', comp: '=?'},          
        template:'<div ng-include="url"></div>',
        controller:function($scope, $timeout, $http)
        {   
            // $timeout(function() {
            //     $scope.url = window.urlabsoluta+'componentes/agendar_visita/agendar_visita.html';   
            // }, 600);

            if(window.location.href.indexOf('-alugar-') !== -1){
                if(window.location.href.indexOf('-comprar-') !== -1){
                    $scope.operacao = false;
                } else {
                    $scope.operacao = true;
                }
            }
            
            // $scope.operacao = window.location.href.indexOf('-alugar-') !== -1 ? true : false;

            // console.info($scope.comp);
            // console.info($scope.operacao);

            $(window).load(function() {
                $scope.url = window.urlabsoluta+'componentes/agendar_visita/agendar_visita.html'; 
                $scope.$digest();   
            });     

            $scope.overlayVisita = false;

            $scope.abre = function()
            {
                $scope.overlayVisita = true;
            }

            $scope.fecha = function()
            {
                $scope.overlayVisita = false;
            }

            $scope.diadaSemana = function(m){
                return new Date($scope.ano, m, $scope.dia).getDay();
            }
            
            $scope.mesdoAno = function(m){
                return new Date($scope.ano, m, $scope.dia).getMonth();
            }
            
            
            $scope.mudaDia = function(d, m){
            $scope.dia = d;
            $scope.mes = m;  
            $scope.nroSemana = $scope.diadaSemana(m);
            
            
            if ($scope.mesdoAno(m) == 0){
                $scope.nroMes = 11;
            }else{
                $scope.nroMes = $scope.mesdoAno(m)-1;
            }
            
            }
            
            $scope.mudaHora = function(h){
            $scope.horario = h;
            
            }

            var dataHoje = new Date();
            $scope.horariosVisita = ['8:00','8:30','9:00','9:30','10:00','10:30','11:00','11:30','12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30','16:00','16:30','17:00','17:30','18:00'];
            $scope.horario = '';
            $scope.diaSemana = ['Domingo', 'Segunda-Feira', 'Terça-Feira', 'Quarta-Feira', 'Quinta-Feira', 'Sexta-Feira', 'Sábado'];
            $scope.meses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
            
            $scope.mes = dataHoje.getMonth();
            $scope.mesHoje = dataHoje.getMonth();
            $scope.mes++;

            $scope.diasNoMes = function(mes, ano) {
                var data = new Date(ano, mes, 0);
                return data.getDate();
            }
            
            if((dataHoje.getDate()+2) > 29 ){
                $scope.mes++;
            }
            
            $scope.dia = dataHoje.getDate(dataHoje.setDate(dataHoje.getDate()+2));
            $scope.diaHj = dataHoje.getDate(dataHoje.setDate(dataHoje.getDate()+2));  

            var qtsDiasMes = $scope.diasNoMes( $scope.mesHoje+1 ,dataHoje.getFullYear());

            if($scope.dia > qtsDiasMes){
                $scope.mesHoje = $scope.mesHoje+2;
            }else{
                $scope.mesHoje = $scope.mesHoje;
            }

            $scope.mesFixo = $scope.mes;
            $scope.ano = dataHoje.getFullYear();
            $scope.arrayDias = [];
            $scope.nroSemana = $scope.diadaSemana($scope.mes-1);            
            
            if ($scope.mesdoAno($scope.mes) == 0){
                $scope.nroMes = 11;
            }else{
                $scope.nroMes = $scope.mesdoAno($scope.mes);
            }
            
            $scope.dias = daysInMonth($scope.mes, $scope.ano);
            $scope.diaClicado = 0;
            
            $scope.diaAtual = $scope.dia;
            $scope.mesAtual = $scope.mes;
            
            
            $scope.checaDia = function(d) { 
                $scope.diaClicado = d.dia;
                var s=0;
                $scope.mudaDia(d.dia, d.mes);  
                $scope.nroSemana = $scope.diadaSemana($scope.mes-1);                  
            }
            
            $scope.proxDia = function(){
                $scope.dia = $scope.dia + 1;
                if($scope.dia > $scope.dias){
                    $scope.dia = 1;
                    $scope.mes = $scope.mes + 1;
                    
                    if($scope.mes > 11){
                        $scope.mes = 0;
                        $scope.ano = $scope.ano + 1;
                        $scope.dias = daysInMonth($scope.mes, $scope.ano);
                    } else {
                        $scope.dias = daysInMonth($scope.mes, $scope.ano);
                    }
                } 
                $scope.nroSemana = $scope.diadaSemana($scope.mes-1);
                $scope.nroMes = $scope.mesdoAno();
            }
            
            $scope.antDia = function(){
                $scope.dia = $scope.dia - 1;
                if($scope.dia < 1){
                    $scope.dia = 1;
                    $scope.mes = $scope.mes - 1;
                
                    if($scope.mes < 0){
                        $scope.mes = 11;
                        $scope.ano = $scope.ano - 1;
                        $scope.dias = daysInMonth($scope.mes, $scope.ano);
                    } else {
                        $scope.dias = daysInMonth($scope.mes, $scope.ano);
                    }
                }
                $scope.nroSemana = $scope.diadaSemana($scope.mes-1);
                $scope.nroMes = $scope.mesdoAno();
            }
            
            $scope.proxMes = function(){
                $scope.dia = 1;
                $scope.mes = $scope.mes + 1;
                if ($scope.mes <= $scope.mesAtual){
                    $scope.dia = $scope.diaAtual;
                } else if($scope.mes > 11){
                    $scope.mes = 0;
                    $scope.ano = $scope.ano + 1;
                    $scope.dias = daysInMonth($scope.mes, $scope.ano);
                } else {
                    $scope.dias = daysInMonth($scope.mes, $scope.ano);
                }
                $scope.nroSemana = $scope.diadaSemana();
                $scope.nroMes = $scope.mesdoAno();                
            }
            
            $scope.antMes = function(){
                $scope.dia = 1;
                $scope.mes = $scope.mes - 1;
                if ($scope.mes <= $scope.mesAtual){
                    $scope.dia = $scope.diaAtual;
                } else if($scope.mes < 0){
                    $scope.mes = 11;
                    $scope.ano = $scope.ano - 1;
                    $scope.dias = daysInMonth($scope.mes, $scope.ano);
                } else {
                    $scope.dias = daysInMonth($scope.mes, $scope.ano);
                }
                $scope.nroSemana = $scope.diadaSemana();
                $scope.nroMes = $scope.mesdoAno();
                
            }
            
            function daysInMonth(month,year) {
                var dataMes = new Date(year, month, 0).getDate();
                $scope.arrayDias = [];

                for(var i = 1; i <= dataMes; i++){

                    $scope.arrayDias.push({mes:month, dia:i});
                }

                if ($scope.dia+5>30)
                {
                    var dias=$scope.dia+4-30;

                    for(var i = 1; i <= dias; i++){

                    $scope.arrayDias.push({mes:month+1, dia:i});
                }
                    

                }

                return dataMes;
            }

            $scope.cliente = {};

            $scope.envioAtendimentoVisita = function(){

                $scope.ativacao = true;
                
                if(!$scope.cliente.nome) {
                    swal({   title: "Por favor, digite o seu nome",  confirmButtonColor:"#A8A9AE", confirmButtonText: "Ok" });
                    return false;
                }
        
                if(!$scope.cliente.email) {         
                    swal({   title: "Por favor, digite o seu email",  confirmButtonColor:"#A8A9AE", confirmButtonText: "Ok" });
                    return false;
                }

                if(!$scope.cliente.numero) {         
                    swal({   title: "Por favor, digite o seu telefone",  confirmButtonColor:"#A8A9AE", confirmButtonText: "Ok" });
                    return false;
                }
        
                $scope.horarioVisita = $scope.horario;
                $scope.diaVisita = $scope.dia+'/'+($scope.mes)+'/'+$scope.ano;
        
                var imovel={'_id':$scope.imovel._id, 'sigla':$scope.imovel.sigla};
                $scope.cliente.midia='Site da imobiliária';
                $scope.cliente.imovel=imovel; 
                $scope.cliente.texto = '\n\n Solicitação de agendamento de visita: \n\n';
        
                if($scope.horarioVisita) {
                    $scope.cliente.texto += ' Data Pretendida: '+$scope.diaVisita;
                }
        
                if($scope.diaVisita) {
                    $scope.cliente.texto += '\n Horário Pretendido:'+$scope.horarioVisita;
                }

                $http.post('atendimentos/novoApi',{cliente:$scope.cliente,busca:window.localStorage.getItem("buscaJson")}).then(function(a)
                {
                    if(!a.data.ok)
                    {
                        $.post('https://turbo.gestaoreal.com.br/exportacao/NovoAtendimento', $scope.cliente).then(function(midia){

                            $scope.finaliza(midia.atendimento.ok);
                            $scope.$apply();
                            $scope.ativacao = false;

                        });
                    }else{
                        $scope.finaliza(a.data.ok);
                        $scope.ativacao = false;
                    }                                
                });

                $scope.finaliza = function(ok)
                {
                    if(ok){
                        swal({   title: "Enviado com sucesso!",  confirmButtonColor:"#333", text: "Entraremos em contato assim que possível!",   type: "success",   confirmButtonText: "Ok" });
                        $scope.overlayopcao = 0;

                        $scope.fecha();        
                        $scope.cliente = {};
        
                    } else {
                        swal({   title: "Erro!", confirmButtonColor:"#333",  text: "Não conseguimos enviar sua mensagem, por favor, tente novamente!",   type: "error",   confirmButtonText: "Voltar" });
                    }
                }

            }

        }
    }
});

/* FIM DIRETIVA AGENDAR VISITA */