/* Template: Juno - Multipurpose Landing Page Pack
   Author: InovatikThemes
   Created: Mar 2019
   Description: Custom JS file
*/


(function($) {
    "use strict"; 
	
	/* Preloader */
	$(window).on('load', function() {
		var preloaderFadeOutTime = 500;
		function hidePreloader() {
			var preloader = $('.spinner-wrapper');
			setTimeout(function() {
				preloader.fadeOut(preloaderFadeOutTime);
			}, 500);
		}
		hidePreloader();
	});

	
	/* Navbar Scripts */
	// jQuery to collapse the navbar on scroll
    $(window).on('scroll load', function() {
		if ($(".navbar").offset().top > 20) {
			$(".fixed-top").addClass("top-nav-collapse");
		} else {
			$(".fixed-top").removeClass("top-nav-collapse");
		}
    });

	// jQuery for page scrolling feature - requires jQuery Easing plugin
	$(function() {
		$(document).on('click', 'a.page-scroll', function(event) {
			var $anchor = $(this);
			$('html, body').stop().animate({
				scrollTop: $($anchor.attr('href')).offset().top
			}, 600, 'easeInOutExpo');
			event.preventDefault();
		});
	});

    // closes the responsive menu on menu item click
    $(".navbar-nav li a").on("click", function(event) {
    if (!$(this).parent().hasClass('dropdown'))
        $(".navbar-collapse").collapse('hide');
    });


    /* Rotating Text - Morphtext */
	$("#js-rotating").Morphext({
		// The [in] animation type. Refer to Animate.css for a list of available animations.
		animation: "fadeIn",
		// An array of phrases to rotate are created based on this separator. Change it if you wish to separate the phrases differently (e.g. So Simple | Very Doge | Much Wow | Such Cool).
		separator: ",",
		// The delay between the changing of each phrase in milliseconds.
		speed: 2000,
		complete: function () {
			// Called after the entrance animation is executed.
		}
    });
    

    /* Card Slider - Swiper */
	var cardSlider = new Swiper('.card-slider', {
		autoplay: {
            delay: 4000,
            disableOnInteraction: false
		},
        loop: true,
        navigation: {
			nextEl: '.swiper-button-next',
			prevEl: '.swiper-button-prev'
		},
		slidesPerView: 3,
		spaceBetween: 20,
        breakpoints: {
            // when window is <= 992px
            992: {
                slidesPerView: 2
            },
            // when window is <= 768px
            768: {
                slidesPerView: 1
            } 
        }
    });

    
    /* Image Slider - Swiper */
    var imageSlider = new Swiper('.image-slider', {
        autoplay: {
            delay: 2000,
            disableOnInteraction: false
		},
        loop: false,
        navigation: {
			nextEl: '.swiper-button-next',
			prevEl: '.swiper-button-prev',
		},
        spaceBetween: 30,
        slidesPerView: 5,
		breakpoints: {
            // when window is <= 380px
            380: {
                slidesPerView: 1,
                spaceBetween: 10
            },
            // when window is <= 516px
            516: {
                slidesPerView: 2,
                spaceBetween: 10
            },
            // when window is <= 768px
            768: {
                slidesPerView: 3,
                spaceBetween: 20
            },
            // when window is <= 992px
            992: {
                slidesPerView: 4,
                spaceBetween: 30
            },
            // when window is <= 1200px
            1200: {
                slidesPerView: 5,
                spaceBetween: 30
            },
        }
    });


    /* Image Slider - Magnific Popup */
	$('.popup-link').magnificPopup({
		removalDelay: 300,
		type: 'image',
		callbacks: {
			beforeOpen: function() {
				this.st.image.markup = this.st.image.markup.replace('mfp-figure', 'mfp-figure ' + this.st.el.attr('data-effect'));
			},
			beforeClose: function() {
				$('.mfp-figure').addClass('fadeOut');
			}
		},
		gallery:{
			enabled:true //enable gallery mode
		}
    });

    
    /* Video Lightbox - Magnific Popup */
    $('.popup-youtube, .popup-vimeo').magnificPopup({
        disableOn: 700,
        type: 'iframe',
        mainClass: 'mfp-fade',
        removalDelay: 160,
        preloader: false,
        fixedContentPos: false,
        iframe: {
            patterns: {
                youtube: {
                    index: 'youtube.com/', 
                    id: function(url) {        
                        var m = url.match(/[\\?\\&]v=([^\\?\\&]+)/);
                        if ( !m || !m[1] ) return null;
                        return m[1];
                    },
                    src: 'https://www.youtube.com/embed/%id%?autoplay=1'
                },
                vimeo: {
                    index: 'vimeo.com/', 
                    id: function(url) {        
                        var m = url.match(/(https?:\/\/)?(www.)?(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/);
                        if ( !m || !m[5] ) return null;
                        return m[5];
                    },
                    src: 'https://player.vimeo.com/video/%id%?autoplay=1'
                }
            }
        }
    });


    /* Lightbox - Magnific Popup */
	$('.popup-with-move-anim').magnificPopup({
		type: 'inline',
		fixedContentPos: false, /* keep it false to avoid html tag shift with margin-right: 17px */
		fixedBgPos: true,
		overflowY: 'auto',
		closeBtnInside: true,
		preloader: false,
		midClick: true,
		removalDelay: 300,
		mainClass: 'my-mfp-slide-bottom'
	});
    

/* Counter - CountTo */
var a = 0;
$(window).scroll(function() {
    if ($('#counter').length) { // checking if CountTo section exists in the page, if not it will not run the script and avoid errors	
        var oTop = $('#counter').offset().top - window.innerHeight;
        if (a == 0 && $(window).scrollTop() > oTop) {
        $('.counter-value').each(function() {
            var $this = $(this),
            countTo = $this.attr('data-count');
            $({
            countNum: $this.text()
            }).animate({
                countNum: countTo
            },
            {
                duration: 2000,
                easing: 'swing',
                step: function() {
                $this.text(Math.floor(this.countNum));
                },
                complete: function() {
                $this.text(this.countNum);
                //alert('finished');
                }
            });
        });
        a = 1;
        }
    }
});


    /* Move Form Fields Label When User Types */
    // for input and textarea fields
    $("input, textarea").keyup(function(){
		if ($(this).val() != '') {
			$(this).addClass('notEmpty');
		} else {
			$(this).removeClass('notEmpty');
		}
    });


    /* Contact Form */
    $("#contactForm").validator().on("submit", function(event) {
    	if (event.isDefaultPrevented()) {
            // handle the invalid form...
            cformError();
            csubmitMSG(false, "Please fill all fields!");
        } else {
            // everything looks good!
            event.preventDefault();
            csubmitForm();
        }
    });

    function csubmitForm() {
        // initiate variables with form content
		var name = $("#cname").val();
		var email = $("#cemail").val();
        var message = $("#cmessage").val();
        var terms = $("#cterms").val();
        $.ajax({
            type: "POST",
            url: "php/contactform-process.php",
            data: "name=" + name + "&email=" + email + "&message=" + message + "&terms=" + terms, 
            success: function(text) {
                if (text == "success") {
                    cformSuccess();
                } else {
                    cformError();
                    csubmitMSG(false, text);
                }
            }
        });
	}

    function cformSuccess() {
        $("#contactForm")[0].reset();
        csubmitMSG(true, "Message Submitted!");
        $("input").removeClass('notEmpty'); // resets the field label after submission
        $("textarea").removeClass('notEmpty'); // resets the field label after submission
    }

    function cformError() {
        $("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
            $(this).removeClass();
        });
	}

    function csubmitMSG(valid, msg) {
        if (valid) {
            var msgClasses = "h3 text-center tada animated";
        } else {
            var msgClasses = "h3 text-center";
        }
        $("#cmsgSubmit").removeClass().addClass(msgClasses).text(msg);
    }


    /* Privacy Form */
    $("#privacyForm").validator().on("submit", function(event) {
    	if (event.isDefaultPrevented()) {
            // handle the invalid form...
            pformError();
            psubmitMSG(false, "Please fill all fields!");
        } else {
            // everything looks good!
            event.preventDefault();
            psubmitForm();
        }
    });

    function psubmitForm() {
        // initiate variables with form content
		var name = $("#pname").val();
		var email = $("#pemail").val();
        var select = $("#pselect").val();
        var terms = $("#pterms").val();
        
        $.ajax({
            type: "POST",
            url: "php/privacyform-process.php",
            data: "name=" + name + "&email=" + email + "&select=" + select + "&terms=" + terms, 
            success: function(text) {
                if (text == "success") {
                    pformSuccess();
                } else {
                    pformError();
                    psubmitMSG(false, text);
                }
            }
        });
	}

    function pformSuccess() {
        $("#privacyForm")[0].reset();
        psubmitMSG(true, "Request Submitted!");
        $("input").removeClass('notEmpty'); // resets the field label after submission
    }

    function pformError() {
        $("#privacyForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
            $(this).removeClass();
        });
	}

    function psubmitMSG(valid, msg) {
        if (valid) {
            var msgClasses = "h3 text-center tada animated";
        } else {
            var msgClasses = "h3 text-center";
        }
        $("#pmsgSubmit").removeClass().addClass(msgClasses).text(msg);
    }
    

    /* Back To Top Button */
    // create the back to top button
    $('body').prepend('<a href="body" class="back-to-top page-scroll">Back to Top</a>');
    var amountScrolled = 700;
    $(window).scroll(function() {
        if ($(window).scrollTop() > amountScrolled) {
            $('a.back-to-top').fadeIn('500');
        } else {
            $('a.back-to-top').fadeOut('500');
        }
    });


	/* Removes Long Focus On Buttons */
	$(".button, a, button").mouseup(function() {
		$(this).blur();
	});

})(jQuery);

