var WaffleItemPrefix = 'waffle_item_';
var LastWaffleIndex = null;

// For 7 waffles
var waffleRing = new Array(
    { id: 0, x: 420, y: 295, z: 2, w: 330, h: 249 },
    { id: 1, x: 270, y: 310, z: 4, w: 191, h: 144 },
    { id: 2, x: 310, y: 250, z: 3, w: 151, h: 114 },
    { id: 3, x: 450, y: 220, z: 1, w: 135, h: 102 },
    { id: 4, x: 590, y: 220, z: 1, w: 135, h: 102 },
    { id: 5, x: 700, y: 250, z: 3, w: 151, h: 114 },
    { id: 6, x: 720, y: 310, z: 4, w: 191, h: 144 });

function AnimateWaffles(dir) {
    var shift = dir / Math.abs(dir);
    var newZero = -1;

    for (var j = 0; j < waffleRing.length; j++) {
        var elem = $('#' + WaffleItemPrefix + j);
        var i = parseInt(waffleRing[j].id) + shift;

        if (i < 0) {
            i += waffleRing.length;
        }
        else if (i >= waffleRing.length) {
            i -= waffleRing.length;
        }

        if (i == 0) {
            elem[0].style.zIndex = 5;
            newZero = j;
        }
        else {
            elem[0].style.zIndex = waffleRing[i].z;
        }

        elem.animate({ left: waffleRing[i].x + 'px', top: waffleRing[i].y + 'px',
            width: waffleRing[i].w + 'px', height: waffleRing[i].h + 'px' }, 400);
        waffleRing[j].id = i;
    }

    dir -= shift;

    if (dir == 0) {
        window.setTimeout("$('#" + WaffleItemPrefix + newZero + "')[0].style.zIndex = " + waffleRing[0].z + ";", 300);
    }
    else
    {
        window.setTimeout("AnimateWaffles(" + dir + ")", 300);
    }
}

function TurnToFront(elem) {
    if (elem && elem.id.match(/.*(\d+)$/)) {
        var id = parseInt(RegExp.$1);
        var index = parseInt(waffleRing[id].id);

        if (LastWaffleIndex || (LastWaffleIndex == 0)) {
            $('#descWaffle' + LastWaffleIndex).hide();
        }

        // Show the description for the waffle
        $('#descWaffle' + id).fadeIn();
        LastWaffleIndex = id;

        if (index > Math.floor(waffleRing.length / 2)) {
            index -= waffleRing.length;
        }

        if (index != 0) {
            AnimateWaffles(-index);
        }
    }
}
