<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
        function toHex(n) {
            n = parseInt(n,10);
            if (isNaN(n)) return "00";
            n = Math.max(0,Math.min(n,255));
            return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
        }

        function floodfill(node, targetcolor, replacementcolor, pathWidth, pathHeight){
            var nodeimgdata = c.getImageData(node.x,node.y,1,1).data;
            var nodecolor = "#" + rgbToHex(nodeimgdata[0],nodeimgdata[1],nodeimgdata[2]);

            if(nodecolor == replacementcolor){
                return;
            }
            if(targetcolor == replacementcolor){
                return;
            }

            if(nodecolor != targetcolor){
                return;
            }
            if(node.x < 0 || node.x >= pathWidth * 30 || node.y < 0 || node.y >= pathHeight*30){
                return;
            }

            c.fillStyle = replacementcolor;
            c.fillRect(node.x, node.y, 8, 8);
            var westnode = {
                x:0,
                y:0
            };
            westnode.x = node.x - 8;
            westnode.y = node.y;
            var eastnode = {
                x:0,
                y:0
            };
            eastnode.x = node.x + 8;
            eastnode.y = node.y
            var northnode = {
                x:0,
                y:0
            };
            northnode.x = node.x;
            northnode.y = node.y - 8;
            var southnode = {
                x:0,
                y:0
            };
            southnode.x = node.x;
            southnode.y = node.y + 8;
            floodfill(westnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(eastnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(northnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(southnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            return;

        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           var branch = 0;
           var branchpoint = {
               x: -1,
               y: -1
           };
           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + movedirX*l + 8, movingpointold.y*30 + movedirY*l + 8, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               if( i >= (pathWidth + pathHeight) - 1 && branch < 1){
                   branchpoint.x = movingpoint.x;
                   branchpoint.y = movingpoint.y;

                   branch++;
               }

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            //c.fillStyle = "#33CC33";
            c.fillStyle = "#FFFFFF";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            //c.fillStyle = "#CC0000";
            c.fillStyle = "#FFFFFF";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            c.fillStyle = "#CC66FF";
            c.fillRect(branchpoint.x*30, branchpoint.y*30, 24, 24);

            var startnode = {
                x:0,
                y:0
            };
            startnode.x = startpoint.x*30;
            startnode.y = startpoint.y*30;
            //floodfill(startnode,"#FFFFFF","#0099FF", pathWidth, pathHeight);
            var imgdata = c.getImageData(0,0,1,1).data;

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
        function toHex(n) {
            n = parseInt(n,10);
            if (isNaN(n)) return "00";
            n = Math.max(0,Math.min(n,255));
            return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
        }

        function floodfill(node, targetcolor, replacementcolor, pathWidth, pathHeight){
            var nodeimgdata = c.getImageData(node.x,node.y,1,1).data;
            var nodecolor = "#" + rgbToHex(nodeimgdata[0],nodeimgdata[1],nodeimgdata[2]);

            if(nodecolor == replacementcolor){
                return;
            }
            if(targetcolor == replacementcolor){
                return;
            }

            if(nodecolor != targetcolor){
                return;
            }
            if(node.x < 0 || node.x >= pathWidth * 30 || node.y < 0 || node.y >= pathHeight*30){
                return;
            }

            c.fillStyle = replacementcolor;
            c.fillRect(node.x, node.y, 8, 8);
            var westnode = {
                x:0,
                y:0
            };
            westnode.x = node.x - 8;
            westnode.y = node.y;
            var eastnode = {
                x:0,
                y:0
            };
            eastnode.x = node.x + 8;
            eastnode.y = node.y
            var northnode = {
                x:0,
                y:0
            };
            northnode.x = node.x;
            northnode.y = node.y - 8;
            var southnode = {
                x:0,
                y:0
            };
            southnode.x = node.x;
            southnode.y = node.y + 8;
            floodfill(westnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(eastnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(northnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(southnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            return;

        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           var branch = 0;
           var branchpoint = {
               x: -1,
               y: -1
           };
           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + movedirX*l + 8, movingpointold.y*30 + movedirY*l + 8, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               if( i >= (pathWidth + pathHeight) - 1 && branch < 1){
                   branchpoint.x = movingpoint.x;
                   branchpoint.y = movingpoint.y;

                   branch++;
               }

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            //c.fillStyle = "#33CC33";
            c.fillStyle = "#FFFFFF";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            //c.fillStyle = "#CC0000";
            c.fillStyle = "#FFFFFF";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            c.fillStyle = "#CC66FF";
            c.fillRect(branchpoint.x*30, branchpoint.y*30, 24, 24);

            var startnode = {
                x:0,
                y:0
            };
            startnode.x = startpoint.x*30;
            startnode.y = startpoint.y*30;
            //floodfill(startnode,"#FFFFFF","#0099FF", pathWidth, pathHeight);
            var imgdata = c.getImageData(0,0,1,1).data;

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>"use strict";

var WebGameMaker = {};

// Global settings (setup)
WebGameMaker.setup = {
    'coreFolder': 'core',
    'pluginsFolder': 'plugins',
}

// List of required resources that needs to get inserted into the document for
// WebGameMaker to work.
WebGameMaker.requiredResources = [
    WebGameMaker.setup.coreFolder + '/utils.js',
    WebGameMaker.setup.coreFolder + '/game.js',
    WebGameMaker.setup.coreFolder + '/plugin_manager.js',
    WebGameMaker.setup.coreFolder + '/ui.js',
    WebGameMaker.setup.coreFolder + '/collision_manager.js',
];

WebGameMaker.init = function() {
    WebGameMaker.Settings = {}
    try {
        var canvas = document.getElementById('canvas');
    } catch (err) {
        alert(err);
        return false;
    }
    WebGameMaker.Settings.canvas = {
        'element': canvas,
        'context': canvas.getContext('2d'),
        'width': canvas.width,
        'height': canvas.height,
        'top': 0,
        'left': 0,
    };
    WebGameMaker.UI.positionCanvas();
    WebGameMaker.PluginManager.findAndInjectPlugins(
        WebGameMaker.setup.pluginsFolder,
        function() {
            WebGameMaker.initPlugins();

            WebGameMaker.Game = new Game();
            WebGameMaker.update();
        }
    );
}

WebGameMaker.initPlugins = function() {
    var plugins = WebGameMaker.PluginManager.getPlugins();
    var pluginButtonClicked = function(evt) {
        var plugin = WebGameMaker.PluginManager.getPluginByName(
                evt.srcElement.name);
        var instance = new plugin();
        WebGameMaker.setActivePluginInstance(instance);
    }
    for (var p in plugins) {
        WebGameMaker.UI.addPluginButton(plugins[p], pluginButtonClicked);
    }
}

WebGameMaker.setActivePluginInstance = function(instance) {
    var propertyUpdated = bind(this, function(evt) {
        WebGameMaker.updateActivePluginInstanceProperty(
                instance,
                evt.srcElement.id,
                evt.srcElement.type,
                evt.srcElement.value);
    });

    var submitSettings = bind(this, function() {
        if (WebGameMaker.Game.getPluginById(instance.settings.id.value)) {
            alert("Object with that id already exists");
            return false;
        }

        WebGameMaker.UI.clearSettingsBox();

        WebGameMaker.Game.addPluginInstance(instance);
        var activePlugins = WebGameMaker.Game.getPluginInstances();

        WebGameMaker.UI.clearActivePlugins();
        for (var p in activePlugins) {
            WebGameMaker.UI.addActivePlugin(activePlugins[p].settings.id.value);
        }
    });

    WebGameMaker.UI.showSettingsBox(instance, propertyUpdated,
            submitSettings);
}

WebGameMaker.updateActivePluginInstanceProperty = function(instance, property, type,
        value) {
    if (property == 'id') {
        var existingInstance = WebGameMaker.Game.getPluginById(value);
        if (existingInstance) {
            alert("Object with that id already exists");
            return false;
        }
        var activePlugins = WebGameMaker.Game.getPluginInstances();
        WebGameMaker.UI.clearActivePlugins();
        for (var p in activePlugins) {
            WebGameMaker.UI.addActivePlugin(
                    activePlugins[p].settings.id.value, function(evt) {
                        WebGameMaker.setActivePluginInstance(
                            WebGameMaker.Game.getPluginById(evt.srcElement.id)
                            )
                    });
        }
    }

    if (type == 'number') {
        instance.settings[property].value = Number(value);
        instance.settings[property].initial_value = Number(value);
    } else {
        instance.settings[property].value = value;
        instance.settings[property].initial_value = value;
    }

    return true;
}

WebGameMaker.update = function() {
    var draw_info = {
        'canvas_context': WebGameMaker.Settings.canvas.context,
    }

    draw_info['canvas_context'].clearRect(0, 0, WebGameMaker.Settings.canvas.width,
            WebGameMaker.Settings.canvas.height);

    WebGameMaker.Game.draw(draw_info);
    window.requestAnimationFrame(WebGameMaker.update);
}

WebGameMaker.injectScripts = function(fileList, callback) {
    WebGameMaker.injectScriptsProgress = {
        'injected': 0,
        'target': fileList.length,
        'callback': callback,
    };
    for (var i in fileList) {
        var s = document.createElement('script');
        s.src = fileList[i];
        s.onload = function() {
            var progress = WebGameMaker.injectScriptsProgress;
            progress.injected++;
            if (progress.injected == progress.target && progress.callback) {
                WebGameMaker.injectScriptsProgress = {};
                setTimeout(progress.callback, 1);
            }
        }
        document.querySelector('head').appendChild(s);
    }
}

window.addEventListener('load', function() {
    WebGameMaker.injectScripts(WebGameMaker.requiredResources, WebGameMaker.init);
}, false);
<commit_msg>Document confusing methods in web_game_maker.js<commit_after>"use strict";

var WebGameMaker = {};

// Global settings (setup)
WebGameMaker.setup = {
    'coreFolder': 'core',
    'pluginsFolder': 'plugins',
}

// List of required resources that needs to get inserted into the document for
// WebGameMaker to work.
WebGameMaker.requiredResources = [
    WebGameMaker.setup.coreFolder + '/utils.js',
    WebGameMaker.setup.coreFolder + '/game.js',
    WebGameMaker.setup.coreFolder + '/plugin_manager.js',
    WebGameMaker.setup.coreFolder + '/ui.js',
    WebGameMaker.setup.coreFolder + '/collision_manager.js',
];

WebGameMaker.init = function() {
    WebGameMaker.Settings = {}
    try {
        var canvas = document.getElementById('canvas');
    } catch (err) {
        alert(err);
        return false;
    }
    WebGameMaker.Settings.canvas = {
        'element': canvas,
        'context': canvas.getContext('2d'),
        'width': canvas.width,
        'height': canvas.height,
        'top': 0,
        'left': 0,
    };
    WebGameMaker.UI.positionCanvas();
    WebGameMaker.PluginManager.findAndInjectPlugins(
        WebGameMaker.setup.pluginsFolder,
        function() {
            WebGameMaker.initPlugins();

            WebGameMaker.Game = new Game();
            WebGameMaker.update();
        }
    );
}

/**
 * The initPlugins method is responsible for retrieving information about the
 * currently installed plugins and letting the UI know about them.
 */
WebGameMaker.initPlugins = function() {
    var plugins = WebGameMaker.PluginManager.getPlugins();
    var pluginButtonClicked = function(evt) {
        var plugin = WebGameMaker.PluginManager.getPluginByName(
                evt.srcElement.name);
        var instance = new plugin();
        WebGameMaker.setActivePluginInstance(instance);
    }
    for (var p in plugins) {
        WebGameMaker.UI.addPluginButton(plugins[p], pluginButtonClicked);
    }
}

/**
 * The setActivePluginInstance method sets the given instance as the currently
 * active object, which means that it will be possible to edit this instance
 * in the settings box. It's also responsible for registering callbacks for
 * storing the active instance in the game and updating properties after the
 * object has already been added.
 *
 * @param instance Plugin instance that should be edited.
 */
WebGameMaker.setActivePluginInstance = function(instance) {
    var propertyUpdated = bind(this, function(evt) {
        WebGameMaker.updateActivePluginInstanceProperty(
                instance,
                evt.srcElement.id,
                evt.srcElement.type,
                evt.srcElement.value);
    });

    var submitSettings = bind(this, function() {
        if (WebGameMaker.Game.getPluginById(instance.settings.id.value)) {
            alert("Object with that id already exists");
            return false;
        }

        WebGameMaker.UI.clearSettingsBox();

        WebGameMaker.Game.addPluginInstance(instance);
        var activePlugins = WebGameMaker.Game.getPluginInstances();

        WebGameMaker.UI.clearActivePlugins();
        for (var p in activePlugins) {
            WebGameMaker.UI.addActivePlugin(activePlugins[p].settings.id.value);
        }
    });

    WebGameMaker.UI.showSettingsBox(instance, propertyUpdated,
            submitSettings);
}

WebGameMaker.updateActivePluginInstanceProperty = function(instance, property, type,
        value) {
    // In case the property that is being changed is the id, we first need
    // to verify that there isn't already an object with the new id.
    if (property == 'id') {
        var existingInstance = WebGameMaker.Game.getPluginById(value);
        if (existingInstance) {
            alert("Object with that id already exists");
            return false;
        }

        // TODO(robert): Is this really needed? I don't see the point of it
        // anymore...
        var activePlugins = WebGameMaker.Game.getPluginInstances();
        WebGameMaker.UI.clearActivePlugins();
        for (var p in activePlugins) {
            WebGameMaker.UI.addActivePlugin(
                    activePlugins[p].settings.id.value, function(evt) {
                        WebGameMaker.setActivePluginInstance(
                            WebGameMaker.Game.getPluginById(evt.srcElement.id));
                    }
            );
        }
    }

    // Store the new property in the object.
    if (type == 'number') {
        instance.settings[property].value = Number(value);
        instance.settings[property].initial_value = Number(value);
    } else {
        instance.settings[property].value = value;
        instance.settings[property].initial_value = value;
    }

    return true;
}

WebGameMaker.update = function() {
    var draw_info = {
        'canvas_context': WebGameMaker.Settings.canvas.context,
    }

    draw_info['canvas_context'].clearRect(0, 0, WebGameMaker.Settings.canvas.width,
            WebGameMaker.Settings.canvas.height);

    WebGameMaker.Game.draw(draw_info);
    window.requestAnimationFrame(WebGameMaker.update);
}

WebGameMaker.injectScripts = function(fileList, callback) {
    WebGameMaker.injectScriptsProgress = {
        'injected': 0,
        'target': fileList.length,
        'callback': callback,
    };
    for (var i in fileList) {
        var s = document.createElement('script');
        s.src = fileList[i];
        s.onload = function() {
            var progress = WebGameMaker.injectScriptsProgress;
            progress.injected++;
            if (progress.injected == progress.target && progress.callback) {
                WebGameMaker.injectScriptsProgress = {};
                setTimeout(progress.callback, 1);
            }
        }
        document.querySelector('head').appendChild(s);
    }
}

window.addEventListener('load', function() {
    WebGameMaker.injectScripts(WebGameMaker.requiredResources, WebGameMaker.init);
}, false);
<|endoftext|>


<commit_before>// vim: noexpandtab
function Log(file, project) {
	//class properties
	this.tab = null;		//holds reference to tab in tabbar
	this.selectedRevision = -1;	//Selected revision, -1 indicates no revision set
	this.team = team;		//team number TODO: get this from elsewhere
	this.project = project;    //holds the current project name
	this.user = null;		//holds author name
	this.userList = new Array();	//List of  users attributed to file(s)
	this.history = new Array();	//array of log entries returned by server
	this.file = file;		//the file/directory for which we are interested
	this.offset = 0;		//which results page we want to retrieve from the server
	this.overflow = 0;		//stores  total number of results pages (retrieved from server)

	//do this only once: add a new tab to the tabbar and link it to this log page
	this.tab = new Tab("Log: "+this.file.toString());
	connect(this.tab, 'onfocus', bind(this._onfocus, this));
	connect(this.tab, 'onblur', bind(this._onblur, this));
	connect(this.tab, 'onclickclose', bind(this.close, this));
	tabbar.add_tab(this.tab);
	tabbar.switch_to(this.tab);
	//start initialisation
	this._init();

/*
	selectedRevision [int]	holds revision number to revert to
	userList [string[]]	Array of users who have made revisions to the selected  file(s)
	history			the array of dictionaries returned by the server
	file			the file(s) for which the logs are for
	user			holds the name of the user who's revisions have been selected
	overflow		holds the total number of page of results for  the latest query
	offset			holds the page offset for the next query

	_init()			Initialize function - clears variables and re-retrieves data from server
	_receiveHistory(rev)	Callback function for loadJSONDoc success
	_errorReceiveHistory()	Callback function for loadJSONDoc fail
	_retrieveHistory()	Instigates call to server to retrieve logs for given file(s) & users
	_populateList()		Takes history and updates list of logs on page, it also adds event handlers to log-menu buttons
	_update()		Event handler for when a new user is selected
	_revert(bool)		event handler for when user clicks 'revert' - if arg is false, confirmation is  requested from user
	_nextview(int)		event handler for when user clicks on 'older'/'newer' buttons,
				if int > 0 an older page of  results is retrieved, if int <0 a later page of results is retrieved
	_onfocus()		event handler for tab click
	_onblur()		event handler for tab looses focus
	close()			completely close the tab and log page
*/
}

Log.prototype._init = function() {
	logDebug("Initializing Log...");
	//clear data from previous query
	this.history = new Array();
	this.userList = new Array();
	//do new query
	this._retrieveHistory();
}

Log.prototype._receiveHistory = function(opt, revisions) {
	logDebug("Log history received ok");
	//extract data from query response
	update(this.history, revisions.log);
	update(this.userList, revisions.authors);
	this.overflow = 0;
	if(opt == null || opt != 'quiet')
		status_msg("File history loaded successfully", LEVEL_OK);
	//present data
	this._populateList();
}

Log.prototype._errorReceiveHistory = function() {
	//handle failed request
	logDebug("Log history retrieval failed");
	this.history = new Array();
	status_button("Error retrieving history", LEVEL_WARN, "Retry", bind(this._receiveHistory, this));
}

Log.prototype._retrieveHistory = function(opt) {
	IDE_backend_request('file/log',
		{ team : team,
		  project: IDE_path_get_project(this.file),
		  path : IDE_path_get_file(this.file),
		  //this key is to filter by author
		  user : this.user,
		  offset : this.offset,
		  number : 4096
		},
		bind(this._receiveHistory, this, opt),
		bind(this._errorReceiveHistory, this)
	);
}

Log.prototype._histDate = function(which) {
	var stamp = this.history[which].time;
	var d = new Date(stamp*1000);
	return d.toDateString();
}

//processess log data and formats into list. connects up related event handlers,
//deals with multile results pages
Log.prototype._populateList = function() {
	logDebug("Processing log list...");

	//print summary information
	var entries = this.history.length;
	if(entries <= 0) {
		$("log-summary").innerHTML = "There are no revisions available for file(s): "+this.file;
	} else {
		$("log-summary").innerHTML = "Displaying "+entries+" revision(s) between "+this._histDate(this.history.length-1)+" & "+this._histDate(0)+" Page "+(this.offset+1)+" of "+(this.overflow+1);
	}

	//fill drop down box with authors attributed to file(s)
	//clear list:
	replaceChildNodes('repo-users', opt);

	//first item in list is: 'Filter by user'
	var opt = OPTION({"value":-1}, "Filter by user");
	appendChildNodes('repo-users', opt);

	//second item in the list is: 'all' meaning, show logs from all users
	var opt = OPTION({"value":-1}, "Show all");
	appendChildNodes('repo-users', opt);

	//now add all attributed authors
	for(var i=0; i < this.userList.length; i++) {
		var opt = OPTION({"value":i}, this.userList[i]);
		appendChildNodes('repo-users', opt);
	}
    //remove event handler for when user applies filter to results
	disconnectAll('repo-users');

	//clear log list
	replaceChildNodes($("log-list"), null);
	//now populate log list
	for(var x=0; x <this.history.length; x++) {
		var logtxt = SPAN(this.history[x].hash+" | "+this.history[x].author+" | "+this._histDate(x));
		var radio = INPUT({'type' : 'radio', 'name' : 'log', 'class' : 'log-radio', 'value' : this.history[x].hash });
		var label = LABEL( null, radio, logtxt );
		var commitMsg = DIV({'class' : 'commit-msg'}, this.history[x].message);
		appendChildNodes($("log-list"), LI(null, label, commitMsg));
	}
	//make selected user selected in drop down box (visual clue that filter is applied)
	if(this.user != null) {
		$('repo-users').value = findValue(this.userList, this.user);
	}

	//connect event handler for when user applies filter to results
	connect('repo-users', 'onchange', bind(this._update, this));

	//disconnect the older/newer buttons
	disconnectAll($("older"));
	disconnectAll($("newer"));

	//if older results are available, enable the 'older' button and hook it up
	if(this.offset < (this.overflow-1)) {
		$("older").disabled = false;
		connect($("older"), 'onclick', bind(this._nextview, this, +1));
	} else
		$("older").disabled = true;

	//if newer results are available, enable the 'newer' button and hook it up
	if(this.offset > 0) {
		$("newer").disabled = false;
		connect($("newer"), 'onclick', bind(this._nextview, this, -1));
	} else
		$("newer").disabled = true;

	//connect up the 'Revert' button to event handler
	disconnectAll($("revert"));
	connect($("revert"), 'onclick', bind(this._revert, this, false));

	//connect up the 'Diff' button to event handler
	disconnectAll('log-diff');
	connect('log-diff', 'onclick', bind(this._diff, this, false));

	//connect up the close button on log menu
	disconnectAll($("log-close"));
	connect($("log-close"), 'onclick', bind(this.close, this));
}
//get older (updown > 0) or newer (updown < 0) results
Log.prototype._nextview = function(updown) {
	this.offset = this.offset+updown;
	//get new results page
	this._init();
}
//called when user applies author filter
Log.prototype._update = function() {
	//find out which author was selected  using select value as key to userList array
	var index = $('repo-users').value;
	//if user clicks 'All' (-1) clear user variable
	if(index > -1) {
		this.user = this.userList[index];
	} else {
		this.user = null;
	}
	logDebug("Filter logs by user: "+this.user);
	//reset offset
	this.offset = 0;
	this._init();
}

Log.prototype._receiveRevert = function(nodes,args) {
    arg_nodes = args["nodes"]
	if(nodes.commit != "")
		status_msg("Successfully reverted to version "+this.selectedRevision+" (New Revision: "+nodes.commit+")", LEVEL_OK);
	else
		status_msg("Failed to revert: "+nodes.success, LEVEL_ERROR);
	//in either case update the history
	this._retrieveHistory('quiet');
	//refresh open files. yes that's right, I'm abusing the scope chain massively to
	//get the file contents here, but I don't care. Whoever wrote the edit module needs
	//their head examined
	for (var key in editpage._open_files) {
		var fileHandle = editpage._open_files[key];
		fileHandle._load_contents()
		fileHandle._update_contents()
	}
}

Log.prototype._errorReceiveRevision = function(commitMsg) {
	status_button("Unable to contact server to revert file", LEVEL_ERROR, "retry", bind(this._do_revert, this, commitMsg));
}
Log.prototype._do_revert = function(commitMsg) {
    IDE_backend_request("file/co",
                        {
                            team:team,
                            project:IDE_path_get_project(this.file),
                            files:[IDE_path_get_file(this.file)],
                            revision:this.selectedRevision
                        },
                        bind(
                            function(nodes) {
                                IDE_backend_request("proj/commit",
                                                    {
                                                        team:team,
                                                        project:IDE_path_get_project(this.file),
                                                        paths:[IDE_path_get_file(this.file)],
                                                        message:commitMsg,
                                                        nodes:nodes
                                                    },
                                                    bind(this._receiveRevert,this),
                                                    bind(this._errorReceiveRevision,this,commitMsg)
                                                   )
                            }, this
                        ),
                        bind(
                            this._errorReceiveRevision,this,commitMsg
                        )
                       )
}

//revert to selected revision. override = true to skip user confirmation
Log.prototype._revert = function(override) {
	this._find_selected();

	if(this.selectedRevision < 0) {
		//no revision selected
		status_msg("No revision selected !", LEVEL_WARN);
	} else if(override) {
		//user has confirmed revert, proceed
		status_msg("Reverting to revision: "+this.selectedRevision+"...", LEVEL_INFO);
		var b = new Browser(bind(this._do_revert, this), {'type' : 'isCommit'});
	} else {
		//user has not confirmed revert, seek confirmation
		status_button("Are you sure you want to revert selected file(s)?", LEVEL_WARN, "Yes", bind(this._revert, this, true));
	}

}

//find out which radio button is checked
Log.prototype._find_selected = function() {
	var radios = getElementsByTagAndClassName("input", "log-radio");
	for(var x=0; x < radios.length; x++) {
		if(radios[x].checked == true) {
			this.selectedRevision = radios[x].value;
			break;
		}
	}
}

//view the diff applied by a selected revision.
Log.prototype._diff = function() {
	this._find_selected();

	if(this.selectedRevision < 0) {
		//no revision selected
		status_msg("No revision selected !", LEVEL_WARN);
	} else {
		diffpage.diff(this.file, this.selectedRevision);
	}
}

//tab gets focus
Log.prototype._onfocus = function() {
	if(getStyle($("log-mode"), "display") != "block") {
		setStyle($("log-mode"), {"display" : "block"});
	}
	//don't waste time doing query again, just process results in buffer
	this._populateList();
}

//tab loses focus
Log.prototype._onblur = function() {
	setStyle($("log-mode"), {"display" : "none"});
}
//tab is closed
Log.prototype.close = function() {
	this.tab.close();
	logDebug("Closing log tab");
}
<commit_msg>replace comment that was a bit inflamatory with a nicer one<commit_after>// vim: noexpandtab
function Log(file, project) {
	//class properties
	this.tab = null;		//holds reference to tab in tabbar
	this.selectedRevision = -1;	//Selected revision, -1 indicates no revision set
	this.team = team;		//team number TODO: get this from elsewhere
	this.project = project;    //holds the current project name
	this.user = null;		//holds author name
	this.userList = new Array();	//List of  users attributed to file(s)
	this.history = new Array();	//array of log entries returned by server
	this.file = file;		//the file/directory for which we are interested
	this.offset = 0;		//which results page we want to retrieve from the server
	this.overflow = 0;		//stores  total number of results pages (retrieved from server)

	//do this only once: add a new tab to the tabbar and link it to this log page
	this.tab = new Tab("Log: "+this.file.toString());
	connect(this.tab, 'onfocus', bind(this._onfocus, this));
	connect(this.tab, 'onblur', bind(this._onblur, this));
	connect(this.tab, 'onclickclose', bind(this.close, this));
	tabbar.add_tab(this.tab);
	tabbar.switch_to(this.tab);
	//start initialisation
	this._init();

/*
	selectedRevision [int]	holds revision number to revert to
	userList [string[]]	Array of users who have made revisions to the selected  file(s)
	history			the array of dictionaries returned by the server
	file			the file(s) for which the logs are for
	user			holds the name of the user who's revisions have been selected
	overflow		holds the total number of page of results for  the latest query
	offset			holds the page offset for the next query

	_init()			Initialize function - clears variables and re-retrieves data from server
	_receiveHistory(rev)	Callback function for loadJSONDoc success
	_errorReceiveHistory()	Callback function for loadJSONDoc fail
	_retrieveHistory()	Instigates call to server to retrieve logs for given file(s) & users
	_populateList()		Takes history and updates list of logs on page, it also adds event handlers to log-menu buttons
	_update()		Event handler for when a new user is selected
	_revert(bool)		event handler for when user clicks 'revert' - if arg is false, confirmation is  requested from user
	_nextview(int)		event handler for when user clicks on 'older'/'newer' buttons,
				if int > 0 an older page of  results is retrieved, if int <0 a later page of results is retrieved
	_onfocus()		event handler for tab click
	_onblur()		event handler for tab looses focus
	close()			completely close the tab and log page
*/
}

Log.prototype._init = function() {
	logDebug("Initializing Log...");
	//clear data from previous query
	this.history = new Array();
	this.userList = new Array();
	//do new query
	this._retrieveHistory();
}

Log.prototype._receiveHistory = function(opt, revisions) {
	logDebug("Log history received ok");
	//extract data from query response
	update(this.history, revisions.log);
	update(this.userList, revisions.authors);
	this.overflow = 0;
	if(opt == null || opt != 'quiet')
		status_msg("File history loaded successfully", LEVEL_OK);
	//present data
	this._populateList();
}

Log.prototype._errorReceiveHistory = function() {
	//handle failed request
	logDebug("Log history retrieval failed");
	this.history = new Array();
	status_button("Error retrieving history", LEVEL_WARN, "Retry", bind(this._receiveHistory, this));
}

Log.prototype._retrieveHistory = function(opt) {
	IDE_backend_request('file/log',
		{ team : team,
		  project: IDE_path_get_project(this.file),
		  path : IDE_path_get_file(this.file),
		  //this key is to filter by author
		  user : this.user,
		  offset : this.offset,
		  number : 4096
		},
		bind(this._receiveHistory, this, opt),
		bind(this._errorReceiveHistory, this)
	);
}

Log.prototype._histDate = function(which) {
	var stamp = this.history[which].time;
	var d = new Date(stamp*1000);
	return d.toDateString();
}

//processess log data and formats into list. connects up related event handlers,
//deals with multile results pages
Log.prototype._populateList = function() {
	logDebug("Processing log list...");

	//print summary information
	var entries = this.history.length;
	if(entries <= 0) {
		$("log-summary").innerHTML = "There are no revisions available for file(s): "+this.file;
	} else {
		$("log-summary").innerHTML = "Displaying "+entries+" revision(s) between "+this._histDate(this.history.length-1)+" & "+this._histDate(0)+" Page "+(this.offset+1)+" of "+(this.overflow+1);
	}

	//fill drop down box with authors attributed to file(s)
	//clear list:
	replaceChildNodes('repo-users', opt);

	//first item in list is: 'Filter by user'
	var opt = OPTION({"value":-1}, "Filter by user");
	appendChildNodes('repo-users', opt);

	//second item in the list is: 'all' meaning, show logs from all users
	var opt = OPTION({"value":-1}, "Show all");
	appendChildNodes('repo-users', opt);

	//now add all attributed authors
	for(var i=0; i < this.userList.length; i++) {
		var opt = OPTION({"value":i}, this.userList[i]);
		appendChildNodes('repo-users', opt);
	}
    //remove event handler for when user applies filter to results
	disconnectAll('repo-users');

	//clear log list
	replaceChildNodes($("log-list"), null);
	//now populate log list
	for(var x=0; x <this.history.length; x++) {
		var logtxt = SPAN(this.history[x].hash+" | "+this.history[x].author+" | "+this._histDate(x));
		var radio = INPUT({'type' : 'radio', 'name' : 'log', 'class' : 'log-radio', 'value' : this.history[x].hash });
		var label = LABEL( null, radio, logtxt );
		var commitMsg = DIV({'class' : 'commit-msg'}, this.history[x].message);
		appendChildNodes($("log-list"), LI(null, label, commitMsg));
	}
	//make selected user selected in drop down box (visual clue that filter is applied)
	if(this.user != null) {
		$('repo-users').value = findValue(this.userList, this.user);
	}

	//connect event handler for when user applies filter to results
	connect('repo-users', 'onchange', bind(this._update, this));

	//disconnect the older/newer buttons
	disconnectAll($("older"));
	disconnectAll($("newer"));

	//if older results are available, enable the 'older' button and hook it up
	if(this.offset < (this.overflow-1)) {
		$("older").disabled = false;
		connect($("older"), 'onclick', bind(this._nextview, this, +1));
	} else
		$("older").disabled = true;

	//if newer results are available, enable the 'newer' button and hook it up
	if(this.offset > 0) {
		$("newer").disabled = false;
		connect($("newer"), 'onclick', bind(this._nextview, this, -1));
	} else
		$("newer").disabled = true;

	//connect up the 'Revert' button to event handler
	disconnectAll($("revert"));
	connect($("revert"), 'onclick', bind(this._revert, this, false));

	//connect up the 'Diff' button to event handler
	disconnectAll('log-diff');
	connect('log-diff', 'onclick', bind(this._diff, this, false));

	//connect up the close button on log menu
	disconnectAll($("log-close"));
	connect($("log-close"), 'onclick', bind(this.close, this));
}
//get older (updown > 0) or newer (updown < 0) results
Log.prototype._nextview = function(updown) {
	this.offset = this.offset+updown;
	//get new results page
	this._init();
}
//called when user applies author filter
Log.prototype._update = function() {
	//find out which author was selected  using select value as key to userList array
	var index = $('repo-users').value;
	//if user clicks 'All' (-1) clear user variable
	if(index > -1) {
		this.user = this.userList[index];
	} else {
		this.user = null;
	}
	logDebug("Filter logs by user: "+this.user);
	//reset offset
	this.offset = 0;
	this._init();
}

Log.prototype._receiveRevert = function(nodes,args) {
    arg_nodes = args["nodes"]
	if(nodes.commit != "")
		status_msg("Successfully reverted to version "+this.selectedRevision+" (New Revision: "+nodes.commit+")", LEVEL_OK);
	else
		status_msg("Failed to revert: "+nodes.success, LEVEL_ERROR);
	//in either case update the history
	this._retrieveHistory('quiet');

	//refresh all open file pages, this will need fixing later
	for (var key in editpage._open_files) {
		var fileHandle = editpage._open_files[key];
		fileHandle._load_contents()
		fileHandle._update_contents()
	}
}

Log.prototype._errorReceiveRevision = function(commitMsg) {
	status_button("Unable to contact server to revert file", LEVEL_ERROR, "retry", bind(this._do_revert, this, commitMsg));
}
Log.prototype._do_revert = function(commitMsg) {
    IDE_backend_request("file/co",
                        {
                            team:team,
                            project:IDE_path_get_project(this.file),
                            files:[IDE_path_get_file(this.file)],
                            revision:this.selectedRevision
                        },
                        bind(
                            function(nodes) {
                                IDE_backend_request("proj/commit",
                                                    {
                                                        team:team,
                                                        project:IDE_path_get_project(this.file),
                                                        paths:[IDE_path_get_file(this.file)],
                                                        message:commitMsg,
                                                        nodes:nodes
                                                    },
                                                    bind(this._receiveRevert,this),
                                                    bind(this._errorReceiveRevision,this,commitMsg)
                                                   )
                            }, this
                        ),
                        bind(
                            this._errorReceiveRevision,this,commitMsg
                        )
                       )
}

//revert to selected revision. override = true to skip user confirmation
Log.prototype._revert = function(override) {
	this._find_selected();

	if(this.selectedRevision < 0) {
		//no revision selected
		status_msg("No revision selected !", LEVEL_WARN);
	} else if(override) {
		//user has confirmed revert, proceed
		status_msg("Reverting to revision: "+this.selectedRevision+"...", LEVEL_INFO);
		var b = new Browser(bind(this._do_revert, this), {'type' : 'isCommit'});
	} else {
		//user has not confirmed revert, seek confirmation
		status_button("Are you sure you want to revert selected file(s)?", LEVEL_WARN, "Yes", bind(this._revert, this, true));
	}

}

//find out which radio button is checked
Log.prototype._find_selected = function() {
	var radios = getElementsByTagAndClassName("input", "log-radio");
	for(var x=0; x < radios.length; x++) {
		if(radios[x].checked == true) {
			this.selectedRevision = radios[x].value;
			break;
		}
	}
}

//view the diff applied by a selected revision.
Log.prototype._diff = function() {
	this._find_selected();

	if(this.selectedRevision < 0) {
		//no revision selected
		status_msg("No revision selected !", LEVEL_WARN);
	} else {
		diffpage.diff(this.file, this.selectedRevision);
	}
}

//tab gets focus
Log.prototype._onfocus = function() {
	if(getStyle($("log-mode"), "display") != "block") {
		setStyle($("log-mode"), {"display" : "block"});
	}
	//don't waste time doing query again, just process results in buffer
	this._populateList();
}

//tab loses focus
Log.prototype._onblur = function() {
	setStyle($("log-mode"), {"display" : "none"});
}
//tab is closed
Log.prototype.close = function() {
	this.tab.close();
	logDebug("Closing log tab");
}
<|endoftext|>


<commit_before>$(function() {

    $( ".pageDiscListen #searchTags" ).autocomplete({
      source: $('#getTagListUrl').val(),
      minLength: 2,
      select: function( event, ui ) {
        var span = $('<span>', {id: ui.item.id, class: 'category'}).html(ui.item.value);
        var plus = $('<span>',{class: 'plus'}).html(' + ');
        if ($( ".pageDiscListen .wrapperCategories .plus").length > 0) {
            $( ".pageDiscListen .wrapperCategories .plus").last().after(span);
            $( ".pageDiscListen .wrapperCategories .category").last().after(plus);
        } else {
            $( ".pageDiscListen .wrapperCategories").prepend(plus);
            $( ".pageDiscListen .wrapperCategories").prepend(span);
        }

        $( ".pageDiscListen #searchTags" ).val('');

        $( document ).ajaxStop();
        searchAlbums();

        event.preventDefault();
      }
    });

    $( ".pageDiscListen .wrapperTags" ).on('click', '.category', function(e) {
        e.preventDefault();
        var me = $(this);
        var aux = me.attr('id').split('tag-');
        var id = aux[1];

        if ($(".pageDiscListen .wrapperCategories #" + parseInt(id)).length > 0) {
            return;
        }

        var span = $('<span>', {id: id, class: 'category'}).html(me.html());
        var plus = $('<span>',{class: 'plus'}).html(' + ');

        if ($( ".pageDiscListen .wrapperCategories .plus").length > 0) {
            $( ".pageDiscListen .wrapperCategories .plus").last().after(span);
            $( ".pageDiscListen .wrapperCategories .category").last().after(plus);
        } else {
            $( ".pageDiscListen .wrapperCategories").prepend(plus);
            $( ".pageDiscListen .wrapperCategories").prepend(span);
        }

        $( document ).ajaxStop();
        searchAlbums();
    });

    // Pestañas del album (lista de temas, informacion, comentarios, similares)
    $('.mainContent').on('click', '.headerDisco .navDisco a', function(e) {
      e.preventDefault();
      var me = $(this);

      var url = me.attr('href');
      if(url == '#') {
          return;
      }
      $.getJSON(url, {}, function(data){
        if (data.success) {
          me.parents('.navDisco').find('.discoActive').removeClass('discoActive');
          me.parent().addClass('discoActive');
          $('.mainContent .albumContent').replaceWith(data.html);
        }
      });
    });

    // Download album modal
    $('.mainContent').on('click', '.headerDisco .btnDescarga', function(e) {
        e.preventDefault();
        var me = $(this);

        var url = me.data('url');
        $.getJSON(url, {}, function(data){
            if (data.success) {
                var content = $(data.html);
                content.modal();
            }
        });
    });

    // On modal close
    $('body').on('hidden.bs.modal', '.modal.fade', function (e) {
        $(this).remove();
    });

    // Checkout album
    $('body').on('click', '.mozcu-descarga-modal .btn-success', function(e) {
        e.preventDefault();
        var me = $(this);
        var div = me.parent();
        var loader = div.find('.ajaxLoader');
        var cancel = div.find('.btn-default');
        var inProcess = div.find('.in-process');
        var ready = div.find('.ready');

        me.addClass('hidden');
        cancel.addClass('hidden');
        inProcess.removeClass('hidden');
        loader.removeClass('hidden');

        var url = me.data('url');
        $.getJSON(url, {}, function(data){
            if(data.success) {
                var zipUrl = data.zipUrl;
                var amount = parseFloat($.trim($('#valor').val()));

                if(isNaN(amount)) {
                    amount = 0;
                }

                if (amount == 0) {
                    inProcess.addClass('hidden');
                    ready.removeClass('hidden');
                    initDownlaod(zipUrl);
                    setTimeout(function() {
                        $('.mozcu-descarga-modal').modal('hide');
                    }, 3000);
                } else {
                    $('#amount').val(amount);
                    $('#checkoutUrl').val(zipUrl);
                    $('#paypalForm').submit();
                }
            }
        });
    });

    var initDownlaod = function(url) {
        var iframe = $('<iframe>', {width:'1', height:'1', frameborder:'0', src:url, id:'downloadAlbumIframe'});
        $('#downloadAlbumIframe').remove();
        $('.row.headerDisco').append(iframe);
    };

    // Modal compartir
    $('.mainContent').on('click', '#shareAlbum', function(e) {
        e.preventDefault();
        var me = $(this);

        var url = me.attr('href');
        $.getJSON(url, {}, function(data){
            $(data.html).modal();
        });
    });

    // Modal denunciar obra
    $('.mainContent').on('click', '#reportAlbum', function(e) {
        e.preventDefault();
        var me = $(this);

        var url = me.attr('href');
        $.getJSON(url, {}, function(data){
            $(data.html).modal();
        });
    });

    // Enviar formulario de denuncia
    $('body').on('click', '.modal-report-album .btn-success', function(e) {
        e.preventDefault();
        var me = $(this);

        var url = me.data('url');
        $.post(url, {}, function(data) {
            // TODO
        });
    });

    // Ir al disco
    $('.mainContent').on('click', '.album .albumLink', function(e) {
      e.preventDefault();
      var me = $(this);

      $.getJSON(me.attr('href'), {}, function(data) {
        if(data.success) {
          $('.mainContent').html(data.html);
        }
      });
    });

    // Ir al perfil del usuario
    $('.mainContent').on('click', '.album .profileLink', function(e) {
      e.preventDefault();
      var me = $(this);

      $.getJSON(me.attr('href'), {}, function(data) {
        if(data.success) {
          $('.mainContent').html(data.html);
        }
      });
    });

    // Subido por
    $('.mainContent').on('click', '.headerDisco .nombreAlbumUser a', function(e) {
      e.preventDefault();
      var url = $(this).attr('href');

      $.getJSON(url, {}, function(data) {
        if(data.success) {
          $('.mainContent').html(data.html);
        }
      });
    });

    // click en tags de informacion
    $('.mainContent').on('click', '.infoDisco .tag', function(e) {
      e.preventDefault();
      var url = $(this).attr('href');

      $.getJSON(url, {}, function(data) {
        if(data.success) {
          $('.mainContent').html(data.html);
        }
      });
    });

    var searchAlbums = function() {
        var container = $('.pageDiscListen .wrapperDiscListen');
        var tags = new Array();
        $( ".pageDiscListen .wrapperCategories .category").each(function(key, value) {
            tags.push($(value).attr('id'));
        });

        var url = $('#findAlbumsByTagUrl').val();
        $.post(url, {tags: tags}, function(data){
            if (data.success) {
                container.html('');
                for(key in data.html) {
                    container.append($(data.html[key]));
                }
            }
        }, 'json');
    };

    // Album favorito
    $('.mainContent').on('click', '#likeAlbum', function(e) {
        e.preventDefault();
        var me = $(this);

        $.post(me.attr('href'), function(data) {
            if(data.success) {
                if(data.action == 'unlike') {
                    me.addClass('unlike');
                } else {
                    me.removeClass('unlike');
                }
            }
        }, 'json');
    });

});<commit_msg>fix en checkout<commit_after>$(function() {

    $( ".pageDiscListen #searchTags" ).autocomplete({
      source: $('#getTagListUrl').val(),
      minLength: 2,
      select: function( event, ui ) {
        var span = $('<span>', {id: ui.item.id, class: 'category'}).html(ui.item.value);
        var plus = $('<span>',{class: 'plus'}).html(' + ');
        if ($( ".pageDiscListen .wrapperCategories .plus").length > 0) {
            $( ".pageDiscListen .wrapperCategories .plus").last().after(span);
            $( ".pageDiscListen .wrapperCategories .category").last().after(plus);
        } else {
            $( ".pageDiscListen .wrapperCategories").prepend(plus);
            $( ".pageDiscListen .wrapperCategories").prepend(span);
        }

        $( ".pageDiscListen #searchTags" ).val('');

        $( document ).ajaxStop();
        searchAlbums();

        event.preventDefault();
      }
    });

    $( ".pageDiscListen .wrapperTags" ).on('click', '.category', function(e) {
        e.preventDefault();
        var me = $(this);
        var aux = me.attr('id').split('tag-');
        var id = aux[1];

        if ($(".pageDiscListen .wrapperCategories #" + parseInt(id)).length > 0) {
            return;
        }

        var span = $('<span>', {id: id, class: 'category'}).html(me.html());
        var plus = $('<span>',{class: 'plus'}).html(' + ');

        if ($( ".pageDiscListen .wrapperCategories .plus").length > 0) {
            $( ".pageDiscListen .wrapperCategories .plus").last().after(span);
            $( ".pageDiscListen .wrapperCategories .category").last().after(plus);
        } else {
            $( ".pageDiscListen .wrapperCategories").prepend(plus);
            $( ".pageDiscListen .wrapperCategories").prepend(span);
        }

        $( document ).ajaxStop();
        searchAlbums();
    });

    // Pestañas del album (lista de temas, informacion, comentarios, similares)
    $('.mainContent').on('click', '.headerDisco .navDisco a', function(e) {
      e.preventDefault();
      var me = $(this);

      var url = me.attr('href');
      if(url == '#') {
          return;
      }
      $.getJSON(url, {}, function(data){
        if (data.success) {
          me.parents('.navDisco').find('.discoActive').removeClass('discoActive');
          me.parent().addClass('discoActive');
          $('.mainContent .albumContent').replaceWith(data.html);
        }
      });
    });

    // Download album modal
    $('.mainContent').on('click', '.headerDisco .btnDescarga', function(e) {
        e.preventDefault();
        var me = $(this);

        var url = me.data('url');
        $.getJSON(url, {}, function(data){
            if (data.success) {
                var content = $(data.html);
                content.modal();
            }
        });
    });

    // On modal close
    $('body').on('hidden.bs.modal', '.modal.fade', function (e) {
        $(this).remove();
    });

    // Checkout album
    $('body').on('click', '.mozcu-descarga-modal .btn-success', function(e) {
        e.preventDefault();
        var me = $(this);
        var div = me.parent();
        var loader = div.find('.ajaxLoader');
        var cancel = div.find('.btn-default');
        var inProcess = div.find('.in-process');
        var ready = div.find('.ready');

        me.addClass('hidden');
        cancel.addClass('hidden');
        inProcess.removeClass('hidden');
        loader.removeClass('hidden');

        var url = me.data('url');
        $.getJSON(url, {}, function(data){
            if(data.success) {
                var zipUrl = data.zipUrl;
                var amount = parseFloat($.trim($('#valor').val()));

                if(isNaN(amount)) {
                    amount = 0;
                }

                if (amount === 0) {
                    inProcess.addClass('hidden');
                    ready.removeClass('hidden');
                    initDownlaod(zipUrl);
                    setTimeout(function() {
                        $('.mozcu-descarga-modal').modal('hide');
                    }, 3000);
                } else {
                    $('#amount').val(amount);
                    $('#checkoutUrl').val(zipUrl);
                    window.onbeforeunload = null;
                    $('#paypalForm').submit();
                }
            }
        });
    });

    var initDownlaod = function(url) {
        var iframe = $('<iframe>', {width:'1', height:'1', frameborder:'0', src:url, id:'downloadAlbumIframe'});
        $('#downloadAlbumIframe').remove();
        $('.row.headerDisco').append(iframe);
    };

    // Modal compartir
    $('.mainContent').on('click', '#shareAlbum', function(e) {
        e.preventDefault();
        var me = $(this);

        var url = me.attr('href');
        $.getJSON(url, {}, function(data){
            $(data.html).modal();
        });
    });

    // Modal denunciar obra
    $('.mainContent').on('click', '#reportAlbum', function(e) {
        e.preventDefault();
        var me = $(this);

        var url = me.attr('href');
        $.getJSON(url, {}, function(data){
            $(data.html).modal();
        });
    });

    // Enviar formulario de denuncia
    $('body').on('click', '.modal-report-album .btn-success', function(e) {
        e.preventDefault();
        var me = $(this);

        var url = me.data('url');
        $.post(url, {}, function(data) {
            // TODO
        });
    });

    // Ir al disco
    $('.mainContent').on('click', '.album .albumLink', function(e) {
      e.preventDefault();
      var me = $(this);

      $.getJSON(me.attr('href'), {}, function(data) {
        if(data.success) {
          $('.mainContent').html(data.html);
        }
      });
    });

    // Ir al perfil del usuario
    $('.mainContent').on('click', '.album .profileLink', function(e) {
      e.preventDefault();
      var me = $(this);

      $.getJSON(me.attr('href'), {}, function(data) {
        if(data.success) {
          $('.mainContent').html(data.html);
        }
      });
    });

    // Subido por
    $('.mainContent').on('click', '.headerDisco .nombreAlbumUser a', function(e) {
      e.preventDefault();
      var url = $(this).attr('href');

      $.getJSON(url, {}, function(data) {
        if(data.success) {
          $('.mainContent').html(data.html);
        }
      });
    });

    // click en tags de informacion
    $('.mainContent').on('click', '.infoDisco .tag', function(e) {
      e.preventDefault();
      var url = $(this).attr('href');

      $.getJSON(url, {}, function(data) {
        if(data.success) {
          $('.mainContent').html(data.html);
        }
      });
    });

    var searchAlbums = function() {
        var container = $('.pageDiscListen .wrapperDiscListen');
        var tags = new Array();
        $( ".pageDiscListen .wrapperCategories .category").each(function(key, value) {
            tags.push($(value).attr('id'));
        });

        var url = $('#findAlbumsByTagUrl').val();
        $.post(url, {tags: tags}, function(data){
            if (data.success) {
                container.html('');
                for(key in data.html) {
                    container.append($(data.html[key]));
                }
            }
        }, 'json');
    };

    // Album favorito
    $('.mainContent').on('click', '#likeAlbum', function(e) {
        e.preventDefault();
        var me = $(this);

        $.post(me.attr('href'), function(data) {
            if(data.success) {
                if(data.action == 'unlike') {
                    me.addClass('unlike');
                } else {
                    me.removeClass('unlike');
                }
            }
        }, 'json');
    });

});<|endoftext|>


<commit_before>(function () {
    var app = angular.module("gameApp", []).config(function ($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    });

    var evtSource = new EventSource("GameServlet");
    var me;

    app.run(['$rootScope', '$http', function ($rootScope, $http) {
        $rootScope.userName = null;
        evtSource.addEventListener("username", function (e) {
            $rootScope.nameObj = JSON.parse(e.data);
            $rootScope.userName = $rootScope.nameObj.Username;
            $rootScope.$apply();
        }, false);

        evtSource.addEventListener("gamelist", function (e) {
            $rootScope.lobbyObj = JSON.parse(e.data);
            $rootScope.lobbyList = $rootScope.lobbyObj.GameList;
            $rootScope.$apply();
        }, false);

        evtSource.addEventListener("gamestate", function (e) {
            $rootScope.obj = JSON.parse(e.data);
            $rootScope.Game = $rootScope.obj.Game;
            $rootScope.GameState = $rootScope.Game.GameState;
            $rootScope.players = $rootScope.Game.Players;
            $rootScope.board = $rootScope.Game.Board;
            $rootScope.gameStarted = $rootScope.GameState.LobbyClosed;
            $rootScope.countryCount = $rootScope.GameState.Unassigned;
            $rootScope.phase = $rootScope.GameState.Phase;
            $rootScope.CurrentPlayer = $rootScope.GameState.CurrentPlayer;
            $rootScope.lobbySize = 6;
            $rootScope.playerString = "player";

            //sets first player to host
            if ($rootScope.players.length !== 0) {
                $rootScope.host = $rootScope.players[0].DisplayName;
            }

            for (var i = 0; i < $rootScope.players.length; i++) {
                if ($rootScope.players[i].DisplayName === $rootScope.userName) {
                    $rootScope.thisUserNumber = i;
                }
                else {
                    console.log("NO USER NUMBER FOR YOU!");
                }

                if ($rootScope.CurrentPlayer === $rootScope.players[i].PlayerOrder) {
                    $rootScope.currentUserName = $rootScope.players[i].DisplayName;
                    $rootScope.troopsToDeploy = $rootScope.players[i].troopsToDeploy;
                }
            }

            if ($rootScope.host === $rootScope.userName) {
                if ($rootScope.phase === "Setup" && $rootScope.countryCount === 0) {
                    var endPhaseData = JSON.stringify({Command: "EndPhase", Data: {CurrentPlayer: $rootScope.CurrentPlayer}});
                    postData(endPhaseData);
                }
            }
            //sends out end phase when the last player has finished deploying
            if ($rootScope.phase === "Deploy" && $rootScope.players[$rootScope.players.length - 1].troopsToDeploy === 0) {
                var endPhaseData = JSON.stringify({Command: "EndPhase", Data: {CurrentPlayer: $rootScope.CurrentPlayer}});
                postData(endPhaseData);
            }
            //if current players trooptodeploy has diminished, switch player
            if ($rootScope.phase === "Deploy" && $rootScope.players[$rootScope.CurrentPlayer].troopsToDeploy === 0) {
                var endTroopDeployData = JSON.stringify({Command: "EndTurn", Data: {CurrentPlayer: $rootScope.CurrentPlayer}});
                postData(endTroopDeployData);
            }
            $rootScope.$apply();

            function postData(data) {
                $http({
                    method: 'POST',
                    url: 'GameServlet',
                    headers: {'Content-Type': 'application/json'},
                    data: data
                }).error();
            }
            function discoverOrderNo(name) {
                angular.forEach($rootScope.players, function (index) {
                    if (index.DisplayName === name) {
                        me = index.PlayerOrder;
                    }
                });
            }
            color($rootScope);
        }, false);
    }]);

    function color($rootScope) {
        angular.forEach($rootScope.board, function (country) {
            if (country.Owner === -1) {
                $rootScope.mapList[country.CountryID].attr("fill", "black");
            }
            else if (country.Owner === 0) {
                $rootScope.mapList[country.CountryID].attr("fill", "#FF3B30");
            }
            else if (country.Owner === 1) {
                $rootScope.mapList[country.CountryID].attr("fill", "#00ff1b");
            }
            else if (country.Owner === 2) {
                $rootScope.mapList[country.CountryID].attr("fill", "#ff5400");
            }
            else if (country.Owner === 3) {
                $rootScope.mapList[country.CountryID].attr("fill", "#4A4A4A");
            }
            else if (country.Owner === 4) {
                $rootScope.mapList[country.CountryID].attr("fill", "#6f3ed6");
            }
            else if (country.Owner === 5) {
                $rootScope.mapList[country.CountryID].attr("fill", "#007AFF");
            }
        });
    }

    app.directive("rightBox", function () {
        return{
            restrict: "E",
            templateUrl: "html/right-box.html"
        };
    });
    app.directive("leftBox", function () {
        return{
            restrict: "E",
            templateUrl: "html/left-box.html"
        };
    });
    app.directive("gameLobby", function () {
        return{
            restrict: "E",
            templateUrl: "html/game-lobby.html"
        };
    });
    app.directive("loginBox", function () {
        return{
            restrict: "AEC",
            templateUrl: "html/login-box.html"
        };
    });
})();<commit_msg>re-fixed troop count reflection bug<commit_after>(function () {
    var app = angular.module("gameApp", []).config(function ($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    });

    var evtSource = new EventSource("GameServlet");
    var me;

    app.run(['$rootScope', '$http', function ($rootScope, $http) {
        $rootScope.userName = null;
        evtSource.addEventListener("username", function (e) {
            $rootScope.nameObj = JSON.parse(e.data);
            $rootScope.userName = $rootScope.nameObj.Username;
            $rootScope.$apply();
        }, false);

        evtSource.addEventListener("gamelist", function (e) {
            $rootScope.lobbyObj = JSON.parse(e.data);
            $rootScope.lobbyList = $rootScope.lobbyObj.GameList;
            $rootScope.$apply();
        }, false);

        evtSource.addEventListener("gamestate", function (e) {
            $rootScope.obj = JSON.parse(e.data);
            $rootScope.Game = $rootScope.obj.Game;
            $rootScope.GameState = $rootScope.Game.GameState;
            $rootScope.players = $rootScope.Game.Players;
            $rootScope.board = $rootScope.Game.Board;
            $rootScope.gameStarted = $rootScope.GameState.LobbyClosed;
            $rootScope.countryCount = $rootScope.GameState.Unassigned;
            $rootScope.phase = $rootScope.GameState.Phase;
            $rootScope.CurrentPlayer = $rootScope.GameState.CurrentPlayer;
            $rootScope.lobbySize = 6;
            $rootScope.playerString = "player";

            //sets first player to host
            if ($rootScope.players.length !== 0) {
                $rootScope.host = $rootScope.players[0].DisplayName;
            }

            for (var i = 0; i < $rootScope.players.length; i++) {
                if ($rootScope.players[i].DisplayName === $rootScope.userName) {
                    $rootScope.thisUserNumber = i;
                }
                else {
                    console.log("NO USER NUMBER FOR YOU!");
                }

                if ($rootScope.CurrentPlayer === $rootScope.players[i].PlayerOrder) {
                    $rootScope.currentUserName = $rootScope.players[i].DisplayName;
                    $rootScope.troopsToDeploy = $rootScope.players[i].TroopsToDeploy;
                }
            }

            if ($rootScope.host === $rootScope.userName) {
                if ($rootScope.phase === "Setup" && $rootScope.countryCount === 0) {
                    var endPhaseData = JSON.stringify({Command: "EndPhase", Data: {CurrentPlayer: $rootScope.CurrentPlayer}});
                    postData(endPhaseData);
                }
            }
            //sends out end phase when the last player has finished deploying
            if ($rootScope.phase === "Deploy" && $rootScope.players[$rootScope.players.length - 1].troopsToDeploy === 0) {
                var endPhaseData = JSON.stringify({Command: "EndPhase", Data: {CurrentPlayer: $rootScope.CurrentPlayer}});
                postData(endPhaseData);
            }
            //if current players trooptodeploy has diminished, switch player
            if ($rootScope.phase === "Deploy" && $rootScope.players[$rootScope.CurrentPlayer].troopsToDeploy === 0) {
                var endTroopDeployData = JSON.stringify({Command: "EndTurn", Data: {CurrentPlayer: $rootScope.CurrentPlayer}});
                postData(endTroopDeployData);
            }
            $rootScope.$apply();

            function postData(data) {
                $http({
                    method: 'POST',
                    url: 'GameServlet',
                    headers: {'Content-Type': 'application/json'},
                    data: data
                }).error();
            }
            function discoverOrderNo(name) {
                angular.forEach($rootScope.players, function (index) {
                    if (index.DisplayName === name) {
                        me = index.PlayerOrder;
                    }
                });
            }
            color($rootScope);
        }, false);
    }]);

    function color($rootScope) {
        angular.forEach($rootScope.board, function (country) {
            if (country.Owner === -1) {
                $rootScope.mapList[country.CountryID].attr("fill", "black");
            }
            else if (country.Owner === 0) {
                $rootScope.mapList[country.CountryID].attr("fill", "#FF3B30");
            }
            else if (country.Owner === 1) {
                $rootScope.mapList[country.CountryID].attr("fill", "#00ff1b");
            }
            else if (country.Owner === 2) {
                $rootScope.mapList[country.CountryID].attr("fill", "#ff5400");
            }
            else if (country.Owner === 3) {
                $rootScope.mapList[country.CountryID].attr("fill", "#4A4A4A");
            }
            else if (country.Owner === 4) {
                $rootScope.mapList[country.CountryID].attr("fill", "#6f3ed6");
            }
            else if (country.Owner === 5) {
                $rootScope.mapList[country.CountryID].attr("fill", "#007AFF");
            }
        });
    }

    app.directive("rightBox", function () {
        return{
            restrict: "E",
            templateUrl: "html/right-box.html"
        };
    });
    app.directive("leftBox", function () {
        return{
            restrict: "E",
            templateUrl: "html/left-box.html"
        };
    });
    app.directive("gameLobby", function () {
        return{
            restrict: "E",
            templateUrl: "html/game-lobby.html"
        };
    });
    app.directive("loginBox", function () {
        return{
            restrict: "AEC",
            templateUrl: "html/login-box.html"
        };
    });
})();<|endoftext|>


<commit_before>'use strict';

console.log('loading config');
L.Util.ajax('config.json').then(function(config){
    var map = L.map('map');

    if (config.map){
        if (!location.hash) {
            map.setView(config.map.center, config.map.zoom);
        }
        if (config.map.maxZoom){
            map.options.maxZoom = config.map.maxZoom;
        }
        if (config.map.maxBounds){
            //var bounds = L.LatLngBounds(config.map.maxBounds[0], config.map.maxBounds[1]);
            map.setMaxBounds(config.map.maxBounds);
        }
    }
    map.addHash();

    var mq = L.tileLayer('http://tiles.mapc.org/basemap/{z}/{x}/{y}.png', {
	    attribution: 'Tiles Courtesy of MAPC — Map data © MassGIS',
	    subdomains: '1234'
    }).addTo(map);

    console.log('loading geojson');
    L.Util.ajax('data.geojson').then(function(data){
        //var layers = L.control.layers().addTo(map);

        var bindPopup = function(feature, layer) {
            console.log("running feature function");
            console.log(feature.properties.address);
            //layer.on({
            //    mouseover: highlightFeature,
            //    mouseout: resetHighlight,
            //    click: zoomToFeature
            //});

            //console.log(layer);
            if (config.properties && feature.properties) {
                layer.bindPopup(createPopup(config.properties, feature.properties));
            }
        };
        console.log(data);

        L.geoJson(data, {onEachFeature: bindPopup}).addTo(map);
    });
});
<commit_msg>panning onclick<commit_after>'use strict';

console.log('loading config');
L.Util.ajax('config.json').then(function(config){
    var map = L.map('map');

    if (config.map){
        if (!location.hash) {
            map.setView(config.map.center, config.map.zoom);
        }
        if (config.map.maxZoom){
            map.options.maxZoom = config.map.maxZoom;
        }
        if (config.map.maxBounds){
            //var bounds = L.LatLngBounds(config.map.maxBounds[0], config.map.maxBounds[1]);
            map.setMaxBounds(config.map.maxBounds);
        }
    }
    map.addHash();

    var mq = L.tileLayer('http://tiles.mapc.org/basemap/{z}/{x}/{y}.png', {
	    attribution: 'Tiles Courtesy of MAPC — Map data © MassGIS',
	    subdomains: '1234'
    }).addTo(map);

    console.log('loading geojson');
    L.Util.ajax('data.geojson').then(function(data){
        //var layers = L.control.layers().addTo(map);

        var onClick = function(e){
            console.log("click");
            zoomToElement(e);
            fillInfobox(e);
        };

        var zoomToElement = function(e){
            console.log(e);
            map.panTo(e.latlng);
        };

        var fillInfobox = function(e){
        };

        var bindPopup = function(feature, layer) {
            console.log("running feature function");
            console.log(feature.properties.address);
            layer.on({
                click: onClick
            });

            //console.log(layer);
            if (config.properties && feature.properties) {
                layer.bindPopup(createPopup(config.properties, feature.properties));
            }
        };
        console.log(data);

        L.geoJson(data, {onEachFeature: bindPopup}).addTo(map);
    });

    map.addControl();

    //use locate() to geolocate
});

<|endoftext|>


<commit_before>/*globals console, d3, jQuery, tangelo */

(function ($) {
    "use strict";

    $.fn.landingPage = function (cfg) {
        var specFile,
            appLeftSelector,
            appRightSelector,
            extLeftSelector,
            extRightSelector,
            container;

        // Pull values from the config object argument.
        specFile = cfg.specFile;
        appLeftSelector = cfg.appLeftSelector;
        appRightSelector = cfg.appRightSelector;
        extLeftSelector = cfg.extLeftSelector;
        extRightSelector = cfg.extRightSelector;

        // Create a d3 selection out of the target element.
        container = d3.select(this[0]);

        // Retrieve the contents of the specification file, then build up the
        // page.
        d3.json(specFile, function (err, spec) {
            var app,
                apps,
                col,
                cols,
                external,
                i,
                left,
                right,
                text;

            if (err !== null) {
                console.log("fatal error: could not load app list from " + specFile);
                return;
            }

            // Pull out the two lists in the specification - one for the list of
            // apps, and one for the list of external links.
            apps = spec.apps;
            external = spec.external;

            if (apps !== undefined) {
                if (!tangelo.allDefined(appLeftSelector, appRightSelector)) {
                    throw "Required config argument property appLeftSelector or appRightSelector missing!";
                }

                // Grab a reference to each of the two index columns.
                left = container.select(appLeftSelector);
                right = container.select(appRightSelector);
                cols = [left, right];

                // Place the app info/links into the two columns, alternating
                // between left and right.
                for (i = 0; i < apps.length; i = i + 1) {
                    col = cols[i % 2];
                    app = apps[i];

                    col.append("a")
                        .attr("href", "/app/" + app.path + "/")
                        .append("h4")
                        .html(app.name);
                    col.append("p")
                        .html(app.description);
                }
            }

            if (external !== undefined) {
                if (!tangelo.allDefined(extLeftSelector, extRightSelector)) {
                    throw "Required config argument property extLeftSelector or extRightSelector missing!";
                }

                // List out the external links in the two columns, as above.
                left = container.select(extLeftSelector);
                right = container.select(extRightSelector);
                cols = [left, right];
                text = function (d) {
                    return "" + "" + d.name + "" + "" +
                        " (" + d.institution + ") - " +
                        d.description;
                };
                for (i = 0; i < external.length; i = i + 1) {
                    col = cols[i % 2];
                    app = external[i];

                    col.append("div")
                        .html(text(app));
                }
            }
        });
    };
}(jQuery));
<commit_msg>Making landing page stuff more general - no longer assumes a particular shape for application URLs.<commit_after>/*globals console, d3, jQuery, tangelo */

(function ($) {
    "use strict";

    $.fn.landingPage = function (cfg) {
        var specFile,
            appLeftSelector,
            appRightSelector,
            extLeftSelector,
            extRightSelector,
            container;

        // Pull values from the config object argument.
        specFile = cfg.specFile;
        appLeftSelector = cfg.appLeftSelector;
        appRightSelector = cfg.appRightSelector;
        extLeftSelector = cfg.extLeftSelector;
        extRightSelector = cfg.extRightSelector;

        // Create a d3 selection out of the target element.
        container = d3.select(this[0]);

        // Retrieve the contents of the specification file, then build up the
        // page.
        d3.json(specFile, function (err, spec) {
            var app,
                apps,
                col,
                cols,
                external,
                i,
                left,
                right,
                text;

            if (err !== null) {
                console.log("fatal error: could not load app list from " + specFile);
                return;
            }

            // Pull out the two lists in the specification - one for the list of
            // apps, and one for the list of external links.
            apps = spec.apps;
            external = spec.external;

            if (apps !== undefined) {
                if (!tangelo.allDefined(appLeftSelector, appRightSelector)) {
                    throw "Required config argument property appLeftSelector or appRightSelector missing!";
                }

                // Grab a reference to each of the two index columns.
                left = container.select(appLeftSelector);
                right = container.select(appRightSelector);
                cols = [left, right];

                // Place the app info/links into the two columns, alternating
                // between left and right.
                for (i = 0; i < apps.length; i = i + 1) {
                    col = cols[i % 2];
                    app = apps[i];

                    col.append("a")
                        .attr("href", app.path)
                        .append("h4")
                        .html(app.name);
                    col.append("p")
                        .html(app.description);
                }
            }

            if (external !== undefined) {
                if (!tangelo.allDefined(extLeftSelector, extRightSelector)) {
                    throw "Required config argument property extLeftSelector or extRightSelector missing!";
                }

                // List out the external links in the two columns, as above.
                left = container.select(extLeftSelector);
                right = container.select(extRightSelector);
                cols = [left, right];
                text = function (d) {
                    return "" + "" + d.name + "" + "" +
                        " (" + d.institution + ") - " +
                        d.description;
                };
                for (i = 0; i < external.length; i = i + 1) {
                    col = cols[i % 2];
                    app = external[i];

                    col.append("div")
                        .html(text(app));
                }
            }
        });
    };
}(jQuery));
<|endoftext|>


<commit_before>var user = {
name: null,
health: 40,
wins: 0,
attack: getNum(1,3),
heal: 0,
healCount: 0
}

var compPlayer = {
name: 'Grant Chirpus',
health:  10,
wins: 0,
attack: getNum(1,5)
}

let pointsNeededToWin = 3;
let healthDepleted = 0;

function healUser(playerOne) {
  if (playerOne.healCount = 2) {
    console.log('get out.');
    decidingPrompt();
  } else {
    var addHealth = getNum(1,10);
    playerOne.health = playerOne.health + addHealth;
    playerOne.healCount++;
    decidingPrompt();
  }
}

function startGame(playerOne, playerTwo) {

  var gameStartPrompt = prompt ('Do you dare enter the Dungeon?');
  var consent = 'yes';
  var checkGamePrompt = gameStartPrompt === consent;
  var playFalse = 'Rerun code to play game.';

  if (checkGamePrompt !== true) {

      console.log(playFalse);

    } else {
      playerOne.name = prompt('Enter your wizarding name!');

      if (playerOne.name !== null) {

        console.log(playerOne.name + ' enters the dungeon...');

        startCombat(playerOne, playerTwo);

      } else {
        playerOne.name = prompt('You did not enter a name.. Enter your wizarding name!');
        return;
      }
    }

}

function getNum(min, max) {
  var min;
  var max;
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random(min, max) * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

function endGame(playerOne, playerTwo) {
  if (playerOne.health < healthDepleted) {
    console.log(playerOne.name + ' Lost');
  } else {
    console.log(playerTwo.name + ' Lost');
  }
  console.log('game over');

  playerTwo.health = 10;
  playerOne.health = 40;
  playerOne.wins = 0;
}

function startCombat(playerOne, playerTwo) {

  while (playerOne.wins < pointsNeededToWin && playerOne.health >=healthDepleted) {// Rounds needed to win

    while (playerOne.health >= healthDepleted && playerTwo.health >= healthDepleted) {

        decidingPrompt();
        function decidingPrompt()  {
          if (decider = prompt('Would you like Attack, Heal, or Quit?') === 'Attack') {
            console.log(playerOne.name + ' decides to attack.');
            attack();
          } else if (decider === 'Heal'){ // Warning this is doing an infinite Loop... D:
            healUser();
            console.log(playerOne.name + ' has healed. ' + playerOne.name + ' has ' + playerOne.health + ' health.' );
          } else {
            console.log(playerOne.name + ' has Quit the game.');
            return;
          }
        }

        function attack() {

          playerTwo.health = playerTwo.health - playerOne.attack;
          playerOne.health = playerOne.health - playerTwo.attack;

          console.log(playerOne.name + ' has ' + playerOne.health + ' health..');
          console.log(playerTwo.name + ' has ' + playerTwo.health + ' health..');
        }

      }

      console.log('round over')
      playerOne.wins++;
      playerTwo.health = 10;
    }
    endGame(playerOne, playerTwo);
}

// Not using this code. We would use this if we used classes instead of Objects

// class CompPlayer {
//   constructor(name) {
//     this.name = 'Grant Chirpus';
//     this.health = 10;
//   }
//   attack() {
//     getNum(0, 5);
//   }
// }
//
// class User extends CompPlayer {
//   constructor(name) {
//     super(name);
//     this.name = 'height';
//     this.heath = 40;
//     this.wins = 0;
//   }
//   heal() {
//     getNum(0, 3);
//   }
// }
<commit_msg>Add shit that doesnt work<commit_after>var user = {
name: null,
health: 40,
wins: 0,
attack: getNum(1,3),
heal: 0,
healCount: 0
}

var compPlayer = {
name: 'Grant Chirpus',
health:  10,
wins: 0,
attack: getNum(1,5)
}

let pointsNeededToWin = 3;
let healthDepleted = 0;

function decidingPrompt(playerOne)  {
  var decider = prompt('Would you like Attack, Heal, or Quit?')
  if (decider === 'Attack') {
    console.log(playerOne.name + ' decides to attack.');
    attack(playerOne, playerTwo);
  } else if (decider === 'Heal'){ // Warning this is doing an infinite Loop... D:
    healUser(playerOne);
    console.log(playerOne.name + ' has healed. ' + playerOne.name + ' has ' + playerOne.health + ' health.' );
  } else if(decider === 'Quit') {
    console.log(playerOne.name + ' has Quit the game.');
    return;
  }
}

function healUser(playerOne) {
  if (playerOne.healCount = 2) {
    console.log('get out.');
    decidingPrompt();
  } else {
    var addHealth = getNum(1,10);
    playerOne.health = playerOne.health + addHealth;
    playerOne.healCount++;
    decidingPrompt();
  }
}

function attack(playerOne, playerTwo) {

  playerTwo.health = playerTwo.health - playerOne.attack;
  playerOne.health = playerOne.health - playerTwo.attack;

  console.log(playerOne.name + ' has ' + playerOne.health + ' health..');
  console.log(playerTwo.name + ' has ' + playerTwo.health + ' health..');
}

function startGame(playerOne, playerTwo) {

  var gameStartPrompt = prompt ('Do you dare enter the Dungeon?');
  var consent = 'yes';
  var checkGamePrompt = gameStartPrompt === consent;
  var playFalse = 'Rerun code to play game.';

  if (checkGamePrompt !== true) {

      console.log(playFalse);

    } else {
      playerOne.name = prompt('Enter your wizarding name!');

      if (playerOne.name !== null) {

        console.log(playerOne.name + ' enters the dungeon...');

        startCombat(playerOne, playerTwo);

      } else {
        playerOne.name = prompt('You did not enter a name.. Enter your wizarding name!');
        return;
      }
    }

}

function getNum(min, max) {
  var min;
  var max;
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random(min, max) * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

function endGame(playerOne, playerTwo) {
  if (playerOne.health < healthDepleted) {
    console.log(playerOne.name + ' Lost');
  } else {
    console.log(playerTwo.name + ' Lost');
  }
  console.log('game over');

  playerTwo.health = 10;
  playerOne.health = 40;
  playerOne.wins = 0;
}

function startCombat(playerOne, playerTwo) {

  while (playerOne.wins < pointsNeededToWin && playerOne.health >=healthDepleted) {// Rounds needed to win

    while (playerOne.health >= healthDepleted && playerTwo.health >= healthDepleted) {

        decidingPrompt();

      console.log('round over')
      playerOne.wins++;
      playerTwo.health = 10;
    }
    endGame(playerOne, playerTwo);
  }

}

// Not using this code. We would use this if we used classes instead of Objects

// class CompPlayer {
//   constructor(name) {
//     this.name = 'Grant Chirpus';
//     this.health = 10;
//   }
//   attack() {
//     getNum(0, 5);
//   }
// }
//
// class User extends CompPlayer {
//   constructor(name) {
//     super(name);
//     this.name = 'height';
//     this.heath = 40;
//     this.wins = 0;
//   }
//   heal() {
//     getNum(0, 3);
//   }
// }
<|endoftext|>