<commit_before>var mapstyle = [
    {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "color": "#ffffff"
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.icon",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "administrative",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "color": "#c9323b"
            }
        ]
    },
    {
        "featureType": "administrative",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "color": "#42f453"
            },
            {
                "weight": 1.2
            }
        ]
    },
    {
        "featureType": "administrative.locality",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "lightness": "-1"
            }
        ]
    },
    {
        "featureType": "administrative.neighborhood",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "lightness": "0"
            },
            {
                "saturation": "0"
            }
        ]
    },
    {
        "featureType": "administrative.neighborhood",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "weight": "0.01"
            }
        ]
    },
    {
        "featureType": "administrative.land_parcel",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "weight": "0.01"
            }
        ]
    },
    {
        "featureType": "landscape",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#c9323b"
            }
        ]
    },
    {
        "featureType": "poi",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#99282f"
            }
        ]
    },
    {
        "featureType": "road",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "color": "#99282f"
            }
        ]
    },
    {
        "featureType": "road.highway.controlled_access",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "color": "#99282f"
            }
        ]
    },
    {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#99282f"
            }
        ]
    },
    {
        "featureType": "road.local",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#99282f"
            }
        ]
    },
    {
        "featureType": "transit",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#99282f"
            }
        ]
    },
    {
        "featureType": "water",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#090228"
            }
        ]
    }
]<commit_msg>updated map styling<commit_after>var mapstyle = [
    {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "color": "#3b3a36"
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.icon",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "administrative",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "color": "#c0dfd9"
            }
        ]
    },
    {
        "featureType": "administrative",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "color": "#e9ece5"
            },
            {
                "weight": 1.2
            }
        ]
    },
    {
        "featureType": "administrative.locality",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "lightness": "-1"
            }
        ]
    },
    {
        "featureType": "administrative.neighborhood",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "lightness": "0"
            },
            {
                "saturation": "0"
            }
        ]
    },
    {
        "featureType": "administrative.neighborhood",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "weight": "0.01"
            }
        ]
    },
    {
        "featureType": "administrative.land_parcel",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "weight": "0.01"
            }
        ]
    },
    {
        "featureType": "landscape",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#e9ece5"
            }
        ]
    },
    {
        "featureType": "poi",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#b3c2bf"
            }
        ]
    },
    {
        "featureType": "road",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "color": "#b3c2bf"
            }
        ]
    },
    {
        "featureType": "road.highway.controlled_access",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "color": "#b3c2bf"
            }
        ]
    },
    {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#b3c2bf"
            }
        ]
    },
    {
        "featureType": "road.local",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#b3c2bf"
            }
        ]
    },
    {
        "featureType": "transit",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#b3c2bf"
            }
        ]
    },
    {
        "featureType": "water",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#c0dfd9"
            }
        ]
    }
]<|endoftext|>


