(function ($) {
	"use strict";
	
	$(window).on('load', function () {
		qodefStickySidebar.init();
	});
	
	var qodefStickySidebar = {
		init: function () {
			var info = $('.widget_alloggio_core_sticky_sidebar');
			
			if (info.length && qodefCore.windowWidth > 1024) {
				info.wrapper = info.parents('#qodef-page-sidebar');
				info.c = 24;
				info.offsetM = info.offset().top - info.wrapper.offset().top;
				info.adj = 15;
				
				qodefStickySidebar.callStack(info);
				
				$(window).on('resize', function () {
					if (qodefCore.windowWidth > 1024) {
						qodefStickySidebar.callStack(info);
					}
				});
				
				$(window).on('scroll', function () {
					if (qodefCore.windowWidth > 1024) {
						qodefStickySidebar.infoPosition(info);
					}
				});
			}
		},
		calc: function (info) {
			var content = $('.qodef-page-content-section'),
				headerH = qodefCore.body.hasClass('qodef-header-appearance--none') ? 0 : parseInt(qodefGlobal.vars.headerHeight, 10);
			
			info.start = content.offset().top;
			info.end = content.outerHeight();
			info.h = info.wrapper.height();
			info.w = info.outerWidth();
			info.left = info.offset().left;
			info.top = headerH + qodefGlobal.vars.adminBarHeight + info.c - info.offsetM;
			info.data('state', 'top');
		},
		infoPosition: function (info) {
			if (qodefCore.scroll < info.start - info.top && qodefCore.scroll + info.h && info.data('state') !== 'top') {
				TweenMax.to(info.wrapper, .1, {
					y: 5,
				});
				TweenMax.to(info.wrapper, .3, {
					y: 0,
					delay: .1,
				});
				info.data('state', 'top');
				info.wrapper.css({
					'position': 'static',
				});
			} else if (qodefCore.scroll >= info.start - info.top && qodefCore.scroll + info.h + info.adj <= info.start + info.end &&
				info.data('state') !== 'fixed') {
				var c = info.data('state') === 'top' ? 1 : -1;
				info.data('state', 'fixed');
				info.wrapper.css({
					'position': 'fixed',
					'top': info.top,
					'left': info.left,
					'width': info.w
				});
				TweenMax.fromTo(info.wrapper, .2, {
					y: 0
				}, {
					y: c * 10,
					ease: Power4.easeInOut
				});
				TweenMax.to(info.wrapper, .2, {
					y: 0,
					delay: .2,
				});
			} else if (qodefCore.scroll + info.h + info.adj > info.start + info.end && info.data('state') !== 'bottom') {
				info.data('state', 'bottom');
				info.wrapper.css({
					'position': 'absolute',
					'top': info.end - info.h - info.adj,
					'left': 0,
				});
				TweenMax.fromTo(info.wrapper, .1, {
					y: 0
				}, {
					y: -5,
				});
				TweenMax.to(info.wrapper, .3, {
					y: 0,
					delay: .1,
				});
			}
		},
		callStack: function (info) {
			this.calc(info);
			this.infoPosition(info);
		}
	};
	
})(jQuery);