jQuery.extend(jQuery.easing, {
    easeInOutSine: function (x, t, b, c, d) {
        return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
    }
});

var current = -1;

var anagram = [
    'Japan Is Shinto',
    'John Passaniti',
    'Has Joint Pains',
    'Its a Posh Ninja',
    'Join Satans Hip',
    'A Spanish Joint',
    'Soap This Ninja',
    'John Is Anti Spa',
];

function forEachLetter(word, count, func) {
    var t = "";
    for (var i = 0; i < word.length; i++) {
        var ch = word.charAt(i).toLowerCase();
        var n = (count[ch] == undefined) ? count[ch] = 0 : ++count[ch];
        t += func(ch, n);
    }
    return t;
}

function generateTileHTML(letters) {
    var count = {};
    return forEachLetter(letters, count, function (ch, n) {
        return "<img class='tile' id='" + ch + n + "' alt='" + ch + "' src='/images/tiles/" + ch + ".png' />";
    });
}

function asTileGroup(word, count) {
    var t = "<span class='tile-group'>";
    t += forEachLetter(word, count, function (ch, n) {
        return "<div id='goal" + ch + n + "' class='tile-holder' />";
    });
    return t + "</span>";
}

function asTiles(s) {
    var count = {}
    var words = s.toLowerCase().split(" ");
    var t = "";

    while (words.length) {
        t += asTileGroup(words.shift(), count);
        if (words.length)
            t += "<span class='separator'> </span>";
    }
    return t;
}

function plusOrMinusRandom(n) {
    return (Math.random() * (n*2)) - n;
}

function plusRandom(n) {
    return (Math.random() * n);
}

function newTopLeft(top, left) {
    var t = {}
    t.top = top;
    t.left = left;
    return t;
}

function moveTiles(word) {
    $("img.tile").stop(true, false);
    var count = {}
    forEachLetter(word, count, function (ch, n) {
        var here = $("#" + ch + n);
        var hereTL = here.offset();
        var thereTL = $("#goal" + ch + n).offset();
        var overTL = newTopLeft(thereTL.top+plusRandom(200), thereTL.left+plusOrMinusRandom(100));

        here
            .animate(overTL,  { queue: true, duration: 650 + plusOrMinusRandom(350), teasing: "easeInOutSine" })
            .animate(thereTL, { queue: true, duration: 650 + plusOrMinusRandom(350), teasing: "easeInOutSine" });
        return "";
    });
}

function next(id) {
    current = (current+1) % anagram.length;
    $(id).html(asTiles(anagram[current]));
    moveTiles("johnpassaniti");
}