function increaseCounter() {
    var counterElement = document.getElementById('downloads-counter');
    var currentCount = parseInt(counterElement.getAttribute('data-count'));
    var newCount = currentCount + 1;
    counterElement.setAttribute('data-count', newCount);
    counterElement.innerText = newCount;
}

// Chame a função para aumentar o contador sempre que a página for carregada
window.onload = function() {
    increaseCounter();
};

 // Desabilita o clique nos elementos que ativam o ícone de edição
 document.addEventListener("DOMContentLoaded", function() {
    var editableElements = document.querySelectorAll("[contenteditable=true]");

    editableElements.forEach(function(element) {
        element.addEventListener("mousedown", function(event) {
            event.preventDefault();
        });
    });
});

window.onload = function() {
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = '/css/bootstrap.css';
    document.head.appendChild(link);
};

window.onload = function() {
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = '/css/fontawesome-all.css';
    document.head.appendChild(link);
};

  // Função para carregar imagens preguiçosamente quando estiverem prestes a entrar na visualização do usuário
  function lazyLoadImages() {
    const lazyImages = document.querySelectorAll('.lazy');

    lazyImages.forEach(img => {
        // Verifica se a imagem está dentro da visualização do usuário
        if (img.getBoundingClientRect().top < window.innerHeight && img.getBoundingClientRect().bottom > 0) {
            // Carrega a imagem definindo o valor do atributo "src" para o valor do atributo "data-src"
            img.src = img.getAttribute('data-src');
            img.classList.remove('lazy'); // Remove a classe "lazy" após carregar a imagem
        }
    });
}

