<commit_before>(function(core) {

    if (typeof define == "function" && define.amd) { // AMD
        define("uikit", function(){

            var uikit = core(window, window.jQuery, window.document);

            uikit.load = function(res, req, onload, config) {

                var resources = res.split(','), load = [], i, base = (config.config && config.config.uikit && config.config.uikit.base ? config.config.uikit.base : "").replace(/\/+$/g, "");

                if (!base) {
                    throw new Error( "Please define base path to UIkit in the requirejs config." );
                }

                for (i = 0; i < resources.length; i += 1) {
                    var resource = resources[i].replace(/\./g, '/');
                    load.push(base+'/components/'+resource);
                }

                req(load, function() {
                    onload(uikit);
                });
            };

            return uikit;
        });
    }

    if (!window.jQuery) {
        throw new Error( "UIkit requires jQuery" );
    }

    if (window && window.jQuery) {
        core(window, window.jQuery, window.document);
    }

})(function(global, $, doc) {

    "use strict";

    var UI = $.UIkit || {}, $html = $("html"), $win = $(window), $doc = $(document);

    if (UI.fn) {
        return UI;
    }

    UI.version = '2.12.0';
    UI.$doc    = $doc;
    UI.$win    = $win;
    UI.$html   = $html;

    UI.fn = function(command, options) {

        var args = arguments, cmd = command.match(/^([a-z\-]+)(?:\.([a-z]+))?/i), component = cmd[1], method = cmd[2];

        if (!UI[component]) {
            $.error("UIkit component [" + component + "] does not exist.");
            return this;
        }

        return this.each(function() {
            var $this = $(this), data = $this.data(component);
            if (!data) $this.data(component, (data = UI[component](this, method ? undefined : options)));
            if (method) data[method].apply(data, Array.prototype.slice.call(args, 1));
        });
    };

    UI.support = {};
    UI.support.transition = (function() {

        var transitionEnd = (function() {

            var element = doc.body || doc.documentElement,
                transEndEventNames = {
                    WebkitTransition: 'webkitTransitionEnd',
                    MozTransition: 'transitionend',
                    OTransition: 'oTransitionEnd otransitionend',
                    transition: 'transitionend'
                }, name;

            for (name in transEndEventNames) {
                if (element.style[name] !== undefined) return transEndEventNames[name];
            }
        }());

        return transitionEnd && { end: transitionEnd };
    })();

    UI.support.animation = (function() {

        var animationEnd = (function() {

            var element = doc.body || doc.documentElement,
                animEndEventNames = {
                    WebkitAnimation: 'webkitAnimationEnd',
                    MozAnimation: 'animationend',
                    OAnimation: 'oAnimationEnd oanimationend',
                    animation: 'animationend'
                }, name;

            for (name in animEndEventNames) {
                if (element.style[name] !== undefined) return animEndEventNames[name];
            }
        }());

        return animationEnd && { end: animationEnd };
    })();

    UI.support.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback){ setTimeout(callback, 1000/60); };
    UI.support.touch                 = (
        ('ontouchstart' in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/)) ||
        (global.DocumentTouch && document instanceof global.DocumentTouch)  ||
        (global.navigator['msPointerEnabled'] && global.navigator['msMaxTouchPoints'] > 0) || //IE 10
        (global.navigator['pointerEnabled'] && global.navigator['maxTouchPoints'] > 0) || //IE >=11
        false
    );
    UI.support.mutationobserver = (global.MutationObserver || global.WebKitMutationObserver || null);

    UI.Utils = {};

    UI.Utils.debounce = function(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

    UI.Utils.removeCssRules = function(selectorRegEx) {
        var idx, idxs, stylesheet, _i, _j, _k, _len, _len1, _len2, _ref;

        if(!selectorRegEx) return;

        setTimeout(function(){
            try {
              _ref = document.styleSheets;
              for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                stylesheet = _ref[_i];
                idxs = [];
                stylesheet.cssRules = stylesheet.cssRules;
                for (idx = _j = 0, _len1 = stylesheet.cssRules.length; _j < _len1; idx = ++_j) {
                  if (stylesheet.cssRules[idx].type === CSSRule.STYLE_RULE && selectorRegEx.test(stylesheet.cssRules[idx].selectorText)) {
                    idxs.unshift(idx);
                  }
                }
                for (_k = 0, _len2 = idxs.length; _k < _len2; _k++) {
                  stylesheet.deleteRule(idxs[_k]);
                }
              }
            } catch (_error) {}
        }, 0);
    };

    UI.Utils.isInView = function(element, options) {

        var $element = $(element);

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

        var window_left = $win.scrollLeft(), window_top = $win.scrollTop(), offset = $element.offset(), left = offset.left, top = offset.top;

        options = $.extend({topoffset:0, leftoffset:0}, options);

        if (top + $element.height() >= window_top && top - options.topoffset <= window_top + $win.height() &&
            left + $element.width() >= window_left && left - options.leftoffset <= window_left + $win.width()) {
          return true;
        } else {
          return false;
        }
    };

    UI.Utils.checkDisplay = function(context) {

        var elements = $('[data-uk-margin], [data-uk-grid-match], [data-uk-grid-margin], [data-uk-check-display]', context || document);

        if (context && !elements.length) {
            elements = $(context);
        }

        elements.trigger('uk.check.display');

        return elements;
    };

    UI.Utils.options = function(string) {

        if ($.isPlainObject(string)) return string;

        var start = (string ? string.indexOf("{") : -1), options = {};

        if (start != -1) {
            try {
                options = (new Function("", "var json = " + string.substr(start) + "; return JSON.parse(JSON.stringify(json));"))();
            } catch (e) {}
        }

        return options;
    };

    UI.Utils.animate = function(element, cls) {

        var d = $.Deferred();

        element = $(element);

        element.css('display', 'none').addClass(cls).one(UI.support.animation.end, function() {
            element.removeClass(cls);
            d.resolve();
        }).width();

        element.css('display', '');

        return d.promise();
    };

    UI.Utils.template = function(str, data) {

        var tokens = str.replace(/\n/g, '\\n').replace(/\{\{\{\s*(.+?)\s*\}\}\}/g, "{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g),
            i=0, toc, cmd, prop, val, fn, output = [], openblocks = 0;

        while(i < tokens.length) {

            toc = tokens[i];

            if(toc.match(/\{\{\s*(.+?)\s*\}\}/)) {
                i = i + 1;
                toc  = tokens[i];
                cmd  = toc[0];
                prop = toc.substring(toc.match(/^(\^|\#|\!|\~|\:)/) ? 1:0);

                switch(cmd) {
                    case '~':
                        output.push("for(var $i=0;$i<"+prop+".length;$i++) { var $item = "+prop+"[$i];");
                        openblocks++;
                        break;
                    case ':':
                        output.push("for(var $key in "+prop+") { var $val = "+prop+"[$key];");
                        openblocks++;
                        break;
                    case '#':
                        output.push("if("+prop+") {");
                        openblocks++;
                        break;
                    case '^':
                        output.push("if(!"+prop+") {");
                        openblocks++;
                        break;
                    case '/':
                        output.push("}");
                        openblocks--;
                        break;
                    case '!':
                        output.push("__ret.push("+prop+");");
                        break;
                    default:
                        output.push("__ret.push(escape("+prop+"));");
                        break;
                }
            } else {
                output.push("__ret.push('"+toc.replace(/\'/g, "\\'")+"');");
            }
            i = i + 1;
        }

        fn  = [
            'var __ret = [];',
            'try {',
            'with($data){', (!openblocks ? output.join('') : '__ret = ["Not all blocks are closed correctly."]'), '};',
            '}catch(e){__ret = [e.message];}',
            'return __ret.join("").replace(/\\n\\n/g, "\\n");',
            "function escape(html) { return String(html).replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');}"
        ].join("\n");

        var func = new Function('$data', fn);
        return data ? func(data) : func;
    };

    UI.Utils.events       = {};
    UI.Utils.events.click = UI.support.touch ? 'tap' : 'click';

    $.UIkit = UI;
    $.fn.uk = UI.fn;

    $.UIkit.langdirection = $html.attr("dir") == "rtl" ? "right" : "left";

    // DOM mutation save ready helper function

    UI.domObservers = [];

    UI.domObserve = function(selector, fn) {

        if(!UI.support.mutationobserver) return;

        $(selector).each(function() {

            var element = this;

            try {

                var observer = new UI.support.mutationobserver(UI.Utils.debounce(function(mutations) {
                    fn.apply(element, []);
                    $(element).trigger('uk.dom.changed');
                }, 50));

                // pass in the target node, as well as the observer options
                observer.observe(element, { childList: true, subtree: true });

            } catch(e) {}
        });
    };

    UI.ready = function(fn) {
        $(function() { fn(document); });
        UI.domObservers.push(fn);
    };

    UI.components = {};

    UI.component = function(name, def) {

        var fn = function(element, options) {

            var $this = this;

            this.element = element ? $(element) : null;
            this.options = $.extend(true, {}, this.defaults, options);
            this.plugins = {};

            if (this.element) {
                this.element.data(name, this);
            }

            this.init();

            (this.options.plugins.length ? this.options.plugins : Object.keys(fn.plugins)).forEach(function(plugin) {

                if (fn.plugins[plugin].init) {
                    fn.plugins[plugin].init($this);
                    $this.plugins[plugin] = true;
                }

            });

            this.trigger('init', [this]);
        };

        fn.plugins = {};

        $.extend(true, fn.prototype, {

            defaults : {plugins: []},

            init: function(){},

            on: function(){
                return $(this.element || this).on.apply(this.element || this, arguments);
            },

            one: function(){
                return $(this.element || this).one.apply(this.element || this, arguments);
            },

            off: function(evt){
                return $(this.element || this).off(evt);
            },

            trigger: function(evt, params) {
                return $(this.element || this).trigger(evt, params);
            },

            find: function(selector) {
                return this.element ? this.element.find(selector) : $([]);
            },

            proxy: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = function() { return obj[method].apply(obj, arguments); };
                });
            },

            mixin: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = obj[method].bind($this);
                });
            }

        }, def);

        this.components[name] = fn;

        this[name] = function() {

            var element, options;

            if(arguments.length) {
                switch(arguments.length) {
                    case 1:

                        if (typeof arguments[0] === "string" || arguments[0].nodeType || arguments[0] instanceof jQuery) {
                            element = $(arguments[0]);
                        } else {
                            options = arguments[0];
                        }

                        break;
                    case 2:

                        element = $(arguments[0]);
                        options = arguments[1];
                        break;
                }
            }

            if (element && element.data(name)) {
                return element.data(name);
            }

            return (new UI.components[name](element, options));
        };

        return fn;
    };

    UI.plugin = function(component, name, def) {
        this.components[component].plugins[name] = def;
    };

    $doc.on('uk.domready', function(){
        UI.domObservers.forEach(function(fn){
            fn(document);
        });
        $doc.trigger('uk.dom.changed');
    });

    $(function(){

        // custom scroll observer
        setInterval((function(){

            var memory = {x: window.pageXOffset, y:window.pageYOffset};

            var fn = function(){

                if (memory.x != window.pageXOffset || memory.y != window.pageYOffset) {
                    memory = {x: window.pageXOffset, y:window.pageYOffset};
                    $doc.trigger('uk-scroll', [memory]);
                }
            };

            if ($.UIkit.support.touch) {
                $doc.on('touchmove touchend MSPointerMove MSPointerUp', fn);
            }

            if(memory.x || memory.y) fn();

            return fn;

        })(), 15);

        // Check for dom modifications
        UI.domObserve('[data-uk-observe]', function() {

            var ele = this;

            UI.domObservers.forEach(function(fn){
                fn(ele);
            });
        });

        if (UI.support.touch) {

            // remove css hover rules for touch devices
            // UI.Utils.removeCssRules(/\.uk-(?!navbar).*:hover/);

            // viewport unit fix for uk-height-viewport - should be fixed in iOS 8
            if (navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) {

                UI.$win.on('load orientationchange resize', UI.Utils.debounce((function(){

                    var fn = function() {
                        $('.uk-height-viewport').css('height', window.innerHeight);
                        return fn;
                    };

                    return fn();

                })(), 100));
            }
        }
    });

    // add touch identifier class
    $html.addClass(UI.support.touch ? "uk-touch" : "uk-notouch");

    // add uk-hover class on tap to support overlays on touch devices
    if (UI.support.touch) {

        var hoverset = false, selector = '.uk-overlay, .uk-overlay-toggle, .uk-has-hover', exclude;

        $html.on('touchstart MSPointerDown', selector, function() {

            if(hoverset) $('.uk-hover').removeClass('uk-hover');

            hoverset = $(this).addClass('uk-hover');

        }).on('touchend MSPointerUp', function(e) {

            exclude = $(e.target).parents(selector);

            if (hoverset) hoverset.not(exclude).removeClass('uk-hover');
        });
    }

    return UI;
});
<commit_msg>core.js cleanup<commit_after>(function(core) {

    if (typeof define == "function" && define.amd) { // AMD
        define("uikit", function(){

            var uikit = core(window, window.jQuery, window.document);

            uikit.load = function(res, req, onload, config) {

                var resources = res.split(','), load = [], i, base = (config.config && config.config.uikit && config.config.uikit.base ? config.config.uikit.base : "").replace(/\/+$/g, "");

                if (!base) {
                    throw new Error( "Please define base path to UIkit in the requirejs config." );
                }

                for (i = 0; i < resources.length; i += 1) {
                    var resource = resources[i].replace(/\./g, '/');
                    load.push(base+'/components/'+resource);
                }

                req(load, function() {
                    onload(uikit);
                });
            };

            return uikit;
        });
    }

    if (!window.jQuery) {
        throw new Error( "UIkit requires jQuery" );
    }

    if (window && window.jQuery) {
        core(window, window.jQuery, window.document);
    }

})(function(global, $, doc) {

    "use strict";

    var UI = $.UIkit || {}, $html = $("html"), $win = $(window), $doc = $(document);

    if (UI.fn) {
        return UI;
    }

    UI.version = '2.12.0';
    UI.$doc    = $doc;
    UI.$win    = $win;
    UI.$html   = $html;

    UI.fn = function(command, options) {

        var args = arguments, cmd = command.match(/^([a-z\-]+)(?:\.([a-z]+))?/i), component = cmd[1], method = cmd[2];

        if (!UI[component]) {
            $.error("UIkit component [" + component + "] does not exist.");
            return this;
        }

        return this.each(function() {
            var $this = $(this), data = $this.data(component);
            if (!data) $this.data(component, (data = UI[component](this, method ? undefined : options)));
            if (method) data[method].apply(data, Array.prototype.slice.call(args, 1));
        });
    };

    UI.support = {};
    UI.support.transition = (function() {

        var transitionEnd = (function() {

            var element = doc.body || doc.documentElement,
                transEndEventNames = {
                    WebkitTransition: 'webkitTransitionEnd',
                    MozTransition: 'transitionend',
                    OTransition: 'oTransitionEnd otransitionend',
                    transition: 'transitionend'
                }, name;

            for (name in transEndEventNames) {
                if (element.style[name] !== undefined) return transEndEventNames[name];
            }
        }());

        return transitionEnd && { end: transitionEnd };
    })();

    UI.support.animation = (function() {

        var animationEnd = (function() {

            var element = doc.body || doc.documentElement,
                animEndEventNames = {
                    WebkitAnimation: 'webkitAnimationEnd',
                    MozAnimation: 'animationend',
                    OAnimation: 'oAnimationEnd oanimationend',
                    animation: 'animationend'
                }, name;

            for (name in animEndEventNames) {
                if (element.style[name] !== undefined) return animEndEventNames[name];
            }
        }());

        return animationEnd && { end: animationEnd };
    })();

    UI.support.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback){ setTimeout(callback, 1000/60); };
    UI.support.touch                 = (
        ('ontouchstart' in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/)) ||
        (global.DocumentTouch && document instanceof global.DocumentTouch)  ||
        (global.navigator['msPointerEnabled'] && global.navigator['msMaxTouchPoints'] > 0) || //IE 10
        (global.navigator['pointerEnabled'] && global.navigator['maxTouchPoints'] > 0) || //IE >=11
        false
    );
    UI.support.mutationobserver = (global.MutationObserver || global.WebKitMutationObserver || null);

    UI.Utils = {};

    UI.Utils.debounce = function(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

    UI.Utils.removeCssRules = function(selectorRegEx) {
        var idx, idxs, stylesheet, _i, _j, _k, _len, _len1, _len2, _ref;

        if(!selectorRegEx) return;

        setTimeout(function(){
            try {
              _ref = document.styleSheets;
              for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                stylesheet = _ref[_i];
                idxs = [];
                stylesheet.cssRules = stylesheet.cssRules;
                for (idx = _j = 0, _len1 = stylesheet.cssRules.length; _j < _len1; idx = ++_j) {
                  if (stylesheet.cssRules[idx].type === CSSRule.STYLE_RULE && selectorRegEx.test(stylesheet.cssRules[idx].selectorText)) {
                    idxs.unshift(idx);
                  }
                }
                for (_k = 0, _len2 = idxs.length; _k < _len2; _k++) {
                  stylesheet.deleteRule(idxs[_k]);
                }
              }
            } catch (_error) {}
        }, 0);
    };

    UI.Utils.isInView = function(element, options) {

        var $element = $(element);

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

        var window_left = $win.scrollLeft(), window_top = $win.scrollTop(), offset = $element.offset(), left = offset.left, top = offset.top;

        options = $.extend({topoffset:0, leftoffset:0}, options);

        if (top + $element.height() >= window_top && top - options.topoffset <= window_top + $win.height() &&
            left + $element.width() >= window_left && left - options.leftoffset <= window_left + $win.width()) {
          return true;
        } else {
          return false;
        }
    };

    UI.Utils.checkDisplay = function(context) {

        var elements = $('[data-uk-margin], [data-uk-grid-match], [data-uk-grid-margin], [data-uk-check-display]', context || document);

        if (context && !elements.length) {
            elements = $(context);
        }

        elements.trigger('uk.check.display');

        return elements;
    };

    UI.Utils.options = function(string) {

        if ($.isPlainObject(string)) return string;

        var start = (string ? string.indexOf("{") : -1), options = {};

        if (start != -1) {
            try {
                options = (new Function("", "var json = " + string.substr(start) + "; return JSON.parse(JSON.stringify(json));"))();
            } catch (e) {}
        }

        return options;
    };

    UI.Utils.animate = function(element, cls) {

        var d = $.Deferred();

        element = $(element);

        element.css('display', 'none').addClass(cls).one(UI.support.animation.end, function() {
            element.removeClass(cls);
            d.resolve();
        }).width();

        element.css('display', '');

        return d.promise();
    };

    UI.Utils.template = function(str, data) {

        var tokens = str.replace(/\n/g, '\\n').replace(/\{\{\{\s*(.+?)\s*\}\}\}/g, "{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g),
            i=0, toc, cmd, prop, val, fn, output = [], openblocks = 0;

        while(i < tokens.length) {

            toc = tokens[i];

            if(toc.match(/\{\{\s*(.+?)\s*\}\}/)) {
                i = i + 1;
                toc  = tokens[i];
                cmd  = toc[0];
                prop = toc.substring(toc.match(/^(\^|\#|\!|\~|\:)/) ? 1:0);

                switch(cmd) {
                    case '~':
                        output.push("for(var $i=0;$i<"+prop+".length;$i++) { var $item = "+prop+"[$i];");
                        openblocks++;
                        break;
                    case ':':
                        output.push("for(var $key in "+prop+") { var $val = "+prop+"[$key];");
                        openblocks++;
                        break;
                    case '#':
                        output.push("if("+prop+") {");
                        openblocks++;
                        break;
                    case '^':
                        output.push("if(!"+prop+") {");
                        openblocks++;
                        break;
                    case '/':
                        output.push("}");
                        openblocks--;
                        break;
                    case '!':
                        output.push("__ret.push("+prop+");");
                        break;
                    default:
                        output.push("__ret.push(escape("+prop+"));");
                        break;
                }
            } else {
                output.push("__ret.push('"+toc.replace(/\'/g, "\\'")+"');");
            }
            i = i + 1;
        }

        fn  = [
            'var __ret = [];',
            'try {',
            'with($data){', (!openblocks ? output.join('') : '__ret = ["Not all blocks are closed correctly."]'), '};',
            '}catch(e){__ret = [e.message];}',
            'return __ret.join("").replace(/\\n\\n/g, "\\n");',
            "function escape(html) { return String(html).replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');}"
        ].join("\n");

        var func = new Function('$data', fn);
        return data ? func(data) : func;
    };

    UI.Utils.events       = {};
    UI.Utils.events.click = UI.support.touch ? 'tap' : 'click';

    $.UIkit = UI;
    $.fn.uk = UI.fn;

    $.UIkit.langdirection = $html.attr("dir") == "rtl" ? "right" : "left";

    UI.components = {};

    UI.component = function(name, def) {

        var fn = function(element, options) {

            var $this = this;

            this.element = element ? $(element) : null;
            this.options = $.extend(true, {}, this.defaults, options);
            this.plugins = {};

            if (this.element) {
                this.element.data(name, this);
            }

            this.init();

            (this.options.plugins.length ? this.options.plugins : Object.keys(fn.plugins)).forEach(function(plugin) {

                if (fn.plugins[plugin].init) {
                    fn.plugins[plugin].init($this);
                    $this.plugins[plugin] = true;
                }

            });

            this.trigger('uk.component.init', [name, this]);
        };

        fn.plugins = {};

        $.extend(true, fn.prototype, {

            defaults : {plugins: []},

            init: function(){},

            on: function(){
                return $(this.element || this).on.apply(this.element || this, arguments);
            },

            one: function(){
                return $(this.element || this).one.apply(this.element || this, arguments);
            },

            off: function(evt){
                return $(this.element || this).off(evt);
            },

            trigger: function(evt, params) {
                return $(this.element || this).trigger(evt, params);
            },

            find: function(selector) {
                return this.element ? this.element.find(selector) : $([]);
            },

            proxy: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = function() { return obj[method].apply(obj, arguments); };
                });
            },

            mixin: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = obj[method].bind($this);
                });
            }

        }, def);

        this.components[name] = fn;

        this[name] = function() {

            var element, options;

            if(arguments.length) {
                switch(arguments.length) {
                    case 1:

                        if (typeof arguments[0] === "string" || arguments[0].nodeType || arguments[0] instanceof jQuery) {
                            element = $(arguments[0]);
                        } else {
                            options = arguments[0];
                        }

                        break;
                    case 2:

                        element = $(arguments[0]);
                        options = arguments[1];
                        break;
                }
            }

            if (element && element.data(name)) {
                return element.data(name);
            }

            return (new UI.components[name](element, options));
        };

        return fn;
    };

    UI.plugin = function(component, name, def) {
        this.components[component].plugins[name] = def;
    };

    $doc.on('uk.domready', function(){
        UI.domObservers.forEach(function(fn){
            fn(document);
        });
        $doc.trigger('uk.dom.changed');
    });

    // DOM mutation save ready helper function

    UI.domObservers = [];

    UI.ready = function(fn) {
        UI.domObservers.push(fn);
    };

    UI.domObserve = function(selector, fn) {

        if(!UI.support.mutationobserver) return;

        $(selector).each(function() {

            var element = this;

            try {

                var observer = new UI.support.mutationobserver(UI.Utils.debounce(function(mutations) {
                    fn.apply(element, []);
                    $(element).trigger('uk.dom.changed');
                }, 50));

                // pass in the target node, as well as the observer options
                observer.observe(element, { childList: true, subtree: true });

            } catch(e) {}
        });
    };

    $(function(){

        UI.$doc.trigger('uk.domready.before');

        // custom scroll observer
        setInterval((function(){

            var memory = {x: window.pageXOffset, y:window.pageYOffset};

            var fn = function(){

                if (memory.x != window.pageXOffset || memory.y != window.pageYOffset) {
                    memory = {x: window.pageXOffset, y:window.pageYOffset};
                    $doc.trigger('uk-scroll', [memory]);
                }
            };

            if ($.UIkit.support.touch) {
                $doc.on('touchmove touchend MSPointerMove MSPointerUp', fn);
            }

            if(memory.x || memory.y) fn();

            return fn;

        })(), 15);

        // Check for dom modifications
        UI.domObserve('[data-uk-observe]', function() {

            var ele = this;

            UI.domObservers.forEach(function(fn){
                fn(ele);
            });
        });

        // run component init functions on dom
        UI.domObservers.forEach(function(fn){
            fn($html);
        });

        if (UI.support.touch) {

            // remove css hover rules for touch devices
            // UI.Utils.removeCssRules(/\.uk-(?!navbar).*:hover/);

            // viewport unit fix for uk-height-viewport - should be fixed in iOS 8
            if (navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) {

                UI.$win.on('load orientationchange resize', UI.Utils.debounce((function(){

                    var fn = function() {
                        $('.uk-height-viewport').css('height', window.innerHeight);
                        return fn;
                    };

                    return fn();

                })(), 100));
            }
        }

        UI.$doc.trigger('uk.domready.after');
    });

    // add touch identifier class
    $html.addClass(UI.support.touch ? "uk-touch" : "uk-notouch");

    // add uk-hover class on tap to support overlays on touch devices
    if (UI.support.touch) {

        var hoverset = false, selector = '.uk-overlay, .uk-overlay-toggle, .uk-has-hover', exclude;

        $html.on('touchstart MSPointerDown', selector, function() {

            if(hoverset) $('.uk-hover').removeClass('uk-hover');

            hoverset = $(this).addClass('uk-hover');

        }).on('touchend MSPointerUp', function(e) {

            exclude = $(e.target).parents(selector);

            if (hoverset) hoverset.not(exclude).removeClass('uk-hover');
        });
    }

    return UI;
});
<|endoftext|>


