<commit_before>
var socket = io();

var words = [
    {word:"supercalifragilisticexpialidocious", action:{type:"gifBomb", gifName:"bananaMan"}},
    {word:"penis", action:{type:"gifBomb", gifName:"bananaMan"}},
    {word:"nipple", action:{type:"gifBomb", gifName:"stimpyButton"}},
    {word:"shocker", action:{type:"gifBomb", gifName:"omgCat"}},
    {word:"dildo", action:{type:"gifBomb", gifName:"rickRoll"}},
    {word:"socket", action:{type:"gifBomb", gifName:"goodDay"}},
    {word:"pickle", action:{type:"gifBomb", gifName:"sloMoFace"}},
    {word:"stank", action:{type:"gifBomb", gifName:"recursiveSmiley"}},
    {word:"twat", action:{type:"gifBomb", gifName:"freeFoodDog"}},
    {word:"pussy", action:{type:"gifBomb", gifName:"keyboardCat"}},
    {word:"snatch", action:{type:"gifBomb", gifName:"ronaldSmack"}},
    {word:"skank", action:{type:"gifBomb", gifName:"trippyMan"}},
    {word:"thong", action:{type:"addPoints", numPoints: 3}},
    {word:"silly", action:{type:"addPoints", numPoints: 5}},
    {word:"spank", action:{type:"addPoints", numPoints: 2}},
    {word:"teleport", action:{type:"teleport"}}
];

var gifBombs = [
    {name:"bananaMan", src:"images/banana-man.gif"},
    {name:"freeFoodDog", src:"images/free-food-dog.gif"},
    {name:"goodDay", src:"images/good-day.gif"},
    {name:"keyboardCat", src:"images/keyboard-cat.gif"},
    {name:"omgCat", src:"images/omg-cat.gif"},
    {name:"recursiveSmiley", src:"images/recursive-smiley.gif"},
    {name:"rickRoll", src:"images/rick-roll.gif"},
    {name:"ronaldSmack", src:"images/ronald-smack.gif"},
    {name:"sloMoFace", src:"images/slo-mo-face.gif"},
    {name:"stimpyButton", src:"images/stimpy-button.gif"},
    {name:"trippyMan", src:"images/trippy-man.gif"}
];

var colors = [
    {name:"pink", hex:""},
    {name:"green", hex:""},
    {name:"blue", hex:""},
    {name:"purple", hex:""},
    {name:"yellow", hex:""}
];

var crosshairsTarget = "";
var collectedGifBombs = [];
var isNewPlayer = true;
var me;

start_voice();

function start_voice() {
    // voice recognition
    annyang.start({ autoRestart: true });

    // show speech debug
    // annyang.debug();

    var word_matched = function(term) {

        console.log('I said:', term);

        var word = getWord(term);

        if(word && word.particle.box.intersected) {

            word.particle.explode = 300;

            socketSend({event: 'explode', body: term});

            performWordAction(word);
        }

        socketSend({event: 'said', body: term});
    }

    var commands = {
        ':term' : word_matched
    };

    /*for(var i=0; i<words.length; i++) {

        var word = words[i].word;

        commands[word] = word_matched;
    }*/

    //commands[':term'] = word_matched;

    // Add word commands to annyang
    annyang.addCommands(commands);
}

function getWord(term) {
    for(var i=0; i<words.length; i++) {
        if(term == words[i].word){
            return words[i];
        }
    }
}

function performWordAction(word) {

    if(word){

        switch(word.action.type) {
            case "gifBomb":
                sendGifBomb(word.action.gifName, "all");
            break;
            case "addPoints":
                updateScore(me.name, parseInt(me.score + word.action.numPoints));
            break;
            case "teleport":
                teleport();
            break;
        }
    }
}

function teleport() {

}

// multiplayer socket.io shit

function socketSend(message){
    socket.emit('message', message);
}

socket.on('message', function(message){
    switch(message.event) {
    case 'welcomeMessage':
        console.log('welcome '+ message.player.name + '!', message.player);
        addMyself(message.player);
    break;
    case 'players':
        console.log('player list update', message.players);
        updatePlayers(message.players);
    break;
    case 'playerPositionUpdate':
        console.log('player position update', message.player);
        updatePlayerPosition(message.player);
    break;
    case "said":
        console.log("word received thru socket: " + message.body);
    break;
    case "playerScoreUpdate":
        updateScore(message.body.playerName, message.body.score);
    break;
    case "removeCommand":
        removeCommand(message.command); // would be a commandName
    break;
    case "gifBomb":
        if(message.body.target == "all") {
            receiveGifBomb(message.body.gifName, message.body.fromPlayer); // would be a gifName
        } else {
            if (me.name == message.body.target){
                receiveGifBomb(message.body.gifName, message.body.fromPlayer); // would be a gifName
            }
        }
    break;
    }
});

// ui functions

function addMyself(myPlayer) {
    me = myPlayer;
    addPlayerToGame(me);
    var $meInScoreboard = getPlayerInScoreboardByName(me.name);
    $meInScoreboard.css({
        backgroundColor: "rgba(0, 255, 0, .4)"
    });
    updateScoreboardRankings();
}

function updatePlayerPosition(player) {
    updatePlayerAvatarPosition(player);
}

function updatePlayers(playerDbList) {
    for(var i=0; i<playerDbList.length; i++) {
        if(!getPlayerInScoreboardByName(playerDbList[i].name)) {
            addPlayerToGame(playerDbList[i]);
        }
    }

    var numScoreboardChildren = $("#scoreboard").children().length;
    if(numScoreboardChildren > playerDbList.length) {
        for(var i=0; i<numScoreboardChildren; i++) {
            var $scoreboardElement = $("#scoreboard").children().eq(i);
            var scoreboardName = $scoreboardElement.find(".scoreboardPlayerName").html();
            var nameInDb = false;
            for(var j=0; j<playerDbList.length; j++) {
                if(playerDbList[j].name == scoreboardName){
                    nameInDb = true;
                }
            }
            if(!nameInDb) {
                removePlayerFromGame(player, $scoreboardElement);
            }
        }
    }

    updateScoreboardRankings();
}

function addPlayerToGame(player) {
    $("#scoreboard").append("
"
                            +""
                            +"
"+ player.name +"
"
                            +"
"+ player.score +"
"
                            +"
"
                           )
    addPlayerAvatarToCanvas(player);
}

function removePlayerFromGame(player, $scoreboardElement) {
    $("#scoreboard").children().eq(i).remove();
    removePlayerAvatarFromCanvas(player);
}

function updateScoreboardRankings() {
    var flagAnimateUpdateScoreboard = false;
    var playersInScoreboard = [];
    var numPlayersInScoreboard = $("#scoreboard").children().length;

    for(var i=0; i<numPlayersInScoreboard; i++) {
        var elem = $("#scoreboard").children().eq(i);
        playersInScoreboard.push({
            element: elem,
            score: $("#scoreboard").children().eq(i).find(".scoreboardPlayerScore").html(),
            rank: elem.attr("data-rank")
        });
    }

    playersInScoreboard.sort(function(player1, player2) {
        // Ascending: first score less than the previous
        return player2.score - player1.score;
    });

    for(var i=0; i<playersInScoreboard.length; i++) {
        playersInScoreboard[i].element.attr("data-rank", (i+1));
    }

    for(var i=0; i<playersInScoreboard.length; i++) {
        var singlePlayerHeight = $("#scoreboard").children().eq(0).height() + 10; // +10 for padding
        playersInScoreboard[i].element.animate({
            top: (singlePlayerHeight * i - 1)
        }, 500);
    }
}

// game functions

function updateScore(playerName, newScore) {
    if(playerName == me.name) {
        me.score = newScore;
        socketSend({event: "playerScoreUpdate", body: {playerName: me.name, score: newScore}});
    }
    var $playerScoreElem = getPlayerScoreElementInScoreboardByName(playerName);
    $playerScoreElem.html(newScore);
    updateScoreboardRankings();
}

function targetInCrosshairs(target) {
    crosshairsTarget = target;
}

function nothingInCrosshairs() {
    crosshairsTarget = "";
}

function addGifBombToArsenal(gifName) {
    var gifBomb = getGifBombByName(gifName);
    collectedGifBombs.push(gifBomb);
}

function sendGifBomb(gifName, target) {
    var gifBomb = getGifBombByName(gifName);

    socketSend({event: 'gifBomb', body: {target: target, gifName: gifName}});
    console.log("sent Gif Bomb: " + gifName + " to " + target + "!!!");
    updateScore("add", me.name, me.score+3);
    return;

    for(var i=0; i<collectedGifBombs.length; i++) {
        if(gifName == collectedGifBombs[i].name) {
            collectedGifBombs.splice(i, 1);
            socketSend({event: 'gifBomb', body: {target: target, gifName: gifName}});
            console.log("sent Gif Bomb: " + gifName + " to " + target + "!!!");
            return;
        }
    }
    console.log("you don't have the gifBomb '" + gifName + "'!");
}

function receiveGifBomb(gifName, fromPlayer) {
    var gifBomb = getGifBombByName(gifName);
    document.getElementById("gifBomb").style.display = "block";
    document.getElementById("gifBomb").setAttribute("src", gifBomb.src);
    setTimeout(function(){
        document.getElementById("gifBomb").setAttribute("src", "");
        document.getElementById("gifBomb").style.display = "none";
    }, 9000);
    // ui display Gif fullscreen
    // also display who sent it
}

// util functions

function getGifBombByName(gifName) {
    for(var i=0; i<gifBombs.length; i++) {
        if(gifName == gifBombs[i].name) {
            return gifBombs[i];
        }
    }
}

function getPlayerScoreElementInScoreboardByName(playerName) {
    for(var i=0; i<$("#scoreboard").children().length; i++) {
        var childAtIndex = $("#scoreboard").children().eq(i);
        if(playerName == childAtIndex.find(".scoreboardPlayerName").html()) {
            return childAtIndex.find(".scoreboardPlayerScore");
        }
    }
}

function getPlayerInScoreboardByName(playerName) {
    for(var i=0; i<$("#scoreboard").children().length; i++) {
        var childAtIndex = $("#scoreboard").children().eq(i);
        if(playerName == childAtIndex.find(".scoreboardPlayerName").html()) {
            return childAtIndex;
        }
    }
    return 0;
}

function removeCommand(commandWord) {
    annyang.removeCommands(commandWord);
}

function addCommand(commandWord, action) {
    annyang.addCommands({commandWord: action});
}
<commit_msg>added more point words<commit_after>
var socket = io();