<commit_before>/*======================================================
************   Messages   ************
======================================================*/
var Messages = function (container, params) {
    var defaults = {
        autoLayout: true,
        newMessagesFirst: false,
        messageTemplate:
            '{{#if day}}' +
            '
{{day}} {{#if time}}, {{time}}{{/if}}
' +
            '{{/if}}' +
            '
' +
                '{{#if name}}
{{name}}
{{/if}}' +
                '
{{text}}
' +
                '{{#if avatar}}

{{/if}}' +
                '{{#if label}}
{{label}}
{{/if}}' +
            '
'
    };
    params = params || {};
    for (var def in defaults) {
        if (typeof params[def] === 'undefined' || params[def] === null) {
            params[def] = defaults[def];
        }
    }

    // Instance
    var m = this;

    // Params
    m.params = params;

    // Container
    m.container = $(container);
    if (m.container.length === 0) return;

    // Autolayout
    if (m.params.autoLayout) m.container.addClass('messages-auto-layout');

    // Is In Page
    m.pageContainer = m.container.parents('.page').eq(0);
    m.pageContent = m.pageContainer.find('.page-content');

    // Compiled template
    m.template = Template7.compile(m.params.messageTemplate);

    // Auto Layout
    m.layout = function () {
        if (!m.container.hasClass('messages-auto-layout')) m.container.addClass('messages-auto-layout');
        m.container.find('.message').each(function () {
            var message = $(this);
            if (message.find('.message-text img').length > 0) message.addClass('message-pic');
            if (message.find('.message-avatar').length > 0) message.addClass('message-with-avatar');
        });
        m.container.find('.message').each(function () {
            var message = $(this);
            var isSent = message.hasClass('message-sent');
            var next = message.next('.message-' + (isSent ? 'sent' : 'received'));
            var prev = message.prev('.message-' + (isSent ? 'sent' : 'received'));
            if (next.length === 0) {
                message.addClass('message-last message-with-tail');
            }
            else message.removeClass('message-last message-with-tail');

            if (prev.length === 0) {
                message.addClass('message-first');
            }
            else message.removeClass('message-first');

            if (prev.length > 0 && prev.find('.message-name').length > 0 && message.find('.message-name').length > 0) {
                if (prev.find('.message-name').text() !== message.find('.message-name').text()) {
                    prev.addClass('message-last message-with-tail');
                    message.addClass('message-first');
                }
            }
        });

    };

    // Add Message
    m.appendMessage = function (props) {
        return m.addMessage(props, 'append');
    };
    m.prependMessage = function (props) {
        return m.addMessage(props, 'prepend');
    };
    m.addMessage = function (props, method) {
        if (typeof method === 'undefined') {
            method = m.params.newMessagesFirst ? 'prepend' : 'append';
        }
        props = props || {};
        props.type = props.type || 'sent';
        if (!props.text) return false;

        props.hasImage = props.text.indexOf('= 0;
        props.position = method === 'append' ? 'bottom' : 'top';

        var messageHTML = m.template(props);
        m.container[method](messageHTML);

        if (m.params.autoLayout) m.layout();
        if ((method === 'append' && !m.params.newMessagesFirst) || (method === 'prepend' && m.params.newMessagesFirst)) {
            m.scrollMessages();
        }
    };
    m.clean = function () {
        m.container.html('');
    };

    // Scroll
    m.scrollMessages = function (duration) {
        if (typeof duration === 'undefined') duration = 400;
        var currentScroll = m.pageContent[0].scrollTop;
        var newScroll = m.params.newMessagesFirst ? 0 : m.pageContent[0].scrollHeight - m.pageContent[0].offsetHeight;
        if (newScroll === currentScroll) return;
        m.pageContent.scrollTop(newScroll, duration);
    };

    // Init Destroy
    m.init = function () {
        if (m.params.autoLayout) m.layout();
        m.scrollMessages(0);
    };
    m.destroy = function () {
        m = null;
    };

    // Init
    m.init();

    m.container[0].f7Messages = m;
    return m;
};
app.messages = function (container, params) {
    return new Messages (container, params);
};
app.initPageMessages = function (pageContainer) {
    pageContainer = $(pageContainer);
    var messages = pageContainer.find('.messages');
    if (messages.length === 0) return;
    if (!messages.hasClass('messages-init')) {
        return;
    }
    var m = app.messages(messages, messages.dataset());

    // Destroy on page remove
    function pageBeforeRemove() {
        m.destroy();
        pageContainer.off('pageBeforeRemove', pageBeforeRemove);
    }
    if (pageContainer.hasClass('page')) {
        pageContainer.on('pageBeforeRemove', pageBeforeRemove);
    }
};
<commit_msg>Improvements<commit_after>/*======================================================
************   Messages   ************
======================================================*/
var Messages = function (container, params) {
    var defaults = {
        autoLayout: true,
        newMessagesFirst: false,
        messageTemplate:
            '{{#if day}}' +
            '
{{day}} {{#if time}}, {{time}}{{/if}}
' +
            '{{/if}}' +
            '
' +
                '{{#if name}}
{{name}}
{{/if}}' +
                '
{{text}}
' +
                '{{#if avatar}}

{{/if}}' +
                '{{#if label}}
{{label}}
{{/if}}' +
            '
'
    };
    params = params || {};
    for (var def in defaults) {
        if (typeof params[def] === 'undefined' || params[def] === null) {
            params[def] = defaults[def];
        }
    }

    // Instance
    var m = this;

    // Params
    m.params = params;

    // Container
    m.container = $(container);
    if (m.container.length === 0) return;

    // Autolayout
    if (m.params.autoLayout) m.container.addClass('messages-auto-layout');

    // Is In Page
    m.pageContainer = m.container.parents('.page').eq(0);
    m.pageContent = m.pageContainer.find('.page-content');

    // Compiled template
    m.template = Template7.compile(m.params.messageTemplate);

    // Auto Layout
    m.layout = function () {
        if (!m.container.hasClass('messages-auto-layout')) m.container.addClass('messages-auto-layout');
        m.container.find('.message').each(function () {
            var message = $(this);
            if (message.find('.message-text img').length > 0) message.addClass('message-pic');
            if (message.find('.message-avatar').length > 0) message.addClass('message-with-avatar');
        });
        m.container.find('.message').each(function () {
            var message = $(this);
            var isSent = message.hasClass('message-sent');
            var next = message.next('.message-' + (isSent ? 'sent' : 'received'));
            var prev = message.prev('.message-' + (isSent ? 'sent' : 'received'));
            if (next.length === 0) {
                message.addClass('message-last message-with-tail');
            }
            else message.removeClass('message-last message-with-tail');

            if (prev.length === 0) {
                message.addClass('message-first');
            }
            else message.removeClass('message-first');

            if (prev.length > 0 && prev.find('.message-name').length > 0 && message.find('.message-name').length > 0) {
                if (prev.find('.message-name').text() !== message.find('.message-name').text()) {
                    prev.addClass('message-last message-with-tail');
                    message.addClass('message-first');
                }
            }
        });

    };

    // Add Message
    m.appendMessage = function (props, animate) {
        return m.addMessage(props, 'append', animate);
    };
    m.prependMessage = function (props, animate) {
        return m.addMessage(props, 'prepend', animate);
    };
    m.addMessage = function (props, method, animate) {
        return m.addMessages([props], method, animate);
    };
    m.addMessages = function (newMessages, method, animate) {
        if (typeof animate === 'undefined') {
            animate = true;
        }
        if (typeof method === 'undefined') {
            method = m.params.newMessagesFirst ? 'prepend' : 'append';
        }
        var newMessagesHTML = '', i;
        for (i = 0; i < newMessages.length; i++) {
            var props = newMessages[i] || {};
            props.type = props.type || 'sent';
            if (!props.text) continue;
            props.hasImage = props.text.indexOf('= 0;
            if (animate) props.position = method === 'append' ? 'bottom' : 'top';

            newMessagesHTML += m.template(props);
        }
        m.container[method](newMessagesHTML);

        if (m.params.autoLayout) m.layout();
        if ((method === 'append' && !m.params.newMessagesFirst) || (method === 'prepend' && m.params.newMessagesFirst)) {
            m.scrollMessages(animate ? undefined : 0);
        }
        var messages = m.container.find('.message');
        if (newMessages.length === 1) {
            return method === 'append' ? messages[messages.length - 1] : messages[0];
        }
        else {
            var messagesToReturn = [];
            if (method === 'append') {
                for (i = messages.length - newMessages.length; i < messages.length; i++) {
                    messagesToReturn.push(messages[i]);
                }
            }
            else {
                for (i = 0; i < newMessages.length; i++) {
                    messagesToReturn.push(messages[i]);
                }
            }
            return messagesToReturn;
        }

    };
    m.removeMessage = function (messageToRemove) {
        messageToRemove = $(messageToRemove);
        if (messageToRemove.length === 0) {
            return false;
        }
        else {
            messageToRemove.remove();
            if (m.params.autoLayout) m.layout();
            return true;
        }
    };
    m.removeMessages = function (messagesToRemove) {
        m.removeMessage(messagesToRemove);
    };
    m.clean = function () {
        m.container.html('');
    };

    // Scroll
    m.scrollMessages = function (duration) {
        if (typeof duration === 'undefined') duration = 400;
        var currentScroll = m.pageContent[0].scrollTop;
        var newScroll = m.params.newMessagesFirst ? 0 : m.pageContent[0].scrollHeight - m.pageContent[0].offsetHeight;
        if (newScroll === currentScroll) return;
        m.pageContent.scrollTop(newScroll, duration);
    };

    // Init Destroy
    m.init = function () {
        if (m.params.messages) {
            m.addMessages(m.params.messages, undefined, false);
        }
        else {
            if (m.params.autoLayout) m.layout();
            m.scrollMessages(0);
        }

    };
    m.destroy = function () {
        m = null;
    };

    // Init
    m.init();

    m.container[0].f7Messages = m;
    return m;
};
app.messages = function (container, params) {
    return new Messages (container, params);
};
app.initPageMessages = function (pageContainer) {
    pageContainer = $(pageContainer);
    var messages = pageContainer.find('.messages');
    if (messages.length === 0) return;
    if (!messages.hasClass('messages-init')) {
        return;
    }
    var m = app.messages(messages, messages.dataset());

    // Destroy on page remove
    function pageBeforeRemove() {
        m.destroy();
        pageContainer.off('pageBeforeRemove', pageBeforeRemove);
    }
    if (pageContainer.hasClass('page')) {
        pageContainer.on('pageBeforeRemove', pageBeforeRemove);
    }
};
<|endoftext|>


<commit_before>var util = require('util'),
    Tab = require('../client/tab').Tab;

var NotFoundTab = function ()
{
  Tab.call(this);
};

util.inherits(NotFoundTab, Tab);

NotFoundTab.prototype.tabName = '404';
NotFoundTab.prototype.mainMenu = 'none';

NotFoundTab.prototype.angularDeps = Tab.prototype.angularDeps.concat(['qr']);

NotFoundTab.prototype.generateHtml = function ()
{

  return require('../../jade/tabs/404.jade')();
};

NotFoundTab.prototype.angular = function (module)
{

  module.controller('NotFoundCtrl', ['$rootScope', 'rpId', 'rpNetwork', '$filter', '$http', 'rpAppManager',
                                     function ($scope, $id, $network, $filter, $http, appManager)
  {

  }]);

};

module.exports = NotFoundTab;

<commit_msg>[TASK] 404: Get rid of unneeded dependencies<commit_after>var util = require('util'),
    Tab = require('../client/tab').Tab;

var NotFoundTab = function ()
{
  Tab.call(this);
};

util.inherits(NotFoundTab, Tab);

NotFoundTab.prototype.tabName = '404';
NotFoundTab.prototype.mainMenu = 'none';

NotFoundTab.prototype.generateHtml = function ()
{

  return require('../../jade/tabs/404.jade')();
};

NotFoundTab.prototype.angular = function (module)
{
  module.controller('NotFoundCtrl', ['$scope', function ($scope)
  {

  }]);
};

module.exports = NotFoundTab;<|endoftext|>


<commit_before>document.getElementById("display").style.display = "none";
function displayBox() {
  document.getElementById("display").style.display = "block";
}
function closeBox() {
  document.getElementById("display").style.display = "none";
  document.getElementById("display1").style.display = "none";
}<commit_msg>updated tiles-list<commit_after>document.getElementById("display").style.display = "none";
function displayBox() {
  document.getElementById("display").style.display = "block";
}
function closeBox() {
  document.getElementById("display").style.display = "none";
}<|endoftext|>


<commit_before>import $ from 'jquery';
import {animationend, transitionend, requestAnimationFrame} from './env';
import {isString, extend} from './lang';

export const langDirection = $('html').attr('dir') == 'rtl' ? 'right' : 'left';

export function ready(fn) {

    var handle = function () {
        document.removeEventListener('DOMContentLoaded', handle);
        window.removeEventListener('load', handle);
        fn();
    };

    if (document.readyState === 'complete' || document.readyState !== 'loading' && !document.documentElement.doScroll) {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', handle);
        window.addEventListener('load', handle);
    }

}

export function transition(element, props, duration, transition) {

    var d = $.Deferred();

    element = $(element);

    for (var name in props) {
        element.css(name, element.css(name));
    }

    let timer = setTimeout(() => element.trigger(transitionend || 'transitionend'), duration);

    element
        .one(transitionend || 'transitionend', () => {
            clearTimeout(timer);
            element.removeClass('uk-transition').css('transition', '');
            d.resolve();
        })
        .addClass('uk-transition')
        .css('transition', `all ${duration}ms ${transition || 'linear'}`)
        .css(props);

    return d.promise();
}

export const Transition = {

    start: transition,

    stop(element) {

        element = $(element);

        $(element).trigger(transitionend || 'transitionend');

        return this;
    },

    inProgress(element) {
        return $(element).hasClass('uk-transition');
    }

};

export function animate(element, animation, duration, out) {

    var d = $.Deferred(), cls = out ? 'uk-animation-leave' : 'uk-animation-enter';

    element = $(element);

    if (out && animation.indexOf('uk-animation-') === 0) {
        animation += ' uk-animation-reverse';
    }

    reset();

    element
        .one(animationend || 'animationend', () => {
            reset();
            d.resolve();
        })
        .css('animation-duration', duration + 'ms')
        .addClass(animation);

    requestAnimationFrame(() => element.addClass(cls));

    if (!animationend) {
        requestAnimationFrame(() => Animation.cancel(element));
    }

    return d.promise();

    function reset() {
        element.css('animation-duration', '').removeClass(`${cls} ${animation}`);
    }
}

export const Animation = {

    in(element, animation, duration) {
        return animate(element, animation, duration, false);
    },

    out(element, animation, duration) {
        return animate(element, animation, duration, true);
    },

    inProgress(element) {
        return $(element).hasClass('uk-animation-enter') || $(element).hasClass('uk-animation-leave');
    },

    cancel(element) {
        $(element).trigger(animationend || 'animationend');
        return this;
    }

};

export function isWithin(element, selector) {
    element = $(element);
    return element.is(selector) || !!(isString(selector) ? element.parents(selector).length : $.contains(selector instanceof $ ? selector[0] : selector, element[0]));
}

export function attrFilter(element, attr, pattern, replacement) {
    element = $(element);
    element.attr(attr, (i, value) => value ? value.replace(pattern, replacement) : value);
    return element;
}

export function removeClass(element, cls) {
    return attrFilter(element, 'class', new RegExp(`(^|\\s)${cls}(?!\\S)`, 'g'), '');
}

export function createEvent(e) {
    if (isString(e)) {
        var ev = document.createEvent('Event');
        ev.initEvent(e, true, false);
        return ev;
    }
    return e;
}

export function isInView(element, offsetTop, offsetLeft) {

    element = $(element);

    if (!element.is(':visible')) {
        return false;
    }

    var win = $(window), scrollLeft = win.scrollLeft(), scrollTop = win.scrollTop(), offset = element.offset();

    return offset.top + element.height() >= scrollTop
        && offset.top - offsetTop <= scrollTop + win.height()
        && offset.left + element.width() >= scrollLeft
        && offset.left - offsetLeft <= scrollLeft + win.width();
}

export function getIndex(index, elements, current = 0) {

    elements = $(elements);

    var length = $(elements).length;

    index = (typeof index === 'number'
        ? index
        : index === 'next'
            ? current + 1
            : index === 'previous'
                ? current - 1
                : isString(index)
                    ? parseInt(index, 10)
                    : elements.index(index)
    ) % length;

    return index < 0 ? index + length : index;
}
<commit_msg>cleanup<commit_after>import $ from 'jquery';
import {animationend, extend, isString, transitionend, requestAnimationFrame} from './index';

export const langDirection = $('html').attr('dir') == 'rtl' ? 'right' : 'left';

export function ready(fn) {

    var handle = function () {
        document.removeEventListener('DOMContentLoaded', handle);
        window.removeEventListener('load', handle);
        fn();
    };

    if (document.readyState === 'complete' || document.readyState !== 'loading' && !document.documentElement.doScroll) {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', handle);
        window.addEventListener('load', handle);
    }

}

export function transition(element, props, duration, transition) {

    var d = $.Deferred();

    element = $(element);

    for (var name in props) {
        element.css(name, element.css(name));
    }

    let timer = setTimeout(() => element.trigger(transitionend || 'transitionend'), duration);

    element
        .one(transitionend || 'transitionend', () => {
            clearTimeout(timer);
            element.removeClass('uk-transition').css('transition', '');
            d.resolve();
        })
        .addClass('uk-transition')
        .css('transition', `all ${duration}ms ${transition || 'linear'}`)
        .css(props);

    return d.promise();
}

export const Transition = {

    start: transition,

    stop(element) {

        element = $(element);

        $(element).trigger(transitionend || 'transitionend');

        return this;
    },

    inProgress(element) {
        return $(element).hasClass('uk-transition');
    }

};

export function animate(element, animation, duration, out) {

    var d = $.Deferred(), cls = out ? 'uk-animation-leave' : 'uk-animation-enter';

    element = $(element);

    if (out && animation.indexOf('uk-animation-') === 0) {
        animation += ' uk-animation-reverse';
    }

    reset();

    element
        .one(animationend || 'animationend', () => {
            reset();
            d.resolve();
        })
        .css('animation-duration', duration + 'ms')
        .addClass(animation);

    requestAnimationFrame(() => element.addClass(cls));

    if (!animationend) {
        requestAnimationFrame(() => Animation.cancel(element));
    }

    return d.promise();

    function reset() {
        element.css('animation-duration', '').removeClass(`${cls} ${animation}`);
    }
}

export const Animation = {

    in(element, animation, duration) {
        return animate(element, animation, duration, false);
    },

    out(element, animation, duration) {
        return animate(element, animation, duration, true);
    },

    inProgress(element) {
        return $(element).hasClass('uk-animation-enter') || $(element).hasClass('uk-animation-leave');
    },

    cancel(element) {
        $(element).trigger(animationend || 'animationend');
        return this;
    }

};

export function isWithin(element, selector) {
    element = $(element);
    return element.is(selector) || !!(isString(selector) ? element.parents(selector).length : $.contains(selector instanceof $ ? selector[0] : selector, element[0]));
}

export function attrFilter(element, attr, pattern, replacement) {
    element = $(element);
    element.attr(attr, (i, value) => value ? value.replace(pattern, replacement) : value);
    return element;
}

export function removeClass(element, cls) {
    return attrFilter(element, 'class', new RegExp(`(^|\\s)${cls}(?!\\S)`, 'g'), '');
}

export function createEvent(e) {
    if (isString(e)) {
        var ev = document.createEvent('Event');
        ev.initEvent(e, true, false);
        return ev;
    }
    return e;
}

export function isInView(element, offsetTop, offsetLeft) {

    element = $(element);

    if (!element.is(':visible')) {
        return false;
    }

    var win = $(window), scrollLeft = win.scrollLeft(), scrollTop = win.scrollTop(), offset = element.offset();

    return offset.top + element.height() >= scrollTop
        && offset.top - offsetTop <= scrollTop + win.height()
        && offset.left + element.width() >= scrollLeft
        && offset.left - offsetLeft <= scrollLeft + win.width();
}

export function getIndex(index, elements, current = 0) {

    elements = $(elements);

    var length = $(elements).length;

    index = (typeof index === 'number'
        ? index
        : index === 'next'
            ? current + 1
            : index === 'previous'
                ? current - 1
                : isString(index)
                    ? parseInt(index, 10)
                    : elements.index(index)
    ) % length;

    return index < 0 ? index + length : index;
}
<|endoftext|>


<commit_before>(function(){
  ko.components.register("ko-dropdown", {
    viewModel: function(params){
      var self = this;

      self.caption = params.caption;
      self.value = params.value;
      self.options = params.options;

      self.dropdownOpen = ko.observable();

      self.selectedOption = ko.observable();
      self.selectedText = ko.computed(function() {
        return ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).text : "";
      });

      self.selectOption = function(option){
        self.value(option.value);
        self.selectedOption(option);
      }

      self.dropdownOptions = ko.computed(function(){
        var retOptions = [];
        self.options().forEach(function(option){
          if (typeof option === 'object' || option instanceof Object){
            retOptions.push(option);
          } else {
            retOptions.push({
              value: option,
              text: option
            });
          }
        });

        if (retOptions.length > 0 && !ko.unwrap(self.caption)) {
          self.selectOption(retOptions[0]);
        }

        return retOptions;
      });

      if (ko.unwrap(self.value)){
        self.selectedOption(findOptionByValue(ko.unwrap(self.value)));
      } else if (ko.unwrap(self.caption)){
        self.selectedOption({
          text: self.caption
        });
      }

      self.toggleOpen = function(data, event){
        event.stopPropagation();
        self.dropdownOpen(!self.dropdownOpen());
      }

      self.value.subscribe(function(newValue){
        var selectedValue = ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).value : null;

        if (newValue !== selectedValue){
          var option = findOptionByValue(newValue);
          if (option != null){
            self.selectOption(option);
          }
        }
      });

      window.addEventListener('click', function (e) {
          self.dropdownOpen(false);
      });

      function findOptionByValue(val){
        var foundOption = null;
        if (ko.unwrap(self.dropdownOptions)){
          self.dropdownOptions().forEach(function(option){
            if (option.value === val){
              foundOption = option;
            }
          });
        }
        return foundOption;
      }
    },
    template: "
\
        \

\

\

\

"
  });

}());
<commit_msg>Fixed some issues with async options<commit_after>(function () {
    ko.components.register("ko-dropdown", {
        viewModel: function (params) {
            var self = this;

            self.caption = params.caption;
            self.value = params.value;
            self.options = params.options;

            self.dropdownOpen = ko.observable(false);

            self.selectedOption = ko.observable();
            self.selectedText = ko.computed(function () {
                return ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).text : "";
            });

            self.selectOption = function (option) {
                self.value(option.value);
                self.selectedOption(option);
            }

            self.dropdownOptions = ko.computed(function () {
                var retOptions = [];
                self.options().forEach(function (option) {
                    if (typeof option === 'object' || option instanceof Object) {
                        retOptions.push(option);
                    } else {
                        retOptions.push({
                            value: option,
                            text: option
                        });
                    }
                });

                if (retOptions.length > 0 && !ko.unwrap(self.caption)) {
                    self.selectOption(retOptions[0]);
                }

                return retOptions;
            });

            self.dropdownOptions.subscribe(function () {
                self.value.notifySubscribers(self.value()); // so if dropdown options change, update selected value
            })

            if (ko.unwrap(self.value)) {
                self.selectedOption(findOptionByValue(ko.unwrap(self.value)));
            } else if (ko.unwrap(self.caption)) {
                self.selectedOption({
                    text: self.caption
                });
            }

            self.toggleOpen = function (data, event) {
                event.stopPropagation();
                self.dropdownOpen(!self.dropdownOpen());
            }

            self.value.subscribe(function (newValue) {
                var selectedValue = ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).value : null;

                if (newValue !== selectedValue) {
                    var option = findOptionByValue(newValue);
                    if (option != null) {
                        self.selectOption(option);
                    }
                }
            });

            window.addEventListener('click', function (e) {
                self.dropdownOpen(false);
            });

            function findOptionByValue(val) {
                var foundOption = null;
                if (ko.unwrap(self.dropdownOptions)) {
                    self.dropdownOptions().forEach(function (option) {
                        if (option.value === val) {
                            foundOption = option;
                        }
                    });
                }
                return foundOption;
            }
        },
        template: "
\
        \

\

\

\

"
    });

}());
<|endoftext|>


<commit_before>/** section: Language
 * class String
 *
 *  Extensions to the built-in `String` class.
 *
 *  Prototype enhances the `String` object with a series of useful methods for
 *  ranging from the trivial to the complex. Tired of stripping trailing
 *  whitespace? Try [[String#strip]]. Want to replace `replace`? Have a look at
 *  [[String#sub]] and [[String#gsub]]. Need to parse a query string? We have
 *  [[String#toQueryParams]].
**/
Object.extend(String, {
  /**
   *  String.interpret(value) -> String
   *
   *  Coerces `value` into a string. Returns an empty string for `null`.
  **/
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

Object.extend(String.prototype, (function() {
  var scriptFragmentMatchAll = new RegExp(Prototype.ScriptFragment, 'ig');
  var scriptFragmentMatchOne = new RegExp(Prototype.ScriptFragment, 'i');

  function prepareReplacement(replacement) {
    if (Object.isFunction(replacement)) return replacement;
    var template = new Template(replacement);
    return function(match) { return template.evaluate(match); };
  }

  /**
   *  String#gsub(pattern, replacement) -> String
   *
   *  Returns the string with every occurence of a given pattern replaced by either
   *  a regular string, the returned value of a function or a [[Template]] string.
   *  The pattern can be a string or a regular expression.
  **/
  function gsub(pattern, replacement) {
    var result = '', source = this, match;
    replacement = prepareReplacement(replacement);

    if (Object.isString(pattern))
      pattern = RegExp.escape(pattern);

    if (!(pattern.length || pattern.source)) {
      replacement = replacement('');
      return replacement + source.split('').join(replacement) + replacement;
    }

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source;
        source = '';
      }
    }
    return result;
  }

  /**
   *  String#sub(pattern, replacement[, count = 1]) -> String
   *
   *  Returns a string with the first count occurrences of pattern replaced by either
   *  a regular string, the returned value of a function or a [[Template]] string.
   *  The pattern can be a string or a regular expression.
  **/
  function sub(pattern, replacement, count) {
    replacement = prepareReplacement(replacement);
    count = Object.isUndefined(count) ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  }

  /** related to: String#gsub
   *  String#scan(pattern, iterator) -> String
   *
   *  Allows iterating over every occurrence of the given pattern (which can be a
   *  string or a regular expression).
   *  Returns the original string.
  **/
  function scan(pattern, iterator) {
    this.gsub(pattern, iterator);
    return String(this);
  }

  /**
   *  String#truncate([length = 30[, suffix = '...']]) -> String
   *
   *  Truncates a string to given `length` and appends `suffix` to it (indicating
   *  that it is only an excerpt).
  **/
  function truncate(length, truncation) {
    length = length || 30;
    truncation = Object.isUndefined(truncation) ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : String(this);
  }

  /**
   *  String#strip() -> String
   *
   *  Strips all leading and trailing whitespace from a string.
  **/
  function strip() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  }

  /**
   *  String#stripTags() -> String
   *
   *  Strips a string of any HTML tag.
   *  Note that `stripTags` will only strip HTML4.01 tags (such as - div, span and abbr)
   *  It will not strip namespace-prefixed tags such as "h:table" or "xsl:template"
  **/
  function stripTags() {
    return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
  }

  /**
   *  String#stripScripts() -> String
   *
   *  Strips a string of anything that looks like an HTML script block.
  **/
  function stripScripts() {
    return this.replace(scriptFragmentMatchAll, '');
  }

  /**
   *  String#extractScripts() -> Array
   *
   *  Exctracts the content of any script block present in the string and returns
   *  them as an array of strings.
  **/
  function extractScripts() {
    return (this.match(scriptFragmentMatchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(scriptFragmentMatchOne) || ['', ''])[1];
    });
  }

  /**
   *  String#evalScripts() -> Array
   *
   *  Evaluates the content of any script block present in the string.
   *  Returns an array containing the value returned by each script.
  **/
  function evalScripts() {
    return this.extractScripts().map(function(script) { return eval(script); });
  }

  /**
   *  String#escapeHTML() -> String
   *
   *  Converts HTML special characters to their entity equivalents.
  **/
  function escapeHTML() {
    escapeHTML.text.data = this;
    return escapeHTML.div.innerHTML;
  }

  /** related to: String#escapeHTML
   *  String#unescapeHTML() -> String
   *
   *  Strips tags and converts the entity forms of special HTML characters to their normal form.
  **/
  function unescapeHTML() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue; }) :
      div.childNodes[0].nodeValue) : '';
  }

  /** alias of: String#parseQuery, related to: Hash#toQueryString
   *  String#toQueryParams([separator = '&']) -> Object
   *
   *  Parses a URI-like query string and returns an object composed of parameter/value pairs.
  **/
  function toQueryParams(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return { };

    return match[1].split(separator || '&').inject({ }, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  }

  /**
   *  String#toArray() -> Array
   *
   *  Splits the string character-by-character and returns an array with the result.
  **/
  function toArray() {
    return this.split('');
  }

  /**
   *  String#succ() -> String
   *
   *  Used internally by ObjectRange.
   *  Converts the last character of the string to the following character in the
   *  Unicode alphabet.
  **/
  function succ() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  }

  /**
   *  String#times(count) -> String
   *
   *  Concatenates the string `count` times.
  **/
  function times(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
  }

  /**
   *  String#camelize() -> String
   *
   *  Converts a string separated by dashes into a camelCase equivalent.
   *  For instance, 'foo-bar' would be converted to 'fooBar'.
  **/
  function camelize() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? (parts[0].charAt(0).toUpperCase() + parts[0].substring(1))
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  }

  /**
   *  String#capitalize() -> String
   *
   *  Capitalizes the first letter of a string and downcases all the others.
  **/
  function capitalize() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  }

  /**
   *  String#underscore() -> String
   *
   *  Converts a camelized string into a series of words separated by an underscore ("_").
  **/
  function underscore() {
    return this.replace(/::/g, '/')
               .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
               .replace(/([a-z\d])([A-Z])/g, '$1_$2')
               .replace(/-/g, '_')
               .toLowerCase();
  }

  /**
   *  String#dasherize() -> String
   *
   *  Replaces every instance of the underscore character ("_") by a dash ("-").
  **/
  function dasherize() {
    return this.replace(/_/g, '-');
  }

  /** related to: Object.inspect
   *  String#inspect([useDoubleQuotes = false]) -> String
   *
   *  Returns a debug-oriented version of the string (i.e. wrapped in single or
   *  double quotes, with backslashes and quotes escaped).
  **/
  function inspect(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }

  /** related to: Object.toJSON
   *  String#toJSON() -> String
   *
   *  Returns a JSON string.
  **/
  function toJSON() {
    return this.inspect(true);
  }

  /**
   *  String#unfilterJSON([filter = Prototype.JSONFilter]) -> String
   *
   *  Strips comment delimiters around Ajax JSON or JavaScript responses.
   *  This security method is called internally.
  **/
  function unfilterJSON(filter) {
    return this.replace(filter || Prototype.JSONFilter, '$1');
  }

  /**
   *  String#isJSON() -> Boolean
   *
   *  Check if the string is valid JSON by the use of regular expressions.
   *  This security method is called internally.
  **/
  function isJSON() {
    var str = this;
    if (str.blank()) return false;
    str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  }

  /**
   *  String#evalJSON([sanitize = false]) -> object
   *
   *  Evaluates the JSON in the string and returns the resulting object.
   *  If the optional sanitize parameter is set to true, the string is checked for
   *  possible malicious attempts and eval is not called if one is detected.
  **/
  function evalJSON(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  }

  /**
   *  String#include(substring) -> Boolean
   *
   *  Check if the string contains a substring.
  **/
  function include(pattern) {
    return this.indexOf(pattern) > -1;
  }

  /**
   *  String#startsWith(substring) -> Boolean
   *
   *  Checks if the string starts with substring.
  **/
  function startsWith(pattern) {
    return this.indexOf(pattern) === 0;
  }

  /**
   *  String#endsWith(substring) -> Boolean
   *
   *  Checks if the string ends with substring.
  **/
  function endsWith(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  }

  /**
   *  String#empty() -> Boolean
   *
   *  Checks if the string is empty.
  **/
  function empty() {
    return this == '';
  }

  /**
   *  String#blank() -> Boolean
   *
   *  Check if the string is 'blank', meaning either empty or containing only whitespace.
  **/
  function blank() {
    return /^\s*$/.test(this);
  }

  /**
   *  String#interpolate(object[, pattern]) -> String
   *
   *  Treats the string as a Template and fills it with object’s properties.
  **/
  function interpolate(object, pattern) {
    return new Template(this, pattern).evaluate(object);
  }

  return {
    gsub:           gsub,
    sub:            sub,
    scan:           scan,
    truncate:       truncate,
    // Firefox 3.5+ supports String.prototype.trim
    // (`trim` is ~ 5x faster than `strip` in FF3.5)
    strip:          String.prototype.trim ? String.prototype.trim : strip,
    stripTags:      stripTags,
    stripScripts:   stripScripts,
    extractScripts: extractScripts,
    evalScripts:    evalScripts,
    escapeHTML:     escapeHTML,
    unescapeHTML:   unescapeHTML,
    toQueryParams:  toQueryParams,
    parseQuery:     toQueryParams,
    toArray:        toArray,
    succ:           succ,
    times:          times,
    camelize:       camelize,
    capitalize:     capitalize,
    underscore:     underscore,
    dasherize:      dasherize,
    inspect:        inspect,
    toJSON:         toJSON,
    unfilterJSON:   unfilterJSON,
    isJSON:         isJSON,
    evalJSON:       evalJSON,
    include:        include,
    startsWith:     startsWith,
    endsWith:       endsWith,
    empty:          empty,
    blank:          blank,
    interpolate:    interpolate
  };
})());

