<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/chrome/reps",
    "firebug/lib/locale",
    "firebug/lib/wrapper",
    "firebug/lib/url",
    "firebug/lib/string",
    "firebug/js/stackFrame",
    "firebug/console/errors",
    "firebug/trace/debug",
    "firebug/console/console",
    "firebug/lib/options",
],
function(FirebugReps, Locale, Wrapper, Url, Str, StackFrame, Errors, Debug, Console, Options) {

// ********************************************************************************************* //

/**
 * Returns a console object (bundled with passed window through closure). The object
 * provides all necessary APIs as described here: http://getfirebug.com/wiki/index.php/Console_API
 *
 * @param {Object} context
 * @param {Object} win
 */
function createFirebugConsole(context, win)
{
    // Defined as a chrome object, but exposed into the web content scope.
    var console = {
        __exposedProps__: {}
    };

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Exposed Properties

    console.log = function log()
    {
        return logFormatted(arguments, "log", true);
    };

    console.debug = function debug()
    {
        return logFormatted(arguments, "debug", true);
    };

    console.info = function info()
    {
        return logFormatted(arguments, "info", true);
    };

    console.warn = function warn()
    {
        return logFormatted(arguments, "warn", true);
    };

    console.exception = function exception()
    {
        return logAssert("error", arguments);
    };

    console.assert = function assert(x)
    {
        if (!x)
        {
            var rest = [];
            for (var i = 1; i < arguments.length; i++)
                rest.push(arguments[i]);
            return logAssert("assert", rest);
        }

        return Console.getDefaultReturnValue(win);
    };

    console.dir = function dir(o)
    {
        Firebug.Console.log(o, context, "dir", Firebug.DOMPanel.DirTable);
        return Console.getDefaultReturnValue(win);
    };

    console.dirxml = function dirxml(o)
    {
        if (o instanceof Wrapper.getContentView(win).Window)
            o = o.document.documentElement;
        else if (o instanceof Wrapper.getContentView(win).Document)
            o = o.documentElement;

        Firebug.Console.log(o, context, "dirxml", Firebug.HTMLPanel.SoloElement);
        return Console.getDefaultReturnValue(win);
    };

    console.trace = function firebugDebuggerTracer()
    {
        var unwrapped = Wrapper.unwrapObject(win);
        unwrapped.top._firebugStackTrace = "console-tracer";
        debugger;
        delete unwrapped.top._firebugStackTrace;

        return Console.getDefaultReturnValue(win);
    };

    console.group = function group()
    {
        var sourceLink = getStackLink();
        Firebug.Console.openGroup(arguments, null, "group", null, false, sourceLink);
        return Console.getDefaultReturnValue(win);
    };

    console.groupEnd = function()
    {
        Firebug.Console.closeGroup(context);
        return Console.getDefaultReturnValue(win);
    };

    console.groupCollapsed = function()
    {
        var sourceLink = getStackLink();

        // noThrottle true can't be used here (in order to get the result row now)
        // because there can be some logs delayed in the queue and they would end up
        // in a different grup.
        // Use rather a different method that causes auto collapsing of the group
        // when it's created.
        Firebug.Console.openCollapsedGroup(arguments, null, "group", null, false, sourceLink);
        return Console.getDefaultReturnValue(win);
    };

    console.profile = function(title)
    {
        Firebug.Profiler.startProfiling(context, title);
        return Console.getDefaultReturnValue(win);
    };

    console.profileEnd = function()
    {
        Firebug.Profiler.stopProfiling(context);
        return Console.getDefaultReturnValue(win);
    };

    console.count = function(key)
    {
        var frameId = getStackFrameId();
        if (frameId)
        {
            if (!context.frameCounters)
                context.frameCounters = {};

            if (key != undefined)
                frameId += key;

            var frameCounter = context.frameCounters[frameId];
            if (!frameCounter)
            {
                var logRow = logFormatted(["0"], null, true, true);

                frameCounter = {logRow: logRow, count: 1};
                context.frameCounters[frameId] = frameCounter;
            }
            else
                ++frameCounter.count;

            var label = key == undefined
                ? frameCounter.count
                : key + " " + frameCounter.count;

            frameCounter.logRow.firstChild.firstChild.nodeValue = label;
        }
        return Console.getDefaultReturnValue(win);
    };

    console.clear = function()
    {
        Firebug.Console.clear(context);
        return Console.getDefaultReturnValue(win);
    };

    console.time = function(name, reset)
    {
        if (!name)
            return Console.getDefaultReturnValue(win);

        var time = new Date().getTime();

        if (!this.timeCounters)
            this.timeCounters = {};

        var key = "KEY"+name.toString();

        if (!reset && this.timeCounters[key])
            return Console.getDefaultReturnValue(win);

        this.timeCounters[key] = time;
        return Console.getDefaultReturnValue(win);
    };

    console.timeEnd = function(name)
    {
        var time = new Date().getTime();
        var diff = undefined;

        if (!this.timeCounters)
            return Console.getDefaultReturnValue(win);

        var key = "KEY"+name.toString();

        var timeCounter = this.timeCounters[key];
        if (timeCounter)
        {
            diff = time - timeCounter;
            var label = name + ": " + diff + "ms";

            this.info(label);

            delete this.timeCounters[key];
        }
        return diff;
    };

    console.timeStamp = function(label)
    {
        label = label || "";

        if (FBTrace.DBG_CONSOLE)
            FBTrace.sysout("consoleExposed.timeStamp; " + label);

        var now = new Date();
        Firebug.NetMonitor.addTimeStamp(context, now.getTime(), label);

        var formattedTime = now.getHours() + ":" + now.getMinutes() + ":" +
            now.getSeconds() + "." + now.getMilliseconds();
        return logFormatted([formattedTime, label], "timeStamp");
    };

    console.table = function(data, columns)
    {
        FirebugReps.Table.log(data, columns, context);
        return Console.getDefaultReturnValue(win);
    };

    console.error = function error()
    {
        // TODO stack trace
        if (arguments.length == 1)
        {
            return logAssert("error", arguments);  // add more info based on stack trace
        }
        else
        {
            Errors.increaseCount(context);
            return logFormatted(arguments, "error", true);  // user already added info
        }
    };

    // xxxHonza: removed from 1.10 (issue 5599)
    /*console.memoryProfile = function(title)
    {
        Firebug.MemoryProfiler.start(context, title);
        return Console.getDefaultReturnValue(win);
    };

    console.memoryProfileEnd = function()
    {
        Firebug.MemoryProfiler.stop(context);
        return Console.getDefaultReturnValue(win);
    };*/

    // Expose only these properties to the content scope (read only).
    console.__exposedProps__.log = "r";
    console.__exposedProps__.debug = "r";
    console.__exposedProps__.info = "r";
    console.__exposedProps__.warn = "r";
    console.__exposedProps__.exception = "r";
    console.__exposedProps__.assert = "r";
    console.__exposedProps__.dir = "r";
    console.__exposedProps__.dirxml = "r";
    console.__exposedProps__.trace = "r";
    console.__exposedProps__.group = "r";
    console.__exposedProps__.groupEnd = "r";
    console.__exposedProps__.groupCollapsed = "r";
    console.__exposedProps__.time = "r";
    console.__exposedProps__.timeEnd = "r";
    console.__exposedProps__.timeStamp = "r";
    console.__exposedProps__.profile = "r";
    console.__exposedProps__.profileEnd = "r";
    console.__exposedProps__.count = "r";
    console.__exposedProps__.clear = "r";
    console.__exposedProps__.table = "r";
    console.__exposedProps__.error = "r";
    //console.__exposedProps__.memoryProfile = "r";
    //console.__exposedProps__.memoryProfileEnd = "r";

    // DBG console.uid = Math.random();

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Helpers (not accessible from web content)

    function logFormatted(args, className, linkToSource, noThrottle)
    {
        var sourceLink = null;

        // Using JSD to get user stack is time consuming.
        if (Options.get("preferJSDSourceLinks"))
        {
            var stack = getJSDUserStack();
            if (stack && stack.toSourceLink)
                sourceLink = stack.toSourceLink();
        }

        if (!sourceLink)
            sourceLink = linkToSource ? getStackLink() : null;

        var ignoreReturnValue = Firebug.Console.getDefaultReturnValue(win);
        var rc = Firebug.Console.logFormatted(args, context, className, noThrottle, sourceLink);
        return rc ? rc : ignoreReturnValue;
    };

    function logAssert(category, args)
    {
        Errors.increaseCount(context);

        var msg = (!args || !args.length || args.length == 0) ?
            [Locale.$STR("Assertion")] : args[0];

        // If there's no error message, there's also no stack trace. See Issue 4700.
        var trace = null;
        if (msg)
        {
            if (msg.stack)
            {
                trace = StackFrame.parseToStackTrace(msg.stack, context);
                if (FBTrace.DBG_CONSOLE)
                    FBTrace.sysout("logAssert trace from msg.stack", trace);
            }
            else if (context.stackTrace)
            {
                trace = context.stackTrace;
                if (FBTrace.DBG_CONSOLE)
                    FBTrace.sysout("logAssert trace from context.window.stackTrace", trace);
            }
            else
            {
                trace = getJSDUserStack();
                if (FBTrace.DBG_CONSOLE)
                    FBTrace.sysout("logAssert trace from getJSDUserStack", trace);
            }
        }

        trace = StackFrame.cleanStackTraceOfFirebug(trace);

        var url = msg && msg.fileName ? msg.fileName : win.location.href;

        // we may have only the line popped above
        var lineNo = (trace && msg && msg.lineNumber) ? msg.lineNumber : 0;
        var errorObject = new FirebugReps.ErrorMessageObj(msg, url, lineNo, "",
            category, context, trace);

        if (trace && trace.frames && trace.frames[0])
            errorObject.correctWithStackTrace(trace);

        errorObject.resetSource();

        if (args.length > 1)
        {
            errorObject.objects = [];
            for (var i = 1; i < args.length; i++)
                errorObject.objects.push(args[i]);
        }

        var row = Firebug.Console.log(errorObject, context, "errorMessage");
        if (row)
            row.scrollIntoView();

        return Console.getDefaultReturnValue(win);
    };

    function getComponentsStackDump()
    {
        // Starting with our stack, walk back to the user-level code
        var frame = Components.stack;
        var userURL = win.location.href.toString();

        if (FBTrace.DBG_CONSOLE)
            FBTrace.sysout("consoleInjector.getComponentsStackDump initial stack for userURL " +
                userURL, frame);

        // Drop frames until we get into user code.
        while (frame && Url.isSystemURL(frame.filename) )
            frame = frame.caller;

        // Drop two more frames, the injected console function and firebugAppendConsole()
        //if (frame)
        //    frame = frame.caller;
        //if (frame)
        //    frame = frame.caller;

        if (FBTrace.DBG_CONSOLE)
            FBTrace.sysout("consoleInjector.getComponentsStackDump final stack for userURL " +
                userURL, frame);

        return frame;
    };

    function getStackLink()
    {
        return StackFrame.getFrameSourceLink(getComponentsStackDump());
    };

    function getJSDUserStack()
    {
        var trace = Firebug.Debugger.getCurrentStackTrace(context);

        var frames = trace ? trace.frames : null;
        if (frames && (frames.length > 0) )
        {
            var filteredFrames = [];

            for (var i = 0; i < frames.length; i++)
            {
                if (Str.hasPrefix(frames[i].href, "chrome:"))
                    continue;

                if (Str.hasPrefix(frames[i].href, "resource:"))
                    continue;

                // firebug-service scope reached, in some cases the url starts with file://
                if (frames[i].href.indexOf("modules/firebug-service.js") != -1)
                    continue;

                // command line
                var fn = frames[i].getFunctionName() + "";
                if (fn && (fn.indexOf("_firebugEvalEvent") != -1))
                    continue;

                filteredFrames.push(frames[i]);
            }

            // take the oldest frames, leave 2 behind they are injection code
            trace.frames = filteredFrames; //trace.frames.slice(2 - i);

            return trace;
        }
        else
        {
            return "Firebug failed to get stack trace with any frames";
        }
    };

    function getStackFrameId(inputFrame)
    {
        for (var frame = Components.stack; frame; frame = frame.caller)
        {
            if (frame.languageName == "JavaScript"
                && !(frame.filename && frame.filename.indexOf("://firebug/") > 0))
            {
                return frame.filename + "/" + frame.lineNumber;
            }
        }
        return null;
    };

    return console;
}

// ********************************************************************************************* //
// Registration

Firebug.ConsoleExposed =
{
    createFirebugConsole: createFirebugConsole
};

return Firebug.ConsoleExposed;

// ********************************************************************************************* //
});
<commit_msg>Issue 4979; fix console/api/count test<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/chrome/reps",
    "firebug/lib/locale",
    "firebug/lib/wrapper",
    "firebug/lib/url",
    "firebug/lib/string",
    "firebug/js/stackFrame",
    "firebug/console/errors",
    "firebug/trace/debug",
    "firebug/console/console",
    "firebug/lib/options",
],
function(FirebugReps, Locale, Wrapper, Url, Str, StackFrame, Errors, Debug, Console, Options) {

// ********************************************************************************************* //

/**
 * Returns a console object (bundled with passed window through closure). The object
 * provides all necessary APIs as described here: http://getfirebug.com/wiki/index.php/Console_API
 *
 * @param {Object} context
 * @param {Object} win
 */
function createFirebugConsole(context, win)
{
    // Defined as a chrome object, but exposed into the web content scope.
    var console = {
        __exposedProps__: {}
    };

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Exposed Properties

    console.log = function log()
    {
        return logFormatted(arguments, "log", true);
    };

    console.debug = function debug()
    {
        return logFormatted(arguments, "debug", true);
    };

    console.info = function info()
    {
        return logFormatted(arguments, "info", true);
    };

    console.warn = function warn()
    {
        return logFormatted(arguments, "warn", true);
    };

    console.exception = function exception()
    {
        return logAssert("error", arguments);
    };

    console.assert = function assert(x)
    {
        if (!x)
        {
            var rest = [];
            for (var i = 1; i < arguments.length; i++)
                rest.push(arguments[i]);
            return logAssert("assert", rest);
        }

        return Console.getDefaultReturnValue(win);
    };

    console.dir = function dir(o)
    {
        Firebug.Console.log(o, context, "dir", Firebug.DOMPanel.DirTable);
        return Console.getDefaultReturnValue(win);
    };

    console.dirxml = function dirxml(o)
    {
        if (o instanceof Wrapper.getContentView(win).Window)
            o = o.document.documentElement;
        else if (o instanceof Wrapper.getContentView(win).Document)
            o = o.documentElement;

        Firebug.Console.log(o, context, "dirxml", Firebug.HTMLPanel.SoloElement);
        return Console.getDefaultReturnValue(win);
    };

    console.trace = function firebugDebuggerTracer()
    {
        var unwrapped = Wrapper.unwrapObject(win);
        unwrapped.top._firebugStackTrace = "console-tracer";
        debugger;
        delete unwrapped.top._firebugStackTrace;

        return Console.getDefaultReturnValue(win);
    };

    console.group = function group()
    {
        var sourceLink = getStackLink();
        Firebug.Console.openGroup(arguments, null, "group", null, false, sourceLink);
        return Console.getDefaultReturnValue(win);
    };

    console.groupEnd = function()
    {
        Firebug.Console.closeGroup(context);
        return Console.getDefaultReturnValue(win);
    };

    console.groupCollapsed = function()
    {
        var sourceLink = getStackLink();

        // noThrottle true can't be used here (in order to get the result row now)
        // because there can be some logs delayed in the queue and they would end up
        // in a different grup.
        // Use rather a different method that causes auto collapsing of the group
        // when it's created.
        Firebug.Console.openCollapsedGroup(arguments, null, "group", null, false, sourceLink);
        return Console.getDefaultReturnValue(win);
    };

    console.profile = function(title)
    {
        Firebug.Profiler.startProfiling(context, title);
        return Console.getDefaultReturnValue(win);
    };

    console.profileEnd = function()
    {
        Firebug.Profiler.stopProfiling(context);
        return Console.getDefaultReturnValue(win);
    };

    console.count = function(key)
    {
        var frameId = getStackFrameId();
        if (frameId)
        {
            if (!context.frameCounters)
                context.frameCounters = {};

            if (key != undefined)
                frameId += key;

            var frameCounter = context.frameCounters[frameId];
            if (!frameCounter)
            {
                var logRow = logFormatted(["0"], null, true, true);

                frameCounter = {logRow: logRow, count: 1};
                context.frameCounters[frameId] = frameCounter;
            }
            else
            {
                ++frameCounter.count;
            }

            var label = key == undefined
                ? frameCounter.count
                : key + " " + frameCounter.count;

            var node = frameCounter.logRow.getElementsByClassName("objectBox-text")[0];
            node.firstChild.nodeValue = label;
        }
        return Console.getDefaultReturnValue(win);
    };

    console.clear = function()
    {
        Firebug.Console.clear(context);
        return Console.getDefaultReturnValue(win);
    };

    console.time = function(name, reset)
    {
        if (!name)
            return Console.getDefaultReturnValue(win);

        var time = new Date().getTime();

        if (!this.timeCounters)
            this.timeCounters = {};

        var key = "KEY"+name.toString();

        if (!reset && this.timeCounters[key])
            return Console.getDefaultReturnValue(win);

        this.timeCounters[key] = time;
        return Console.getDefaultReturnValue(win);
    };

    console.timeEnd = function(name)
    {
        var time = new Date().getTime();
        var diff = undefined;

        if (!this.timeCounters)
            return Console.getDefaultReturnValue(win);

        var key = "KEY"+name.toString();

        var timeCounter = this.timeCounters[key];
        if (timeCounter)
        {
            diff = time - timeCounter;
            var label = name + ": " + diff + "ms";

            this.info(label);

            delete this.timeCounters[key];
        }
        return diff;
    };

    console.timeStamp = function(label)
    {
        label = label || "";

        if (FBTrace.DBG_CONSOLE)
            FBTrace.sysout("consoleExposed.timeStamp; " + label);

        var now = new Date();
        Firebug.NetMonitor.addTimeStamp(context, now.getTime(), label);

        var formattedTime = now.getHours() + ":" + now.getMinutes() + ":" +
            now.getSeconds() + "." + now.getMilliseconds();
        return logFormatted([formattedTime, label], "timeStamp");
    };

    console.table = function(data, columns)
    {
        FirebugReps.Table.log(data, columns, context);
        return Console.getDefaultReturnValue(win);
    };

    console.error = function error()
    {
        // TODO stack trace
        if (arguments.length == 1)
        {
            return logAssert("error", arguments);  // add more info based on stack trace
        }
        else
        {
            Errors.increaseCount(context);
            return logFormatted(arguments, "error", true);  // user already added info
        }
    };

    // xxxHonza: removed from 1.10 (issue 5599)
    /*console.memoryProfile = function(title)
    {
        Firebug.MemoryProfiler.start(context, title);
        return Console.getDefaultReturnValue(win);
    };

    console.memoryProfileEnd = function()
    {
        Firebug.MemoryProfiler.stop(context);
        return Console.getDefaultReturnValue(win);
    };*/

    // Expose only these properties to the content scope (read only).
    console.__exposedProps__.log = "r";
    console.__exposedProps__.debug = "r";
    console.__exposedProps__.info = "r";
    console.__exposedProps__.warn = "r";
    console.__exposedProps__.exception = "r";
    console.__exposedProps__.assert = "r";
    console.__exposedProps__.dir = "r";
    console.__exposedProps__.dirxml = "r";
    console.__exposedProps__.trace = "r";
    console.__exposedProps__.group = "r";
    console.__exposedProps__.groupEnd = "r";
    console.__exposedProps__.groupCollapsed = "r";
    console.__exposedProps__.time = "r";
    console.__exposedProps__.timeEnd = "r";
    console.__exposedProps__.timeStamp = "r";
    console.__exposedProps__.profile = "r";
    console.__exposedProps__.profileEnd = "r";
    console.__exposedProps__.count = "r";
    console.__exposedProps__.clear = "r";
    console.__exposedProps__.table = "r";
    console.__exposedProps__.error = "r";
    //console.__exposedProps__.memoryProfile = "r";
    //console.__exposedProps__.memoryProfileEnd = "r";

    // DBG console.uid = Math.random();

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Helpers (not accessible from web content)

    function logFormatted(args, className, linkToSource, noThrottle)
    {
        var sourceLink = null;

        // Using JSD to get user stack is time consuming.
        if (Options.get("preferJSDSourceLinks"))
        {
            var stack = getJSDUserStack();
            if (stack && stack.toSourceLink)
                sourceLink = stack.toSourceLink();
        }

        if (!sourceLink)
            sourceLink = linkToSource ? getStackLink() : null;

        var ignoreReturnValue = Firebug.Console.getDefaultReturnValue(win);
        var rc = Firebug.Console.logFormatted(args, context, className, noThrottle, sourceLink);
        return rc ? rc : ignoreReturnValue;
    };

    function logAssert(category, args)
    {
        Errors.increaseCount(context);

        var msg = (!args || !args.length || args.length == 0) ?
            [Locale.$STR("Assertion")] : args[0];

        // If there's no error message, there's also no stack trace. See Issue 4700.
        var trace = null;
        if (msg)
        {
            if (msg.stack)
            {
                trace = StackFrame.parseToStackTrace(msg.stack, context);
                if (FBTrace.DBG_CONSOLE)
                    FBTrace.sysout("logAssert trace from msg.stack", trace);
            }
            else if (context.stackTrace)
            {
                trace = context.stackTrace;
                if (FBTrace.DBG_CONSOLE)
                    FBTrace.sysout("logAssert trace from context.window.stackTrace", trace);
            }
            else
            {
                trace = getJSDUserStack();
                if (FBTrace.DBG_CONSOLE)
                    FBTrace.sysout("logAssert trace from getJSDUserStack", trace);
            }
        }

        trace = StackFrame.cleanStackTraceOfFirebug(trace);

        var url = msg && msg.fileName ? msg.fileName : win.location.href;

        // we may have only the line popped above
        var lineNo = (trace && msg && msg.lineNumber) ? msg.lineNumber : 0;
        var errorObject = new FirebugReps.ErrorMessageObj(msg, url, lineNo, "",
            category, context, trace);

        if (trace && trace.frames && trace.frames[0])
            errorObject.correctWithStackTrace(trace);

        errorObject.resetSource();

        if (args.length > 1)
        {
            errorObject.objects = [];
            for (var i = 1; i < args.length; i++)
                errorObject.objects.push(args[i]);
        }

        var row = Firebug.Console.log(errorObject, context, "errorMessage");
        if (row)
            row.scrollIntoView();

        return Console.getDefaultReturnValue(win);
    };

    function getComponentsStackDump()
    {
        // Starting with our stack, walk back to the user-level code
        var frame = Components.stack;
        var userURL = win.location.href.toString();

        if (FBTrace.DBG_CONSOLE)
            FBTrace.sysout("consoleInjector.getComponentsStackDump initial stack for userURL " +
                userURL, frame);

        // Drop frames until we get into user code.
        while (frame && Url.isSystemURL(frame.filename) )
            frame = frame.caller;

        // Drop two more frames, the injected console function and firebugAppendConsole()
        //if (frame)
        //    frame = frame.caller;
        //if (frame)
        //    frame = frame.caller;

        if (FBTrace.DBG_CONSOLE)
            FBTrace.sysout("consoleInjector.getComponentsStackDump final stack for userURL " +
                userURL, frame);

        return frame;
    };

    function getStackLink()
    {
        return StackFrame.getFrameSourceLink(getComponentsStackDump());
    };

    function getJSDUserStack()
    {
        var trace = Firebug.Debugger.getCurrentStackTrace(context);

        var frames = trace ? trace.frames : null;
        if (frames && (frames.length > 0) )
        {
            var filteredFrames = [];

            for (var i = 0; i < frames.length; i++)
            {
                if (Str.hasPrefix(frames[i].href, "chrome:"))
                    continue;

                if (Str.hasPrefix(frames[i].href, "resource:"))
                    continue;

                // firebug-service scope reached, in some cases the url starts with file://
                if (frames[i].href.indexOf("modules/firebug-service.js") != -1)
                    continue;

                // command line
                var fn = frames[i].getFunctionName() + "";
                if (fn && (fn.indexOf("_firebugEvalEvent") != -1))
                    continue;

                filteredFrames.push(frames[i]);
            }

            // take the oldest frames, leave 2 behind they are injection code
            trace.frames = filteredFrames; //trace.frames.slice(2 - i);

            return trace;
        }
        else
        {
            return "Firebug failed to get stack trace with any frames";
        }
    };

    function getStackFrameId(inputFrame)
    {
        for (var frame = Components.stack; frame; frame = frame.caller)
        {
            if (frame.languageName == "JavaScript"
                && !(frame.filename && frame.filename.indexOf("://firebug/") > 0))
            {
                return frame.filename + "/" + frame.lineNumber;
            }
        }
        return null;
    };

    return console;
}

// ********************************************************************************************* //
// Registration

Firebug.ConsoleExposed =
{
    createFirebugConsole: createFirebugConsole
};

return Firebug.ConsoleExposed;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>/**
 * 应用程序
 * @type {Object}
 */
var cluster = require("cluster");
var fs = require("fs");

var App = module.exports = Class(function(){
    return {
        http: null,
        init: function(http){
            this.http = http;
        },
        dispatch: function(){
            //路径解析
            return thinkRequire('Dispatcher')(this.http).run();
        },
        exec: function(){
            var group = this.http.group;
            var controller = '';
            var reg = /^[A-Za-z](\w)*$/;
            var self = this;
            //检测controller名
            if (!reg.test(this.http.controller)) {
                controller = '';
            }else{
                controller = A(group + "/" + this.http.controller, this.http);
            }
            if (!controller) {
                var event = C('empty_controller_event');
                if (event && E(event, true).length > 0) {
                    E(event, this.http.controller, group, this.http);
                    return true;
                };
                return getPromise(this.http.controller + " controller not found", true);
            };
            var action = this.http.action;
            var oldAction = action;
            //添加action后缀
            action += C('action_suffix') || "";
            //检测action名
            if (!reg.test(action)) {
                return getPromise('action name error', true);
            };
            var initReturnPromise = getPromise(controller.__initReturn);
            //对应的action方法存在
            if (typeof controller[action] == 'function') {
                //方法参数自动绑定，直接从形参里拿到对应的值
                if (C('url_params_bind')) {
                    var toString = controller[action].toString();
                    toString = toString.replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/mg, '');
                    var match = toString.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1].split(/,/).filter(function(item){
                        return item;
                    });
                    //匹配到形参
                    if (match && match.length) {
                        var data = [];
                        match.forEach(function(item){
                            var value = self.http.post[item] || self.http.get[item] || "";
                            data.push(value);
                        });
                        return initReturnPromise.then(function(){
                            return self.execAction(controller, action, oldAction, data);
                        })
                    }
                }
                return initReturnPromise.then(function(){
                    return self.execAction(controller, action, oldAction);
                })
            }else{
                //当指定的方法不存在时，调用魔术方法
                //默认为__call方法
                if (C('call_method') && typeof controller[C('call_method')] == 'function') {
                    return initReturnPromise.then(function(){
                        return controller[C('call_method')](action);
                    });
                };
            }
            return getPromise("action: " + action + " not found", true);
        },
        /**
         * 执行一个action, 支持before和after的统一操作
         * 不对每个action都增加一个before和after，而是使用统一的策略
         * 默认before和after调用名__before和__after
         * @param  {[type]} controller [description]
         * @param  {[type]} action     [description]
         * @param  {[type]} oldAction  [description]
         * @param  {[type]} data       [description]
         * @return {[type]}            [description]
         */
        execAction: function(controller, action, oldAction, data){
            var promise = null;
            //before action
            var before = C('before_action_name');
            if (before && typeof controller[before] == 'function') {
                var ret = controller[before].call(controller, oldAction, action);
                promise = getPromise(ret);
            }else{
                promise = getPromise();
            }
            promise = promise.then(function(){
                var ret = null;
                //绑定方法参数
                if (data) {
                    ret = controller[action].apply(controller, data);
                }else{
                    ret = controller[action]();
                }
                return getPromise(ret);
            }).then(function(){
                //after action
                var after = C('after_action_name');
                if (after && typeof controller[after] == 'function') {
                    return controller[after].call(controller, oldAction, action);
                };
             });
            //debug模式下将错误信息打印出来
            if (APP_DEBUG) {
                promise = promise.catch(function(err){
                    console.log(err)
                });
            };
            return promise;
        }
    }
});
/**
 * run
 * @return {[type]} [description]
 */