var words = [
    // bombs
    {word:"teleport", action:{type:"teleport"}},
    {word:"supercalifragilisticexpialidocious", action:{type:"gifBomb", gifName:"bananaMan"}},
    {word:"penis", action:{type:"gifBomb", gifName:"bananaMan"}},
    {word:"nipple", action:{type:"gifBomb", gifName:"stimpyButton"}},
    {word:"shocker", action:{type:"gifBomb", gifName:"omgCat"}},
    {word:"dildo", action:{type:"gifBomb", gifName:"rickRoll"}},
    {word:"socket", action:{type:"gifBomb", gifName:"goodDay"}},
    {word:"pickle", action:{type:"gifBomb", gifName:"sloMoFace"}},
    {word:"stank", action:{type:"gifBomb", gifName:"recursiveSmiley"}},
    {word:"twat", action:{type:"gifBomb", gifName:"freeFoodDog"}},
    {word:"pussy", action:{type:"gifBomb", gifName:"keyboardCat"}},
    {word:"snatch", action:{type:"gifBomb", gifName:"ronaldSmack"}},
    {word:"skank", action:{type:"gifBomb", gifName:"trippyMan"}},
    {word:"thong", action:{type:"gifBomb", gifName:"freeFoodDog"}},
    {word:"silly", action:{type:"gifBomb", gifName:"trippyMan"}},
    {word:"spank", action:{type:"gifBomb", gifName:"stimpyButton"}},

    // point words
    {word:"caboodle", action:{type:"addPoints", numPoints: 5}},
    {word:"banana", action:{type:"addPoints", numPoints: 5}},
    {word:"epiglottis", action:{type:"addPoints", numPoints: 5}},
    {word:"bumfuzzle", action:{type:"addPoints", numPoints: 5}},
    {word:"collywobbles", action:{type:"addPoints", numPoints: 5}},
    {word:"goomba", action:{type:"addPoints", numPoints: 5}},
    {word:"bumbershoot", action:{type:"addPoints", numPoints: 5}},
    {word:"monkey", action:{type:"addPoints", numPoints: 5}},
    {word:"nincompoop", action:{type:"addPoints", numPoints: 5}},
    {word:"stinkpot", action:{type:"addPoints", numPoints: 5}},
    {word:"kazoo", action:{type:"addPoints", numPoints: 5}},
    {word:"squabble", action:{type:"addPoints", numPoints: 5}},
    {word:"crusty", action:{type:"addPoints", numPoints: 5}},
    {word:"toejam", action:{type:"addPoints", numPoints: 5}},
    {word:"lollygag", action:{type:"addPoints", numPoints: 5}},
    {word:"slurpee", action:{type:"addPoints", numPoints: 5}},
    {word:"bloated", action:{type:"addPoints", numPoints: 5}},
    {word:"dongle", action:{type:"addPoints", numPoints: 5}},
    {word:"giblets", action:{type:"addPoints", numPoints: 5}},
    {word:"orangutan", action:{type:"addPoints", numPoints: 5}},
    {word:"nugget", action:{type:"addPoints", numPoints: 5}},
    {word:"persnickety", action:{type:"addPoints", numPoints: 5}},
    {word:"pipsqueak", action:{type:"addPoints", numPoints: 5}},
    {word:"shenanigans", action:{type:"addPoints", numPoints: 5}},
    {word:"supercilious", action:{type:"addPoints", numPoints: 5}},
    {word:"zamboni", action:{type:"addPoints", numPoints: 5}},
    {word:"schmutz", action:{type:"addPoints", numPoints: 5}},
    {word:"guacamole", action:{type:"addPoints", numPoints: 5}},
    {word:"dangler", action:{type:"addPoints", numPoints: 5}},
    {word:"snickerdoodle", action:{type:"addPoints", numPoints: 5}},
    {word:"fart", action:{type:"addPoints", numPoints: 5}},
    {word:"cheese", action:{type:"addPoints", numPoints: 5}},
    {word:"stinkbomb", action:{type:"addPoints", numPoints: 5}},
    {word:"bunion", action:{type:"addPoints", numPoints: 5}},
    {word:"bladder", action:{type:"addPoints", numPoints: 5}},
    {word:"ukulele", action:{type:"addPoints", numPoints: 5}},
    {word:"greasy", action:{type:"addPoints", numPoints: 5}},
    {word:"stanky", action:{type:"addPoints", numPoints: 20}},
    {word:"Narwhal", action:{type:"addPoints", numPoints: 5}},
    {word:"slimy", action:{type:"addPoints", numPoints: 5}},
    {word:"sourpuss", action:{type:"addPoints", numPoints: 5}}
];

var gifBombs = [
    {name:"bananaMan", src:"images/banana-man.gif"},
    {name:"freeFoodDog", src:"images/free-food-dog.gif"},
    {name:"goodDay", src:"images/good-day.gif"},
    {name:"keyboardCat", src:"images/keyboard-cat.gif"},
    {name:"omgCat", src:"images/omg-cat.gif"},
    {name:"recursiveSmiley", src:"images/recursive-smiley.gif"},
    {name:"rickRoll", src:"images/rick-roll.gif"},
    {name:"ronaldSmack", src:"images/ronald-smack.gif"},
    {name:"sloMoFace", src:"images/slo-mo-face.gif"},
    {name:"stimpyButton", src:"images/stimpy-button.gif"},
    {name:"trippyMan", src:"images/trippy-man.gif"}
];

var colors = [
    {name:"pink", hex:""},
    {name:"green", hex:""},
    {name:"blue", hex:""},
    {name:"purple", hex:""},
    {name:"yellow", hex:""}
];

var crosshairsTarget = "";
var collectedGifBombs = [];
var isNewPlayer = true;
var me;

start_voice();

function start_voice() {
    // voice recognition
    annyang.start({ autoRestart: true });

    // show speech debug
    // annyang.debug();

    var word_matched = function(term) {

        console.log('I said:', term);

        var word = getWord(term);

        if(word && word.particle.box.intersected) {

            word.particle.explode = 300;

            socketSend({event: 'explode', body: term});

            performWordAction(word);
        }

        socketSend({event: 'said', body: term});
    }

    var commands = {
        ':term' : word_matched
    };

    /*for(var i=0; i<words.length; i++) {

        var word = words[i].word;

        commands[word] = word_matched;
    }*/

    //commands[':term'] = word_matched;

    // Add word commands to annyang
    annyang.addCommands(commands);
}

function getWord(term) {
    for(var i=0; i<words.length; i++) {
        if(term == words[i].word){
            return words[i];
        }
    }
}

function performWordAction(word) {

    if(word){

        switch(word.action.type) {
            case "gifBomb":
                sendGifBomb(word.action.gifName, "all");
            break;
            case "addPoints":
                updateScore(me.name, parseInt(me.score + word.action.numPoints));
            break;
            case "teleport":
                teleport();
            break;
        }
    }
}

function teleport() {

}

// multiplayer socket.io shit

function socketSend(message){
    socket.emit('message', message);
}

socket.on('message', function(message){
    switch(message.event) {
    case 'welcomeMessage':
        console.log('welcome '+ message.player.name + '!', message.player);
        addMyself(message.player);
    break;
    case 'players':
        console.log('player list update', message.players);
        updatePlayers(message.players);
    break;
    case 'playerPositionUpdate':
        console.log('player position update', message.player);
        updatePlayerPosition(message.player);
    break;
    case "said":
        console.log("word received thru socket: " + message.body);
    break;
    case "playerScoreUpdate":
        updateScore(message.body.playerName, message.body.score);
    break;
    case "removeCommand":
        removeCommand(message.command); // would be a commandName
    break;
    case "gifBomb":
        if(message.body.target == "all") {
            receiveGifBomb(message.body.gifName, message.body.fromPlayer); // would be a gifName
        } else {
            if (me.name == message.body.target){
                receiveGifBomb(message.body.gifName, message.body.fromPlayer); // would be a gifName
            }
        }
    break;
    }
});

// ui functions

function addMyself(myPlayer) {
    me = myPlayer;
    addPlayerToGame(me);
    var $meInScoreboard = getPlayerInScoreboardByName(me.name);
    $meInScoreboard.css({
        backgroundColor: "rgba(0, 255, 0, .4)"
    });
    updateScoreboardRankings();
}

function updatePlayerPosition(player) {
    updatePlayerAvatarPosition(player);
}

function updatePlayers(playerDbList) {
    for(var i=0; i<playerDbList.length; i++) {
        if(!getPlayerInScoreboardByName(playerDbList[i].name)) {
            addPlayerToGame(playerDbList[i]);
        }
    }

    var numScoreboardChildren = $("#scoreboard").children().length;
    if(numScoreboardChildren > playerDbList.length) {
        for(var i=0; i<numScoreboardChildren; i++) {
            var $scoreboardElement = $("#scoreboard").children().eq(i);
            var scoreboardName = $scoreboardElement.find(".scoreboardPlayerName").html();
            var nameInDb = false;
            for(var j=0; j<playerDbList.length; j++) {
                if(playerDbList[j].name == scoreboardName){
                    nameInDb = true;
                }
            }
            if(!nameInDb) {
                removePlayerFromGame(player, $scoreboardElement);
            }
        }
    }

    updateScoreboardRankings();
}

function addPlayerToGame(player) {
    $("#scoreboard").append("
"
                            +""
                            +"
"+ player.name +"
"
                            +"
"+ player.score +"
"
                            +"
"
                           )
    addPlayerAvatarToCanvas(player);
}

function removePlayerFromGame(player, $scoreboardElement) {
    $("#scoreboard").children().eq(i).remove();
    removePlayerAvatarFromCanvas(player);
}

function updateScoreboardRankings() {
    var flagAnimateUpdateScoreboard = false;
    var playersInScoreboard = [];
    var numPlayersInScoreboard = $("#scoreboard").children().length;

    for(var i=0; i<numPlayersInScoreboard; i++) {
        var elem = $("#scoreboard").children().eq(i);
        playersInScoreboard.push({
            element: elem,
            score: $("#scoreboard").children().eq(i).find(".scoreboardPlayerScore").html(),
            rank: elem.attr("data-rank")
        });
    }

    playersInScoreboard.sort(function(player1, player2) {
        // Ascending: first score less than the previous
        return player2.score - player1.score;
    });

    for(var i=0; i<playersInScoreboard.length; i++) {
        playersInScoreboard[i].element.attr("data-rank", (i+1));
    }

    for(var i=0; i<playersInScoreboard.length; i++) {
        var singlePlayerHeight = $("#scoreboard").children().eq(0).height() + 10; // +10 for padding
        playersInScoreboard[i].element.animate({
            top: (singlePlayerHeight * i - 1)
        }, 500);
    }
}

// game functions

function updateScore(playerName, newScore) {
    if(playerName == me.name) {
        me.score = newScore;
        socketSend({event: "playerScoreUpdate", body: {playerName: me.name, score: newScore}});
    }
    var $playerScoreElem = getPlayerScoreElementInScoreboardByName(playerName);
    $playerScoreElem.html(newScore);
    updateScoreboardRankings();
}

function targetInCrosshairs(target) {
    crosshairsTarget = target;
}

function nothingInCrosshairs() {
    crosshairsTarget = "";
}

function addGifBombToArsenal(gifName) {
    var gifBomb = getGifBombByName(gifName);
    collectedGifBombs.push(gifBomb);
}

