/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Bespin.
 *
 * The Initial Developer of the Original Code is
 * Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Bespin Team (bespin@mozilla.com)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */


var NATIVE_JSON = this.JSON ? true : false;
var __GLOBAL__  = this;

if (!__GLOBAL__.console) {
    __GLOBAL__.console = {
        log: function(msg) {
            postMessage("log="+msg);
        }
    };
}

// this is called in different spots depending on emulation of importScripts
var loadDone = function() {
    // theObject is the one generated by WorkerFacade
    if (theObject.initialize) {
        theObject.initialize();
    }
};

var internalMessageIdentifier = "__IMPORT_SCRIPT__";

var SCRIPT_COUNT = 0;
var LOADED_SCRIPTS = 0;
var EMULATE_LOAD   = false;

// Gears

// For Gears we need to create a fake postMessage function
if (typeof google != "undefined" && google.gears && google.gears.workerPool) {
    var wp = google.gears.workerPool;

    wp.onmessage =  function(a, b, message) {
        var sender = message.sender;
        postMessage = function(data) {
            wp.sendMessage(data, sender);
        };
        onmessage({ // call the onmessage function defined below
            data: message.body
        });
    };

    // emulate importScripts in Gears.
    __GLOBAL__.importScripts = function() {
        var global = this;
        var src = "";
        var i = 0;
        var load = function(url, callback) {
            var request = google.gears.factory.create('beta.httprequest');
            request.open('GET', url);
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                    if (request.status >= 200 && request.status < 400) {
                        var res = request.responseText;
                        src += res+"\n";
                        callback();
                    } else {
                        throw new Error("Error fetching script "+url+". Response code: " + request.status + " Response text: "+request.responseText);
                    }
                }
            };
            request.send();
        };
        var urls = Array.prototype.splice.call(arguments, 0);
        var loader = function() {
            var url = urls.shift();
            if (url) {
                load(url, loader);
            } else {
                try {
                    global.eval(src);
                } catch (e) {
                    console.log("Error evaluating source ", e);
                }
                loadDone();
            }
        };
        loader();
    };
}

// No importScripts and no Gears -> Safari 4
if (typeof importScripts == "undefined") {
    EMULATE_LOAD = true;
    var loadCounter = 0;
    __GLOBAL__.importScripts = function() {
        for (var i = 0; i < arguments.length; ++i) {
            var script = arguments[i];
            //console.log("Loading")
            postMessage(internalMessageIdentifier + "["+(SCRIPT_COUNT++) + ", '" + script + "']");
            ++loadCounter;
        }
    };

    var loaded = [];
    var nextLoad = 0;
    // make sure we eval scripts in requested order
    __GLOBAL__.__evalScriptFromImport = function(index, source) {
        loaded[index] = source;
        // console.log("Received script "+index + ". ")
        for (var i = nextLoad; i < loaded.length; ++i) {
            if (loaded[i]) {
                nextLoad = i+1;
                //console.log("Evalling "+i)
                try {
                    __GLOBAL__.eval(loaded[i]);
                } catch (e) {
                    console.log("Error evaluating script from import: ", e);
                }
                //console.log("evaled "+i);
                if (loadCounter == i) {
                    //console.log("Done");
                    loadDone();
                }
            } else {
                break;
            }
        }
    };
}

if (!NATIVE_JSON) {
    origPostMessage = postMessage;
    postMessage = function(data) {
        if (typeof data != "string") {
            data = JSON.stringify(data);
        }
        origPostMessage(data);
    };
}

onmessage = function(event) {
    var body = event.data;
    var dataIsString = false;
    if (typeof body == "string") {
        // special case: somebody posts source to us
        if (body.indexOf("// YOUcannotGuessMe") == 0) {
            if (EMULATE_LOAD) {
                __GLOBAL__.__evalScriptFromImport(SCRIPT_COUNT++, body);
            } else {
                try {
                    __GLOBAL__.eval(body);
                } catch (e) {
                    console.log("Unable to evaluate onmessage() " + e);
                }
                loadDone();
            }
            return;
        }
        // special case: outside asks us to load source
        else if (body.indexOf("__IMPORT_SCRIPT__") == 0) {
            var source = body.substr("__IMPORT_SCRIPT__".length);
            var match = source.match(/^\/\/(\d+)/);
            if (match) {
                var index = parseInt(match[1], 10);
                __evalScriptFromImport(index, source);
            }
            return;
        }
        else {
            dataIsString = true;
            try {
                body = JSON.parse(body);
            } catch (e) {
                throw e + "" + body;
            }
        }
    }

    // regular postMessage
    // body has now been parsed.

    if (body.event) {
        bespin.receive(body);
        return;
    }

    var method = body.method;

    var o = theObject;

    // actually call the method
    var ret = o[body.method].apply(o, body.paras);

    var data = {
        method: body.method,
        returnValue: ret,
        callIndex: body.callIndex // the original callIndex to find callback
    };

    postMessage(data);
};