<commit_before>let spiros = [];

function setup(){
    createCanvas(800, 600);
    background(0);

    angleMode(DEGREES);
}

function draw(){
    for (let i = 0; i < spiros.length; i++){
        spiros[i].draw();
    }
}

function mouseClicked() {
    let r0 = random(10, 100);
    let s0 = random(0.1, 5);
    let r1 = random(10, 100);
    let s1 = random(0.1, 5);
    let colour = color(random(255), random(255), random(255));
    spiros.push(new Spirograph(createVector(mouseX, mouseY), r0, s0, r1, s1, colour))
}
<commit_msg>Small tweak to speeds<commit_after>let spiros = [];

function setup(){
    createCanvas(800, 600);
    background(0);

    angleMode(DEGREES);
}

function draw(){
    for (let i = 0; i < spiros.length; i++){
        spiros[i].draw();
    }
}

function mouseClicked() {
    let r0 = random(10, 100);
    let s0 = random(0.1, 50);
    let r1 = random(10, 100);
    let s1 = random(0.1, 50);
    let colour = color(random(255), random(255), random(255));
    spiros.push(new Spirograph(createVector(mouseX, mouseY), r0, s0, r1, s1, colour))
}
<|endoftext|>


<commit_before>'use strict'

const EventEmitter = require('events')
const espree = require('espree')
const HtmlParser = require('htmlparser2').Parser
const path = require('path')
const utils = require('./utils')