function sendGifBomb(gifName, target) {
    var gifBomb = getGifBombByName(gifName);

    socketSend({event: 'gifBomb', body: {target: target, gifName: gifName}});
    console.log("sent Gif Bomb: " + gifName + " to " + target + "!!!");
    updateScore("add", me.name, me.score+3);
    return;

    for(var i=0; i<collectedGifBombs.length; i++) {
        if(gifName == collectedGifBombs[i].name) {
            collectedGifBombs.splice(i, 1);
            socketSend({event: 'gifBomb', body: {target: target, gifName: gifName}});
            console.log("sent Gif Bomb: " + gifName + " to " + target + "!!!");
            return;
        }
    }
    console.log("you don't have the gifBomb '" + gifName + "'!");
}

function receiveGifBomb(gifName, fromPlayer) {
    var gifBomb = getGifBombByName(gifName);
    document.getElementById("gifBomb").style.display = "block";
    document.getElementById("gifBomb").setAttribute("src", gifBomb.src);
    setTimeout(function(){
        document.getElementById("gifBomb").setAttribute("src", "");
        document.getElementById("gifBomb").style.display = "none";
    }, 9000);
    // ui display Gif fullscreen
    // also display who sent it
}

// util functions

function getGifBombByName(gifName) {
    for(var i=0; i<gifBombs.length; i++) {
        if(gifName == gifBombs[i].name) {
            return gifBombs[i];
        }
    }
}

function getPlayerScoreElementInScoreboardByName(playerName) {
    for(var i=0; i<$("#scoreboard").children().length; i++) {
        var childAtIndex = $("#scoreboard").children().eq(i);
        if(playerName == childAtIndex.find(".scoreboardPlayerName").html()) {
            return childAtIndex.find(".scoreboardPlayerScore");
        }
    }
}

function getPlayerInScoreboardByName(playerName) {
    for(var i=0; i<$("#scoreboard").children().length; i++) {
        var childAtIndex = $("#scoreboard").children().eq(i);
        if(playerName == childAtIndex.find(".scoreboardPlayerName").html()) {
            return childAtIndex;
        }
    }
    return 0;
}

function removeCommand(commandWord) {
    annyang.removeCommands(commandWord);
}

function addCommand(commandWord, action) {
    annyang.addCommands({commandWord: action});
}
<|endoftext|>


<commit_before>// An example Backbone application contributed by
// [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple
// [LocalStorage adapter](backbone-localstorage.html)
// to persist Backbone models within your browser.

// Load the application once the DOM is ready, using `jQuery.ready`:
$(function(){

  // Todo Model
  // ----------

  // Our basic **Todo** model has `text`, `order`, and `done` attributes.
  window.Todo = Backbone.Model.extend({

    // Default attributes for a todo item.
    defaults: function() {
      return {
        done:  false,
        order: Todos.nextOrder()
      };
    },

    // Toggle the `done` state of this todo item.
    toggle: function() {
      this.save({done: !this.get("done")});
    }

  });

  // Todo Collection
  // ---------------

  // The collection of todos is backed by *localStorage* instead of a remote
  // server.
  window.TodoList = Backbone.Collection.extend({

    // Reference to this collection's model.
    model: Todo,

    // Save all of the todo items under the `"todos"` namespace.
    localStorage: new Store("todos"),

    // Filter down the list of all todo items that are finished.
    done: function() {
      return this.filter(function(todo){ return todo.get('done'); });
    },

    // Filter down the list to only todo items that are still not finished.
    remaining: function() {
      return this.without.apply(this, this.done());
    },

    // We keep the Todos in sequential order, despite being saved by unordered
    // GUID in the database. This generates the next order number for new items.
    nextOrder: function() {
      if (!this.length) return 1;
      return this.last().get('order') + 1;
    },

    // Todos are sorted by their original insertion order.
    comparator: function(todo) {
      return todo.get('order');
    }

  });

  // Create our global collection of **Todos**.
  window.Todos = new TodoList;

  // Todo Item View
  // --------------

  // The DOM element for a todo item...
  window.TodoView = Backbone.View.extend({

    //... is a list tag.
    tagName:  "li",

    // Cache the template function for a single item.
    template: _.template($('#item-template').html()),

    // The DOM events specific to an item.
    events: {
      "click .check"              : "toggleDone",
      "click div.todo-text"       : "edit",
      "click span.todo-destroy"   : "clear",
      "keypress .todo-input"      : "updateOnEnter"
    },

    // The TodoView listens for changes to its model, re-rendering.
    initialize: function() {
      this.model.bind('change', this.render, this);
      this.model.bind('destroy', this.remove, this);
    },

    // Re-render the contents of the todo item.
    render: function() {
      $(this.el).html(this.template(this.model.toJSON()));
      this.setText();
      return this;
    },

    // To avoid XSS (not that it would be harmful in this particular app),
    // we use `jQuery.text` to set the contents of the todo item.
    setText: function() {
      var text = this.model.get('text');
      this.$('.todo-text').text(text);
      this.input = this.$('.todo-input');
      this.input.bind('blur', _.bind(this.close, this)).val(text);
    },

    // Toggle the `"done"` state of the model.
    toggleDone: function() {
      this.model.toggle();
      this.$('.check').focus();
    },

    // Switch this view into `"editing"` mode, displaying the input field.
    edit: function() {
      $(this.el).addClass("editing");
      this.input.focus();
    },

    // Close the `"editing"` mode, saving changes to the todo.
    close: function() {
      this.model.save({text: this.input.val()});
      $(this.el).removeClass("editing");
    },

    // If you hit `enter`, we're through editing the item.
    updateOnEnter: function(e) {
      if (e.keyCode == 13) this.close();
    },

    // Remove this view from the DOM.
    remove: function() {
      $(this.el).remove();
    },

    // Remove the item, destroy the model.
    clear: function() {
      this.model.destroy();
    }

  });

  // The Application
  // ---------------

  // Our overall **AppView** is the top-level piece of UI.
  window.AppView = Backbone.View.extend({

    // Instead of generating a new element, bind to the existing skeleton of
    // the App already present in the HTML.
    el: $("#todoapp"),

    // Our templates for the line of statistics at the bottom of the app.
    statsCountTemplate: _.template($('#stats-count-template').html()),
    statsClearTemplate: _.template($('#stats-clear-template').html()),

    // Delegated events for creating new items, and clearing completed ones.
    events: {
      "keypress #new-todo":  "createOnEnter",
      "keyup #new-todo":     "showTooltip",
      "click .todo-clear a": "clearCompleted"
    },

    // At initialization we bind to the relevant events on the `Todos`
    // collection, when items are added or changed. Kick things off by
    // loading any preexisting todos that might be saved in *localStorage*.
    initialize: function() {
      this.input    = this.$("#new-todo");

      Todos.bind('add',   this.addOne, this);
      Todos.bind('reset', this.addAll, this);
      Todos.bind('all',   this.render, this);

      Todos.fetch();
    },

    // Re-rendering the App just means refreshing the statistics -- the rest
    // of the app doesn't change.
    render: function() {
      var total     = Todos.length
        , done      = Todos.done().length
        , remaining = Todos.remaining().length

      this.$('#todo-stats-count').html(this.statsCountTemplate({
        total: total,
        remaining: remaining
      }));

      this.$('#todo-stats-clear').html(this.statsClearTemplate({
        done: done
      }));
    },

    // Add a single todo item to the list by creating a view for it, and
    // appending its element to the `<ul>`.
    addOne: function(todo) {
      var view = new TodoView({model: todo});
      $("#todo-list").append(view.render().el);
    },

    // Add all items in the **Todos** collection at once.
    addAll: function() {
      Todos.each(this.addOne);
    },

    // If you hit return in the main input field, and there is text to save,
    // create new **Todo** model persisting it to *localStorage*.
    createOnEnter: function(e) {
      var text = this.input.val();
      if (!text || e.keyCode != 13) return;
      Todos.create({text: text});
      this.input.val('');
    },

    // Clear all done todo items, destroying their models.
    clearCompleted: function() {
      _.each(Todos.done(), function(todo){ todo.destroy(); });
      return false;
    },

    // Lazily show the tooltip that tells you to press `enter` to save
    // a new todo item, after one second.
    showTooltip: function(e) {
      var tooltip = this.$(".ui-tooltip-top");
      var val = this.input.val();
      tooltip.fadeOut();
      if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
      if (val == '' || val == this.input.attr('placeholder')) return;
      var show = function(){ tooltip.show().fadeIn(); };
      this.tooltipTimeout = _.delay(show, 1000);
    }

  });

  // Finally, we kick things off by creating the **App**.
  window.App = new AppView;

});
<commit_msg>don't call save (which fires render and changes a live region) when no changes were made<commit_after>// An example Backbone application contributed by
// [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple
// [LocalStorage adapter](backbone-localstorage.html)
// to persist Backbone models within your browser.

