$( function() {

    $('<div id="imagePreview"></div>').appendTo('body');
    $('<div id="productPreview"></div>').appendTo('body');
    
    $('.product img').each(function(i) {
	    $(this).bind('mouseover', function() {
	        setTimeout('showImagePreview(\''+ $(this).attr('id') +'\')', 500);    
	    });
    });
});

function showImagePreview(id) {
    o = $('#' + id);
    
    if (!o.attr('id')) return;
    
    if (o.data('hideImage')) return;
    o.data('imageVisible', true);
    
    offset = o.offset();
    
    w = o.width();
    h = o.height(); 
    
    // #imagePreview dimensions
    dw = w * 2;
    dh = h * 2;
    
    // creating image
        
    $('#imagePreview').addClass('loading').empty().css('top', offset.top + h/2 - dh/2).css('left', offset.left + w/2 - dw/2).data('id',id).show().load(
        '/products/imagePreview/' + id.split('_')[1], null, function( data ) {
            $(this).removeClass('loading');
            $(this).html(data);
            
            $(this).find('img').bind('mouseout', function() {
		        o = $('#' + $(this).parent().parent().data('id'));
		        if (!o.data('imageVisible')) return;
		        o.data('imageVisible', false);
		         
		        // hiding image
		        $(this).parent().parent().hide();
            });
        }
    );
}