/*
	Stempora Web Framework
	Copyright (c) 2002-2018 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com				
*/


var STBModuleTopintro = Object.create(STBModule.prototype);
STBModuleTopintro.name = "ModuleTopintro";

STBModuleTopintro.initAnimation = function() {
	var intro = $('.centered-content').find('.intro:not(.__done)'),
		body = $('body');

	if (intro.length > 0) {
		intro.each(function () {

			var fadeStart = 0,
				fadeUntil = 350,
				fading = $(this);

			var onScroll = function () {

				if ($("body").hasClass("frozen")) {
					return null;
				}

				var offset = $(document).scrollTop(),
					opacity = 0;

				if (offset <= fadeStart) {
					opacity = 1;
				} else if (offset <= fadeUntil) {
					opacity = 1 - offset / fadeUntil;
				}

				fading.css('opacity', opacity);
			};

			$(window).on('scroll', onScroll);
		});

		intro.addClass("__done");
	}
}

STBModuleTopintro.disable = function() {
	var top = $("body > .topintro");

	if (top.length > 0)	{
		top.remove();
	}
}

STBModuleTopintro.scrollButton = function() {

	var body = $('body'),
		downBtn = function (e) {
		e.preventDefault();


		if ($(".page-wrapper").length) {
			var cont = $(".page-wrapper");
		} else {
			var cont = $(window);
		}

		cont.scrollTo(
			$(".topintro").outerHeight(),
			500
		);
	};

	$('.topintro a.to-down-button').on('click', downBtn);
}

STBModuleTopintro.initButtons = function() {
	var intros = $(".topintro:not(.__done), .widget-topintro-content:not(.__done)");

	if (intros.length) {
		intros.each(function() {
			var buttons = $(this).find(".buttons .btn"),
				max = 0;

			if (buttons.length){
				buttons.each(function() {
					max = Math.max(Math.ceil($(this).outerWidth()) , max);
				});

				buttons.css('width' , max);
			}
		});

		intros.addClass('__done');
	}
}


STBModuleTopintro.pageHasTopIntro =  function() {
	return ($("body").find(".topintro").length > 0);
}

STBModuleTopintro.runOnReady = function() {
	STBModuleTopintro.initButtons();
	STBModuleTopintro.initAnimation();
	STBModuleTopintro.scrollButton();
}

STBModuleTopintro.runOnContentUpdate = function() {
	STBModuleTopintro.initButtons();
	STBModuleTopintro.initAnimation();	
}

STBModuleTopintro.runOnResize = function() {
	STBModuleTopintro.initButtons();
}

site.registerModule(STBModuleTopintro);