// Load the application once the DOM is ready, using `jQuery.ready`:
$(function(){

  // Todo Model
  // ----------

  // Our basic **Todo** model has `text`, `order`, and `done` attributes.
  window.Todo = Backbone.Model.extend({

    // Default attributes for a todo item.
    defaults: function() {
      return {
        done:  false,
        order: Todos.nextOrder()
      };
    },

    // Toggle the `done` state of this todo item.
    toggle: function() {
      this.save({done: !this.get("done")});
    }

  });

  // Todo Collection
  // ---------------

  // The collection of todos is backed by *localStorage* instead of a remote
  // server.
  window.TodoList = Backbone.Collection.extend({

    // Reference to this collection's model.
    model: Todo,

    // Save all of the todo items under the `"todos"` namespace.
    localStorage: new Store("todos"),

    // Filter down the list of all todo items that are finished.
    done: function() {
      return this.filter(function(todo){ return todo.get('done'); });
    },

    // Filter down the list to only todo items that are still not finished.
    remaining: function() {
      return this.without.apply(this, this.done());
    },

    // We keep the Todos in sequential order, despite being saved by unordered
    // GUID in the database. This generates the next order number for new items.
    nextOrder: function() {
      if (!this.length) return 1;
      return this.last().get('order') + 1;
    },

    // Todos are sorted by their original insertion order.
    comparator: function(todo) {
      return todo.get('order');
    }

  });

  // Create our global collection of **Todos**.
  window.Todos = new TodoList;

  // Todo Item View
  // --------------

  // The DOM element for a todo item...
  window.TodoView = Backbone.View.extend({

    //... is a list tag.
    tagName:  "li",

    // Cache the template function for a single item.
    template: _.template($('#item-template').html()),

    // The DOM events specific to an item.
    events: {
      "click .check"              : "toggleDone",
      "click div.todo-text"       : "edit",
      "click span.todo-destroy"   : "clear",
      "keypress .todo-input"      : "updateOnEnter"
    },

    // The TodoView listens for changes to its model, re-rendering.
    initialize: function() {
      this.model.bind('change', this.render, this);
      this.model.bind('destroy', this.remove, this);
    },

    // Re-render the contents of the todo item.
    render: function() {
      $(this.el).html(this.template(this.model.toJSON()));
      this.setText();
      return this;
    },

    // To avoid XSS (not that it would be harmful in this particular app),
    // we use `jQuery.text` to set the contents of the todo item.
    setText: function() {
      var text = this.model.get('text');
      this.$('.todo-text').text(text);
      this.input = this.$('.todo-input');
      this.input.bind('blur', _.bind(this.close, this)).val(text);
    },

    // Toggle the `"done"` state of the model.
    toggleDone: function() {
      this.model.toggle();
      this.$('.check').focus();
    },

    // Switch this view into `"editing"` mode, displaying the input field.
    edit: function() {
      $(this.el).addClass("editing");
      this.input.focus();
    },

    // Close the `"editing"` mode, saving changes to the todo.
    close: function() {
      if (this.model.changedAttributes()) {
        this.model.save({text: this.input.val()});
      }
      $(this.el).removeClass("editing");
    },

    // If you hit `enter`, we're through editing the item.
    updateOnEnter: function(e) {
      if (e.keyCode == 13) this.close();
    },

    // Remove this view from the DOM.
    remove: function() {
      $(this.el).remove();
    },

    // Remove the item, destroy the model.
    clear: function() {
      this.model.destroy();
    }

  });

  // The Application
  // ---------------

  // Our overall **AppView** is the top-level piece of UI.
  window.AppView = Backbone.View.extend({

    // Instead of generating a new element, bind to the existing skeleton of
    // the App already present in the HTML.
    el: $("#todoapp"),

    // Our templates for the line of statistics at the bottom of the app.
    statsCountTemplate: _.template($('#stats-count-template').html()),
    statsClearTemplate: _.template($('#stats-clear-template').html()),

    // Delegated events for creating new items, and clearing completed ones.
    events: {
      "keypress #new-todo":  "createOnEnter",
      "keyup #new-todo":     "showTooltip",
      "click .todo-clear a": "clearCompleted"
    },

    // At initialization we bind to the relevant events on the `Todos`
    // collection, when items are added or changed. Kick things off by
    // loading any preexisting todos that might be saved in *localStorage*.
    initialize: function() {
      this.input    = this.$("#new-todo");

      Todos.bind('add',   this.addOne, this);
      Todos.bind('reset', this.addAll, this);
      Todos.bind('all',   this.render, this);

      Todos.fetch();
    },

    // Re-rendering the App just means refreshing the statistics -- the rest
    // of the app doesn't change.
    render: function() {
      var total     = Todos.length
        , done      = Todos.done().length
        , remaining = Todos.remaining().length

      this.$('#todo-stats-count').html(this.statsCountTemplate({
        total: total,
        remaining: remaining
      }));

      this.$('#todo-stats-clear').html(this.statsClearTemplate({
        done: done
      }));
    },

    // Add a single todo item to the list by creating a view for it, and
    // appending its element to the `<ul>`.
    addOne: function(todo) {
      var view = new TodoView({model: todo});
      $("#todo-list").append(view.render().el);
    },

    // Add all items in the **Todos** collection at once.
    addAll: function() {
      Todos.each(this.addOne);
    },

    // If you hit return in the main input field, and there is text to save,
    // create new **Todo** model persisting it to *localStorage*.
    createOnEnter: function(e) {
      var text = this.input.val();
      if (!text || e.keyCode != 13) return;
      Todos.create({text: text});
      this.input.val('');
    },

    // Clear all done todo items, destroying their models.
    clearCompleted: function() {
      _.each(Todos.done(), function(todo){ todo.destroy(); });
      return false;
    },

    // Lazily show the tooltip that tells you to press `enter` to save
    // a new todo item, after one second.
    showTooltip: function(e) {
      var tooltip = this.$(".ui-tooltip-top");
      var val = this.input.val();
      tooltip.fadeOut();
      if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
      if (val == '' || val == this.input.attr('placeholder')) return;
      var show = function(){ tooltip.show().fadeIn(); };
      this.tooltipTimeout = _.delay(show, 1000);
    }

  });

  // Finally, we kick things off by creating the **App**.
  window.App = new AppView;

});
<|endoftext|>


<commit_before>var Player = function(context, player, isMe, x, y) {
    this.game = context;
    this.isMe = isMe;
    this.isSelected = false;
    this.sprites = [];
    if(player.b == 0) {
        this.sprites.push(game.add.sprite(x, y, 'female_base', 131));
        this.sprites.push(game.add.sprite(x, y, 'female_shoes', 131));
        this.sprites.push(game.add.sprite(x, y, 'female_pants', 131));
        this.sprites.push(game.add.sprite(x, y, femaleHair[player.ht], 131));
        this.sprites.push(game.add.sprite(x, y, 'female_shirt', 131));
    }
    else if(player.b == 1) {
        this.sprites.push(game.add.sprite(x, y, 'male_base', 131));
        this.sprites.push(game.add.sprite(x, y, 'male_shoes', 131));
        this.sprites.push(game.add.sprite(x, y, 'male_pants', 131));
        this.sprites.push(game.add.sprite(x, y, maleHair[player.ht], 131));
        this.sprites.push(game.add.sprite(x, y, 'male_shirt', 131));
    }
    else {
        this.sprites.push(game.add.sprite(x, y, 'skeleton_base', 131));
        this.sprites.push(game.add.sprite(x, y, 'male_shoes', 131));
        this.sprites.push(game.add.sprite(x, y, 'male_pants', 131));
        this.sprites.push(game.add.sprite(x, y, maleHair[player.ht], 131));
        this.sprites.push(game.add.sprite(x, y, 'male_shirt', 131));
        this.sprites[1].alpha = 0;
        this.sprites[4].alpha = 0;
    }
    this.sprites[0].tint = valueToColor(player.sk);
    this.sprites[3].tint = valueToColor(player.h);
    this.sprites[4].tint = valueToColor(player.sh);
    this.sprites[2].tint = valueToColor(player.p);

    for(var i in this.sprites) {
        this.sprites[i].animations.add('up', [105,106,107,108,109,110,111,112], 15, true);
        this.sprites[i].animations.add('left', [118,119,120,121,122,123,124,125], 15, true);
        this.sprites[i].animations.add('down', [131,132,133,134,135,136,137,138], 15, true);
        this.sprites[i].animations.add('right', [144,145,146,147,148,149,150,151], 15, true);
        game.physics.enable(this.sprites[i], Phaser.Physics.ARCADE);
        this.sprites[i].body.setSize(64, 64, 2, 1);
        this.sprites[i].body.collideWorldBounds = true;
    }

    this.sprites[0].inputEnabled = true;

    this.maxSpeed = 175;
    this.isMoving = false;
    this.MAX_MESSAGE_LIFE = 8000;
    this.messageLife = 0;

    this.startPoint = new Phaser.Point(x, y);
    this.targetPoint = new Phaser.Point(x, y);
    this.remainderDistance = -1;
    this.rotation = Math.PI/2;
    this.lastPosition = this.startPoint;
    this.distanceSinceLastFootstep = 0;

    this.name = game.add.text(x, y, player.n);
    this.name.font = 'Slackey';
    this.name.fill = this.isMe ? "#00ff00" : "#ffffff";
    this.name.fontSize = 13;
    this.name.stroke = '#000000';
    this.name.strokeThickness = 3;
    this.stateChanged = false;

    if(this.isMe) {
      game.camera.follow(this.sprites[0]);
    }
};

Player.prototype = {

    setSelected: function(selected) {
        this.isSelected = selected;
    },
    setMessage: function(latestMessage) {
        if(this.message != undefined) {
            this.message.destroy();
        }
        this.message = game.add.text(this.sprites[0].body.x, 0, " " + latestMessage.trim() + " ", { font: "16px Walter Turncoat", fill: '#ffffff', backgroundColor: 'rgba(0,0,0,0.75)' });
        this.messageLife = 0;
    },

    remove: function() {
        for(var i in this.sprites) {
            this.sprites[i].destroy();
        }
        this.name.destroy();
        if(this.message != undefined) {
            this.message.destroy();
        }
    },

    setTarget: function(x, y) {
        this.startPoint = new Phaser.Point(this.sprites[0].body.x, this.sprites[0].body.y);
        this.targetPoint = new Phaser.Point(x, y);

        this.remainderDistance = -1;
        if(this.startPoint.distance(this.targetPoint) > 0) {
            this.rotation = this.startPoint.angle(this.targetPoint);
        }

    },

    bringToTop: function() {
        this.name.bringToTop();
        if(this.message != undefined) {
            this.message.bringToTop();
        }
        for(var i in this.sprites) {
            this.sprites[i].bringToTop();
        }
    },

    update: function(world, rotation, force, dt) {
        moving = force != 0;

        this.stateChanged = false;
        var currentPoint = new Phaser.Point(this.sprites[0].body.x, this.sprites[0].body.y);
        if(!this.isMe) {
          rotation = this.rotation;
          force = 1;
          moving = this.isMoving;

          var newRemainderDistance = this.targetPoint.distance(currentPoint);
          if(newRemainderDistance >= this.remainderDistance && this.remainderDistance >= 0) {
            force = 0;
            this.remainderDistance = -1;
            this.startPoint = this.targetPoint;
            this.sprites[0].body.x = this.targetPoint.x;
            this.sprites[0].body.y = this.targetPoint.y;
          }
          this.remainderDistance = newRemainderDistance;

            if(this.isSelected) {
                this.name.stroke = '#00ff00';
                this.name.strokeThickness = 3;
            }
            else {
                this.name.stroke = '#000000';
                this.name.strokeThickness = 3;
            }
        }
        else {
          game.physics.arcade.collide(this.sprites[0], world);
          if(force == 0) {
              if(this.isMoving) {
                  this.stateChanged = true;
              }
              this.isMoving = false;
          }
          else {
              this.isMoving = true;
              this.stateChanged = true;
          }
        }
        this.sprites[0].body.velocity.set(0);
        if (force != 0)
        {
            var vel = force * this.maxSpeed;
            this.sprites[0].body.velocity.x = Math.cos(rotation) * vel;
            this.sprites[0].body.velocity.y = Math.sin(rotation) * vel;

            if(rotation >= -Math.PI / 4 && rotation <= Math.PI / 4) {
                for(var i in this.sprites) {
                    this.sprites[i].play('right');
                }
            }
            else if(rotation >= Math.PI * .75 || rotation <= -Math.PI * 75) {
                for(var i in this.sprites) {
                    this.sprites[i].play('left');
                }
            }
            else if (rotation < 0) {
                for(var i in this.sprites) {
                    this.sprites[i].play('up');
                }
            }
            else {
                for(var i in this.sprites) {
                    this.sprites[i].play('down');
                }
            }
        }
        else if (!moving)
        {
            for(var i in this.sprites) {
                this.sprites[i].animations.stop();
            }
        }
        this.name.x = this.sprites[0].body.x-((this.name.width-this.sprites[0].body.width)/2);
        this.name.y = this.sprites[0].body.y+this.sprites[0].body.height;
        for(var i in this.sprites) {
            this.sprites[i].body.x = this.sprites[0].body.x;
            this.sprites[i].body.y = this.sprites[0].body.y;
        }

        if(this.message != undefined) {
            this.messageLife += dt;
            if(this.messageLife <= this.MAX_MESSAGE_LIFE) {
                this.message.x = this.sprites[0].body.x-((this.message.width-this.sprites[0].body.width)/2);
                this.message.y = this.sprites[0].body.y-20;
            }
            else {
                this.message.destroy();
                this.message = undefined;
            }
        }

        var distanceTravelled = this.lastPosition.distance(currentPoint);
        this.distanceSinceLastFootstep += distanceTravelled;
        this.lastPosition = currentPoint;
        if(this.distanceSinceLastFootstep > 30) {
            var footprintX = this.sprites[0].body.x+(this.sprites[0].body.width/2);
            var footPrintY = this.sprites[0].body.y+this.sprites[0].body.height-15;
            footprints.push(new Footprint(this.game, footprintX, footPrintY, rotation));
            this.distanceSinceLastFootstep = 0;
        }
    }
};

