$(document).ready(function() {
    $('.splash, .init-img').fadeIn(1500);

    var img = $('.img img');
    img.hide().load(function(e) {
        $(img).fadeIn(500);
    });

    if (img.length > 0) {
        img = img[0];
        if (!(!img.complete && (typeof img.naturalWidth != 'undefined' &&
                                img.naturalWidth == 0))) {
            $(img).fadeIn(500);
        }
    }

    $('#thumbnails a').hover(function(e) {
        $(this).fadeTo(200, 1.0);
    }, function(e) {
        if (!$(this).hasClass('active')) {
            $(this).fadeTo(200, 0.5);
        }
    }).click(changeImageHandler);

    $('#next-img, #prev-img').click(changeImageHandler);

    $('#gallery-display .img').click(function() {
        window.location = $('#zoom').attr('href');
    });

    function changeImageHandler(e) {
        if ($('.img img').length > 0) {
            e.preventDefault();
        }

        var selected = this;
        swapImage(selected.href);
        $('#thumbnails a').each(function(i, elem) {
            if (elem.href == selected.href) {
                $(elem).addClass('active').css('opacity', 1.0);
            } else {
                $(elem).removeClass('active').css('opacity', 0.5);
            }
        });
    }

    function swapImage(url) {
        var mode = (url.lastIndexOf('zoom') != -1) ? 'zoom' : 'thumbs';
        $('.img img').fadeOut(400, function() {
            jQuery.ajax(url + '.json', {
                success: function(data, textStatus, jqXHR) {
                    var img = $('<img>');
                    img.load(function(e) {
                        $('.img').html($(this).hide());
                        $('.img img').fadeIn(400);
                    }).attr('src', data.image);
                    $('#next-img').attr('href', data.next);
                    $('#prev-img').attr('href', data.prev);

                    switch (mode) {
                    case 'zoom':
                        $('#back').attr('href', data.back);
                        break;
                    case 'thumbs':
                        $('#zoom').attr('href', data.zoom);
                        break;
                    default:
                        throw new Error('Unknown mode.');
                    }

                    $('.title').html(data.title);
                    Cufon.replace('.title');
                }
            });
        });
    }
});