// Adiciona um evento de rolagem para verificar quando as imagens estão prestes a entrar na visualização do usuário
document.addEventListener('scroll', lazyLoadImages);
window.addEventListener('resize', lazyLoadImages);
window.addEventListener('orientationchange', lazyLoadImages);

// Chama a função de carregamento preguiçoso para carregar as imagens que já estão na visualização do usuário
lazyLoadImages();


function disableRightClick(event) {
    if (event.button == 2 || event.which == 3) {
        event.preventDefault();
        return false;
    }
}

document.addEventListener('contextmenu', disableRightClick);


// notification.js

// Função para gerar um nome aleatório
function randomName() {
    var names = ["Miguel","Jane", "Marcos", "Natanael", "Gael", "Theo", "Sandra", "Geovane", "Cida", "Ingrid", "Anderson", "Angelo", "Jéssica", "Patricia", "Kauan", "Sophia", "Davi", "Viviane", "Monica", "Maicon", "Nelson", "Andreia", "Julia", "Arthur", "Edson", "Alice", "Gabriel", "Manuela", "Pedro", "Isabella", "Lucas", "Laura", "Matheus", "Maria Eduarda", "Bernardo", "Giovanna", "Rafael", "Valentina", "Guilherme", "Beatriz", "Enzo", "Luiza", "Felipe", "Helena", "Gustavo", "Maria Luiza", "Nicolas", "Isadora", "Heitor", "Mariana", "Cleiton", "Samuel", "Gabriela", "João Pedro", "Ana Clara", "Pedro Henrique", "Rafaela", "Cauã", "Maria Clara", "Henrique", "Isabelly", "Murilo", "Yasmin", "Eduardo", "Ana Julia", "Vitor", "Lívia", "Daniel", "Lara", "Lorenzo", "Lorena", "Vinicius", "Heloísa", "Pietro", "Melissa", "João Vitor", "Sarah", "Leonardo", "Ana Luiza", "Théo", "Letícia", "Caio", "Nicole", "Isaac", "Ana Beatriz", "Lucca", "Emanuelly", "João", "Esther", "Davi Lucas", "Lavínia", "Enzo Gabriel", "Marina", "Yuri", "Cecília", "Bryan", "Rebeca", "Thiago", "Vitória", "João Gabriel", "", "Maria Fernanda", "Benjamin", "Larissa", "Joaquim", "Clara", "Emanuel", "Carolina", "Thomas", "Bianca", "Ryan", "Alícia", "Carlos Eduardo", "Fernanda", "Rodrigo", "Gabrielly", "Ian", "Rubia","Catarina", "Fernando", "Ana Laura", "Bruno", "Emilly", "Otávio", "Eduarda", "Francisco", "Karoline", "Thaina", "Amanda", "Calebe", "Pietra", "Igor", "Agatha", "Antonio", "Jorge", "Milena", "Erick", "Maria Alice", "João Lucas", "Laís", "Luiz Felipe", "Maria Julia", "André", "Maria", "Davi Lucca", "Elisa", "Kaique", "Stella", "Nathan", "Maria Vitória", "Higor", "Luiz Miguel", "Bruna", "Breno", "Ana Sophia", "Vitor Hugo", "Bárbara", "João Guilherme", "Maria Cecília", "Benício", "Olivia", "Augusto", "Nathalia", "João Miguel", "Camila", "Pedro Lucas", "Ana Carolina", "Levi", "Maitê", "Anthony", "Eloá", "Yago", "Luana", "Danilo", "Luna", "Juan", "Ana Lívia", "Kauê", "Brenda", "Diego", "Alana", "Vicente", "Sophie", "André", "Davi Luiz", "Ana", "Luiz Gustavo", "Isabel", "Alexandre", "Marco", "Mirella", "Alex", "Raul", "Juliana", "Silvio", "Luan", "Jean", "Marcela", "Diogo", "Isis", "Marcelo", "Iara", "Ricardo", "Antônia", "Luiz Henrique", "Kamilly", "Henry", "Sofia", "Alexia", "Noah", "Lis", "Enrico", "Renato", "Maria Sophia", "Lucas Gabriel", "Debora", "Joana", "Renan", "Clarice", "Neide", "Luiz Otávio", "Ayla", "Pedro Miguel", "Caroline", "William", "Antonella", "Ícaro", "Evellyn", "Giovanni", "Malu", "João Paulo", "Maria Laura", "Paulo", "Mikaela", "Adryan", "Stefany"]; // Lista de nomes
    return names[Math.floor(Math.random() * names.length)]; // Retorna um nome aleatório da lista
}