Object.extend(String.prototype.escapeHTML, {
  div:  document.createElement('div'),
  text: document.createTextNode('')
});

String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);

if ('<\n>'.escapeHTML() !== '<\n>') {
  String.prototype.escapeHTML = function() {
    return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
  };
}

if ('<\n>'.unescapeHTML() !== '<\n>') {
  String.prototype.unescapeHTML = function() {
    return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
  };
}<commit_msg>Remove redundant ternary<commit_after>/** section: Language
 * class String
 *
 *  Extensions to the built-in `String` class.
 *
 *  Prototype enhances the `String` object with a series of useful methods for
 *  ranging from the trivial to the complex. Tired of stripping trailing
 *  whitespace? Try [[String#strip]]. Want to replace `replace`? Have a look at
 *  [[String#sub]] and [[String#gsub]]. Need to parse a query string? We have
 *  [[String#toQueryParams]].
**/
Object.extend(String, {
  /**
   *  String.interpret(value) -> String
   *
   *  Coerces `value` into a string. Returns an empty string for `null`.
  **/
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

Object.extend(String.prototype, (function() {
  var scriptFragmentMatchAll = new RegExp(Prototype.ScriptFragment, 'ig');
  var scriptFragmentMatchOne = new RegExp(Prototype.ScriptFragment, 'i');

  function prepareReplacement(replacement) {
    if (Object.isFunction(replacement)) return replacement;
    var template = new Template(replacement);
    return function(match) { return template.evaluate(match); };
  }

  /**
   *  String#gsub(pattern, replacement) -> String
   *
   *  Returns the string with every occurence of a given pattern replaced by either
   *  a regular string, the returned value of a function or a [[Template]] string.
   *  The pattern can be a string or a regular expression.
  **/
  function gsub(pattern, replacement) {
    var result = '', source = this, match;
    replacement = prepareReplacement(replacement);

    if (Object.isString(pattern))
      pattern = RegExp.escape(pattern);

    if (!(pattern.length || pattern.source)) {
      replacement = replacement('');
      return replacement + source.split('').join(replacement) + replacement;
    }

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source;
        source = '';
      }
    }
    return result;
  }

  /**
   *  String#sub(pattern, replacement[, count = 1]) -> String
   *
   *  Returns a string with the first count occurrences of pattern replaced by either
   *  a regular string, the returned value of a function or a [[Template]] string.
   *  The pattern can be a string or a regular expression.
  **/
  function sub(pattern, replacement, count) {
    replacement = prepareReplacement(replacement);
    count = Object.isUndefined(count) ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  }

  /** related to: String#gsub
   *  String#scan(pattern, iterator) -> String
   *
   *  Allows iterating over every occurrence of the given pattern (which can be a
   *  string or a regular expression).
   *  Returns the original string.
  **/
  function scan(pattern, iterator) {
    this.gsub(pattern, iterator);
    return String(this);
  }

  /**
   *  String#truncate([length = 30[, suffix = '...']]) -> String
   *
   *  Truncates a string to given `length` and appends `suffix` to it (indicating
   *  that it is only an excerpt).
  **/
  function truncate(length, truncation) {
    length = length || 30;
    truncation = Object.isUndefined(truncation) ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : String(this);
  }

  /**
   *  String#strip() -> String
   *
   *  Strips all leading and trailing whitespace from a string.
  **/
  function strip() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  }

  /**
   *  String#stripTags() -> String
   *
   *  Strips a string of any HTML tag.
   *  Note that `stripTags` will only strip HTML4.01 tags (such as - div, span and abbr)
   *  It will not strip namespace-prefixed tags such as "h:table" or "xsl:template"
  **/
  function stripTags() {
    return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
  }

  /**
   *  String#stripScripts() -> String
   *
   *  Strips a string of anything that looks like an HTML script block.
  **/
  function stripScripts() {
    return this.replace(scriptFragmentMatchAll, '');
  }

  /**
   *  String#extractScripts() -> Array
   *
   *  Exctracts the content of any script block present in the string and returns
   *  them as an array of strings.
  **/
  function extractScripts() {
    return (this.match(scriptFragmentMatchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(scriptFragmentMatchOne) || ['', ''])[1];
    });
  }

  /**
   *  String#evalScripts() -> Array
   *
   *  Evaluates the content of any script block present in the string.
   *  Returns an array containing the value returned by each script.
  **/
  function evalScripts() {
    return this.extractScripts().map(function(script) { return eval(script); });
  }

  /**
   *  String#escapeHTML() -> String
   *
   *  Converts HTML special characters to their entity equivalents.
  **/
  function escapeHTML() {
    escapeHTML.text.data = this;
    return escapeHTML.div.innerHTML;
  }

  /** related to: String#escapeHTML
   *  String#unescapeHTML() -> String
   *
   *  Strips tags and converts the entity forms of special HTML characters to their normal form.
  **/
  function unescapeHTML() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue; }) :
      div.childNodes[0].nodeValue) : '';
  }

  /** alias of: String#parseQuery, related to: Hash#toQueryString
   *  String#toQueryParams([separator = '&']) -> Object
   *
   *  Parses a URI-like query string and returns an object composed of parameter/value pairs.
  **/
  function toQueryParams(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return { };

    return match[1].split(separator || '&').inject({ }, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  }

  /**
   *  String#toArray() -> Array
   *
   *  Splits the string character-by-character and returns an array with the result.
  **/
  function toArray() {
    return this.split('');
  }

  /**
   *  String#succ() -> String
   *
   *  Used internally by ObjectRange.
   *  Converts the last character of the string to the following character in the
   *  Unicode alphabet.
  **/
  function succ() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  }

  /**
   *  String#times(count) -> String
   *
   *  Concatenates the string `count` times.
  **/
  function times(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
  }

  /**
   *  String#camelize() -> String
   *
   *  Converts a string separated by dashes into a camelCase equivalent.
   *  For instance, 'foo-bar' would be converted to 'fooBar'.
  **/
  function camelize() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? (parts[0].charAt(0).toUpperCase() + parts[0].substring(1))
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  }

  /**
   *  String#capitalize() -> String
   *
   *  Capitalizes the first letter of a string and downcases all the others.
  **/
  function capitalize() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  }

  /**
   *  String#underscore() -> String
   *
   *  Converts a camelized string into a series of words separated by an underscore ("_").
  **/
  function underscore() {
    return this.replace(/::/g, '/')
               .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
               .replace(/([a-z\d])([A-Z])/g, '$1_$2')
               .replace(/-/g, '_')
               .toLowerCase();
  }

  /**
   *  String#dasherize() -> String
   *
   *  Replaces every instance of the underscore character ("_") by a dash ("-").
  **/
  function dasherize() {
    return this.replace(/_/g, '-');
  }

  /** related to: Object.inspect
   *  String#inspect([useDoubleQuotes = false]) -> String
   *
   *  Returns a debug-oriented version of the string (i.e. wrapped in single or
   *  double quotes, with backslashes and quotes escaped).
  **/
  function inspect(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }

  /** related to: Object.toJSON
   *  String#toJSON() -> String
   *
   *  Returns a JSON string.
  **/
  function toJSON() {
    return this.inspect(true);
  }

  /**
   *  String#unfilterJSON([filter = Prototype.JSONFilter]) -> String
   *
   *  Strips comment delimiters around Ajax JSON or JavaScript responses.
   *  This security method is called internally.
  **/
  function unfilterJSON(filter) {
    return this.replace(filter || Prototype.JSONFilter, '$1');
  }

  /**
   *  String#isJSON() -> Boolean
   *
   *  Check if the string is valid JSON by the use of regular expressions.
   *  This security method is called internally.
  **/
  function isJSON() {
    var str = this;
    if (str.blank()) return false;
    str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  }

  /**
   *  String#evalJSON([sanitize = false]) -> object
   *
   *  Evaluates the JSON in the string and returns the resulting object.
   *  If the optional sanitize parameter is set to true, the string is checked for
   *  possible malicious attempts and eval is not called if one is detected.
  **/
  function evalJSON(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  }

  /**
   *  String#include(substring) -> Boolean
   *
   *  Check if the string contains a substring.
  **/
  function include(pattern) {
    return this.indexOf(pattern) > -1;
  }

  /**
   *  String#startsWith(substring) -> Boolean
   *
   *  Checks if the string starts with substring.
  **/
  function startsWith(pattern) {
    return this.indexOf(pattern) === 0;
  }

  /**
   *  String#endsWith(substring) -> Boolean
   *
   *  Checks if the string ends with substring.
  **/
  function endsWith(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  }

  /**
   *  String#empty() -> Boolean
   *
   *  Checks if the string is empty.
  **/
  function empty() {
    return this == '';
  }

  /**
   *  String#blank() -> Boolean
   *
   *  Check if the string is 'blank', meaning either empty or containing only whitespace.
  **/
  function blank() {
    return /^\s*$/.test(this);
  }

  /**
   *  String#interpolate(object[, pattern]) -> String
   *
   *  Treats the string as a Template and fills it with object’s properties.
  **/
  function interpolate(object, pattern) {
    return new Template(this, pattern).evaluate(object);
  }

  return {
    gsub:           gsub,
    sub:            sub,
    scan:           scan,
    truncate:       truncate,
    // Firefox 3.5+ supports String.prototype.trim
    // (`trim` is ~ 5x faster than `strip` in FF3.5)
    strip:          String.prototype.trim || strip,
    stripTags:      stripTags,
    stripScripts:   stripScripts,
    extractScripts: extractScripts,
    evalScripts:    evalScripts,
    escapeHTML:     escapeHTML,
    unescapeHTML:   unescapeHTML,
    toQueryParams:  toQueryParams,
    parseQuery:     toQueryParams,
    toArray:        toArray,
    succ:           succ,
    times:          times,
    camelize:       camelize,
    capitalize:     capitalize,
    underscore:     underscore,
    dasherize:      dasherize,
    inspect:        inspect,
    toJSON:         toJSON,
    unfilterJSON:   unfilterJSON,
    isJSON:         isJSON,
    evalJSON:       evalJSON,
    include:        include,
    startsWith:     startsWith,
    endsWith:       endsWith,
    empty:          empty,
    blank:          blank,
    interpolate:    interpolate
  };
})());

