(function() {
    
    function WindowOverride(element, newdocument)
    {
        this.closed = false;
        this.document = newdocument;
        this.history = window.history;
        this.location = window.location;
        this.name = window.name;
        this.opener = window.opener;
        this.parent = window.parent;
        this.self = window.self;
        this.status = "";
        this.top = window.top;
        
        this.alert = function(text) {
            window.alert(text);
        }
        
        this.blur = function() {
            window.blur();
        }
        
        this.clearInterval = function(id) {
            window.clearInterval(id);
        }
        
        this.clearTimeout = function(id) {
            window.clearTimeout(id);
        }
        
        this.focus = function() {
            window.focus();
        }
        
        this.moveBy = function(x, y) {
            window.moveBy(x, y);
        }
        
        this.moveTo = function(x, y) {
            window.moveTo(x, y);
        }
        
        this.open = function(URL, name, specs, replace) {
            window.open(URL, name, specs, replace);
        }
        
        this.print = function() {
            window.alert("This function is not available. Please use the print button.");
        }
        
        this.prompt = function(text, defaultText) {
            return window.prompt(text, defaultText);
        }

        this.setInterval = function(code, millisec) {
            if(typeof(code) == "function") return window.setInterval(code, millisec);
            else return window.setInterval(eval('(function() {'+code+'})'), millisec);
        }
        
        this.setTimeout = function(code, millisec) {
            if(typeof(code) == "function") return window.setTimeout(code, millisec);
            else return window.setTimeout(eval('(function() {'+code+'})'), millisec);
        }

/** Fix ME: These should really point at the DIV. **/
        this.resizeBy = function(x, y) {
            window.resizeBy(x, y);
        }
        
        this.resizeTo = function(x, y) {
            window.resizeTo(x, y);
        }
        
        this.scrollBy = function(x, y) {
            window.scrollBy(x, y);
        }
        
        this.scrollTo = function(x, y) {
            window.scrollTo(x, y);
        }
    }

    function DocumentOverride(element)
    {
        var output = "";
        
        this.body = element;
        this.title = window.title;
        this.URL = document.URL;
        
        this.getElementById = function(id) {
            return document.getElementById(id);
        }
        
        this.getElementsByName = function(id) {
            return document.getElementsByName(id);
        }
        
        this.getElementsByTagName = function(id) {
            return document.getElementsByTagName(id);
        }
        
        this.createElement = function(id) {
            return document.createElement(id);
        }
        
        this.createTextNode = function(id) {
            return document.createTextNode(id);
        }
        
        this.addEventListener = function(type, listener, bubble) {
            return document.addEventListener(type, listener, bubble);
        }
        
        this.removeEventListener = function(type, listener, bubble) {
            return document.removeEventListener(type, listener, bubble);
        }
        
        this.open = function(mimetype, replace) {
            if(replace) element.innerHTML = "";
        }
        
        this.write = function(text) {
            output += text;
        }
        
        this.writeln = function(text) {
            output += text + "\n";
        }
        
        this.close = function() {
            if(output == "") return;
            
            element.innerHTML += output;
            output = "";
        }
        
    }

    function init()
    {
        var elements = document.getElementsByTagName("jsgame");

        for(var i=0; i<elements.length; i++) loadJavascriptGame(elements[i]);
    }

    function loadJavascriptGame(element)
    {
        var src = element.getAttribute("src");
        var request = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"));
        var response;

        request.open("GET", src+"/JS_DEPLOY/META_DATA", false);
        request.send(null);

        response = eval("("+request.responseText+")");

        if(response.type == "frame") insertIFrameGame(element, response);
        else if(response.type == "inline-script") inlineJavascriptGame(element, response);
        else alert("Unknown deployment method: "+response.type);
    }
    
    function insertIFrameGame(element, info)
    {
        var src = element.getAttribute("src");
        
        element.innerHTML = 
            '<iframe scrolling="auto" frameborder="no" src="'+src+"/"+info.main+'" style="width: '+info.width+'px; height: '+info.height+'px; overflow: auto; padding: 0px; margin: 0px; font-size: medium; line-height: normal;">'+
            '</iframe>';
    }

    function runScripts(e, document, window) 
    {
        var args = "";
        var argValues = [];
        
        for(var i in window)
        {
            if(argValues.length > 0) args += ',';
            
            args += i;
            argValues.push(window[i]);
        }
        
        args += ",window";
        argValues.push(window);

        if (e.nodeType != 1) return; //if it's not an element node, return

        if (e.tagName.toLowerCase() == 'script') 
        {
            //FIX ME: Needs SRC support!
            //run the script
            eval("(function("+args+") {" + e.text +" })").apply(window, argValues);
        }
        else 
        {
            var n = e.firstChild;
            while ( n ) 
            {
                if ( n.nodeType == 1 ) runScripts( n, document, window ); //if it's an element node, recurse
                n = n.nextSibling;
            }
        }
    }
    
    function inlineJavascriptGame(element, info)
    {
        var div = document.createElement("div");
        var src = element.getAttribute("src");
        var request = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"));

        request.open("GET", src+"/"+info.main, false);
        request.send(null);
        
        div.style.width = info.width+"px";
        div.style.height = info.height+"px";
        
        element.appendChild(div);
        
        var args = "";
        var argValues = [];
        
        var newdocument = new DocumentOverride(div);
        var newwindow = new WindowOverride(div, newdocument);
        
 
//Temporary Hack
window.wiicade = {path: src + "/"}; 
        
        for(var i in window)
        {
            if(argValues.length > 0) args += ',';
            
            args += i;
            
            if(!newwindow[i]) newwindow[i] = window[i];
            
            argValues.push(newwindow[i]);
        }
        
        args += ",window";
        argValues.push(newwindow);
        
        new Function(args, request.responseText).apply(newwindow, argValues);
    }
    
    init();
})();