// Função para gerar um valor de compra aleatório
function randomValue() {
    var values = [29.90, 74.90, 189.90]; // Valores permitidos
    return values[Math.floor(Math.random() * values.length)]; // Retorna um valor aleatório da lista
}

// Função para exibir a notificação de compra
function showNotification() {
    var purchaseNotification = document.getElementById('purchaseNotification');
    var name = randomName(); // Gera um nome aleatório
    var value = randomValue().toFixed(2); // Gera um valor de compra aleatório e arredonda para duas casas decimais
    var action = Math.random() < 0.5 ? "comprou" : "renovou"; // Escolhe aleatoriamente entre "comprou" e "renovou"
    purchaseNotification.textContent = name + " " + "renovou" + " por R$" + value; // Define o conteúdo da notificação
    purchaseNotification.style.left = '10px'; // Move a notificação para a posição visível
    setTimeout(function() {
        purchaseNotification.style.left = '-200px'; // Move a notificação para fora da tela após 5 segundos
    }, 5000);
}

// Exibe uma notificação inicial após 10 a 20 segundos
setTimeout(showNotification, Math.floor(Math.random() * (20000 - 10000) + 10000)); // Exibe a primeira notificação após um intervalo aleatório entre 10 e 20 segundos

// Exibe notificações de compra em loop
setInterval(showNotification, Math.floor(Math.random() * (90000 - 30000) + 60000)); // Exibe uma notificação a cada intervalo aleatório entre 30 e 60 segundos


