$(function() {
    //$.imgzoom();

    var $currentPhoto;

    $('#preview').css('left', (window.innerWidth - 800)/2);

    $('#preview_img').load(function() {
        $('#preview').css('left', (window.innerWidth - $(this).width())/2);
        $('#preview_img').css('visibility', 'visible');
    });

    $('#preview_close').click(function() {
        $('#preview').fadeOut();
        $('#preview_img').attr('src', '');
        return false;
    });

    $('#preview_prev').click(function() {
        $currentPhoto.parent().parent().prev().find('a').trigger('click');
        return false;
    })

    $('#preview_next').click(function() {
        $currentPhoto.parent().parent().next().find('a').trigger('click');
        return false;
    })

    $('.gallery a').click(function() {
        $currentPhoto = $(this);
        var $preview = $('#preview');
        var $previewImg = $preview.find('#preview_img');

        $previewImg.attr('src', $currentPhoto.attr('href')).css('visibility', 'hidden');
        $preview.fadeIn();

        if( hasNextPhoto($currentPhoto) ) $('#preview_next').show()
        else $('#preview_next').hide()

        if( hasPrevPhoto($currentPhoto) ) $('#preview_prev').show();
        else $('#preview_prev').hide();

        return false;
    })

    function hasNextPhoto($thumbAElement) {
        return $thumbAElement.parent().parent().next().length > 0;
    }

    function hasPrevPhoto($thumbAElement) {
        return $thumbAElement.parent().parent().prev().length > 0;
    }

});