<commit_msg>more transparent background on message text<commit_after>var Player = function(context, player, isMe, x, y) {
    this.game = context;
    this.isMe = isMe;
    this.isSelected = false;
    this.sprites = [];
    if(player.b == 0) {
        this.sprites.push(game.add.sprite(x, y, 'female_base', 131));
        this.sprites.push(game.add.sprite(x, y, 'female_shoes', 131));
        this.sprites.push(game.add.sprite(x, y, 'female_pants', 131));
        this.sprites.push(game.add.sprite(x, y, femaleHair[player.ht], 131));
        this.sprites.push(game.add.sprite(x, y, 'female_shirt', 131));
    }
    else if(player.b == 1) {
        this.sprites.push(game.add.sprite(x, y, 'male_base', 131));
        this.sprites.push(game.add.sprite(x, y, 'male_shoes', 131));
        this.sprites.push(game.add.sprite(x, y, 'male_pants', 131));
        this.sprites.push(game.add.sprite(x, y, maleHair[player.ht], 131));
        this.sprites.push(game.add.sprite(x, y, 'male_shirt', 131));
    }
    else {
        this.sprites.push(game.add.sprite(x, y, 'skeleton_base', 131));
        this.sprites.push(game.add.sprite(x, y, 'male_shoes', 131));
        this.sprites.push(game.add.sprite(x, y, 'male_pants', 131));
        this.sprites.push(game.add.sprite(x, y, maleHair[player.ht], 131));
        this.sprites.push(game.add.sprite(x, y, 'male_shirt', 131));
        this.sprites[1].alpha = 0;
        this.sprites[4].alpha = 0;
    }
    this.sprites[0].tint = valueToColor(player.sk);
    this.sprites[3].tint = valueToColor(player.h);
    this.sprites[4].tint = valueToColor(player.sh);
    this.sprites[2].tint = valueToColor(player.p);

    for(var i in this.sprites) {
        this.sprites[i].animations.add('up', [105,106,107,108,109,110,111,112], 15, true);
        this.sprites[i].animations.add('left', [118,119,120,121,122,123,124,125], 15, true);
        this.sprites[i].animations.add('down', [131,132,133,134,135,136,137,138], 15, true);
        this.sprites[i].animations.add('right', [144,145,146,147,148,149,150,151], 15, true);
        game.physics.enable(this.sprites[i], Phaser.Physics.ARCADE);
        this.sprites[i].body.setSize(64, 64, 2, 1);
        this.sprites[i].body.collideWorldBounds = true;
    }

    this.sprites[0].inputEnabled = true;

    this.maxSpeed = 175;
    this.isMoving = false;
    this.MAX_MESSAGE_LIFE = 8000;
    this.messageLife = 0;

    this.startPoint = new Phaser.Point(x, y);
    this.targetPoint = new Phaser.Point(x, y);
    this.remainderDistance = -1;
    this.rotation = Math.PI/2;
    this.lastPosition = this.startPoint;
    this.distanceSinceLastFootstep = 0;

    this.name = game.add.text(x, y, player.n);
    this.name.font = 'Slackey';
    this.name.fill = this.isMe ? "#00ff00" : "#ffffff";
    this.name.fontSize = 13;
    this.name.stroke = '#000000';
    this.name.strokeThickness = 3;
    this.stateChanged = false;

    if(this.isMe) {
      game.camera.follow(this.sprites[0]);
    }
};

Player.prototype = {

    setSelected: function(selected) {
        this.isSelected = selected;
    },
    setMessage: function(latestMessage) {
        if(this.message != undefined) {
            this.message.destroy();
        }
        this.message = game.add.text(this.sprites[0].body.x, 0, " " + latestMessage.trim() + " ", { font: "16px Walter Turncoat", fill: '#ffffff', backgroundColor: 'rgba(0,0,0,0.5)' });
        this.messageLife = 0;
    },

    remove: function() {
        for(var i in this.sprites) {
            this.sprites[i].destroy();
        }
        this.name.destroy();
        if(this.message != undefined) {
            this.message.destroy();
        }
    },

    setTarget: function(x, y) {
        this.startPoint = new Phaser.Point(this.sprites[0].body.x, this.sprites[0].body.y);
        this.targetPoint = new Phaser.Point(x, y);

        this.remainderDistance = -1;
        if(this.startPoint.distance(this.targetPoint) > 0) {
            this.rotation = this.startPoint.angle(this.targetPoint);
        }

    },

    bringToTop: function() {
        this.name.bringToTop();
        if(this.message != undefined) {
            this.message.bringToTop();
        }
        for(var i in this.sprites) {
            this.sprites[i].bringToTop();
        }
    },

    update: function(world, rotation, force, dt) {
        moving = force != 0;

        this.stateChanged = false;
        var currentPoint = new Phaser.Point(this.sprites[0].body.x, this.sprites[0].body.y);
        if(!this.isMe) {
          rotation = this.rotation;
          force = 1;
          moving = this.isMoving;

          var newRemainderDistance = this.targetPoint.distance(currentPoint);
          if(newRemainderDistance >= this.remainderDistance && this.remainderDistance >= 0) {
            force = 0;
            this.remainderDistance = -1;
            this.startPoint = this.targetPoint;
            this.sprites[0].body.x = this.targetPoint.x;
            this.sprites[0].body.y = this.targetPoint.y;
          }
          this.remainderDistance = newRemainderDistance;

            if(this.isSelected) {
                this.name.stroke = '#00ff00';
                this.name.strokeThickness = 3;
            }
            else {
                this.name.stroke = '#000000';
                this.name.strokeThickness = 3;
            }
        }
        else {
          game.physics.arcade.collide(this.sprites[0], world);
          if(force == 0) {
              if(this.isMoving) {
                  this.stateChanged = true;
              }
              this.isMoving = false;
          }
          else {
              this.isMoving = true;
              this.stateChanged = true;
          }
        }
        this.sprites[0].body.velocity.set(0);
        if (force != 0)
        {
            var vel = force * this.maxSpeed;
            this.sprites[0].body.velocity.x = Math.cos(rotation) * vel;
            this.sprites[0].body.velocity.y = Math.sin(rotation) * vel;

            if(rotation >= -Math.PI / 4 && rotation <= Math.PI / 4) {
                for(var i in this.sprites) {
                    this.sprites[i].play('right');
                }
            }
            else if(rotation >= Math.PI * .75 || rotation <= -Math.PI * 75) {
                for(var i in this.sprites) {
                    this.sprites[i].play('left');
                }
            }
            else if (rotation < 0) {
                for(var i in this.sprites) {
                    this.sprites[i].play('up');
                }
            }
            else {
                for(var i in this.sprites) {
                    this.sprites[i].play('down');
                }
            }
        }
        else if (!moving)
        {
            for(var i in this.sprites) {
                this.sprites[i].animations.stop();
            }
        }
        this.name.x = this.sprites[0].body.x-((this.name.width-this.sprites[0].body.width)/2);
        this.name.y = this.sprites[0].body.y+this.sprites[0].body.height;
        for(var i in this.sprites) {
            this.sprites[i].body.x = this.sprites[0].body.x;
            this.sprites[i].body.y = this.sprites[0].body.y;
        }

        if(this.message != undefined) {
            this.messageLife += dt;
            if(this.messageLife <= this.MAX_MESSAGE_LIFE) {
                this.message.x = this.sprites[0].body.x-((this.message.width-this.sprites[0].body.width)/2);
                this.message.y = this.sprites[0].body.y-20;
            }
            else {
                this.message.destroy();
                this.message = undefined;
            }
        }

        var distanceTravelled = this.lastPosition.distance(currentPoint);
        this.distanceSinceLastFootstep += distanceTravelled;
        this.lastPosition = currentPoint;
        if(this.distanceSinceLastFootstep > 30) {
            var footprintX = this.sprites[0].body.x+(this.sprites[0].body.width/2);
            var footPrintY = this.sprites[0].body.y+this.sprites[0].body.height-15;
            footprints.push(new Footprint(this.game, footprintX, footPrintY, rotation));
            this.distanceSinceLastFootstep = 0;
        }
    }
};

<|endoftext|>


<commit_before>'use strict';

describe('uniqFilter', function() {
  var filter;

  beforeEach(module('a8m.unique'));
  beforeEach(inject(function ($filter) {
    filter = $filter('unique');
  }));

  it('should get a collection of primitives and return filtered collection', function() {
    //Boolean
    expect(filter([true, true, false, false, true])).toEqual([true, false]);
    //numbers
    expect(filter([1, 1, 2, 3, 4, 5, 5, 5, 5])).toEqual([1, 2, 3, 4, 5]);
    //strings
    expect(filter(["Ariel", "Ariel", "Ariel"])).toEqual(["Ariel"]);
  });

  it('should get array as collection, property(nested to) as identifier and filter', function() {

    var orders = [
      { id:10, customer: { name: 'foo', id: 1 } },
      { id:11, customer: { name: 'bar', id: 2 } },
      { id:12, customer: { name: 'foo', id: 1 } },
      { id:13, customer: { name: 'bar', id: 2 } },
      { id:14, customer: { name: 'baz', id: 3 } },
    ];

    var filteredOrders = [
      { id:10, customer: { name: 'foo', id: 1 } },
      { id:11, customer: { name: 'bar', id: 2 } },
      { id:14, customer: { name: 'baz', id: 3 } },
    ];

    expect(filter(orders, 'customer.id')).toEqual(filteredOrders);
    expect(filter(orders, 'customer.id').length).toEqual(filteredOrders.length);

    expect(filter(orders, 'customer.name')).toEqual(filteredOrders);
    expect(filter(orders, 'customer.name').length).toEqual(filteredOrders.length);

    expect(filter(orders, 'id')).toEqual(orders);
    expect(filter(orders, 'id').length).toEqual(orders.length);

  });

  it('should filtered by property and not touch members without this property', function() {

    var array = [
      { id: 1, person: { name: 'Ariel' , age: 25 } },
      { id: 2, person: { name: 'Joe' , age: 25 } },
      { id: 3, person: { name: 'Bob' , age: 42 } },
      { id: 4, person: { name: 'Marie' , age: 42 } },
      {}, [], 1,2, 'foo', true, null
    ];

    var filteredArray = [
      { id: 1, person: { name: 'Ariel' , age: 25 } },
      { id: 3, person: { name: 'Bob' , age: 42 } },
      {}, [], 1,2, 'foo', true, null
    ];

    //filter by person.age
    expect(filter(array, 'person.age')).toEqual(filteredArray);

    //should not touch members without this property
    expect(filter(array, 'id')).toEqual(array);

  });

  it('should get object as collection and return filtered collection', function() {

    var dataObject = {
      0: { id: 1, data: {} },
      1: { id: 1, data: {} },
      2: { id: 2, data: {} },
      3: { id: 2, data: {} }
    };
    var dataArray = [
      { id: 1, data: {} },
      { id: 2, data: {}}
    ];

    expect(filter(dataObject, 'id')).toEqual(dataArray);

  });

  it('should support advance nested properties', function() {
    var orders = [
      { order: { person: { credit: { information: { num: 99999 } } } } },
      { order: { person: { credit: { information: { num: 99999 } } } } },
      { order: { person: { credit: { information: { num: 99999 } } } } }
    ];
    expect(filter(orders, 'order.person.credit.information.num')).toEqual([orders[0]]);
  });

});
<commit_msg>test(unique): add more tests<commit_after>'use strict';