const DEFAULT_OPTIONS = {
  range: false,
  // comment: true,
  attachComment: true,

  // create a top-level tokens array containing all tokens
  tokens: true,

  // set to 3, 5 (default), 6, 7, or 8 to specify the version of ECMAScript syntax you want to use.
  // You can also set to 2015 (same as 6), 2016 (same as 7), or 2017 (same as 8) to use the year-based naming.
  ecmaVersion: 8,

  // specify which type of script you're parsing (script or module, default is script)
  sourceType: 'module',

  ecmaFeatures: {
    experimentalObjectRestSpread: true
  }
}

const SUPPORTED_FEATURES = [
  'name', 'description', 'keywords', 'slots',
  'props', 'data', 'computed', 'events', 'methods'
]

const EVENT_EMIT_RE = /^\$emit\(['"](.+)['"]/

class Parser extends EventEmitter {
  constructor (options) {
    options = Object.assign({}, DEFAULT_OPTIONS, options)

    Parser.validateOptions(options)

    super()

    this.source = options.source
    this.features = options.features || SUPPORTED_FEATURES

    if (options.source.hasOwnProperty('script') && options.source.script) {
      this.ast = espree.parse(options.source.script, options)
    } else {
      this.ast = null
    }

    this.componentName = null
    this.template = options.source.template
    this.filename = options.filename
    this.eventsEmmited = {}
    this.defaultMethodVisibility = options.defaultMethodVisibility
  }

  static validateOptions (options) {
    if (!options.source) {
      throw new Error('options.source is required')
    }

    if (options.features) {
      if (!Array.isArray(options.features)) {
        throw new TypeError('options.features must be an array')
      }

      options.features.forEach((feature) => {
        if (!SUPPORTED_FEATURES.includes(feature)) {
          throw new Error(`Unknow '${feature}' feature. Supported features: ` + JSON.stringify(SUPPORTED_FEATURES))
        }
      })
    }
  }

  static getEventName (feature) {
    return feature.endsWith('s')
      ? feature.substring(0, feature.length - 1) : feature
  }

  parseObjectExpression (property) {
    if (!this.features.includes(property.key.name)) {
      return
    }

    const eventName = Parser.getEventName(property.key.name)

    property.value.properties.forEach((p) => {
      let defaultVisibility = utils.DEFAULT_VISIBILITY

      if (property.key.name === 'methods' && this.defaultMethodVisibility) {
        defaultVisibility = this.defaultMethodVisibility
      }

      const entry = utils.getComment(p, defaultVisibility)

      entry.value = utils.value(p)
      entry.name = Object.keys(entry.value)[0]
      entry.value = entry.value[entry.name]

      if (property.key.name === 'computed') {
        if (entry.value instanceof utils.NodeFunction) {
          entry.dependencies = utils.getDependencies(entry.value, this.source.script)
        } else if (entry.value instanceof Object && entry.value.get instanceof utils.NodeFunction) {
          entry.dependencies = utils.getDependencies(entry.value.get, this.source.script)
        } else {
          entry.dependencies = []
        }
      } else if (entry.value instanceof utils.NodeFunction) {
        entry.params = entry.value.params
      } else if (property.key.name === 'props') {
        if (entry.describeModel) {
          entry.name = 'v-model'
        } else {
          entry.name = utils.unCamelcase(entry.name)
        }
      }

      delete entry.describeModel

      this.parseKeywords(entry.keywords, entry)
      this.emit(eventName, entry)
      this.subWalk(entry.value)
    })
  }

  parseProperty (property) {
    const propertyValue = utils.value(property)

    if (propertyValue.hasOwnProperty('name') && !this.componentName) {
      this.componentName = propertyValue.name
      return
    }

    const entryValue = propertyValue[Object.keys(propertyValue)[0]]

    this.subWalk(entryValue)
  }

  extractProperties (property) {
    switch (property.value.type) {
      case 'FunctionExpression':
        const expression = property.value.body.body.find((p) => {
          return p.type === 'ReturnStatement'
        })

        if (expression) {
          if (expression.argument.type === 'ObjectExpression') {
            return this.parseObjectExpression({
              key: property.key,
              value: expression.argument
            })
          }
        }
        this.parseProperty(property)
        break

      case 'ArrowFunctionExpression':
        if (property.value.body.type === 'ObjectExpression') {
          this.parseObjectExpression({
            key: property.key,
            value: property.value.body
          })
        } else {
          this.parseProperty(property)
        }
        break

      case 'ObjectExpression':
        this.parseObjectExpression(property)
        break

      default:
        this.parseProperty(property)
    }
  }

  parseComponentName () {
    if (this.componentName === null) {
      if (this.filename) {
        this.componentName = path.parse(this.filename).name
      }
    }

    if (this.componentName) {
      this.emit('name', utils.unCamelcase(this.componentName))
    }
  }

  walk () {
    process.nextTick(() => {
      if (this.features.length === 0) {
        return this.emit('end')
      }

      if (this.template) {
        this.parseTemplate()
      }

      if (this.ast === null) {
        if (this.features.includes('name')) {
          this.parseComponentName()
        }

        return this.emit('end')
      }

      const identifiers = {}

      this.ast.body.forEach((body) => {
        const entry = utils.getComment(body, this.defaultMethodVisibility, this.features)

        if (entry.description) {
          this.emit('description', entry.description)
        }

        if (entry.keywords.length) {
          this.emit('keywords', entry.keywords)
        }

        if (body.type !== 'ExportDefaultDeclaration' && body.type !== 'ExpressionStatement') {
          if (body.type === 'VariableDeclaration') {
            identifiers[body.declarations[0].id.name] = body.declarations[0].init
          }
          return
        }

        if (body.declaration) {
          switch (body.declaration.type) {
            case 'ObjectExpression':
              body.declaration.properties.forEach((property) => this.extractProperties(property))
              break

            case 'Identifier':
              if (identifiers.hasOwnProperty(body.declaration.name)) {
                identifiers[body.declaration.name].properties.forEach((property) => this.extractProperties(property))
              }
              break
          }
        } else if (body.expression !== null && body.expression.right && body.expression.right.properties) {
          body.expression.right.properties.forEach((property) => this.extractProperties(property))
        }

        if (this.features.includes('name')) {
          this.parseComponentName()
        }
      })

      this.emit('end')
    })

    return this
  }

  subWalk (entry) {
    if (entry instanceof utils.NodeFunction) {
      const tokens = utils.tokensInterval(this.ast.tokens, entry.range)

      for (let i = 0; i < tokens.length; i++) {
        const token = tokens[i]

        if (token.type === 'Identifier' && token.value === '$emit') {
          if (!tokens[i + 2]) {
            break
          }

          if (!this.features.includes('events')) {
            continue
          }

          const next = tokens[i + 2]
          const event = {
            name: null,
            description: null,
            visibility: utils.DEFAULT_VISIBILITY,
            keywords: []
          }

          const range = [
            tokens[i - 3].range[1],
            tokens[i - 2].range[0]
          ]

          event.description = this.ast.comments.reverse().find((c) => {
            return c.range[0] > range[0] && c.range[1] < range[1]
          })

          if (event.description) {
            const comment = utils.parseComment(
              event.description.value)

            event.visibility = comment.visibility
            event.description = comment.description
            event.keywords = comment.keywords

            const keyword = comment.keywords.find((keyword) => keyword.name === 'event')

            if (keyword) {
              if (!keyword.description) {
                const error = new Error('Missing keyword value for @event')

                this.emit('error', error)

                continue
              }

              event.name = keyword.description
            }
          }

          if (event.name === null) {
            switch (next.type) {
              case 'String':
                event.name = next.value.replace(/['"]/g, '')
                break

              case 'Identifier':
                event.name = utils.getIdentifierValue(tokens, next.value, next.range[0])

                if (typeof event.name === 'object') {
                  event.name = utils.getIdentifierValueFromStart(this.ast.tokens, event.name.notFoundIdentifier)
                }
                break
            }
          }

          if (!event.name) {
            event.name = '****unhandled-event-name****'
          } else {
            if (this.eventsEmmited.hasOwnProperty(event.name)) {
              continue
            }

            this.eventsEmmited[event.name] = true
          }

          this.parseKeywords(event.keywords, event)
          this.emit('event', event)

          i += 2
        }
      }
    }
  }

  parseTemplate () {
    let lastComment = null

    const parser = new HtmlParser({
      oncomment: (data) => {
        lastComment = data.trim()
      },
      ontext: (text) => {
        if (text.trim()) {
          lastComment = null
        }
      },
      onopentag: (name, attrs) => {
        if (name === 'slot') {
          if (this.features.includes('slots')) {
            this.emit('slot', {
              name: attrs.name || 'default',
              description: lastComment
            })
          }
        } else if (this.features.includes('events')) {
          Object.keys(attrs)
            .map((name) => attrs[name])
            .map((value) => EVENT_EMIT_RE.exec(value))
            .filter((result) => result !== null)
            .map((matches) => ({ name: matches[1] }))
            .forEach((event) => {
              if (lastComment) {
                lastComment = `/** ${lastComment} */`
              }

              const comment = utils.parseComment(lastComment || '')

              event.visibility = comment.visibility
              event.description = comment.description
              event.keywords = comment.keywords

              this.parseKeywords(comment.keywords, event)
              this.emit('event', event)

              lastComment = null
            })

          lastComment = null
        }
      }
    })

    parser.write(this.template)
    parser.end()
  }

  parseKeywords (keywords = [], event) {
    event.params = []

    keywords.forEach(({ name, description }) => {
      switch (name) {
        case 'param':
          event.params.push(utils.parseParamKeyword(description))
          break

        case 'return':
          event.return = utils.parseReturnKeyword(description)
          break
      }
    })

    if (event.params.length === 0) {
      delete event.params
    }
  }
}

module.exports = Parser
module.exports.SUPPORTED_FEATURES = SUPPORTED_FEATURES
<commit_msg>Move to the ECMA 9 for espree parsing<commit_after>'use strict'

const EventEmitter = require('events')
const espree = require('espree')
const HtmlParser = require('htmlparser2').Parser
const path = require('path')
const utils = require('./utils')

const DEFAULT_OPTIONS = {
  range: false,
  // comment: true,
  attachComment: true,

  // create a top-level tokens array containing all tokens
  tokens: true,

  // The version of ECMAScript syntax to use
  ecmaVersion: 9,

  // Type of script to parse
  sourceType: 'module',

  ecmaFeatures: {
    experimentalObjectRestSpread: true
  }
}

const SUPPORTED_FEATURES = [
  'name', 'description', 'keywords', 'slots',
  'props', 'data', 'computed', 'events', 'methods'
]

const EVENT_EMIT_RE = /^\$emit\(['"](.+)['"]/

class Parser extends EventEmitter {
  constructor (options) {
    options = Object.assign({}, DEFAULT_OPTIONS, options)

    Parser.validateOptions(options)

    super()

    this.source = options.source
    this.features = options.features || SUPPORTED_FEATURES

    if (options.source.hasOwnProperty('script') && options.source.script) {
      this.ast = espree.parse(options.source.script, options)
    } else {
      this.ast = null
    }

    this.componentName = null
    this.template = options.source.template
    this.filename = options.filename
    this.eventsEmmited = {}
    this.defaultMethodVisibility = options.defaultMethodVisibility
  }

  static validateOptions (options) {
    if (!options.source) {
      throw new Error('options.source is required')
    }

    if (options.features) {
      if (!Array.isArray(options.features)) {
        throw new TypeError('options.features must be an array')
      }

      options.features.forEach((feature) => {
        if (!SUPPORTED_FEATURES.includes(feature)) {
          throw new Error(`Unknow '${feature}' feature. Supported features: ` + JSON.stringify(SUPPORTED_FEATURES))
        }
      })
    }
  }

  static getEventName (feature) {
    return feature.endsWith('s')
      ? feature.substring(0, feature.length - 1) : feature
  }

  parseObjectExpression (property) {
    if (!this.features.includes(property.key.name)) {
      return
    }

    const eventName = Parser.getEventName(property.key.name)

    property.value.properties.forEach((p) => {
      let defaultVisibility = utils.DEFAULT_VISIBILITY

      if (property.key.name === 'methods' && this.defaultMethodVisibility) {
        defaultVisibility = this.defaultMethodVisibility
      }

      const entry = utils.getComment(p, defaultVisibility)

      entry.value = utils.value(p)
      entry.name = Object.keys(entry.value)[0]
      entry.value = entry.value[entry.name]

      if (property.key.name === 'computed') {
        if (entry.value instanceof utils.NodeFunction) {
          entry.dependencies = utils.getDependencies(entry.value, this.source.script)
        } else if (entry.value instanceof Object && entry.value.get instanceof utils.NodeFunction) {
          entry.dependencies = utils.getDependencies(entry.value.get, this.source.script)
        } else {
          entry.dependencies = []
        }
      } else if (entry.value instanceof utils.NodeFunction) {
        entry.params = entry.value.params
      } else if (property.key.name === 'props') {
        if (entry.describeModel) {
          entry.name = 'v-model'
        } else {
          entry.name = utils.unCamelcase(entry.name)
        }
      }

      delete entry.describeModel

      this.parseKeywords(entry.keywords, entry)
      this.emit(eventName, entry)
      this.subWalk(entry.value)
    })
  }

  parseProperty (property) {
    const propertyValue = utils.value(property)

    if (propertyValue.hasOwnProperty('name') && !this.componentName) {
      this.componentName = propertyValue.name
      return
    }

    const entryValue = propertyValue[Object.keys(propertyValue)[0]]

    this.subWalk(entryValue)
  }

  extractProperties (property) {
    switch (property.value.type) {
      case 'FunctionExpression':
        const expression = property.value.body.body.find((p) => {
          return p.type === 'ReturnStatement'
        })

        if (expression) {
          if (expression.argument.type === 'ObjectExpression') {
            return this.parseObjectExpression({
              key: property.key,
              value: expression.argument
            })
          }
        }
        this.parseProperty(property)
        break

      case 'ArrowFunctionExpression':
        if (property.value.body.type === 'ObjectExpression') {
          this.parseObjectExpression({
            key: property.key,
            value: property.value.body
          })
        } else {
          this.parseProperty(property)
        }
        break

      case 'ObjectExpression':
        this.parseObjectExpression(property)
        break

      default:
        this.parseProperty(property)
    }
  }

  parseComponentName () {
    if (this.componentName === null) {
      if (this.filename) {
        this.componentName = path.parse(this.filename).name
      }
    }

    if (this.componentName) {
      this.emit('name', utils.unCamelcase(this.componentName))
    }
  }

  walk () {
    process.nextTick(() => {
      if (this.features.length === 0) {
        return this.emit('end')
      }

      if (this.template) {
        this.parseTemplate()
      }

      if (this.ast === null) {
        if (this.features.includes('name')) {
          this.parseComponentName()
        }

        return this.emit('end')
      }

      const identifiers = {}

      this.ast.body.forEach((body) => {
        const entry = utils.getComment(body, this.defaultMethodVisibility, this.features)

        if (entry.description) {
          this.emit('description', entry.description)
        }

        if (entry.keywords.length) {
          this.emit('keywords', entry.keywords)
        }

        if (body.type !== 'ExportDefaultDeclaration' && body.type !== 'ExpressionStatement') {
          if (body.type === 'VariableDeclaration') {
            identifiers[body.declarations[0].id.name] = body.declarations[0].init
          }
          return
        }

        if (body.declaration) {
          switch (body.declaration.type) {
            case 'ObjectExpression':
              body.declaration.properties.forEach((property) => this.extractProperties(property))
              break

            case 'Identifier':
              if (identifiers.hasOwnProperty(body.declaration.name)) {
                identifiers[body.declaration.name].properties.forEach((property) => this.extractProperties(property))
              }
              break
          }
        } else if (body.expression !== null && body.expression.right && body.expression.right.properties) {
          body.expression.right.properties.forEach((property) => this.extractProperties(property))
        }

        if (this.features.includes('name')) {
          this.parseComponentName()
        }
      })

      this.emit('end')
    })

    return this
  }

  subWalk (entry) {
    if (entry instanceof utils.NodeFunction) {
      const tokens = utils.tokensInterval(this.ast.tokens, entry.range)

      for (let i = 0; i < tokens.length; i++) {
        const token = tokens[i]

        if (token.type === 'Identifier' && token.value === '$emit') {
          if (!tokens[i + 2]) {
            break
          }

          if (!this.features.includes('events')) {
            continue
          }

          const next = tokens[i + 2]
          const event = {
            name: null,
            description: null,
            visibility: utils.DEFAULT_VISIBILITY,
            keywords: []
          }

          const range = [
            tokens[i - 3].range[1],
            tokens[i - 2].range[0]
          ]

          event.description = this.ast.comments.reverse().find((c) => {
            return c.range[0] > range[0] && c.range[1] < range[1]
          })

          if (event.description) {
            const comment = utils.parseComment(
              event.description.value)

            event.visibility = comment.visibility
            event.description = comment.description
            event.keywords = comment.keywords

            const keyword = comment.keywords.find((keyword) => keyword.name === 'event')

            if (keyword) {
              if (!keyword.description) {
                const error = new Error('Missing keyword value for @event')

                this.emit('error', error)

                continue
              }

              event.name = keyword.description
            }
          }

          if (event.name === null) {
            switch (next.type) {
              case 'String':
                event.name = next.value.replace(/['"]/g, '')
                break

              case 'Identifier':
                event.name = utils.getIdentifierValue(tokens, next.value, next.range[0])

                if (typeof event.name === 'object') {
                  event.name = utils.getIdentifierValueFromStart(this.ast.tokens, event.name.notFoundIdentifier)
                }
                break
            }
          }

          if (!event.name) {
            event.name = '****unhandled-event-name****'
          } else {
            if (this.eventsEmmited.hasOwnProperty(event.name)) {
              continue
            }

            this.eventsEmmited[event.name] = true
          }

          this.parseKeywords(event.keywords, event)
          this.emit('event', event)

          i += 2
        }
      }
    }
  }

  parseTemplate () {
    let lastComment = null

    const parser = new HtmlParser({
      oncomment: (data) => {
        lastComment = data.trim()
      },
      ontext: (text) => {
        if (text.trim()) {
          lastComment = null
        }
      },
      onopentag: (name, attrs) => {
        if (name === 'slot') {
          if (this.features.includes('slots')) {
            this.emit('slot', {
              name: attrs.name || 'default',
              description: lastComment
            })
          }
        } else if (this.features.includes('events')) {
          Object.keys(attrs)
            .map((name) => attrs[name])
            .map((value) => EVENT_EMIT_RE.exec(value))
            .filter((result) => result !== null)
            .map((matches) => ({ name: matches[1] }))
            .forEach((event) => {
              if (lastComment) {
                lastComment = `/** ${lastComment} */`
              }

              const comment = utils.parseComment(lastComment || '')

              event.visibility = comment.visibility
              event.description = comment.description
              event.keywords = comment.keywords

              this.parseKeywords(comment.keywords, event)
              this.emit('event', event)

              lastComment = null
            })

          lastComment = null
        }
      }
    })

    parser.write(this.template)
    parser.end()
  }

  parseKeywords (keywords = [], event) {
    event.params = []

    keywords.forEach(({ name, description }) => {
      switch (name) {
        case 'param':
          event.params.push(utils.parseParamKeyword(description))
          break

        case 'return':
          event.return = utils.parseReturnKeyword(description)
          break
      }
    })

    if (event.params.length === 0) {
      delete event.params
    }
  }
}

module.exports = Parser
module.exports.SUPPORTED_FEATURES = SUPPORTED_FEATURES
<|endoftext|>


<commit_before>function showDiv(divName) {
  $('.all').hide();
  $(divName).show();
}

// When the user clicks the button
$('.btn-username').click(processForm, function(){
	showDiv(".prep");
	$('.btn-all').hide();
	setTimeout(function() {$('.btn-prep').show();},10000);

});

// When the user clicks the button
$('.btn-prep').click(function(){
	showDiv(".instruction");
	setTimeout(function() {$('.btn-instruction').show();},10000);
})

// Get the form, listen to its submit event

$('.form-set-username').on('submit', processForm);

$('.btn-instruction').click(finishedOnboarding);

// function to run when the form is submitted
function processForm() {

	showDiv(".prep");
	$('.btn-all').hide();
	setTimeout(function() {$('.btn-prep').show();},10000);
 // get the entered user name from the input
	var username = $('input').val();
 	localStorage.setItem('username', username);
		database.ref('users/'+ username).set({
    	username: username
    });
 	return false;
};

showDiv(".username")
startCurrentView();

<commit_msg>the code for anonymous<commit_after>function showDiv(divName) {
  $('.all').hide();
  $(divName).show();
}

// When the user clicks the button
$('.btn-username').click(processForm, function(){
	showDiv(".prep");
	$('.btn-all').hide();
	setTimeout(function() {$('.btn-prep').show();},10000);

});

// When the user clicks the button
$('.btn-prep').click(function(){
	showDiv(".instruction");
	setTimeout(function() {$('.btn-instruction').show();},10000);
})

// Get the form, listen to its submit event

$('.form-set-username').on('submit', processForm);

$('.btn-instruction').click(finishedOnboarding);

// function to run when the form is submitted
function processForm() {

	showDiv(".prep");
	$('.btn-all').hide();
	setTimeout(function() {$('.btn-prep').show();},10000);
 // get the entered user name from the input
	var username = $('input').val();
	if (username == null || username == ""){
		username = "anonymous";
	}
 	localStorage.setItem('username', username);
		database.ref('users/'+ username).set({
    	username: username
    });
 	return false;
};

showDiv(".username")
startCurrentView();

<|endoftext|>


<commit_before>/**
 * @author : matthewsun
 * @mail : matthew-sun@foxmail.com
 * @description : 封装一些与业务无关的底层方法
 * @description : CLASS || UTIls || EVENT || HTTP || MOBILE
 * @date : 2014/08/25
 */
define(function(require, exports, module) {
    var $ = require('../zepto/zepto');

    /**
     * CLASS model
     * @return {[type]} [description]
     */

    var func = (function() {

        var _func = {};

        /**
         * 创建Class
         * 范式：Class(superClass,subClass) || Class(subClass)
         * 创建类的API，统一自调用init方法
         */

        _func.Class = function() {
            var length = arguments.length;
            var option = arguments[length-1];
            option.init = option.init || function(){};

            if(length === 2){
                var superClass = arguments[0];

                var tempClass = function() {};
                tempClass.prototype = superClass.prototype;

                var subClass = function() {
                    return new subClass.prototype._init(arguments);
                }

                subClass.superClass = superClass.prototype;
                subClass.callSuper = function(context,method){
                    var slice = Array.prototype.slice;
                    var a = slice.call(arguments, 2);
                    var method = subClass.superClass[method];

                    if(method){
                        method.apply(context, a.concat(slice.call(arguments)));
                    }
                };
                subClass.prototype = new tempClass();
                subClass.prototype.constructor = subClass;

                $.extend(subClass.prototype, option);

                subClass.prototype._init = function(args){
                    this.init.apply(this, args);
                };
                subClass.prototype._init.prototype = subClass.prototype;
                return subClass;

            }else if(length === 1){
                var newClass = function() {
                    return new newClass.prototype._init(arguments);
                }
                newClass.prototype = option;
                newClass.prototype._init = function(arg){
                    this.init.apply(this,arg);
                };
                newClass.prototype.constructor = newClass;
                newClass.prototype._init.prototype = newClass.prototype;
                return newClass;
            }
        }

        return _func;
    })()

    /**
     * UTIls model
     */

    ;(function(func) {

        /**
         * 获取键值
         *
         * @param  {[type]} obj [description]
         * @return {[Array]}     [description]
         */

        func.keys = function(obj) {
            var keys = [];
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) keys.push(key)
            }
            return keys;

        }

        /**
         * hover hack
         * 移动端模拟手触摸时的效果
         */

        func.bindActiveLink = function() {
            var $body = $('body');

            $body.on('touchstart','.J_active',function() {
                $(this).addClass('hover');
            })
            $body.on('touchend','.J_active',function() {
                $(this).removeClass('hover');
            })
        }

    })(func)

    /**
     * EVENT model
     */

    ;(function(func) {

        var _cache = {};

        /**
         * 广播事件
         * 目标: 为了尽可能的减少模块之间业务逻辑的耦合度, 而开发了这个eventbus, 主要用于业务逻辑的事件传递
         * 使用规范: 每个js模块尽可能通过事件去通信, 减少模块之间的直接调用和依赖(耦合)
         */

        /**
         * 派发
         * @param  {[type]} type 事件类型
         * @param  {[type]} data 回调数据
         * @return {[type]}      [description]
         */
        func.fire = function(type, data) {
            var listeners = _cache[type],
                len = 0;
            if (typeof listeners !== 'undefined') {
                var args = [].slice.call(arguments, 0);
                args = args.length > 2 ? args.splice(2, args.length - 1) : [];
                args = [data].concat(args);

                len = listeners.length;
                for (var i = 0; i < len; i++) {
                    var listener = listeners[i];
                    if (listener && listener.callback) {
                        args = args.concat(listener.args);
                        listener.callback.apply(listener.scope, args);
                    }
                }
            }
            return this;
        }

        /**
         * 订阅广播事件
         * @param  {[type]}   types     事件类型，支持,分隔符
         * @param  {Function} callback 回调函数
         * @param  {[type]}   scope    回调函数上下文
         * @return {[type]}            this
         */

        func.on = function(types, callback, scope) {
            types = types || [];
            var args = [].slice.call(arguments);

            if (typeof types === 'string') {
                types = types.split(',');
            }
            var len = types.length;
            if (len === 0) {
                return this;
            }
            args = args.length > 3 ? args.splice(3, args.length - 1) : [];
            for (var i = 0; i < len; i++) {
                var type = types[i];
                _cache[type] = _cache[type] || [];
                _cache[type].push({
                    callback: callback,
                    scope: scope,
                    args: args
                });
            }
            return this;
        }

        /**
         * 退订
         * @param  {[type]}   type     [description]
         * @param  {Function} callback 假如传入则移出传入的监控事件，否则移出全部
         * @return {[type]}            [description]
         */

        func.un = function(type, callback, scope) {
            var listeners = _cache[type];
            if (!listeners) {
                return this;
            }
            if (callback) {
                var len = listeners.length,
                    tmp = [];

                for (var i = 0; i < len; i++) {
                    var listener = listeners[i];
                    if (listener.callback == callback && listener.scope == scope) {} else {
                        tmp.push(listener);
                    }
                }
                listeners = tmp;
            } else {
                listeners.length = 0;
            }
            return this;
        }

        func.removeAll = function() {
            _cache = {};
            return this;
        }

    })(func)

    /**
     * HTTP model
     */

    ;(function(func) {

        /**
         * loader
         */
        func.loader = function(opts){
            opts = $.extend({
                dataType : "jsonp",
                jsonp : "cb",
                cache:false,
                timeout : 10000,

                success : function(){},
                error : function(jqXHR, textStatus, errorThrown){ console.log(textStatus)},
                complete : function(){}
            }, opts);

            $.ajax(opts);
        }

        /**
         * 获取cookie
         * @param  {[type]} name   [cookie名]
         * @return {[type]} String [cookie值]
         */

        func.getCookie = function(name) {
            var arr = document.cookie.split('; '),
                i = 0,
                len = arr.length ;

            for(;i<len;i++){
                var arr2 = arr[i].split('=');
                if(arr2[0] == name) {
                    return arr2[1];
                }
            }

            return '';
        }

        /**
         * 设置cookie值
         * @param {[type]} name  [cookie名字]
         * @param {[type]} value [cookie值]
         * @param {[type]} iDay  [过期时间，单位：天]
         */

        func.setCookie = function(name, value, iDay) {
            if(iDay!==false){

                var exp = new Date();
                exp.setTime(exp.getTime() + iDay*24*60*60*1000);
                document.cookie=name+'='+value+';expires='+exp.toGMTString()+';path=/';

            }else{
                document.cookie=name+'='+value;
            }
        }

        /**
         * 移除Cookie
         * @param  {[type]} name [Cookie名]
         */

        func.removeCookie = function (name) {
            func.setCookie(name, '', -1);
        }
    })(func)

    /**
     * MOBILE model
     */

    ;(function(func) {

        /**
         * 判断浏览器版本
         */

        func.Device = function() {
            var ua = navigator.userAgent;
            var os = this.os = {},browser = this.browser = {},

                webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/),
                android = ua.match(/(Android);?[\s\/]+([\d.]+)?/),
                osx = !!ua.match(/\(Macintosh\; Intel /),
                ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
                ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/),
                iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
                webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),
                touchpad = webos && ua.match(/TouchPad/),
                kindle = ua.match(/Kindle\/([\d.]+)/),
                silk = ua.match(/Silk\/([\d._]+)/),
                blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/),
                bb10 = ua.match(/(BB10).*Version\/([\d.]+)/),
                rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/),
                playbook = ua.match(/PlayBook/),
                baidu = ua.match( /baiduboxapp\/[^\/]+\/([\d.]+)_/ )
                        || ua.match( /baiduboxapp\/([\d.]+)/ )
                        || ua.match( /BaiduHD\/([\d.]+)/ )
                        || ua.match( /FlyFlow\/([\d.]+)/ )
                        || ua.match( /baidubrowser\/([\d.]+)/ ),
                qq = ua.match( /MQQBrowser\/([\d.]+)/ ) || ua.match( /QQ\/([\d.]+)/ ),
                uc = ua.match(/UCBrowser\/([\w.\s]+)/),
                chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/),
                firefox = ua.match(/Firefox\/([\d.]+)/),
                ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/),
                webview = !chrome && ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/),
                safari = webview || ua.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/),
                orientation = Math.abs(window.orientation);

            if (browser.webkit = !!webkit) browser.version = webkit[1]

            if (android) os.android = true, os.version = android[2]
            if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.')
            if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.')
            if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null
            if (webos) os.webos = true, os.version = webos[2]
            if (touchpad) os.touchpad = true
            if (blackberry) os.blackberry = true, os.version = blackberry[2]
            if (bb10) os.bb10 = true, os.version = bb10[2]
            if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2]
            if (playbook) browser.playbook = true
            if (baidu) browser.baidu = true,browser.version = baidu[1]
            if (qq) os.qq = true, os.ucversion = qq[1]
            if (uc) os.uc = true, os.ucversion = uc[1]
            if (kindle) os.kindle = true, os.version = kindle[1]
            if (silk) browser.silk = true, browser.version = silk[1]
            if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true
            if (orientation !== 90) os.protrait = true
            if (orientation === 90) os.landscape = true

            if (chrome) browser.chrome = true, browser.version = chrome[1]
            if (firefox) browser.firefox = true, browser.version = firefox[1]
            if (ie) browser.ie = true, browser.version = ie[1]
            if (safari && (osx || os.ios)) {browser.safari = true; if (osx) browser.version = safari[1]}
            if (webview) browser.webview = true

            os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
            (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)))
            os.phone  = !!(!os.tablet && !os.ipod && (android || iphone || webos || blackberry || bb10 ||
            (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
            (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))))
            return {
                browser: browser,
                os: os
            };
        }

    })(func)

    return func;
})<commit_msg>add fix<commit_after>/**
 * @author : matthewsun
 * @mail : matthew-sun@foxmail.com
 * @description : 封装一些与业务无关的底层方法
 * @description : CLASS || UTIls || EVENT || HTTP || MOBILE
 * @date : 2014/08/25
 */
