// file comdono/imovel.js

var iniStreetView = true;
var centerMap   = {lat: parseFloat($('#latitude').val()), lng: parseFloat($('#longitude').val())};
var zoomMap     = 14;
var id_imovel;
var actionLogin;
var w = $(this).width();

addToCart = function(){
    // track facebook pixel para catalogo dinamico
    if (typeof fbq !== 'undefined') { // apenas na prod
          
        fbq('track', 'AddToCart',{
          content_ids: ['742359892923039'],
          contents: [{'id': $('input[name=id_imovel]').val(), 'quantity': 1 }],
          content_type: 'HOME_LISTING'
        });
    }
}

/*var meta_type = "";
var meta_title = "";
var meta_description = "";
var meta_image = "";
var meta_url = "";*/

/*function getMetas(){
    
    meta_type = $(".meta_type").data("meta_type");
    meta_title = $(".meta_title").data("meta_title");
    meta_description = $(".meta_description").data("meta_description");
    meta_image = $(".meta_image").data("meta_image");
    meta_url = $(".meta_url").data("meta_url");
    
    
    console.log(meta_type,meta_title,meta_description,meta_image,meta_url);
    
    $("meta[property='og:type']").attr("content", meta_type);
    $("meta[property='og:title']").attr("content", meta_title);
    $("meta[property='og:descrition']").attr("content", meta_description);
    $("meta[property='og:url']").attr("content", meta_url);
    $("meta[property='og:image']").attr("content", meta_image);
    
}*/

var galeriaGrupos
$(window).on('load', function(){
    
    if(!($('#gcaptcha2').length == 0 || $('#gcaptcha2').val() == undefined))
    {
        console.log('gcaptcha2');
        widgetId2 = grecaptcha.render('gcaptcha2', {
            'sitekey' : sitekey,
            'theme' : 'light'
		});
    }
    
    
    
    
    if(typeof trigger_click != 'undefined'){
        switch (trigger_click) {
            case 'Falar com o Dono':
                $(".falarComdono").trigger('click');
            break;
            
            default:
                // code
        }
    }
    
    /*getMetas();*/
    
    /*if (w == 480){
        $(".ug-default-button-hidepanel-bg").trigger("click");
    }*/
    
    if ($('.audio-player').length ) {
        playerDepimento();
    }
    
    id_imovel = $('#id_imovel').val();
    
    $('.d-none').hide();
    $('.d-none').removeClass("d-none");
    showContainer('.container-fotos');
    
    $(".actFotos").addClass("active");
    
    var pathname = window.location.pathname;
    
    if(pathname == "/cadastro/preview"){
        loadPage();
    }
    else{
        ini_moreContent();
    }
    
    galeriaGrupos = $('.galeria_premium').data('galeria');
    tipoDescricao = $('.galeria_premium').data('tipo-descricao');
    contGrupo = [];
    
    if(galeriaGrupos != undefined)
    {
        for(y in galeriaGrupos){
            galeria = galeriaGrupos[y]['imagens'];
            contGaleria = 0;
            for(i in galeria){
                contGaleria++;
                contGrupo[y] = contGaleria;
            }
        }
            
        for(y in galeriaGrupos){
            galeria = galeriaGrupos[y]['imagens'];
            for(i in galeria)
            {   
                img = galeria[i];
                
                $caption = (tipoDescricao == 1) ? 'data-caption="'+img.descricao+'"' : "";

                /*antigo -->> html = '<div class="loadImg_'+img.id_img+' loading-box"><i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw load-icon"></i></div>';*/
                html = `<div class="loadImg_${img.id_img} loading-box"><i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw load-icon"></i></div>`;
                html  += '<a data-fancybox="images" '+$caption+' href="'+img.uri+img.imagem+'" class="blocoImg_'+img.id_img+' d-none"><img alt="" src="'+img.uri+img.imagem+'" data-image="" onload="loadImage('+img.id_img+','+y+')" data-description="">';
                if(img.descricao !="" && tipoDescricao == 1)
                    html += '<div class="caption">'+img.descricao+'</div>';
                html  += '</a>';
                
                $('.img_galeria_'+img.id_img).html(html);
            }
        }
    }
});


contImg = 0;
contCat = [];
//window.onload
 function loadImage(e,y)
 {
    if(contCat[y] == undefined)
        contCat[y] = [e];
    else
        contCat[y].push(e);
     
    //console.log(contGrupo[y], contCat[y].length);
    
    $('.blocoImg_'+e).removeClass('d-none');
    $('.loadImg_'+e).hide();
     
    contImg++;
    
    if(contGrupo[y] == contCat[y].length){
       justifiedGallery(y);
       /*console.log(galeriaGrupos[y]['categoria']);
       console.log("openHeightGaleria "+$('.container-galeria').height());*/
    }
 }


