(function($) {
  var viewportWidth = 378;
  var animating = false;

  $.fn.gallery = function() {
    return $(this).each(function() {
      var rootNode = this;
      var sliderWidth = $(rootNode).find('div.thumbHolder a img').length * $(rootNode).find('div.thumbHolder').outerWidth(true);

      $(rootNode).find("div.thumbHolder a img").click(function(){
        return $.fn.gallery.LoadImage(this, rootNode);
      });

      $(rootNode).find('.thumbsInner').css('width', sliderWidth + 'px');

      $(rootNode).find("a.previous").click(function(){
        return $.fn.gallery.Slide(rootNode, sliderWidth, '+');
      });

      $(rootNode).find("a.next").click(function(){
        return $.fn.gallery.Slide(rootNode, sliderWidth, '-');
      });

      $.fn.gallery.DisplayButtons(rootNode, sliderWidth);
    });
  };

  $.fn.gallery.Slide = function(rootNode, sliderWidth, direction){
    if(!animating){
      animating = true;
      $(rootNode).find('div.thumbsInner').animate({ left: direction + '=' + viewportWidth }, 1500, 'swing', function(){
        $.fn.gallery.DisplayButtons(rootNode, sliderWidth);
        animating = false;
      });
    }
    return false;
  };

  $.fn.gallery.DisplayButtons = function(rootNode, sliderWidth){
    var leftPosition = $(rootNode).find('div.thumbsInner').position().left;

    if(leftPosition > -1){
      $(rootNode).find("a.previous").hide();
    } else {
      $(rootNode).find("a.previous").show();
    }

    if(sliderWidth + leftPosition - viewportWidth < 1){
      $(rootNode).find("a.next").hide();
    } else {
      $(rootNode).find("a.next").show();
    }
  };

  $.fn.gallery.LoadImage = function(thumbNail, rootNode){
    $(rootNode).find("div.thumbArrow").css('left', $(thumbNail).position().left + 'px');

    $(rootNode).find("div.galleryImage img").each(function(){
      $(this).attr({
        'src' : $(thumbNail).attr('src').replace('_thumbnail', '') + '',
        'alt' : $(thumbNail).attr('alt') + '',
        'title' : $(thumbNail).attr('title') + ''
      });
    });

    $(rootNode).find('div#gallery-image-caption').html($(thumbNail).attr('title'));

    return false;
  };
})(jQuery);