<commit_before>FlowRouter.route("/projects", {
  action: function (params) {
    BlazeLayout.render("mainLayout", {main: "viewProjects"});
  }
});

FlowRouter.route("/projects/add", {
  action: function (params) {
    BlazeLayout.render("mainLayout", {main: "addProject"});
  }
});

JsonRoutes.add("get", "/projects/:projectId", function (req, res, next) {
  var projectId = req.params.projectId;

  JsonRoutes.sendResult(res, 200, Projects.findOne(projectId));
});

JsonRoutes.add("get", "/projects", function (req, res, next) {

  JsonRoutes.sendResult(res, 200, Projects.find().fetch());
});
<commit_msg>Added comments and allProjects variable<commit_after>FlowRouter.route("/projects", {
  action: function (params) {
    BlazeLayout.render("mainLayout", {main: "viewProjects"});
  }
});

FlowRouter.route("/projects/add", {
  action: function (params) {
    BlazeLayout.render("mainLayout", {main: "addProject"});
  }
});

// Return a single JSON object containing the specified project.
JsonRoutes.add("get", "/projects/:projectId", function (req, res, next) {
  var projectId = req.params.projectId;

  JsonRoutes.sendResult(res, 200, Projects.findOne(projectId));
});

// Returns JSON array containing all projects in Projects collection.
JsonRoutes.add("get", "/projects", function (req, res, next) {
    var allProjects = Projects.find().fetch();
  JsonRoutes.sendResult(res, 200, allProjects);
});
<|endoftext|>


<commit_before>var me = {
    fetch: [
        function(fetched_elts) {
            return '/v1/users/self';
        }
    ],
    params: {},
    fields: {
        id: function(me) {
            return me.data.id || undefined;
        },
        alias: function(me) {
            return me.data.username || undefined;
        },
        name: function(me) {
            return me.data.full_name || undefined;
        },
        avatar: function(me) {
            return me.data.profile_picture || undefined;
        }
    }
};
module.exports = me;
<commit_msg>instagram profile url<commit_after>var me = {
    fetch: [
        function(fetched_elts) {
            return '/v1/users/self';
        }
    ],
    params: {},
    fields: {
        id: function(me) {
            return me.data.id || undefined;
        },
        alias: function(me) {
            return me.data.username || undefined;
        },
        name: function(me) {
            return me.data.full_name || undefined;
        },
        avatar: function(me) {
            return me.data.profile_picture || undefined;
        },
        url: function(me) {
            return 'https://instagram.com/' + me.data.username;
        }
    }
};
module.exports = me;
<|endoftext|>


<commit_before>/* global SVG, jQuery */
/* exported eisenhowerGraph */

/**
 * @todo improve onclick task creation url generation
 * @todo improve task colour selection
 * @todo add hover events for tasks?
 */

var eisenhowerGraph = (function( window, document, SVG, $, undefined ) {
  /**
   * Generate a random pastel colour
   * @return {String} CSS style hex colour value
   */
  function randColor() {
    var getVal = function() {
      return ( Math.round( Math.random() * 110 ) + 110 ).toString( 16 );
    };

    var r = getVal();
    var g = getVal();
    var b = getVal();

    return '#' + r + g + b;
  }

  /**
   * Round a number to 2 decimal places
   * @param  {Number} num Number to round
   * @return {Number}     Number to 2 decimal places
   */
  function round2dp( num ) {
    return Math.round( num * 100 ) / 100;
  }

  /**
   * Get cursor location within the given SVG context
   *
   * @param  {MouseEvent} event MouseEvent object.
   * @param  {Object}     graph Graph (SVGJS) object as context.
   * @return {Object}           Information about the location of the cursor.
   */
  function cursorLocation( event, graph ) {
    var point = graph.node.createSVGPoint();

    point.x = event.clientX;
    point.y = event.clientY;
    point = point.matrixTransform( graph.node.getScreenCTM().inverse() );

    return point;
  }

  /**
   * Plot a task on a graph
   *
   * @param  {Object} task      Task object from the API
   * @param  {Object} graph     Graph (SVGJS) object
   * @param  {String} [color]   Optional predefined colour for the task.
   * @param  {Number} [opacity] Optional predefined opacity for the task.
   * @return {Object}           SVGJS object for the plotted task
   */
  function plotTask( task, graph, color, opacity ) {
    color = color || randColor();
    opacity = opacity || 1;

    var plot = graph.group().attr( 'class', 'task' );

    // add base circle
    plot.add( graph.circle( 30 ).fill( color ) );

    // add icon to center of plot
    plot.add( graph.text( 'x' ).fill( '#ffffff' ) );
    plot.last().center( plot.first().attr( 'cx' ), plot.first( 'cy' ) );

    plot.opacity( opacity );

    // adjust task coordinates to work on SVG coordinate system
    // Math: plot_coord = ( graph_width / 2 ) + ( ( ( graph_width / 2 ) / 100 ) * task_coord )
    var coordX = 250 + ( 2.5 * task.coordX );
    // we have to invert the value of Y here as svg is from top left not bottom left
    var coordY = 250 + ( 2.5 * -task.coordY );

    // center plot on task coordinates
    plot.center( coordX, coordY );

    // add task details to plot
    plot.data( 'task', task );

    // handle events for this plot
    plot.on( 'mouseenter', function() {
      graph.preventPlot = true;
    });
    plot.on( 'mouseleave', function() {
      graph.preventPlot = false;
    });

    // highlight task if needed
    if( graph.highlightTask ) {
      if( task.id === graph.highlightTask ) {
        plot.scale( 1.5, 1.5 );
      }
      else {
        plot.opacity( opacity * 0.4 );
      }
    }

    return plot;
  }

  var graphs = [];

  // get all graph wrappers
  $( '.eisenhower-graph' ).each( function() {
    // generate a unique id for each graph
    var graphId = 'graph-' + (new Date()).valueOf();
    var $self = $( this );
    $self.attr( 'id', graphId );

    // init graph w/ a blank SVG
    var graph = new SVG( graphId ).attr({
      viewBox: '0 0 500 500',
      x: '0px',
      y: '0px',
      width: $self.data( 'graphSize' ),
      height: $self.data( 'graphSize' ),
      class: 'img-responsive'
    });
    graphs.push( graph );

    graph.highlightTask = $self.data( 'highlightTask' );

    // draw axes on graph
    var axes = graph.group();
    axes.add( graph.line( 20, 250, 480, 250 ).stroke( { width: 1, color: '#444' } ) );
    axes.add( graph.line( 250, 20, 250, 480 ).stroke( { width: 1, color: '#444' } ) );
    // add arrow heads
    axes.add( graph.path( 'M 250 20 C 254 28, 258 30, 252 32 L 250 31, 248 32 C 242 30, 246 28, 250 20 Z' ).style( { fill: '#444', stroke: '#444' } ) );
    axes.add( graph.path( 'M 480 250 C 472 254, 470 258, 468 252 L 469 250, 468 248 C 470 242, 472 246, 480 250 Z' ).style( { fill: '#444', stroke: '#444' } ) );

    // get topic tasks if they exist
    if( $self.data( 'topicId' ) ) {
      $.getJSON( '/api/topics/' + $self.data( 'topicId' ) + '/tasks', function( data ) {
        data.forEach( function( task ) {
          plotTask( task, graph );
        });
      });
    }

    // get tasks from json api
    if( $self.data( 'tasksUrl' ) ) {
      $.getJSON( $self.data( 'tasksUrl' ), function( data ) {
        data.forEach( function( task ) {
          plotTask( task, graph );
        });
      });
    }

    // plot a point using x,y coord
    if( ( $self.data( 'x' ) !== undefined ) && ( $self.data( 'x' ) !== undefined ) ) {
      // plot point
      var xyPlot = graph.group();

      // add base circle
      xyPlot.add( graph.circle( 30 ).fill( randColor() ) );

      // add icon to center of plot
      xyPlot.add( graph.text( 'x' ).fill( '#ffffff' ) );
      xyPlot.last().center( xyPlot.first().attr( 'cx' ), xyPlot.first( 'cy' ) );

      // center plot on task coordinates
      xyPlot.center( ( 250 + ( 2.5 * $self.data( 'x' ) ) ), ( 250 + ( 2.5 * -$self.data( 'y' ) ) ) );
    }

    if( $self.data( 'graphNewTask' ) ) {
      // prevent default graph behaviour
      $self.data( 'graphReadonly', true );

      // on click move xyPlot
      graph.on( 'click', function( event ) {
        var loc = cursorLocation( event, graph );

        // move plot
        xyPlot.center( loc.x, loc.y );

        // update data attributes to reflect change
        $self.attr( 'data-x', round2dp( ( loc.x - 250 ) / 2.5 ) );
        $self.attr( 'data-y', round2dp( -( loc.y - 250 ) / 2.5 ) );
      });
    }

    // handle graph events
    if( ! $self.data( 'graphReadonly' ) ) {
      // on click plot new point and confirm new task
      graph.on( 'click', function( event ) {
        if( ! graph.preventPlot ) {
          var loc = cursorLocation( event, graph );

          // plot point
          var plot = graph.group();

          // add base circle
          plot.add( graph.circle( 30 ).fill( randColor() ) );

          // add icon to center of plot
          plot.add( graph.text( 'x' ).fill( '#ffffff' ) );
          plot.last().center( plot.first().attr( 'cx' ), plot.first( 'cy' ) );

          // center plot on task coordinates
          plot.center( loc.x, loc.y );

          // confirm new task
          if( window.confirm( 'Add new task here?' ) ) {
            // redirect to task creation
            window.location.href = '/tasks/create?' +
                                   ( $self.data( 'topicId' ) ? 'topic=' + $self.data( 'topicId' ) : '' ) +
                                   '&x=' + ( ( loc.x - 250 ) / 2.5 ) +
                                   '&y=' + ( -( loc.y - 250 ) / 2.5 );
          }
          else {
            plot.animate().attr( 'opacity', 0 ).after( function() {
              this.remove();
            });
          }
        }
      });
    }
  });

  return {
    graphs: graphs,
    plotTask: plotTask,
    cursorLocation: cursorLocation
  };
})( window, document, SVG, jQuery );
<commit_msg>Better colour selection for usage, and enhanced interactions with tasks.<commit_after>/* global SVG, jQuery */
/* exported eisenhowerGraph */