$(".act-tour").on("click", function(){
    $('.open-modal-tour').modal('show');
});

//galeria

function justifiedGallery(y)
{
    $(".mygallery-final-"+y).removeClass('d-none');
    $(".mygallery-final-"+y).justifiedGallery({
        rowHeight: 300,
        margins: 20
    });
    $(".mygallery-final-"+y).show();
    $(".mygallery-load-"+y).hide();
    
    $(".mygallery-final-"+y).find('img').prop( "onload", null );
}


//player
function playerDepimento(){
   $('.audio-player').mediaelementplayer({
        features: ['playpause','progress'],
        audioVolume: 'horizontal',
        /*iPadUseNativeControls: true,
        iPhoneUseNativeControls: true,
        AndroidUseNativeControls: true*/
    }); 
}


$(document).scroll(function () {
	    
	var heightHeader = $('header').height();
	var posicaoScroll = $(document).scrollTop();
    
    //menu fixo
    if(w > 991){
        if (posicaoScroll > heightHeader) 
    	{
    		$('.box-fixed').addClass('fixo');
    	}
    	else
    	{
    		$('.box-fixed').removeClass('fixo');
    	}
    }
	
});

function loadPage()
{
    $(".loader-page-preview").delay(100).fadeToggle();
	$(".show-page-preview").delay(500).fadeToggle().queue(function(){
	    ini_moreContent();
	    $(this).dequeue();
	});
}

function ini_moreContent()
{
    var heightContent = 200;
    var heightMrccontent = $(".leia_mais").height();
    
    if(heightMrccontent < heightContent){
        $('.box-control-more').hide();
    }
    
    var leia_mais = $('[data-mrc]');
    if(leia_mais.length != 0){
        leia_mais.moreContent({
            height: heightContent,
        	speed: 800,
        	shadow: true,
        	tpl: {
                btn: ''
              }
        });
    }
}

$('.close-text').click(function(){
    $(this).hide('slow');
    $('.open-text').show('slow');
    $('.leia_mais').moreContent('close');
});

$('.open-text').click(function(){
    $(this).hide('slow');
    $('.close-text').show('slow');
    $('.leia_mais').moreContent('open');
});

function addActive(active){	
    $(active).parents(".container-actions").find(".item-action").removeClass("active").removeClass("show");
    $(active).addClass("active");
}

function showGoogleMapsStreeView() {

    var latLng = centerMap;

    var mapOptions = {
        zoom: zoomMap,
        center: latLng
    };

    map = new google.maps.Map(
        document.getElementById('mapImovel'), {
            zoom: zoomMap,
            center: latLng,
            //mapTypeId: "satellite"
            mapTypeId: "roadmap"
    });
    
    var marker = new google.maps.Marker({position: latLng, map: map});
    
    var panorama = new google.maps.StreetViewPanorama(
     document.getElementById('mapStreetView'), {
        position: centerMap,        //pov: {heading: 34,pitch: 10}
     });
    //map.setStreetView(panorama);
    /*var svService = new google.maps.StreetViewService();
            var panoRequest = {
                location: centerMap,
                preference: google.maps.StreetViewPreference.NEAREST,
                radius: 50,
                source: google.maps.StreetViewSource.OUTDOOR
            };

            var findPanorama = function(radius) {
                panoRequest.radius = radius;
                svService.getPanorama(panoRequest, function(panoData, status){
                    if (status === google.maps.StreetViewStatus.OK) {
                        var panorama = new google.maps.StreetViewPanorama(
                            document.getElementById('mapStreetView'),
                            {
                                pano: panoData.location.pano,
                            });
                    } else {
                        //Handle other statuses here
                        if (radius > 200) {
                            alert("Street View is not available");  
                        } else {
                            findPanorama(radius + 5);
                        }
                    }
                });     
            };

            findPanorama(50);*/
}

function showContainer(nClass)
{
    if(nClass == ".actCompartilhar"){
        $(".boxCompartilhar").fadeIn();
	    $(".container-body-detalhes").removeClass("mt-60");
    }else{
        $(".boxCompartilhar").hide();
    	$(".container-body-detalhes").addClass("mt-60");
    	$(".container-fotos").hide();
        $(".container-videos").hide();
        $(".container-map").hide();
        $(".container-street-view").hide();
        $(nClass).show();
    }    
}