Object.extend(String.prototype.escapeHTML, {
  div:  document.createElement('div'),
  text: document.createTextNode('')
});

String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);

if ('<\n>'.escapeHTML() !== '<\n>') {
  String.prototype.escapeHTML = function() {
    return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
  };
}

if ('<\n>'.unescapeHTML() !== '<\n>') {
  String.prototype.unescapeHTML = function() {
    return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
  };
}<|endoftext|>


<commit_before>
L.Map.mergeOptions({
	closePopupOnClick: true
});

L.Popup = L.Class.extend({
	includes: L.Mixin.Events,

	options: {
		minWidth: 50,
		maxWidth: 300,
		maxHeight: null,
		autoPan: true,
		closeButton: true,
		offset: new L.Point(0, 2),
		autoPanPadding: new L.Point(5, 5),
		className: ''
	},

	initialize: function (options, source) {
		L.Util.setOptions(this, options);

		this._source = source;
	},

	onAdd: function (map) {
		this._map = map;

		if (!this._container) {
			this._initLayout();
		}
		this._updateContent();

		L.DomUtil.setOpacity(this._container, 0);
		map._panes.popupPane.appendChild(this._container);

		map.on('viewreset', this._updatePosition, this);

		if (L.Browser.any3d) {
			map.on('zoomanim', this._zoomAnimation, this);
		}

		if (map.options.closePopupOnClick) {
			map.on('preclick', this._close, this);
		}

		this._update();

		L.DomUtil.setOpacity(this._container, 1);
	},

	addTo: function (map) {
		map.addLayer(this);
		return this;
	},

	onRemove: function (map) {
		map._panes.popupPane.removeChild(this._container);

		L.Util.falseFn(this._container.offsetWidth); // force reflow

		map.off({
			viewreset: this._updatePosition,
			preclick: this._close,
			zoomanim: this._zoomAnimation
		}, this);

		L.DomUtil.setOpacity(this._container, 0);

		this._map = null;
	},

	setLatLng: function (latlng) {
		this._latlng = L.latLng(latlng);
		this._update();
		return this;
	},

	setContent: function (content) {
		this._content = content;
		this._update();
		return this;
	},

	_close: function () {
		var map = this._map;

		if (map) {
			map._popup = null;

			map
				.removeLayer(this)
				.fire('popupclose', {popup: this});
		}
	},

	_initLayout: function () {
		var prefix = 'leaflet-popup',
			container = this._container = L.DomUtil.create('div', prefix + ' ' + this.options.className + ' leaflet-zoom-animated'),
			closeButton;

		if (this.options.closeButton) {
			closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
			closeButton.href = '#close';

			L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
		}

		var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
		L.DomEvent.disableClickPropagation(wrapper);

		this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
		L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);

		this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
		this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
	},

	_update: function () {
		if (!this._map) { return; }

		this._container.style.visibility = 'hidden';

		this._updateContent();
		this._updateLayout();
		this._updatePosition();

		this._container.style.visibility = '';

		this._adjustPan();
	},

	_updateContent: function () {
		if (!this._content) { return; }

		if (typeof this._content === 'string') {
			this._contentNode.innerHTML = this._content;
		} else {
			while (this._contentNode.hasChildNodes()) {
				this._contentNode.removeChild(this._contentNode.firstChild);
			}
			this._contentNode.appendChild(this._content);
		}
		this.fire('contentupdate');
	},

	_updateLayout: function () {
		var container = this._contentNode,
			style = container.style;

		style.width = '';
		style.whiteSpace = 'nowrap';

		var width = container.offsetWidth;
		width = Math.min(width, this.options.maxWidth);
		width = Math.max(width, this.options.minWidth);

		style.width = (width + 1) + 'px';
		style.whiteSpace = '';

		style.height = '';

		var height = container.offsetHeight,
			maxHeight = this.options.maxHeight,
			scrolledClass = 'leaflet-popup-scrolled';

		if (maxHeight && height > maxHeight) {
			style.height = maxHeight + 'px';
			L.DomUtil.addClass(container, scrolledClass);
		} else {
			L.DomUtil.removeClass(container, scrolledClass);
		}

		this._containerWidth = this._container.offsetWidth;
	},

	_updatePosition: function () {
		var pos = this._map.latLngToLayerPoint(this._latlng),
			is3d = L.Browser.any3d,
			offset = this.options.offset;

		if (is3d) {
			L.DomUtil.setPosition(this._container, pos);
		}

		this._containerBottom = -offset.y - (is3d ? 0 : pos.y);
		this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (is3d ? 0 : pos.x);

		//Bottom position the popup in case the height of the popup changes (images loading etc)
		this._container.style.bottom = this._containerBottom + 'px';
		this._container.style.left = this._containerLeft + 'px';
	},

	_zoomAnimation: function (opt) {
		var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center)._round();

		L.DomUtil.setPosition(this._container, pos);
	},

	_adjustPan: function () {
		if (!this.options.autoPan) { return; }

		var map = this._map,
			containerHeight = this._container.offsetHeight,
			containerWidth = this._containerWidth,

			layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);

		if (L.Browser.any3d) {
			layerPos._add(L.DomUtil.getPosition(this._container));
		}

		var containerPos = map.layerPointToContainerPoint(layerPos),
			padding = this.options.autoPanPadding,
			size = map.getSize(),
			dx = 0,
			dy = 0;

		if (containerPos.x < 0) {
			dx = containerPos.x - padding.x;
		}
		if (containerPos.x + containerWidth > size.x) {
			dx = containerPos.x + containerWidth - size.x + padding.x;
		}
		if (containerPos.y < 0) {
			dy = containerPos.y - padding.y;
		}
		if (containerPos.y + containerHeight > size.y) {
			dy = containerPos.y + containerHeight - size.y + padding.y;
		}

		if (dx || dy) {
			map.panBy(new L.Point(dx, dy));
		}
	},

	_onCloseButtonClick: function (e) {
		this._close();
		L.DomEvent.stop(e);
	}
});