/**
 * @todo improve onclick task creation url generation
 * @todo improve task colour selection
 * @todo add hover events for tasks?
 */

var eisenhowerGraph = (function( window, document, SVG, $, undefined ) {
  /**
   * Generate a random pastel colour
   * @return {String} CSS style hex colour value
   */
  function randColor() {
    var getVal = function() {
      return ( Math.round( Math.random() * 110 ) + 110 ).toString( 16 );
    };

    var r = getVal();
    var g = getVal();
    var b = getVal();

    return '#' + r + g + b;
  }

  /**
   * Round a number to 2 decimal places
   * @param  {Number} num Number to round
   * @return {Number}     Number to 2 decimal places
   */
  function round2dp( num ) {
    return Math.round( num * 100 ) / 100;
  }

  /**
   * Get cursor location within the given SVG context
   *
   * @param  {MouseEvent} event MouseEvent object.
   * @param  {Object}     graph Graph (SVGJS) object as context.
   * @return {Object}           Information about the location of the cursor.
   */
  function cursorLocation( event, graph ) {
    var point = graph.node.createSVGPoint();

    point.x = event.clientX;
    point.y = event.clientY;
    point = point.matrixTransform( graph.node.getScreenCTM().inverse() );

    return point;
  }

  /**
   * Returns a hex colour code dependant on provided state
   *
   * @todo choose colour based on value in css.
   *
   * @param  {String} state
   * @return {String}       hex colour code.
   */
  function stateColor( state ) {
    var map = {
      complete: '#4CAF50',
      incomplete: '#FF9800'
    };
    return map[ state ];
  }

  /**
   * Plot a task on a graph
   *
   * @param  {Object} task      Task object from the API
   * @param  {Object} graph     Graph (SVGJS) object
   * @param  {String} [color]   Optional predefined colour for the task.
   * @param  {Number} [opacity] Optional predefined opacity for the task.
   * @return {Object}           SVGJS object for the plotted task
   */
  function plotTask( task, graph, color, opacity ) {
    color = color || stateColor( task.state ) || '#2196F3';
    opacity = opacity || 1;

    var plot = graph.group().attr( 'class', 'task' );

    // add base circle
    plot.add( graph.circle( 30 ).fill( color ) );

    // add icon to center of plot
    plot.add( graph.text( 'x' ).fill( '#ffffff' ) );
    plot.last().center( plot.first().attr( 'cx' ), plot.first( 'cy' ) );

    plot.opacity( opacity );

    // adjust task coordinates to work on SVG coordinate system
    // Math: plot_coord = ( graph_width / 2 ) + ( ( ( graph_width / 2 ) / 100 ) * task_coord )
    var coordX = 250 + ( 2.5 * task.coordX );
    // we have to invert the value of Y here as svg is from top left not bottom left
    var coordY = 250 + ( 2.5 * -task.coordY );

    // center plot on task coordinates
    plot.center( coordX, coordY );

    // add task details to plot
    plot.data( 'task', task );

    // handle events for this plot
    plot.on( 'mouseenter', function() {
      graph.preventPlot = true;

      plot.animate( 400 ).scale( 1.7, 1.7 ).center( coordX, coordY );
    });
    plot.on( 'mouseleave', function() {
      graph.preventPlot = false;

      if( task.id === graph.highlightTask ) {
        plot.animate( 400 ).scale( 1.5, 1.5 ).center( coordX, coordY );
      }
      else {
        plot.animate( 400 ).scale( 1, 1 ).center( coordX, coordY );
      }
    });
    plot.on( 'click', function() {
      window.location.href = '/tasks/' + task.id;
    });

    // highlight task if needed
    if( graph.highlightTask ) {
      if( task.id === graph.highlightTask ) {
        plot.scale( 1.5, 1.5 );
      }
      else {
        plot.opacity( opacity * 0.4 );
      }
    }

    return plot;
  }

  var graphs = [];

  // get all graph wrappers
  $( '.eisenhower-graph' ).each( function() {
    // generate a unique id for each graph
    var graphId = 'graph-' + (new Date()).valueOf();
    var $self = $( this );
    $self.attr( 'id', graphId );

    // init graph w/ a blank SVG
    var graph = new SVG( graphId ).attr({
      viewBox: '0 0 500 500',
      x: '0px',
      y: '0px',
      width: $self.data( 'graphSize' ),
      height: $self.data( 'graphSize' ),
      class: 'img-responsive'
    });
    graphs.push( graph );

    graph.highlightTask = $self.data( 'highlightTask' );

    // draw axes on graph
    var axes = graph.group();
    axes.add( graph.line( 20, 250, 480, 250 ).stroke( { width: 1, color: '#444' } ) );
    axes.add( graph.line( 250, 20, 250, 480 ).stroke( { width: 1, color: '#444' } ) );
    // add arrow heads
    axes.add( graph.path( 'M 250 20 C 254 28, 258 30, 252 32 L 250 31, 248 32 C 242 30, 246 28, 250 20 Z' ).style( { fill: '#444', stroke: '#444' } ) );
    axes.add( graph.path( 'M 480 250 C 472 254, 470 258, 468 252 L 469 250, 468 248 C 470 242, 472 246, 480 250 Z' ).style( { fill: '#444', stroke: '#444' } ) );

    // get topic tasks if they exist
    if( $self.data( 'topicId' ) ) {
      $.getJSON( '/api/topics/' + $self.data( 'topicId' ) + '/tasks', function( data ) {
        data.forEach( function( task ) {
          plotTask( task, graph );
        });
      });
    }

    // get tasks from json api
    if( $self.data( 'tasksUrl' ) ) {
      $.getJSON( $self.data( 'tasksUrl' ), function( data ) {
        data.forEach( function( task ) {
          plotTask( task, graph );
        });
      });
    }

    // plot a point using x,y coord
    if( ( $self.data( 'x' ) !== undefined ) && ( $self.data( 'x' ) !== undefined ) ) {
      // plot point
      var xyPlot = graph.group();

      // add base circle
      xyPlot.add( graph.circle( 30 ).fill( $self.data( 'color' ) || '#2196F3' ) );

      // add icon to center of plot
      xyPlot.add( graph.text( 'x' ).fill( '#ffffff' ) );
      xyPlot.last().center( xyPlot.first().attr( 'cx' ), xyPlot.first( 'cy' ) );

      // center plot on task coordinates
      xyPlot.center( ( 250 + ( 2.5 * $self.data( 'x' ) ) ), ( 250 + ( 2.5 * -$self.data( 'y' ) ) ) );
    }

    if( $self.data( 'graphNewTask' ) ) {
      // prevent default graph behaviour
      $self.data( 'graphReadonly', true );
      graph.readonly = true;

      xyPlot.scale( 1.5, 1.5 );

      // on click move xyPlot
      graph.on( 'click', function( event ) {
        var loc = cursorLocation( event, graph );

        // move plot
        xyPlot.animate( 400 ).center( loc.x, loc.y );

        // update data attributes to reflect change
        $self.attr( 'data-x', round2dp( ( loc.x - 250 ) / 2.5 ) );
        $self.attr( 'data-y', round2dp( -( loc.y - 250 ) / 2.5 ) );
      });
    }

    // handle graph events
    if( ! $self.data( 'graphReadonly' ) ) {
      graph.readonly = true;
      // on click plot new point and confirm new task
      graph.on( 'click', function( event ) {
        if( ! graph.preventPlot ) {
          var loc = cursorLocation( event, graph );

          // plot point
          var plot = graph.group();

          // add base circle
          plot.add( graph.circle( 30 ).fill( '#2196F3' ) );

          // add icon to center of plot
          plot.add( graph.text( 'x' ).fill( '#ffffff' ) );
          plot.last().center( plot.first().attr( 'cx' ), plot.first( 'cy' ) );

          // center plot on task coordinates
          plot.center( loc.x, loc.y );

          // confirm new task
          if( window.confirm( 'Add new task here?' ) ) {
            // redirect to task creation
            window.location.href = '/tasks/create?' +
                                   ( $self.data( 'topicId' ) ? 'topic=' + $self.data( 'topicId' ) : '' ) +
                                   '&x=' + ( ( loc.x - 250 ) / 2.5 ) +
                                   '&y=' + ( -( loc.y - 250 ) / 2.5 );
          }
          else {
            plot.animate( 400 ).attr( 'opacity', 0 ).after( function() {
              this.remove();
            });
          }
        }
      });
    }
  });

  return {
    graphs: graphs,
    plotTask: plotTask,
    cursorLocation: cursorLocation
  };
})( window, document, SVG, jQuery );
<|endoftext|>


