if (!Ascribe) {
  var Ascribe = {};
}

if (typeof(Ascribe.Gallery)  == "undefined") {
  Ascribe.Gallery = function(config) {
    this.largeImages = config.largeImagesArray();
    this.xlargeImages = config.xLargeImagesArray();
    this.imagePos;
    this.defaultImage;
    this.singleImageGallery;
    this.viewFullSizeID = config.viewFullSizeID || 'view-full-size';
    
    // determine if there is only one image
    if (this.largeImages.length <= 1) {
      this.singleImageGallery = true;
    }
    else {
      // determine gallery start index from default image
      for (i=0; i<this.largeImages.length; i++) {
        if (config.defaultImagePath == this.largeImages[i]) {
          this.imagePos = [i];
        }
      }
    }
    
    // event listeners
    Event.observe('default-photo', 'load', this.imageFadeIn.bindAsEventListener(this));
  } // constructor

  Ascribe.Gallery.prototype = {
    nextImage: function() {
      if (!this.singleImageGallery) {
        this.imagePos++;
        if (this.imagePos == this.largeImages.length) {
          this.imagePos = 0;
        }
        this.imageFadeOut();
      }
    },

    prevImage: function() {
      if (!this.singleImageGallery) {
        this.imagePos--;
        if (this.imagePos < 0) {
          this.imagePos = this.largeImages.length - 1;
        }
        this.imageFadeOut();
      }
    },

    imageFadeOut: function() {
      new Effect.Opacity('default-photo', {
        from: 1,
        to: 0,
        duration: 0
      });
      this.loadingIndicator();
    },

    imageFadeIn: function(event) {
      $('loading').style.visibility = 'hidden';
      new Effect.Opacity('default-photo', {
        from: 0,
        to: 1.0,
        duration: .3
      });
      if ($(this.viewFullSizeID)) {
        $(this.viewFullSizeID).update('<img src="http://assets.ascribehq.com/integrations/images/misc/view_full_size.png" alt="View Full Size" />');
      }
      x = $('default-photo').getDimensions().height;
      $('prev-container').style.height = x + 'px';
      $('next-container').style.height = x + 'px';
      if (!this.singleImageGallery) {
        $('prev-container').style.visibility = 'visible';
        $('next-container').style.visibility = 'visible';
      }
    },

    imageDomUpdate: function() {
      $('default-photo').src = this.largeImages[this.imagePos];
      $('large-image-container').href = this.xlargeImages[this.imagePos];
    },
    
    loadingIndicator: function() {
      $('loading').style.visibility = 'visible';
      if ($(this.viewFullSizeID)) {
        $(this.viewFullSizeID).update('&nbsp;');
      }
      this.imageDomUpdate();
    },

    showViewFullSize: function() {
      $(this.viewFullSizeID).style.visibility = 'visible';
    },

    hideViewFullSize: function() {
      $(this.viewFullSizeID).style.visibility = 'hidden';
    }
  } // Ascribe.Gallery.prototype
} // if (typeof(Ascribe.Gallery)
