git » galala » master » tree

[master] / static / galala.js

/* Operations on the images list */

function findImageIndex(anchor) {
    for (var i = 0; i < images.length; i++) {
        if (images[i].anchor == anchor) {
            return i;
        }
    }

    return -1;
}

function nextImageIndex(anchor) {
    var i = findImageIndex(anchor) + 1;
    if (i >= images.length) {
        return images.length - 1;
    }

    return i;
}

function nextImage(anchor) {
    return images[nextImageIndex(anchor)];
}

function prevImageIndex(anchor) {
    var i = findImageIndex(anchor) - 1;
    if (i < 0) {
        return 0;
    }

    return i;
}

function prevImage(anchor) {
    return images[prevImageIndex(anchor)];
}


/* Operations on the main <img> */

function setMain(anchor) {
    var main = $("img#main");
    var img = images[findImageIndex(anchor)];
    main.attr("src", img.image);
    main.attr("alt", img.title);
    main.data().anchor = img.anchor;

    $("span#title").text(img.title);
    $("span#desc").text(img.description);

    document.location.hash = img.anchor;

    scrollToThumbnail(img.anchor);
    updatePreload();
}

function scrollToThumbnail(anchor) {
    // We need to use the long selector because anchor can have a '.'.
    var thumb = $('img[id="' + anchor + '"]');

    $("div.thumbnails").animate(
        { scrollTop: thumb[0].offsetTop },
        { duration: "fast"});
}

function advanceMain() {
    var next = nextImage($("img#main").data("anchor"));
    setMain(next.anchor);
}

function retreatMain() {
    var prev = prevImage($("img#main").data("anchor"));
    setMain(prev.anchor);
}

function updatePreload() {
    var next = nextImage($("img#main").data("anchor"));
    var preload1 = $("img#preload1");
    preload1.attr("src", next.image);

    next = nextImage(next.anchor);
    var preload2 = $("img#preload2");
    preload2.attr("src", next.image);
}

$(document).ready(function() {
    // Binding for clicks, swipes and keys.
    $("img#main").click(advanceMain);

    $("img#main").swipe({
        swipeLeft: advanceMain,
        swipeRight: retreatMain,
    });

    $("html").keydown(function(e) {
        switch (e.which) {
            case 39: // Right.
                advanceMain();
                break;
            case 37: // Left.
                retreatMain();
                break;
        }
    });

    $("img.thumb").click(function() {
        var anchor = this.id;
        setMain(anchor);
    });

    // Set the first image.
    if (document.location.hash != "") {
        setMain(document.location.hash.substr(1));
    } else {
        setMain(images[0].anchor);
    }
});