<commit_before>define([], function() {
    //Default configuration settings for the applciation. This is where you'll define things like a bing maps key,
    //default web map, default app color theme and more. These values can be overwritten by template configuration settings
    //and url parameters.
    var defaults = {
        "appid": "bAkrQgFPquOr8OXa",
        "webmap": "a30160193b1f4922be09d62940f65696",//"de5ae0c2040c49d38e9ea0637454ac73", // "0eece0d5de2140e9a44d8050f943fd18", "de5ae0c2040c49d38e9ea0637454ac73"
        "oauthappid": null, //"bAkrQgFPquOr8OXa", //"AFTKRmv16wj14N3z",
        //Group templates must support a group url parameter. This will contain the id of the group.
        //group: "",
        //Enter the url to the proxy if needed by the applcation. See the 'Using the proxy page' help topic for details
        //http://developers.arcgis.com/en/javascript/jshelp/ags_proxy.html
        "proxyurl": "",
        //Example of a template specific property. If your template had several color schemes
        //you could define the default here and setup configuration settings to allow users to choose a different
        //color theme.
        "theme": "blue",
        "bingmapskey": "", //Enter the url to your organizations bing maps key if you want to use bing basemaps
        "sharinghost": location.protocol + "//" + "www.arcgis.com" //Defaults to arcgis.com. Set this value to your portal or organization host name.
    };
    return defaults;
});<commit_msg>readded appid<commit_after>define([], function() {
    //Default configuration settings for the applciation. This is where you'll define things like a bing maps key,
    //default web map, default app color theme and more. These values can be overwritten by template configuration settings
    //and url parameters.
    var defaults = {
        "appid": "f7af18c42f3740d5abfa241e07874563",
        "webmap": "a30160193b1f4922be09d62940f65696",//"de5ae0c2040c49d38e9ea0637454ac73", // "0eece0d5de2140e9a44d8050f943fd18", "de5ae0c2040c49d38e9ea0637454ac73"
        "oauthappid": null, //"bAkrQgFPquOr8OXa", //"AFTKRmv16wj14N3z",
        //Group templates must support a group url parameter. This will contain the id of the group.
        //group: "",
        //Enter the url to the proxy if needed by the applcation. See the 'Using the proxy page' help topic for details
        //http://developers.arcgis.com/en/javascript/jshelp/ags_proxy.html
        "proxyurl": "",
        //Example of a template specific property. If your template had several color schemes
        //you could define the default here and setup configuration settings to allow users to choose a different
        //color theme.
        "theme": "blue",
        "bingmapskey": "", //Enter the url to your organizations bing maps key if you want to use bing basemaps
        "sharinghost": location.protocol + "//" + "www.arcgis.com" //Defaults to arcgis.com. Set this value to your portal or organization host name.
    };
    return defaults;
});<|endoftext|>


<commit_before>// works out the X, Y position of the click inside the canvas from the X, Y position on the page
function getPosition(mouseEvent, sigCanvas) {
   var x, y;
   if (mouseEvent.pageX != undefined && mouseEvent.pageY != undefined) {
      x = mouseEvent.pageX;
      y = mouseEvent.pageY;
   } else {
      x = mouseEvent.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      y = mouseEvent.clientY + document.body.scrollTop + document.documentElement.scrollTop;
   }

   return { X: x - sigCanvas.offsetLeft, Y: y - sigCanvas.offsetTop };
}

function initialize() {
   // get references to the canvas element as well as the 2D drawing context
   var sigCanvas = document.getElementById("canvasSignature");
   var context = sigCanvas.getContext("2d");
   context.strokeStyle = 'Black';

   // This will be defined on a TOUCH device such as iPad or Android, etc.
   var is_touch_device = 'ontouchstart' in document.documentElement;

   if (is_touch_device) {
      // create a drawer which tracks touch movements
      var drawer = {
         isDrawing: false,
         touchstart: function (coors) {
            context.beginPath();
            context.moveTo(coors.x, coors.y);
            this.isDrawing = true;
         },
         touchmove: function (coors) {
            if (this.isDrawing) {
               context.lineTo(coors.x, coors.y);
               context.stroke();
            }
         },
         touchend: function (coors) {
            if (this.isDrawing) {
               this.touchmove(coors);
               this.isDrawing = false;
            }
         }
      };

      // create a function to pass touch events and coordinates to drawer
      function draw(event) {

         // get the touch coordinates.  Using the first touch in case of multi-touch
         var coors = {
            x: event.targetTouches[0].pageX,
            y: event.targetTouches[0].pageY
         };

         // Now we need to get the offset of the canvas location
         var obj = sigCanvas;

         if (obj.offsetParent) {
            // Every time we find a new object, we add its offsetLeft and offsetTop to curleft and curtop.
            do {
               coors.x -= obj.offsetLeft;
               coors.y -= obj.offsetTop;
            }
                    // The while loop can be "while (obj = obj.offsetParent)" only, which does return null
                    // when null is passed back, but that creates a warning in some editors (i.e. VS2010).
            while ((obj = obj.offsetParent) != null);
         }

         // pass the coordinates to the appropriate handler
         drawer[event.type](coors);
      }

      // attach the touchstart, touchmove, touchend event listeners.
      sigCanvas.addEventListener('touchstart', draw, false);
      sigCanvas.addEventListener('touchmove', draw, false);
      sigCanvas.addEventListener('touchend', draw, false);

      // prevent elastic scrolling
      sigCanvas.addEventListener('touchmove', function (event) {
         event.preventDefault();
      }, false);
   }
   else {

      // start drawing when the mousedown event fires, and attach handlers to
      // draw a line to wherever the mouse moves to
      $("#canvasSignature").mousedown(function (mouseEvent) {
         var position = getPosition(mouseEvent, sigCanvas);

         context.moveTo(position.X, position.Y);
         var prevPosition = { x: position.X, y: position.Y };
         context.beginPath();
         console.log(sigCanvas);

         drawOnePixel(mouseEvent, sigCanvas, context);

         // attach event handlers
         $(this).mousemove(function (mouseEvent) {
            drawLine(mouseEvent, sigCanvas, context, prevPosition);
            prevPosition = updatePrevPosition(mouseEvent, sigCanvas);
         }).mouseup(function (mouseEvent) {
            finishDrawing(mouseEvent, sigCanvas, context, prevPosition);
            prevPosition = updatePrevPosition(mouseEvent, sigCanvas);
         }).mouseout(function (mouseEvent) {
            drawUponExitingCanvas(mouseEvent, sigCanvas, context, prevPosition);
            prevPosition = updatePrevPosition(mouseEvent, sigCanvas);
         }).mouseover(function (mouseEvent) {
            drawUponReenter(mouseEvent, sigCanvas, context, prevPosition);
            prevPosition = updatePrevPosition(mouseEvent, sigCanvas);
         })
         //mouse press is released outside of canvas
         $(document).mouseup(function(mouseEvent) {
            finish(mouseEvent, sigCanvas, context);
         });
      });
   }
}

function updatePrevPosition(mouseEvent, sigCanvas) {
   var position = getPosition(mouseEvent, sigCanvas);

   return { x: position.X, y: position.Y };
}

function finish(mouseEvent, sigCanvas, context) {
   context.closePath();

   $(sigCanvas).unbind("mousemove")
      .unbind("mouseup")
      .unbind("mouseout")
      .unbind("mouseover");
   $(document).unbind("mouseup");
}

function drawUponReenter(mouseEvent, sigCanvas, context, prevPosition) {
   var position = getPosition(mouseEvent, sigCanvas);

   context.moveTo(position.X, position.Y);
   drawLine(mouseEvent, sigCanvas, context, prevPosition);
}

function drawUponExitingCanvas(mouseEvent, sigCanvas, context, prevPosition) {
   drawLine(mouseEvent, sigCanvas, context, prevPosition);
}

// draws a line to the x and y coordinates of the mouse event inside
// the specified element using the specified context
function drawLine(mouseEvent, sigCanvas, context, prevPosition) {
   var position = getPosition(mouseEvent, sigCanvas);
   socket.emit('draw', {initialX: prevPosition.x,
                        initialY: prevPosition.y,
                        endX: position.X,
                        endY: position.Y});
   context.moveTo(prevPosition.x, prevPosition.y);
   context.lineTo(position.X, position.Y);
   context.stroke();
}

function drawOnePixel(mouseEvent, sigCanvas, context, prevPosition) {
    var position = getPosition(mouseEvent, sigCanvas);

    context.lineTo(position.X-1, position.Y);
    context.stroke();
}

// draws a line from the last coordiantes in the path to the finishing
// coordinates and unbind any event handlers which need to be preceded
// by the mouse down event
function finishDrawing(mouseEvent, sigCanvas, context, prevPosition) {
   // draw the line to the finishing coordinates
   drawLine(mouseEvent, sigCanvas, context, prevPosition);

   finish(mouseEvent, sigCanvas, context);
}<commit_msg>Okay, this should fix it. Really need to refactor.<commit_after>// works out the X, Y position of the click inside the canvas from the X, Y position on the page
function getPosition(mouseEvent, sigCanvas) {
   var x, y;
   if (mouseEvent.pageX != undefined && mouseEvent.pageY != undefined) {
      x = mouseEvent.pageX;
      y = mouseEvent.pageY;
   } else {
      x = mouseEvent.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      y = mouseEvent.clientY + document.body.scrollTop + document.documentElement.scrollTop;
   }

   return { X: x - sigCanvas.offsetLeft, Y: y - sigCanvas.offsetTop };
}