define(function(require, exports, module) {
    var $ = require('../zepto/zepto');

    /**
     * CLASS model
     * @return {[type]} [description]
     */

    var func = (function() {

        var _func = {};

        /**
         * 创建Class
         * 范式：Class(superClass,subClass) || Class(subClass)
         * 创建类的API，统一自调用init方法
         */

        _func.Class = function() {
            var length = arguments.length;
            var option = arguments[length-1];
            option.init = option.init || function(){};

            if(length === 2){
                var superClass = arguments[0];

                var tempClass = function() {};
                tempClass.prototype = superClass.prototype;

                var subClass = function() {
                    return new subClass.prototype._init(arguments);
                }

                subClass.superClass = superClass.prototype;
                subClass.callSuper = function(context,method){
                    var slice = Array.prototype.slice;
                    var a = slice.call(arguments, 2);
                    var method = subClass.superClass[method];

                    if(method){
                        method.apply(context, a.concat(slice.call(arguments)));
                    }
                };
                subClass.prototype = new tempClass();
                subClass.prototype.constructor = subClass;

                $.extend(subClass.prototype, option);

                subClass.prototype._init = function(args){
                    this.init.apply(this, args);
                };
                subClass.prototype._init.prototype = subClass.prototype;
                return subClass;

            }else if(length === 1){
                var newClass = function() {
                    return new newClass.prototype._init(arguments);
                }
                newClass.prototype = option;
                newClass.prototype._init = function(arg){
                    this.init.apply(this,arg);
                };
                newClass.prototype.constructor = newClass;
                newClass.prototype._init.prototype = newClass.prototype;
                return newClass;
            }
        }

        return _func;
    })()

    /**
     * UTIls model
     */

    ;(function(func) {

        /**
         * 获取键值
         *
         * @param  {[type]} obj [description]
         * @return {[Array]}     [description]
         */

        func.keys = function(obj) {
            var keys = [];
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) keys.push(key)
            }
            return keys;

        }

        /**
         * hover hack
         * 移动端模拟手触摸时的效果
         */

        func.bindActiveLink = function() {
            var $body = $('body');

            $body.on('touchstart','.J_active',function() {
                $(this).addClass('hover');
            })
            $body.on('touchend','.J_active',function() {
                $(this).removeClass('hover');
            })
        }

        /**
         * @name fix
         * @grammar fix($obj, options)
         * @param  DOM $obj 绑定fix的zepto对象
         * @param JSON {top:0, left:0}
         * @desc 固顶fix方法，对不支持position:fixed的设备上将元素position设为absolute，
         * 在每次scrollstop时根据opts参数设置当前显示的位置，类似fix效果。
         *
         * Options:
         * - ''top'' {Number}: 距离顶部的px值
         * - ''left'' {Number}: 距离左侧的px值
         * - ''bottom'' {Number}: 距离底部的px值
         * - ''right'' {Number}: 距离右侧的px值
         * @example
         * var div = $('div');
         * div.fix({top:0, left:0}); //将div固顶在左上角
         * div.fix({top:0, right:0}); //将div固顶在右上角
         * div.fix({bottom:0, left:0}); //将div固顶在左下角
         * div.fix({bottom:0, right:0}); //将div固顶在右下角
         *
         */

        func.fix = function($obj, opts) {
            var me = $obj;                      //如果一个集合中的第一元素已fix，则认为这个集合的所有元素已fix，
            if(me.attr('isFixed')) return me;   //这样在操作时就可以针对集合进行操作，不必单独绑事件去操作
            me.css(opts).css('position', 'fixed').attr('isFixed', true);
            setTimeout(function() {
                var buff = $('

').appendTo('body'),
                    top = buff.offset(true).top,
                    checkFixed = function() {
                        if(window.pageYOffset > 0) {
                            if(buff.offset(true).top !== top) {
                                me.css('position', 'absolute');
                                doFixed();
                                $(document).on('scrollStop', doFixed);
                                $(window).on('ortchange', doFixed);
                            }
                            $(document).off('scrollStop', checkFixed);
                            buff.remove();
                        }
                    },
                    doFixed = function() {
                        me.css({
                            top: window.pageYOffset + (opts.bottom !== undefined ? window.innerHeight - me.height() - opts.bottom : (opts.top ||0)),
                            left: opts.right !== undefined ? document.body.offsetWidth - me.width() - opts.right : (opts.left || 0)
                        });
                        opts.width == '100%' && me.css('width', document.body.offsetWidth);
                    };
                $(document).on('scrollStop', checkFixed);
            }, 300);
        }

    })(func)

    /**
     * EVENT model
     */

    ;(function(func) {

        var _cache = {};

        /**
         * 广播事件
         * 目标: 为了尽可能的减少模块之间业务逻辑的耦合度, 而开发了这个eventbus, 主要用于业务逻辑的事件传递
         * 使用规范: 每个js模块尽可能通过事件去通信, 减少模块之间的直接调用和依赖(耦合)
         */

        /**
         * 派发
         * @param  {[type]} type 事件类型
         * @param  {[type]} data 回调数据
         * @return {[type]}      [description]
         */
        func.fire = function(type, data) {
            var listeners = _cache[type],
                len = 0;
            if (typeof listeners !== 'undefined') {
                var args = [].slice.call(arguments, 0);
                args = args.length > 2 ? args.splice(2, args.length - 1) : [];
                args = [data].concat(args);

                len = listeners.length;
                for (var i = 0; i < len; i++) {
                    var listener = listeners[i];
                    if (listener && listener.callback) {
                        args = args.concat(listener.args);
                        listener.callback.apply(listener.scope, args);
                    }
                }
            }
            return this;
        }

        /**
         * 订阅广播事件
         * @param  {[type]}   types     事件类型，支持,分隔符
         * @param  {Function} callback 回调函数
         * @param  {[type]}   scope    回调函数上下文
         * @return {[type]}            this
         */

        func.on = function(types, callback, scope) {
            types = types || [];
            var args = [].slice.call(arguments);

            if (typeof types === 'string') {
                types = types.split(',');
            }
            var len = types.length;
            if (len === 0) {
                return this;
            }
            args = args.length > 3 ? args.splice(3, args.length - 1) : [];
            for (var i = 0; i < len; i++) {
                var type = types[i];
                _cache[type] = _cache[type] || [];
                _cache[type].push({
                    callback: callback,
                    scope: scope,
                    args: args
                });
            }
            return this;
        }

        /**
         * 退订
         * @param  {[type]}   type     [description]
         * @param  {Function} callback 假如传入则移出传入的监控事件，否则移出全部
         * @return {[type]}            [description]
         */

        func.un = function(type, callback, scope) {
            var listeners = _cache[type];
            if (!listeners) {
                return this;
            }
            if (callback) {
                var len = listeners.length,
                    tmp = [];

                for (var i = 0; i < len; i++) {
                    var listener = listeners[i];
                    if (listener.callback == callback && listener.scope == scope) {} else {
                        tmp.push(listener);
                    }
                }
                listeners = tmp;
            } else {
                listeners.length = 0;
            }
            return this;
        }

        func.removeAll = function() {
            _cache = {};
            return this;
        }

    })(func)

    /**
     * HTTP model
     */

    ;(function(func) {

        /**
         * loader
         */
        func.loader = function(opts){
            opts = $.extend({
                dataType : "jsonp",
                jsonp : "cb",
                cache:false,
                timeout : 10000,

                success : function(){},
                error : function(jqXHR, textStatus, errorThrown){ console.log(textStatus)},
                complete : function(){}
            }, opts);

            $.ajax(opts);
        }

        /**
         * 获取cookie
         * @param  {[type]} name   [cookie名]
         * @return {[type]} String [cookie值]
         */

        func.getCookie = function(name) {
            var arr = document.cookie.split('; '),
                i = 0,
                len = arr.length ;

            for(;i<len;i++){
                var arr2 = arr[i].split('=');
                if(arr2[0] == name) {
                    return arr2[1];
                }
            }

            return '';
        }

        /**
         * 设置cookie值
         * @param {[type]} name  [cookie名字]
         * @param {[type]} value [cookie值]
         * @param {[type]} iDay  [过期时间，单位：天]
         */

        func.setCookie = function(name, value, iDay) {
            if(iDay!==false){

                var exp = new Date();
                exp.setTime(exp.getTime() + iDay*24*60*60*1000);
                document.cookie=name+'='+value+';expires='+exp.toGMTString()+';path=/';

            }else{
                document.cookie=name+'='+value;
            }
        }

        /**
         * 移除Cookie
         * @param  {[type]} name [Cookie名]
         */

        func.removeCookie = function (name) {
            func.setCookie(name, '', -1);
        }
    })(func)

    /**
     * MOBILE model
     */

    ;(function(func) {

        /**
         * 判断浏览器版本
         */

        func.Device = function() {
            var ua = navigator.userAgent;
            var os = this.os = {},browser = this.browser = {},

                webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/),
                android = ua.match(/(Android);?[\s\/]+([\d.]+)?/),
                osx = !!ua.match(/\(Macintosh\; Intel /),
                ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
                ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/),
                iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
                webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),
                touchpad = webos && ua.match(/TouchPad/),
                kindle = ua.match(/Kindle\/([\d.]+)/),
                silk = ua.match(/Silk\/([\d._]+)/),
                blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/),
                bb10 = ua.match(/(BB10).*Version\/([\d.]+)/),
                rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/),
                playbook = ua.match(/PlayBook/),
                baidu = ua.match( /baiduboxapp\/[^\/]+\/([\d.]+)_/ )
                        || ua.match( /baiduboxapp\/([\d.]+)/ )
                        || ua.match( /BaiduHD\/([\d.]+)/ )
                        || ua.match( /FlyFlow\/([\d.]+)/ )
                        || ua.match( /baidubrowser\/([\d.]+)/ ),
                qq = ua.match( /MQQBrowser\/([\d.]+)/ ) || ua.match( /QQ\/([\d.]+)/ ),
                uc = ua.match(/UCBrowser\/([\w.\s]+)/),
                chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/),
                firefox = ua.match(/Firefox\/([\d.]+)/),
                ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/),
                webview = !chrome && ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/),
                safari = webview || ua.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/),
                orientation = Math.abs(window.orientation);

            if (browser.webkit = !!webkit) browser.version = webkit[1]

            if (android) os.android = true, os.version = android[2]
            if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.')
            if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.')
            if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null
            if (webos) os.webos = true, os.version = webos[2]
            if (touchpad) os.touchpad = true
            if (blackberry) os.blackberry = true, os.version = blackberry[2]
            if (bb10) os.bb10 = true, os.version = bb10[2]
            if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2]
            if (playbook) browser.playbook = true
            if (baidu) browser.baidu = true,browser.version = baidu[1]
            if (qq) os.qq = true, os.ucversion = qq[1]
            if (uc) os.uc = true, os.ucversion = uc[1]
            if (kindle) os.kindle = true, os.version = kindle[1]
            if (silk) browser.silk = true, browser.version = silk[1]
            if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true
            if (orientation !== 90) os.protrait = true
            if (orientation === 90) os.landscape = true

            if (chrome) browser.chrome = true, browser.version = chrome[1]
            if (firefox) browser.firefox = true, browser.version = firefox[1]
            if (ie) browser.ie = true, browser.version = ie[1]
            if (safari && (osx || os.ios)) {browser.safari = true; if (osx) browser.version = safari[1]}
            if (webview) browser.webview = true

            os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
            (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)))
            os.phone  = !!(!os.tablet && !os.ipod && (android || iphone || webos || blackberry || bb10 ||
            (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
            (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))))
            return {
                browser: browser,
                os: os
            };
        }

    })(func)

    return func;
})<|endoftext|>