L.popup = function (options, source) {
	return new L.Popup(options, source);
};
<commit_msg>add Popup openOn(map)<commit_after>
L.Map.mergeOptions({
	closePopupOnClick: true
});

L.Popup = L.Class.extend({
	includes: L.Mixin.Events,

	options: {
		minWidth: 50,
		maxWidth: 300,
		maxHeight: null,
		autoPan: true,
		closeButton: true,
		offset: new L.Point(0, 2),
		autoPanPadding: new L.Point(5, 5),
		className: ''
	},

	initialize: function (options, source) {
		L.Util.setOptions(this, options);

		this._source = source;
	},

	onAdd: function (map) {
		this._map = map;

		if (!this._container) {
			this._initLayout();
		}
		this._updateContent();

		L.DomUtil.setOpacity(this._container, 0);
		map._panes.popupPane.appendChild(this._container);

		map.on('viewreset', this._updatePosition, this);

		if (L.Browser.any3d) {
			map.on('zoomanim', this._zoomAnimation, this);
		}

		if (map.options.closePopupOnClick) {
			map.on('preclick', this._close, this);
		}

		this._update();

		L.DomUtil.setOpacity(this._container, 1);
	},

	addTo: function (map) {
		map.addLayer(this);
		return this;
	},

	openOn: function (map) {
		map.openPopup(this);
		return this;
	},

	onRemove: function (map) {
		map._panes.popupPane.removeChild(this._container);

		L.Util.falseFn(this._container.offsetWidth); // force reflow

		map.off({
			viewreset: this._updatePosition,
			preclick: this._close,
			zoomanim: this._zoomAnimation
		}, this);

		L.DomUtil.setOpacity(this._container, 0);

		this._map = null;
	},

	setLatLng: function (latlng) {
		this._latlng = L.latLng(latlng);
		this._update();
		return this;
	},

	setContent: function (content) {
		this._content = content;
		this._update();
		return this;
	},

	_close: function () {
		var map = this._map;

		if (map) {
			map._popup = null;

			map
				.removeLayer(this)
				.fire('popupclose', {popup: this});
		}
	},

	_initLayout: function () {
		var prefix = 'leaflet-popup',
			container = this._container = L.DomUtil.create('div', prefix + ' ' + this.options.className + ' leaflet-zoom-animated'),
			closeButton;

		if (this.options.closeButton) {
			closeButton = this._closeButton = L.DomUtil.create('a', prefix + '-close-button', container);
			closeButton.href = '#close';

			L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
		}

		var wrapper = this._wrapper = L.DomUtil.create('div', prefix + '-content-wrapper', container);
		L.DomEvent.disableClickPropagation(wrapper);

		this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
		L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);

		this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
		this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
	},

	_update: function () {
		if (!this._map) { return; }

		this._container.style.visibility = 'hidden';

		this._updateContent();
		this._updateLayout();
		this._updatePosition();

		this._container.style.visibility = '';

		this._adjustPan();
	},

	_updateContent: function () {
		if (!this._content) { return; }

		if (typeof this._content === 'string') {
			this._contentNode.innerHTML = this._content;
		} else {
			while (this._contentNode.hasChildNodes()) {
				this._contentNode.removeChild(this._contentNode.firstChild);
			}
			this._contentNode.appendChild(this._content);
		}
		this.fire('contentupdate');
	},

	_updateLayout: function () {
		var container = this._contentNode,
			style = container.style;

		style.width = '';
		style.whiteSpace = 'nowrap';

		var width = container.offsetWidth;
		width = Math.min(width, this.options.maxWidth);
		width = Math.max(width, this.options.minWidth);

		style.width = (width + 1) + 'px';
		style.whiteSpace = '';

		style.height = '';

		var height = container.offsetHeight,
			maxHeight = this.options.maxHeight,
			scrolledClass = 'leaflet-popup-scrolled';

		if (maxHeight && height > maxHeight) {
			style.height = maxHeight + 'px';
			L.DomUtil.addClass(container, scrolledClass);
		} else {
			L.DomUtil.removeClass(container, scrolledClass);
		}

		this._containerWidth = this._container.offsetWidth;
	},

	_updatePosition: function () {
		var pos = this._map.latLngToLayerPoint(this._latlng),
			is3d = L.Browser.any3d,
			offset = this.options.offset;

		if (is3d) {
			L.DomUtil.setPosition(this._container, pos);
		}

		this._containerBottom = -offset.y - (is3d ? 0 : pos.y);
		this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (is3d ? 0 : pos.x);

		//Bottom position the popup in case the height of the popup changes (images loading etc)
		this._container.style.bottom = this._containerBottom + 'px';
		this._container.style.left = this._containerLeft + 'px';
	},

	_zoomAnimation: function (opt) {
		var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center)._round();

		L.DomUtil.setPosition(this._container, pos);
	},

	_adjustPan: function () {
		if (!this.options.autoPan) { return; }

		var map = this._map,
			containerHeight = this._container.offsetHeight,
			containerWidth = this._containerWidth,

			layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);

		if (L.Browser.any3d) {
			layerPos._add(L.DomUtil.getPosition(this._container));
		}

		var containerPos = map.layerPointToContainerPoint(layerPos),
			padding = this.options.autoPanPadding,
			size = map.getSize(),
			dx = 0,
			dy = 0;

		if (containerPos.x < 0) {
			dx = containerPos.x - padding.x;
		}
		if (containerPos.x + containerWidth > size.x) {
			dx = containerPos.x + containerWidth - size.x + padding.x;
		}
		if (containerPos.y < 0) {
			dy = containerPos.y - padding.y;
		}
		if (containerPos.y + containerHeight > size.y) {
			dy = containerPos.y + containerHeight - size.y + padding.y;
		}

		if (dx || dy) {
			map.panBy(new L.Point(dx, dy));
		}
	},

	_onCloseButtonClick: function (e) {
		this._close();
		L.DomEvent.stop(e);
	}
});

