var mediaElements;
var multipleMedias = [];

$(window).load(function() {
  mediaElements = $(".multiple-media-inner");
  if(mediaElements) {
    mediaElements.each(function() {
      multipleMedias.push(new MultipleMedia($(this)));
    });
  }
});

MultipleMedia = function(media)
{
  this.media = media;
  this.mediaItems = this.createMediaItems($(".media-item", this.media));
  this.isMoving = false; // a lock for sliding

  this.currentMedia = this.mediaItems[0];
  this.previousThumb = null;
  this.clearGallery();
  this.buildSkeleton();

  this.expandVideoHeight();

  this.media.show();
  this.setupArrows();
  this.showCurrent(true);
};

MultipleMedia.THUMB_HEIGHT = 46;
MultipleMedia.THUMB_HEIGHT_SELECTED = 52;
MultipleMedia.THUMB_WIDTH = 72;
MultipleMedia.THUMB_WIDTH_SELECTED = 80;
MultipleMedia.ACTUAL_THUMB_WIDTH = 87;
MultipleMedia.DISPLAY_HEIGHT = 315;
MultipleMedia.IMAGES_SHOWN = 3;

MultipleMedia.prototype.expandVideoHeight = function()
{
  // resize display area if type is youtube or vimeo and there exists a movie that is higher
  // than the current display height.
  var mediaWrapper = $(".big-media-wrapper", this.media);
  var wrapperHeight = mediaWrapper.css("height").replace(/px/, "");

  var maxVideoHeight = this.getMaxVideoHeight();
  if(maxVideoHeight > 0)
    mediaWrapper.css("height", maxVideoHeight);
}

MultipleMedia.prototype.getMaxVideoHeight = function()
{
  var maxHeight = 0;
  for(var i = 0; i < this.mediaItems.length; i ++) {
    maxHeight = Math.max(maxHeight, this.mediaItems[i].getVideoHeight());
  }
  return maxHeight;
}

MultipleMedia.prototype.setupArrows = function()
{
  var arrows = $("<div class='multiple-media-arrows'></div>").appendTo(this.media);
  if(this.mediaItems.length > 3) {
    this.arrowLeft = $("<a href='#' class='arrow-left'><img src='/images/photo_story_arrow_left.gif'></img></a>")
      .appendTo(arrows);
    this.arrowLeft.hide();
    this.arrowRight = $("<a href='#' class='arrow-right'><img src='/images/photo_story_arrow_right.gif'></img></a>")
      .appendTo(arrows);

    var self = this;
    this.arrowLeft.click(function() {
      if(!self.isMoving) {
	self.isMoving = true;
	var offset = self.getViewOffsetSteps();
	if(offset == 1)
	  self.arrowLeft.fadeOut(100);
	if(offset == self.mediaItems.length - MultipleMedia.IMAGES_SHOWN)
	  self.arrowRight.fadeIn(100);
	self.moveViewFrame(1);
      }
      return false;
    });
    this.arrowRight.click(function() {
      if(!self.isMoving) {
	self.isMoving = true;
	var offset = self.getViewOffsetSteps();
	if(offset == self.mediaItems.length - MultipleMedia.IMAGES_SHOWN - 1)
	  self.arrowRight.fadeOut(100);
	if(offset == 0)
	  self.arrowLeft.fadeIn(100);
	self.moveViewFrame(-1);
      }
      return false;
    });
  }
}

/**
 * @return the number of steps the thumb list is offset by (negative to margin-left)
 */
MultipleMedia.prototype.getViewOffsetSteps = function()
{
  return -this.getViewOffset() / MultipleMedia.ACTUAL_THUMB_WIDTH;
}

/**
 * @return the margin-left of the thumb-list element
 */
MultipleMedia.prototype.getViewOffset = function()
{
  return this.thumbList.css("margin-left").replace(/px/,"") - 0;
}

MultipleMedia.prototype.moveViewFrame = function(steps)
{
  var currentViewPos = this.getViewOffset()
  var self = this;
  this.thumbList.animate({marginLeft: steps * MultipleMedia.ACTUAL_THUMB_WIDTH + currentViewPos}, 200,
			 function() {
			   self.isMoving = false;
			 });
}

MultipleMedia.prototype.createMediaItems = function(mediaItemNodes)
{
  var mediaItems = [];
  var self = this;
  mediaItemNodes.each(function() {
    mediaItems.push(new MediaItem($(".big-media-wrapper", this).html(),
				  $(".caption-degrade", this).html(), $(".thumb-source", this).val()));
  });
  return mediaItems;
};