//var validCaptcha = $('#validCaptcha').val();
/*$(window).on('load',function(){
    widgetId1 = grecaptcha.render('gcaptcha', {
            'sitekey' : sitekey,
            'theme' : 'light'
		});
});*/

$('#login-form-2').submit(function(event){	

    event.preventDefault();
    
    loadButton($('.btn-login'));
    
    if($('#login-form-2').find('textarea[name=g-recaptcha-response]') != undefined)
	{
		var captcha = $('#login-form-2').find('textarea[name=g-recaptcha-response]').val();
		if(captcha == '' && validCaptcha == true){
			$('#content-error-2').html('<div class="message login-warning alert alert-warning"><i class="fa fa-warning fa-lg mr-2"></i>Por favor preencher o captcha.</div>');
			loadButton(null,false);
			return false;
		}
	}
    
    //var email = $('#login-form-2 input[name=email]').val()
	//var password = $('#login-form-2 input[name=password]').val()	
	
    if($('#login-form-2 input[name=lembrar]').is(':checked')){
		var lembrar = 1;
	}else{
		var lembrar = 0;
	}
	
	var target = $(this).attr('action');
	
	/*var data = {
			email: email,
			password: password,
			lembrar: lembrar
			
		}*/
	
    var data = getForm('#login-form-2');
	
	$.ajax({
		url: target,
		dataType: 'json',
		type: 'POST',
		data: data,
		success: function(retorno)
		{	
		    console.log('success',retorno);
		    
			if (retorno.valid === true)
			{
			    
			    
			    ga('send', 'event', 'Conversâo', 'Falar Comdono', 'Imovel', 'Value');
			    
			    loadButton(null,false);
			    $('.modal-login-chat').modal('hide');
			    //$('.modal-login').modal('hide');
			    if(actionLogin == 'falarComdono')
			    {
			        falarComdono($('.falarComdono'));
			    }
			    else if(actionLogin == 'simulaFinanciamento')
			    {
			        simulaFinanciamento($('.simulaFinanciamento'))
			    }
			    else
			    {
			        document.location.href = retorno.redirect;
			    }
			    
			}
			else
			{
			   
			    //if(retorno.reset == true)
			        grecaptcha.reset(widgetId2);
			    
			    
			    $.ajax({
            		url: base_url+"comdono/ajax/login_ajax/checkCaptcha",
            		dataType: 'json',
            		type: 'POST',
            		success: function(retorno)
            		{
            		    if(retorno.valid == true){
            		        $('.captcha').show();
            		        validCaptcha = true;
            		    }
            		    //loadButton(null,false);
                    }
    		    });
			    
			    loadButton(null,false);
				/*$(":text,input[name=email]", $("#login-form-2")).each(function () {
		            $(this).val("");			           
		        });
		        $(":text,input[name=password]", $("#login-form-2")).each(function () {
		            $(this).val("");			           
		        });
				$(":checkbox", $("#login-form-2")).each(function () {
		            $(this).prop({ checked: false });
		        });*/
                ico = '<img src="'+base_url+'/assets/img/comdono/icons/error.png">';
		        $('#login-form-2 #content-error-2').show();
		        $('#login-form-2 #content-error-2').html('<label class="error-login"><span>'+ico+'</span>'+retorno.msg+'</label>');
		        
			}
		},
		error: function(error)
		{
		    console.log('error',retorno);
		    
		    loadButton(null,false);
			
			ico = '<img src="'+base_url+'/assets/img/comdono/icons/error.png">';
	        $('#login-form-2 #content-error-2').show();
	        $('#login-form-2 #content-error-2').html('<label class="error-login"><span>'+ico+'</span>Não foi possível realizar o acesso! Falha na Comunicação.</label>');
			
		}
	});
	//return false;
});

var cond_click_compartilhar = true;
$(".actFotos").on("click", function(){
    addActive($(this));
    showContainer(".container-fotos");
    cond_click_compartilhar = true;
});

$(".actVideo").on("click", function(){
    addActive($(this));
    heightGalleryFotos = $("#gallery").attr("style");
    $(".container-videos").attr("style",heightGalleryFotos);
    showContainer(".container-videos");
    cond_click_compartilhar = true;
});

$(".actVideo2").on("click", function(){
    addActive($(this));
    
    heightGalleryFotos = $(".heightContentPainel").outerHeight();
    $(".heightContentPainel").css("height",heightGalleryFotos);
    $(".container-videos").css("height",heightGalleryFotos);
    
    showContainer(".container-videos");
    cond_click_compartilhar = true;
});