// JavaScript para repetir a animação a cada 5 segundos
setInterval(function() {
    $('.whatsapp-button').toggleClass('swing');
}, 5000);


// Script para incrementar o número de downloads 

        // Função para aumentar o contador de downloads
        function aumentarDownloads() {
            // Recupera o elemento do contador de downloads
            var downloadsCounter = document.getElementById('downloads-counter');

            // Obtém o valor atual do contador de downloads
            var currentCount = parseInt(downloadsCounter.dataset.count);

            // Incrementa o contador
            var newCount = currentCount + 1;

            // Atualiza o valor do contador de downloads no DOM
            downloadsCounter.textContent = newCount;
            downloadsCounter.dataset.count = newCount;
        }

        // Chama a função para aumentar o contador de downloads ao carregar a página
        window.onload = aumentarDownloads;



        // Script para mostrar a notificação de cookie após 5 segundos e escondê-lo após 30 segundos //

        // Função para definir um cookie
        function setCookie(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toUTCString();
            document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
        }

        // Função para obter um cookie
        function getCookie(cname) {
            var name = cname + "=";
            var decodedCookie = decodeURIComponent(document.cookie);
            var ca = decodedCookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        }

        // Função para fechar a notificação de cookie
        function fecharNotificacao() {
            document.getElementById('cookieNotification').style.display = 'none';
        }

        // Exibir a notificação de cookie apenas se o cookie de notificação não estiver definido
        if (!getCookie("cookieNotification")) {
            setTimeout(function(){
                document.getElementById('cookieNotification').style.display = 'block';
                setTimeout(function(){
                    setCookie("cookieNotification", "true", 30); // Define um cookie chamado "cookieNotification" com valor "true" que expira em 30 dias
                    fecharNotificacao(); // Fecha a notificação após 30 segundos
                }, 30000); // Esconde a notificação após 30 segundos
            }, 5000); // Exibe a notificação após 5 segundos
        }


// Seleciona todas as perguntas
const faqQuestions = document.querySelectorAll('.faq-question');

// Adiciona um evento de clique a cada pergunta
faqQuestions.forEach(question => {
    question.addEventListener('click', () => {
        // Toggle class 'open' para a pergunta clicada
        question.parentElement.classList.toggle('open');
    });
});

//desabilitar f12
if (document.addEventListener) {
    document.addEventListener("contextmenu", function(e) {
        e.preventDefault();
        return false;
    });
} else { //Versões antigas do IE
    document.attachEvent("oncontextmenu", function(e) {
        e = e || window.event;
        e.returnValue = false;
        return false;
    });
}
        