$(function () {
    var img, tn_img;
    
    $('body').append('<div id="gimage_overlay"></div><div id="gimage_container"></div>');
    
    function show_image() {
        $('#gimage_overlay').css({
            'display': 'block',
            'width': $(document).width() + 'px',
            'height': $(document).height() + 'px'
        })
        . bind('click', close);
        
        if ($.browser.msie) {
            $('#gimage_overlay').css('filter', 'alpha(opacity = 1)');
        }
        
        var left = Math.round(tn_img.offset()['left'] + tn_img.width() / 2 - (img.width / 2));
        if (left < 10) {
            left = 10;
        }
        else if ($(window).width() - (left + img.width + 16) < 10) {
            left = $(window).width() - img.width - 16;
        }
        
        var top = Math.round(tn_img.offset()['top'] + tn_img.height() / 2 - (img.height / 2));
        if (top < $(window).scrollTop() + 10) {
            top = $(window).scrollTop() + 10;
        }
        else if ($(window).scrollTop() + $(window).height() - (top + img.height + 16) < 10) {
            top = $(window).scrollTop() + $(window).height() - img.height - 16;
        }
        
        $('#gimage_container').css({
            'display': 'block',
            'width': img.width + 'px',
            'height': img.height + 'px',
            'left': left + 'px',
            'top': top + 'px'
        })
        . append('<img src="' + img.src + '" alt="">');
        
        $('#gimage_container img').css( {'cursor': 'pointer'} ).bind('click', close);
        
        $(document).bind('keydown', keydown);
    }
    
    function close() {
        $(document).unbind('keydown', keydown);
        $('#gimage_container img').remove();
        $('#gimage_container').css('display', 'none');
        $('#gimage_overlay').unbind('click', close).css('display', 'none');
    }
    
    function keydown(event) {
        var code = event.keyCode;
        return (code == 27) ? close() : false;
    }
    
    $('a[rel="gimage"]').click(function (event) {
        event.preventDefault();
        
        tn_img = $(' img', this);
        
		img = new Image();
		img.onload = show_image
		img.src = $(this).attr('href');
    });
});