function initialize() {
   // get references to the canvas element as well as the 2D drawing context
   var sigCanvas = document.getElementById("canvasSignature");
   var context = sigCanvas.getContext("2d");
   context.strokeStyle = 'Black';

   // This will be defined on a TOUCH device such as iPad or Android, etc.
   var is_touch_device = 'ontouchstart' in document.documentElement;

   if (is_touch_device) {
      // create a drawer which tracks touch movements
      var drawer = {
         isDrawing: false,
         touchstart: function (coors) {
            context.beginPath();
            context.moveTo(coors.x, coors.y);
            this.isDrawing = true;
         },
         touchmove: function (coors) {
            if (this.isDrawing) {
               context.lineTo(coors.x, coors.y);
               context.stroke();
            }
         },
         touchend: function (coors) {
            if (this.isDrawing) {
               this.touchmove(coors);
               this.isDrawing = false;
            }
         }
      };

      // create a function to pass touch events and coordinates to drawer
      function draw(event) {

         // get the touch coordinates.  Using the first touch in case of multi-touch
         var coors = {
            x: event.targetTouches[0].pageX,
            y: event.targetTouches[0].pageY
         };

         // Now we need to get the offset of the canvas location
         var obj = sigCanvas;

         if (obj.offsetParent) {
            // Every time we find a new object, we add its offsetLeft and offsetTop to curleft and curtop.
            do {
               coors.x -= obj.offsetLeft;
               coors.y -= obj.offsetTop;
            }
                    // The while loop can be "while (obj = obj.offsetParent)" only, which does return null
                    // when null is passed back, but that creates a warning in some editors (i.e. VS2010).
            while ((obj = obj.offsetParent) != null);
         }

         // pass the coordinates to the appropriate handler
         drawer[event.type](coors);
      }

      // attach the touchstart, touchmove, touchend event listeners.
      sigCanvas.addEventListener('touchstart', draw, false);
      sigCanvas.addEventListener('touchmove', draw, false);
      sigCanvas.addEventListener('touchend', draw, false);

      // prevent elastic scrolling
      sigCanvas.addEventListener('touchmove', function (event) {
         event.preventDefault();
      }, false);
   }
   else {

      // start drawing when the mousedown event fires, and attach handlers to
      // draw a line to wherever the mouse moves to
      $("#canvasSignature").mousedown(function (mouseEvent) {
         var position = getPosition(mouseEvent, sigCanvas);

         context.moveTo(position.X, position.Y);
         var prevPosition = { x: position.X, y: position.Y };
         context.beginPath();
         console.log(sigCanvas);

         drawOnePixel(mouseEvent, sigCanvas, context);

         // attach event handlers
         $(this).mousemove(function (mouseEvent) {
            context.moveTo(prevPosition.x, prevPosition.y);
            drawLine(mouseEvent, sigCanvas, context, prevPosition);
            prevPosition = updatePrevPosition(mouseEvent, sigCanvas);
         }).mouseup(function (mouseEvent) {
            finishDrawing(mouseEvent, sigCanvas, context, prevPosition);
            prevPosition = updatePrevPosition(mouseEvent, sigCanvas);
         }).mouseout(function (mouseEvent) {
            drawUponExitingCanvas(mouseEvent, sigCanvas, context, prevPosition);
            prevPosition = updatePrevPosition(mouseEvent, sigCanvas);
         }).mouseover(function (mouseEvent) {
            drawUponReenter(mouseEvent, sigCanvas, context, prevPosition);
            prevPosition = updatePrevPosition(mouseEvent, sigCanvas);
         })
         //mouse press is released outside of canvas
         $(document).mouseup(function(mouseEvent) {
            finish(mouseEvent, sigCanvas, context);
         });
      });
   }
}

function updatePrevPosition(mouseEvent, sigCanvas) {
   var position = getPosition(mouseEvent, sigCanvas);

   return { x: position.X, y: position.Y };
}

function finish(mouseEvent, sigCanvas, context) {
   context.closePath();

   $(sigCanvas).unbind("mousemove")
      .unbind("mouseup")
      .unbind("mouseout")
      .unbind("mouseover");
   $(document).unbind("mouseup");
}

function drawUponReenter(mouseEvent, sigCanvas, context, prevPosition) {
   var position = getPosition(mouseEvent, sigCanvas);

   context.moveTo(position.X, position.Y);
   drawLine(mouseEvent, sigCanvas, context, prevPosition);
}

function drawUponExitingCanvas(mouseEvent, sigCanvas, context, prevPosition) {
   drawLine(mouseEvent, sigCanvas, context, prevPosition);
}

// draws a line to the x and y coordinates of the mouse event inside
// the specified element using the specified context
function drawLine(mouseEvent, sigCanvas, context, prevPosition) {
   var position = getPosition(mouseEvent, sigCanvas);
   socket.emit('draw', {initialX: prevPosition.x,
                        initialY: prevPosition.y,
                        endX: position.X,
                        endY: position.Y});
   context.lineTo(position.X, position.Y);
   context.stroke();
}

function drawOnePixel(mouseEvent, sigCanvas, context, prevPosition) {
    var position = getPosition(mouseEvent, sigCanvas);

    context.lineTo(position.X-1, position.Y);
    context.stroke();
}

// draws a line from the last coordiantes in the path to the finishing
// coordinates and unbind any event handlers which need to be preceded
// by the mouse down event
function finishDrawing(mouseEvent, sigCanvas, context, prevPosition) {
   // draw the line to the finishing coordinates
   drawLine(mouseEvent, sigCanvas, context, prevPosition);

   finish(mouseEvent, sigCanvas, context);
}<|endoftext|>


<commit_before>function Chattr() {
  this.socket   = null;
  this.name     = null;
  this.messages = $('.messages > ul');
  this.ctx      = null;
  this.typing   = null;
  this.isTyping = false;

  this.init = function() {
    var _this = this;

    this.socket = io.connect(["http://", window.location.hostname, ":3003"].join(""));

    // Create audio if we can
    if (typeof(window.audioContext) !== 'undefined' || typeof(window.webkitAudioContext) !== 'undefined') {
      _this.ctx = new(window.audioContext || window.webkitAudioContext);
    }

    // Check if we have a name
    var nickname = this.get_cookie('nickname');

    if (nickname.length) {
      _this.name = nickname;

      socket.emit('set name', {
        name: nickname,
        cookie: true
      });
    }

    $('#set-name').submit(function() {
      _this.name = $(".login-as input").val();

      $(".login-as input").val("")

      socket.emit('set name', {
        name: _this.name
      });

      if (_this.name.toLowerCase() !== 'system') {
        _this.set_cookie({
          name: 'nickname',
          value: _this.name,
          expires: (60 * 60 * 24)
        });
      }

      return false;
    });

    $('.login-as > button').click(function() {
      $('#set-name').submit();
    });

    $('#send-message').submit(function() {
      var message = $(this).serializeArray();
      message = message[0].value;

      if (message.length) {
        socket.emit('send_message', {
          message: message
        });

        $($(this).find('input')[0]).val("");
      }

      return false;
    });

    $('.message-input input').keyup(function() {
      if (_this.isTyping === false) {
       socket.emit('type', {});
      }

      _this.isTyping = true;
    });

    socket.on('message', function(data) {
      if (data.name !== _this.name && data.name.toLowerCase() !== 'system') {
        _this.beep(50, 2);
      }

      if (typeof(data.message) !== 'undefined') {
        _this.messages.append([
          '
',
          '',
          moment(data.date).format("HH:mma"),
          ' ',
          data.name,
          ': ',
          data.message,
          '
'
        ].join(""));

        _this.messages.animate({
          scrollTop: _this.messages[0].scrollHeight
        }, 20);
      }
    });

    socket.on('online', function(data) {
      $('.online-users > ul').empty();

      for (var i in data.online) {
        data.avatar = data.avatar !== null ? data.avatar = [''].join("") : "";

        $('.online-users > ul').append([
          '
',
          data.avatar,
          '',
          data.online[i],
          '',
          '
'
        ].join(""));
      }

      $('#online-count').html(['(', data.count, ')'].join(""));

      // New user
      if (typeof(data.new_user) !== 'undefined') {
        _this.show_alert([data.new_user, 'has come online!'].join(" "));
      }
    });

    socket.on('clear_messages', function() {
      $('.messages > ul').empty();
    });

    socket.on('beep', function(data) {
      _this.beep(data.duration, data.type);
    });

    socket.on('show error', function(data) {
      $('.alert').addClass('error');

      _this.show_alert(data.message);
    });

    socket.on('typing', function(data) {
      // Clear any timeout
      if (typeof(_this.typing) !== 'null') {
        clearTimeout(_this.typing);

        _this.typing = null;
      }

      if (data.name !== _this.name) {
        $('.messages-info').html([data.name, "is typing..."].join(" "));
      }

      _this.typing = window.setTimeout(function() {
        $('.messages-info').html(" ");
        _this.isTyping = false;
      }, 2000);
    });
  }

  this.set_cookie = function(settings) {
    if (typeof(settings) === 'undefined') return false;

    var expires = +new Date() + settings.expires;

    settings.name = [window.location.port, settings.name].join("_");

    document.cookie = settings.name + "=" + settings.value + ";expires=" + expires + "; path=/";
  }

  this.get_cookie = function(c_name) {
    c_name = [window.location.port, c_name].join("_");

    if (document.cookie.length > 0) {
      var c_start, c_end;

      c_start = document.cookie.indexOf(c_name + "=");

      if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        c_end = document.cookie.indexOf(";", c_start);

        if (c_end == -1) {
          c_end = document.cookie.length;
        }

        return unescape(document.cookie.substring(c_start, c_end));
      }
    }

    return "";
  },

  this.beep = function (duration, type, finishedCallback) {
    var _this = this;

    duration = +duration;

    // Only 0-4 are valid types.
    type = (type % 5) || 0;

    if (typeof finishedCallback != "function") {
        finishedCallback = function () {};
    }

    var osc = _this.ctx.createOscillator();

    osc.type = type;

    osc.connect(_this.ctx.destination);
    osc.noteOn(0);

    setTimeout(function () {
        osc.noteOff(0);
        finishedCallback();
    }, duration);
  }

  this.show_alert = function(alert) {
    $('.alert').html(alert);

    $('.alert').animate({
      height: '34px',
      opacity: 1
    }, 500, function() {
      window.setTimeout(function() {
        $('.alert').html("");

        $('.alert').animate({
          height: '0px',
          opacity: 0
        }, 500, function() {
          $('.alert').removeClass('error');
        });
      }, 2500);
    });
  }

  this.init();
}

