<commit_before>(function(factory) {
    'use strict';

    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {
    'use strict';

    // Polyfill Number.isNaN(value)
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
    Number.isNaN = Number.isNaN || function(value) {
        return typeof value === 'number' && value !== value;
    };

    /**
     * Range feature detection
     * @return {Boolean}
     */
    function supportsRange() {
        var input = document.createElement('input');
        input.setAttribute('type', 'range');
        return input.type !== 'text';
    }

    var pluginName = 'rangeslider',
        pluginIdentifier = 0,
        hasInputRangeSupport = supportsRange(),
        defaults = {
            polyfill: true,
            orientation: 'horizontal',
            rangeClass: 'rangeslider',
            disabledClass: 'rangeslider--disabled',
            horizontalClass: 'rangeslider--horizontal',
            verticalClass: 'rangeslider--vertical',
            fillClass: 'rangeslider__fill',
            handleClass: 'rangeslider__handle',
            startEvent: ['mousedown', 'touchstart', 'pointerdown'],
            moveEvent: ['mousemove', 'touchmove', 'pointermove'],
            endEvent: ['mouseup', 'touchend', 'pointerup']
        },
        constants = {
            orientation: {
                horizontal: {
                    dimension: 'width',
                    direction: 'left',
                    directionStyle: 'left',
                    coordinate: 'x'
                },
                vertical: {
                    dimension: 'height',
                    direction: 'top',
                    directionStyle: 'bottom',
                    coordinate: 'y'
                }
            }
        };

    /**
     * Delays a function for the given number of milliseconds, and then calls
     * it with the arguments supplied.
     *
     * @param  {Function} fn   [description]
     * @param  {Number}   wait [description]
     * @return {Function}
     */
    function delay(fn, wait) {
        var args = Array.prototype.slice.call(arguments, 2);
        return setTimeout(function(){ return fn.apply(null, args); }, wait);
    }

    /**
     * Returns a debounced function that will make sure the given
     * function is not triggered too much.
     *
     * @param  {Function} fn Function to debounce.
     * @param  {Number}   debounceDuration OPTIONAL. The amount of time in milliseconds for which we will debounce the function. (defaults to 100ms)
     * @return {Function}
     */
    function debounce(fn, debounceDuration) {
        debounceDuration = debounceDuration || 100;
        return function() {
            if (!fn.debouncing) {
                var args = Array.prototype.slice.apply(arguments);
                fn.lastReturnVal = fn.apply(window, args);
                fn.debouncing = true;
            }
            clearTimeout(fn.debounceTimeout);
            fn.debounceTimeout = setTimeout(function(){
                fn.debouncing = false;
            }, debounceDuration);
            return fn.lastReturnVal;
        };
    }

    /**
     * Check if a `element` is visible in the DOM
     *
     * @param  {Element}  element
     * @return {Boolean}
     */
    function isHidden(element) {
        return (
            element && (
                element.offsetWidth === 0 ||
                element.offsetHeight === 0 ||
                // Also Consider native `<details>` elements.
                element.open === false
            )
        );
    }

    /**
     * Get hidden parentNodes of an `element`
     *
     * @param  {Element} element
     * @return {[type]}
     */
    function getHiddenParentNodes(element) {
        var parents = [],
            node    = element.parentNode;

        while (isHidden(node)) {
            parents.push(node);
            node = node.parentNode;
        }
        return parents;
    }

    /**
     * Returns dimensions for an element even if it is not visible in the DOM.
     *
     * @param  {Element} element
     * @param  {String}  key     (e.g. offsetWidth …)
     * @return {Number}
     */
    function getDimension(element, key) {
        var hiddenParentNodes       = getHiddenParentNodes(element),
            hiddenParentNodesLength = hiddenParentNodes.length,
            inlineStyle             = [],
            dimension               = element[key];

        // Used for native `<details>` elements
        function toggleOpenProperty(element) {
            if (typeof element.open !== 'undefined') {
                element.open = (element.open) ? false : true;
            }
        }

        if (hiddenParentNodesLength) {
            for (var i = 0; i < hiddenParentNodesLength; i++) {

                // Cache style attribute to restore it later.
                inlineStyle[i] = hiddenParentNodes[i].style.cssText;

                // visually hide
                if (hiddenParentNodes[i].style.setProperty) {
                    hiddenParentNodes[i].style.setProperty('display', 'block', 'important');
                } else {
                    hiddenParentNodes[i].style.cssText += ';display: block !important';
                }
                hiddenParentNodes[i].style.height = '0';
                hiddenParentNodes[i].style.overflow = 'hidden';
                hiddenParentNodes[i].style.visibility = 'hidden';
                toggleOpenProperty(hiddenParentNodes[i]);
            }

            // Update dimension
            dimension = element[key];

            for (var j = 0; j < hiddenParentNodesLength; j++) {

                // Restore the style attribute
                hiddenParentNodes[j].style.cssText = inlineStyle[j];
                toggleOpenProperty(hiddenParentNodes[j]);
            }
        }
        return dimension;
    }

    /**
     * Returns the parsed float or the default if it failed.
     *
     * @param  {String}  str
     * @param  {Number}  defaultValue
     * @return {Number}
     */
    function tryParseFloat(str, defaultValue) {
        var value = parseFloat(str);
        return Number.isNaN(value) ? defaultValue : value;
    }

    /**
     * Capitalize the first letter of string
     *
     * @param  {String} str
     * @return {String}
     */
    function ucfirst(str) {
        return str.charAt(0).toUpperCase() + str.substr(1);
    }

    /**
     * Plugin
     * @param {String} element
     * @param {Object} options
     */
    function Plugin(element, options) {
        this.$window            = $(window);
        this.$document          = $(document);
        this.$element           = $(element);
        this.options            = $.extend( {}, defaults, options );
        this.polyfill           = this.options.polyfill;
        this.orientation        = this.$element[0].getAttribute('data-orientation') || this.options.orientation;
        this.onInit             = this.options.onInit;
        this.onSlide            = this.options.onSlide;
        this.onSlideEnd         = this.options.onSlideEnd;
        this.DIMENSION          = constants.orientation[this.orientation].dimension;
        this.DIRECTION          = constants.orientation[this.orientation].direction;
        this.DIRECTION_STYLE    = constants.orientation[this.orientation].directionStyle;
        this.COORDINATE         = constants.orientation[this.orientation].coordinate;

        // Plugin should only be used as a polyfill
        if (this.polyfill) {
            // Input range support?
            if (hasInputRangeSupport) { return false; }
        }

        this.identifier = 'js-' + pluginName + '-' +(pluginIdentifier++);
        this.startEvent = this.options.startEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.moveEvent  = this.options.moveEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.endEvent   = this.options.endEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.toFixed    = (this.step + '').replace('.', '').length - 1;
        this.$fill      = $('
');
        this.$handle    = $('
');
        this.$range     = $('
').insertAfter(this.$element).prepend(this.$fill, this.$handle);

        // visually hide the input
        this.$element.css({
            'position': 'absolute',
            'width': '1px',
            'height': '1px',
            'overflow': 'hidden',
            'opacity': '0'
        });

        // Store context
        this.handleDown = $.proxy(this.handleDown, this);
        this.handleMove = $.proxy(this.handleMove, this);
        this.handleEnd  = $.proxy(this.handleEnd, this);

        this.init();

        // Attach Events
        var _this = this;
        this.$window.on('resize.' + this.identifier, debounce(function() {
            // Simulate resizeEnd event.
            delay(function() { _this.update(false, false); }, 300);
        }, 20));

        this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);

        // Listen to programmatic value changes
        this.$element.on('change.' + this.identifier, function(e, data) {
            if (data && data.origin === _this.identifier) {
                return;
            }

            var value = e.target.value,
                pos = _this.getPositionFromValue(value);
            _this.setPosition(pos);
        });
    }

    Plugin.prototype.init = function() {
        this.update(true, false);

        if (this.onInit && typeof this.onInit === 'function') {
            this.onInit();
        }
    };

    Plugin.prototype.update = function(updateAttributes, triggerSlide) {
        updateAttributes = updateAttributes || false;

        if (updateAttributes) {
            this.min    = tryParseFloat(this.$element[0].getAttribute('min'), 0);
            this.max    = tryParseFloat(this.$element[0].getAttribute('max'), 100);
            this.value  = tryParseFloat(this.$element[0].value, Math.round(this.min + (this.max-this.min)/2));
            this.step   = tryParseFloat(this.$element[0].getAttribute('step'), 1);
        }

        this.handleDimension    = getDimension(this.$handle[0], 'offset' + ucfirst(this.DIMENSION));
        this.rangeDimension     = getDimension(this.$range[0], 'offset' + ucfirst(this.DIMENSION));
        this.maxHandlePos       = this.rangeDimension - this.handleDimension;
        this.grabPos            = this.handleDimension / 2;
        this.position           = this.getPositionFromValue(this.value);

        // Consider disabled state
        if (this.$element[0].disabled) {
            this.$range.addClass(this.options.disabledClass);
        } else {
            this.$range.removeClass(this.options.disabledClass);
        }

        this.setPosition(this.position, triggerSlide);
    };

    Plugin.prototype.handleDown = function(e) {
        this.$document.on(this.moveEvent, this.handleMove);
        this.$document.on(this.endEvent, this.handleEnd);

        // If we click on the handle don't set the new position
        if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
            return;
        }

        var pos         = this.getRelativePosition(e),
            rangePos    = this.$range[0].getBoundingClientRect()[this.DIRECTION],
            handlePos   = this.getPositionFromNode(this.$handle[0]) - rangePos,
            setPos      = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);

        this.setPosition(setPos);

        if (pos >= handlePos && pos < handlePos + this.handleDimension) {
            this.grabPos = pos - handlePos;
        }
    };

    Plugin.prototype.handleMove = function(e) {
        e.preventDefault();
        var pos = this.getRelativePosition(e);
        var setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
        this.setPosition(setPos);
    };

    Plugin.prototype.handleEnd = function(e) {
        e.preventDefault();
        this.$document.off(this.moveEvent, this.handleMove);
        this.$document.off(this.endEvent, this.handleEnd);

        // Ok we're done fire the change event
        this.$element.trigger('change', { origin: this.identifier });

        if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
            this.onSlideEnd(this.position, this.value);
        }
    };

    Plugin.prototype.cap = function(pos, min, max) {
        if (pos < min) { return min; }
        if (pos > max) { return max; }
        return pos;
    };

    Plugin.prototype.setPosition = function(pos, triggerSlide) {
        var value, newPos;

        if (triggerSlide === undefined) {
            triggerSlide = true;
        }

        // Snapping steps
        value = this.getValueFromPosition(this.cap(pos, 0, this.maxHandlePos));
        newPos = this.getPositionFromValue(value);

        // Update ui
        this.$fill[0].style[this.DIMENSION] = (newPos + this.grabPos) + 'px';
        this.$handle[0].style[this.DIRECTION_STYLE] = newPos + 'px';
        this.setValue(value);

        // Update globals
        this.position = newPos;
        this.value = value;

        if (triggerSlide && this.onSlide && typeof this.onSlide === 'function') {
            this.onSlide(newPos, value);
        }
    };

    // Returns element position relative to the parent
    Plugin.prototype.getPositionFromNode = function(node) {
        var i = 0;
        while (node !== null) {
            i += node.offsetLeft;
            node = node.offsetParent;
        }
        return i;
    };

    Plugin.prototype.getRelativePosition = function(e) {
        // Get the offset DIRECTION relative to the viewport
        var ucCoordinate = ucfirst(this.COORDINATE),
            rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
            pageCoordinate = 0;

        if (typeof e['page' + ucCoordinate] !== 'undefined') {
            pageCoordinate = e['client' + ucCoordinate];
        }
        else if (typeof e.originalEvent['client' + ucCoordinate] !== 'undefined') {
            pageCoordinate = e.originalEvent['client' + ucCoordinate];
        }
        else if (e.originalEvent.touches && e.originalEvent.touches[0] && typeof e.originalEvent.touches[0]['client' + ucCoordinate] !== 'undefined') {
            pageCoordinate = e.originalEvent.touches[0]['client' + ucCoordinate];
        }
        else if(e.currentPoint && typeof e.currentPoint[this.COORDINATE] !== 'undefined') {
            pageCoordinate = e.currentPoint[this.COORDINATE];
        }

        return pageCoordinate - rangePos;
    };

    Plugin.prototype.getPositionFromValue = function(value) {
        var percentage, pos;
        percentage = (value - this.min)/(this.max - this.min);
        pos = (!Number.isNaN(percentage)) ? percentage * this.maxHandlePos : 0;
        return pos;
    };

    Plugin.prototype.getValueFromPosition = function(pos) {
        var percentage, value;
        percentage = ((pos) / (this.maxHandlePos || 1));
        value = this.step * Math.round(percentage * (this.max - this.min) / this.step) + this.min;
        return Number((value).toFixed(this.toFixed));
    };

    Plugin.prototype.setValue = function(value) {
        if (value === this.value && this.$element[0].value !== '') {
            return;
        }

        // Set the new value and fire the `input` event
        this.$element
            .val(value)
            .trigger('input', { origin: this.identifier });
    };

    Plugin.prototype.destroy = function() {
        this.$document.off('.' + this.identifier);
        this.$window.off('.' + this.identifier);

        this.$element
            .off('.' + this.identifier)
            .removeAttr('style')
            .removeData('plugin_' + pluginName);

        // Remove the generated markup
        if (this.$range && this.$range.length) {
            this.$range[0].parentNode.removeChild(this.$range[0]);
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function(options) {
        var args = Array.prototype.slice.call(arguments, 1);

        return this.each(function() {
            var $this = $(this),
                data  = $this.data('plugin_' + pluginName);

            // Create a new instance.
            if (!data) {
                $this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
            }

            // Make it possible to access methods from public.
            // e.g `$element.rangeslider('method');`
            if (typeof options === 'string') {
                data[options].apply(data, args);
            }
        });
    };

}));
<commit_msg>chore: add info how to use plugin to factory<commit_after>(function(factory) {
    'use strict';

    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {
    'use strict';

    // Polyfill Number.isNaN(value)
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
    Number.isNaN = Number.isNaN || function(value) {
        return typeof value === 'number' && value !== value;
    };

    /**
     * Range feature detection
     * @return {Boolean}
     */
    function supportsRange() {
        var input = document.createElement('input');
        input.setAttribute('type', 'range');
        return input.type !== 'text';
    }

    var pluginName = 'rangeslider',
        pluginIdentifier = 0,
        hasInputRangeSupport = supportsRange(),
        defaults = {
            polyfill: true,
            orientation: 'horizontal',
            rangeClass: 'rangeslider',
            disabledClass: 'rangeslider--disabled',
            horizontalClass: 'rangeslider--horizontal',
            verticalClass: 'rangeslider--vertical',
            fillClass: 'rangeslider__fill',
            handleClass: 'rangeslider__handle',
            startEvent: ['mousedown', 'touchstart', 'pointerdown'],
            moveEvent: ['mousemove', 'touchmove', 'pointermove'],
            endEvent: ['mouseup', 'touchend', 'pointerup']
        },
        constants = {
            orientation: {
                horizontal: {
                    dimension: 'width',
                    direction: 'left',
                    directionStyle: 'left',
                    coordinate: 'x'
                },
                vertical: {
                    dimension: 'height',
                    direction: 'top',
                    directionStyle: 'bottom',
                    coordinate: 'y'
                }
            }
        };

    /**
     * Delays a function for the given number of milliseconds, and then calls
     * it with the arguments supplied.
     *
     * @param  {Function} fn   [description]
     * @param  {Number}   wait [description]
     * @return {Function}
     */
    function delay(fn, wait) {
        var args = Array.prototype.slice.call(arguments, 2);
        return setTimeout(function(){ return fn.apply(null, args); }, wait);
    }

    /**
     * Returns a debounced function that will make sure the given
     * function is not triggered too much.
     *
     * @param  {Function} fn Function to debounce.
     * @param  {Number}   debounceDuration OPTIONAL. The amount of time in milliseconds for which we will debounce the function. (defaults to 100ms)
     * @return {Function}
     */
    function debounce(fn, debounceDuration) {
        debounceDuration = debounceDuration || 100;
        return function() {
            if (!fn.debouncing) {
                var args = Array.prototype.slice.apply(arguments);
                fn.lastReturnVal = fn.apply(window, args);
                fn.debouncing = true;
            }
            clearTimeout(fn.debounceTimeout);
            fn.debounceTimeout = setTimeout(function(){
                fn.debouncing = false;
            }, debounceDuration);
            return fn.lastReturnVal;
        };
    }

    /**
     * Check if a `element` is visible in the DOM
     *
     * @param  {Element}  element
     * @return {Boolean}
     */
    function isHidden(element) {
        return (
            element && (
                element.offsetWidth === 0 ||
                element.offsetHeight === 0 ||
                // Also Consider native `<details>` elements.
                element.open === false
            )
        );
    }

    /**
     * Get hidden parentNodes of an `element`
     *
     * @param  {Element} element
     * @return {[type]}
     */
    function getHiddenParentNodes(element) {
        var parents = [],
            node    = element.parentNode;

        while (isHidden(node)) {
            parents.push(node);
            node = node.parentNode;
        }
        return parents;
    }

    /**
     * Returns dimensions for an element even if it is not visible in the DOM.
     *
     * @param  {Element} element
     * @param  {String}  key     (e.g. offsetWidth …)
     * @return {Number}
     */
    function getDimension(element, key) {
        var hiddenParentNodes       = getHiddenParentNodes(element),
            hiddenParentNodesLength = hiddenParentNodes.length,
            inlineStyle             = [],
            dimension               = element[key];

        // Used for native `<details>` elements
        function toggleOpenProperty(element) {
            if (typeof element.open !== 'undefined') {
                element.open = (element.open) ? false : true;
            }
        }

        if (hiddenParentNodesLength) {
            for (var i = 0; i < hiddenParentNodesLength; i++) {

                // Cache style attribute to restore it later.
                inlineStyle[i] = hiddenParentNodes[i].style.cssText;

                // visually hide
                if (hiddenParentNodes[i].style.setProperty) {
                    hiddenParentNodes[i].style.setProperty('display', 'block', 'important');
                } else {
                    hiddenParentNodes[i].style.cssText += ';display: block !important';
                }
                hiddenParentNodes[i].style.height = '0';
                hiddenParentNodes[i].style.overflow = 'hidden';
                hiddenParentNodes[i].style.visibility = 'hidden';
                toggleOpenProperty(hiddenParentNodes[i]);
            }

            // Update dimension
            dimension = element[key];

            for (var j = 0; j < hiddenParentNodesLength; j++) {

                // Restore the style attribute
                hiddenParentNodes[j].style.cssText = inlineStyle[j];
                toggleOpenProperty(hiddenParentNodes[j]);
            }
        }
        return dimension;
    }

    /**
     * Returns the parsed float or the default if it failed.
     *
     * @param  {String}  str
     * @param  {Number}  defaultValue
     * @return {Number}
     */
    function tryParseFloat(str, defaultValue) {
        var value = parseFloat(str);
        return Number.isNaN(value) ? defaultValue : value;
    }

    /**
     * Capitalize the first letter of string
     *
     * @param  {String} str
     * @return {String}
     */
    function ucfirst(str) {
        return str.charAt(0).toUpperCase() + str.substr(1);
    }

    /**
     * Plugin
     * @param {String} element
     * @param {Object} options
     */
    function Plugin(element, options) {
        this.$window            = $(window);
        this.$document          = $(document);
        this.$element           = $(element);
        this.options            = $.extend( {}, defaults, options );
        this.polyfill           = this.options.polyfill;
        this.orientation        = this.$element[0].getAttribute('data-orientation') || this.options.orientation;
        this.onInit             = this.options.onInit;
        this.onSlide            = this.options.onSlide;
        this.onSlideEnd         = this.options.onSlideEnd;
        this.DIMENSION          = constants.orientation[this.orientation].dimension;
        this.DIRECTION          = constants.orientation[this.orientation].direction;
        this.DIRECTION_STYLE    = constants.orientation[this.orientation].directionStyle;
        this.COORDINATE         = constants.orientation[this.orientation].coordinate;

        // Plugin should only be used as a polyfill
        if (this.polyfill) {
            // Input range support?
            if (hasInputRangeSupport) { return false; }
        }

        this.identifier = 'js-' + pluginName + '-' +(pluginIdentifier++);
        this.startEvent = this.options.startEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.moveEvent  = this.options.moveEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.endEvent   = this.options.endEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
        this.toFixed    = (this.step + '').replace('.', '').length - 1;
        this.$fill      = $('
');
        this.$handle    = $('
');
        this.$range     = $('
').insertAfter(this.$element).prepend(this.$fill, this.$handle);

        // visually hide the input
        this.$element.css({
            'position': 'absolute',
            'width': '1px',
            'height': '1px',
            'overflow': 'hidden',
            'opacity': '0'
        });

        // Store context
        this.handleDown = $.proxy(this.handleDown, this);
        this.handleMove = $.proxy(this.handleMove, this);
        this.handleEnd  = $.proxy(this.handleEnd, this);

        this.init();

        // Attach Events
        var _this = this;
        this.$window.on('resize.' + this.identifier, debounce(function() {
            // Simulate resizeEnd event.
            delay(function() { _this.update(false, false); }, 300);
        }, 20));

        this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);

        // Listen to programmatic value changes
        this.$element.on('change.' + this.identifier, function(e, data) {
            if (data && data.origin === _this.identifier) {
                return;
            }

            var value = e.target.value,
                pos = _this.getPositionFromValue(value);
            _this.setPosition(pos);
        });
    }

    Plugin.prototype.init = function() {
        this.update(true, false);

        if (this.onInit && typeof this.onInit === 'function') {
            this.onInit();
        }
    };

    Plugin.prototype.update = function(updateAttributes, triggerSlide) {
        updateAttributes = updateAttributes || false;

        if (updateAttributes) {
            this.min    = tryParseFloat(this.$element[0].getAttribute('min'), 0);
            this.max    = tryParseFloat(this.$element[0].getAttribute('max'), 100);
            this.value  = tryParseFloat(this.$element[0].value, Math.round(this.min + (this.max-this.min)/2));
            this.step   = tryParseFloat(this.$element[0].getAttribute('step'), 1);
        }

        this.handleDimension    = getDimension(this.$handle[0], 'offset' + ucfirst(this.DIMENSION));
        this.rangeDimension     = getDimension(this.$range[0], 'offset' + ucfirst(this.DIMENSION));
        this.maxHandlePos       = this.rangeDimension - this.handleDimension;
        this.grabPos            = this.handleDimension / 2;
        this.position           = this.getPositionFromValue(this.value);

        // Consider disabled state
        if (this.$element[0].disabled) {
            this.$range.addClass(this.options.disabledClass);
        } else {
            this.$range.removeClass(this.options.disabledClass);
        }

        this.setPosition(this.position, triggerSlide);
    };

    Plugin.prototype.handleDown = function(e) {
        this.$document.on(this.moveEvent, this.handleMove);
        this.$document.on(this.endEvent, this.handleEnd);

        // If we click on the handle don't set the new position
        if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
            return;
        }

        var pos         = this.getRelativePosition(e),
            rangePos    = this.$range[0].getBoundingClientRect()[this.DIRECTION],
            handlePos   = this.getPositionFromNode(this.$handle[0]) - rangePos,
            setPos      = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);

        this.setPosition(setPos);

        if (pos >= handlePos && pos < handlePos + this.handleDimension) {
            this.grabPos = pos - handlePos;
        }
    };

    Plugin.prototype.handleMove = function(e) {
        e.preventDefault();
        var pos = this.getRelativePosition(e);
        var setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
        this.setPosition(setPos);
    };

    Plugin.prototype.handleEnd = function(e) {
        e.preventDefault();
        this.$document.off(this.moveEvent, this.handleMove);
        this.$document.off(this.endEvent, this.handleEnd);

        // Ok we're done fire the change event
        this.$element.trigger('change', { origin: this.identifier });

        if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
            this.onSlideEnd(this.position, this.value);
        }
    };

    Plugin.prototype.cap = function(pos, min, max) {
        if (pos < min) { return min; }
        if (pos > max) { return max; }
        return pos;
    };

    Plugin.prototype.setPosition = function(pos, triggerSlide) {
        var value, newPos;

        if (triggerSlide === undefined) {
            triggerSlide = true;
        }

        // Snapping steps
        value = this.getValueFromPosition(this.cap(pos, 0, this.maxHandlePos));
        newPos = this.getPositionFromValue(value);

        // Update ui
        this.$fill[0].style[this.DIMENSION] = (newPos + this.grabPos) + 'px';
        this.$handle[0].style[this.DIRECTION_STYLE] = newPos + 'px';
        this.setValue(value);

        // Update globals
        this.position = newPos;
        this.value = value;

        if (triggerSlide && this.onSlide && typeof this.onSlide === 'function') {
            this.onSlide(newPos, value);
        }
    };

    // Returns element position relative to the parent
    Plugin.prototype.getPositionFromNode = function(node) {
        var i = 0;
        while (node !== null) {
            i += node.offsetLeft;
            node = node.offsetParent;
        }
        return i;
    };

    Plugin.prototype.getRelativePosition = function(e) {
        // Get the offset DIRECTION relative to the viewport
        var ucCoordinate = ucfirst(this.COORDINATE),
            rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
            pageCoordinate = 0;

        if (typeof e['page' + ucCoordinate] !== 'undefined') {
            pageCoordinate = e['client' + ucCoordinate];
        }
        else if (typeof e.originalEvent['client' + ucCoordinate] !== 'undefined') {
            pageCoordinate = e.originalEvent['client' + ucCoordinate];
        }
        else if (e.originalEvent.touches && e.originalEvent.touches[0] && typeof e.originalEvent.touches[0]['client' + ucCoordinate] !== 'undefined') {
            pageCoordinate = e.originalEvent.touches[0]['client' + ucCoordinate];
        }
        else if(e.currentPoint && typeof e.currentPoint[this.COORDINATE] !== 'undefined') {
            pageCoordinate = e.currentPoint[this.COORDINATE];
        }

        return pageCoordinate - rangePos;
    };

    Plugin.prototype.getPositionFromValue = function(value) {
        var percentage, pos;
        percentage = (value - this.min)/(this.max - this.min);
        pos = (!Number.isNaN(percentage)) ? percentage * this.maxHandlePos : 0;
        return pos;
    };

    Plugin.prototype.getValueFromPosition = function(pos) {
        var percentage, value;
        percentage = ((pos) / (this.maxHandlePos || 1));
        value = this.step * Math.round(percentage * (this.max - this.min) / this.step) + this.min;
        return Number((value).toFixed(this.toFixed));
    };

    Plugin.prototype.setValue = function(value) {
        if (value === this.value && this.$element[0].value !== '') {
            return;
        }

        // Set the new value and fire the `input` event
        this.$element
            .val(value)
            .trigger('input', { origin: this.identifier });
    };

    Plugin.prototype.destroy = function() {
        this.$document.off('.' + this.identifier);
        this.$window.off('.' + this.identifier);

        this.$element
            .off('.' + this.identifier)
            .removeAttr('style')
            .removeData('plugin_' + pluginName);

        // Remove the generated markup
        if (this.$range && this.$range.length) {
            this.$range[0].parentNode.removeChild(this.$range[0]);
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function(options) {
        var args = Array.prototype.slice.call(arguments, 1);

        return this.each(function() {
            var $this = $(this),
                data  = $this.data('plugin_' + pluginName);

            // Create a new instance.
            if (!data) {
                $this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
            }

            // Make it possible to access methods from public.
            // e.g `$element.rangeslider('method');`
            if (typeof options === 'string') {
                data[options].apply(data, args);
            }
        });
    };

    return 'rangeslider.js is available in jQuery context e.g $(selector).rangeslider(options);';

}));
<|endoftext|>


<commit_before>/*
  Accepts an abstract syntax tree and returns the equivalent lua code.
*/
module.exports = (ast) => {
  let code = ''
  let level = 0

  const body = (x, i) => {
    if (i === 0) code += '\n'
    rnode(x)
    code += '\n'
  }

  const bodynr = (x, i) => {
    rnode(x)
    code += '\n'
  }

  const inset = () => {
    code += '\t'.repeat(level)
  }

  const write = (x) => {
    inset()
    code += x
  }

  const rnode = (x) => {
    if (x.type === 'Chunk') {
      x.body.forEach(bodynr)
    }

    if (x.type === 'FunctionDeclaration') {
      write('function ')
      if (x.identifier) {
        rnode(x.identifier)
      }

      // Arguments
      code += '('
      x.parameters.forEach((par, i) => {
        rnode(par)
        if (i !== x.parameters.length - 1) code += ', '
      })
      code += ')'

      // Body
      code += ' '
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'IfStatement') {
      write('if ')

      // Clauses
      x.clauses.forEach(rnode)

      // end
      level -= 1
      write('end')
    }

    if (x.type === 'ReturnStatement') {
      write('return ')
      x.arguments.forEach(rnode)
    }

    if (x.type === 'CallStatement') {
      inset()
      rnode(x.expression)
    }

    if (x.type === 'WhileStatement') {
      write('while ')

        // Condition
      code += '('
      rnode(x.condition)
      code += ')'

        // Body
      code += ' do '
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'AssignmentStatement') {
      // Variables
      inset()
      x.variables.forEach((par, i) => {
        rnode(par)
        if (i !== x.variables.length - 1) code += ', '
      })

      // middle
      code += ' = '

      // Init
      x.init.forEach((par, i) => {
        rnode(par)
        if (i !== x.init.length - 1) code += ', '
      })
    }

    if (x.type === 'LocalStatement') {
      write('local ')

      // Variables
      x.variables.forEach((par, i) => {
        rnode(par)
        if (i !== x.variables.length - 1) code += ', '
      })

      // middle
      code += ' = '

      // Init
      x.init.forEach((par, i) => {
        rnode(par)
        if (i !== x.init.length - 1) code += ', '
      })
    }

    if (x.type === 'ForNumericStatement') {
      write('for ')

      // variable
      rnode(x.variable)
      code += ' = '

      // start
      rnode(x.start)
      code += ', '

      // end
      rnode(x.end)

      // step
      if (x.step) {
        code += ', '
        rnode(x.step)
      }

      // body
      code += ' do '
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'ForGenericStatement') {
      write('for ')

      // variables
      x.variables.forEach((par, i) => {
        rnode(par)
        if (i !== x.variables.length - 1) code += ', '
      })

      // middle
      code += ' in '

      // iterators
      x.iterators.forEach((par, i) => {
        rnode(par)
        if (i !== x.iterators.length - 1) code += ', '
      })

      // body
      code += ' do '
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'LabelStatement') {
      inset()
      code += '::'
      rnode(x.label)
      code += '::'
    }

    if (x.type === 'GotoStatement') {
      write('goto ')
      rnode(x.label)
    }

    if (x.type === 'BreakStatement') {
      write('break ')
    }

    if (x.type === 'DoStatement') {
      write('do ')
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'RepeatStatement') {
      write('repeat ')
      level += 1

      // body
      x.body.forEach(body)

      // until
      level -= 1
      write('until (')
      rnode(x.condition)
      code += ')'
    }

    if (x.type === 'IfClause') {
      // Condition
      code += '('
      rnode(x.condition)
      code += ')'

      // Body
      code += ' then '
      level += 1
      x.body.forEach(body)
    }

    if (x.type === 'ElseClause') {
      // body
      code += ' else '
      level += 1
      x.body.forEach(body)
    }

    if (x.type === 'ElseifClause') {
      code += ' elseif '

      // Condition
      code += '('
      rnode(x.condition)
      code += ')'

      // Body
      code += ' then '
      level += 1
      x.body.forEach(body)
    }

    if (x.type === 'Identifier') {
      code += x.name
    }

    if (x.type === 'StringLiteral') {
      code += x.raw
    }

    if (x.type === 'VarargLiteral') {
      code += x.raw
    }

    if (x.type === 'NilLiteral') {
      code += x.raw
    }

    if (x.type === 'NumericLiteral') {
      code += x.raw
    }

    if (x.type === 'BooleanLiteral') {
      code += x.raw
    }

    if (x.type === 'MemberExpression') {
      rnode(x.base)
      code += x.indexer
      rnode(x.identifier)
    }

    if (x.type === 'BinaryExpression') {
      if (x.inParens) code += '('
      rnode(x.left)
      code += ' ' + x.operator + ' '
      rnode(x.right)
      if (x.inParens) code += ')'
    }

    if (x.type === 'UnaryExpression') {
      if (x.inParens) code += '('
      code += ' ' + x.operator + ' '
      rnode(x.argument)
      if (x.inParens) code += ')'
    }

    if (x.type === 'LogicalExpression') {
      if (x.inParens) code += '('
      rnode(x.left)
      code += ' ' + x.operator + ' '
      rnode(x.right)
      if (x.inParens) code += ')'
    }

    if (x.type === 'CallExpression') {
      // base
      rnode(x.base)

      // arguments
      code += '('
      x.arguments.forEach((par, i) => {
        rnode(par)
        if (i !== x.arguments.length - 1) code += ', '
      })
      code += ')'
    }

    if (x.type === 'IndexExpression') {
      rnode(x.base)
      code += '['
      rnode(x.index)
      code += ']'
    }

    if (x.type === 'TableConstructorExpression') {
      code += '{'
      x.fields.forEach((f, i) => {
        rnode(f)
        if (i !== x.fields.length - 1) code += ', '
      })
      code += '}'
    }

    if (x.type === 'TableKeyString') {
      rnode(x.key)
      code += ' = '
      rnode(x.value)
    }

    if (x.type === 'TableValue') {
      rnode(x.value)
    }

    if (x.type === 'TableKey') {
      code += '['
      rnode(x.key)
      code += '] = '
      rnode(x.value)
    }
  }

  // Recompile from the root node
  rnode(ast)

  return code
}
<commit_msg>Reconstruct multiple returns<commit_after>/*
  Accepts an abstract syntax tree and returns the equivalent lua code.
*/
module.exports = (ast) => {
  let code = ''
  let level = 0

  const body = (x, i) => {
    if (i === 0) code += '\n'
    rnode(x)
    code += '\n'
  }

  const bodynr = (x, i) => {
    rnode(x)
    code += '\n'
  }

  const inset = () => {
    code += '\t'.repeat(level)
  }

  const write = (x) => {
    inset()
    code += x
  }

  const rnode = (x) => {
    if (x.type === 'Chunk') {
      x.body.forEach(bodynr)
    }

    if (x.type === 'FunctionDeclaration') {
      write('function ')
      if (x.identifier) {
        rnode(x.identifier)
      }

      // Arguments
      code += '('
      x.parameters.forEach((par, i) => {
        rnode(par)
        if (i !== x.parameters.length - 1) code += ', '
      })
      code += ')'

      // Body
      code += ' '
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'IfStatement') {
      write('if ')

      // Clauses
      x.clauses.forEach(rnode)

      // end
      level -= 1
      write('end')
    }

    if (x.type === 'ReturnStatement') {
      write('return ')
      x.arguments.forEach((par, i) => {
        rnode(par)
        if (i !== x.arguments.length - 1) code += ', '
      })
    }

    if (x.type === 'CallStatement') {
      inset()
      rnode(x.expression)
    }

    if (x.type === 'WhileStatement') {
      write('while ')

        // Condition
      code += '('
      rnode(x.condition)
      code += ')'

        // Body
      code += ' do '
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'AssignmentStatement') {
      // Variables
      inset()
      x.variables.forEach((par, i) => {
        rnode(par)
        if (i !== x.variables.length - 1) code += ', '
      })

      // middle
      code += ' = '

      // Init
      x.init.forEach((par, i) => {
        rnode(par)
        if (i !== x.init.length - 1) code += ', '
      })
    }

    if (x.type === 'LocalStatement') {
      write('local ')

      // Variables
      x.variables.forEach((par, i) => {
        rnode(par)
        if (i !== x.variables.length - 1) code += ', '
      })

      // middle
      code += ' = '

      // Init
      x.init.forEach((par, i) => {
        rnode(par)
        if (i !== x.init.length - 1) code += ', '
      })
    }

    if (x.type === 'ForNumericStatement') {
      write('for ')

      // variable
      rnode(x.variable)
      code += ' = '

      // start
      rnode(x.start)
      code += ', '

      // end
      rnode(x.end)

      // step
      if (x.step) {
        code += ', '
        rnode(x.step)
      }

      // body
      code += ' do '
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'ForGenericStatement') {
      write('for ')

      // variables
      x.variables.forEach((par, i) => {
        rnode(par)
        if (i !== x.variables.length - 1) code += ', '
      })

      // middle
      code += ' in '

      // iterators
      x.iterators.forEach((par, i) => {
        rnode(par)
        if (i !== x.iterators.length - 1) code += ', '
      })

      // body
      code += ' do '
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'LabelStatement') {
      inset()
      code += '::'
      rnode(x.label)
      code += '::'
    }

    if (x.type === 'GotoStatement') {
      write('goto ')
      rnode(x.label)
    }

    if (x.type === 'BreakStatement') {
      write('break ')
    }

    if (x.type === 'DoStatement') {
      write('do ')
      level += 1
      x.body.forEach(body)
      level -= 1
      write('end')
    }

    if (x.type === 'RepeatStatement') {
      write('repeat ')
      level += 1

      // body
      x.body.forEach(body)

      // until
      level -= 1
      write('until (')
      rnode(x.condition)
      code += ')'
    }

    if (x.type === 'IfClause') {
      // Condition
      code += '('
      rnode(x.condition)
      code += ')'

      // Body
      code += ' then '
      level += 1
      x.body.forEach(body)
    }

    if (x.type === 'ElseClause') {
      // body
      code += ' else '
      level += 1
      x.body.forEach(body)
    }

    if (x.type === 'ElseifClause') {
      code += ' elseif '

      // Condition
      code += '('
      rnode(x.condition)
      code += ')'

      // Body
      code += ' then '
      level += 1
      x.body.forEach(body)
    }

    if (x.type === 'Identifier') {
      code += x.name
    }

    if (x.type === 'StringLiteral') {
      code += x.raw
    }

    if (x.type === 'VarargLiteral') {
      code += x.raw
    }

    if (x.type === 'NilLiteral') {
      code += x.raw
    }

    if (x.type === 'NumericLiteral') {
      code += x.raw
    }

    if (x.type === 'BooleanLiteral') {
      code += x.raw
    }

    if (x.type === 'MemberExpression') {
      rnode(x.base)
      code += x.indexer
      rnode(x.identifier)
    }

    if (x.type === 'BinaryExpression') {
      if (x.inParens) code += '('
      rnode(x.left)
      code += ' ' + x.operator + ' '
      rnode(x.right)
      if (x.inParens) code += ')'
    }

    if (x.type === 'UnaryExpression') {
      if (x.inParens) code += '('
      code += ' ' + x.operator + ' '
      rnode(x.argument)
      if (x.inParens) code += ')'
    }

    if (x.type === 'LogicalExpression') {
      if (x.inParens) code += '('
      rnode(x.left)
      code += ' ' + x.operator + ' '
      rnode(x.right)
      if (x.inParens) code += ')'
    }

    if (x.type === 'CallExpression') {
      // base
      rnode(x.base)

      // arguments
      code += '('
      x.arguments.forEach((par, i) => {
        rnode(par)
        if (i !== x.arguments.length - 1) code += ', '
      })
      code += ')'
    }

    if (x.type === 'IndexExpression') {
      rnode(x.base)
      code += '['
      rnode(x.index)
      code += ']'
    }

    if (x.type === 'TableConstructorExpression') {
      code += '{'
      x.fields.forEach((f, i) => {
        rnode(f)
        if (i !== x.fields.length - 1) code += ', '
      })
      code += '}'
    }

    if (x.type === 'TableKeyString') {
      rnode(x.key)
      code += ' = '
      rnode(x.value)
    }

    if (x.type === 'TableValue') {
      rnode(x.value)
    }

    if (x.type === 'TableKey') {
      code += '['
      rnode(x.key)
      code += '] = '
      rnode(x.value)
    }
  }

  // Recompile from the root node
  rnode(ast)

  return code
}
<|endoftext|>


<commit_before>//Debug = Log all the things!
var d = false;
var mob = 640;
var isMob;

$(function() {
	//When document is ready with loading
	registerSideMenuEvents();

	$(window).resize(function(event) {
		updateResize();
	});
	$("#BannerSrc").load(function() {
		updateResize();
	});
	updateResize();
});

function registerSideMenuEvents() {
	$('.sidebar li.active').children('ul').show();
	$('.sidebar li.has-sub>a').on('click', function() {
		$(this).removeAttr('href');
		element = $(this).parent('li');
		if (element.hasClass('open')) {
			element.removeClass('open');
			element.find('li').removeClass('open');
			element.find('ul').slideUp(200);
		} else {
			element.addClass('open');
			element.children('ul').slideDown(200);
			element.siblings('li').children('ul').slideUp(200);
			element.siblings('li').removeClass('open');
			element.siblings('li').find('li').removeClass('open');
			element.siblings('li').find('ul').slideUp(200);
		}
		for(i=0; i<201; i++){
			setTimeout(updateResize, i);
		}
	});
}

function updateResize() {
	if(isMob == undefined){
		isMob = $("#Pagina").hasClass("Mobiel");
	}else if(!PHP.isMobiel) {
		setMob(window.innerWidth < 640, false);
	}
	onResize(window.innerWidth, window.innerHeight);
}

function onResize(width, height) {
	if(isMob) {
		resizeMobiel(width, height);
	} else {
		resizeDesktop(width, height);
	}
}

function resizeDesktop(width, height) {
	if(d) {
		console.log(width, height);
	}
	$("#Pagina").width(width * 0.8);
	resizeBanner(width, height);
	resizeMenu(width, height);
	resizeContent(width, height);
	resizeFooter(width, height);
	resizeSidebar(width, height);
}

function resizeBanner(width, height) {
	canvas = $("#Banner").get(0);
	g2d = canvas.getContext("2d");
	img = $("#BannerSrc").get(0);

	ht = 130, st = 640, ms = 1920;
	vw = Math.max(Math.min((width*0.8), ms), mob);
	nvw = Math.min((width*0.8), ms);

	canvas.height = ht;
	canvas.width  = nvw;

	g2d.drawImage(img, (st-((vw-mob)/2)), 0, vw, ht, 0, 0, nvw, ht);
}

function resizeMenu(width, height) {
	$(".Menu").width(width * 0.8 - 2);
}

function resizeContent(width, height) {
	if (PHP.page.hasSideBar == "false")
	{
		$(".Content").width(width * 0.8 -2);
	}
	else
	{
		$(".Content").width(width * 0.8 * 0.8 -16);
		$(".Content").height(Math.max($(".markdown-body").height() + 20, $(".sidebar").height()));
	}
	$(".Content").css("margin-bottom", 15);
}

function resizeFooter(width, height) {
	$(".Footer").width(width * 0.8 - 2);
}

function resizeSidebar(width, height) {
	$(".sidebar").width(width * 0.8 * 0.2);
	$(".MenuButton img").hide();
}<commit_msg>change looks.js<commit_after>//Debug = Log all the things!
var d = false;
var mob = 640;
var isMob;

$(function() {
	//When document is ready with loading
	registerSideMenuEvents();

	$(window).resize(function(event) {
		updateResize();
	});
	$("#BannerSrc").load(function() {
		updateResize();
	});
	updateResize();
});

function registerSideMenuEvents() {
	$('.sidebar li.active').children('ul').show();
	$('.sidebar li.has-sub>a').on('click', function() {
		$(this).removeAttr('href');
		element = $(this).parent('li');
		if (element.hasClass('open')) {
			element.removeClass('open');
			element.find('li').removeClass('open');
			element.find('ul').slideUp(200);
		} else {
			element.addClass('open');
			element.children('ul').slideDown(200);
			element.siblings('li').children('ul').slideUp(200);
			element.siblings('li').removeClass('open');
			element.siblings('li').find('li').removeClass('open');
			element.siblings('li').find('ul').slideUp(200);
		}
		for(i=0; i<201; i++){
			setTimeout(updateResize, i);
		}
	});
}

function updateResize() {
	if(isMob == undefined){
		isMob = $("#Pagina").hasClass("Mobiel");
	}else if(!PHP.isMobiel) {
		setMob(window.innerWidth < 640, false);
	}
	onResize(window.innerWidth, window.innerHeight);
}

function onResize(width, height) {
	if(isMob) {
		resizeMobiel(width, height);
	} else {
		resizeDesktop(width, height);
	}
}

function resizeDesktop(width, height) {
	if(d) {
		console.log(width, height);
	}
	$("#Pagina").width(width * 0.8);
	resizeBanner(width, height);
	resizeMenu(width, height);
	resizeContent(width, height);
	resizeFooter(width, height);
	resizeSidebar(width, height);
}

function resizeBanner(width, height) {
	canvas = $("#Banner").get(0);
	g2d = canvas.getContext("2d");
	img = $("#BannerSrc").get(0);

	ht = 130, st = 640, ms = 1920;
	vw = Math.max(Math.min((width*0.8), ms), mob);
	nvw = Math.min((width*0.8), ms);

	canvas.height = ht;
	canvas.width  = nvw;

	g2d.drawImage(img, (st-((vw-mob)/2)), 0, vw, ht, 0, 0, nvw, ht);
}

function resizeMenu(width, height) {
	$(".Menu").width(width * 0.8);
}

function resizeContent(width, height) {
	if (PHP.page.hasSideBar == "false")
	{
		$(".Content").width(width * 0.8);
	}
	else
	{
		$(".Content").width(width * 0.8 * 0.8 -16);
		$(".Content").height(Math.max($(".markdown-body").height() + 20, $(".sidebar").height()));
	}
	$(".Content").css("margin-bottom", 15);
}

function resizeFooter(width, height) {
	$(".Footer").width(width * 0.8);
}

function resizeSidebar(width, height) {
	$(".sidebar").width(width * 0.8 * 0.2);
	$(".MenuButton img").hide();
}<|endoftext|>


<commit_before>var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', { preload: preload, create: create, update: update });
var cursors;

var player;

function preload() {
	game.load.image('food', 'asset/pizza.png');
	game.load.image('snake', 'asset/circle.png');
}

function create() {
	game.physics.startSystem(Phaser.Physics.ARCADE);
	initFood();
	initSnake();
	cursors = game.input.keyboard.createCursorKeys();
}

function update() {
	player.sprite.movimiento(player.sprite);
	game.physics.arcade.overlap(player.sprite, food.sprite, eatFood, null, this);
}

function initFood() {
	var rx = Math.floor((Math.random() * 800) + 1);
	var ry = Math.floor((Math.random() * 600) + 1);
	food = new Food(game, rx, ry);
	return food;

}

function initSnake() {
	var rx = Math.floor((Math.random() * 800) + 1);
	var ry = Math.floor((Math.random() * 600) + 1);
	player = new Snake(game, rx, ry);
	return player;
}

function eatFood(player,food) {
	food.kill();
	initFood();
}<commit_msg>Puntuación de juego<commit_after>var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', { preload: preload, create: create, update: update });
var cursors;

var player;

var score = 0;
var scoreText;

function preload() {
	game.load.image('food', 'asset/pizza.png');
	game.load.image('snake', 'asset/circle.png');
}

function create() {
	game.physics.startSystem(Phaser.Physics.ARCADE);
	initFood();
	initSnake();
	cursors = game.input.keyboard.createCursorKeys();

	scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#FF0000' });
}

function update() {
	player.sprite.movimiento(player.sprite);
	game.physics.arcade.overlap(player.sprite, food.sprite, eatFood, null, this);
}

function initFood() {
	var rx = Math.floor((Math.random() * 800) + 1);
	var ry = Math.floor((Math.random() * 600) + 1);
	food = new Food(game, rx, ry);
	return food;

}

function initSnake() {
	var rx = Math.floor((Math.random() * 800) + 1);
	var ry = Math.floor((Math.random() * 600) + 1);
	player = new Snake(game, rx, ry);
	return player;
}

function eatFood(player,food) {
	food.kill();
	initFood();

	 score += 10;
    scoreText.text = 'Score: ' + score;
}<|endoftext|>


<commit_before>function GameLoop(){

	var self = this;

	//create the renderer
	this.renderer = new PIXI.WebGLRenderer(AH_GLOBALS.SCREEN_W, AH_GLOBALS.SCREEN_H);//autoDetectRenderer(400, 300);

	//add it to the DOM body
	document.body.appendChild(this.renderer.view);

	//create a stage (all sprites added to this)
	self.stage = new PIXI.Container();

	//add a keyboard listener for escape key
	self.kEsc = keyboard(27);

	//key listeners
	this.kEsc.press = function() {
		startLevel();
	}
	this.kEsc.release = function() {
	}

	this.clean = function()
	{
		self.level = null;
		self.player = null;
		self.terrain = null;
		self.topTerrain = null;
		self.buttons = [];
	}

	this.init = function(level_){

		self.timeElapsed = 0.0;
		self.speachRemoved = false;

		//remove all the menu stuff
		self.stage.removeChild(self.promptText);
		self.stage.removeChild(self.promptText1);
		self.stage.removeChild(self.promptText2);
		self.stage.removeChild(self.promptText3);
		self.stage.removeChild(self.menuSprite);

		//setup game objects
		self.level = level_;
		self.player = new Player(level_.playerPos.row, level_.playerPos.col, level_.playerText, level_.textAnchor);
		self.terrain = new Terrain(self.level.levelBottom);
		self.topTerrain = new TopLevelTerrain(self.level.levelTop);
		self.buttons = [];
		//iterate over all buttons in level_
		for ( var i = 0; i < level_.buttons.length; ++i)
		{
			self.buttons.push(new Button(level_.buttons[i]));
		}

		//add sprites to stage
		self.terrain.addToStage(self.stage);

		//add buttons
		for ( var i = 0; i < self.buttons.length; ++i)
		{
			self.stage.addChild(self.buttons[i].sprite);
		}

		//add top terrain (spikes, crates)
		self.topTerrain.addToStage(self.stage);
		//add player to stage
		self.stage.addChild(this.player.sprite);
		self.stage.addChild(this.player.speachText);
	}

	this.run = function() {
		requestAnimationFrame( this.animate );
	}

	this.resetGame = function() {
		while(self.stage.children[0]) { self.stage.removeChild(self.stage.children[0]); }

		// //reset all buttons
		// self.buttons = [];
		// self.terrain = {};
	}

	this.setGameOverState = function() {
		gameState = 'gameOver';
		self.player.turnOffInput();
	}

	this.animate = function(){

		//calc delta
		var now = Date.now();
		var dt = now - lastUpdate;
		self.timeElapsed += dt;
		lastUpdate = now;

		if ( gameState === 'playing') {

			if ( self.timeElapsed > 6000 && self.speachRemoved === false ) {
				self.stage.removeChild(self.player.speachText);
				self.speachRemoved = true;
			}

			//check X collision
    		self.player.updateX();
    		if (self.terrain.collidesWith(self.player.sprite) || self.topTerrain.collisionWithCrate(self.player.sprite) )
    		{
    			self.player.undoX();
    		}

    		//check Y collision
    		self.player.updateY();
    		if (self.terrain.collidesWith(self.player.sprite) || self.topTerrain.collisionWithCrate(self.player.sprite) )
    		{
    			self.player.undoY();
    		}

    		//check if player or crate is colliding with button
    		for (var i = 0; i < self.buttons.length; ++i)
    		{
    			if (self.buttons[i].buttonDown === false )
    			{
    				if ( self.buttons[i].collidesWith(self.player.sprite) === true ||
    					self.topTerrain.collisionWithCrate(self.buttons[i].sprite) === true)
    				{
	    				self.buttons[i].buttonDown = true;
	    				soundButtonDown.play();

	    				//get terrain switching info and pass it to terrain
	    				var swapRow = self.buttons[i].buttonDefinition.swapRow;
	    				var swapCol = self.buttons[i].buttonDefinition.swapCol;
	    				self.terrain.switchTerrainTile(swapRow, swapCol, 0, self.stage);
	    			}
	    		}
    			else if (self.buttons[i].buttonDown === true)
    			{
	    			if (self.buttons[i].collidesWith(self.player.sprite) === false &&
	    				self.topTerrain.collisionWithCrate(self.buttons[i].sprite) === false)
	    			{
	    				self.buttons[i].buttonDown = false;
	    				soundButtonUp.play();

	    				//get terrain switching info and pass it to terrain
	    				var swapRow = self.buttons[i].buttonDefinition.swapRow;
	    				var swapCol = self.buttons[i].buttonDefinition.swapCol;
	    				self.terrain.switchTerrainTile(swapRow, swapCol, 2, self.stage);
	    			}
	    		}
    		}

    		self.topTerrain.moveCrates(self.player.sprite);

    		//check if spikes collide with player
			if (self.topTerrain.causesDeathTo(self.player.sprite) )
			{
				soundPlayerDeath.play();
				self.setGameOverState();
	    		self.promptText = new PIXI.Text('Game Menu', fontStyle);
	    		self.promptText1 = new PIXI.Text('Try Again', fontStyle);
				self.promptText.interactive = true;
				self.promptText1.interactive = true;
				var setLoadMenuGameState = function(){soundSelect.play(); currentLevel = 0; gameState='loadMenu';};
				self.promptText.on('mousedown', setLoadMenuGameState);
				self.promptText1.on('mousedown', startLevel);
				self.promptText.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 + 50);
				self.promptText1.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 - 50);
				self.promptText.anchor.x = 0.5;
				self.promptText.anchor.y = 0.5;
				self.promptText1.anchor.x = 0.5;
				self.promptText1.anchor.y = 0.5;
				self.stage.addChild(self.promptText);
				self.stage.addChild(self.promptText1);
			}

			//spike move
			//dummy var for delta time
			self.topTerrain.update(1, self.terrain);

			if (self.player.reachedGoal === false && self.topTerrain.reachedGoal(self.player.sprite) )
			{
				soundLevelSuccess.play();
				self.setGameOverState();
				self.player.reachedGoal = true;
				self.promptText = new PIXI.Text('CLICK TO GO UP STAIRS', fontStyle);
				self.promptText.interactive = true;
				//var setLoadMenuGameState = function(){gameState='loadMenu';};
				++window.currentLevel;
				self.promptText.on('mousedown', startLevel);
				self.promptText.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2);
				self.promptText.anchor.x = 0.5;
				self.promptText.anchor.y = 0.5;
				self.stage.addChild(self.promptText);
			}
    	}
    	if  ( gameState === 'loadMenu') {
    		self.resetGame();

    		self.promptText = new PIXI.Text('LIT Dark', fontStyle);
    		self.promptText1 = new PIXI.Text('Start Game', fontStyle);
    		// self.promptText2 = new PIXI.Text('Level 2', fontStyle);
    		// self.promptText3 = new PIXI.Text('Level 3', fontStyle);

			self.promptText1.interactive = true;
			// self.promptText2.interactive = true;
			// self.promptText3.interactive = true;

			self.promptText1.on('mousedown', startLevel);
			// self.promptText2.on('mousedown', startLevel2);
			// self.promptText3.on('mousedown', startLevel3);

			self.promptText.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 - 50);
			self.promptText1.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 + 50);
			// self.promptText2.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 + 40);
			// self.promptText3.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 + 80);

			self.promptText.anchor.x = 0.5;
			self.promptText.anchor.y = 0.5;
			self.promptText1.anchor.x = 0.5;
			self.promptText1.anchor.y = 0.5;
			// self.promptText2.anchor.x = 0.5;
			// self.promptText2.anchor.y = 0.5;
			// self.promptText3.anchor.x = 0.5;
			// self.promptText3.anchor.y = 0.5;

			self.menuSprite = PIXI.Sprite.fromImage("./img/LitDarkTitle.png");
			self.menuSprite.position.set(0, 0);

			self.stage.addChild(self.menuSprite);
    		self.stage.addChild(self.promptText);
    		self.stage.addChild(self.promptText1);
    		// self.stage.addChild(self.promptText2);
    		// self.stage.addChild(self.promptText3);
    		gameState = 'mainMenu';
    	}
    	self.renderer.render(self.stage);
		requestAnimationFrame( self.animate );
	}
}<commit_msg>sound bug on suicide fixed<commit_after>function GameLoop(){

	var self = this;

	//create the renderer
	this.renderer = new PIXI.WebGLRenderer(AH_GLOBALS.SCREEN_W, AH_GLOBALS.SCREEN_H);//autoDetectRenderer(400, 300);

	//add it to the DOM body
	document.body.appendChild(this.renderer.view);

	//create a stage (all sprites added to this)
	self.stage = new PIXI.Container();

	//add a keyboard listener for escape key
	self.kEsc = keyboard(27);

	//key listeners
	this.kEsc.press = function() {
		soundPlayerDeath.play();
		self.setGameOverState();
		startLevel();
	}
	this.kEsc.release = function() {
	}

	this.clean = function()
	{
		self.level = null;
		self.player = null;
		self.terrain = null;
		self.topTerrain = null;
		self.buttons = [];
	}

	this.resetGame = function() {
		while(self.stage.children[0]) { self.stage.removeChild(self.stage.children[0]); }

		// //reset all buttons
		// self.buttons = [];
		// self.terrain = {};
	}

	this.init = function(level_){

		self.resetGame();

		self.timeElapsed = 0.0;
		self.speachRemoved = false;

		//remove all the menu stuff
		self.stage.removeChild(self.promptText);
		self.stage.removeChild(self.promptText1);
		self.stage.removeChild(self.promptText2);
		self.stage.removeChild(self.promptText3);
		self.stage.removeChild(self.menuSprite);

		//setup game objects
		self.level = level_;
		self.player = new Player(level_.playerPos.row, level_.playerPos.col, level_.playerText, level_.textAnchor);
		self.terrain = new Terrain(self.level.levelBottom);
		self.topTerrain = new TopLevelTerrain(self.level.levelTop);
		self.buttons = [];
		//iterate over all buttons in level_
		for ( var i = 0; i < level_.buttons.length; ++i)
		{
			self.buttons.push(new Button(level_.buttons[i]));
		}

		//add sprites to stage
		self.terrain.addToStage(self.stage);

		//add buttons
		for ( var i = 0; i < self.buttons.length; ++i)
		{
			self.stage.addChild(self.buttons[i].sprite);
		}

		//add top terrain (spikes, crates)
		self.topTerrain.addToStage(self.stage);
		//add player to stage
		self.stage.addChild(this.player.sprite);
		self.stage.addChild(this.player.speachText);
	}

	this.run = function() {
		requestAnimationFrame( this.animate );
	}

	this.setGameOverState = function() {
		gameState = 'gameOver';
		self.player.turnOffInput();
	}

	this.animate = function(){

		//calc delta
		var now = Date.now();
		var dt = now - lastUpdate;
		self.timeElapsed += dt;
		lastUpdate = now;

		if ( gameState === 'playing') {

			if ( self.timeElapsed > 6000 && self.speachRemoved === false ) {
				self.stage.removeChild(self.player.speachText);
				self.speachRemoved = true;
			}

			//check X collision
    		self.player.updateX();
    		if (self.terrain.collidesWith(self.player.sprite) || self.topTerrain.collisionWithCrate(self.player.sprite) )
    		{
    			self.player.undoX();
    		}

    		//check Y collision
    		self.player.updateY();
    		if (self.terrain.collidesWith(self.player.sprite) || self.topTerrain.collisionWithCrate(self.player.sprite) )
    		{
    			self.player.undoY();
    		}

    		//check if player or crate is colliding with button
    		for (var i = 0; i < self.buttons.length; ++i)
    		{
    			if (self.buttons[i].buttonDown === false )
    			{
    				if ( self.buttons[i].collidesWith(self.player.sprite) === true ||
    					self.topTerrain.collisionWithCrate(self.buttons[i].sprite) === true)
    				{
	    				self.buttons[i].buttonDown = true;
	    				soundButtonDown.play();

	    				//get terrain switching info and pass it to terrain
	    				var swapRow = self.buttons[i].buttonDefinition.swapRow;
	    				var swapCol = self.buttons[i].buttonDefinition.swapCol;
	    				self.terrain.switchTerrainTile(swapRow, swapCol, 0, self.stage);
	    			}
	    		}
    			else if (self.buttons[i].buttonDown === true)
    			{
	    			if (self.buttons[i].collidesWith(self.player.sprite) === false &&
	    				self.topTerrain.collisionWithCrate(self.buttons[i].sprite) === false)
	    			{
	    				self.buttons[i].buttonDown = false;
	    				soundButtonUp.play();

	    				//get terrain switching info and pass it to terrain
	    				var swapRow = self.buttons[i].buttonDefinition.swapRow;
	    				var swapCol = self.buttons[i].buttonDefinition.swapCol;
	    				self.terrain.switchTerrainTile(swapRow, swapCol, 2, self.stage);
	    			}
	    		}
    		}

    		self.topTerrain.moveCrates(self.player.sprite);

    		//check if spikes collide with player
			if (self.topTerrain.causesDeathTo(self.player.sprite) )
			{
				soundPlayerDeath.play();
				self.setGameOverState();
	    		self.promptText = new PIXI.Text('Game Menu', fontStyle);
	    		self.promptText1 = new PIXI.Text('Try Again', fontStyle);
				self.promptText.interactive = true;
				self.promptText1.interactive = true;
				var setLoadMenuGameState = function(){soundSelect.play(); currentLevel = 0; gameState='loadMenu';};
				self.promptText.on('mousedown', setLoadMenuGameState);
				self.promptText1.on('mousedown', startLevel);
				self.promptText.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 + 50);
				self.promptText1.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 - 50);
				self.promptText.anchor.x = 0.5;
				self.promptText.anchor.y = 0.5;
				self.promptText1.anchor.x = 0.5;
				self.promptText1.anchor.y = 0.5;
				self.stage.addChild(self.promptText);
				self.stage.addChild(self.promptText1);
			}

			//spike move
			//dummy var for delta time
			self.topTerrain.update(1, self.terrain);

			if (self.player.reachedGoal === false && self.topTerrain.reachedGoal(self.player.sprite) )
			{
				soundLevelSuccess.play();
				self.setGameOverState();
				self.player.reachedGoal = true;
				self.promptText = new PIXI.Text('CLICK TO GO UP STAIRS', fontStyle);
				self.promptText.interactive = true;
				//var setLoadMenuGameState = function(){gameState='loadMenu';};
				++window.currentLevel;
				self.promptText.on('mousedown', startLevel);
				self.promptText.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2);
				self.promptText.anchor.x = 0.5;
				self.promptText.anchor.y = 0.5;
				self.stage.addChild(self.promptText);
			}
    	}
    	if  ( gameState === 'loadMenu') {
    		self.resetGame();

    		self.promptText = new PIXI.Text('LIT Dark', fontStyle);
    		self.promptText1 = new PIXI.Text('Start Game', fontStyle);
    		// self.promptText2 = new PIXI.Text('Level 2', fontStyle);
    		// self.promptText3 = new PIXI.Text('Level 3', fontStyle);

			self.promptText1.interactive = true;
			// self.promptText2.interactive = true;
			// self.promptText3.interactive = true;

			self.promptText1.on('mousedown', startLevel);
			// self.promptText2.on('mousedown', startLevel2);
			// self.promptText3.on('mousedown', startLevel3);

			self.promptText.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 - 50);
			self.promptText1.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 + 50);
			// self.promptText2.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 + 40);
			// self.promptText3.position.set(AH_GLOBALS.SCREEN_W/2, AH_GLOBALS.SCREEN_H/2 + 80);

			self.promptText.anchor.x = 0.5;
			self.promptText.anchor.y = 0.5;
			self.promptText1.anchor.x = 0.5;
			self.promptText1.anchor.y = 0.5;
			// self.promptText2.anchor.x = 0.5;
			// self.promptText2.anchor.y = 0.5;
			// self.promptText3.anchor.x = 0.5;
			// self.promptText3.anchor.y = 0.5;

			self.menuSprite = PIXI.Sprite.fromImage("./img/LitDarkTitle.png");
			self.menuSprite.position.set(0, 0);

			self.stage.addChild(self.menuSprite);
    		self.stage.addChild(self.promptText);
    		self.stage.addChild(self.promptText1);
    		// self.stage.addChild(self.promptText2);
    		// self.stage.addChild(self.promptText3);
    		gameState = 'mainMenu';
    	}
    	self.renderer.render(self.stage);
		requestAnimationFrame( self.animate );
	}
}<|endoftext|>