$(".actMap").on("click", function(){
    addActive($(this));
    
    heightGalleryFotos = $("#gallery").attr("style");
    styleStreet = "position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"
    $(".container-map").attr("style",heightGalleryFotos+styleStreet);
    
    showContainer(".container-map");
    showGoogleMapsStreeView();
    cond_click_compartilhar = true;
});

$(".actMap2").on("click", function(){
    addActive($(this));
    
    heightGalleryFotos = $(".heightContentPainel").outerHeight();
    $(".heightContentPainel").css("height",heightGalleryFotos);
    $(".container-map").css("height",heightGalleryFotos);
    showContainer(".container-map");
    showGoogleMapsStreeView();
    cond_click_compartilhar = true;
});

$(".actStreetView").on("click", function(){
    
    addActive($(this));
    
    heightGalleryFotos = $("#gallery").attr("style");
    styleStreet = "position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"
    $(".container-street-view").attr("style",heightGalleryFotos+styleStreet);
    
    showContainer(".container-street-view");
    //if(iniStreetView)
    showGoogleMapsStreeView();
    //iniStreetView = false;
    cond_click_compartilhar = true;
});

$(".actStreetView2").on("click", function(){
    
    addActive($(this));
    
    heightGalleryFotos = $(".heightContentPainel").outerHeight();
    $(".heightContentPainel").css("height",heightGalleryFotos);
    $(".container-street-view").css("height",heightGalleryFotos);
    
    showContainer(".container-street-view");
    //if(iniStreetView)
    showGoogleMapsStreeView();
    //iniStreetView = false;
    cond_click_compartilhar = true;
});


$(".actCompartilhar").on("click", function(){
    if(cond_click_compartilhar == true){
        addActive($(this));
        showContainer(".actCompartilhar");
        cond_click_compartilhar = false;
        
    }else if (cond_click_compartilhar == false){
        $(".actFotos").trigger("click");
        cond_click_compartilhar = true;
    }
});

$("body").on("click", ".falarComdono", function() {
    addToCart();
    actionLogin = 'falarComdono';
    falarComdono($(this));
});

function falarComdono(e)
{
    loadButton(e);
    
        (function(d, t) {
                    var g = d.createElement(t),
                    s = d.getElementsByTagName(t)[0];
                    g.src = "https://cdn.pushalert.co/integrate_c74ae55fc5e90d6933fffb75bb904803.js";
                    s.parentNode.insertBefore(g, s);
            }(document, "script"));
    
        console.log('clicou');
        (pushalertbyiw = window.pushalertbyiw || []).push(['onReady', onPAReady]);
    
        function onPAReady() {
            
            $sub = PushAlertCo.getSubsInfo();
            
            //CASO NÃO INSCRITO ELE FORÇA, DEPOIS ENVIA
            var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
            if(isSafari != true){
                if($sub.status != "subscribed"){
                    
                    PushAlertCo.forceSubscribe();
                    $sub = PushAlertCo.getSubsInfo();
                }
            }
            
            
            if($sub.status == "subscribed"){
                
                $.ajax({
                    url: base_url + "comdono/imovel/save_push_alert",
                    dataType: "json", 
                    type: "POST",
                    data: $sub,
                    success: function(retorno) {
                        console.log(retorno);
                    }
                });
            }
            
            
            console.log($sub); //You can call this method to get the subscription status of the subscriberPushAlertCo.getSubsInfo(); //You can call this method to get the subscription status of the subscriber
        }
    
    $imovel = e.data('unidade');
    
    $.ajax({
        url: base_url + "minha_conta/ajax/chat_ajax/ini_chat",
        dataType: "json", 
        type: "POST",
        data: $imovel,
        success: function(retorno) {
            if(retorno.valid)
            {
                    $.ajax({
                        url: base_url + "comdono/imovel/send_push_alert_interessado",
                        dataType: "json", 
                        type: "POST",
                        data: $imovel,
                        success: function(retorno) {
                            console.log(retorno);
                            die();
                        }
                    });
                
                setChat(retorno.chat);
                if(retorno.notifica)
                    conn.sendMsg({ broadType : 'ini_chat', data : retorno.chat});
                
                loadButton(null, false);
                document.location.href = base_url+"minha_conta/minhas_compras/negociacoes/"+retorno.chat.id_imovel+'/'+retorno.chat.id_chat;
            }
            else
            {
                if(retorno.erro == 1)
                {
                    $('.modal-login-chat').modal('show');
                    //$('.modal-login').modal('show');
                    //$('.modal-title').html('Negociar com o Dono');
                    //$('p.contentLogin').html('Faça o login.');
                    //$('p.contentCadastro').html('Preencha o cadastro.');
                }
                else{
                    alert(retorno.msg);
                } 
                
                loadButton(null, false);
            }
            
        },
        error: function(error) {
          loadButton(null, false);
        }
    });
}