$(document).ready(function() {
  Chattr();
});<commit_msg>Bug fix<commit_after>function Chattr() {
  this.socket   = null;
  this.name     = null;
  this.messages = $('.messages > ul');
  this.ctx      = null;
  this.typing   = null;
  this.isTyping = false;

  this.init = function() {
    var _this = this;

    this.socket = io.connect(["http://", window.location.hostname, ":3003"].join(""));

    // Create audio if we can
    if (typeof(window.audioContext) !== 'undefined' || typeof(window.webkitAudioContext) !== 'undefined') {
      _this.ctx = new(window.audioContext || window.webkitAudioContext);
    }

    // Check if we have a name
    var nickname = this.get_cookie('nickname');

    if (nickname.length) {
      _this.name = nickname;

      socket.emit('set name', {
        name: nickname,
        cookie: true
      });
    }

    $('#set-name').submit(function() {
      _this.name = $(".login-as input").val();

      $(".login-as input").val("")

      socket.emit('set name', {
        name: _this.name
      });

      if (_this.name.toLowerCase() !== 'system') {
        _this.set_cookie({
          name: 'nickname',
          value: _this.name,
          expires: (60 * 60 * 24)
        });
      }

      return false;
    });

    $('.login-as > button').click(function() {
      $('#set-name').submit();
    });

    $('#send-message').submit(function() {
      var message = $(this).serializeArray();
      message = message[0].value;

      if (message.length) {
        socket.emit('send_message', {
          message: message
        });

        $($(this).find('input')[0]).val("");
      }

      return false;
    });

    $('.message-input input').keyup(function() {
      if (_this.isTyping === false) {
       socket.emit('type', {});
      }

      _this.isTyping = true;
    });

    socket.on('message', function(data) {
      if (data.name !== _this.name && data.name.toLowerCase() !== 'system') {
        _this.beep(50, 2);
      }

      if (typeof(data.message) !== 'undefined') {
        _this.messages.append([
          '
',
          '',
          moment(data.date).format("HH:mma"),
          ' ',
          data.name,
          ': ',
          data.message,
          '
'
        ].join(""));

        _this.messages.animate({
          scrollTop: _this.messages[0].scrollHeight
        }, 20);
      }
    });

    socket.on('online', function(data) {
      $('.online-users > ul').empty();

      for (var i in data.online) {
        data.avatar = data.avatar !== null ? [''].join("") : "";

        $('.online-users > ul').append([
          '
',
          data.avatar,
          '',
          data.online[i],
          '',
          '
'
        ].join(""));
      }

      $('#online-count').html(['(', data.count, ')'].join(""));

      // New user
      if (typeof(data.new_user) !== 'undefined') {
        _this.show_alert([data.new_user, 'has come online!'].join(" "));
      }
    });

    socket.on('clear_messages', function() {
      $('.messages > ul').empty();
    });

    socket.on('beep', function(data) {
      _this.beep(data.duration, data.type);
    });

    socket.on('show error', function(data) {
      $('.alert').addClass('error');

      _this.show_alert(data.message);
    });

    socket.on('typing', function(data) {
      // Clear any timeout
      if (typeof(_this.typing) !== 'null') {
        clearTimeout(_this.typing);

        _this.typing = null;
      }

      if (data.name !== _this.name) {
        $('.messages-info').html([data.name, "is typing..."].join(" "));
      }

      _this.typing = window.setTimeout(function() {
        $('.messages-info').html(" ");
        _this.isTyping = false;
      }, 2000);
    });
  }

  this.set_cookie = function(settings) {
    if (typeof(settings) === 'undefined') return false;

    var expires = +new Date() + settings.expires;

    settings.name = [window.location.port, settings.name].join("_");

    document.cookie = settings.name + "=" + settings.value + ";expires=" + expires + "; path=/";
  }

  this.get_cookie = function(c_name) {
    c_name = [window.location.port, c_name].join("_");

    if (document.cookie.length > 0) {
      var c_start, c_end;

      c_start = document.cookie.indexOf(c_name + "=");

      if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        c_end = document.cookie.indexOf(";", c_start);

        if (c_end == -1) {
          c_end = document.cookie.length;
        }

        return unescape(document.cookie.substring(c_start, c_end));
      }
    }

    return "";
  },

  this.beep = function (duration, type, finishedCallback) {
    var _this = this;

    duration = +duration;

    // Only 0-4 are valid types.
    type = (type % 5) || 0;

    if (typeof finishedCallback != "function") {
        finishedCallback = function () {};
    }

    var osc = _this.ctx.createOscillator();

    osc.type = type;

    osc.connect(_this.ctx.destination);
    osc.noteOn(0);

    setTimeout(function () {
        osc.noteOff(0);
        finishedCallback();
    }, duration);
  }

  this.show_alert = function(alert) {
    $('.alert').html(alert);

    $('.alert').animate({
      height: '34px',
      opacity: 1
    }, 500, function() {
      window.setTimeout(function() {
        $('.alert').html("");

        $('.alert').animate({
          height: '0px',
          opacity: 0
        }, 500, function() {
          $('.alert').removeClass('error');
        });
      }, 2500);
    });
  }

  this.init();
}

$(document).ready(function() {
  Chattr();
});<|endoftext|>


<commit_before>var epsg4326 = new OpenLayers.Projection("EPSG:4326");
var map;
var markers;
var vectors;
var popup;

var nonamekeys = {
   'openstreetmap.org': '2f59745a6b525b4ebdb100891d5b6711',
   'www.openstreetmap.org': 'fd093e52f0965d46bb1c6c6281022199',
   'openstreetmap.com': '4c60e7f5f31c576a9bb8da71c8d61152',
   'www.openstreetmap.com': '142f25a0770a51a9a400b3513834a199',
   'openstreetmap.net': '687c58fd1d715596bfc94abe653d8ac0',
   'www.openstreetmap.net': '0bd1654141c85d30b9c2ccdb5302f2e4'
};

OpenLayers._getScriptLocation = function () {
  // Should really have this file as an erb, so that this can return
  // the real rails root
   return "/openlayers/";
}