<commit_before>/*
 * @author: Hsiaoming Yang
 */

function parse(code) {
  code = code + '\n';
  var lines = code.split(/\r\n|\r|\n/);
  var sections = [];

  var comments = [];
  var inComment = false, section;
  lines.forEach(function(line) {
    // comment block
    if (/^\/\*/.test(line)) {
      inComment = true;
    }
    if (/\*\/$/.test(line)) {
      inComment = false;
      line = line.replace(/\*\/$/, '');
      comments.push(cleanLine(line));
      return;
    }

    if (/^\/\//.test(line)) {
      comments.push(cleanLine(line));
      return;
    }

    if (inComment) {
      comments.push(cleanLine(line));
      return;
    }

    // it is not comment now
    if (comments.length) {
      section = parseSection(comments);
      if (section) {
        sections.push(section);
      }
      // reset storage
      comments = [];
    }
  });
  return sections;
}
module.exports = parse;

function parseSection(lines) {
  var name, title, description = [], modifiers = [], examples = [];

  var parsed, exampleStart, exampleFile;
  lines.forEach(function(line) {
    // example file is the last line of comment
    if (exampleFile) return;

    if (!name && line.trim()) {
      parsed = parseTitle(line);
      if (parsed) {
        name = parsed.name;
        title = parsed.title;
        return;
      }
    }
    if (!name) return;

    // parse modifier
    // :hover - Button when hover
    if (/^((?:\:|\.)[a-zA-Z0-9\:]+)\s+\-\s+(.*)$/.exec(line)) {
      return modifiers.push({name: RegExp.$1, description: RegExp.$2});
    }

    if (/^Examples\:/.test(line.trim())) {
      if (line.trim() === 'Examples:') {
        exampleStart = true;
      } else {
        exampleFile = line.trim().replace(/^Examples\:/, '').trim()
      }
      return;
    }

    if (!exampleStart && /^\s{2,}/.test(line)) {
      exampleStart = true;
    }
    if (exampleStart) {
      examples.push(line);
      return;
    }

    description.push(line);
  });
  if (!name) return null;

  var ret = {name: name, title: title, modifiers: modifiers};

  ret.description = description.join('\n').replace(/^\n*\s*/, '');

  if (exampleFile) {
    ret.exampleFile = exampleFile;
  } else {
    ret.html = formatCode(examples);
    ret.examples = parseExamples(ret.html, modifiers);
  }
  return ret;
}