MultipleMedia.prototype.clearGallery = function()
{
  this.media.html("");
};

MultipleMedia.prototype.buildSkeleton = function()
{
  this.bigMedia = $("<div class='big-media-wrapper'></img>").appendTo(this.media);
  this.caption = $("<div class='caption'></div>").appendTo(this.media);
  var viewPort = this.buildThumbListRow();
  viewPort.appendTo(this.media);
};

MultipleMedia.prototype.buildThumbListRow = function()
{
  var viewPort = $("<div class='media-viewport'></div>");
  this.thumbList = $("<ul class='media-thumb-list'></ul").appendTo(viewPort);
  var self = this;
  $.each(this.mediaItems, function(index, item) {
    var thumb = $("<li class='thumb'></li>").appendTo(self.thumbList);
    var imageUrl = "/resize/72x" + MultipleMedia.THUMB_HEIGHT_SELECTED + item.staticSrc;
    var anchor = $("<a href='#'></a>").appendTo(thumb);
    var thumbListImage = $("<img src='" + imageUrl + "'></img>").appendTo(anchor);
    thumbListImage.height(MultipleMedia.THUMB_HEIGHT);
    anchor.click(function() {
      self.expandThumb(anchor, thumbListImage, index);
      self.setMediaByNumber(index);
      return false;
    });

    // expand first 
    if(index == 0)
      self.expandThumb(anchor, thumbListImage, index);
  });

  // float if less than IMAGES_SHOWN items
  if(this.mediaItems.length < MultipleMedia.IMAGES_SHOWN) {
    this.thumbList
      .css("margin-left", (MultipleMedia.IMAGES_SHOWN - this.mediaItems.length) * MultipleMedia.ACTUAL_THUMB_WIDTH);
  }

  return viewPort;
};

MultipleMedia.prototype.expandThumb = function(anchor, image)
{
  if(this.previousThumb != anchor) {
    if(this.previousThumb) {
      $("img", this.previousThumb).animate({height: MultipleMedia.THUMB_HEIGHT}, 200);
    }
    this.previousThumb = anchor;
    image.animate({height: MultipleMedia.THUMB_HEIGHT_SELECTED}, 200);
  }
}

MultipleMedia.prototype.setMediaByNumber = function(number)
{
  this.currentMedia = this.mediaItems[number];
  this.showCurrent();
}

MultipleMedia.prototype.showCurrent = function(first)
{
  var self = this;
  if(first) {
    this.caption.hide();
    this.bigMedia.hide(0, function() { showIt.call(self) });
  }
  else {
    // can't use fadeIn and fadeOut since it needs to remain block level
    // fadeOut makes it display: none
    this.caption.animate({opacity: 0});
    this.bigMedia.fadeOut(400, function() { showIt.call(self) });
  }
  function showIt() {
    this.bigMedia.html(this.currentMedia.mediaHTML);
    this.caption.html(this.currentMedia.captionHTML);
    this.bigMedia.fadeIn(function() {
      if(self.currentMedia.mediaHTML.indexOf('http://www.youtube.com') == -1 && self.currentMedia.mediaHTML.indexOf('http://vimeo.com') == -1) {
	var anchor = $("a.colorbox", $(this));
	var mediaobjectId = anchor.attr("id").substr("image_".length);
	anchor.colorbox({title: "<a class='download-link' href='/download_image?id=" + mediaobjectId +
			 "'>Download full size image</a>",
			 maxWidth: "95%",
			 maxHeight: "95%"});
      }
    });
    this.caption.animate({opacity: 1});
  }
}


MediaItem = function(mediaHTML, captionHTML, staticSrc)
{
  this.mediaHTML = mediaHTML;
  this.staticSrc = staticSrc;
  this.captionHTML = captionHTML;
}

MediaItem.prototype.getVideoHeight = function()
{
  // return image height if not video
  if(this.mediaHTML.indexOf('http://www.youtube.com') == -1 && this.mediaHTML.indexOf('http://vimeo.com') == -1)
    return MultipleMedia.DISPLAY_HEIGHT;

  // quick fix to ie bug
  try {
    // can't use String.replace as html contains newlines.
    var split1 = this.mediaHTML.split(" height=\"");
    var split2 = split1[1].split('"')
    var height = split2[0];

    return height - 1 + 1;
  }
  catch(e) {
    return 400;
  }
}


