/*
jquery-navigationdrawer

The MIT License (MIT)

Copyright (c) 2015 IT Cener RWTH Aachen, RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function ($) {
    'use strict';


    var drawer = {

        htmlRepresentation: null,

        // <summary>helper class for drawer functions</summary>
        slide: function ($element, x, d, complete) {
            /// <summary>animate the elements left css property to target value.</summary>
            /// <param name="$element">jQuery object to be animated</param>
            /// <param name="x">target value for left property</param>
            /// <param name="d">duration of the animation</param>

            // Ignore if drawer is disabled
            if (!isEnabled) {
                return;
            }

            // Ignore if drawer should always be visible
            if (drawerVisibilityHandler.isDrawerAlwaysVisible()) {
                return;
            }

            var _this = this;
            var menuWidth = $element.width();
            // limit x to range [-element.width, 0]
            x = Math.min(Math.max(-menuWidth, x), 0);
            var opacity = Math.max((1 - (x / -menuWidth)) * 0.66, 0.01);
            // Shift x to be used with translate property instead of left
            x += menuWidth;

            var duration = d;
            // Try to calculate animation duration based on current position
            try {
                var translateX = $element.css('transform').split(/[()]/)[1].split(',')[4];
                var distance = Math.abs(parseInt(translateX) - x);
                duration = distance / menuWidth * d;
            } catch (e) {
            }

            var easing = 'easeInOutCubic';
            // Skip ease in when menu is halfway open
            if (duration < d) {
                easing = 'easeOutCubic';
            }
            // Linear easing while sliding menu
            if (duration === 0) {
                easing = 'linear';
            }

            // ---- JQuery Animation ---
            // setup general animation options
            var animationOptions = {
                duration: duration,
                queue: false,
                easing: easing
            };

            // dim background with blender
            $(_this.blenderSelector).velocity({
                opacity: opacity
            }, animationOptions);

            // add complete callback to drawer animation options
            animationOptions.complete = complete;

            // move drawer to target position
            $element.velocity({
                translateX: x
            }, animationOptions);

            //// --- CSS Animation ---
            //if (typeof complete === "function") {
            //    // Only subscribe to transitionend event if the x value is changed
            //    if (x === parseInt($element.css('left'))) { // TODO parse css property correctly, should be supplied as a pixel value
            //        complete();
            //    } else {
            //        var transitionCompleted = function () {
            //            // Unbind both events to avoid executing complete twice
            //            $element.off("transitionend.xxx");
            //            $element.off("webkitTransitionEnd.xxx");
            //            complete();
            //        };
            //        $element.on("transitionend.xxx", transitionCompleted);
            //        $element.on("webkitTransitionEnd.xxx", transitionCompleted);
            //    }
            //}

            //$element.css('transition', 'left ' + d + 'ms');
            //$element.css('left', x);

            //$(_this.blenderSelector).css('transition', 'opacity ' + d + 'ms');
            //$(_this.blenderSelector).css('opacity', Math.max((1 - (x / -$element.width())) * 0.66, 0.01));
        },

        blenderSelector: '.nav-drawer-blender',

        open: function ($element) {
            /// <summary>completely opens the drawer. Animated css left property to 0 in 500ms and displays blender</summary>
            /// <param name="$element">jQuery object to be animated</param>

            this.htmlRepresentation = $element;

            // Ignore if drawer is disabled
            if (!isEnabled) {
                return;
            }

            // Ignore if drawer should always be visible
            if (drawerVisibilityHandler.isDrawerAlwaysVisible()) {
                return;
            }

            var _this = this;
            // make sure to show blender
            $(_this.blenderSelector).show();
            var x = 0;
            this.slide($element, x, 500, function () {
                // make sure to show blender
                $(_this.blenderSelector).show();

                // ... and disable scrolling body
                // TODO currently not working on WP8. OK in Win8.1, Android
                $('body').css('overflow', 'hidden');
            });
        },

        close: function ($element) {
            /// <summary>completely closes the drawer. Animated css left property to -$element.width in 500ms also hides the blender.</summary>
            /// <param name="$element">jQuery object to be animated</param>

            // Ignore if drawer is disabled
            if (!isEnabled) {
                return;
            }

            // Ignore if drawer should always be visible
            if (drawerVisibilityHandler.isDrawerAlwaysVisible()) {
                return;
            }

            var _this = this;
            var x = -$element.width();
            this.slide($element, x, 500, function () {
                // after animation completes hide blender
                $(_this.blenderSelector).hide();
                // ... and allow scrolling body
                $('body').css('overflow', '');
            });
        },

        reInit: function ($element) {

            var isDrawerAlwaysVisible = drawerVisibilityHandler.isDrawerAlwaysVisible();

            if (!isDrawerAlwaysVisible) {

                this.open($element);
            }
        }
    };

    var isEnabled = true;

    var drawerVisibilityHandler = (function () {
        var drawerAlwaysVisible = false;

        var neverAlwaysVisible = false;
        var blockNeverAlwaysVisibleTrue = false;

        var lockAlwaysVisible = false;

        var orientationChanged = function () {

            var visibleState = false;

            if (!lockAlwaysVisible) {

                if ($(window).width() > 992 && isEnabled) {

                    visibleState = true;
                    neverAlwaysVisible = false;
                    blockNeverAlwaysVisibleTrue = true;
                }
                else {

                    visibleState = false;

                    if (!blockNeverAlwaysVisibleTrue) {

                        neverAlwaysVisible = true;
                    }
                }
            }
            else {

                visibleState = false;
            }

            setDrawerAlwaysVisible(visibleState);
        };

        var init = function () {
            this.orientationChanged();
        };

        var checkBlock = function () {

            if ($(window).width() > 992) {

                blockNeverAlwaysVisibleTrue = true;
                neverAlwaysVisible = false;
                return neverAlwaysVisible;
            }
            
            neverAlwaysVisible = true;

            return neverAlwaysVisible;
        };

        var isDrawerAlwaysVisible = function () {

            return drawerAlwaysVisible;
        }

        var setDrawerAlwaysVisible = function (alwaysVisible) {

            drawerAlwaysVisible = alwaysVisible;

            if (alwaysVisible === true) {

                $('body').addClass('always-show-nav-drawer');
                return;
            }

            $('body').removeClass('always-show-nav-drawer');
        }

        var isNeverAlwaysVisible = function () {

            return neverAlwaysVisible;
        };

        var setLockAlwaysVisible = function (localLockAlwaysVisible) {

            lockAlwaysVisible = localLockAlwaysVisible
        }

        return {
            orientationChanged: orientationChanged,
            init: init,
            isDrawerAlwaysVisible: isDrawerAlwaysVisible,
            setDrawerAlwaysVisible: setDrawerAlwaysVisible,
            isNeverAlwaysVisible: isNeverAlwaysVisible,
            checkBlock: checkBlock,
            setLockAlwaysVisible: setLockAlwaysVisible
        }

    })();

    $.fn.navdrawer = function (action, options) {
        /// <summary>Create a navigation drawer from jQuery object.</summary>
        /// <param name="action">'init', 'open', 'close'
        ///     <para/>'init' or undefined - initialize drawer on element 
        ///     <para/>'open' - completely open drawer
        ///     <para/>'close' - completely close drawer
        ///     <para/>'isAlwaysVisible' - returns true if the drawer is always visible
        ///     <para/>'enable' - drawer can be opened and closed
        ///     <para/>'disable' - drawer cannot be opened anymore
        /// </param>
        /// <param name="options">for future use</param>

        var $this = this;

        if (action === 'open') {

            // open drawer
            drawer.open($this);
        }
        else if (action === 'close') {

            // close drawer
            drawer.close($this);
        }
        else if (action === 'isAlwaysVisible') {

            return drawerVisibilityHandler.isDrawerAlwaysVisible();
        }
        else if (action === 'reinit') {

            var oldState = drawerVisibilityHandler.isDrawerAlwaysVisible();

            if (oldState === false) {

                drawer.close($this);

                setTimeout(function () {

                    drawerVisibilityHandler.setDrawerAlwaysVisible(options);
                }, 1000);
            }
            else {

                drawerVisibilityHandler.setDrawerAlwaysVisible(options);
                drawer.reInit($this);
            }
        }
        else if (action === 'isNeverAlwaysVisible') {

            return drawerVisibilityHandler.isNeverAlwaysVisible();
        }
        else if (action === 'smallDeviceSupport') {
            
            return drawerVisibilityHandler.checkBlock();
        }
        else if (action === 'lockAlwaysVisible') {

            drawerVisibilityHandler.setLockAlwaysVisible(options);
        }
        else if (action === 'enable') {

            isEnabled = true;
            // Trigger orientation change to adjust padding
            drawerVisibilityHandler.orientationChanged();
        }
        else if (action === 'disable') {

            isEnabled = false;
            drawer.close($this);
            // Trigger orientation change to adjust padding
            drawerVisibilityHandler.orientationChanged();
        }
        else {

            if ($this.hasClass('nav-drawer')) {
                // already initializes do nothing
                return;
            }

            $this.addClass('nav-drawer');

            // prepare settings with default values
            var settings = $.extend({
                swipeTarget: 'body',
                closeOnClick: false,
            }, options || {});

            // Bind events to always show drawer on wide screens
            drawerVisibilityHandler.init();
            window.addEventListener('orientationchange', function () {
                // Browsers need time to set new dimensions
                setTimeout(function () {
                    var oldVisibility = drawerVisibilityHandler.isDrawerAlwaysVisible();
                    drawerVisibilityHandler.orientationChanged();

                    // If visibility changed
                    if (oldVisibility !== drawerVisibilityHandler.isDrawerAlwaysVisible()) {

                        // Open or close drawer (without animation)
                        if (drawerVisibilityHandler.isDrawerAlwaysVisible()) {

                            $this.css({ left: 0, transition: 'none' });

                            // when menu has been slided out or just opened transform style has been set
                            // to prevent positioning to far right remove transform attribute (spots on
                            // orientation changed, when drawer is always visible)
                            if (drawer.htmlRepresentation) {

                                drawer.htmlRepresentation.css("transform", "");
                            }
                        }
                        else {

                            $this.css({ left: -$this.width(), transition: 'none' });
                        }

                        $(drawer.blenderSelector).hide();

                        // Trigger event to inform listeners that visibility changed
                        $this.trigger('drawerVisibilityStateChange');

                        // TODO issue with keyboard in landscape?
                    }
                }, 200);
            }, false);

            // Bind handler to automatically close navigation on item select
            if (settings.closeOnClick) {
                $this.on('click.itemSelect', 'a', function () {

                });
            }

            if ($(drawer.blenderSelector).length == 0) {
                // if no blender found in DOM insert blender
                $('<div>')
                    .addClass(drawer.blenderSelector.replace('.', ''))
                    .click(function () {
                        drawer.close($this);
                    })
                    .css('opacity', '0.1')
                    .hide()
                    .appendTo(settings.swipeTarget);
            }

            $(settings.swipeTarget).hammer({
                prevent_default: false
            }).on('panstart', function (ev) {
                if (ev.gesture.center.x - $this.width() - $this.offset().left < 40 &&
                    (ev.gesture.direction & Hammer.DIRECTION_HORIZONTAL) != 0 &&
                    !drawerVisibilityHandler.isDrawerAlwaysVisible()) {
                    // if gesture starts close to the border of the drawer start sliding
                    $this.data('isSliding', true);
                    $this.data('offset', $this.offset().left);

                    $(drawer.blenderSelector).show();
                };
            });

            $(settings.swipeTarget).hammer({
                prevent_default: false
            }).on('pan', function (ev) {
                if ($this.data('isSliding') === true) {
                    // move drawer to current thumb position 
                    //var x = ev.gesture.center.x - $this.width() - 40;
                    var x = $this.data('offset') + ev.gesture.deltaX;// - $this.width() - 40;
                    drawer.slide($this, x, 0);
                }
            });

            var panendHandler = function (ev) {
                if ($this.data('isSliding') === true) {
                    //if (ev.gesture.center.x < $this.width() / 2) {
                    var velocityX = ev.gesture.velocityX;
                    if ((-$this.offset().left > $this.width() / 2 && velocityX > -0.3) || velocityX > 0.5) {
                        // once panning has ended and drawer is less than half open: close it
                        drawer.close($this);
                    } else {
                        // otherwise open drawer
                        drawer.open($this);
                    }
                }

                $this.data('isSliding', false);
            };

            $(settings.swipeTarget).hammer({
                prevent_default: false
            }).on('panend', panendHandler);

            // Sometimes, pancancel is called instead of panend, also a workaround for strange windows phone behaviour 
            $(settings.swipeTarget).hammer({
                prevent_default: false
            }).on('pancancel', panendHandler);
        }
        return $this;
    };
}(jQuery));