$(document).on("click", ".simulaFinanciamento", function() {
    addToCart();
    actionLogin = 'simulaFinanciamento';
    simulaFinanciamento($(this))
    
});

function simulaFinanciamento(e)
{
    
    loadButton(e);
    //return false;
    $.ajax({
        url: base_url + "comdono/ajax/get_ajax/valid_login",
        dataType: "json",
        type: "POST",
        data: {ref: base_url+"financiamento/simulacao/"+id_imovel},
        success: function(retorno) {
            if(retorno.valid)
            {
                document.location.href = base_url+"financiamento/simulacao/"+id_imovel;
            }
            else
            { 
                $('.modal-login-site').modal('show');
                //$('.modal-login').modal('show');
                loadButton(null, false);
            }
        },
        error: function(error) {
          loadButton(null, false);
        }
    });
}

$(".act-detalhes-imovel").on("click", function(){
    $('.open-modal-detalhes').modal('show');
    $('.list-detalhes-imovel').show();
    $('.list-detalhes-condominio').hide();
});

$(".act-detalhes-condominio").on("click", function(){
    $('.open-modal-detalhes').modal('show');
    $('.list-detalhes-condominio').show();
    $('.list-detalhes-imovel').hide();
});

$(".act-compartilhar").click(function(){
    openForm();
    var url = $(this).data("url");
    $("#imovel_comp").val(url);
    $('.open-modal-compartilhar').modal('show');
});

$('#email_comp').multiple_emails({position: "bottom"});

$('.btnCompartilhar').on('click',function(){
    $('#form-contato').submit();
});

$('#form-contato').submit(function(e){	
    e.stopPropagation();
    
    var url = $('.act-compartilhar').data("url");
    
    loadButton($('#form-contato button.btn-success'));
	
	$.ajax({
		url: base_url+"comdono/ajax/compartilhar_ajax/index",
		dataType: 'json',
		type: 'POST',
		data: getFormContato(),
		success: function(retorno)
		{		
			if (retorno.valid === true)
			{	
			    loadButton(null,false);
			    //$("#form-contato")[0].reset();
			    $(".multiple_emails-close").trigger("click");
			    $('#form-contato input[name=remetente]').val("");
			    $('#form-contato input[name=email_comp]').val("");
			    $('.content-form #content-error-2').html('');
    	        $('.content-form').hide();
			    $('.modal-title').html("Pronto!");
    	        $('.content-result').show();
    	        $('.content-result').html(retorno.msg);
			}
			else
			{ 
			    loadButton(null,false);
			    ico = '<img src="'+base_url+'/assets/img/comdono/icons/error.png">';
    	        $('.content-form #content-error-2').html('<label class="error-login"><span>'+ico+'</span>'+retorno.msg+'</label>');
			}
		},
		error: function(error)
		{ 
		    loadButton(null,false);
			ico = '<img src="'+base_url+'/assets/img/comdono/icons/error.png">';
	        $('.content-form #content-error-2').html('<label class="error-login"><span>'+ico+'</span>Não foi possível enviar o e-mail. Tente novamente mais tarde.</label>');
		}
	});
	return false;
})

function openForm(){
    $(".multiple_emails-close").trigger("click");
    $('#form-contato input[name=remetente]').val("");
    $('#form-contato input[name=email_comp]').val("");
    $('.content-result').hide();
    $('.content-result').html('');
    $('.content-form').show();
    $('.content-form #content-error-2').html('');
}

function getFormContato(){
    
    data = [];
    $('#form-contato').find('input:not([type=radio]):input:not([type=checkbox]):input:not([type=file])').each(function(key,value){
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    $('#form-contato').find('textarea').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    $('#form-contato').find('input[type=radio]:checked').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    $('#form-contato').find('select option:selected').each(function(key,value)    {
        if(this.parentElement.localName == 'select')
            data.push({"name": this.parentElement.name, "value": this.value});
            
        if(this.parentElement.parentElement.localName == 'select')
            data.push({"name": this.parentElement.parentElement.name, "value": this.value});
    });
    
    $('#form-contato').find('input[type=checkbox]:checked').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    
    $('#form-contato').find('input[type=checkbox]:not(:checked)').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": ""});
    });
    
    return data;
}