(function($) {
    'use strict';
    $.fn.sqrFactPano = function() {
        $(this).each(function() {
            var container = $(this);
            var img = $(this).find('img');
            var ratio = parseFloat(img.attr('height')) / parseFloat(img.attr('width'));
            var maxOffset = 0;
            var h2 = $(this).find('h2');
            var p = $(this).find('p');
            var div = $(this).find('div');
            var fadeIn = h2.hasClass('sqrfactpanofadein');

            function size() {
                var width = container.width();
                var height = container.height();

                var imgWidth = width;
                var imgHeight = Math.floor(imgWidth * ratio);

                if (imgHeight < Math.floor(height * 1.3)) {
                    imgHeight = Math.floor(height * 1.3);
                    imgWidth = Math.floor(imgHeight / ratio);
                }

                maxOffset = imgHeight - height;


                img.css({
                    'width': imgWidth + 'px',
                    'height': imgHeight + 'px',
                    'left': Math.floor((width - imgWidth) / 2) + 'px'
                });

                place();
            }

            function place() {
                var containerTop = container.offset().top;
                var containerHeight = container.height();
                var windowheight = $(window).height();
                var scrolltop = $(window).scrollTop();

                var top = scrolltop + windowheight - containerTop;
                var range = windowheight + containerHeight;
                var offset = -Math.floor((1 - (top / range)) * maxOffset);

                img.css('transform', 'translateY(' + offset + 'px)');

                if (fadeIn) {
                    if (containerTop + containerHeight / 2 < scrolltop + windowheight) {
                        fadeIn = false;
                        h2.removeClass('sqrfactpanofadein');
                        window.setTimeout(function() {
                            p.removeClass('sqrfactpanofadein');
                        }, 400);
                        window.setTimeout(function() {
                          div.removeClass('sqrfactpanofadein');
                        }, 800);
                    }
                }
            }

            $(window).on('scroll', place);
            $(window).on('resize', size);
			
			$(window).on('load', size);
            size();
        });
    };
})(jQuery);

$(document).ready(function() {
    $('.sqrfactpano').sqrFactPano();
});