describe('uniqFilter', function() {
  var filter;

  beforeEach(module('a8m.unique'));
  beforeEach(inject(function ($filter) {
    filter = $filter('unique');
  }));

  it('should get a collection of primitives and return filtered collection', function() {
    //Boolean
    expect(filter([true, true, false, false, true])).toEqual([true, false]);
    //numbers
    expect(filter([1, 1, 2, 3, 4, 5, 5, 5, 5])).toEqual([1, 2, 3, 4, 5]);
    //strings
    expect(filter(["Ariel", "Ariel", "Ariel"])).toEqual(["Ariel"]);
  });

  it('should get array as collection, property(nested to) as identifier and filter', function() {

    var orders = [
      { id:10, customer: { name: 'foo', id: 1 } },
      { id:11, customer: { name: 'bar', id: 2 } },
      { id:12, customer: { name: 'foo', id: 1 } },
      { id:13, customer: { name: 'bar', id: 2 } },
      { id:14, customer: { name: 'baz', id: 3 } },
    ];

    var filteredOrders = [
      { id:10, customer: { name: 'foo', id: 1 } },
      { id:11, customer: { name: 'bar', id: 2 } },
      { id:14, customer: { name: 'baz', id: 3 } },
    ];

    expect(filter(orders, 'customer.id')).toEqual(filteredOrders);
    expect(filter(orders, 'customer.id').length).toEqual(filteredOrders.length);

    expect(filter(orders, 'customer.name')).toEqual(filteredOrders);
    expect(filter(orders, 'customer.name').length).toEqual(filteredOrders.length);

    expect(filter(orders, 'id')).toEqual(orders);
    expect(filter(orders, 'id').length).toEqual(orders.length);

  });

  it('should filtered by property and not touch members without this property', function() {

    var array = [
      { id: 1, person: { name: 'Ariel' , age: 25 } },
      { id: 2, person: { name: 'Joe' , age: 25 } },
      { id: 3, person: { name: 'Bob' , age: 42 } },
      { id: 4, person: { name: 'Marie' , age: 42 } },
      {}, [], 1,2, 'foo', true, null
    ];

    var filteredArray = [
      { id: 1, person: { name: 'Ariel' , age: 25 } },
      { id: 3, person: { name: 'Bob' , age: 42 } },
      {}, [], 1,2, 'foo', true, null
    ];

    //filter by person.age
    expect(filter(array, 'person.age')).toEqual(filteredArray);

    //should not touch members without this property
    expect(filter(array, 'id')).toEqual(array);

  });

  it('should get object as collection and return filtered collection', function() {

    var dataObject = {
      0: { id: 1, data: {} },
      1: { id: 1, data: {} },
      2: { id: 2, data: {} },
      3: { id: 2, data: {} }
    };
    var dataArray = [
      { id: 1, data: {} },
      { id: 2, data: {}}
    ];

    expect(filter(dataObject, 'id')).toEqual(dataArray);

  });

  it('should support advance nested properties', function() {
    var orders = [
      { order: { person: { credit: { information: { num: 99999 } } } } },
      { order: { person: { credit: { information: { num: 99999 } } } } },
      { order: { person: { credit: { information: { num: 99999 } } } } }
    ];
    expect(filter(orders, 'order.person.credit.information.num')).toEqual([orders[0]]);
  });

  it('should get a !collection and return as-is', function() {
    expect(filter(undefined)).toEqual(undefined);
    expect(filter('foo')).toEqual('foo');
    expect(filter(1)).toEqual(1);
    expect(filter(!1)).toBeFalsy();
  });

});
<|endoftext|>


<commit_before>/**
 * Talisman tokenizers/syllables/sonoripy tests
 * =============================================
 *
 */
import assert from 'assert';
import defaultTokenizer, {
  createTokenizer,
  merge
} from '../../../src/tokenizers/syllables/sonoripy';

const VOWELS_REGEX = /[aeiouy]/;

const PHONOGRAM_HIERARCHY = [
  'aeéɛøoɔiuʌyãẽõ',
  'jwɥh',
  'rl',
  'mn',
  'zvðʒ',
  'sfθʃ',
  'bdg',
  'ptkx'
];

describe('sonoripy', function() {
  it('should merge tokens correctly.', function() {
    assert.deepEqual(merge(VOWELS_REGEX, ['his', 'to', 'ry']), ['his', 'to', 'ry']);
    assert.deepEqual(merge(VOWELS_REGEX, ['grr', 'ad', 'ual']), ['grrad', 'ual']);
    assert.deepEqual(merge(VOWELS_REGEX, ['pro', 'grr', 'am']), ['progrr', 'am']);
  });

  it('should tokenize words correctly.', function() {
    const tests = [
      ['history', ['his', 'to', 'ry']],
      ['History', ['His', 'to', 'ry']],
      ['justification', ['jus', 'ti', 'fi', 'ca', 'tion']],
      ['channel', ['chan', 'nel']],
      ['chapel', ['cha', 'pel']],
      ['unconstitutional', ['un', 'cons', 'ti', 'tu', 'tio', 'nal']]
    ];

    tests.forEach(function([word, syllables]) {
      assert.deepEqual(defaultTokenizer(word), syllables);
    });
  });

  it('should be possible to create a custom tokenizer.', function() {
    const phonogramTokenizer = createTokenizer({
      hierarchy: PHONOGRAM_HIERARCHY
    });

    // NOTE: see if breaking on diphtongue

    const tests = [
      ['ametist', ['a', 'me', 'tist']],
      // ['aɛd', ['a', 'ɛd']],
      ['arl', ['arl']],
      ['arlezjɛn', ['ar', 'le', 'zjɛn']],
      ['ãbjãs', ['ã', 'bjãs']],
      // ['diazot', ['di', 'a', 'zot']],
      ['djazot', ['dja', 'zot']],
      // ['ãtikõstitysjõ', ['ã', 'ti', 'kõs', 'ti', 'ty', 'sjõ']],
      ['pubel', ['pu', 'bel']],
      ['tjar', ['tjar']],
      // ['frao', ['fra', 'o']],
      ['fraw', ['fraw']],
      ['illegal', ['il', 'le', 'gal']],
      ['imminã', ['im', 'mi', 'nã']]
    ];

    tests.forEach(function([word, syllables]) {
      assert.deepEqual(phonogramTokenizer(word), syllables);
    });
  });
});
<commit_msg>Adding test<commit_after>/**
 * Talisman tokenizers/syllables/sonoripy tests
 * =============================================
 *
 */
import assert from 'assert';
import defaultTokenizer, {
  createTokenizer,
  merge
} from '../../../src/tokenizers/syllables/sonoripy';

const VOWELS_REGEX = /[aeiouy]/;

const PHONOGRAM_HIERARCHY = [
  'aeéɛøoɔiuʌyãẽõ',
  'jwɥh',
  'rl',
  'mn',
  'zvðʒ',
  'sfθʃ',
  'bdg',
  'ptkx'
];

describe('sonoripy', function() {
  it('should merge tokens correctly.', function() {
    assert.deepEqual(merge(VOWELS_REGEX, ['his', 'to', 'ry']), ['his', 'to', 'ry']);
    assert.deepEqual(merge(VOWELS_REGEX, ['grr', 'ad', 'ual']), ['grrad', 'ual']);
    assert.deepEqual(merge(VOWELS_REGEX, ['pro', 'grr', 'am']), ['progrr', 'am']);
  });

  it('should tokenize words correctly.', function() {
    const tests = [
      ['history', ['his', 'to', 'ry']],
      ['History', ['His', 'to', 'ry']],
      ['justification', ['jus', 'ti', 'fi', 'ca', 'tion']],
      ['channel', ['chan', 'nel']],
      ['chapel', ['cha', 'pel']],
      ['unconstitutional', ['un', 'cons', 'ti', 'tu', 'tio', 'nal']]
    ];

    tests.forEach(function([word, syllables]) {
      assert.deepEqual(defaultTokenizer(word), syllables);
    });
  });

  it('should be possible to create a custom tokenizer.', function() {
    const phonogramTokenizer = createTokenizer({
      hierarchy: PHONOGRAM_HIERARCHY
    });

    // NOTE: see if breaking on diphtongue

    const tests = [
      ['ametist', ['a', 'me', 'tist']],
      // ['aɛd', ['a', 'ɛd']],
      ['arl', ['arl']],
      ['arlezjɛn', ['ar', 'le', 'zjɛn']],
      ['ãbjãs', ['ã', 'bjãs']],
      // ['diazot', ['di', 'a', 'zot']],
      ['djazot', ['dja', 'zot']],
      ['ãtikõstitysjõ', ['ã', 'ti', 'kõs', 'ti', 'ty', 'sjõ']],
      ['pubel', ['pu', 'bel']],
      ['tjar', ['tjar']],
      // ['frao', ['fra', 'o']],
      ['fraw', ['fraw']],
      ['illegal', ['il', 'le', 'gal']],
      ['imminã', ['im', 'mi', 'nã']]
    ];

    tests.forEach(function([word, syllables]) {
      assert.deepEqual(phonogramTokenizer(word), syllables);
    });
  });
});
<|endoftext|>


<commit_before>/* this variable represents the current script element */
var me = {};

function dirname(dir)
{
   if (dir.lastIndexOf("/") == dir.length - 1)
      dir = dir.substring(0, dir.lastIndexOf("/"));

   if (dir.lastIndexOf("/") == -1)
      return "";

   return dir.substring(0, dir.lastIndexOf("/"));
}

/* relative path to the element whose script is currently being processed.*/
if (typeof document.currentScript != "undefined" && document.currentScript != null)
{
   var str = document.currentScript.src;
   me.path = (str.lastIndexOf("/") == -1) ? "." : str.substring(0, str.lastIndexOf("/"));
}
else {
   /* alternative method to get the currentScript (older browsers) */
       // ...
   /* else get the URL path */
   me.path = '.';
}