<commit_before>//v0.1k

$('#helloContainer').after('
' +
    '

' +
    '
' +
    '
' +
    '
<button id="CloseReplay" type="button" class="close" data-dismiss="modal">×' + Premadeletter113 + '</button> <button id="FAQReplay type="button" class="close" data-dismiss="modal">?' + Premadeletter113 + '</button>' +
    '
' + 'Replay' + '
' +
    '
' +
    '
' +
    '<select id="savedArenas" class="form-control" required="" style="display:inline; margin-bottom: 10px; width: 70%"></select>' +
	'<button id="watchReplaybtn" style="display:inline; margin-left: 12px;" type="button" data-dismiss="modal">Watch</button>' +
	'<button onclick="saveTextAsFile()" "display:inline;">Save</button>' +
    '<input type="text" class="form-control" id="arenaReplaySpecifications" placeholder="Predicted values" style="width: 95%; display: inline-block" disabled>' +
    '
' +
    '
' +
    '<color="red" style="display:inline"> Speed:</color><input id="arenaReplaySpeed" value="20" type="number" min="1" max="100" step="1" class="form-control" required="" style="display:inline; width: 15%; margin-top: -30px;">' +
	//'<color="red" style="display:inline;"> PPS:</color>

<input type="file" id="fileToLoad" style="display:inline;" onchange="loadFileAsText()">' +
    '<color="red" style="display:inline;"> <input type="file" id="fileToLoad" style="display:inline;" onchange="loadFileAsText()">' +
    '
' +
	'
' +
	'Start:<input type="number" class="form-control" id="startReplayTime" placeholder="" style="width: 19%; display: inline-block">' +
	' End:<input type="number" class="form-control" id="endReplayTime" placeholder="" style="width: 19%; display: inline-block">' +
	' Current:<input type="text" class="form-control" id="totalReplayPackets" placeholder="" style="width: 19%; display: inline-block" disabled>' +
	'<button id="stopReplaybtn" style="display:inline; margin-left: 12px;" type="button" data-dismiss="modal">Stop</button>' +
	'
' +
	'
' +
	'Greyscale: <input type="checkbox" id="greyScale">' +
	' Sepia: <input type="checkbox" id="sepia">' +
	' Hue-rotate: <input type="checkbox" id="hueRotate">' +

	'
' +
	'
' +
    '
' +
    '
' +
    '
');
$("#replayModal").draggable()
$("#stopReplaybtn").prop('disabled', true);
if (window.replayGreyScale){
	$("#greyScale").click()
}
else if (window.replaySepia){
	$("#sepia").click()
}
else if (window.replayHueRotate){
	$("#hueRotate").click()
}

$("#greyScale").change(function() {
	if (document.getElementById("greyScale").checked){
		document.getElementById("sepia").checked = false
		document.getElementById("hueRotate").checked =false
	}
});
$("#sepia").change(function() {
	if (document.getElementById("sepia").checked){
		document.getElementById("greyScale").checked = false
		document.getElementById("hueRotate").checked =false
	}
});
$("#hueRotate").change(function() {
	if (document.getElementById("hueRotate").checked){
		document.getElementById("greyScale").checked = false
		document.getElementById("sepia").checked =false
	}
});
$("#CloseReplay").click(function() {

    $("#replayModal").remove();
});
$("#FAQReplay").click(function() {
    window.open('https://legendmod.ml/', '_blank');
});

if (localStorage.getItem("replayTiming") && localStorage.getItem("replayTiming")!=""){
	window.replayTiming = localStorage.getItem("replayTiming")
}
$("#arenaReplaySpeed").val(window.replayTiming)
//$("#arenaReplayPPS").text((1000/window.replayTiming).toFixed(0))
PopulateArenas();
fillArenasSpecifications()
revealReplayTotal()

$("#savedArenas").change(function() {
    fillArenasSpecifications()
	revealReplayTotal()
	console.log('a')
});
$("#arenaReplaySpeed").change(function() {
    window.replayTiming = $("#arenaReplaySpeed").val()
	localStorage.setItem("replayTiming", window.replayTiming);
	//$("#arenaReplayPPS").text((1000/window.replayTiming).toFixed(0))
});

/*
$(document).on('click', '#watchReplaybtn', function() {
    $("#server-token").val("replay^" + $("#savedArenas").val())
    $("#server-join").click()
});
*/
$("#watchReplaybtn").click(function() {
	window.replayGreyScale = document.getElementById("greyScale").checked
	window.replaySepia = document.getElementById("sepia").checked
	window.replayHueRotate = document.getElementById("hueRotate").checked
    $("#server-token").val("replay^" + $("#savedArenas").val())
    $("#server-join").click()
});
$("#stopReplaybtn").click(function() {
	clearTimeout(window.replayTimeOuts)
	$('#pause-hud').text(textLanguage.pause);
	$('#pause-hud').hide()
	$("#stopReplaybtn").prop('disabled', true);
});
function revealReplayTotal(){
	if ($("#savedArenas").val()!=null && $("#savedArenas").val()!="" && window.RecordedProtocol[$("#savedArenas").val()]){
		window.RecordedProtocolPackets=window.RecordedProtocol[$("#savedArenas").val()].length-2
		$("#totalReplayPackets").val("0/" +window.RecordedProtocolPackets)
		$("#startReplayTime").val(0)
		$("#endReplayTime").val(window.RecordedProtocol[$("#savedArenas").val()].length-2)
	}
}
function PopulateArenas() {
    var select = document.getElementById("savedArenas");
    if (window.RecordedProtocolArenas && window.RecordedProtocolArenas.length) {
        for (var i = 0; i < window.RecordedProtocolArenas.length; i++) {
            select.options[select.options.length] = new Option(window.RecordedProtocolArenas[i]);
        }
    }
}

function fillArenasSpecifications() {

    if (window.RecordedArenasSpecifications && window.RecordedArenasSpecifications[$("#savedArenas").val()] && window.RecordedArenasSpecifications[$("#savedArenas").val()].length)
		try{
        var dateThen = new Date(window.RecordedArenasSpecifications[$("#savedArenas").val()][0])
		var monthErrorFix = dateThen.getMonth() + 1
		var tempRegion = " Region:" + window.RecordedArenasSpecifications[$("#savedArenas").val()][2]
		var tempGameMode = " Mode" + window.RecordedArenasSpecifications[$("#savedArenas").val()][1]
		var tempGameNick = " Nick:" + window.RecordedArenasSpecifications[$("#savedArenas").val()][3]
		var dateThen2 = dateThen.getDate() + "/" + monthErrorFix + "/" + dateThen.getFullYear() + " " + dateThen.getHours() + ":" + dateThen.getMinutes() + ":" + dateThen.getSeconds() + tempRegion + tempGameMode + tempGameNick
		$("#arenaReplaySpecifications").val(dateThen2)
		$("#arenaReplaySpecifications").blur();
		} catch (e) {}
}
function saveTextAsFile()
{

//for saving

savedBuffedReplayProtocol=[]
for (var i=0; i<window.RecordedProtocol[$('#savedArenas').val()].length;i++){
	savedBuffedReplayProtocol[i] = ab2str(window.RecordedProtocol[$('#savedArenas').val()][i].buffer)
}
try{
savedBuffedReplayProtocol[savedBuffedReplayProtocol.length]=window.RecordedArenasSpecifications[$("#savedArenas").val()]
}
catch{}
var tempo = JSON.stringify(savedBuffedReplayProtocol);

    var textToSave = tempo;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
	var savedfileName = $("#savedArenas").val().replace(".lm", "");
    var fileNameToSaveAs = savedfileName+".lm";

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

function loadFileAsText(file)
{
	if (!file){
		var fileToLoad = document.getElementById("fileToLoad").files[0];
	}
	else if(file){
		var fileToLoad = file
	}
	//console.log(fileToLoad.name)
    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent)
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        var tempo = textFromFileLoaded;
//for loading
var tempo2 = JSON.parse(tempo);
window.RecordedProtocol[fileToLoad.name]=[]
window.RecordedProtocolArenas.push(fileToLoad.name)

var x = document.getElementById("savedArenas");
var option = document.createElement("option");
option.text = fileToLoad.name;
x.add(option);
x.options[x.length-1].selected = true;

for (var i=0; i<tempo2.length-1;i++){
	window.RecordedProtocol[fileToLoad.name][i]=[]
	//window.RecordedProtocol['saved'][i] = new DataView(tempo2[i])
	//window.RecordedProtocol['saved'][i]=str2ab(tempo2[i])
	window.RecordedProtocol[fileToLoad.name][i]=new DataView(str2ab(tempo2[i]));

}
var temp1=tempo2[tempo2.length-1][0]
var temp2=tempo2[tempo2.length-1][2]
var temp3=tempo2[tempo2.length-1][1]
var temp4=tempo2[tempo2.length-1][3]

		try{
        var dateThen = new Date(temp1)
		var monthErrorFix = dateThen.getMonth() + 1
		var tempRegion = " Region:" + temp2
		var tempGameMode = " Mode" + temp3
		var tempGameNick = " Nick:" + temp4
		var dateThen2 = dateThen.getDate() + "/" + monthErrorFix + "/" + dateThen.getFullYear() + " " + dateThen.getHours() + ":" + dateThen.getMinutes() + ":" + dateThen.getSeconds() + tempRegion + tempGameMode + tempGameNick
		window.RecordedArenasSpecifications[$("#savedArenas").val()]=tempo2[tempo2.length-1]
		$("#arenaReplaySpecifications").val(dateThen2)
		$("#arenaReplaySpecifications").blur();
		revealReplayTotal()
		} catch (e) {}

    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}
function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}
//ab2str(window.RecordedProtocol['1llnrvk'][0].buffer)

