$(document).ready(function(){
  var preview = $("#istock_preview");

  scale_factor = 4; // Zoom level for image preview  
  stand_off = 30; // Number of pixel preview window will be from the top/bottom of page when adjusted
  right_offset = 10; // Distance preview is displayed to the right of the thumb
  var left;
  var top;
  var show;
  var scroll_offset;

  $('.e_loupe').mouseover(function() {

    window_width = $(window).width();

    // Load content into preview
    thumb = $(this).find("img");
    thumb_width = $(this).width() + right_offset;
    
    source = thumb.attr("src");
    width = thumb.width() * scale_factor;
    height = thumb.height() * scale_factor;
    filename = thumb.attr("alt");

    // Take the filename and work out the larger preview filename
    filename_pieces = source.split("/");
    last = filename_pieces[4];
    last_pieces = last.split("-");
    last_pieces[0] = last_pieces[1] = last_pieces[0] * scale_factor;
    filename_pieces[4] = last_pieces.join("-");
    source = filename_pieces.join('/');

    preview.html("<img src='" + source + "' width='" + width + "' height='" +  height + "'><div class='filename'>" + filename + "</div>");


    // Set Position
    position = $(this).offset();

    left = position.left + thumb_width;
    top = position.top - stand_off;
    
    
    // Stop the preview appearing off the top of the page
    if(top < $(window).scrollTop()){
      top = $(window).scrollTop() + stand_off;
    }
    
    // Stop the preview appearing off the bottom of the page
    if((30 + top + preview.height()) > ($(window).scrollTop() + $(window).height()) ){
      top = ($(window).scrollTop() + $(window).height()) - preview.height() - 40;
    }
    
    // Stop the preivew displaying off the right of the screen
    if((10 + left + preview.width()) > window_width){
      left = position.left - 30 - preview.width();
    }


    preview.css("left", left);
    preview.css("top", top);
    

    
    // Show
    preview.show()
    
  })
  $('.e_loupe').mouseout(function() {
    preview.hide();
  })
});