// Build a facade that allows to subscribe to events and publish events via the main page
var eventIndex      = 0;
var eventCallbacks  = [];

bespin = {
    subscribe: function(name, callback) {
        //console.log("Subscribe: "+name)
        postMessage({
            type: "subscribe",
            name: name,
            index: eventIndex
        });

        eventCallbacks[eventIndex] = function() {
            //console.log("Fire "+name);
            callback.apply(this, arguments);
        };

        eventIndex++;
    },

    publish: function(name, event) {
        //console.log("Publish: "+name)
        postMessage({
            type: "publish",
            name: name,
            event: event
        });
    },

    // receives external event
    receive: function(info) {
        //console.log("Receive: "+info.name);
        eventCallbacks[info.index](info.event);
    }
};



//Downloaded unchanged from http://www.json.org/json2.js

/*
    json2.js
    2008-02-14

    Public Domain

    No warranty expressed or implied. Use at your own risk.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods:

        JSON.stringify(value, whitelist)
            value       any JavaScript value, usually an object or array.

            whitelist   an optional array parameter that determines how object
                        values are stringified.

            This method produces a JSON text from a JavaScript value.
            There are three possible ways to stringify an object, depending
            on the optional whitelist parameter.

            If an object has a toJSON method, then the toJSON() method will be
            called. The value returned from the toJSON method will be
            stringified.

            Otherwise, if the optional whitelist parameter is an array, then
            the elements of the array will be used to select members of the
            object for stringification.

            Otherwise, if there is no whitelist parameter, then all of the
            members of the object will be stringified.

            Values that do not have JSON representaions, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays will be replaced with null.
            JSON.stringify(undefined) returns undefined. Dates will be
            stringified as quoted ISO dates.

            Example:

            var text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'

        JSON.parse(text, filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function that can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = JSON.parse(text, function(key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load third party
    code into your pages.
*/

/*jslint evil: true */

/*global JSON */

/*members "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    charCodeAt, floor, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, length,
    parse, propertyIsEnumerable, prototype, push, replace, stringify, test,
    toJSON, toString
*/

if (!this.JSON) {
    JSON = function() {

        function f(n) {    // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        Date.prototype.toJSON = function() {

// Eventually, this method will be based on the date.toISOString method.

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };


        var m = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        function stringify(value, whitelist) {
            var a,          // The array holding the partial texts.
                i,          // The loop counter.
                k,          // The member key.
                l,          // Length.
                r = /["\\\x00-\x1f\x7f-\x9f]/g,
                v;          // The member value.

            switch (typeof value) {
            case 'string':

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe sequences.

                return r.test(value) ?
                    '"' + value.replace(r, function(a) {
                        var c = m[a];
                        if (c) {
                            return c;
                        }
                        c = a.charCodeAt();
                        return '\\u00' + Math.floor(c / 16).toString(16) +
                                                   (c % 16).toString(16);
                    }) + '"' :
                    '"' + value + '"';

            case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':
                return String(value);

            case 'object':

// Due to a specification blunder in ECMAScript,
// typeof null is 'object', so watch out for that case.

                if (!value) {
                    return 'null';
                }

// If the object has a toJSON method, call it, and stringify the result.

                if (typeof value.toJSON === 'function') {
                    return stringify(value.toJSON());
                }
                a = [];
                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {

// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                    l = value.length;
                    for (i = 0; i < l; i += 1) {
                        a.push(stringify(value[i], whitelist) || 'null');
                    }

// Join all of the elements together and wrap them in brackets.

                    return '[' + a.join(',') + ']';
                }
                if (whitelist) {

// If a whitelist (array of keys) is provided, use it to select the components
// of the object.

                    l = whitelist.length;
                    for (i = 0; i < l; i += 1) {
                        k = whitelist[i];
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                } else {

// Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                }

// Join all of the member texts together and wrap them in braces.

                return '{' + a.join(',') + '}';
            }
        }

        return {
            stringify: stringify,
            parse: function(text, filter) {
                var j;

                function walk(k, v) {
                    var i, n;
                    if (v && typeof v === 'object') {
                        for (i in v) {
                            if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                                n = walk(i, v[i]);
                                if (n !== undefined) {
                                    v[i] = n;
                                } else {
                                    delete v[i];
                                }
                            }
                        }
                    }
                    return filter(k, v);
                }


// Parsing happens in three stages. In the first stage, we run the text against
// regular expressions that look for non-JSON patterns. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we want to reject all
// unexpected forms.

// We split the first stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace all backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

                if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                    j = eval('(' + text + ')');

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

                    return typeof filter === 'function' ? walk('', j) : j;
                }

// If the text is not JSON parseable, then a SyntaxError is thrown.

                throw new SyntaxError('parseJSON');
            }
        };
    }();
}