function createMap(divName, options) {
   options = options || {};

   map = new OpenLayers.Map(divName, {
      controls: options.controls || [
         new OpenLayers.Control.ArgParser(),
         new OpenLayers.Control.Attribution(),
         new OpenLayers.Control.LayerSwitcher(),
         new OpenLayers.Control.Navigation(),
         new OpenLayers.Control.PanZoomBar()
      ],
      units: "m",
      maxResolution: 156543.0339,
      numZoomLevels: 20,
      displayProjection: new OpenLayers.Projection("EPSG:4326")
   });

   var mapnik = new OpenLayers.Layer.OSM.Mapnik(i18n("javascripts.map.base.mapnik"), {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(mapnik);

   var osmarender = new OpenLayers.Layer.OSM.Osmarender(i18n("javascripts.map.base.osmarender"), {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(osmarender);

   var cyclemap = new OpenLayers.Layer.OSM.CycleMap(i18n("javascripts.map.base.cycle_map"), {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(cyclemap);

   var nonamekey = nonamekeys[document.domain];
   var noname = new OpenLayers.Layer.OSM(i18n("javascripts.map.base.noname"), [
      "http://a.tile.cloudmade.com/" + nonamekey + "/3/256/${z}/${x}/${y}.png",
      "http://b.tile.cloudmade.com/" + nonamekey + "/3/256/${z}/${x}/${y}.png",
      "http://c.tile.cloudmade.com/" + nonamekey + "/3/256/${z}/${x}/${y}.png"
   ], {
      displayOutsideMaxExtent: true,
      wrapDateLine: true,
      numZoomLevels: 19
   });
   map.addLayer(noname);

   var maplint = new OpenLayers.Layer.OSM.Maplint(i18n("javascripts.map.overlays.maplint"), {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(maplint);

   var numZoomLevels = Math.max(mapnik.numZoomLevels, osmarender.numZoomLevels);

   markers = new OpenLayers.Layer.Markers("Markers", {
      displayInLayerSwitcher: false,
      numZoomLevels: numZoomLevels,
      maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
      maxResolution: 156543,
      units: "m",
      projection: "EPSG:900913"
   });
   map.addLayer(markers);

   return map;
}

function getArrowIcon() {
   var size = new OpenLayers.Size(25, 22);
   var offset = new OpenLayers.Pixel(-30, -27);
   var icon = new OpenLayers.Icon("/images/arrow.png", size, offset);

   return icon;
}

function addMarkerToMap(position, icon, description) {
   var marker = new OpenLayers.Marker(position.clone().transform(epsg4326, map.getProjectionObject()), icon);

   markers.addMarker(marker);

   if (description) {
      marker.events.register("click", marker, function() { openMapPopup(marker, description) });
   }

   return marker;
}

function addObjectToMap(url, zoom, callback) {
   var layer = new OpenLayers.Layer.GML("Objects", url, {
      format: OpenLayers.Format.OSM,
      style: {
          strokeColor: "blue",
          strokeWidth: 3,
          strokeOpacity: 0.5,
          fillOpacity: 0.2,
          fillColor: "lightblue",
          pointRadius: 6
      },
      projection: new OpenLayers.Projection("EPSG:4326"),
      displayInLayerSwitcher: false
   });

   layer.events.register("loadend", layer, function() {
      var extent;

      if (this.features.length) {
         extent = this.features[0].geometry.getBounds();

         for (var i = 1; i < this.features.length; i++) {
            extent.extend(this.features[i].geometry.getBounds());
         }

         if (zoom) {
            if (extent) {
               this.map.zoomToExtent(extent);
            } else {
               this.map.zoomToMaxExtent();
            }
         }
      }

      if (callback) {
         callback(extent);
      }
   });

   map.addLayer(layer);

   layer.loadGML();
}

function addBoxToMap(boxbounds) {
   if (!vectors) {
     // Be aware that IE requires Vector layers be initialised on page load, and not under deferred script conditions
     vectors = new OpenLayers.Layer.Vector("Boxes", {
        displayInLayerSwitcher: false
     });
     map.addLayer(vectors);
   }
   var geometry = boxbounds.toGeometry().transform(epsg4326, map.getProjectionObject());
   var box = new OpenLayers.Feature.Vector(geometry, {}, {
      strokeWidth: 2,
      strokeColor: '#ee9900',
      fillOpacity: 0
   });

   vectors.addFeatures(box);

   return box;
}

function openMapPopup(marker, description) {
   closeMapPopup();

   popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat, null,
                                               description, marker.icon, true);
   popup.setBackgroundColor("#E3FFC5");
   popup.autoSize = true;
   map.addPopup(popup);

   return popup;
}

function closeMapPopup() {
   if (popup) {
      map.removePopup(popup);
      delete popup;
   }
}

function removeMarkerFromMap(marker){
   markers.removeMarker(marker);
}

function removeBoxFromMap(box){
   vectors.removeFeature(box);
}

function getMapCenter(center, zoom) {
   return map.getCenter().clone().transform(map.getProjectionObject(), epsg4326);
}

function setMapCenter(center, zoom) {
   zoom = parseInt(zoom);
   var numzoom = map.getNumZoomLevels();
   if (zoom >= numzoom) zoom = numzoom - 1;
   map.setCenter(center.clone().transform(epsg4326, map.getProjectionObject()), zoom);
}

function setMapExtent(extent) {
   map.zoomToExtent(extent.clone().transform(epsg4326, map.getProjectionObject()));
}

function getMapExtent() {
   return map.getExtent().clone().transform(map.getProjectionObject(), epsg4326);
}

function getEventPosition(event) {
   return map.getLonLatFromViewPortPx(event.xy).clone().transform(map.getProjectionObject(), epsg4326);
}

function getMapLayers() {
   var layerConfig = "";

   for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) {
      layerConfig += layers[i] == map.baseLayer ? "B" : "0";
   }

   for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) {
      layerConfig += layers[i].getVisibility() ? "T" : "F";
   }

   return layerConfig;
}

function setMapLayers(layerConfig) {
   var l = 0;

   for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) {
      var c = layerConfig.charAt(l++);

      if (c == "B") {
         map.setBaseLayer(layers[i]);
      }
   }

   while (layerConfig.charAt(l) == "B" || layerConfig.charAt(l) == "0") {
      l++;
   }

   for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) {
      var c = layerConfig.charAt(l++);

      if (c == "T") {
         layers[i].setVisibility(true);
      } else if(c == "F") {
         layers[i].setVisibility(false);
      }
   }
}

function scaleToZoom(scale) {
   return Math.log(360.0/(scale * 512.0)) / Math.log(2.0);
}
<commit_msg>Remove hack that was needed to cope with our old asset tagging but which now does nothing except break installation in subdirectories.<commit_after>var epsg4326 = new OpenLayers.Projection("EPSG:4326");
var map;
var markers;
var vectors;
var popup;

var nonamekeys = {
   'openstreetmap.org': '2f59745a6b525b4ebdb100891d5b6711',
   'www.openstreetmap.org': 'fd093e52f0965d46bb1c6c6281022199',
   'openstreetmap.com': '4c60e7f5f31c576a9bb8da71c8d61152',
   'www.openstreetmap.com': '142f25a0770a51a9a400b3513834a199',
   'openstreetmap.net': '687c58fd1d715596bfc94abe653d8ac0',
   'www.openstreetmap.net': '0bd1654141c85d30b9c2ccdb5302f2e4'
};

function createMap(divName, options) {
   options = options || {};

   map = new OpenLayers.Map(divName, {
      controls: options.controls || [
         new OpenLayers.Control.ArgParser(),
         new OpenLayers.Control.Attribution(),
         new OpenLayers.Control.LayerSwitcher(),
         new OpenLayers.Control.Navigation(),
         new OpenLayers.Control.PanZoomBar()
      ],
      units: "m",
      maxResolution: 156543.0339,
      numZoomLevels: 20,
      displayProjection: new OpenLayers.Projection("EPSG:4326")
   });

   var mapnik = new OpenLayers.Layer.OSM.Mapnik(i18n("javascripts.map.base.mapnik"), {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(mapnik);

   var osmarender = new OpenLayers.Layer.OSM.Osmarender(i18n("javascripts.map.base.osmarender"), {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(osmarender);

   var cyclemap = new OpenLayers.Layer.OSM.CycleMap(i18n("javascripts.map.base.cycle_map"), {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(cyclemap);

   var nonamekey = nonamekeys[document.domain];
   var noname = new OpenLayers.Layer.OSM(i18n("javascripts.map.base.noname"), [
      "http://a.tile.cloudmade.com/" + nonamekey + "/3/256/${z}/${x}/${y}.png",
      "http://b.tile.cloudmade.com/" + nonamekey + "/3/256/${z}/${x}/${y}.png",
      "http://c.tile.cloudmade.com/" + nonamekey + "/3/256/${z}/${x}/${y}.png"
   ], {
      displayOutsideMaxExtent: true,
      wrapDateLine: true,
      numZoomLevels: 19
   });
   map.addLayer(noname);

   var maplint = new OpenLayers.Layer.OSM.Maplint(i18n("javascripts.map.overlays.maplint"), {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(maplint);

   var numZoomLevels = Math.max(mapnik.numZoomLevels, osmarender.numZoomLevels);

   markers = new OpenLayers.Layer.Markers("Markers", {
      displayInLayerSwitcher: false,
      numZoomLevels: numZoomLevels,
      maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
      maxResolution: 156543,
      units: "m",
      projection: "EPSG:900913"
   });
   map.addLayer(markers);

   return map;
}

function getArrowIcon() {
   var size = new OpenLayers.Size(25, 22);
   var offset = new OpenLayers.Pixel(-30, -27);
   var icon = new OpenLayers.Icon("/images/arrow.png", size, offset);

   return icon;
}

function addMarkerToMap(position, icon, description) {
   var marker = new OpenLayers.Marker(position.clone().transform(epsg4326, map.getProjectionObject()), icon);

   markers.addMarker(marker);

   if (description) {
      marker.events.register("click", marker, function() { openMapPopup(marker, description) });
   }

   return marker;
}

function addObjectToMap(url, zoom, callback) {
   var layer = new OpenLayers.Layer.GML("Objects", url, {
      format: OpenLayers.Format.OSM,
      style: {
          strokeColor: "blue",
          strokeWidth: 3,
          strokeOpacity: 0.5,
          fillOpacity: 0.2,
          fillColor: "lightblue",
          pointRadius: 6
      },
      projection: new OpenLayers.Projection("EPSG:4326"),
      displayInLayerSwitcher: false
   });

   layer.events.register("loadend", layer, function() {
      var extent;

      if (this.features.length) {
         extent = this.features[0].geometry.getBounds();

         for (var i = 1; i < this.features.length; i++) {
            extent.extend(this.features[i].geometry.getBounds());
         }

         if (zoom) {
            if (extent) {
               this.map.zoomToExtent(extent);
            } else {
               this.map.zoomToMaxExtent();
            }
         }
      }

      if (callback) {
         callback(extent);
      }
   });

   map.addLayer(layer);

   layer.loadGML();
}

function addBoxToMap(boxbounds) {
   if (!vectors) {
     // Be aware that IE requires Vector layers be initialised on page load, and not under deferred script conditions
     vectors = new OpenLayers.Layer.Vector("Boxes", {
        displayInLayerSwitcher: false
     });
     map.addLayer(vectors);
   }
   var geometry = boxbounds.toGeometry().transform(epsg4326, map.getProjectionObject());
   var box = new OpenLayers.Feature.Vector(geometry, {}, {
      strokeWidth: 2,
      strokeColor: '#ee9900',
      fillOpacity: 0
   });

   vectors.addFeatures(box);

   return box;
}

function openMapPopup(marker, description) {
   closeMapPopup();

   popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat, null,
                                               description, marker.icon, true);
   popup.setBackgroundColor("#E3FFC5");
   popup.autoSize = true;
   map.addPopup(popup);

   return popup;
}

function closeMapPopup() {
   if (popup) {
      map.removePopup(popup);
      delete popup;
   }
}

function removeMarkerFromMap(marker){
   markers.removeMarker(marker);
}

function removeBoxFromMap(box){
   vectors.removeFeature(box);
}

function getMapCenter(center, zoom) {
   return map.getCenter().clone().transform(map.getProjectionObject(), epsg4326);
}

function setMapCenter(center, zoom) {
   zoom = parseInt(zoom);
   var numzoom = map.getNumZoomLevels();
   if (zoom >= numzoom) zoom = numzoom - 1;
   map.setCenter(center.clone().transform(epsg4326, map.getProjectionObject()), zoom);
}

function setMapExtent(extent) {
   map.zoomToExtent(extent.clone().transform(epsg4326, map.getProjectionObject()));
}

function getMapExtent() {
   return map.getExtent().clone().transform(map.getProjectionObject(), epsg4326);
}

function getEventPosition(event) {
   return map.getLonLatFromViewPortPx(event.xy).clone().transform(map.getProjectionObject(), epsg4326);
}

function getMapLayers() {
   var layerConfig = "";

   for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) {
      layerConfig += layers[i] == map.baseLayer ? "B" : "0";
   }

   for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) {
      layerConfig += layers[i].getVisibility() ? "T" : "F";
   }

   return layerConfig;
}

function setMapLayers(layerConfig) {
   var l = 0;

   for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) {
      var c = layerConfig.charAt(l++);

      if (c == "B") {
         map.setBaseLayer(layers[i]);
      }
   }

   while (layerConfig.charAt(l) == "B" || layerConfig.charAt(l) == "0") {
      l++;
   }

   for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) {
      var c = layerConfig.charAt(l++);

      if (c == "T") {
         layers[i].setVisibility(true);
      } else if(c == "F") {
         layers[i].setVisibility(false);
      }
   }
}

function scaleToZoom(scale) {
   return Math.log(360.0/(scale * 512.0)) / Math.log(2.0);
}
<|endoftext|>


<commit_before>// Mapping functions

var map;
var proj = new OpenLayers.Projection("EPSG:4326");
var selectControl;
var openPopup;
var stopsById = new Array();
var segmentStyle =
{
  strokeColor: "#CC0000",
  strokeOpacity: 0.7,
  strokeWidth: 4
};

var segmentSelectedStyle =
{
  strokeColor: "#000000",
  strokeOpacity: 0.7,
  strokeWidth: 4
};

function area_init() {
  createMap();
  var stopCoords;
  bounds = new OpenLayers.Bounds();
  var markers = new OpenLayers.Layer.Markers( "Markers" );
  map.addLayer(markers);
  for (var i=0; i < areaStops.length; i++){
    var item = areaStops[i];
    if (item[0] instanceof Array){
      for (var j=0; j < item.length; j++){
        coords = item[j];
        stopCoords = new OpenLayers.LonLat(coords[1], coords[0]).transform(proj, map.getProjectionObject());
        addRouteMarker(stopCoords, bounds, markers, coords[2], coords[3], coords[4], i);
      }
    }else{
      coords = item;
      stopCoords = new OpenLayers.LonLat(coords[1], coords[0]).transform(proj, map.getProjectionObject());
      addRouteMarker(stopCoords, bounds, markers, coords[2], coords[3], coords[4], i);
    }

  }
  map.zoomToExtent(bounds, false);
}

function route_init() {

  createMap();
  bounds = new OpenLayers.Bounds();
  var markers = new OpenLayers.Layer.Markers( "Markers", {projection: proj});
  var vectorLayer = new OpenLayers.Layer.Vector("Vector Layer",{projection: proj});
  map.addLayer(markers);
  map.addLayer(vectorLayer);
  addSelectedHandler(vectorLayer);
  for (var i=0; i < routeSegments.length; i++){
     var coords = routeSegments[i];
     var fromCoords = new OpenLayers.LonLat(coords[0][1], coords[0][0]);
     var toCoords = new OpenLayers.LonLat(coords[1][1], coords[1][0]);
     fromCoords.transform(proj, map.getProjectionObject());
     toCoords.transform(proj, map.getProjectionObject());
     var fromPoint = new OpenLayers.Geometry.Point(fromCoords.lon, fromCoords.lat);
     var toPoint = new OpenLayers.Geometry.Point(toCoords.lon, toCoords.lat);
     var points = [];
     points.push(fromPoint);
     points.push(toPoint)
     bounds.extend(fromPoint);
     bounds.extend(toPoint);
     addRouteMarker(fromCoords, bounds, markers, coords[0][2], coords[0][3], coords[0][4], 0);
     addRouteMarker(toCoords, bounds, markers, coords[1][2], coords[1][3], coords[1][4], 0);
     lineString = new OpenLayers.Geometry.LineString(points);
     lineFeature = new OpenLayers.Feature.Vector(lineString, {projection: proj}, segmentStyle);
     lineFeature.segment_id = coords[2];
     vectorLayer.addFeatures([lineFeature]);
   }
   map.zoomToExtent(bounds, false);

}

function addSelectedHandler(vectorLayer) {
  vectorLayer.events.on({
      'featureselected': segmentSelected,
      'featureunselected': segmentUnselected
  });
  selectControl = new OpenLayers.Control.SelectFeature(vectorLayer, {multiple: false,
                                                                     toggleKey: "ctrlKey",
                                                                     multipleKey: "shiftKey"});
  map.addControl(selectControl);
  selectControl.activate();
}

function segmentSelected(event) {
  segment = event.feature;
  segment.style = segmentSelectedStyle;
  this.drawFeature(segment);
  var row = jQuery("#route_segment_" + segment.segment_id);
  row.toggleClass("selected");
  row.find(".check-route-segment").attr('checked', 'true');
}

function segmentUnselected(event) {
  segment = event.feature;
  segment.style = segmentStyle;
  this.drawFeature(segment);
  jQuery("#route_segment_" + segment.segment_id).toggleClass("selected");

}

/**
 * @requires OpenLayers/Layer/XYZ.js
 *
 * Class: OpenLayers.Layer.StreetView
 *
 * Inherits from:
 *  - <OpenLayers.Layer.XYZ>
 */
OpenLayers.Layer.StreetView = OpenLayers.Class(OpenLayers.Layer.XYZ, {
    /**
     * Constructor: OpenLayers.Layer.StreetView
     *
     * Parameters:
     * name - {String}
     * url - {String}
     * options - {Object} Hashtable of extra options to tag onto the layer
     */
    initialize: function(name, options) {
        var url = [
            "http://a.os.openstreetmap.org/sv/${z}/${x}/${y}.png",
            "http://b.os.openstreetmap.org/sv/${z}/${x}/${y}.png",
            "http://c.os.openstreetmap.org/sv/${z}/${x}/${y}.png"
        ];
        options = OpenLayers.Util.extend({
            numZoomLevels: 18,
            transitionEffect: "resize",
            sphericalMercator: true,
            attribution: "Contains Ordnance Survey data © Crown copyright and database right 2010"
        }, options);
        var newArguments = [name, url, options];
        OpenLayers.Layer.XYZ.prototype.initialize.apply(this, newArguments);
    },

    CLASS_NAME: "OpenLayers.Layer.StreetView"
});

function createMap() {

  var options = {
        'projection': new OpenLayers.Projection("EPSG:900913"),
        'units': "m",
        'numZoomLevels': 18,
        'maxResolution': 156543.0339,
        'maxExtent': new OpenLayers.Bounds(-20037508.34, -20037508.34,
                                          20037508.34, 20037508.34)
      };
  jQuery('.static-map-element').hide();
  map = new OpenLayers.Map('map', options);
  var layer = new OpenLayers.Layer.Google("Google Streets",{'sphericalMercator': true,
                                                           'maxExtent': new OpenLayers.Bounds(-20037508.34, -20037508.34,
                                                                                20037508.34, 20037508.34)});
  map.addLayer(layer);
}

function onPopupClose(evt) {
  stopUnselected(this.stop);
}

function stopUnselected(stop) {
  if (stop && stop.popup) {
      popup.stop = null;
      map.removePopup(stop.popup);
      stop.popup.destroy();
      stop.popup = null;
  }
}
function stopSelected () {
  selectStop(this);
}

function selectStop(stop) {
  if (openPopup){
    stopUnselected(openPopup.stop);
    openPopup = null;
  }
  popup = new OpenLayers.Popup.AnchoredBubble("stopPopup",
                                            stop.lonlat,
                                            new OpenLayers.Size(50,50),
                                            ''+
                                            stop.name + '',
                                            null, true, onPopupClose);
  popup.autoSize = true;
  stop.popup = popup;
  popup.stop = stop;
  map.addPopup(popup);
  openPopup = popup;
}

function addRouteMarker(stopCoords, bounds, markers, id, url, name, index) {
  bounds.extend(stopCoords);
  var size = new OpenLayers.Size(6, 6);
  var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
  var stopIcon = new OpenLayers.Icon('/images/circle-icon-sm_'+index+'.png', size, offset);
  var marker = new OpenLayers.Marker(stopCoords, stopIcon);
  marker.url = url;
  marker.name = name;
  marker.id = id;
  stopsById[id] = marker;
  marker.events.register("click", marker, stopSelected);
  markers.addMarker(marker);
}

// Run jquery in no-conflict mode so it doesn't use $()
jQuery.noConflict();

<commit_msg>Street map code not currently used<commit_after>// Mapping functions

var map;
var proj = new OpenLayers.Projection("EPSG:4326");
var selectControl;
var openPopup;
var stopsById = new Array();
var segmentStyle =
{
  strokeColor: "#CC0000",
  strokeOpacity: 0.7,
  strokeWidth: 4
};

var segmentSelectedStyle =
{
  strokeColor: "#000000",
  strokeOpacity: 0.7,
  strokeWidth: 4
};

function area_init() {
  createMap();
  var stopCoords;
  bounds = new OpenLayers.Bounds();
  var markers = new OpenLayers.Layer.Markers( "Markers" );
  map.addLayer(markers);
  for (var i=0; i < areaStops.length; i++){
    var item = areaStops[i];
    if (item[0] instanceof Array){
      for (var j=0; j < item.length; j++){
        coords = item[j];
        stopCoords = new OpenLayers.LonLat(coords[1], coords[0]).transform(proj, map.getProjectionObject());
        addRouteMarker(stopCoords, bounds, markers, coords[2], coords[3], coords[4], i);
      }
    }else{
      coords = item;
      stopCoords = new OpenLayers.LonLat(coords[1], coords[0]).transform(proj, map.getProjectionObject());
      addRouteMarker(stopCoords, bounds, markers, coords[2], coords[3], coords[4], i);
    }

  }
  map.zoomToExtent(bounds, false);
}

function route_init() {

  createMap();
  bounds = new OpenLayers.Bounds();
  var markers = new OpenLayers.Layer.Markers( "Markers", {projection: proj});
  var vectorLayer = new OpenLayers.Layer.Vector("Vector Layer",{projection: proj});
  map.addLayer(markers);
  map.addLayer(vectorLayer);
  addSelectedHandler(vectorLayer);
  for (var i=0; i < routeSegments.length; i++){
     var coords = routeSegments[i];
     var fromCoords = new OpenLayers.LonLat(coords[0][1], coords[0][0]);
     var toCoords = new OpenLayers.LonLat(coords[1][1], coords[1][0]);
     fromCoords.transform(proj, map.getProjectionObject());
     toCoords.transform(proj, map.getProjectionObject());
     var fromPoint = new OpenLayers.Geometry.Point(fromCoords.lon, fromCoords.lat);
     var toPoint = new OpenLayers.Geometry.Point(toCoords.lon, toCoords.lat);
     var points = [];
     points.push(fromPoint);
     points.push(toPoint)
     bounds.extend(fromPoint);
     bounds.extend(toPoint);
     addRouteMarker(fromCoords, bounds, markers, coords[0][2], coords[0][3], coords[0][4], 0);
     addRouteMarker(toCoords, bounds, markers, coords[1][2], coords[1][3], coords[1][4], 0);
     lineString = new OpenLayers.Geometry.LineString(points);
     lineFeature = new OpenLayers.Feature.Vector(lineString, {projection: proj}, segmentStyle);
     lineFeature.segment_id = coords[2];
     vectorLayer.addFeatures([lineFeature]);
   }
   map.zoomToExtent(bounds, false);

}

function addSelectedHandler(vectorLayer) {
  vectorLayer.events.on({
      'featureselected': segmentSelected,
      'featureunselected': segmentUnselected
  });
  selectControl = new OpenLayers.Control.SelectFeature(vectorLayer, {multiple: false,
                                                                     toggleKey: "ctrlKey",
                                                                     multipleKey: "shiftKey"});
  map.addControl(selectControl);
  selectControl.activate();
}

function segmentSelected(event) {
  segment = event.feature;
  segment.style = segmentSelectedStyle;
  this.drawFeature(segment);
  var row = jQuery("#route_segment_" + segment.segment_id);
  row.toggleClass("selected");
  row.find(".check-route-segment").attr('checked', 'true');
}

function segmentUnselected(event) {
  segment = event.feature;
  segment.style = segmentStyle;
  this.drawFeature(segment);
  jQuery("#route_segment_" + segment.segment_id).toggleClass("selected");

}

function createMap() {

  var options = {
        'projection': new OpenLayers.Projection("EPSG:900913"),
        'units': "m",
        'numZoomLevels': 18,
        'maxResolution': 156543.0339,
        'maxExtent': new OpenLayers.Bounds(-20037508.34, -20037508.34,
                                          20037508.34, 20037508.34)
      };
  jQuery('.static-map-element').hide();
  map = new OpenLayers.Map('map', options);
  var layer = new OpenLayers.Layer.Google("Google Streets",{'sphericalMercator': true,
                                                           'maxExtent': new OpenLayers.Bounds(-20037508.34, -20037508.34,
                                                                                20037508.34, 20037508.34)});
  map.addLayer(layer);
}

function onPopupClose(evt) {
  stopUnselected(this.stop);
}

function stopUnselected(stop) {
  if (stop && stop.popup) {
      popup.stop = null;
      map.removePopup(stop.popup);
      stop.popup.destroy();
      stop.popup = null;
  }
}
function stopSelected () {
  selectStop(this);
}

function selectStop(stop) {
  if (openPopup){
    stopUnselected(openPopup.stop);
    openPopup = null;
  }
  popup = new OpenLayers.Popup.AnchoredBubble("stopPopup",
                                            stop.lonlat,
                                            new OpenLayers.Size(50,50),
                                            ''+
                                            stop.name + '',
                                            null, true, onPopupClose);
  popup.autoSize = true;
  stop.popup = popup;
  popup.stop = stop;
  map.addPopup(popup);
  openPopup = popup;
}

function addRouteMarker(stopCoords, bounds, markers, id, url, name, index) {
  bounds.extend(stopCoords);
  var size = new OpenLayers.Size(6, 6);
  var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
  var stopIcon = new OpenLayers.Icon('/images/circle-icon-sm_'+index+'.png', size, offset);
  var marker = new OpenLayers.Marker(stopCoords, stopIcon);
  marker.url = url;
  marker.name = name;
  marker.id = id;
  stopsById[id] = marker;
  marker.events.register("click", marker, stopSelected);
  markers.addMarker(marker);
}

// Run jquery in no-conflict mode so it doesn't use $()
jQuery.noConflict();

<|endoftext|>


<commit_before>define(['backbone'], function(Backbone){
	var InputModel = Backbone.Model.extend({
        initialize: function() {
            console.log(this);
        }
   	});

   	return InputModel;
});<commit_msg>removed space<commit_after>define(['backbone'], function(Backbone){

	var InputModel = Backbone.Model.extend({
        initialize: function() {
            console.log(this);
        }
   	});

   	return InputModel;
});
<|endoftext|>


<commit_before>define(["io", "modules/gameRenderer"], function (io, GameRenderer) {
    var socket = io.connect(),
        game = {};

    var App = Class.extend({
        init: function() {
            this.log_div  = ".game-state .messages";
            this.socket   = socket;
            this.render   = new GameRenderer(this);
            console.log("App - init");

            socket.on(Types.Messages.GAMESINFO, this.updateGamesInfo.bind(this));
            socket.on(Types.Messages.GAMESTATE, this.updateGameState.bind(this));
            socket.on(Types.Messages.NEWGAME, this.newGame.bind(this));
            socket.on(Types.Messages.ENTERGAME, this.enterGame.bind(this));
            socket.on(Types.Messages.INIT, this.initPlayer.bind(this));
            socket.on(Types.Messages.RADIO, this.onRadioMessage.bind(this));
            socket.on(Types.Messages.MAP, this.render.initMap.bind(this.render));
            socket.on("disconnect", this.onGameDisconnect.bind(this));

            this.bindEvents();

            $(".register button, .register select").prop("disabled", false);
            $(".loader, .game .loader").remove();

            if (name = localStorage.getItem('playername')) {
                $('.player-name').val(name);
            }
        },

        bindEvents: function () {
            var self = this;

            $(".register .new-game").on("click", function() {
                //Save name in localstorage
                var name = $('.player-name').val();
                localStorage.setItem('playername', name);
                socket.emit(Types.Messages.NEWGAME);
            });

            $(".register .game-list").on("change", function() {
                if (!$(this).val()) { return; }
                window.location = "/game/" + $(this).val();
            });

            var matches = window.location.pathname.match(/game\/([^\/]*)\/?$/);
            if (matches && matches[1]){
                var gameId = matches[1];
                localStorage.getItem('playername');
                socket.emit(Types.Messages.ENTERGAME, {game: gameId, name: name});
            }

            //Handle radio communication
             $('body').on('keydown', '.radio input', function(e) {
                if(e.keyCode == 13) {
                    var input = $(this);
                    if (input.val()) {
                        socket.emit(Types.Messages.RADIO, input.val());
                    }
                    input.val('');
                }
            });
        },

        newGame: function (data) {
            if (data.game) {
                window.location = "/game/" + data.game;
            }
        },

        enterGame: function (data) {
            if (!data.success) {
                console.log(data.error);
                window.location.hash = "";
                return;
            }

            console.log("App - enterGame");

            $(".register").remove();
            $(".game .game-id").html(data.game.id);
            $(".player-count").html(data.game.players_count);

            $(".game, .game .desktop").show();
        },

        updateGamesInfo: function (data) {
            $(".register .game-list option:gt(0)").remove();
            for (id in data.games) {
                game = data.games[id];
                $(".register .game-list").append($("<option>",{
                    value: id,
                    text: id + " (" + game.players + "/" + game.maxPlayers + ")"
                }));
            }
        },

        initPlayer: function (player) {
            this.player = player;
        },

        onRadioMessage: function (data) {
            this.logMessages(data.name + ": " + data.message);
        },

        updateGameState: function (data) {
            $(".player-count").html(data.players_count);
            this.printGameState(data);
        },

        printGameState: function(data) {
            $(".game-info").html(JSON.stringify(data, null, 2));
        },

        onGameDisconnect: function(callback) {
            setTimeout(function() {
                window.location.reload();
            }, 1000);

        },

        logMessages: function(message) {
            $("<div>").html(message).hide().appendTo('.radio .messages').fadeIn();
        }
    });

    var app = new App();
});
<commit_msg>Added small input validation.<commit_after>define(["io", "modules/gameRenderer"], function (io, GameRenderer) {
    var socket = io.connect(),
        game = {};

    var App = Class.extend({
        init: function() {
            this.log_div  = ".game-state .messages";
            this.socket   = socket;
            this.render   = new GameRenderer(this);
            console.log("App - init");

            socket.on(Types.Messages.GAMESINFO, this.updateGamesInfo.bind(this));
            socket.on(Types.Messages.GAMESTATE, this.updateGameState.bind(this));
            socket.on(Types.Messages.NEWGAME, this.newGame.bind(this));
            socket.on(Types.Messages.ENTERGAME, this.enterGame.bind(this));
            socket.on(Types.Messages.INIT, this.initPlayer.bind(this));
            socket.on(Types.Messages.RADIO, this.onRadioMessage.bind(this));
            socket.on(Types.Messages.MAP, this.render.initMap.bind(this.render));
            socket.on("disconnect", this.onGameDisconnect.bind(this));

            this.bindEvents();

            $(".register button, .register select").prop("disabled", false);
            $(".loader, .game .loader").remove();

            if (name = localStorage.getItem('playername')) {
                $('.player-name').val(name);
            }
        },

        bindEvents: function () {
            var self = this;

            $(".register .new-game").on("click", function() {
                var name = $('.player-name');
                name.removeClass('error');

                if (!name.val()) {
                    name.addClass('error');
                    return false;
                }

                //Save name in localstorage
                localStorage.setItem('playername', name.val());
                socket.emit(Types.Messages.NEWGAME);
            });

            $(".register .game-list").on("change", function() {
                var name = $('.player-name');
                name.removeClass('error');
                if (!name.val()) {
                    name.addClass('error');
                    return false;
                }
                if (!$(this).val()) { return; }
                window.location = "/game/" + $(this).val();
            });

            var matches = window.location.pathname.match(/game\/([^\/]*)\/?$/);
            if (matches && matches[1]){
                var gameId = matches[1];
                localStorage.getItem('playername');
                socket.emit(Types.Messages.ENTERGAME, {game: gameId, name: name});
            }

            //Handle radio communication
             $('body').on('keydown', '.radio input', function(e) {
                if(e.keyCode == 13) {
                    var input = $(this);
                    if (input.val()) {
                        socket.emit(Types.Messages.RADIO, input.val());
                    }
                    input.val('');
                }
            });
        },

        newGame: function (data) {
            if (data.game) {
                window.location = "/game/" + data.game;
            }
        },

        enterGame: function (data) {
            if (!data.success) {
                console.log(data.error);
                window.location.hash = "";
                return;
            }

            console.log("App - enterGame");

            $(".register").remove();
            $(".game .game-id").html(data.game.id);
            $(".player-count").html(data.game.players_count);

            $(".game, .game .desktop").show();
        },

        updateGamesInfo: function (data) {
            $(".register .game-list option:gt(0)").remove();
            for (id in data.games) {
                game = data.games[id];
                $(".register .game-list").append($("<option>",{
                    value: id,
                    text: id + " (" + game.players + "/" + game.maxPlayers + ")"
                }));
            }
        },

        initPlayer: function (player) {
            this.player = player;
        },

        onRadioMessage: function (data) {
            this.logMessages(data.name + ": " + data.message);
        },

        updateGameState: function (data) {
            $(".player-count").html(data.players_count);
            this.printGameState(data);
        },

        printGameState: function(data) {
            $(".game-info").html(JSON.stringify(data, null, 2));
        },

        onGameDisconnect: function(callback) {
            setTimeout(function() {
                window.location.reload();
            }, 1000);

        },

        logMessages: function(message) {
            $("<div>").html(message).hide().appendTo('.radio .messages').fadeIn();
        }
    });

    var app = new App();
});
<|endoftext|>