<commit_before>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var x = 0;

            for (var key in gamesData.games) {
                if (!gamesData.games.hasOwnProperty(key)) {
                    continue;
                }
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game! (reload the page to see the result)
";

            var nicknames = getNicknames();

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        gameData.votes[i].target = gameData.votes[i].target.toLowerCase();
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equafls one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                                if (key.toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name                                     // (if it's in the nicknames list)
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        for (var j = 0; j < players.length; j++) {
                            if (players[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name                                     // (if it's in the players list)
                                gameData.votes[i].target = players[j];
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = targets.length - 1; i >= 0; i--) {
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                        break;
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay = gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase()) {
                                if(voters.hasOwnProperty(targets[j]) || activeVoters.hasOwnProperty(targets[j])){
                                    continue;
                                }
                                // add a new key (property) to the object for every vote target during the current day
                                voters[targets[j]] = [];
                                activeVoters[targets[j]] = [];
                            }
                        }
                    }
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            var remainingVoters = activeVoters[targets[j]].slice(0);
                            for (var z = remainingVoters.length - 1; z >= 0; z--) {
                                if (remainingVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, remove every previous vote from the active votes
                                    remainingVoters.splice(z, 1);
                                }
                            }
                            var markedVoters = voters[targets[j]].slice(0);
                            for (var z = markedVoters.length - 1; z >= 0; z--) {
                                if (markedVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, mark every previous vote with the mark "!" (unvoted) in the general votes
                                    markedVoters[z] = "!" + markedVoters[z];
                                }
                            }
                            activeVoters[targets[j]] = remainingVoters;
                            voters[targets[j]] = markedVoters;
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[j].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    var activesList = activeVoters[targets[i]];
                    for (var j = 0; j < activesList.length; j++) {
                        for (var z = nonvoters.length - 1; z >= 0; z--) {
                            if (activesList[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

             //   var orderedWagonKeys = Object.keys(voters).sort(function(a,b){return activeVoters[b].length - activeVoters[a].length});
            //    var orderedWagons = {};

            //    for(var i = 0; i < orderedWagonKeys.length; i++){
            //        var key = orderedWagonKeys[i];
            //        orderedWagons[key] = voters[key];
            //    }

            //    console.log(orderedWagonKeys);
            //    console.log(orderedWagons);

                console.log(voters);
                console.log(activeVoters);

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    var mainVotersList = voters[targets[i]].slice(0);
                    for (var j = 0; j < mainVotersList.length; j++) {
                            if (mainVotersList[j].indexOf("!") != -1) {
                                var nameWithoutMark = mainVotersList[j].substring(1);
                                mainVotersList[j] = "<s>" + nameWithoutMark + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + mainVotersList.join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]].slice(0);
                    for (var j = 0; j < votersList.length; j++) {
                            if (votersList[j].indexOf("!") != -1) {
                                var nameWithoutMark = votersList[j].substring(1);
                                votersList[j] = "[s]" + nameWithoutMark + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + votersList.join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<commit_msg>more debugging<commit_after>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var x = 0;

            for (var key in gamesData.games) {
                if (!gamesData.games.hasOwnProperty(key)) {
                    continue;
                }
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game! (reload the page to see the result)
";

            var nicknames = getNicknames();

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        gameData.votes[i].target = gameData.votes[i].target.toLowerCase();
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equafls one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                                if (key.toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name                                     // (if it's in the nicknames list)
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        for (var j = 0; j < players.length; j++) {
                            if (players[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name                                     // (if it's in the players list)
                                gameData.votes[i].target = players[j];
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = targets.length - 1; i >= 0; i--) {
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                        break;
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay = gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase()) {
                                if(voters.hasOwnProperty(targets[j]) || activeVoters.hasOwnProperty(targets[j])){
                                    continue;
                                }
                                // add a new key (property) to the object for every vote target during the current day
                                voters[targets[j]] = [];
                                activeVoters[targets[j]] = [];
                            }
                        }
                    }
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            var remainingVoters = activeVoters[targets[j]].slice(0);
                            for (var z = remainingVoters.length - 1; z >= 0; z--) {
                                if (remainingVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, remove every previous vote from the active votes
                                    remainingVoters.splice(z, 1);
                                }
                            }
                            var markedVoters = voters[targets[j]].slice(0);
                            console.log(markedVoters);
                            for (var z = markedVoters.length - 1; z >= 0; z--) {
                                if (markedVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, mark every previous vote with the mark "!" (unvoted) in the general votes
                                    markedVoters[z] = "!" + markedVoters[z];
                                }
                            }
                            activeVoters[targets[j]] = remainingVoters;
                            console.log(markedVoters);
                            voters[targets[j]] = markedVoters;
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[j].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    var activesList = activeVoters[targets[i]];
                    for (var j = 0; j < activesList.length; j++) {
                        for (var z = nonvoters.length - 1; z >= 0; z--) {
                            if (activesList[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

             //   var orderedWagonKeys = Object.keys(voters).sort(function(a,b){return activeVoters[b].length - activeVoters[a].length});
            //    var orderedWagons = {};

            //    for(var i = 0; i < orderedWagonKeys.length; i++){
            //        var key = orderedWagonKeys[i];
            //        orderedWagons[key] = voters[key];
            //    }

            //    console.log(orderedWagonKeys);
            //    console.log(orderedWagons);

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    var mainVotersList = voters[targets[i]].slice(0);
                    for (var j = 0; j < mainVotersList.length; j++) {
                            if (mainVotersList[j].indexOf("!") != -1) {
                                var nameWithoutMark = mainVotersList[j].substring(1);
                                mainVotersList[j] = "<s>" + nameWithoutMark + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + mainVotersList.join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]].slice(0);
                    for (var j = 0; j < votersList.length; j++) {
                            if (votersList[j].indexOf("!") != -1) {
                                var nameWithoutMark = votersList[j].substring(1);
                                votersList[j] = "[s]" + nameWithoutMark + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + votersList.join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<|endoftext|>


<commit_before>import Phaser from 'phaser'
import axios from 'axios'
import _ from 'lodash'
import config from '../config'
import {centerGameObjects} from '../utils'

export default class extends Phaser.State {
	init() {
		this.stage.backgroundColor = config.css.webWhite
	}

	preload() {
	}

	create() {
		const margin = 50
		this.game.add.text(margin, 50, 'High Scores:', config.text.xl)
		const logo = this.game.add.sprite(margin, 100, 'liipLogo')
		logo.scale.setTo(0.62)

		setTimeout(() => {
			this.player = this.game.add.sprite(margin * 2, 100, 'player')
			this.game.add.tween(logo).to({alpha: 0}, 300, Phaser.Easing.Linear.None, true)
		}, 500)

		setTimeout(() => {
			this.game.physics.arcade.enable(this.player)
			this.player.body.velocity.x = config.player.speed * 2
		}, 1000)

		const replay = this.game.add.sprite(this.game.width / 2, this.game.height - margin - 10, 'replay')
		replay.inputEnabled = true
		replay.events.onInputDown.add(() => {
			// logo.alpha = 0
			this.game.state.start('Game')
		})
		replay.scale.setTo(0.61)
		replay.anchor.setTo(0.5)

		axios.get(config.backendDomain + '/scores')
			.then(({data}) => data)
			.then(winners => _(winners)
				.map((score, winner) => [score, winner])
				.sort((a, b) => b[0] - a[0])
				.value())
			.then(winners => {
				winners.map(([score, w], i) => {
					const text = this.game.add.text(margin, 200 + i * 40, `Person:\t${w}\tScore:\t${score}`, config.text.lg)
					text.setShadow(-1, 1, 'rgba(0,0,0,0.5)', 0)
				})
			})
			.catch(console.warn)
	}

	render() {
	}

}
<commit_msg>restart when user hits spacebar on highscore screen<commit_after>import Phaser from 'phaser'
import axios from 'axios'
import _ from 'lodash'
import config from '../config'
import {centerGameObjects} from '../utils'

export default class extends Phaser.State {
	init() {
		this.stage.backgroundColor = config.css.webWhite
	}

	preload() {
	}

	create() {
		const margin = 50
		this.game.add.text(margin, 50, 'High Scores:', config.text.xl)
		const logo = this.game.add.sprite(margin, 100, 'liipLogo')
		logo.scale.setTo(0.62)

		setTimeout(() => {
			this.player = this.game.add.sprite(margin * 2, 100, 'player')
			this.game.add.tween(logo).to({alpha: 0}, 300, Phaser.Easing.Linear.None, true)
		}, 500)

		setTimeout(() => {
			this.game.physics.arcade.enable(this.player)
			this.player.body.velocity.x = config.player.speed * 2
		}, 1000)

		const replay = this.game.add.sprite(this.game.width / 2, this.game.height - margin - 10, 'replay')
		replay.inputEnabled = true
		replay.events.onInputDown.add(() => {
			// logo.alpha = 0
			this.game.state.start('Game')
		})
		replay.scale.setTo(0.61)
		replay.anchor.setTo(0.5)

		// init keys
		this.keys = this.game.input.keyboard.addKeys({
			space: Phaser.KeyCode.SPACEBAR,
		})

		axios.get(config.backendDomain + '/scores')
			.then(({data}) => data)
			.then(winners => _(winners)
				.map((score, winner) => [score, winner])
				.sort((a, b) => b[0] - a[0])
				.value())
			.then(winners => {
				winners.map(([score, w], i) => {
					const text = this.game.add.text(margin, 200 + i * 40, `Person:\t${w}\tScore:\t${score}`, config.text.lg)
					text.setShadow(-1, 1, 'rgba(0,0,0,0.5)', 0)
				})
			})
			.catch(console.warn)
	}

	update() {
		if (this.keys.space.isDown) {
			this.state.start('Game')
		}
	}

}
<|endoftext|>


<commit_before>module.exports = (dependencies = {}) => {
  if (!dependencies.isAlbum) {
    throw new Error('isAlbum dependency is missing')
  }

  const isAlbum = dependencies.isAlbum

  return class Store {

    constructor() {
      this.albums = []
    }

    read(callback) {
      return callback(null, this.albums)
    }

    readOneById(id, callback) {
      if (!Number.isInteger(id) || id < 0 || id >= this.albums.length) {
        return callback({ err: 'invalid id' })
      }

      return callback(null, this.albums[id])
    }

    createOne(data, callback) {
      if (!isAlbum(data)) {
        return callback({ err: 'invalid data format' })
      }

      const album = {
        id: this.albums.length,
        songs: data
      }

      this.albums.push(album)
      return callback(null, { id: album.id })
    }

    static create() {
      return new Store()
    }
  }
}
<commit_msg>use es6 object literal shorthand in store<commit_after>module.exports = (dependencies = {}) => {
  if (!dependencies.isAlbum) {
    throw new Error('isAlbum dependency is missing')
  }

  const { isAlbum } = dependencies

  return class Store {

    constructor() {
      this.albums = []
    }

    read(callback) {
      return callback(null, this.albums)
    }

    readOneById(id, callback) {
      if (!Number.isInteger(id) || id < 0 || id >= this.albums.length) {
        return callback({ err: 'invalid id' })
      }

      return callback(null, this.albums[id])
    }

    createOne(data, callback) {
      if (!isAlbum(data)) {
        return callback({ err: 'invalid data format' })
      }

      const album = {
        id: this.albums.length,
        songs: data
      }

      this.albums.push(album)
      return callback(null, { id: album.id })
    }

    static create() {
      return new Store()
    }
  }
}
<|endoftext|>


<commit_before>/**
 * jQuery if-else plugin
 *
 * Creates if(), else() and fi() methods that can be used in
 * a chain of methods on jQuery objects
 *
 * @author Vegard Løkken <vegard@headspin.no>
 * @copyright 2013
 * @version 0.1
 * @licence MIT
 */
(function( $ ) {

    /* Undef object that all chained jQuery methods work on
     * if they should not be executed */
    var $undef = $();

    /* The original object is stored here so we can restore
     * it later */
    var orig;

    /* We store the condition given in the if() method */
    var condition;

    $.fn["if"] = function(options) {
        orig = this;
        condition = !!options;

        if (!condition) {
            return $undef;
        } else {
            return this;
        }
    };

    $.fn["else"] = function( options) {
        if (orig === undefined)
            throw "else() can't be used before if()";

        return this === $undef ? orig : $undef;
    };

    $.fn["fi"] = function(options) {
        if (orig === undefined)
            throw "fi() can't be used before if()";

        var toReturn = orig;
        orig = undefined;

        return toReturn;
    };

})(jQuery);
<commit_msg>Add semicolon as first character<commit_after>/**
 * jQuery if-else plugin
 *
 * Creates if(), else() and fi() methods that can be used in
 * a chain of methods on jQuery objects
 *
 * @author Vegard Løkken <vegard@headspin.no>
 * @copyright 2013
 * @version 0.1
 * @licence MIT
 */
;(function( $ ) {

    /* Undef object that all chained jQuery methods work on
     * if they should not be executed */
    var $undef = $();

    /* The original object is stored here so we can restore
     * it later */
    var orig;

    /* We store the condition given in the if() method */
    var condition;

    $.fn["if"] = function(options) {
        orig = this;
        condition = !!options;

        if (!condition) {
            return $undef;
        } else {
            return this;
        }
    };

    $.fn["else"] = function( options) {
        if (orig === undefined)
            throw "else() can't be used before if()";

        return this === $undef ? orig : $undef;
    };

    $.fn["fi"] = function(options) {
        if (orig === undefined)
            throw "fi() can't be used before if()";

        var toReturn = orig;
        orig = undefined;

        return toReturn;
    };

})(jQuery);
<|endoftext|>


<commit_before>/**
 * @file jQuery lightweight ticker plugin
 * @author Aleix Fabra
 */
(function ($) {
  "use strict";

  var jTicker = function (attributes) {
    var defaults = {
        offset: 3
      },
      attr = attributes || {};

    /**
     * Set CSS3 Cross-browser transition to element instance
     * @param  {string} string - CSS3 transition string
     */
    function setAnimation(string) {
      attr.el.css({
        webkitTransition  : string,
        mozTransition     : string,
        msTransition      : string,
        oTransition       : string,
        transition        : string
      });
    }

    /**
     * Add animation to element instance
     */
    function addAnimation() {
      var string = 'left ' + attr.duration + 's ' + attr.effect;
      setAnimation(string);
      //Set text animation pixels
      attr.el.css({left: attr.width + 'px'});
    }

    /**
     * Remove animation to element instance
     */
    function removeAnimation() {
      var string = 'none';
      setAnimation(string);
      //Set text width to the beginning
      attr.el.css({left: 0});
    }

    /**
     * Animate element instance text
     */
    function animate() {
      //Remove animation
      removeAnimation();
      //Animate
      setTimeout(addAnimation, attr.loop * 1000);
    }

    /**
     * Detect when CSS3 transition ends
     */
    function eventsOn() {
      attr.el.on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', animate);
    }

    /**
     * Initialize function to setup the class
     */
    function initialize() {
      var width,
        containerWidth;

      //Setup css
      attr.container.css({overflow: 'hidden'});
      attr.el.css({
        whiteSpace: 'nowrap',
        position: 'relative'
      });

      width = attr.el.width();
      containerWidth = attr.container.width();

      //Check if text is bigger than it's container and start animation
      if (width > containerWidth) {

        //Calculate text width
        attr.width = (-1 * (width + defaults.offset));
        //Duplicate text
        attr.el.append(' ' + attr.el.html());
        //Add events listeners
        eventsOn();
        //Trigger first animation
        animate();
      }
    }

    return {
      'initialize': initialize
    };
  };

  var DEFAULTS = {
    duration : 50,
    loop     : 1,
    effect   : ''
  };

  /**
   * Create jTicker input object
   * @param  {number} el - current jquery element
   * @return {object} jTicker input object
   */
  function newAttr(el) {
    return {
      container : el,
      el        : el.children('span').first(),
      duration  : el.data().duration || DEFAULTS.duration,
      loop      : el.data().loop     || DEFAULTS.loop,
      effect    : el.data().effect   || DEFAULTS.effect
    };
  }

  /**
   * Initialize jQuery plugin function
   * @return {object} jQuery plugin object
   */
  $.fn.jTicker = function () {
    var animation;
    return this.each(function () {
      animation = new jTicker(newAttr($(this)));
      animation.initialize();
    });
  };

}(jQuery));<commit_msg>Small comments<commit_after>/**
 * @file jQuery lightweight ticker plugin
 * @author Aleix Fabra <aleixfabra@gmail.com>
 */
(function ($) {
  "use strict";

  var jTicker = function (attributes) {
    var defaults = {
        offset: 3
      },
      attr = attributes || {};

    /**
     * Set CSS3 Cross-browser transition to element instance
     * @param {string} string - CSS3 transition string
     */
    function setAnimation(string) {
      attr.el.css({
        webkitTransition  : string,
        mozTransition     : string,
        msTransition      : string,
        oTransition       : string,
        transition        : string
      });
    }

    /**
     * Add animation to element instance
     */
    function addAnimation() {
      var string = 'left ' + attr.duration + 's ' + attr.effect;
      setAnimation(string);
      //Set text animation pixels
      attr.el.css({left: attr.width + 'px'});
    }

    /**
     * Remove animation to element instance
     */
    function removeAnimation() {
      var string = 'none';
      setAnimation(string);
      //Set text width to the beginning
      attr.el.css({left: 0});
    }

    /**
     * Animate element instance text
     */
    function animate() {
      //Remove animation
      removeAnimation();
      //Animate
      setTimeout(addAnimation, attr.loop * 1000);
    }

    /**
     * Detect when CSS3 transition ends
     */
    function eventsOn() {
      attr.el.on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', animate);
    }

    /**
     * Initialize function to setup the class
     */
    function initialize() {
      var width,
        containerWidth;

      //Setup css
      attr.container.css({overflow: 'hidden'});
      attr.el.css({
        whiteSpace: 'nowrap',
        position: 'relative'
      });

      width = attr.el.width();
      containerWidth = attr.container.width();

      //Check if text is bigger than it's container and start animation
      if (width > containerWidth) {

        //Calculate text width
        attr.width = (-1 * (width + defaults.offset));
        //Duplicate text
        attr.el.append(' ' + attr.el.html());
        //Add events listeners
        eventsOn();
        //Trigger first animation
        animate();
      }
    }

    return {
      'initialize': initialize
    };
  };

  var DEFAULTS = {
    duration : 50,
    loop     : 1,
    effect   : ''
  };

  /**
   * Create jTicker input object
   * @param  {number} el - current jquery element
   * @return {object} jTicker input object
   */
  function newAttr(el) {
    return {
      container : el,
      el        : el.children('span').first(),
      duration  : el.data().duration || DEFAULTS.duration,
      loop      : el.data().loop     || DEFAULTS.loop,
      effect    : el.data().effect   || DEFAULTS.effect
    };
  }

  /**
   * Initialize jQuery plugin function
   * @return {object} jQuery plugin object
   */
  $.fn.jTicker = function () {
    var animation;
    return this.each(function () {
      animation = new jTicker(newAttr($(this)));
      animation.initialize();
    });
  };

}(jQuery));<|endoftext|>


<commit_before>/*!
    jQuery.kinetic v1.8.3
    Dave Taylor http://the-taylors.org/jquery.kinetic

    The MIT License (MIT)
    Copyright (c) <2011> <Dave Taylor http://the-taylors.org>
*/
/*global define,require */
(function($){
	'use strict';

    var DEFAULT_SETTINGS = {
            cursor: 'move',
            decelerate: true,
            triggerHardware: false,
            y: true,
            x: true,
            slowdown: 0.9,
            maxvelocity: 40,
            throttleFPS: 60,
            movingClass: {
                up: 'kinetic-moving-up',
                down: 'kinetic-moving-down',
                left: 'kinetic-moving-left',
                right: 'kinetic-moving-right'
            },
            deceleratingClass: {
                up: 'kinetic-decelerating-up',
                down: 'kinetic-decelerating-down',
                left: 'kinetic-decelerating-left',
                right: 'kinetic-decelerating-right'
            }
        },
        SETTINGS_KEY = 'kinetic-settings',
        ACTIVE_CLASS = 'kinetic-active';
    /**
     * Provides requestAnimationFrame in a cross browser way.
     * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
     */
    if ( !window.requestAnimationFrame ) {

        window.requestAnimationFrame = ( function() {

            return window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
                window.setTimeout( callback, 1000 / 60 );
            };

        }());

    }

    // add touch checker to jQuery.support
    $.support = $.support || {};
    $.extend($.support, {
        touch: "ontouchend" in document
    });
    var selectStart = function() { return false; };

    var decelerateVelocity = function(velocity, slowdown) {
        return Math.floor(Math.abs(velocity)) === 0 ? 0 // is velocity less than 1?
               : velocity * slowdown; // reduce slowdown
    };

    var capVelocity = function(velocity, max) {
        var newVelocity = velocity;
        if (velocity > 0) {
            if (velocity > max) {
                newVelocity = max;
            }
        } else {
            if (velocity < (0 - max)) {
                newVelocity = (0 - max);
            }
        }
        return newVelocity;
    };

    var setMoveClasses = function(settings, classes) {
        this.removeClass(settings.movingClass.up)
            .removeClass(settings.movingClass.down)
            .removeClass(settings.movingClass.left)
            .removeClass(settings.movingClass.right)
            .removeClass(settings.deceleratingClass.up)
            .removeClass(settings.deceleratingClass.down)
            .removeClass(settings.deceleratingClass.left)
            .removeClass(settings.deceleratingClass.right);

        if (settings.velocity > 0) {
            this.addClass(classes.right);
        }
        if (settings.velocity < 0) {
            this.addClass(classes.left);
        }
        if (settings.velocityY > 0) {
            this.addClass(classes.down);
        }
        if (settings.velocityY < 0) {
            this.addClass(classes.up);
        }

    };

    var stop = function($scroller, settings) {
        settings.velocity = 0;
        settings.velocityY = 0;
        settings.decelerate = true;
        if (typeof settings.stopped === 'function') {
            settings.stopped.call($scroller, settings);
        }
    };

    /** do the actual kinetic movement */
    var move = function($scroller, settings) {
        var scroller = $scroller[0];
        // set scrollLeft
        if (settings.x && scroller.scrollWidth > 0){
            scroller.scrollLeft = settings.scrollLeft = scroller.scrollLeft + settings.velocity;
            if (Math.abs(settings.velocity) > 0) {
                settings.velocity = settings.decelerate ?
                    decelerateVelocity(settings.velocity, settings.slowdown) : settings.velocity;
            }
        } else {
            settings.velocity = 0;
        }

        // set scrollTop
        if (settings.y && scroller.scrollHeight > 0){
            scroller.scrollTop = settings.scrollTop = scroller.scrollTop + settings.velocityY;
            if (Math.abs(settings.velocityY) > 0) {
                settings.velocityY = settings.decelerate ?
                    decelerateVelocity(settings.velocityY, settings.slowdown) : settings.velocityY;
            }
        } else {
            settings.velocityY = 0;
        }

        setMoveClasses.call($scroller, settings, settings.deceleratingClass);

        if (typeof settings.moved === 'function') {
            settings.moved.call($scroller, settings);
        }

        if (Math.abs(settings.velocity) > 0 || Math.abs(settings.velocityY) > 0) {
            // tick for next movement
            window.requestAnimationFrame(function(){ move($scroller, settings); });
        } else {
            stop($scroller, settings);
        }
    };

    var callOption = function(method, options) {
        var methodFn = $.kinetic.callMethods[method],
            args = Array.prototype.slice.call(arguments)
        ;
        if (methodFn) {
            this.each(function(){
                var opts = args.slice(1), settings = $(this).data(SETTINGS_KEY);
                opts.unshift(settings);
                methodFn.apply(this, opts);
            });
        }
    };

    var attachListeners = function($this, settings) {
        var element = $this[0];
        if ($.support.touch) {
            $this.bind('touchstart', settings.events.touchStart)
                .bind('touchend', settings.events.inputEnd)
                .bind('touchmove', settings.events.touchMove)
            ;
        } else {
            $this
                .mousedown(settings.events.inputDown)
                .mouseup(settings.events.inputEnd)
                .mousemove(settings.events.inputMove)
            ;
        }
        $this
            .click(settings.events.inputClick)
            .scroll(settings.events.scroll)
            .bind("selectstart", selectStart) // prevent selection when dragging
            .bind('dragstart', settings.events.dragStart);
    };
    var detachListeners = function($this, settings) {
        var element = $this[0];
        if ($.support.touch) {
            $this.unbind('touchstart', settings.events.touchStart)
                .unbind('touchend', settings.events.inputEnd)
                .unbind('touchmove', settings.events.touchMove);
        } else {
            $this
            .unbind('mousedown', settings.events.inputDown)
            .unbind('mouseup', settings.events.inputEnd)
            .unbind('mousemove', settings.events.inputMove)
            .unbind('scroll', settings.events.scroll);
        }
        $this.unbind('click', settings.events.inputClick)
        .unbind("selectstart", selectStart); // prevent selection when dragging
        $this.unbind('dragstart', settings.events.dragStart);
    };

    var initElements = function(options) {
        this
        .addClass(ACTIVE_CLASS)
        .each(function(){

            var self = this,
                $this = $(this);

            if ($this.data(SETTINGS_KEY)){
                return;
            }

            var settings = $.extend({}, DEFAULT_SETTINGS, options),
                xpos,
                prevXPos = false,
                ypos,
                prevYPos = false,
                mouseDown = false,
                scrollLeft,
                scrollTop,
                throttleTimeout = 1000 / settings.throttleFPS,
                lastMove,
                elementFocused
            ;

            settings.velocity = 0;
            settings.velocityY = 0;

            // make sure we reset everything when mouse up
            var resetMouse = function() {
                xpos = false;
                ypos = false;
                mouseDown = false;
            };
            $(document).mouseup(resetMouse).click(resetMouse);

            var calculateVelocities = function() {
                settings.velocity    = capVelocity(prevXPos - xpos, settings.maxvelocity);
                settings.velocityY   = capVelocity(prevYPos - ypos, settings.maxvelocity);
            };
            var useTarget = function(target, ev) {
                if ($.isFunction(settings.filterTarget)) {
                    return settings.filterTarget.call(self, target, ev) !== false;
                } else {
                  if (ev.which && ev.which > 1){
                    return false;
                  } else {
                    return true;
                  }
                }
            };
            var start = function(clientX, clientY) {
                mouseDown = true;
                settings.velocity = prevXPos = 0;
                settings.velocityY = prevYPos = 0;
                xpos = clientX;
                ypos = clientY;
            };
            var end = function() {
                if (xpos && prevXPos && settings.decelerate === false) {
                    settings.decelerate = true;
                    calculateVelocities();
                    xpos = prevXPos = mouseDown = false;
                    move($this, settings);
                }
            };
            var inputmove = function(clientX, clientY) {
                if (!lastMove || new Date() > new Date(lastMove.getTime() + throttleTimeout)) {
                    lastMove = new Date();

                    if (mouseDown && (xpos || ypos)) {
                        if (elementFocused) {
                            $(elementFocused).blur();
                            elementFocused = null;
                            $this.focus();
                        }
                        settings.decelerate = false;
                        settings.velocity   = settings.velocityY  = 0;
                        $this[0].scrollLeft = settings.scrollLeft = settings.x ? $this[0].scrollLeft - (clientX - xpos) : $this[0].scrollLeft;
                        $this[0].scrollTop  = settings.scrollTop  = settings.y ? $this[0].scrollTop - (clientY - ypos)  : $this[0].scrollTop;
                        prevXPos = xpos;
                        prevYPos = ypos;
                        xpos = clientX;
                        ypos = clientY;

                        calculateVelocities();
                        setMoveClasses.call($this, settings, settings.movingClass);

                        if (typeof settings.moved === 'function') {
                            settings.moved.call($this, settings);
                        }
                    }
                }
            };

            // Events
            settings.events = {
                touchStart: function(e){
                    var touch;
                    if (useTarget(e.target, e)) {
                        touch = e.originalEvent.touches[0];
                        start(touch.clientX, touch.clientY);
                        e.stopPropagation();
                    }
                },
                touchMove: function(e){
                    var touch;
                    if (mouseDown) {
                        touch = e.originalEvent.touches[0];
                        inputmove(touch.clientX, touch.clientY);
                        if (e.preventDefault) {e.preventDefault();}
                    }
                },
                inputDown: function(e){
                    if (useTarget(e.target, e)) {
                        start(e.clientX, e.clientY);
                        elementFocused = e.target;
                        if (e.target.nodeName === 'IMG'){
                            e.preventDefault();
                        }
                        e.stopPropagation();
                    }
                },
                inputEnd: function(e){
                    end();
                    elementFocused = null;
                    if (e.preventDefault) {e.preventDefault();}
                },
                inputMove: function(e) {
                    if (mouseDown){
                        inputmove(e.clientX, e.clientY);
                        if (e.preventDefault) {e.preventDefault();}
                    }
                },
                scroll: function(e) {
                    if (typeof settings.moved === 'function') {
                        settings.moved.call($this, settings);
                    }
                    if (e.preventDefault) {e.preventDefault();}
                },
                inputClick: function(e){
                    if (Math.abs(settings.velocity) > 0) {
                        e.preventDefault();
                        return false;
                    }
                },
                // prevent drag and drop images in ie
                dragStart: function(e) {
                    if (elementFocused) {
                        return false;
                    }
                }
            };

            attachListeners($this, settings);
            $this.data(SETTINGS_KEY, settings)
                .css("cursor", settings.cursor);

            if (settings.triggerHardware) {
                $this.css({
                    '-webkit-transform': 'translate3d(0,0,0)',
                    '-webkit-perspective': '1000',
                    '-webkit-backface-visibility': 'hidden'
                });
            }
        });
    };

    $.kinetic = {
        settingsKey: SETTINGS_KEY,
        callMethods: {
            start: function(settings, options){
                var $this = $(this);
                settings = $.extend(settings, options);
                if (settings) {
                    settings.decelerate = false;
                    move($this, settings);
                }
            },
            end: function(settings, options){
                var $this = $(this);
                if (settings) {
                    settings.decelerate = true;
                }
            },
            stop: function(settings, options){
                var $this = $(this);
                stop($this, settings);
            },
            detach: function(settings, options) {
                var $this = $(this);
                detachListeners($this, settings);
                $this
                .removeClass(ACTIVE_CLASS)
                .css("cursor", "");
            },
            attach: function(settings, options) {
                var $this = $(this);
                attachListeners($this, settings);
                $this
                .addClass(ACTIVE_CLASS)
                .css("cursor", "move");
            }
        }
    };
    $.fn.kinetic = function(options) {
        if (typeof options === 'string') {
            callOption.apply(this, arguments);
        } else {
            initElements.call(this, options);
        }
        return this;
    };

}(window.jQuery || window.Zepto));
<commit_msg>Stop inputEnd from stealing mouse up events when the target does not belong to it<commit_after>/*!
    jQuery.kinetic v1.8.3
    Dave Taylor http://the-taylors.org/jquery.kinetic

    The MIT License (MIT)
    Copyright (c) <2011> <Dave Taylor http://the-taylors.org>
*/
/*global define,require */
(function($){
	'use strict';

    var DEFAULT_SETTINGS = {
            cursor: 'move',
            decelerate: true,
            triggerHardware: false,
            y: true,
            x: true,
            slowdown: 0.9,
            maxvelocity: 40,
            throttleFPS: 60,
            movingClass: {
                up: 'kinetic-moving-up',
                down: 'kinetic-moving-down',
                left: 'kinetic-moving-left',
                right: 'kinetic-moving-right'
            },
            deceleratingClass: {
                up: 'kinetic-decelerating-up',
                down: 'kinetic-decelerating-down',
                left: 'kinetic-decelerating-left',
                right: 'kinetic-decelerating-right'
            }
        },
        SETTINGS_KEY = 'kinetic-settings',
        ACTIVE_CLASS = 'kinetic-active';
    /**
     * Provides requestAnimationFrame in a cross browser way.
     * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
     */
    if ( !window.requestAnimationFrame ) {

        window.requestAnimationFrame = ( function() {

            return window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
                window.setTimeout( callback, 1000 / 60 );
            };

        }());

    }

    // add touch checker to jQuery.support
    $.support = $.support || {};
    $.extend($.support, {
        touch: "ontouchend" in document
    });
    var selectStart = function() { return false; };

    var decelerateVelocity = function(velocity, slowdown) {
        return Math.floor(Math.abs(velocity)) === 0 ? 0 // is velocity less than 1?
               : velocity * slowdown; // reduce slowdown
    };

    var capVelocity = function(velocity, max) {
        var newVelocity = velocity;
        if (velocity > 0) {
            if (velocity > max) {
                newVelocity = max;
            }
        } else {
            if (velocity < (0 - max)) {
                newVelocity = (0 - max);
            }
        }
        return newVelocity;
    };

    var setMoveClasses = function(settings, classes) {
        this.removeClass(settings.movingClass.up)
            .removeClass(settings.movingClass.down)
            .removeClass(settings.movingClass.left)
            .removeClass(settings.movingClass.right)
            .removeClass(settings.deceleratingClass.up)
            .removeClass(settings.deceleratingClass.down)
            .removeClass(settings.deceleratingClass.left)
            .removeClass(settings.deceleratingClass.right);

        if (settings.velocity > 0) {
            this.addClass(classes.right);
        }
        if (settings.velocity < 0) {
            this.addClass(classes.left);
        }
        if (settings.velocityY > 0) {
            this.addClass(classes.down);
        }
        if (settings.velocityY < 0) {
            this.addClass(classes.up);
        }

    };

    var stop = function($scroller, settings) {
        settings.velocity = 0;
        settings.velocityY = 0;
        settings.decelerate = true;
        if (typeof settings.stopped === 'function') {
            settings.stopped.call($scroller, settings);
        }
    };

    /** do the actual kinetic movement */
    var move = function($scroller, settings) {
        var scroller = $scroller[0];
        // set scrollLeft
        if (settings.x && scroller.scrollWidth > 0){
            scroller.scrollLeft = settings.scrollLeft = scroller.scrollLeft + settings.velocity;
            if (Math.abs(settings.velocity) > 0) {
                settings.velocity = settings.decelerate ?
                    decelerateVelocity(settings.velocity, settings.slowdown) : settings.velocity;
            }
        } else {
            settings.velocity = 0;
        }

        // set scrollTop
        if (settings.y && scroller.scrollHeight > 0){
            scroller.scrollTop = settings.scrollTop = scroller.scrollTop + settings.velocityY;
            if (Math.abs(settings.velocityY) > 0) {
                settings.velocityY = settings.decelerate ?
                    decelerateVelocity(settings.velocityY, settings.slowdown) : settings.velocityY;
            }
        } else {
            settings.velocityY = 0;
        }

        setMoveClasses.call($scroller, settings, settings.deceleratingClass);

        if (typeof settings.moved === 'function') {
            settings.moved.call($scroller, settings);
        }

        if (Math.abs(settings.velocity) > 0 || Math.abs(settings.velocityY) > 0) {
            // tick for next movement
            window.requestAnimationFrame(function(){ move($scroller, settings); });
        } else {
            stop($scroller, settings);
        }
    };

    var callOption = function(method, options) {
        var methodFn = $.kinetic.callMethods[method],
            args = Array.prototype.slice.call(arguments)
        ;
        if (methodFn) {
            this.each(function(){
                var opts = args.slice(1), settings = $(this).data(SETTINGS_KEY);
                opts.unshift(settings);
                methodFn.apply(this, opts);
            });
        }
    };

    var attachListeners = function($this, settings) {
        var element = $this[0];
        if ($.support.touch) {
            $this.bind('touchstart', settings.events.touchStart)
                .bind('touchend', settings.events.inputEnd)
                .bind('touchmove', settings.events.touchMove)
            ;
        } else {
            $this
                .mousedown(settings.events.inputDown)
                .mouseup(settings.events.inputEnd)
                .mousemove(settings.events.inputMove)
            ;
        }
        $this
            .click(settings.events.inputClick)
            .scroll(settings.events.scroll)
            .bind("selectstart", selectStart) // prevent selection when dragging
            .bind('dragstart', settings.events.dragStart);
    };
    var detachListeners = function($this, settings) {
        var element = $this[0];
        if ($.support.touch) {
            $this.unbind('touchstart', settings.events.touchStart)
                .unbind('touchend', settings.events.inputEnd)
                .unbind('touchmove', settings.events.touchMove);
        } else {
            $this
            .unbind('mousedown', settings.events.inputDown)
            .unbind('mouseup', settings.events.inputEnd)
            .unbind('mousemove', settings.events.inputMove)
            .unbind('scroll', settings.events.scroll);
        }
        $this.unbind('click', settings.events.inputClick)
        .unbind("selectstart", selectStart); // prevent selection when dragging
        $this.unbind('dragstart', settings.events.dragStart);
    };

    var initElements = function(options) {
        this
        .addClass(ACTIVE_CLASS)
        .each(function(){

            var self = this,
                $this = $(this);

            if ($this.data(SETTINGS_KEY)){
                return;
            }

            var settings = $.extend({}, DEFAULT_SETTINGS, options),
                xpos,
                prevXPos = false,
                ypos,
                prevYPos = false,
                mouseDown = false,
                scrollLeft,
                scrollTop,
                throttleTimeout = 1000 / settings.throttleFPS,
                lastMove,
                elementFocused
            ;

            settings.velocity = 0;
            settings.velocityY = 0;

            // make sure we reset everything when mouse up
            var resetMouse = function() {
                xpos = false;
                ypos = false;
                mouseDown = false;
            };
            $(document).mouseup(resetMouse).click(resetMouse);

            var calculateVelocities = function() {
                settings.velocity    = capVelocity(prevXPos - xpos, settings.maxvelocity);
                settings.velocityY   = capVelocity(prevYPos - ypos, settings.maxvelocity);
            };
            var useTarget = function(target, ev) {
                if ($.isFunction(settings.filterTarget)) {
                    return settings.filterTarget.call(self, target, ev) !== false;
                } else {
                  if (ev.which && ev.which > 1){
                    return false;
                  } else {
                    return true;
                  }
                }
            };
            var start = function(clientX, clientY) {
                mouseDown = true;
                settings.velocity = prevXPos = 0;
                settings.velocityY = prevYPos = 0;
                xpos = clientX;
                ypos = clientY;
            };
            var end = function() {
                if (xpos && prevXPos && settings.decelerate === false) {
                    settings.decelerate = true;
                    calculateVelocities();
                    xpos = prevXPos = mouseDown = false;
                    move($this, settings);
                }
            };
            var inputmove = function(clientX, clientY) {
                if (!lastMove || new Date() > new Date(lastMove.getTime() + throttleTimeout)) {
                    lastMove = new Date();

                    if (mouseDown && (xpos || ypos)) {
                        if (elementFocused) {
                            $(elementFocused).blur();
                            elementFocused = null;
                            $this.focus();
                        }
                        settings.decelerate = false;
                        settings.velocity   = settings.velocityY  = 0;
                        $this[0].scrollLeft = settings.scrollLeft = settings.x ? $this[0].scrollLeft - (clientX - xpos) : $this[0].scrollLeft;
                        $this[0].scrollTop  = settings.scrollTop  = settings.y ? $this[0].scrollTop - (clientY - ypos)  : $this[0].scrollTop;
                        prevXPos = xpos;
                        prevYPos = ypos;
                        xpos = clientX;
                        ypos = clientY;

                        calculateVelocities();
                        setMoveClasses.call($this, settings, settings.movingClass);

                        if (typeof settings.moved === 'function') {
                            settings.moved.call($this, settings);
                        }
                    }
                }
            };

            // Events
            settings.events = {
                touchStart: function(e){
                    var touch;
                    if (useTarget(e.target, e)) {
                        touch = e.originalEvent.touches[0];
                        start(touch.clientX, touch.clientY);
                        e.stopPropagation();
                    }
                },
                touchMove: function(e){
                    var touch;
                    if (mouseDown) {
                        touch = e.originalEvent.touches[0];
                        inputmove(touch.clientX, touch.clientY);
                        if (e.preventDefault) {e.preventDefault();}
                    }
                },
                inputDown: function(e){
                    if (useTarget(e.target, e)) {
                        start(e.clientX, e.clientY);
                        elementFocused = e.target;
                        if (e.target.nodeName === 'IMG'){
                            e.preventDefault();
                        }
                        e.stopPropagation();
                    }
                },
                inputEnd: function(e){
                    if (useTarget(e.target, e)) {
                        end();
                        elementFocused = null;
                        if (e.preventDefault) {e.preventDefault();}
                    }
                },
                inputMove: function(e) {
                    if (mouseDown){
                        inputmove(e.clientX, e.clientY);
                        if (e.preventDefault) {e.preventDefault();}
                    }
                },
                scroll: function(e) {
                    if (typeof settings.moved === 'function') {
                        settings.moved.call($this, settings);
                    }
                    if (e.preventDefault) {e.preventDefault();}
                },
                inputClick: function(e){
                    if (Math.abs(settings.velocity) > 0) {
                        e.preventDefault();
                        return false;
                    }
                },
                // prevent drag and drop images in ie
                dragStart: function(e) {
                    if (elementFocused) {
                        return false;
                    }
                }
            };

            attachListeners($this, settings);
            $this.data(SETTINGS_KEY, settings)
                .css("cursor", settings.cursor);

            if (settings.triggerHardware) {
                $this.css({
                    '-webkit-transform': 'translate3d(0,0,0)',
                    '-webkit-perspective': '1000',
                    '-webkit-backface-visibility': 'hidden'
                });
            }
        });
    };

    $.kinetic = {
        settingsKey: SETTINGS_KEY,
        callMethods: {
            start: function(settings, options){
                var $this = $(this);
                settings = $.extend(settings, options);
                if (settings) {
                    settings.decelerate = false;
                    move($this, settings);
                }
            },
            end: function(settings, options){
                var $this = $(this);
                if (settings) {
                    settings.decelerate = true;
                }
            },
            stop: function(settings, options){
                var $this = $(this);
                stop($this, settings);
            },
            detach: function(settings, options) {
                var $this = $(this);
                detachListeners($this, settings);
                $this
                .removeClass(ACTIVE_CLASS)
                .css("cursor", "");
            },
            attach: function(settings, options) {
                var $this = $(this);
                attachListeners($this, settings);
                $this
                .addClass(ACTIVE_CLASS)
                .css("cursor", "move");
            }
        }
    };
    $.fn.kinetic = function(options) {
        if (typeof options === 'string') {
            callOption.apply(this, arguments);
        } else {
            initElements.call(this, options);
        }
        return this;
    };

}(window.jQuery || window.Zepto));
<|endoftext|>


<commit_before>(function($)
{
  var methods =
  {
    update: function()
    {
      methods.loadPage.apply(this, [0]);
    },
    nextPage: function()
    {
      var page = parseInt($(this).data("options").tail, 10);
      var library = this;

      methods.loadPage.apply(this, [page + 1])
        .done(function(images)
        {
          if(images.length > 0)
          {
            $(library).data("options").tail++;
          }
        });
    },
    loadPage: function(page)
    {
      var f = $(this).data("options").onLoad;

      if(f)
      {
        var library = this;

        return f(page, $(library).data("options").pageSize)
          .done(function(images)
          {
            $(images).each(function()
            {
              methods.touch.apply(library, [this, true]);
            });
          });
      }

      return null;
    },
    touch: function(image, insert)
    {
      // test if image has already been inserted:
      var li = $(this).find('li[data-source="' + image["source"] + '"]').first();

      if(li.get(0))
      {
        // update details of already inserted image:
        $(li).find('span[data-field="comments_n"]').html(image["comments_n"]);
        $(li).find('span[data-field="up"]').html(image["score"]["up"]);
        $(li).find('span[data-field="down"]').html(image["score"]["down"]);
        $(li).find('span[data-field="fav"]').html(image["score"]["fav"]);
      }
      else
      {
        var compare = $(this).data("options").onCompare;

        // insert new image:
        var html = '
' +
                   '' +
                   '
' + image["source"] + '
' +
                   '
Created on: ' +
                   '' + new Date(image["created_on"]["$date"]).toLocaleString() + '
' +
                   '
Comments: ' +
                   '' + image["comments_n"] + '
' +
                   '
Score: ' +
                   '' + image["score"]["up"] + ' up,' +
                   '' + image["score"]["down"] + ' down, ' +
                   '' + image["score"]["fav"] + ' favs
' +
                   '
';

        var inserted = false;

        if(compare)
        {
          $(this).find("li").each(function()
          {
            var obj = {};

            obj["source"] = $(this).data("source");
            obj["created_on"] = {"$data": $(this).data("timestamp")}
            obj["comments_n"] = parseInt($(li).find('span[data-field="comments_n"]').text(), 10);
            obj["score"] = {}
            obj["score"]["up"] = parseInt($(li).find('span[data-field="up"]').text(), 10);
            obj["score"]["down"] = parseInt($(li).find('span[data-field="down"]').text(), 10);
            obj["score"]["fav"] = parseInt($(li).find('span[data-field="fav"]').text(), 10);

            if(compare(image, obj))
            {
              $(html).insertBefore(this);
              inserted = true;
            }
          });
        }

        if(!inserted)
        {
          $(this).append(html);
        }
      }

      $(this).listview("refresh");

      // load thumbnail:
      var client = new MeatStore().createClient();

      client.getThumbnail(image["source"])
        .success(function(thumbnail)
        {
          $('img[data-source="' + image["source"] + '"]').attr("src", thumbnail);
        })
        .fail(function(r)
        {
          $('img[data-source="' + image["source"] + '"]').attr("src", "images/image-missing.png");
        });
    },
    clear: function()
    {
      $(this).find("li").remove();
      $(this).listview("refresh");
    }
  };

  function createLibrary(obj, options)
  {
    $(obj).data("options", $.extend({pageSize: 10, tail: 0, onLoad: null, onCompare: null}, options));
    $(obj).data("images", new Array());
  }

  $.fn.library = function(args)
  {
    if(methods[args])
    {
      this.each(function()
      {
        return methods[args].apply(this, Array.prototype.slice.call(arguments, 1));
      });
    }
    else if(typeof args === 'object' || !args)
    {
      return this.each(function()
      {
        createLibrary(this, args);
      });
    }
  }
}(jQuery));
<commit_msg>renamed data attributes in jquery.library, don't call jquery.library methods if selected DOM element hasn't been initialized with jquery.library() call before<commit_after>(function($)
{
  var methods =
  {
    update: function()
    {
      methods.loadPage.apply(this, [0]);
    },
    nextPage: function()
    {
      var page = parseInt($(this).data("jquery.library.options").tail, 10);
      var library = this;

      methods.loadPage.apply(this, [page + 1])
        .done(function(images)
        {
          if(images.length > 0)
          {
            $(library).data("jquery.library.options").tail++;
          }
        });
    },
    loadPage: function(page)
    {
      var f = $(this).data("jquery.library.options").onLoad;

      if(f)
      {
        var library = this;

        return f(page, $(this).data("jquery.library.options").pageSize)
          .done(function(images)
          {
            $(images).each(function()
            {
              methods.touch.apply(library, [this, true]);
            });
          });
      }

      return null;
    },
    touch: function(image, insert)
    {
      // test if image has already been inserted:
      var li = $(this).find('li[data-source="' + image["source"] + '"]').first();

      if(li.get(0))
      {
        // update details of already inserted image:
        $(li).find('span[data-field="comments_n"]').html(image["comments_n"]);
        $(li).find('span[data-field="up"]').html(image["score"]["up"]);
        $(li).find('span[data-field="down"]').html(image["score"]["down"]);
        $(li).find('span[data-field="fav"]').html(image["score"]["fav"]);
      }
      else if(insert)
      {
        var compare = $(this).data("jquery.library.options").onCompare;

        // insert new image:
        var html = '
' +
                   '' +
                   '
' + image["source"] + '
' +
                   '
Created on: ' +
                   '' + new Date(image["created_on"]["$date"]).toLocaleString() + '
' +
                   '
Comments: ' +
                   '' + image["comments_n"] + '
' +
                   '
Score: ' +
                   '' + image["score"]["up"] + ' up,' +
                   '' + image["score"]["down"] + ' down, ' +
                   '' + image["score"]["fav"] + ' favs
' +
                   '
';

        var inserted = false;

        if(compare)
        {
          $(this).find("li").each(function()
          {
            var obj = {};

            obj["source"] = $(this).data("source");
            obj["created_on"] = {"$data": $(this).data("timestamp")}
            obj["comments_n"] = parseInt($(li).find('span[data-field="comments_n"]').text(), 10);
            obj["score"] = {}
            obj["score"]["up"] = parseInt($(li).find('span[data-field="up"]').text(), 10);
            obj["score"]["down"] = parseInt($(li).find('span[data-field="down"]').text(), 10);
            obj["score"]["fav"] = parseInt($(li).find('span[data-field="fav"]').text(), 10);

            if(compare(image, obj))
            {
              $(html).insertBefore(this);
              inserted = true;
            }
          });
        }

        if(!inserted)
        {
          $(this).append(html);
        }
      }

      $(this).listview("refresh");

      // load thumbnail:
      var client = new MeatStore().createClient();

      client.getThumbnail(image["source"])
        .success(function(thumbnail)
        {
          $('img[data-source="' + image["source"] + '"]').attr("src", thumbnail);
        })
        .fail(function(r)
        {
          $('img[data-source="' + image["source"] + '"]').attr("src", "images/image-missing.png");
        });
    },
    clear: function()
    {
      $(this).find("li").remove();
      $(this).listview("refresh");
    }
  };

  function createLibrary(obj, options)
  {
    $(obj).data("jquery.library", true);
    $(obj).data("jquery.library.options", $.extend({pageSize: 10, tail: 0, onLoad: null, onCompare: null}, options));
  }

  $.fn.library = function(args)
  {
    if(methods[args])
    {
      var parameters = Array.prototype.slice.call(arguments, 1);

      this.each(function()
      {
        if($(this).data("jquery.library"))
        {
          return methods[args].apply(this, parameters);
        }
        else
        {
          return null;
        }
      });
    }
    else if(typeof args === 'object' || !args)
    {
      return this.each(function()
      {
        createLibrary(this, args);
      });
    }
  }
}(jQuery));
<|endoftext|>


<commit_before>(function ($) {

	$.mqSync = {
		currentMediaQuery: '', // The current media query
		mqOrderNamed: {}, // The order of the named media queries
		mqOrderNumbered: [], // The order of the media queries

		/**
		 * Set up the media query plugin
		 * @param options The options to pass at run time
		 */
		init: function (options) {
			// Initialize the media query
			this.currentMediaQuery = this.fetchMediaQuery();
			$('body').data('media-query', this.currentMediaQuery);

			// On window resize, set media query var
			$(window).resize(this.onResize);
		},

		/**
		 * Check if the media query name is a match
		 * @param which The media query to check against
		 */
		matches: function (which) {
			// See if the current media query matches the requested one
			return (this.fetchMediaQuery() == which);
		},

		/**
		 * Check if the media query is greater than the specified
		 * @param which The media query to check against
		 */
		isAbove: function (which) {
			return (this.mqOrderNamed[this.fetchMediaQuery()] >= this.mqOrderNamed[which]);
		},

		/**
		 * Check if the media query is less than the specified
		 * @param which The media query to check against
		 */
		isBelow: function (which) {
			return (this.mqOrderNamed[this.fetchMediaQuery()] < this.mqOrderNamed[which]);
		},

		/**
		 * When the browser is resized, update the media query
		 */
		onResize: function () {
			var lastQuery = this.currentMediaQuery;

			// Set the global current media query
			this.currentMediaQuery = $.mqSync.fetchMediaQuery();

			// The media query does not match the old
			if (this.currentMediaQuery != lastQuery) {
				// Fire an event noting that the media query has changed
				$('html').trigger('mediaQueryChange', [this.currentMediaQuery, lastQuery]);
				$('body').data('media-query', this.currentMediaQuery);
			}

		},

		/**
		 * Read in the media query
		 */
		fetchMediaQuery: function () {
			// We read in the media query name from the html element's font family
			var mq = $('html').css('font-family');

			// Strip out quotes and commas
			mq = mq.replace(/['",]/g, '');

			return mq;
		},

		/**
		 * Set the order of media queries
		 * @param orderedArray An array of the media queries in order from smallest to largest
		 */
		setOrder: function (orderedArray) {
			var self = this;

			this.mqOrderNumbered = orderedArray;

			$.each(orderedArray, function(index, value) {
				self.mqOrderNamed[value] = index;
			});
		},

		/**
		 * This module resizes responsive images automatically
		*/
		responsiveImages: {

			/**
			 * Initialize events
			 */
			init: function() {
				var self = this;

				// Every time the media query changes, do these things
				function onMediaQueryChange (event, newMediaQuery, oldMediaQuery) {
					self.update(newMediaQuery);
				}

				$('html').on('mediaQueryChange', onMediaQueryChange);

				// Loop through each and store its original source
				$('img.responsive').each(function () {
					$(this).data('original-src', $(this).attr('src'));
				});

				// Update the current responsive image size
				this.update();
			},

			/**
			 * Run through each responsive image and see if an image exists at that media query
			 * @param newMediaQuery [current] The new media query to load
			 */
			update: function (newMediaQuery) {
				// Default to the current media query - just run an update
				if (newMediaQuery == null)
					newMediaQuery = $.mqSync.fetchMediaQuery();

				// Loop over each responsive image and update its source
				$('img.responsive').each(function () {
					var mqOrderNumbered = $.mqSync.mqOrderNumbered,
						$img = $(this),
						mqMax = 0,
						currentSource = null;

					mqMax = $.mqSync.mqOrderNamed[newMediaQuery];

					// If there is an ordered list of media queries
					if ($.mqSync.mqOrderNumbered.length > 0) {
						// Loop backwards and find the nearest match
						for (var ii = mqMax; ii >= 0; ii--) {
							currentSource = $img.data($.mqSync.mqOrderNumbered[ii] + '-src');

							if (currentSource != null) {
								break;
							}
						}
					} else {
						// No ordered list of media queries, so just check the current
						currentSource = $img.data(newMediaQuery + '-src');
					}

					if (currentSource) {
						// There is an image supplied for this media query
 						$img.attr('src', currentSource);
					} else {
						// Default to the original image
						$img.attr('src', $img.data('original-src'));
					}
				});
			}

		} // End responsive images module

	};

	// Do this stuff when the page is ready
	$(document).ready(function () {
		$.mqSync.init();
	});

}(jQuery));
<commit_msg>Detect font-family on head vs html<commit_after>(function ($) {

	$.mqSync = {
		currentMediaQuery: '', // The current media query
		mqOrderNamed: {}, // The order of the named media queries
		mqOrderNumbered: [], // The order of the media queries

		/**
		 * Set up the media query plugin
		 * @param options The options to pass at run time
		 */
		init: function (options) {
			// Initialize the media query
			this.currentMediaQuery = this.fetchMediaQuery();
			$('body').data('media-query', this.currentMediaQuery);

			// On window resize, set media query var
			$(window).resize(this.onResize);
		},

		/**
		 * Check if the media query name is a match
		 * @param which The media query to check against
		 */
		matches: function (which) {
			// See if the current media query matches the requested one
			return (this.fetchMediaQuery() == which);
		},

		/**
		 * Check if the media query is greater than the specified
		 * @param which The media query to check against
		 */
		isAbove: function (which) {
			return (this.mqOrderNamed[this.fetchMediaQuery()] >= this.mqOrderNamed[which]);
		},

		/**
		 * Check if the media query is less than the specified
		 * @param which The media query to check against
		 */
		isBelow: function (which) {
			return (this.mqOrderNamed[this.fetchMediaQuery()] < this.mqOrderNamed[which]);
		},

		/**
		 * When the browser is resized, update the media query
		 */
		onResize: function () {
			var lastQuery = this.currentMediaQuery;

			// Set the global current media query
			this.currentMediaQuery = $.mqSync.fetchMediaQuery();

			// The media query does not match the old
			if (this.currentMediaQuery != lastQuery) {
				// Fire an event noting that the media query has changed
				$('html').trigger('mediaQueryChange', [this.currentMediaQuery, lastQuery]);
				$('body').data('media-query', this.currentMediaQuery);
			}

		},

		/**
		 * Read in the media query
		 */
		fetchMediaQuery: function () {
			// We read in the media query name from the html element's font family
			var mq = $('head').css('font-family');

			// Strip out quotes and commas
			mq = mq.replace(/['",]/g, '');

			return mq;
		},

		/**
		 * Set the order of media queries
		 * @param orderedArray An array of the media queries in order from smallest to largest
		 */
		setOrder: function (orderedArray) {
			var self = this;

			this.mqOrderNumbered = orderedArray;

			$.each(orderedArray, function(index, value) {
				self.mqOrderNamed[value] = index;
			});
		},

		/**
		 * This module resizes responsive images automatically
		*/
		responsiveImages: {

			/**
			 * Initialize events
			 */
			init: function() {
				var self = this;

				// Every time the media query changes, do these things
				function onMediaQueryChange (event, newMediaQuery, oldMediaQuery) {
					self.update(newMediaQuery);
				}

				$('html').on('mediaQueryChange', onMediaQueryChange);

				// Loop through each and store its original source
				$('img.responsive').each(function () {
					$(this).data('original-src', $(this).attr('src'));
				});

				// Update the current responsive image size
				this.update();
			},

			/**
			 * Run through each responsive image and see if an image exists at that media query
			 * @param newMediaQuery [current] The new media query to load
			 */
			update: function (newMediaQuery) {
				// Default to the current media query - just run an update
				if (newMediaQuery == null)
					newMediaQuery = $.mqSync.fetchMediaQuery();

				// Loop over each responsive image and update its source
				$('img.responsive').each(function () {
					var mqOrderNumbered = $.mqSync.mqOrderNumbered,
						$img = $(this),
						mqMax = 0,
						currentSource = null;

					mqMax = $.mqSync.mqOrderNamed[newMediaQuery];

					// If there is an ordered list of media queries
					if ($.mqSync.mqOrderNumbered.length > 0) {
						// Loop backwards and find the nearest match
						for (var ii = mqMax; ii >= 0; ii--) {
							currentSource = $img.data($.mqSync.mqOrderNumbered[ii] + '-src');

							if (currentSource != null) {
								break;
							}
						}
					} else {
						// No ordered list of media queries, so just check the current
						currentSource = $img.data(newMediaQuery + '-src');
					}

					if (currentSource) {
						// There is an image supplied for this media query
 						$img.attr('src', currentSource);
					} else {
						// Default to the original image
						$img.attr('src', $img.data('original-src'));
					}
				});
			}

		} // End responsive images module

	};

	// Do this stuff when the page is ready
	$(document).ready(function () {
		$.mqSync.init();
	});

}(jQuery));
<|endoftext|>


<commit_before>(function($){

    /**
     * Copyright 2012, Digital Fusion
     * Licensed under the MIT license.
     * http://teamdf.com/jquery-plugins/license/
     *
     * @author Sam Sehnert
     * @desc A small plugin that checks whether elements are within
     *       the user visible viewport of a web browser.
     *       only accounts for vertical position, not horizontal.
     */
    var $w = $(window);
    $.fn.visible = function(partial,hidden,direction){

        if (this.length < 1)
            return;

        var $t        = this.length > 1 ? this.eq(0) : this,
            t         = $t.get(0),
            vpWidth   = $w.width(),
            vpHeight  = $w.height(),
            direction = (direction) ? direction : 'both',
            clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

        if (typeof t.getBoundingClientRect === 'function'){

            // Use this native browser method, if available.
            var rec = t.getBoundingClientRect(),
                tViz = rec.top    >= 0 && rec.top    <  vpHeight,
                bViz = rec.bottom >  0 && rec.bottom <= vpHeight,
                lViz = rec.left   >= 0 && rec.left   <  vpWidth,
                rViz = rec.right  >  0 && rec.right  <= vpWidth,
                vVisible   = partial ? tViz || bViz : tViz && bViz,
                hVisible   = partial ? lViz || lViz : lViz && rViz;

            if(direction === 'both')
                return clientSize && vVisible && hVisible;
            else if(direction === 'vertical')
                return clientSize && vVisible;
            else if(direction === 'horizontal')
                return clientSize && hVisible;
        } else {

            var viewTop         = $w.scrollTop(),
                viewBottom      = viewTop + vpHeight,
                viewLeft        = $w.scrollLeft(),
                viewRight       = viewLeft + vpWidth,
                offset          = $t.offset(),
                _top            = offset.top,
                _bottom         = _top + $t.height(),
                _left           = offset.left,
                _right          = _left + $t.width(),
                compareTop      = partial === true ? _bottom : _top,
                compareBottom   = partial === true ? _top : _bottom,
                compareLeft     = partial === true ? _right : _left,
                compareRight    = partial === true ? _left : _right;

            if(direction === 'both')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
            else if(direction === 'vertical')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
            else if(direction === 'horizontal')
                return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
        }
    };

})(jQuery);<commit_msg>Update jquery.visible.js<commit_after>(function($){

    /**
     * Copyright 2012, Digital Fusion
     * Licensed under the MIT license.
     * http://teamdf.com/jquery-plugins/license/
     *
     * @author Sam Sehnert
     * @desc A small plugin that checks whether elements are within
     *       the user visible viewport of a web browser.
     *       only accounts for vertical position, not horizontal.
     */
    var $w = $(window);
    $.fn.visible = function(partial,hidden,direction){

        if (this.length < 1)
            return;

        var $t        = this.length > 1 ? this.eq(0) : this,
            t         = $t.get(0),
            vpWidth   = $w.width(),
            vpHeight  = $w.height(),
            direction = (direction) ? direction : 'both',
            clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

        if (typeof t.getBoundingClientRect === 'function'){

            // Use this native browser method, if available.
            var rec = t.getBoundingClientRect(),
                tViz = rec.top    >= 0 && rec.top    <  vpHeight,
                bViz = rec.bottom >  0 && rec.bottom <= vpHeight,
                lViz = rec.left   >= 0 && rec.left   <  vpWidth,
                rViz = rec.right  >  0 && rec.right  <= vpWidth,
                vVisible   = partial ? tViz || bViz : tViz && bViz,
                hVisible   = partial ? lViz || rViz : lViz && rViz;

            if(direction === 'both')
                return clientSize && vVisible && hVisible;
            else if(direction === 'vertical')
                return clientSize && vVisible;
            else if(direction === 'horizontal')
                return clientSize && hVisible;
        } else {

            var viewTop         = $w.scrollTop(),
                viewBottom      = viewTop + vpHeight,
                viewLeft        = $w.scrollLeft(),
                viewRight       = viewLeft + vpWidth,
                offset          = $t.offset(),
                _top            = offset.top,
                _bottom         = _top + $t.height(),
                _left           = offset.left,
                _right          = _left + $t.width(),
                compareTop      = partial === true ? _bottom : _top,
                compareBottom   = partial === true ? _top : _bottom,
                compareLeft     = partial === true ? _right : _left,
                compareRight    = partial === true ? _left : _right;

            if(direction === 'both')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
            else if(direction === 'vertical')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
            else if(direction === 'horizontal')
                return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
        }
    };

})(jQuery);
<|endoftext|>