App.run = function(){
    //命令行调用
    if (APP_MODE) {
        var http = thinkRequire("Http")[APP_MODE](APP_MODE_DATA);
        return App.listener(http);
    };
    var clusterNums = C('use_cluster');
    //不使用cluster
    if (clusterNums === false) {
        return App.createServer();
    }
    if (clusterNums === 0 || clusterNums === true) {
        clusterNums = require('os').cpus().length;
    };
    var cluster = require('cluster');
    if (cluster.isMaster) {
        for (var i = 0; i < clusterNums; i++) {
            cluster.fork();
        }
        cluster.on('exit', function(worker, code, signal) {
            console.log('worker ' + worker.process.pid + ' died');
            process.nextTick(function(){
                cluster.fork();
            });
        });
    }else {
        App.createServer();
    }
}
/**
 * 创建服务
 * @return {[type]} [description]
 */
App.createServer = function(){
    var server = require("http").createServer(function (req, res) {
        thinkRequire("Http")(req, res).run(App.listener);
    });
    var params = [C('port')];
    //禁止外网直接通过IP访问
    if (C('deny_remote_access_by_ip')) {
        params.push("127.0.0.1");
    };
    server.listen.apply(server, params);
};
/**
 * 监听回调函数
 * @param  {[type]} http [description]
 * @return {[type]}      [description]
 */