function str2ab(str) {
  var buf = new ArrayBuffer(str.length);
  //var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint8Array(buf);
  //var bufView = new DataView(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
return buf;
	//return bufView;
}
function loadReplayFromWeb(temp2){
	$.ajax(temp2, {
        error() {},
        success(sketchContents) {
			if (temp2.includes(".lm")){
				temp2 = temp2.split("/").pop();
				var replayWebLoaded = new Blob([sketchContents], {type:"text/plain"});
				replayWebLoaded.name = temp2
				loadFileAsText(replayWebLoaded)
				setTimeout(function() {
					if (replayStart && isNaN(replayStart)){
						$("#startReplayTime").val()
					}
					if (replayEnd && isNaN(replayEnd)){
						$("#endReplayTime").val()
					}
					$("#watchReplaybtn").click()
					application.onSpectate()
				}, 1000);
			}
			else{
				toastr.warning("[" + Premadeletter123 + "]: " + "Requested file is not .lm");
			}
        },
        method: "GET",
        cache: false,
        crossDomain: true
    });
}
<commit_msg>Update replay.js<commit_after>//v0.1l

$('#helloContainer').after('
' +
    '

' +
    '
' +
    '
' +
    '
<button id="CloseReplay" type="button" class="close" data-dismiss="modal">×' + Premadeletter113 + '</button> <button id="FAQReplay type="button" class="close" data-dismiss="modal">?' + Premadeletter113 + '</button>' +
    '
' + 'Replay' + '
' +
    '
' +
    '
' +
    '<select id="savedArenas" class="form-control" required="" style="display:inline; margin-bottom: 10px; width: 70%"></select>' +
	'<button id="watchReplaybtn" style="display:inline; margin-left: 12px;" type="button" data-dismiss="modal">Watch</button>' +
	'<button onclick="saveTextAsFile()" "display:inline;">Save</button>' +
    '<input type="text" class="form-control" id="arenaReplaySpecifications" placeholder="Predicted values" style="width: 95%; display: inline-block" disabled>' +
    '
' +
    '
' +
    '<color="red" style="display:inline"> Speed:</color><input id="arenaReplaySpeed" value="20" type="number" min="1" max="100" step="1" class="form-control" required="" style="display:inline; width: 15%; margin-top: -30px;">' +
	//'<color="red" style="display:inline;"> PPS:</color>

<input type="file" id="fileToLoad" style="display:inline;" onchange="loadFileAsText()">' +
    '<color="red" style="display:inline;"> <input type="file" id="fileToLoad" style="display:inline;" onchange="loadFileAsText()">' +
    '
' +
	'
' +
	'Start:<input type="number" class="form-control" id="startReplayTime" placeholder="" style="width: 19%; display: inline-block">' +
	' End:<input type="number" class="form-control" id="endReplayTime" placeholder="" style="width: 19%; display: inline-block">' +
	' Current:<input type="text" class="form-control" id="totalReplayPackets" placeholder="" style="width: 19%; display: inline-block" disabled>' +
	'<button id="stopReplaybtn" style="display:inline; margin-left: 12px;" type="button" data-dismiss="modal">Stop</button>' +
	'
' +
	'
' +
	'Greyscale: <input type="checkbox" id="greyScale">' +
	' Sepia: <input type="checkbox" id="sepia">' +
	' Hue-rotate: <input type="checkbox" id="hueRotate">' +

	'
' +
	'
' +
    '
' +
    '
' +
    '
');
$("#replayModal").draggable()
$("#stopReplaybtn").prop('disabled', true);
if (window.replayGreyScale){
	$("#greyScale").click()
}
else if (window.replaySepia){
	$("#sepia").click()
}
else if (window.replayHueRotate){
	$("#hueRotate").click()
}

$("#greyScale").change(function() {
	if (document.getElementById("greyScale").checked){
		document.getElementById("sepia").checked = false
		document.getElementById("hueRotate").checked =false
	}
});
$("#sepia").change(function() {
	if (document.getElementById("sepia").checked){
		document.getElementById("greyScale").checked = false
		document.getElementById("hueRotate").checked =false
	}
});
$("#hueRotate").change(function() {
	if (document.getElementById("hueRotate").checked){
		document.getElementById("greyScale").checked = false
		document.getElementById("sepia").checked =false
	}
});
$("#CloseReplay").click(function() {

    $("#replayModal").remove();
});
$("#FAQReplay").click(function() {
    window.open('https://legendmod.ml/', '_blank');
});

if (localStorage.getItem("replayTiming") && localStorage.getItem("replayTiming")!=""){
	window.replayTiming = localStorage.getItem("replayTiming")
}
$("#arenaReplaySpeed").val(window.replayTiming)
//$("#arenaReplayPPS").text((1000/window.replayTiming).toFixed(0))
PopulateArenas();
fillArenasSpecifications()
revealReplayTotal()

$("#savedArenas").change(function() {
    fillArenasSpecifications()
	revealReplayTotal()
	console.log('a')
});
$("#arenaReplaySpeed").change(function() {
    window.replayTiming = $("#arenaReplaySpeed").val()
	localStorage.setItem("replayTiming", window.replayTiming);
	//$("#arenaReplayPPS").text((1000/window.replayTiming).toFixed(0))
});

/*
$(document).on('click', '#watchReplaybtn', function() {
    $("#server-token").val("replay^" + $("#savedArenas").val())
    $("#server-join").click()
});
*/
$("#watchReplaybtn").click(function() {
	window.replayGreyScale = document.getElementById("greyScale").checked
	window.replaySepia = document.getElementById("sepia").checked
	window.replayHueRotate = document.getElementById("hueRotate").checked
    $("#server-token").val("replay^" + $("#savedArenas").val())
    $("#server-join").click()
});
$("#stopReplaybtn").click(function() {
	clearTimeout(window.replayTimeOuts)
	$('#pause-hud').text(textLanguage.pause);
	$('#pause-hud').hide()
	$("#stopReplaybtn").prop('disabled', true);
});
function revealReplayTotal(){
	if ($("#savedArenas").val()!=null && $("#savedArenas").val()!="" && window.RecordedProtocol[$("#savedArenas").val()]){
		window.RecordedProtocolPackets=window.RecordedProtocol[$("#savedArenas").val()].length-2
		$("#totalReplayPackets").val("0/" +window.RecordedProtocolPackets)
		$("#startReplayTime").val(0)
		$("#endReplayTime").val(window.RecordedProtocol[$("#savedArenas").val()].length-2)
	}
}
function PopulateArenas() {
    var select = document.getElementById("savedArenas");
    if (window.RecordedProtocolArenas && window.RecordedProtocolArenas.length) {
        for (var i = 0; i < window.RecordedProtocolArenas.length; i++) {
            select.options[select.options.length] = new Option(window.RecordedProtocolArenas[i]);
        }
    }
}

function fillArenasSpecifications() {

    if (window.RecordedArenasSpecifications && window.RecordedArenasSpecifications[$("#savedArenas").val()] && window.RecordedArenasSpecifications[$("#savedArenas").val()].length)
		try{
        var dateThen = new Date(window.RecordedArenasSpecifications[$("#savedArenas").val()][0])
		var monthErrorFix = dateThen.getMonth() + 1
		var tempRegion = " Region:" + window.RecordedArenasSpecifications[$("#savedArenas").val()][2]
		var tempGameMode = " Mode" + window.RecordedArenasSpecifications[$("#savedArenas").val()][1]
		var tempGameNick = " Nick:" + window.RecordedArenasSpecifications[$("#savedArenas").val()][3]
		var dateThen2 = dateThen.getDate() + "/" + monthErrorFix + "/" + dateThen.getFullYear() + " " + dateThen.getHours() + ":" + dateThen.getMinutes() + ":" + dateThen.getSeconds() + tempRegion + tempGameMode + tempGameNick
		$("#arenaReplaySpecifications").val(dateThen2)
		$("#arenaReplaySpecifications").blur();
		} catch (e) {}
}
function saveTextAsFile()
{

//for saving

savedBuffedReplayProtocol=[]
for (var i=0; i<window.RecordedProtocol[$('#savedArenas').val()].length;i++){
	savedBuffedReplayProtocol[i] = ab2str(window.RecordedProtocol[$('#savedArenas').val()][i].buffer)
}
try{
savedBuffedReplayProtocol[savedBuffedReplayProtocol.length]=window.RecordedArenasSpecifications[$("#savedArenas").val()]
}
catch{}
var tempo = JSON.stringify(savedBuffedReplayProtocol);

    var textToSave = tempo;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
	var savedfileName = $("#savedArenas").val().replace(".lm", "");
    var fileNameToSaveAs = savedfileName+".lm";

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

function loadFileAsText(file)
{
	if (!file){
		var fileToLoad = document.getElementById("fileToLoad").files[0];
	}
	else if(file){
		var fileToLoad = file
	}
	//console.log(fileToLoad.name)
    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent)
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        var tempo = textFromFileLoaded;
//for loading
var tempo2 = JSON.parse(tempo);
window.RecordedProtocol[fileToLoad.name]=[]
window.RecordedProtocolArenas.push(fileToLoad.name)

var x = document.getElementById("savedArenas");
var option = document.createElement("option");
option.text = fileToLoad.name;
x.add(option);
x.options[x.length-1].selected = true;

for (var i=0; i<tempo2.length-1;i++){
	window.RecordedProtocol[fileToLoad.name][i]=[]
	//window.RecordedProtocol['saved'][i] = new DataView(tempo2[i])
	//window.RecordedProtocol['saved'][i]=str2ab(tempo2[i])
	window.RecordedProtocol[fileToLoad.name][i]=new DataView(str2ab(tempo2[i]));

}
var temp1=tempo2[tempo2.length-1][0]
var temp2=tempo2[tempo2.length-1][2]
var temp3=tempo2[tempo2.length-1][1]
var temp4=tempo2[tempo2.length-1][3]

		try{
        var dateThen = new Date(temp1)
		var monthErrorFix = dateThen.getMonth() + 1
		var tempRegion = " Region:" + temp2
		var tempGameMode = " Mode" + temp3
		var tempGameNick = " Nick:" + temp4
		var dateThen2 = dateThen.getDate() + "/" + monthErrorFix + "/" + dateThen.getFullYear() + " " + dateThen.getHours() + ":" + dateThen.getMinutes() + ":" + dateThen.getSeconds() + tempRegion + tempGameMode + tempGameNick
		window.RecordedArenasSpecifications[$("#savedArenas").val()]=tempo2[tempo2.length-1]
		$("#arenaReplaySpecifications").val(dateThen2)
		$("#arenaReplaySpecifications").blur();
		revealReplayTotal()
		} catch (e) {}

    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}
function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}
//ab2str(window.RecordedProtocol['1llnrvk'][0].buffer)

function str2ab(str) {
  var buf = new ArrayBuffer(str.length);
  //var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint8Array(buf);
  //var bufView = new DataView(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
return buf;
	//return bufView;
}
function loadReplayFromWeb(temp2){
	$.ajax(temp2, {
        error() {},
        success(sketchContents) {
			if (temp2.includes(".lm")){
				temp2 = temp2.split("/").pop();
				var replayWebLoaded = new Blob([sketchContents], {type:"text/plain"});
				replayWebLoaded.name = temp2
				loadFileAsText(replayWebLoaded)
				setTimeout(function() {
					var replayStart, replayEnd;
					if (replayStart && isNaN(replayStart)){
						$("#startReplayTime").val()
					}
					if (replayEnd && isNaN(replayEnd)){
						$("#endReplayTime").val()
					}
					$("#watchReplaybtn").click()
					application.onSpectate()
				}, 1000);
			}
			else{
				toastr.warning("[" + Premadeletter123 + "]: " + "Requested file is not .lm");
			}
        },
        method: "GET",
        cache: false,
        crossDomain: true
    });
}
<|endoftext|>