view nodejs-server/app.js @ 0:89a05584e39e

initial commit of mood conductor stuff
author gyorgyf
date Sat, 16 Jun 2012 20:31:41 +0100
parents
children 9d2f4e6a3f36
line wrap: on
line source
var Application = {
  init: function() {
    this.canvas = document.getElementById('canvas');
    this.marker = document.getElementById('marker');
    this.label = document.getElementById('label');

    this.canvas.addEventListener('mousedown', this.onMouseDown.bind(this));
    this.canvas.addEventListener('mousemove', this.onMouseMove.bind(this));
    this.canvas.addEventListener('mouseup', this.onMouseUp.bind(this));
    
    this.request("/moods.csv", this.loadCSV.bind(this));
  },

  loadCSV: function(text) {
    this.moods = [];

    var lines = text.split("\n");

    for (var i = 1; i < lines.length; i++) {
      var row = lines[i].split(",");
      this.moods.push({
        label: row[1], 
        x: Number(row[3]), 
        y: Number(row[5])
      });
    }
  },
  
  request: function(url, callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
      callback(request.responseText);
    }.bind(this);
    request.open("GET", url);
    request.send(null);
  },

  onMouseDown: function(event) {
    this.mouseDown = true;
    this.setMarker(event.pageX, event.pageY);
  },

  onMouseMove: function(event) {
    if (this.mouseDown) {
      this.setMarker(event.pageX, event.pageY);
    }
  },

  onMouseUp: function(event) {
    this.mouseDown = false;
    this.setMarker(event.pageX, event.pageY);
  },

  setMarker: function(pageX, pageY) {
    this.marker.style.left = pageX + 'px';
    this.marker.style.top = pageY + 'px';
    
    var x = 1 - pageX / 480;
    var y = 1 - pageY / 960;
    
    var mood = this.findMood(x, y);

    this.marker.innerHTML = mood.label;
   
    if (mood != this.mood) {
      this.mood = mood;
      this.request("/mood?x=" + x + "&y=" + y);
    }
  },

  findMood: function(x, y) {
    var distance = 1;
    var index = null;
    
    for (var i = 0; i < this.moods.length; i++) {
      var mood = this.moods[i];
      var dx = Math.abs(mood.x - x);
      var dy = Math.abs(mood.y - y);
      var d = Math.sqrt(dx * dx + dy * dy);

      if (d < distance) {
        distance = d;
        index = i;
      }
    }

    return this.moods[index];
  }
};