/*
 * Author: Evgeniy Gusarov StMechanus (Diversant)
 * Under the MIT License
 *
 * Version: 2.0.1
 *
 */


;
(function ($) {

    var RDParallax = function (element, options) {
        this.options = options;

        this.settings = {
            'imageClass': 'parallax_image',
            'patternClass': 'parallax_pattern',
            'contentClass': 'parallax_cnt',
            'wrapClass': 'parallax'
        }

        this.$wrap = $(element);

        this.$image = $.noop();
    };

    RDParallax.prototype = {
        init: function () {
            var parallax = this;
            parallax.isInit = true;
            parallax.createDOM();
            parallax.blur();
            parallax.createListeners();
        },

        createDOM: function () {
            var parallax = this;

            parallax
                .$wrap
                .addClass(parallax.settings.wrapClass)
                .wrapInner($('<div/>', {
                    'class': parallax.settings.contentClass
                }))
                .prepend($('<div/>', {
                    'class': (parallax.options.pattern ? parallax.settings.patternClass : parallax.settings.imageClass)
                }).css({
                    'background-image': 'url(' + parallax.options.url + ')',
                    'background-color': parallax.options.color
                }));

            parallax.$image = parallax.options.pattern ? parallax.$wrap.find('.' + parallax.settings.patternClass) : parallax.$wrap.find('.' + parallax.settings.imageClass);
        },

        createListeners: function () {
            this.createResizeListener();
            this.createScrollListener();
        },

        createScrollListener: function () {
            var parallax = this;

            if (parallax.isMobile()) {
                if (!parallax.options.mobile) {
                    return;
                }
            }

            $(window).bind('touchstart', function () {
                parallax.isTouched = true;
            });

            $(window).bind('touchend', function () {
                if(parallax.timer){
                    clearTimeout(parallax.timer);
                }

                parallax.timer = setTimeout(function () {
                    parallax.isTouched = false;
                }, 1200);
            });

            $(window).bind('scroll', function () {
                parallax.move();
            });
            parallax.move();
        },

        createResizeListener: function () {
            var parallax = this;

            if (parallax.isMobile()) {
                if (!parallax.options.mobile) {
                    return;
                }
            }

            if (!parallax.isMobile()) {
                $(window).bind('resize', function () {
                    parallax.resize();
                });
            }

            $(window).bind('orientationchange', function () {
                setTimeout(function () {
                    parallax.resize();
                }, 300);
            });

            parallax.resize();
        },

        move: function () {
            var parallax = this;

            if (!parallax.isVisible()) {
                return;
            }

            if (parallax.isMobile()) {
                if (!parallax.options.mobile) {
                    return;
                }
            }

            var st = $(window).scrollTop(),
                off = parallax.$wrap.offset().top,
                wh = $(window).height(),
                h = parallax.$wrap.outerHeight(),
                ph = parallax.$image.height();

            var speed = parallax.options.speed;
            if (speed < 0) {
                speed = 0;
            }
            if (speed > 1) {
                speed = 1;
            }

            var step = (st - (off - wh)) / ((off + h) - (off - wh)) * speed;


            if (parallax.options.direction == 'normal') {
                var pos = step * (h - ph);
            } else {
                var pos = (1 - step) * (h - ph);
            }

            if (parallax.isIE() && parallax.ieVersion() <= 10) {
                parallax.$image.css('top', '' + pos + 'px');
            }
            else if (parallax.isMobile() && parallax.options.mobile) {
                if (parallax.isTouched || parallax.isInit) {
                    parallax.$image.stop().animate({pos: pos}, {
                        step: function (pos) {
                            $(this).css('transform', 'translate3d(0, ' + pos + 'px, 0)');
                        },
                        duration: parallax.options.duration
                    }, parallax.options.easing);

                    parallax.isInit = false;
                }
            } else {
                parallax.$image.css('transform', 'translate3d(0, ' + pos + 'px, 0)');
            }

            if (parallax.isFirefox() && window.devicePixelRatio < 1){
                parallax.$image.css('background-color', '#010101');

                setTimeout(function () {
                    parallax.$image.css('background-color', parallax.options.color);
                }, 10);
            }
        },

        resize: function () {
            var parallax = this,
                h = Math.max($(window).height(), 500);

            if(h < parallax.$wrap.outerHeight()){
                h = parallax.$wrap.outerHeight() + $(window).height() * parallax.options.speed;
            }

            parallax.$image.height(h);

            setTimeout(function () {
                parallax.move();
                parallax.blur();
            }, 300);
        },

        blur: function () {
            var parallax = this;

            if (parallax.options.blur && !parallax.isIE() && !parallax.options.pattern) {

                $('<img/>', {src: parallax.options.url}).load(function () {
                    var dh = parallax.$image.height() / this.height,
                        dw = parallax.$image.width() / this.width,
                        blur = Math.floor(Math.max(dh, dw));


                    if (blur > 2) {
                        parallax.$image.css({
                            'filter': 'blur(' + blur + 'px)',
                            '-webkit-filter': 'blur(' + blur + 'px)'
                        });
                    } else {
                        parallax.$image.css({
                            'filter': 'blur(' + 0 + 'px)',
                            '-webkit-filter': 'blur(' + 0 + 'px)'
                        });
                    }
                });

            }
        },

        isVisible: function () {
            var parallax = this,

                windowScroll = $(window).scrollTop(),
                windowHeight = $(window).height(),
                parallaxOffset = parallax.$wrap.offset().top,
                parallaxHeight = parallax.$wrap.outerHeight();

            return (parallaxOffset + parallaxHeight >= windowScroll) && (parallaxOffset <= windowScroll + windowHeight)
        },

        isIE: function () {
            if (navigator.appVersion.indexOf("MSIE") != -1) {
                return true;
            }
            return false;
        },

        isMobile: function () {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        },

        ieVersion: function () {
            return parseFloat(navigator.appVersion.split("MSIE")[1]);
        },

        isFirefox: function () {
            return typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
        }
    };

    $.fn.rdparallax = function (option) {
        var element = this.each(function () {
            var options = $.extend({}, $.fn.rdparallax.defaults, option);

            if (options.url) {
                new RDParallax(this, options).init();
            } else {
                console.error('RD Parallax: data-url is not defined');
            }
        });
        return element;
    };

    $.fn.rdparallax.defaults = {
        speed: 0.4,
        direction: 'normal',
        blur: false,
        mobile: false,
        url: false,
        pattern: false,
        duration: 200,
        easing: 'linear',
        color: 'inherit'
    };

    window.RDParallax_autoinit = function (selector) {
        $(selector).each(function () {
            var options = $.extend({}, $.fn.rdparallax.defaults, {
                url: $(this).data('url'),
                speed: $(this).data('speed'),
                direction: $(this).data('direction'),
                blur: $(this).data('blur'),
                mobile: $(this).data('mobile'),
                pattern: $(this).data('pattern'),
                color: $(this).data('color')
            });

            if (options.url) {
                new RDParallax(this, options).init();
            } else {
                console.error('RD Parallax: data-url is not defined');
            }
        });
    };
})(jQuery);

$(document).ready(function () {
    RDParallax_autoinit('.parallax');
});
