(function($) {
  $.mw = $.extend($.mw?$.mw:{}, {
    gallery: {
      gallery: null,
      currentPhoto: 0,
      ui: {},
      
      createUi: function() {
        var ie6 = ($.browser.msie && ($.browser.version < 7));
        var $window = $(window);
        
        if (this.ui.$background) return;
        
        
        this.ui = {
          $gallery: $("<div id='mw_gallery' />"),
          $background: $("<div id='mw_gallery_overlay' />"),
          $content: $("<div id='mw_gallery_content_area' />"),
          resize: function() {
            var center = $.mw.gallery.ui.$content;
            var css = { 
              position: 'absolute',
              left: ($window.width() - center.width()) / 2,
              top: ($window.height() - center.height()) / 2,
              margin: '0px'
            };
            if (css.left < 0) css.left = 0;
            css.left = css.left + 'px';
            if (css.top < 0) css.top = 0;
            css.top = css.top +'px';
            center.css(css);
          }
        };
        
        this.ui.$gallery.appendTo($("body"));
        this.ui.$background.appendTo(this.ui.$gallery);
        this.ui.$content.appendTo(this.ui.$gallery);
                
        this.ui.$content.append("<div id='mw_gallery_image_space'><img id='mw_gallery_image' /><img id='mw_gallery_image_overlay' /></div>");
        $("#mw_gallery_image", this.ui.$content).load( function() {
          var $this = $(this);
          $this.css({ 
            position: 'absolute',
            left: ($this.parent().width() - $this.width()) / 2,
            top: ($this.parent().height() - $this.height()) / 2 
          });
        });
        this.ui.$content.append("<div id='mw_gallery_caption' />");
        this.ui.$content.append("<a href='#prev' class='mw_gallery_button mw_gallery_prev'>&lt;</a> <a href='#next' class='mw_gallery_button mw_gallery_next'>&gt;</a> <a href='#close' class='mw_gallery_button mw_gallery_close'>X</a>");
        this.ui.$next = $(".mw_gallery_next", this.ui.$content).click(this.nextPhoto);
        this.ui.$prev = $(".mw_gallery_prev", this.ui.$content).click(this.prevPhoto);
        var close = function() {
          $.mw.gallery.ui.$gallery.hide();
          delete $.mw.gallery.gallery;
        };
        $(".mw_gallery_close", this.ui.$content).click(close);
        this.ui.$background.click(close);
        
        this.ui.resize();
        $(window).bind('resize', this.ui.resize);
        
        if (ie6)
        {
          this.ui.$gallery.css({
            'position': 'absolute',
            'top': $window.scrollTop(),
            'height': $window.height()
          });
          this.ui.$background.css({
            'opacity': 0.7,
            'height': '100%'
          });
          $window.scroll(function() { $.mw.gallery.ui.$gallery.css({ 'top': $window.scrollTop() });});
        }
      },
      
      fadeIn: function() {
        this.createUi();
        this.ui.$content.hide();
        this.ui.$gallery.show();
        this.ui.$background.show(2000, this.fadedIn);
        this.ui.fadedIn = false;
      },
      
      fadedIn: function() {
        if (this !== $.mw.gallery) return $.mw.gallery.fadedIn(this);
        this.ui.fadedIn = true;
        return;
      },
      
      showPhoto: function(photonumber) {
        this.ui.$content.show();
        var photo = this.gallery.photos[photonumber];
        if (!photo) return;
        photo.caption = (photo.caption && photo.caption.length)?photo.caption:' ';
        this.currentPhoto = photonumber;
        $("#mw_gallery_image", this.ui.$content).attr('src', photo.src);
        $("#mw_gallery_caption", this.ui.$content).html(photo.caption).show();
        if (this.gallery.galleries.length) {
          var $gals = $("<div>More Galleries: </div>");
          $.each(this.gallery.galleries, function() {
            var gal = this;
            $gals.append($("<a>").attr('href', gal.href).text(gal.name).click(function() {
              $.mw.gallery.loadGallery($(this).attr('href'))
              return false;
            }),' ');
          }); 
          $("#mw_gallery_caption").append($gals);
        }
        if (this.gallery.last) {
          var $last = $("<a style='display:block'>Back to "+this.gallery.last.name+"</a>").click(function() {
            $.mw.gallery.gallery = $.mw.gallery.gallery.last;
            $.mw.gallery.showPhoto(0);
          });
          $("#mw_gallery_caption").append($last);
        }
        this.ui.$next.add(this.ui.$prev).hide();
        if (this.currentPhoto != 0) {
          this.ui.$prev.show();
        }
        if (this.currentPhoto < this.gallery.photos.length) {
          this.ui.$next.show();
        }
      },
      
      nextPhoto: function() {
        var next = $.mw.gallery.currentPhoto + 1;
        if (next >= $.mw.gallery.gallery.photos.length) next=0;
        $.mw.gallery.showPhoto(next);
      },
      
      prevPhoto: function() {
        var next = $.mw.gallery.currentPhoto - 1;
        if (next < 0) next=$.mw.gallery.gallery.photos.length - 1;
        $.mw.gallery.showPhoto(next);
      },
      
      loadGallery: function(url) {
        $.mw.gallery.fadeIn();
        var info = {width: this.ui.$gallery.width(), height: this.ui.$gallery.height()};
        // if (this.ui.$gallery.height() < 700) this.ui.$content.addClass("small"); else this.ui.$content.removeClass("small");
        $.ajax({
          type: 'GET',
          url: url,
          data: info,
          dataType: 'json',
          success: function(data) {
            if ($.mw.gallery.gallery) data.last = $.mw.gallery.gallery;
            $.mw.gallery.gallery = data;
            if (data.opts && data.opts.imageoverlay) {
              var $imageoverlay = $("#mw_gallery_image_overlay", $.mw.gallery.ui.$content);
              if (data.opts.imageoverlay.src) {
                if (/\.png/i.test(data.opts.imageoverlay.src) && ($.browser.msie && $.browser.version<7))
                {
                  $imageoverlay.hide();
                } else {
                  $imageoverlay.load(function() {
                    $.mw.gallery.ui.$content.pngfix();                  
                  }).attr('src',data.opts.imageoverlay.src).show();                                    
                }
              } else {
                $imageoverlay.hide();
              }
            } 
            $.mw.gallery.showPhoto(0);
          },
          error: function(status, data) {
            alert("An error occured trying to get the gallery.  Sorry.  Please try again later.");
          }
        });
      },
      
      bindFuncs: {
        bindGalleryLink: function(elem) {
          var $galleryLink = $(elem);
          $galleryLink.click(function() {
            $.mw.gallery.loadGallery($galleryLink.attr('href'));
            return false;
          });
        }
      },
      bind: function(elem) {
        if (!elem) elem = document;
        var $elem = $(elem);
        $('.mw_gallery_link',$elem).each(function() {$.mw.gallery.bindFuncs.bindGalleryLink(this);});
      }
    }
  });
  
  $(function() {
    $.mw.gallery.bind();
  });
})(jQuery);