function cleanLine(line) {
  // clean comment line
  line = line.replace(/^\/\//, '');
  line = line.replace(/^\s*\*/, '');
  line = line.replace(/^\/\*/, '');
  line = line.replace(/\*\/$/, '');
  line = line.replace(/^\s{0,1}/, '');
  return line.trimRight();
}

function parseTitle(line) {
  // the first line can be title
  if (/^(\d+\.\d+(?:\.\d+)?)\s+(.*)$/.exec(line)) {
    var name = RegExp.$1;
    var title = RegExp.$2;
    return {name: name, title: title};
  }
  return null;
}

function parseExamples(code, modifiers) {
  // <button class="classy {{modifier}}">Button</button>
  var examples = [];

  // we should have an example without modifier
  examples.push({
    name: '',
    code: code.replace(/\{\{modifier\}\}/g, '')
  });

  if (!modifiers) return examples;

  var name, value;
  modifiers.forEach(function(modifier) {
    name = modifier.name;
    value = code.replace(
      /\{\{modifier\}\}/g,
      name.replace(':', ' pseudo-class-').replace('.', ' ')
    );
    examples.push({name: name, code: value});
  });
  return examples;
}

function formatCode(lines) {
  var indent;
  var codes = [];

  lines.forEach(function(line) {
    if (indent === undefined && line.trim()) {
      var match = line.match(/\S/);
      if (match) {
        indent = new RegExp('^\\s{' + match.index + '}');
      }
    }
    if (!indent) return;
    codes.push(line.replace(indent, ''));
  });
  return codes.join('\n');
}
<commit_msg>loose control of {{modifier}}<commit_after>/*
 * @author: Hsiaoming Yang
 */

function parse(code) {
  code = code + '\n';
  var lines = code.split(/\r\n|\r|\n/);
  var sections = [];

  var comments = [];
  var inComment = false, section;
  lines.forEach(function(line) {
    // comment block
    if (/^\/\*/.test(line)) {
      inComment = true;
    }
    if (/\*\/$/.test(line)) {
      inComment = false;
      line = line.replace(/\*\/$/, '');
      comments.push(cleanLine(line));
      return;
    }

    if (/^\/\//.test(line)) {
      comments.push(cleanLine(line));
      return;
    }

    if (inComment) {
      comments.push(cleanLine(line));
      return;
    }

    // it is not comment now
    if (comments.length) {
      section = parseSection(comments);
      if (section) {
        sections.push(section);
      }
      // reset storage
      comments = [];
    }
  });
  return sections;
}
module.exports = parse;

function parseSection(lines) {
  var name, title, description = [], modifiers = [], examples = [];

  var parsed, exampleStart, exampleFile;
  lines.forEach(function(line) {
    // example file is the last line of comment
    if (exampleFile) return;

    if (!name && line.trim()) {
      parsed = parseTitle(line);
      if (parsed) {
        name = parsed.name;
        title = parsed.title;
        return;
      }
    }
    if (!name) return;

    // parse modifier
    // :hover - Button when hover
    if (/^((?:\:|\.)[a-zA-Z0-9\:]+)\s+\-\s+(.*)$/.exec(line)) {
      return modifiers.push({name: RegExp.$1, description: RegExp.$2});
    }

    if (/^Examples\:/.test(line.trim())) {
      if (line.trim() === 'Examples:') {
        exampleStart = true;
      } else {
        exampleFile = line.trim().replace(/^Examples\:/, '').trim()
      }
      return;
    }

    if (!exampleStart && /^\s{2,}/.test(line)) {
      exampleStart = true;
    }
    if (exampleStart) {
      examples.push(line);
      return;
    }

    description.push(line);
  });
  if (!name) return null;

  var ret = {name: name, title: title, modifiers: modifiers};

  ret.description = description.join('\n').replace(/^\n*\s*/, '');

  if (exampleFile) {
    ret.exampleFile = exampleFile;
  } else {
    ret.html = formatCode(examples);
    ret.examples = parseExamples(ret.html, modifiers);
  }
  return ret;
}

function cleanLine(line) {
  // clean comment line
  line = line.replace(/^\/\//, '');
  line = line.replace(/^\s*\*/, '');
  line = line.replace(/^\/\*/, '');
  line = line.replace(/\*\/$/, '');
  line = line.replace(/^\s{0,1}/, '');
  return line.trimRight();
}

function parseTitle(line) {
  // the first line can be title
  if (/^(\d+\.\d+(?:\.\d+)?)\s+(.*)$/.exec(line)) {
    var name = RegExp.$1;
    var title = RegExp.$2;
    return {name: name, title: title};
  }
  return null;
}

function parseExamples(code, modifiers) {
  // <button class="classy {{modifier}}">Button</button>
  var examples = [];

  // modifier regex
  var modifierRegex = /\{\{\s*modifier\s*\}\}/g;

  // we should have an example without modifier
  examples.push({
    name: '',
    code: code.replace(modifierRegex, '')
  });

  if (!modifiers) return examples;

  var name, value;
  modifiers.forEach(function(modifier) {
    name = modifier.name;
    value = code.replace(
      modifierRegex,
      name.replace(':', ' pseudo-class-').replace('.', ' ')
    );
    examples.push({name: name, code: value});
  });
  return examples;
}

function formatCode(lines) {
  var indent;
  var codes = [];

  lines.forEach(function(line) {
    if (indent === undefined && line.trim()) {
      var match = line.match(/\S/);
      if (match) {
        indent = new RegExp('^\\s{' + match.index + '}');
      }
    }
    if (!indent) return;
    codes.push(line.replace(indent, ''));
  });
  return codes.join('\n');
}
<|endoftext|>


<commit_before>'use strict';

angular
	.module('webClient.places')
	.factory('PlacesService', PlacesService);

function PlacesService($resource, envService) {
	console.log('Hello :)');
	return $resource(
		envService.read('baseBackendUrl') + '/places',
		{},
		{query: {method:'GET', isArray:true}}
	);
}
<commit_msg>Revert "Story-52 [Marcela, Felipe] Just testing if the new versions are being correctly deployed to Heroku from Snap - this commit will be reverted in the next push"<commit_after>'use strict';

angular
	.module('webClient.places')
	.factory('PlacesService', PlacesService);

function PlacesService($resource, envService) {
	return $resource(
		envService.read('baseBackendUrl') + '/places',
		{},
		{query: {method:'GET', isArray:true}}
	);
}
<|endoftext|>


<commit_before>// DOM Library Utilites
$.parseUrlQuery = function (url) {
    var query = {}, i, params, param;
    if (url.indexOf('?') >= 0) url = url.split('?')[1];
    params = url.split('&');
    for (i = 0; i < params.length; i++) {
        param = params[i].split('=');
        query[param[0]] = param[1];
    }
    return query;
};
$.isArray = function (arr) {
    if (Object.prototype.toString.apply(arr) === '[object Array]') return true;
    else return false;
};
$.unique = function (arr) {
    var unique = [];
    for (var i = 0; i < arr.length; i++) {
        if (unique.indexOf(arr[i]) === -1) unique.push(arr[i]);
    }
    return unique;
};
$.trim = function (str) {
    return str.trim();
};
$.supportTouch = (function () {
    return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
})();
$.fn = Dom7.prototype;
<commit_msg>Remove supportTouch, add new serializeObject util<commit_after>// DOM Library Utilites
$.parseUrlQuery = function (url) {
    var query = {}, i, params, param;
    if (url.indexOf('?') >= 0) url = url.split('?')[1];
    params = url.split('&');
    for (i = 0; i < params.length; i++) {
        param = params[i].split('=');
        query[param[0]] = param[1];
    }
    return query;
};
$.isArray = function (arr) {
    if (Object.prototype.toString.apply(arr) === '[object Array]') return true;
    else return false;
};
$.unique = function (arr) {
    var unique = [];
    for (var i = 0; i < arr.length; i++) {
        if (unique.indexOf(arr[i]) === -1) unique.push(arr[i]);
    }
    return unique;
};
$.trim = function (str) {
    return str.trim();
};
$.serializeObject = function (obj) {
    if (typeof obj === 'string') return obj;
    var resultArray = [];
    var separator = '&';
    for (var prop in obj) {
        if ($.isArray(obj[prop])) {
            var toPush = [];
            for (var i = 0; i < obj[prop].length; i ++) {
                toPush.push(prop + '=' + obj[prop][i]);
            }
            resultArray.push(toPush.join(separator));
        }
        else {
            // Should be string
            resultArray.push(prop + '=' + obj[prop]);
        }
    }

    return resultArray.join(separator);
};
$.fn = Dom7.prototype;
<|endoftext|>