$(document).ready(function() {
  $('.jphoto').jPhoto();
  $('.jgallery').jPhoto({ gallery: true });
  $('.gallery').galleria({
     onImage: function(image) { image.css('display','none').fadeIn(500); },
     insert: '.main_photo'
  });
});

jQuery.fn.jPhoto = function(options) {  
  options = jQuery.extend({
  }, options);  
  
  return this.each(function() {
    var targetContainer = $(this);
    var height = targetContainer.height();
    var width  = targetContainer.width();
    var top    = this.offsetTop;
    var left   = this.offsetLeft;
  
    var gallery_component = function() {
      return([ '<div id="photo_upload_component" style="position:absolute;width:', width, 
          'px;height:', height, 'px;top:', top, 'px;left:', left, 'px;">',
          '<form method="post" action="/images/upload_gallery" enctype="multipart/form-data">',
          '<input type="hidden" name="id" value="', targetContainer[0].id.substr(8), '" />',
          '<input type="file" name="gallery_file" />',
          '<input type="submit" value="Upload" />',
          '</form>',
          '</div>' ].join('')); 
    };
  
    var file_component = function() {
      return([ '<div id="photo_upload_component" style="position:absolute;width:', width, 
        'px;height:', height, 'px;top:', top, 'px;left:', left, 'px;">',
        '<form method="post" action="/images/upload_single_photo" enctype="multipart/form-data">',
        '<input type="hidden" name="id" value="', targetContainer[0].id.substr(6), '" />',
        '<input type="file" name="photo[image_file]" />',
        '<input type="submit" value="Upload" />',
        '</form>',
        '</div>' ].join('')); 
    };
    
    var show_upload = function() {
      var upload_component = options['gallery'] ? gallery_component() : file_component();  
      targetContainer.after(upload_component);
      $('#photo_upload_component').bind('mouseleave', hide_upload);
      $('#photo_upload_component input[type=file]').click(upload_click);
    };
  
    var hide_upload = function() {
      if (this.id == 'close_photo_component')
        targetContainer.unbind('mouseover').mouseout(function() { $(this).mouseover(show_upload); });
      $('#photo_upload_component').remove();
      return false;
    };
  
    var upload_click = function() {
      $('#photo_upload_component').unbind('mouseleave');
      $('#photo_upload_component').append('<a href="#" id="close_photo_component">Close</a>');
      $('#close_photo_component').click(hide_upload);  
    }
  
    targetContainer.mouseover(show_upload);
  });
};