App.listener = function(http){
    //自动发送thinkjs和版本的header
    http.setHeader("X-Powered-By", "thinkjs-" + THINK_VERSION);
    //初始化Session
    if (C('session_auto_start')) {
        thinkRequire('Session').start(http);
    };
    var instance = App(http);
    var promise = tag ('app_init', http).then(function(){
        return instance.dispatch();
    }).then(function(){
        return tag('app_begin', http);
    }).then(function(){
        return tag('action_init', http);
    }).then(function(){
        return instance.exec();
    }).then(function(){
        return tag('app_end', http);
    });
    //debug模式下将错误信息打印出来
    if (APP_DEBUG) {
        promise = promise.catch(function(err){
            console.log(err);
        })
    }else{
        //显示默认的错误页
        promise = promise.catch(function(err){
            http.setHeader('Content-Type', 'text/html; charset=' + C('encoding'));
            var readStream = fs.createReadStream(C('error_tpl_path'));
            readStream.pipe(http.res);
            readStream.on("end", function(){
                http.res.end();
            })
        })
    }
    return promise;
}<commit_msg>update<commit_after>/**
 * 应用程序
 * @type {Object}
 */
var cluster = require("cluster");
var fs = require("fs");

var App = module.exports = Class(function(){
    //controller和action的校验正则
    var nameReg = /^[A-Za-z](\w)*$/;
    //注释的正则
    var commentReg = /((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/mg;
    //获取形参的正则
    var parsReg = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;

    return {
        http: null,
        init: function(http){
            this.http = http;
        },
        dispatch: function(){
            //路径解析
            return thinkRequire('Dispatcher')(this.http).run();
        },
        exec: function(){
            var group = this.http.group;
            var controller = '';
            var self = this;
            //检测controller名
            if (!nameReg.test(this.http.controller)) {
                controller = '';
            }else{
                controller = A(group + "/" + this.http.controller, this.http);
            }
            if (!controller) {
                var event = C('empty_controller_event');
                if (event && E(event, true).length > 0) {
                    E(event, this.http.controller, group, this.http);
                    return true;
                };
                return getPromise(this.http.controller + " controller not found", true);
            };
            var action = this.http.action;
            var oldAction = action;
            //添加action后缀
            action += C('action_suffix') || "";
            //检测action名
            if (!nameReg.test(action)) {
                return getPromise('action name error', true);
            };
            var initReturnPromise = getPromise(controller.__initReturn);
            //对应的action方法存在
            if (typeof controller[action] == 'function') {
                //方法参数自动绑定，直接从形参里拿到对应的值
                if (C('url_params_bind')) {
                    var toString = controller[action].toString();
                    toString = toString.replace(commentReg, '');
                    var match = toString.match(parsReg)[1].split(/,/).filter(function(item){
                        return item;
                    });
                    //匹配到形参
                    if (match && match.length) {
                        var data = [];
                        match.forEach(function(item){
                            var value = self.http.post[item] || self.http.get[item] || "";
                            data.push(value);
                        });
                        return initReturnPromise.then(function(){
                            return self.execAction(controller, action, oldAction, data);
                        })
                    }
                }
                return initReturnPromise.then(function(){
                    return self.execAction(controller, action, oldAction);
                })
            }else{
                //当指定的方法不存在时，调用魔术方法
                //默认为__call方法
                if (C('call_method') && typeof controller[C('call_method')] == 'function') {
                    return initReturnPromise.then(function(){
                        return controller[C('call_method')](action);
                    });
                };
            }
            return getPromise("action: " + action + " not found", true);
        },
        /**
         * 执行一个action, 支持before和after的统一操作
         * 不对每个action都增加一个before和after，而是使用统一的策略
         * 默认before和after调用名__before和__after
         * @param  {[type]} controller [description]
         * @param  {[type]} action     [description]
         * @param  {[type]} oldAction  [description]
         * @param  {[type]} data       [description]
         * @return {[type]}            [description]
         */
        execAction: function(controller, action, oldAction, data){
            var promise = null;
            //before action
            var before = C('before_action_name');
            if (before && typeof controller[before] == 'function') {
                var ret = controller[before].call(controller, oldAction, action);
                promise = getPromise(ret);
            }else{
                promise = getPromise();
            }
            promise = promise.then(function(){
                var ret = null;
                //绑定方法参数
                if (data) {
                    ret = controller[action].apply(controller, data);
                }else{
                    ret = controller[action]();
                }
                return getPromise(ret);
            }).then(function(){
                //after action
                var after = C('after_action_name');
                if (after && typeof controller[after] == 'function') {
                    return controller[after].call(controller, oldAction, action);
                };
             });
            //debug模式下将错误信息打印出来
            if (APP_DEBUG) {
                promise = promise.catch(function(err){
                    console.log(err)
                });
            };
            return promise;
        }
    }
});
/**
 * run
 * @return {[type]} [description]
 */
App.run = function(){
    //命令行调用
    if (APP_MODE) {
        var http = thinkRequire("Http")[APP_MODE](APP_MODE_DATA);
        return App.listener(http);
    };
    var clusterNums = C('use_cluster');
    //不使用cluster
    if (clusterNums === false) {
        return App.createServer();
    }
    if (clusterNums === 0 || clusterNums === true) {
        clusterNums = require('os').cpus().length;
    };
    if (cluster.isMaster) {
        for (var i = 0; i < clusterNums; i++) {
            cluster.fork();
        }
        cluster.on('exit', function(worker, code, signal) {
            console.log('worker ' + worker.process.pid + ' died');
            process.nextTick(function(){
                cluster.fork();
            });
        });
    }else {
        App.createServer();
    }
}
/**
 * 创建服务
 * @return {[type]} [description]
 */
App.createServer = function(){
    var server = require("http").createServer(function (req, res) {
        thinkRequire("Http")(req, res).run(App.listener);
    });
    var params = [C('port')];
    //禁止外网直接通过IP访问
    if (C('deny_remote_access_by_ip')) {
        params.push("127.0.0.1");
    };
    server.listen.apply(server, params);
};
/**
 * 监听回调函数
 * @param  {[type]} http [description]
 * @return {[type]}      [description]
 */
App.listener = function(http){
    //自动发送thinkjs和版本的header
    http.setHeader("X-Powered-By", "thinkjs-" + THINK_VERSION);
    //初始化Session
    if (C('session_auto_start')) {
        thinkRequire('Session').start(http);
    };
    var instance = App(http);
    var promise = tag ('app_init', http).then(function(){
        return instance.dispatch();
    }).then(function(){
        return tag('app_begin', http);
    }).then(function(){
        return tag('action_init', http);
    }).then(function(){
        return instance.exec();
    }).then(function(){
        return tag('app_end', http);
    });
    //debug模式下将错误信息打印出来
    if (APP_DEBUG) {
        promise = promise.catch(function(err){
            console.log(err);
        })
    }else{
        //显示默认的错误页
        promise = promise.catch(function(err){
            http.setHeader('Content-Type', 'text/html; charset=' + C('encoding'));
            var readStream = fs.createReadStream(C('error_tpl_path'));
            readStream.pipe(http.res);
            readStream.on("end", function(){
                http.res.end();
            })
        })
    }
    return promise;
}<|endoftext|>


<commit_before>"use strict";

module.exports = function($scope, kauReportsData)
{
    var self = this;

    function loadData() {
        self.isLoading = true;
        self.grid.data = null;
        self.table.data = null;

            kauReportsData.getReportData('plays', self.filters.date).then(function (result) {
                self.grid.data = [{key: '', values: result.data}];
                self.table.data = result.data;
                self.errorMessage = '';
                self.isLoading = false;
            }, function (reason) {
                self.errorMessage = "Failed to load data : '" + reason.errorMessage + "'";
                self.isLoading = false;
            });
    }

    self.loadData = loadData;
    self.errorMessage = "";
    self.isLoading = false;

    self.filters = { date : { startDate: moment().subtract(3, 'month').startOf('month'), endDate: moment().subtract(1, 'month').endOf('month')}};
    self.dateOptions = {
        ranges: {
            'This Month': [moment().startOf('month'), moment().endOf('month')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
            'Last 3 Months': [moment().subtract(3, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        }
    };

    self.table = {
        data : null
    }
    self.grid = {
        config : {
        },
        data: null,
        api: {}, /* this object will be modified by nvd3 directive to have invokation functions */
        options: {
            chart: {
                type: 'discreteBarChart',
                height: 300,
                noData : '',
                margin: {
                    top: 20,
                    right: 20,
                    bottom: 50,
                    left: 110
                },
                color : ['#00a1d5'],
                staggerLabels: true,
                rotateLabels: true,
                x: function (d) {
                    return moment(d['month_id'],'YYYYMM').format('MMMM, YYYY');
                },
                y: function (d) {
                    return parseFloat(d['total_plays']);
                },
                showValues: true,
                valueFormat: function (d) {
                    return d3.format(',')(d);
                },
                duration: 500,
                xAxis: {
                },
                yAxis: {
                    axisLabel: 'Plays (CPM)',
                    tickFormat: function (d) {
                        return d3.format(',')(d);
                    },
                    axisLabelDistance: -10,
                    showMaxMin: true
                }
            }
        }
    };

    $scope.$watch('vm.filters.date',function()
    {
        loadData();
    });

    loadData();
};
<commit_msg>account usage graph y axis label margin<commit_after>"use strict";

module.exports = function($scope, kauReportsData)
{
    var self = this;

    function loadData() {
        self.isLoading = true;
        self.grid.data = null;
        self.table.data = null;

            kauReportsData.getReportData('plays', self.filters.date).then(function (result) {
                self.grid.data = [{key: '', values: result.data}];
                self.table.data = result.data;
                self.errorMessage = '';
                self.isLoading = false;
            }, function (reason) {
                self.errorMessage = "Failed to load data : '" + reason.errorMessage + "'";
                self.isLoading = false;
            });
    }

    self.loadData = loadData;
    self.errorMessage = "";
    self.isLoading = false;

    self.filters = { date : { startDate: moment().subtract(3, 'month').startOf('month'), endDate: moment().subtract(1, 'month').endOf('month')}};
    self.dateOptions = {
        ranges: {
            'This Month': [moment().startOf('month'), moment().endOf('month')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
            'Last 3 Months': [moment().subtract(3, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        }
    };

    self.table = {
        data : null
    }
    self.grid = {
        config : {
        },
        data: null,
        api: {}, /* this object will be modified by nvd3 directive to have invokation functions */
        options: {
            chart: {
                type: 'discreteBarChart',
                height: 300,
                noData : '',
                margin: {
                    top: 20,
                    right: 20,
                    bottom: 50,
                    left: 130
                },
                color : ['#00a1d5'],
                staggerLabels: true,
                rotateLabels: true,
                x: function (d) {
                    return moment(d['month_id'],'YYYYMM').format('MMMM, YYYY');
                },
                y: function (d) {
                    return parseFloat(d['total_plays']);
                },
                showValues: true,
                valueFormat: function (d) {
                    return d3.format(',')(d);
                },
                duration: 500,
                xAxis: {
                },
                yAxis: {
                    axisLabel: 'Plays (CPM)',
                    tickFormat: function (d) {
                        return d3.format(',')(d);
                    },
                    axisLabelDistance: 0,
                    showMaxMin: true
                }
            }
        }
    };

    $scope.$watch('vm.filters.date',function()
    {
        loadData();
    });

    loadData();
};
<|endoftext|>


<commit_before>VMX.config.useMagicCanvas = true;
VMX.callback = function(detections){
  if (! ( mc = VMX.getMagicCanvas() ) ){
    return; //canvas not open
  };
  var modelName = detections[0].cls;

  var mcc = mc.getContext('2d');

  for(var x in detections){
    if(detections[x].score > MIN_CONFIDENCE){
      VMX.storage.ledger[modelName] = (x+1);
    } else {
      break;
    }
  }

  console.log(VMX.storage.ledger);
}

<commit_msg>adding min_confidence<commit_after>var MIN_CONFIDENCE = .5;
VMX.config.useMagicCanvas = true;
VMX.callback = function(detections){
  if (! ( mc = VMX.getMagicCanvas() ) ){
    return; //canvas not open
  };
  var modelName = detections[0].cls;

  var mcc = mc.getContext('2d');

  for(var x in detections){
    if(detections[x].score > MIN_CONFIDENCE){
      VMX.storage.ledger[modelName] = (x+1);
    } else {
      break;
    }
  }

  console.log(VMX.storage.ledger);
}

<|endoftext|>


<commit_before>// ==UserScript==
// @name         OPR China Map Helper
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Add some buttons for China map in OPR
// @author       Ethern Triomphe346 记忆的残骸
// @match        https://opr.ingress.com/recon
// @grant        none
// ==/UserScript==
(function () {
    //constants
    var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
    var PI = 3.1415926535897932384626;
    var a = 6378245.0;
    var ee = 0.00669342162296594323;

    //global var
    var name;
    var postion;

    function transform_lat(lng, lat) {
        var lat = +lat;
        var lng = +lng;
        var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    function transform_lng(lng, lat) {
        var lat = +lat;
        var lng = +lng;
        var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
    }

    function out_of_china(lng, lat) {
        var lat = +lat;
        var lng = +lng;
        // 纬度3.86~53.55,经度73.66~135.05
        return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
    }

    /**
     * WGS84转GCj02
     * @param lng
     * @param lat
     * @returns {*[]}
     */
    function wgs84togcj02(lng, lat) {
        var lat = +lat;
        var lng = +lng;
        if (out_of_china(lng, lat)) {
            return [lng, lat];
        } else {
            var dlat = transform_lat(lng - 105.0, lat - 35.0);
            var dlng = transform_lng(lng - 105.0, lat - 35.0);
            var radlat = lat / 180.0 * PI;
            var magic = Math.sin(radlat);
            magic = 1 - ee * magic * magic;
            var sqrtmagic = Math.sqrt(magic);
            dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
            dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
            var mglat = lat + dlat;
            var mglng = lng + dlng;
            return [mglng, mglat];
        }
    }

    /**
     * 火星坐标系 (GCJ-02) 到百度坐标系 (BD-09) 的转换
     * @param lng
     * @param lat
     * @returns {*[]}
     */
    function gcj02tobd09(lng, lat) {
        var lat = +lat;
        var lng = +lng;
        var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
        var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
        var bd_lng = z * Math.cos(theta) + 0.0065;
        var bd_lat = z * Math.sin(theta) + 0.006;
        return [bd_lng, bd_lat];
    }

    function get_portal_info() {
        var name = target.getElementsByTagName('a')[0].innerHTML;
        var position = target.getElementsByTagName('a')[1].getAttribute("href");
        name = /^\s*(.*)\s*$/.exec(name)[1];
        position = /@(.*)$/.exec(position)[1];
        return [name, position];
    }

    function goto_tencent_map() {
        var portal_info = get_portal_info();
        var name = portal_info[0];
        var position = portal_info[1];
        var wgs_lat = position.split(",")[0];
        var wgs_lng = position.split(",")[1];
        var gcj = wgs84togcj02(wgs_lng, wgs_lat);
        var href = "http://map.qq.com/?type=marker&isopeninfowin=1&markertype=1&name=" + name + "&addr=" + position + "&pointy=" + gcj[1] + "&pointx=" + gcj[0];
        window.open(href, "_blank");
    }

    function goto_baidu_map() {
        var portal_info = get_portal_info();
        var name = portal_info[0];
        var position = portal_info[1];
        var wgs_lat = position.split(",")[0];
        var wgs_lng = position.split(",")[1];
        var href = "http://api.map.baidu.com/marker?location=" + wgs_lat + "," + wgs_lng + "&title=" + name + "&content=Application&output=html&coord_type=wgs84";
        window.open(href, "_blank");
    }

    function goto_OSM() {
        var portal_info = get_portal_info();
        // var name = portal_info[0];
        var position = portal_info[1];
        var wgs_lat = position.split(",")[0];
        var wgs_lng = position.split(",")[1];
        var href = "http://www.openstreetmap.org/search?query=" + wgs_lat + "," + wgs_lng + "#map=16/" + wgs_lat + "/" + wgs_lng;
        window.open(href, "_blank");
    }

    var target = document.getElementById("descriptionDiv");
    target.appendChild(document.createElement("br"));
    target.appendChild(document.createElement("br"));

    //Tencent Map Button
    var tencent_map_button = document.createElement("button");
    var textnode = document.createTextNode("Tencent Map");
    tencent_map_button.className += "button";
    tencent_map_button.onclick = goto_tencent_map;
    tencent_map_button.appendChild(textnode);
    target.appendChild(tencent_map_button);

    //Baidu Map Button
    var baidu_map_button = document.createElement("button");
    var textnode = document.createTextNode("Baidu Map");
    baidu_map_button.className += "button";
    baidu_map_button.onclick = goto_baidu_map;
    baidu_map_button.appendChild(textnode);
    target.appendChild(baidu_map_button);

    //OSM Button
    var OSM_button = document.createElement("button");
    var textnode = document.createTextNode("OSM");
    OSM_button.className += "button";
    OSM_button.onclick = goto_OSM;
    OSM_button.appendChild(textnode);
    target.appendChild(OSM_button);
})();<commit_msg>Delete OPR_China_Map_Helper.js<commit_after><|endoftext|>


<commit_before>/*
Up : 38
Down : 40
Right : 39
Left : 37
Enter : 13
SpaceBar : 32
Shift : 16
*/

var walking;
walking = false;

$(document).keydown(function(e) {
	//var element = $(".joshua");
	if(e.keyCode == 32) {
		//alert("hi");
		$(".joshua").css("width", "80px");
		$(".joshua").css("background-image", "url(../image/joshua-sprite-walk.png");
		walking = true;
	} else {
		walking = false;
	}
});

if (!walking) {
	$(".joshua").css("width", "88px");
}
<commit_msg>Update joshuaSprite.js<commit_after>/*
Up : 38
Down : 40
Right : 39
Left : 37
Enter : 13
SpaceBar : 32
Shift : 16
*/

var walking;

$(document).keydown(function(e) {
	//var element = $(".joshua");
	if(e.keyCode == 32) {
		//alert("hi");
		$(".joshua").css("width", "80px");
		$(".joshua").css("background-image", "url(../image/joshua-sprite-walk.png");
	}
});

$(document).keyup(function(e) {
	if(e.keyCode == 32) {
		$(".joshua").css("width", "88px");
	}
});
<|endoftext|>


<commit_before>/* global document, window UMS_CONFIG */
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, hashHistory } from 'react-router';
import {
    Publications,
    Core,
    UMS,
    Provider as CoreProvider
} from 'oicr-ui-core';
import UserDashboard from '../site/modules/UserDashboard';

// Load store.
const store = require('../site/store').default;

if (window.UMS_CONFIG) UMS.setConfig(window.UMS_CONFIG);

// Get User Session, Invoke once
UMS.getUserInfo()(store.dispatch);

// Render UMS
const target = document.getElementById('app-user-services');
if (target) {
    ReactDOM.render(
        <CoreProvider store={store}>
            <Router history={hashHistory}>
                <UMS.Route path="/dashboard" component={UserDashboard} />
                <UMS.BaseRoutes />
            </Router>
        </CoreProvider>,
        target
    );
}

// Render User Menu
const targetUserMenu = document.getElementById('app-user-nav');
if (targetUserMenu) {
    ReactDOM.render(
        <CoreProvider store={store}>
            <UMS.Components.UserNavMenu rootPath="/user" />
        </CoreProvider>,
        targetUserMenu
    );
}

/**
 * Render view/edit tab for admin user.
 * This will be rendered after pubmed publications are rendered.
 */
const config = Core.getConfig();
if (config.CMUI_ENABLED) {
    const targetEditable = document.getElementById('editButton');
    if (targetEditable) {
        ReactDOM.render(
            <Core.Provider store={store}>
                <Core.Components.ContentPageWrapper
                    viewDOM={targetEditable.innerHTML}
                    rootPath={'/user/#/dashboard'}
                    eventKey={3}
                    path={targetEditable.getAttribute('data-path')}
                    isPublic={targetEditable.getAttribute('data-is-public')}
                />
            </Core.Provider>,
            targetEditable
        );
    }
}
<commit_msg>Update _ums.js<commit_after>/* global document, window UMS_CONFIG */
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, hashHistory } from 'react-router';
import {
    Publications,
    Core,
    UMS,
    Provider as CoreProvider
} from 'oicr-ui-core';
import UserDashboard from '../site/modules/UserDashboard';

// What happens

// Load store.
const store = require('../site/store').default;

if (window.UMS_CONFIG) UMS.setConfig(window.UMS_CONFIG);

// Get User Session, Invoke once
UMS.getUserInfo()(store.dispatch);

// Render UMS
const target = document.getElementById('app-user-services');
if (target) {
    ReactDOM.render(
        <CoreProvider store={store}>
            <Router history={hashHistory}>
                <UMS.Route path="/dashboard" component={UserDashboard} />
                <UMS.BaseRoutes />
            </Router>
        </CoreProvider>,
        target
    );
}

// Render User Menu
const targetUserMenu = document.getElementById('app-user-nav');
if (targetUserMenu) {
    ReactDOM.render(
        <CoreProvider store={store}>
            <UMS.Components.UserNavMenu rootPath="/user" />
        </CoreProvider>,
        targetUserMenu
    );
}

/**
 * Render view/edit tab for admin user.
 * This will be rendered after pubmed publications are rendered.
 */
const config = Core.getConfig();
if (config.CMUI_ENABLED) {
    const targetEditable = document.getElementById('editButton');
    if (targetEditable) {
        ReactDOM.render(
            <Core.Provider store={store}>
                <Core.Components.ContentPageWrapper
                    viewDOM={targetEditable.innerHTML}
                    rootPath={'/user/#/dashboard'}
                    eventKey={3}
                    path={targetEditable.getAttribute('data-path')}
                    isPublic={targetEditable.getAttribute('data-is-public')}
                />
            </Core.Provider>,
            targetEditable
        );
    }
}
<|endoftext|>


<commit_before>/*

*/
"use strict";

(function (jQuery) {
   var SourceArray = ["Lombardia", "Abruzzo", "Toscana", "Liguria"];
   var SourceAjaxArray = new Array();

   var delimeters = new Array();
   var backspace = new Array();
   var inputObj = null;
   var tagList = new Array();
   var tagLiID = new Array();
   var lastTagId = 0;
   var hiddenTagList = null;

   var tagManagerOptions = null;

   var queuedTag = "";

   if (typeof console === "undefined" || typeof console.log === "undefined") {
      console = {};
      console.log = function () { };
   }

   inputObj = this;

   jQuery.fn.trimTag = function (tag) {
      var txt = jQuery.trim(tag);

      var l = txt.length;
      var t = 0;

      //          console.log(
      //                "tag to trim : " + txt
      //              );
      //remove from end
      for (var i = l - 1; i >= 0; i--) {
         //            console.log(
         //                "char to evaluate : " + txt[i] + " (" + txt.charCodeAt(i) + ")"
         //              );
         if (-1 != jQuery.inArray(txt.charCodeAt(i), delimeters)) {
            //              console.log(
            //                "char to remove from end: " + txt[i]
            //              );
            t++;
         } else
            break;
      }
      txt = txt.substring(0, l - t);
      l = txt.length;
      t = 0;
      //remove from head
      for (var i = 0; i < l; i++) {
         //            console.log(
         //                "char to evaluate : " + txt[i] + " (" + txt.charCodeAt(i) + ")"
         //              );
         if (-1 != jQuery.inArray(txt.charCodeAt(i), delimeters)) {
            //              console.log(
            //                "char to remove from head: " + txt[i]
            //              );
            t++;
         } else
            break;
      }

      txt = txt.substring(t, l);
      //          console.log(
      //                "trimmed to : " + txt
      //              );

      return txt;
   };

   jQuery.fn.setupTypeahead = function (tag) {
      var obj = jQuery(this);

      if(!obj.typeahead)
         return;

      if (tagManagerOptions.typeaheadSource != null) {
         obj.typeahead();
         obj.data('active', true);
         obj.data('typeahead').source = tagManagerOptions.typeaheadSource;
         obj.data('active', false);
      } else if (tagManagerOptions.typeaheadAjaxSource != null) {
         obj.typeahead();
         jQuery.getJSON(tagManagerOptions.typeaheadAjaxSource, function (data) {
            if (data != undefined && data.tags != undefined) {
               SourceAjaxArray.length = 0;
               jQuery.each(data.tags, function (key, val) {
                  var a = 1;
                  //jQuery('#addexpenses select[name="who"]').append('<option value="' + val.who + '">' + val.name + '</option>');
                  SourceAjaxArray.push(val.tag);
                  //obj.attr("data-sources", SourceArray);
                  obj.data('active', true);
                  obj.data('typeahead').source = SourceAjaxArray;
                  obj.data('active', false);
                  //obj.attr("data-sources", SourceAjaxArray.join(", "));
               });
            }
         });
      }
   };

   jQuery.fn.refreshHiddenTagList = function (robj) {
      var obj;
      if (robj == null)
         obj = jQuery(this);
      else
         obj = robj;

      var tlis = obj.data("tlis");
      var lhiddenTagList = obj.data("lhiddenTagList");

      if(lhiddenTagList == undefined)
         return;

      jQuery(lhiddenTagList).val(tlis.join(",")).change();
   };

   jQuery.fn.spliceTag = function (TagId,robj) {
      var obj;
      if (robj == null)
         return;
      else
         obj = robj;
      var tlis = obj.data("tlis");
      var tlid = obj.data("tlid");

      console.log(
              "TagIdToRemove: " + TagId
            );
      var p = jQuery.inArray(TagId, tlid)
      console.log(
              "position: " + p
            );
      if (-1 != p) {
         jQuery("#myTag_" + TagId).remove();
         tlis.splice(p, 1);
         tlid.splice(p, 1);
         obj.refreshHiddenTagList(obj);
         console.log(tlis);
      }

      if ( tagManagerOptions.maxTags > 0 && tlis.length < tagManagerOptions.maxTags ) {
         obj.show();
      }
   };

   jQuery.fn.popTag = function (robj) {
      var obj;
      if (robj == null)
         obj = jQuery(this);
      else
         obj = robj;

      var tlis = obj.data("tlis");
      var tlid = obj.data("tlid");

      if (tlid.length > 0) {
         var TagId = tlid.pop();
         tlis.pop();
         console.log(
              "TagIdToRemove: " + TagId
            );
         jQuery("#myTag_" + TagId).remove();
         jQuery(obj).refreshHiddenTagList();
         console.log(tlis);
      }
   };

   jQuery.fn.pushTag = function (tag, robj) {
      if (!tag || tag.length <= 0) {
         return;
      }
      if (tagManagerOptions.CapitalizeFirstLetter && tag.length > 1) {
         tag = tag.charAt(0).toUpperCase() + tag.slice(1).toLowerCase();
      }

      // call the validator (if any) and do not let the tag pass if invalid
      if (tagManagerOptions.validator !== undefined) {
        if ( tagManagerOptions.validator(tag) !== true ) return;
      }

      var obj;
      if (robj == null)
         obj = jQuery(this);
      else
         obj = robj;

      var tlis = obj.data("tlis");
      var tlid = obj.data("tlid");

      // dont accept new tags beyond the defined maximum
      if ( tagManagerOptions.maxTags > 0 && tlis.length >= tagManagerOptions.maxTags ) return;

      var alreadyInList = false;
      var p = jQuery.inArray(tag, tlis);
      if (-1 != p) {
         console.log(
                "tag:" + tag + " !!already in list!!"
              );
         alreadyInList = true;
      }

      if (alreadyInList) {
         var pTagId = tlid[p];
         jQuery("#myTag_" + pTagId).stop().animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100);
      } else {
         var TagId = lastTagId++;
         tlis.push(tag);
         tlid.push(TagId);

         var html = '';
         html += '' + tag + '  x';
         console.log(
              "tagList: " + tlis
            );
         obj.before(html);
         jQuery("#myRemover_" + TagId).on("click", obj, function (e) {
			e.preventDefault();
            var TagIdToRemove = parseInt(jQuery(this).attr("TagIdToRemove"));

            e.data.spliceTag(TagIdToRemove,e.data);
//            var TagIdToRemove = parseInt(jQuery(this).attr("TagIdToRemove"));
//            jQuery(this).spliceTag(parseInt(jQuery(this).attr("TagIdToRemove")));
         });

         obj.refreshHiddenTagList(obj);

         if ( tagManagerOptions.maxTags > 0 && tlis.length >= tagManagerOptions.maxTags ) {
            obj.hide();
         }

      }
      obj.val("");

   };

   jQuery.fn.tagsManager = function (options) {
      tagManagerOptions = {
         prefilled: null,
         CapitalizeFirstLetter: true,
         preventSubmitOnEnter: true,
         typeahead: false,
         typeaheadAjaxSource: null,
         typeaheadSource: null,
         delimeters: [44, 188, 13],
         backspace: [8],
         maxTags: 0,
         hiddenTagListName: 'hiddenTagList'
      };
      jQuery.extend(tagManagerOptions, options);

      return this.each(function() {
         var obj = jQuery(this);

         //let's store some instance specific data directly into the DOM object
         var tlis = new Array();
         var tlid = new Array();
         obj.data("tlis", tlis); //list of string tags
         obj.data("tlid", tlid); //list of ID of the string tags

         var html = "";
         html += "<input name='" + tagManagerOptions.hiddenTagListName + "' type='hidden' value=''/>";
         obj.after(html);
         obj.data("lhiddenTagList",
            obj.siblings("input[name='" + tagManagerOptions.hiddenTagListName + "']")[0]
         );

         delimeters = tagManagerOptions.delimeters;
         backspace = tagManagerOptions.backspace;

         if (lastTagId > 0) {
            while (lastTagId > 0) {
               obj.popTag(obj);
               lastTagId--;
            }
         }

         if (tagManagerOptions.typeahead) {
            obj.setupTypeahead();
            //obj.typeahead({ source: SourceArray })
         }

         // disable submit on enter for this input field
         obj.on("focus", function (e) {
            if (jQuery(this).popover) {
               jQuery(this).popover("hide");
               //jQuery(this).popover = null;
            }
         });

         obj.on("keypress", function (e) {
            if (jQuery(this).popover) {
               jQuery(this).popover("hide");
               //jQuery(this).popover = null;
            }
            if (tagManagerOptions.preventSubmitOnEnter) {
               if (e.which == 13) {
                  e.cancelBubble = true;
                  e.returnValue = false;
                  e.stopPropagation();
                  e.preventDefault();
                  //e.keyCode = 9;
               }
            }
            console.log(
                     "keyup: " + e.keyCode
                   );
         });

         obj.on("keyup", obj, function (e) {
            if(e.which == 9){
               var ao = jQuery(".typeahead:visible");
               if (ao[0] != undefined) {
                  console.log('pressed tab with typeaheadIsVisible is visible');
               } else {
                  console.log('pressed tab with typeaheadIsVisible is NOT visible');
               }
            }
            var p = jQuery.inArray(e.which, delimeters);
            if (-1 != p) {
               //user just entered a valid delimeter
               var user_input = jQuery(this).val(); //user_input = jQuery().inArray(delimeters[p]);
               user_input = jQuery(this).trimTag(user_input);
               e.data.pushTag(user_input,e.data);
               console.log(
                        "pushTag: keyup "
                      );
            }
   //         console.log(
   //                  "keyup: " + e.which
   //                );
         });

         obj.on("keydown", obj, function (e) {
            var p = jQuery.inArray(e.which, backspace);
            if (-1 != p) {
               //user just entered backspace or equivalent
               var user_input = jQuery(this).val(); //user_input = jQuery().inArray(delimeters[p]);
               var i = user_input.length;
               if (i <= 0) {
                  console.log(
                     "backspace detected"
                   );
                  e.data.popTag();
               }
            }
         });

         obj.change(function (e) {
            e.cancelBubble = true;
            e.returnValue = false;
            e.stopPropagation();
            e.preventDefault();

            var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
            var is_explorer = navigator.userAgent.indexOf('MSIE') > -1;
            var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
            var is_safari = navigator.userAgent.indexOf("Safari") > -1;

            if(!is_chrome && !is_safari )
               jQuery(this).focus();

            console.log('Handler for .change() called, value selected:' + obj.val());
            var ao = jQuery(".typeahead:visible");
            if (ao[0] != undefined){
               console.log('change: typeaheadIsVisible is visible');
               //when the user click with the mouse on the typeahead li element we get the change event fired twice, once when the input field loose focus and later with the input field value is replaced with li value
               var user_input = jQuery(".typeahead .active").attr("data-value");
               user_input = jQuery(this).trimTag(user_input);
               if( queuedTag == obj.val() && queuedTag == user_input ){
                  queuedTag = "";
                  obj.val(queuedTag);
               }else{
                  jQuery(this).pushTag(user_input);
                  queuedTag = user_input;
                  console.log('Handler for .change() called, typeahead value pushed:' + queuedTag);
               }
            } else {
               console.log('change: typeaheadIsVisible is NOT visible');
               var user_input = jQuery(this).val(); //user_input = jQuery().inArray(delimeters[p]);
               user_input = jQuery(this).trimTag(user_input);
               jQuery(this).pushTag(user_input);
               console.log(
                        "pushTag: change "
                      );
            }

         });

         if (1 == 1 || !tagManagerOptions.typeahead) {
            obj.on("blur", function (e) {
               //lost focus
               e.cancelBubble = true;
               e.returnValue = false;
               e.stopPropagation();
               e.preventDefault();

               var push = true;
               if (tagManagerOptions.typeahead) {
                  var ao = jQuery(".typeahead:visible");
                  if (ao[0] != undefined) {
                     console.log('blur: typeaheadIsVisible is visible');
                     push = false;
                  } else {
                     console.log('blur: typeaheadIsVisible is NOT visible');
                     push = true;
                  }
               }

               if (push) {
                  console.log('lost focus');
                  var user_input = jQuery(this).val(); //user_input = jQuery().inArray(delimeters[p]);
                  user_input = jQuery(this).trimTag(user_input);
                  jQuery(this).pushTag(user_input);
                  console.log(
                           "pushTag: blur"
                         );
               }
            });
         }

         if (tagManagerOptions.prefilled != null) {
            if (typeof (tagManagerOptions.prefilled) == "object") {
               var pta = tagManagerOptions.prefilled;
               jQuery.each(pta, function (key, val) {
                  var a = 1;
                  obj.pushTag(val, obj);
               });
            } else if (typeof (tagManagerOptions.prefilled) == "string") {
               var pta = tagManagerOptions.prefilled.split(',');

               jQuery.each(pta, function (key, val) {
                  var a = 1;
                  obj.pushTag(val, obj);
               });

            }
         }
      });

   }
})(jQuery);
<commit_msg>added preventDefault when tag is removed<commit_after>/*

*/
"use strict";

(function (jQuery) {
   var SourceArray = ["Lombardia", "Abruzzo", "Toscana", "Liguria"];
   var SourceAjaxArray = new Array();

   var delimeters = new Array();
   var backspace = new Array();
   var inputObj = null;
   var tagList = new Array();
   var tagLiID = new Array();
   var lastTagId = 0;
   var hiddenTagList = null;

   var tagManagerOptions = null;

   var queuedTag = "";

   if (typeof console === "undefined" || typeof console.log === "undefined") {
      console = {};
      console.log = function () { };
   }

   inputObj = this;

   jQuery.fn.trimTag = function (tag) {
      var txt = jQuery.trim(tag);

      var l = txt.length;
      var t = 0;

      //          console.log(
      //                "tag to trim : " + txt
      //              );
      //remove from end
      for (var i = l - 1; i >= 0; i--) {
         //            console.log(
         //                "char to evaluate : " + txt[i] + " (" + txt.charCodeAt(i) + ")"
         //              );
         if (-1 != jQuery.inArray(txt.charCodeAt(i), delimeters)) {
            //              console.log(
            //                "char to remove from end: " + txt[i]
            //              );
            t++;
         } else
            break;
      }
      txt = txt.substring(0, l - t);
      l = txt.length;
      t = 0;
      //remove from head
      for (var i = 0; i < l; i++) {
         //            console.log(
         //                "char to evaluate : " + txt[i] + " (" + txt.charCodeAt(i) + ")"
         //              );
         if (-1 != jQuery.inArray(txt.charCodeAt(i), delimeters)) {
            //              console.log(
            //                "char to remove from head: " + txt[i]
            //              );
            t++;
         } else
            break;
      }

      txt = txt.substring(t, l);
      //          console.log(
      //                "trimmed to : " + txt
      //              );

      return txt;
   };

   jQuery.fn.setupTypeahead = function (tag) {
      var obj = jQuery(this);

      if(!obj.typeahead)
         return;

      if (tagManagerOptions.typeaheadSource != null) {
         obj.typeahead();
         obj.data('active', true);
         obj.data('typeahead').source = tagManagerOptions.typeaheadSource;
         obj.data('active', false);
      } else if (tagManagerOptions.typeaheadAjaxSource != null) {
         obj.typeahead();
         jQuery.getJSON(tagManagerOptions.typeaheadAjaxSource, function (data) {
            if (data != undefined && data.tags != undefined) {
               SourceAjaxArray.length = 0;
               jQuery.each(data.tags, function (key, val) {
                  var a = 1;
                  //jQuery('#addexpenses select[name="who"]').append('<option value="' + val.who + '">' + val.name + '</option>');
                  SourceAjaxArray.push(val.tag);
                  //obj.attr("data-sources", SourceArray);
                  obj.data('active', true);
                  obj.data('typeahead').source = SourceAjaxArray;
                  obj.data('active', false);
                  //obj.attr("data-sources", SourceAjaxArray.join(", "));
               });
            }
         });
      }
   };

   jQuery.fn.refreshHiddenTagList = function (robj) {
      var obj;
      if (robj == null)
         obj = jQuery(this);
      else
         obj = robj;

      var tlis = obj.data("tlis");
      var lhiddenTagList = obj.data("lhiddenTagList");

      if(lhiddenTagList == undefined)
         return;

      jQuery(lhiddenTagList).val(tlis.join(",")).change();
   };

   jQuery.fn.spliceTag = function (TagId,robj) {
      var obj;
      if (robj == null)
         return;
      else
         obj = robj;
      var tlis = obj.data("tlis");
      var tlid = obj.data("tlid");

      console.log(
              "TagIdToRemove: " + TagId
            );
      var p = jQuery.inArray(TagId, tlid)
      console.log(
              "position: " + p
            );
      if (-1 != p) {
         jQuery("#myTag_" + TagId).remove();
         tlis.splice(p, 1);
         tlid.splice(p, 1);
         obj.refreshHiddenTagList(obj);
         console.log(tlis);
      }

      if ( tagManagerOptions.maxTags > 0 && tlis.length < tagManagerOptions.maxTags ) {
         obj.show();
      }
   };

   jQuery.fn.popTag = function (robj) {
      var obj;
      if (robj == null)
         obj = jQuery(this);
      else
         obj = robj;

      var tlis = obj.data("tlis");
      var tlid = obj.data("tlid");

      if (tlid.length > 0) {
         var TagId = tlid.pop();
         tlis.pop();
         console.log(
              "TagIdToRemove: " + TagId
            );
         jQuery("#myTag_" + TagId).remove();
         jQuery(obj).refreshHiddenTagList();
         console.log(tlis);
      }
   };

   jQuery.fn.pushTag = function (tag, robj) {
      if (!tag || tag.length <= 0) {
         return;
      }
      if (tagManagerOptions.CapitalizeFirstLetter && tag.length > 1) {
         tag = tag.charAt(0).toUpperCase() + tag.slice(1).toLowerCase();
      }

      // call the validator (if any) and do not let the tag pass if invalid
      if (tagManagerOptions.validator !== undefined) {
        if ( tagManagerOptions.validator(tag) !== true ) return;
      }

      var obj;
      if (robj == null)
         obj = jQuery(this);
      else
         obj = robj;

      var tlis = obj.data("tlis");
      var tlid = obj.data("tlid");

      // dont accept new tags beyond the defined maximum
      if ( tagManagerOptions.maxTags > 0 && tlis.length >= tagManagerOptions.maxTags ) return;

      var alreadyInList = false;
      var p = jQuery.inArray(tag, tlis);
      if (-1 != p) {
         console.log(
                "tag:" + tag + " !!already in list!!"
              );
         alreadyInList = true;
      }

      if (alreadyInList) {
         var pTagId = tlid[p];
         jQuery("#myTag_" + pTagId).stop().animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100).animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100);
      } else {
         var TagId = lastTagId++;
         tlis.push(tag);
         tlid.push(TagId);

         var html = '';
         html += '' + tag + '  x';
         console.log(
              "tagList: " + tlis
            );
         obj.before(html);
         jQuery("#myRemover_" + TagId).on("click", obj, function (e) {
			      e.preventDefault();
            var TagIdToRemove = parseInt(jQuery(this).attr("TagIdToRemove"));

            e.data.spliceTag(TagIdToRemove,e.data);
//            var TagIdToRemove = parseInt(jQuery(this).attr("TagIdToRemove"));
//            jQuery(this).spliceTag(parseInt(jQuery(this).attr("TagIdToRemove")));
         });

         obj.refreshHiddenTagList(obj);

         if ( tagManagerOptions.maxTags > 0 && tlis.length >= tagManagerOptions.maxTags ) {
            obj.hide();
         }

      }
      obj.val("");

   };

   jQuery.fn.tagsManager = function (options) {
      tagManagerOptions = {
         prefilled: null,
         CapitalizeFirstLetter: true,
         preventSubmitOnEnter: true,
         typeahead: false,
         typeaheadAjaxSource: null,
         typeaheadSource: null,
         delimeters: [44, 188, 13],
         backspace: [8],
         maxTags: 0,
         hiddenTagListName: 'hiddenTagList'
      };
      jQuery.extend(tagManagerOptions, options);

      return this.each(function() {
         var obj = jQuery(this);

         //let's store some instance specific data directly into the DOM object
         var tlis = new Array();
         var tlid = new Array();
         obj.data("tlis", tlis); //list of string tags
         obj.data("tlid", tlid); //list of ID of the string tags

         var html = "";
         html += "<input name='" + tagManagerOptions.hiddenTagListName + "' type='hidden' value=''/>";
         obj.after(html);
         obj.data("lhiddenTagList",
            obj.siblings("input[name='" + tagManagerOptions.hiddenTagListName + "']")[0]
         );

         delimeters = tagManagerOptions.delimeters;
         backspace = tagManagerOptions.backspace;

         if (lastTagId > 0) {
            while (lastTagId > 0) {
               obj.popTag(obj);
               lastTagId--;
            }
         }

         if (tagManagerOptions.typeahead) {
            obj.setupTypeahead();
            //obj.typeahead({ source: SourceArray })
         }

         // disable submit on enter for this input field
         obj.on("focus", function (e) {
            if (jQuery(this).popover) {
               jQuery(this).popover("hide");
               //jQuery(this).popover = null;
            }
         });

         obj.on("keypress", function (e) {
            if (jQuery(this).popover) {
               jQuery(this).popover("hide");
               //jQuery(this).popover = null;
            }
            if (tagManagerOptions.preventSubmitOnEnter) {
               if (e.which == 13) {
                  e.cancelBubble = true;
                  e.returnValue = false;
                  e.stopPropagation();
                  e.preventDefault();
                  //e.keyCode = 9;
               }
            }
            console.log(
                     "keyup: " + e.keyCode
                   );
         });

         obj.on("keyup", obj, function (e) {
            if(e.which == 9){
               var ao = jQuery(".typeahead:visible");
               if (ao[0] != undefined) {
                  console.log('pressed tab with typeaheadIsVisible is visible');
               } else {
                  console.log('pressed tab with typeaheadIsVisible is NOT visible');
               }
            }
            var p = jQuery.inArray(e.which, delimeters);
            if (-1 != p) {
               //user just entered a valid delimeter
               var user_input = jQuery(this).val(); //user_input = jQuery().inArray(delimeters[p]);
               user_input = jQuery(this).trimTag(user_input);
               e.data.pushTag(user_input,e.data);
               console.log(
                        "pushTag: keyup "
                      );
            }
   //         console.log(
   //                  "keyup: " + e.which
   //                );
         });

         obj.on("keydown", obj, function (e) {
            var p = jQuery.inArray(e.which, backspace);
            if (-1 != p) {
               //user just entered backspace or equivalent
               var user_input = jQuery(this).val(); //user_input = jQuery().inArray(delimeters[p]);
               var i = user_input.length;
               if (i <= 0) {
                  console.log(
                     "backspace detected"
                   );
                  e.data.popTag();
               }
            }
         });

         obj.change(function (e) {
            e.cancelBubble = true;
            e.returnValue = false;
            e.stopPropagation();
            e.preventDefault();

            var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
            var is_explorer = navigator.userAgent.indexOf('MSIE') > -1;
            var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
            var is_safari = navigator.userAgent.indexOf("Safari") > -1;

            if(!is_chrome && !is_safari )
               jQuery(this).focus();

            console.log('Handler for .change() called, value selected:' + obj.val());
            var ao = jQuery(".typeahead:visible");
            if (ao[0] != undefined){
               console.log('change: typeaheadIsVisible is visible');
               //when the user click with the mouse on the typeahead li element we get the change event fired twice, once when the input field loose focus and later with the input field value is replaced with li value
               var user_input = jQuery(".typeahead .active").attr("data-value");
               user_input = jQuery(this).trimTag(user_input);
               if( queuedTag == obj.val() && queuedTag == user_input ){
                  queuedTag = "";
                  obj.val(queuedTag);
               }else{
                  jQuery(this).pushTag(user_input);
                  queuedTag = user_input;
                  console.log('Handler for .change() called, typeahead value pushed:' + queuedTag);
               }
            } else {
               console.log('change: typeaheadIsVisible is NOT visible');
               var user_input = jQuery(this).val(); //user_input = jQuery().inArray(delimeters[p]);
               user_input = jQuery(this).trimTag(user_input);
               jQuery(this).pushTag(user_input);
               console.log(
                        "pushTag: change "
                      );
            }

         });

         if (1 == 1 || !tagManagerOptions.typeahead) {
            obj.on("blur", function (e) {
               //lost focus
               e.cancelBubble = true;
               e.returnValue = false;
               e.stopPropagation();
               e.preventDefault();

               var push = true;
               if (tagManagerOptions.typeahead) {
                  var ao = jQuery(".typeahead:visible");
                  if (ao[0] != undefined) {
                     console.log('blur: typeaheadIsVisible is visible');
                     push = false;
                  } else {
                     console.log('blur: typeaheadIsVisible is NOT visible');
                     push = true;
                  }
               }

               if (push) {
                  console.log('lost focus');
                  var user_input = jQuery(this).val(); //user_input = jQuery().inArray(delimeters[p]);
                  user_input = jQuery(this).trimTag(user_input);
                  jQuery(this).pushTag(user_input);
                  console.log(
                           "pushTag: blur"
                         );
               }
            });
         }

         if (tagManagerOptions.prefilled != null) {
            if (typeof (tagManagerOptions.prefilled) == "object") {
               var pta = tagManagerOptions.prefilled;
               jQuery.each(pta, function (key, val) {
                  var a = 1;
                  obj.pushTag(val, obj);
               });
            } else if (typeof (tagManagerOptions.prefilled) == "string") {
               var pta = tagManagerOptions.prefilled.split(',');

               jQuery.each(pta, function (key, val) {
                  var a = 1;
                  obj.pushTag(val, obj);
               });

            }
         }
      });

   }
})(jQuery);
<|endoftext|>


<commit_before>'use strict';

const MVA = require('@scola/mva');

class CheckboxView extends MVA.View.Abstract {
  constructor() {
    super();
    this.checked = false;
    this.customStyling = false;
  }

  build() {
    this
      .element('checkbox', 'span')
      .style({
        float: 'left',
        width: '1.5em',
        height: '1.5em',
        border: '0.3em solid #FFF',
        background: '#FFF',
        cursor: 'pointer',
        textAlign: 'center'
      })
      .listen({
        'click': this.handleClick,
        'check': this.handleCheck
      }, this);

    return this;
  }

  render() {
    return this.element('checkbox');
  }

  isChecked() {
    return this.checked;
  }

  check(checked) {
    this.checked = checked;

    this.element('checkbox').emit('check', {
      view: this,
      checked
    });

    return this;
  }

  handleClick() {
    this.check(!Boolean(this.checked));
  }

  handleCheck(event) {
    event.view
      .element('checkbox')
      .style({
        background: event.checked ? '#000' : '#FFF'
      });
  }
}

module.exports = CheckboxView;
<commit_msg>Make checkbox focusable<commit_after>'use strict';

const MVA = require('@scola/mva');

class CheckboxView extends MVA.View.Abstract {
  build() {
    this
      .element('checkbox', 'div')
      .style({
        float: 'left',
        width: '1.5em',
        height: '1.5em',
        border: '0.3em solid #FFF',
        background: '#FFF',
        cursor: 'pointer',
        textAlign: 'center',
        position: 'relative'
      })
      .listen({
        click: this.handleClick,
        check: this.handleCheck
      }, this);

    this
      .element('input', 'input')
      .properties({
        type: 'checkbox'
      })
      .style({
        left: 0,
        opacity: 0,
        position: 'absolute',
        top: 0
      })
      .listen({
        click: this.handleClick
      }, this);

    this
      .element('checkbox')
      .append(
        this.element('input')
      );

    return this;
  }

  render() {
    return this.element('checkbox');
  }

  handleClick() {
    const element = this.element('input').get();
    element.checked = !element.checked;

    this.element('checkbox').emit('check', {
      view: this,
      checked: element.checked
    });
  }

  handleCheck(event) {
    event
      .view
      .element('checkbox')
      .style({
        background: event.checked ? '#000' : '#FFF'
      });
  }
}

module.exports = CheckboxView;
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {
    var path = require('path'),
        lang = require('mercenary').lang,
        extend = lang.extend;

    grunt.task.registerMultiTask(
        'formidable',
        'Generate a static site with formidable',
        function() {
            var done = this.async(),
                options = this.options({
                    // The root of the project, from which other paths will be resolved.
                    // Defaults to './src' with respect to the grunt base directory
                    // (usually the same as the grunt file).
                    root: path.join('src'),
                    // The build directory into which the site's files will be generated.
                    // Defaults to '../build' with respect to the root.
                    build: null,
                    // The path to the top-level urls module with respect to the root and
                    // without the '.js' extension. Defaults to 'urls'.
                    urls: null,
                    // Template directory globbing patterns for findiing directories in
                    // addition to the standard '**/templates' pattern. Defaults to [].
                    templates: null,
                    // The template rendering engine to use. Defaults to 'swig'.
                    templating: null,
                    // Plugins for swig.
                    swig: {
                        filters: {},
                        tags: {},
                        extensions: {}
                    },
                    // Allow overwrite of existing rendered files. When false, an attempted
                    // overwrite will raise a fatal exception. Defaults to true.
                    overwrite: null
                });

            // Instantiate the formidable instance, invoke it and wait for the results.
            (require('formidable/settings')
            .load(
                // The simulated settings.js path.
                path.join(options.root, 'settings.js'),
                // The settings.
                extend({}, options, {
                    log: {
                        info: function(message) {
                            grunt.log.ok(message || '');
                        },
                        warn: function(message) {
                            grunt.log.error(message || '');
                        },
                        fail: function(message, code) {
                            grunt.fail.fatal(message, code);
                        }
                    },
                    verbose: grunt.option('verbose') || false
                }))()
            .then(function() {
                done(true);
            }));
        });
};
<commit_msg>Attempting a formidable initialization bugfix.<commit_after>'use strict';

module.exports = function(grunt) {
    var path = require('path'),
        lang = require('mercenary').lang,
        extend = lang.extend;

    grunt.task.registerMultiTask(
        'formidable',
        'Generate a static site with formidable',
        function() {
            var done = this.async(),
                options = this.options({
                    // The root of the project, from which other paths will be resolved.
                    // Defaults to './src' with respect to the grunt base directory
                    // (usually the same as the grunt file).
                    root: path.join('src'),
                    // The build directory into which the site's files will be generated.
                    // Defaults to '../build' with respect to the root.
                    build: null,
                    // The path to the top-level urls module with respect to the root and
                    // without the '.js' extension. Defaults to 'urls'.
                    urls: null,
                    // Template directory globbing patterns for findiing directories in
                    // addition to the standard '**/templates' pattern. Defaults to [].
                    templates: null,
                    // The template rendering engine to use. Defaults to 'swig'.
                    templating: null,
                    // Plugins for swig.
                    swig: {
                        filters: {},
                        tags: {},
                        extensions: {}
                    },
                    // Allow overwrite of existing rendered files. When false, an attempted
                    // overwrite will raise a fatal exception. Defaults to true.
                    overwrite: null
                });

            // Instantiate the formidable instance, invoke it and wait for the results.
            (require('formidable/settings')
            // The simulated settings.js path.
            .configure(path.join(options.root, 'settings.js'))
            // The settings.
            .load(
                extend({}, options, {
                    log: {
                        info: function(message) {
                            grunt.log.ok(message || '');
                        },
                        warn: function(message) {
                            grunt.log.error(message || '');
                        },
                        fail: function(message, code) {
                            grunt.fail.fatal(message, code);
                        }
                    },
                    verbose: grunt.option('verbose') || false
                }))()
            .then(function() {
                done(true);
            }));
        });
};
<|endoftext|>