/* Get index path based on current script url and requested url */

var indexPath = '';

var size = me.path.length - 1;

for (var i = 0; i <= size; i++)
{
	if (me.path[i] == document.URL[i])
		indexPath += me.path[i];
   else
      break;
}

/* Get dirname of index path based on public folder */

var rootPath = dirname(indexPath) + '/';

var comet;

$(function(){

   comet = new jRender.ajax.Comet({
      url: indexPath + "application/index/backend"
      /* For remote requests (Cross domain) */
      //url:  "http://www.example.com/backend.php",
      //jsonp: true
   });

   var settings =
   {
      data: {},
      callback: {
         success: function(data)
         {
            // Connection established
            if (typeof data != "object")
               data = $.parseJSON(data);

            if (data.errors.length)
            {
               for (var i = data.errors.length - 1; i >= 0; i--) {
                  var code = data.errors[i].code;

                  /* Lost session */
                  if (parseInt(code) == 101)
                  {
                     // show lost session message
                     $('#lost-session-message').modal('show');

                     $("#word").attr('disabled', 'disabled');

                     setTimeout(function(){
                        location.reload();
                     }, 5000);

                     comet.disconnect();
                  }
                  else {
                     //
                  }
               };
            }
            else {

               $("#state").text("Online");

               if (!($("#" + data["timestamp"]).length))
               {
                  if ($('#content').length)
                  {
                     $('#content').append(data["msg"]);
                     $('#content')[0].scrollTop = 9999999;

                     // if (data["user"] !== $.cookie("username"))         $.cookie not works
                     if (data["user"] !== $("#current-session").val())
                     {
                        $("#notification-audio")[0].load();
                        $("#notification-audio")[0].play();
                     }
                  }
               }

               $("#online_users").empty();

               for (var i = data["online_users"].length - 1; i >= 0; i--)
               {
                  var user = data["online_users"][i];
                  var bg_x, bg_y;

                  // Get user's configuration
                  $.getJSON(rootPath + 'data/cache/' + user + '.json', function(data) {

                     var i = parseInt(data["avatar"].toString().charAt(0)) - 1;
                     var j = parseInt(data["avatar"].toString().charAt(1)) - 1;

                     var x = j;
                     var y = i;

                     bg_x = ( -32 * x ) + 3;
                     bg_y = ( -(336/11) * y ) + 3;

                     var nitem = "
" +
                                 "" +
                                 "
" +
                                 "
" + data["username"] +  "
" +
                                 "
3min
" +
                                 "
" +
                                 "
";

                     $("#online_users").append(nitem);
                  });
               };
            }

         },
         error: function(jqXHR, textStatus, errorThrown)
         {
            // Connection unestablished
            setTimeout(function(){
               if (!comet.state)
                  $("#state").text("Offline");
            }, 3000);
         },
         complete: function()
         {
            // For each request
            if (comet.state)
               $("#state").text("Online");
         }
      }
   }

   // To connect only if the cookie exists
   if (typeof $.cookie('username') != 'undefined')
      comet.connect(settings);

   // Get identity information
   $.ajax({
   	url: indexPath +  'application/index/getIdentityInformation',
   	dataType: 'json',
   	success: function(data) {

         if (typeof data != "object")
         	data = $.parseJSON(data);

   		if (data.username != null)
   			comet.connect(settings);

   	}
   })

   $("#chat").submit(function(event){

      event.preventDefault();

      if ($('#word').val().trim() != "")
      {
         var message = $('#word').val();
         $('#word').val('').attr('disabled', 'disabled');

         $('#content').append("
" + message + "
");
         $('#content')[0].scrollTop = 9999999;

         settings =
         {
            data: {
               msg: message
            },
            callback: {
               success: function(data)
               {
                  $('#content').append(data["msg"]);
               },
               error: function(jqXHR, textStatus, errorThrown) {
                  $('#loading-message-status i').attr('class', 'remove icon');
                  $('#loading-message-status').removeAttr('id');
                  $('#content').append("
Error! The message was not sent.
");
               },
               complete: function()
               {
                  if ($('#loading-message-status i').attr('class') != 'remove icon')
                     $('#loading-message-status').remove();

                  $('#word').removeAttr('disabled');

                  $('#content')[0].scrollTop = 9999999;
                  $('#word').focus();
               }
            }
         }

         comet.doRequest(settings);
      }

      return false;
   });

   /* Semantic ui tools */
   $('.ui.modal').modal();
   $('.ui.sidebar').sidebar();
   $('.ui.dropdown').dropdown();

   $("#show-users").click(function(){
      $('.ui.sidebar').sidebar('toggle');
   });

   $('.message .close').on('click', function() {
      $(this).closest('.message').fadeOut();
   });

   $j.ready(function(){

      if ($("#file_reader_response").length)
      {
         var Reader = $j.reader;

         var _files = new Reader.File({
            fileBox: document.querySelector("#file-reader-onchange"),      // input[type='file']
            dropBox: document.querySelector("#file-reader-ondrop"),        // dropbox
            preview: document.querySelector("#file-reader-ondrop"),        // preview
            url: 'source/file-upload.php',
            size: 104857600,
         });

         _files.addDropEvent(function(files){
            _files.upload(files);
         });
         _files.addChangeEvent(function(files){
            _files.upload(files, function(uploadedFiles) {
               uploadedFiles = $.parseJSON(uploadedFiles);
               var links = "
";
               for (var i = uploadedFiles.length - 1; i >= 0; i--) {
                  links += "" + uploadedFiles[i] + "  ";
               };
               links += "
";
               $("#file_reader_response").append(links);
            });
         });
      }
   });

   /* Avatar gallery */

   $("body").delegate(".tk-gallery.selectable .item", "click", function(event){
      event.preventDefault();

      var input = $(this).parent().parent().attr('data-input');

      $(".tk-gallery.selectable").find(".item").addClass("unselected").removeClass("selected");
      $(this).removeClass("unselected").addClass("selected");

      $("#"+input).val($(this).attr('data-value'));
   });

   $(".tk-gallery.selectable").find(".control-right").click(function(event){
      event.preventDefault();

      var me = $(this);

      me.addClass("disabled");

      var items = $(".tk-gallery.selectable").find('.item');

      var item = items.first().clone()
      $(".tk-gallery.selectable").find(".items").append(item);

      items.first().animate({
         width: 0
      }, 200, function(){
         items.first().remove();
         me.removeClass("disabled");
      });
   });

   $(".tk-gallery.selectable").find(".control-left").click(function(event){
      event.preventDefault();

      var me = $(this);

      me.addClass("disabled");

      var items = $(".tk-gallery.selectable").find('.item');

      var item = items.last().clone()

      $(".tk-gallery.selectable").find(".items").prepend(item);
      item.css('width', 0);

      item.animate({
         width: parseInt(items.last().css('width'))
      }, 200, function(){
         items.last().remove();
         me.removeClass("disabled");
      });

   });
});<commit_msg>Fix redirect loop when exists $.cookie and not identityInformation<commit_after>/* this variable represents the current script element */
var me = {};

function dirname(dir)
{
   if (dir.lastIndexOf("/") == dir.length - 1)
      dir = dir.substring(0, dir.lastIndexOf("/"));

   if (dir.lastIndexOf("/") == -1)
      return "";

   return dir.substring(0, dir.lastIndexOf("/"));
}

/* relative path to the element whose script is currently being processed.*/
if (typeof document.currentScript != "undefined" && document.currentScript != null)
{
   var str = document.currentScript.src;
   me.path = (str.lastIndexOf("/") == -1) ? "." : str.substring(0, str.lastIndexOf("/"));
}
else {
   /* alternative method to get the currentScript (older browsers) */
       // ...
   /* else get the URL path */
   me.path = '.';
}

/* Get index path based on current script url and requested url */

var indexPath = '';

var size = me.path.length - 1;

for (var i = 0; i <= size; i++)
{
	if (me.path[i] == document.URL[i])
		indexPath += me.path[i];
   else
      break;
}

/* Get dirname of index path based on public folder */

var rootPath = dirname(indexPath) + '/';

var comet;

$(function(){

   comet = new jRender.ajax.Comet({
      url: indexPath + "application/index/backend"
      /* For remote requests (Cross domain) */
      //url:  "http://www.example.com/backend.php",
      //jsonp: true
   });

   var settings =
   {
      data: {},
      callback: {
         success: function(data)
         {
            // Connection established
            if (typeof data != "object")
               data = $.parseJSON(data);

            if (data.errors.length)
            {
               for (var i = data.errors.length - 1; i >= 0; i--) {
                  var code = data.errors[i].code;

                  /* Lost session */
                  if (parseInt(code) == 101)
                  {
                     // show lost session message
                     $('#lost-session-message').modal('show');

                     $("#word").attr('disabled', 'disabled');

                     setTimeout(function(){
                        location.reload();
                     }, 5000);

                     comet.disconnect();
                  }
                  else {
                     //
                  }
               };
            }
            else {

               $("#state").text("Online");

               if (!($("#" + data["timestamp"]).length))
               {
                  if ($('#content').length)
                  {
                     $('#content').append(data["msg"]);
                     $('#content')[0].scrollTop = 9999999;

                     // if (data["user"] !== $.cookie("username"))         $.cookie not works
                     if (data["user"] !== $("#current-session").val())
                     {
                        $("#notification-audio")[0].load();
                        $("#notification-audio")[0].play();
                     }
                  }
               }

               $("#online_users").empty();

               for (var i = data["online_users"].length - 1; i >= 0; i--)
               {
                  var user = data["online_users"][i];
                  var bg_x, bg_y;

                  // Get user's configuration
                  $.getJSON(rootPath + 'data/cache/' + user + '.json', function(data) {

                     var i = parseInt(data["avatar"].toString().charAt(0)) - 1;
                     var j = parseInt(data["avatar"].toString().charAt(1)) - 1;

                     var x = j;
                     var y = i;

                     bg_x = ( -32 * x ) + 3;
                     bg_y = ( -(336/11) * y ) + 3;

                     var nitem = "
" +
                                 "" +
                                 "
" +
                                 "
" + data["username"] +  "
" +
                                 "
3min
" +
                                 "
" +
                                 "
";

                     $("#online_users").append(nitem);
                  });
               };
            }

         },
         error: function(jqXHR, textStatus, errorThrown)
         {
            // Connection unestablished
            setTimeout(function(){
               if (!comet.state)
                  $("#state").text("Offline");
            }, 3000);
         },
         complete: function()
         {
            // For each request
            if (comet.state)
               $("#state").text("Online");
         }
      }
   }

   // Get identity information and connect if identityInformatin is not null
   $.ajax({
   	url: indexPath +  'application/index/getIdentityInformation',
   	dataType: 'json',
   	success: function(data) {

         if (typeof data != "object")
         	data = $.parseJSON(data);

   		if (data.username != null)
   			comet.connect(settings);

   	}
   })

   $("#chat").submit(function(event){

      event.preventDefault();

      if ($('#word').val().trim() != "")
      {
         var message = $('#word').val();
         $('#word').val('').attr('disabled', 'disabled');

         $('#content').append("
" + message + "
");
         $('#content')[0].scrollTop = 9999999;

         settings =
         {
            data: {
               msg: message
            },
            callback: {
               success: function(data)
               {
                  $('#content').append(data["msg"]);
               },
               error: function(jqXHR, textStatus, errorThrown) {
                  $('#loading-message-status i').attr('class', 'remove icon');
                  $('#loading-message-status').removeAttr('id');
                  $('#content').append("
Error! The message was not sent.
");
               },
               complete: function()
               {
                  if ($('#loading-message-status i').attr('class') != 'remove icon')
                     $('#loading-message-status').remove();

                  $('#word').removeAttr('disabled');

                  $('#content')[0].scrollTop = 9999999;
                  $('#word').focus();
               }
            }
         }

         comet.doRequest(settings);
      }

      return false;
   });

   /* Semantic ui tools */
   $('.ui.modal').modal();
   $('.ui.sidebar').sidebar();
   $('.ui.dropdown').dropdown();

   $("#show-users").click(function(){
      $('.ui.sidebar').sidebar('toggle');
   });

   $('.message .close').on('click', function() {
      $(this).closest('.message').fadeOut();
   });

   $j.ready(function(){

      if ($("#file_reader_response").length)
      {
         var Reader = $j.reader;

         var _files = new Reader.File({
            fileBox: document.querySelector("#file-reader-onchange"),      // input[type='file']
            dropBox: document.querySelector("#file-reader-ondrop"),        // dropbox
            preview: document.querySelector("#file-reader-ondrop"),        // preview
            url: 'source/file-upload.php',
            size: 104857600,
         });

         _files.addDropEvent(function(files){
            _files.upload(files);
         });
         _files.addChangeEvent(function(files){
            _files.upload(files, function(uploadedFiles) {
               uploadedFiles = $.parseJSON(uploadedFiles);
               var links = "
";
               for (var i = uploadedFiles.length - 1; i >= 0; i--) {
                  links += "" + uploadedFiles[i] + "  ";
               };
               links += "
";
               $("#file_reader_response").append(links);
            });
         });
      }
   });

   /* Avatar gallery */

   $("body").delegate(".tk-gallery.selectable .item", "click", function(event){
      event.preventDefault();

      var input = $(this).parent().parent().attr('data-input');

      $(".tk-gallery.selectable").find(".item").addClass("unselected").removeClass("selected");
      $(this).removeClass("unselected").addClass("selected");

      $("#"+input).val($(this).attr('data-value'));
   });

   $(".tk-gallery.selectable").find(".control-right").click(function(event){
      event.preventDefault();

      var me = $(this);

      me.addClass("disabled");

      var items = $(".tk-gallery.selectable").find('.item');

      var item = items.first().clone()
      $(".tk-gallery.selectable").find(".items").append(item);

      items.first().animate({
         width: 0
      }, 200, function(){
         items.first().remove();
         me.removeClass("disabled");
      });
   });

   $(".tk-gallery.selectable").find(".control-left").click(function(event){
      event.preventDefault();

      var me = $(this);

      me.addClass("disabled");

      var items = $(".tk-gallery.selectable").find('.item');

      var item = items.last().clone()

      $(".tk-gallery.selectable").find(".items").prepend(item);
      item.css('width', 0);

      item.animate({
         width: parseInt(items.last().css('width'))
      }, 200, function(){
         items.last().remove();
         me.removeClass("disabled");
      });

   });
});<|endoftext|>


<commit_before>
$(function(){

  $( "form" ).validate({
    rules: {
      password2: {
          equalTo: "#p1"
      }
    }
  });

  $( "form" ).submit(function(e) {

    $.ajax({
      type: "POST",
      url: "xo-signin.herokuapp.com/webui/sign",
      dataType: 'jsonp',
      data: JSON.stringify($('form').serializeObject()),
      success: function(data) {
        alert(data); // show response
      },
      error: function(data) {
        console.log("fail");
      }
    });

    e.preventDefault();
  });
});<commit_msg>closes #17. freeuni-sdp/xo-signin#9 still active<commit_after>
$(function(){

  $( "form" ).validate({
    rules: {
      password2: {
          equalTo: "#p1"
      }
    },
    submitHandler: function(e) {

      $.ajax({
        type: "POST",
        url: "http://private-6e6f0-xosignin.apiary-mock.com/webapi/signup",
        dataType: 'json',
        data: JSON.stringify($('form').serializeObject()),
        success: function(data) {
          alert(data); // show response
        },
        error: function(data) {
          console.log("fail");
        }
      });

    }
  });

});<|endoftext|>


<commit_before>alert('Stop it.');while(1){}
<commit_msg>Remove stopit.js. Our work here is done.<commit_after><|endoftext|>


<commit_before>var Uploader = require('../../../src/uploader')

describe('webKitDataTransfer', function () {
	var uploader

	beforeEach(function () {
		uploader = new Uploader()
	})

	var getWebKitFile = function (filename) {
		return {
			isFile: true,
			isDirectory: false,
			fullPath: '/home/user/foo/' + filename,
			file: function (callback) {
				callback({
					relativePath: '/foo/' + filename
				})
			}
		}
	}

	it('should return empty array', function() {
		var event = {
			dataTransfer: {
				items: [
					{
						webkitGetAsEntry: function () {
							return false
						}
					}
				]
			}
		}
		spyOn(uploader, 'addFiles')
		uploader.webkitReadDataTransfer(event)
		expect(uploader.addFiles).toHaveBeenCalledWith([], event)
	})

	it('should return one file', function() {
		var event = {
			dataTransfer: {
				items: [
					{
						webkitGetAsEntry: function () {
							return getWebKitFile('111.txt')
						},
						getAsFile: function () {
							return {
								relativePath: '/foo/111.txt'
							}
						}
					}
				]
			}
		}
		spyOn(uploader, 'addFiles')
		uploader.webkitReadDataTransfer(event)
		expect(uploader.addFiles).toHaveBeenCalledWith(
			[{relativePath: 'home/user/foo/111.txt'}],
			event
		)
	})

	it('should return one file from subdirectory', function() {
		var event = {
			dataTransfer: {
				items: [
					{
						webkitGetAsEntry: function () {
							return {
								isFile: false,
								isDirectory: true,
								fullPath: '/home/user/foo/',
								createReader: function () {
									var entries = [
										getWebKitFile('111.txt')
									]
									return {
										readEntries: function (success, error) {
											var entry = entries.shift()
											if (entry) {
												return success([entry])
											} else {
												return success([])
											}
										}
									}
								}
							}
						}
					}
				]
			}
		}
		spyOn(uploader, 'addFiles')
		uploader.webkitReadDataTransfer(event)
		expect(uploader.addFiles).toHaveBeenCalledWith(
			[{relativePath: 'home/user/foo/111.txt'}],
			event
		)
	})

	it('should return two files from subdirectory', function() {
		var event = {
			dataTransfer: {
				items: [
					{
						webkitGetAsEntry: function () {
							return {
								isFile: false,
								isDirectory: true,
								fullPath: '/home/user/foo/',
								createReader: function () {
									var entries = [
										getWebKitFile('111.txt'),
										getWebKitFile('222.txt')
									]
									return {
										readEntries: function (success, error) {
											var entry = entries.shift()
											if (entry) {
												return success([entry])
											} else {
												return success([])
											}
										}
									}
								}
							}
						}
					}
				]
			}
		}
		spyOn(uploader, 'addFiles')
		uploader.webkitReadDataTransfer(event)
		expect(uploader.addFiles).toHaveBeenCalledWith(
			[
				{relativePath: 'home/user/foo/111.txt'},
				{relativePath: 'home/user/foo/222.txt'}
			],
			event
		)
	})
})
<commit_msg>fix test<commit_after>var Uploader = require('../../../src/uploader')

describe('webKitDataTransfer', function () {
	var uploader

	beforeEach(function () {
		uploader = new Uploader()
	})

	var getWebKitFile = function (filename) {
		return {
			isFile: true,
			isDirectory: false,
			fullPath: '/home/user/foo/' + filename,
			file: function (callback) {
				callback({
					relativePath: '/foo/' + filename
				})
			}
		}
	}

	it('should return empty array', function() {
		var event = {
			dataTransfer: {
				items: [
					{
						webkitGetAsEntry: function () {
							return false
						}
					}
				]
			}
		}
		spyOn(uploader, 'addFiles')
		uploader.webkitReadDataTransfer(event.dataTransfer, event)
		expect(uploader.addFiles).toHaveBeenCalledWith([], event)
	})

	it('should return one file', function() {
		var event = {
			dataTransfer: {
				items: [
					{
						webkitGetAsEntry: function () {
							return getWebKitFile('111.txt')
						},
						getAsFile: function () {
							return {
								relativePath: '/foo/111.txt'
							}
						}
					}
				]
			}
		}
		spyOn(uploader, 'addFiles')
		uploader.webkitReadDataTransfer(event.dataTransfer, event)
		expect(uploader.addFiles).toHaveBeenCalledWith(
			[{relativePath: 'home/user/foo/111.txt'}],
			event
		)
	})

	it('should return one file from subdirectory', function() {
		var event = {
			dataTransfer: {
				items: [
					{
						webkitGetAsEntry: function () {
							return {
								isFile: false,
								isDirectory: true,
								fullPath: '/home/user/foo/',
								createReader: function () {
									var entries = [
										getWebKitFile('111.txt')
									]
									return {
										readEntries: function (success, error) {
											var entry = entries.shift()
											if (entry) {
												return success([entry])
											} else {
												return success([])
											}
										}
									}
								}
							}
						}
					}
				]
			}
		}
		spyOn(uploader, 'addFiles')
		uploader.webkitReadDataTransfer(event.dataTransfer, event)
		expect(uploader.addFiles).toHaveBeenCalledWith(
			[{relativePath: 'home/user/foo/111.txt'}],
			event
		)
	})

	it('should return two files from subdirectory', function() {
		var event = {
			dataTransfer: {
				items: [
					{
						webkitGetAsEntry: function () {
							return {
								isFile: false,
								isDirectory: true,
								fullPath: '/home/user/foo/',
								createReader: function () {
									var entries = [
										getWebKitFile('111.txt'),
										getWebKitFile('222.txt')
									]
									return {
										readEntries: function (success, error) {
											var entry = entries.shift()
											if (entry) {
												return success([entry])
											} else {
												return success([])
											}
										}
									}
								}
							}
						}
					}
				]
			}
		}
		spyOn(uploader, 'addFiles')
		uploader.webkitReadDataTransfer(event.dataTransfer, event)
		expect(uploader.addFiles).toHaveBeenCalledWith(
			[
				{relativePath: 'home/user/foo/111.txt'},
				{relativePath: 'home/user/foo/222.txt'}
			],
			event
		)
	})
})
<|endoftext|>