"use strict";

(function ($) {


	/**
	 * Window load function
	 */
	$(window).load(function () {

		/**
		 * Sticky Header
		 */
		var headerBox = $('.site-header'),
			stickyArea = headerBox.children('.sticky-area'),
			stickyType = stickyArea.attr('data-type'),
			headerHeight = 0,
			lastScrollTop = 0;

		function dotspiceStickyHeader() {
			var windowScrollTop = $(window).scrollTop(),
				htmlMargin = parseInt($('html').css('marginTop'), 10),
				headeBoxOffsetTop = parseInt($(headerBox).offset().top - htmlMargin, 10);

			// Disable on Mobile
			if (window.matchMedia("(max-width: 1200px)").matches) {
				stickyArea.removeClass('sticky pinned no-transition');
				stickyArea.css('margin-top', 'auto');
				headerBox.css('height', 'auto');

				return;
			}

			// Set Height
			if (headerHeight == 0) {
				headerHeight = headerBox.height();
			}

			// Stick
			if (windowScrollTop > (headerHeight + htmlMargin + headeBoxOffsetTop)) {
				if (!stickyArea.hasClass('sticky')) {
					headerBox.css('height', headerHeight + 'px');
					stickyArea.css({ 'margin-top': htmlMargin }).addClass('sticky no-transition');
				}
			}

			// Unstick
			if (windowScrollTop <= headerHeight - stickyArea.innerHeight() + headeBoxOffsetTop) {
				headerBox.css('height', 'auto');
				stickyArea.css({ 'margin-top': 0 }).removeClass('sticky pinned no-transition');
			}

			// Pinned
			if (stickyArea.is('.sticky')) {
				stickyArea.removeClass('no-transition');

				// Type Scroll
				if (stickyType == 'scroll') {
					stickyArea.addClass('pinned');
				}

				// Type Only Scroll Up
				else {
					if (lastScrollTop > windowScrollTop) {
						stickyArea.addClass('pinned');
					}
					else if (lastScrollTop < windowScrollTop) {
						stickyArea.removeClass('pinned');
					}
				}
				lastScrollTop = windowScrollTop;
			};
		}
		dotspiceStickyHeader();


		/**
		 * Scroll Functions
		 */
		$(window).scroll(function () {
			dotspiceStickyHeader();
		});


		/**
		 * Resize Functions
		 */
		$(window).resize(function () {
			clearTimeout(window.stickyResized);

			window.stickyResized = setTimeout(function () {
				dotspiceStickyHeader();
			}, 100);
		});

	});

})(jQuery);