L.popup = function (options, source) {
	return new L.Popup(options, source);
};
<|endoftext|>


<commit_before>/**
 * The safe-mode layout
 *
 * Copyright (C) 2010 Nikolay Nemshilov
 */
var RightJS = (function(src) {
  // premassaging the source code, swapping the document reference where needed
  src = src
    // making it search in this document by default
    .replace(/(\.\$=.+?\{.+?)([a-z]+)(\.getElementById.+?\})/,  '$1parent.document$3')
    .replace(/(\.\$\$=.+?\{.+?)([a-z]+)(\.querySelector.+?\})/, '$1parent.document$3')
    .replace(/(\.\$\$=[^{}]+?\{[^}]+?\()(document)(,[^}]+?\})/, '$1parent.document$3');

  // building the frame sandbox
  var frame_id = '__rightjs_condom', window = self, document = window.document;
  if ('attachEvent' in window) {
    document.write('');
  } else {
    var frame  = document.createElement('iframe');
    frame.name = frame_id;
    frame.style.display = 'none';
    document.documentElement.appendChild(frame);
  }

  // puttin the code into the frame
  var win = window.frames[frame_id];
  var doc = win.document;

  doc.open();
  doc.write('');
  doc.close();

  // transferring the object references from the sandbox into local variable
  var RightJS = win.RightJS;
  var natives = ['String', 'Array', 'Function', 'Math', 'Number', 'Object', 'RegExp', 'Date'];
  for (var i=0; i < natives.length; i++) {
    RightJS[natives[i]] = win[natives[i]];
  }

  // building the access proxy
  var proxy = function(value) {
    switch (typeof value) {
      case 'number':   return new RightJS.Number(value);
      case 'string':   return new RightJS.String(value);
      case 'function': return RightJS.$ext(value, RightJS.Function.Methods);
      case 'object':
        if (RightJS.isArray(value))
          return RightJS.$A(value);
    }

    return value;
  };

  // loads up the native class extensions in the current window
  proxy.civilize = function() {
    for (var i=0, klass; i < natives.length; i++) {
      R_Klass = RightJS[natives[i]];
      W_Klass = window[natives[i]];

      if ('include' in R_Klass) {
        W_Klass.include = function(modules, dont_overwrite) {
          RightJS.$ext(this.prototype, modules, dont_overwrite);
        };

        if ('Methods' in R_Klass) {
          W_Klass.include(R_Klass.Methods);
        }
      }
    }
  };

  return RightJS.$ext(proxy, RightJS);

})(#{source_code});<commit_msg>Safe-mode faster initialization process<commit_after>/**
 * The safe-mode layout
 *
 * Copyright (C) 2010 Nikolay Nemshilov
 */
var RightJS = (function(src) {
  // premassaging the source code, swapping the document reference where needed
  src = src
    // making it search in this document by default
    .replace(/(\.\$=.+?\{.+?)([a-z]+)(\.getElementById.+?\})/,  '$1parent.document$3')
    .replace(/(\.\$\$=.+?\{.+?)([a-z]+)(\.querySelector.+?\})/, '$1parent.document$3')
    .replace(/(\.\$\$=[^{}]+?\{[^}]+?\()(document)(,[^}]+?\})/, '$1parent.document$3');

  // building the frame sandbox
  var frame_id = '__rightjs_condom', window = self, document = window.document;
  if ('attachEvent' in window) {
    document.write('');
  } else {
    var frame  = document.createElement('iframe');
    frame.name = frame_id;
    frame.style.display = 'none';
    document.documentElement.appendChild(frame);
  }

  // puttin the code into the frame
  var win = window.frames[frame_id];

  if ('execScript' in win) {
    win.execScript(src);
  } else {
    var doc = win.document;
    doc.open();doc.write(''); doc.close();

    var script = document.createElement('script');
    script.text = src;
    doc.body.appendChild(script);
  }

  // transferring the object references from the sandbox into local variable
  var RightJS = win.RightJS;
  var natives = ['String', 'Array', 'Function', 'Math', 'Number', 'Object', 'RegExp', 'Date'];
  for (var i=0; i < natives.length; i++) {
    RightJS[natives[i]] = win[natives[i]];
  }

  // building the access proxy
  var proxy = function(value) {
    switch (typeof value) {
      case 'number':   return new RightJS.Number(value);
      case 'string':   return new RightJS.String(value);
      case 'function': return RightJS.$ext(value, RightJS.Function.Methods);
      case 'object':
        if (RightJS.isArray(value))
          return RightJS.$A(value);
    }

    return value;
  };

  // loads up the native class extensions in the current window
  proxy.civilize = function() {
    for (var i=0, klass; i < natives.length; i++) {
      R_Klass = RightJS[natives[i]];
      W_Klass = window[natives[i]];

      if ('include' in R_Klass) {
        W_Klass.include = function(modules, dont_overwrite) {
          RightJS.$ext(this.prototype, modules, dont_overwrite);
        };

        if ('Methods' in R_Klass) {
          W_Klass.include(R_Klass.Methods);
        }
      }
    }
  };

  return RightJS.$ext(proxy, RightJS);

})(#{source_code});<|endoftext|>


<commit_before>var creep_combat = {

	/** @param {Creep} creep **/
	run: function(creep) {
		//Defensive-focused attack
		//Only run this code if the room is being invaded, remain offline otherwise.
		//(Saves running excess finds in peacetime)
		if (creep.hits < creep.hitsMax) {
			creep.heal(creep);
		}

		if (Memory.roomsUnderAttack.indexOf(creep.room.name) != -1) {
			//Move towards Foe, stop at rampart
			var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
			var Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 50, {
				filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
			});

			var closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
				filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
			});

			if (Foe.length) {
				Foe.sort(targetOther);
				var boostFlag = false;
				if ((Foe[0].getActiveBodyparts(ATTACK) > 0 || Foe[0].getActiveBodyparts(RANGED_ATTACK) > 0 || Foe[0].getActiveBodyparts(WORK) > 0) && Foe[0].owner.username != 'Invader') {
					Foe[0].body.forEach(function(thisPart) {
						if (thisPart.boost) {
							boostFlag = true;
						}
					});
				}
				if (boostFlag && creep.room.controller.level >= 7 && Memory.labList[thisRoom.name].length >= 6) {
					var attackLab = Game.getObjectById(Memory.labList[thisRoom.name][3]);
					var mineralCost = creep.getActiveBodyparts(ATTACK) * LAB_BOOST_MINERAL;
					var energyCost = creep.getActiveBodyparts(ATTACK) * LAB_BOOST_ENERGY;
					if (attackLab && attackLab.mineralAmount >= mineralCost && attackLab.energy >= energyCost) {
						creep.memory.needBoosts = true;
					} else {
						creep.memory.needBoosts = false;
					}
				} else {
					creep.memory.needBoosts = false;
				}
			}

			var unboostedAttack = 0;
			if (creep.memory.needBoosts && creep.room.controller.level >= 7) {
				creep.body.forEach(function(thisPart) {
					if (thisPart.type == ATTACK && !thisPart.boost) {
						unboostedAttack = unboostedAttack + 1;
					}
				});
			}

			if (creep.memory.needBoosts && unboostedAttack > 0) {
				var thisLab = Game.getObjectById(Memory.labList[thisRoom.name][3]);
				if (thisLab) {
					creep.travelTo(thisLab);
					thisLab.boostCreep(creep);
				} else {
					creep.memory.needBoost = false;
				}
			} else if (closeFoe) {
				if (!creep.memory.waitingTimer) {
					creep.memory.waitingTimer = 0
				}
				var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
				if (lookResult.length && creep.memory.waitingTimer < 10) {
					var found = false;
					for (var y = 0; y < lookResult.length; y++) {
						if (lookResult[y].structureType == STRUCTURE_RAMPART) {
							creep.memory.waitingTimer = creep.memory.waitingTimer + 1;
							found = true;
							break;
						}
					}
					if (!found) {
						creep.travelTo(closeFoe, {
							maxRooms: 1
						});
					}
				} else {
					creep.memory.waitingTimer = 0;
					creep.travelTo(closeFoe, {
						maxRooms: 1
					});
				}
			}

			if (closeFoe) {
				if (creep.pos.inRangeTo(closeFoe, 3)) {
					creep.rangedMassAttack();
				}
				creep.attack(closeFoe);
			}
		} else {
			var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
			var homeSpawn = Game.getObjectById(creep.memory.fromSpawn)
			if (lookResult.length && lookResult[0].structureType == STRUCTURE_RAMPART) {

			} else if (homeSpawn) {
				creep.travelTo(homeSpawn);
			}
		}
	}
};

function targetOther(a, b) {
	if (a.getActiveBodyparts(HEAL) > b.getActiveBodyparts(HEAL))
		return 1;
	if (a.getActiveBodyparts(HEAL) < b.getActiveBodyparts(HEAL))
		return -1;
	return 0;
}

module.exports = creep_combat;<commit_msg>Successful attacks reset waiting timer<commit_after>var creep_combat = {

	/** @param {Creep} creep **/
	run: function(creep) {
		//Defensive-focused attack
		//Only run this code if the room is being invaded, remain offline otherwise.
		//(Saves running excess finds in peacetime)
		if (creep.hits < creep.hitsMax) {
			creep.heal(creep);
		}

		if (Memory.roomsUnderAttack.indexOf(creep.room.name) != -1) {
			//Move towards Foe, stop at rampart
			var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
			var Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 50, {
				filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
			});

			var closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
				filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
			});

			if (Foe.length) {
				Foe.sort(targetOther);
				var boostFlag = false;
				if ((Foe[0].getActiveBodyparts(ATTACK) > 0 || Foe[0].getActiveBodyparts(RANGED_ATTACK) > 0 || Foe[0].getActiveBodyparts(WORK) > 0) && Foe[0].owner.username != 'Invader') {
					Foe[0].body.forEach(function(thisPart) {
						if (thisPart.boost) {
							boostFlag = true;
						}
					});
				}
				if (boostFlag && creep.room.controller.level >= 7 && Memory.labList[thisRoom.name].length >= 6) {
					var attackLab = Game.getObjectById(Memory.labList[thisRoom.name][3]);
					var mineralCost = creep.getActiveBodyparts(ATTACK) * LAB_BOOST_MINERAL;
					var energyCost = creep.getActiveBodyparts(ATTACK) * LAB_BOOST_ENERGY;
					if (attackLab && attackLab.mineralAmount >= mineralCost && attackLab.energy >= energyCost) {
						creep.memory.needBoosts = true;
					} else {
						creep.memory.needBoosts = false;
					}
				} else {
					creep.memory.needBoosts = false;
				}
			}

			var unboostedAttack = 0;
			if (creep.memory.needBoosts && creep.room.controller.level >= 7) {
				creep.body.forEach(function(thisPart) {
					if (thisPart.type == ATTACK && !thisPart.boost) {
						unboostedAttack = unboostedAttack + 1;
					}
				});
			}

			if (creep.memory.needBoosts && unboostedAttack > 0) {
				var thisLab = Game.getObjectById(Memory.labList[thisRoom.name][3]);
				if (thisLab) {
					creep.travelTo(thisLab);
					thisLab.boostCreep(creep);
				} else {
					creep.memory.needBoost = false;
				}
			} else if (closeFoe) {
				if (!creep.memory.waitingTimer) {
					creep.memory.waitingTimer = 0
				}
				var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
				if (lookResult.length && creep.memory.waitingTimer < 10) {
					var found = false;
					for (var y = 0; y < lookResult.length; y++) {
						if (lookResult[y].structureType == STRUCTURE_RAMPART) {
							creep.memory.waitingTimer = creep.memory.waitingTimer + 1;
							found = true;
							break;
						}
					}
					if (!found) {
						creep.travelTo(closeFoe, {
							maxRooms: 1
						});
					}
				} else {
					creep.memory.waitingTimer = 0;
					creep.travelTo(closeFoe, {
						maxRooms: 1
					});
				}
			}

			if (closeFoe) {
				if (creep.pos.inRangeTo(closeFoe, 3)) {
					creep.rangedMassAttack();
				}
				if (creep.attack(closeFoe) == OK) {
					creep.memory.waitingTimer = 0;
				}
			}
		} else {
			var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
			var homeSpawn = Game.getObjectById(creep.memory.fromSpawn)
			if (lookResult.length && lookResult[0].structureType == STRUCTURE_RAMPART) {

			} else if (homeSpawn) {
				creep.travelTo(homeSpawn);
			}
		}
	}
};

function targetOther(a, b) {
	if (a.getActiveBodyparts(HEAL) > b.getActiveBodyparts(HEAL))
		return 1;
	if (a.getActiveBodyparts(HEAL) < b.getActiveBodyparts(HEAL))
		return -1;
	return 0;
}

module.exports = creep_combat;<|endoftext|>