var isPlaying = false;
var isFullScreen = false;
(function( $ ){
  $.fn.slideshow = function(options) {
    // only supports single element for each instance
    if (this.length > 1){
      var slideshow = this.eq(0);
    }
    else {
      var slideshow = this;
    }
    
    // SETUP options
    var defaults = {
      elemTag : 'p',
      timerDuration : 5000, //milliseconds
      tweenDuration : 1000, //milliseconds
      enableTabs : 'false',
      tabsPosition : 'after',
      enableThumbs : 'true',
      thumbsPosition : 'right',
      thumbWidth : 110,
      thumbHeight : 62
    };
    var options = $.extend(defaults, options);

    // SETUP private variables
    var slideshowElems = $(options.elemTag, slideshow);
    var slideshowLength = slideshowElems.length;
    var timer = null;
    var currentID = 0;
    var height = slideshowElems.eq(0).height();
    
    // SETUP private functions
    var initialize = function() {
		$('.frame', slideshow).css({
			'width': 523,
    		'height': 294,
			'border': '1px solid #505050',
			'background': '#505050'
		});
		if(options.enableThumbs == 'true')
		{
			var thumbStrip = $('<ul id="thumbStrip"></ul>');
			if(options.thumbsPosition == 'right' || options.thumbsPosition == 'bottom')
			{
				slideshow.append(thumbStrip);
			}
			else if(options.thumbsPosition == 'left' || options.thumbsPosition == 'top')
			{
				slideshow.prepend(thumbStrip);
			}
			var thumbLi;
			var thumbA;
			var thumb;
			var thumbsrc;
			slideshowElems.each(function(index) {
			  thumbLi = $('<li></li>');
			  thumbStrip.append(thumbLi);
			  if($(':first-child', this)[0].tagName == 'IFRAME') {
			    thumbsrc = $('iframe', this).attr('src').replace(/.*name=/g, 'http://s3.amazonaws.com/chapel_video/').replace(/\&.*/g, '.png');
			  }
			  else {
			  	thumbsrc = $('img', this).eq(0).attr('src');
			  }
			  if(index==0) {
			    $(this).addClass("activeslide");
			    thumbA = $('<a href="#" class="activethumb"></a>').height(options.thumbHeight).width(options.thumbWidth);
			    thumb = $('<img src="' + thumbsrc + '" width="' + options.thumbWidth + 'px" height="' + options.thumbHeight + 'px" />');
			    thumbA.append(thumb);
			  }
              else {
			    $(this).css({'opacity': 0 });
			    $(this).addClass("slide");
			    thumbA = $('<a href="#" class="thumb"></a>').height(options.thumbHeight).width(options.thumbWidth);
			    thumb = $('<img src="' + thumbsrc + '" width="' + options.thumbWidth + 'px" height="' + options.thumbHeight + 'px" />').css({ 'opacity': 0.4});
			    thumbA.append(thumb);
              }
		      thumbLi.append(thumbA);
		      thumbA.click(function(e) {
		        e.preventDefault();
		        if(isPlaying) {
		        	try {
		        		$('iframe', '.activeslide').eq(0).contents().find('#video-js-box').trigger("pause");
		        		isPlaying = false;
		        	} catch(e) {}
		        	try {
		        		$('iframe','.activeslide')[0].contentWindow.myFPlayer.pause();
		        		isPlaying = false;
		        	} catch(e) {}
		        }
		        stop();
		        slideshow.goToSlide(index);
		        start();
		      });
			});
			var highlight = $('<li id="thumbhighlight"></li>').css({
				'position' : 'absolute',
				'top' : 0
			});
			thumbStrip.append(highlight);
		}
		if(options.enableTabs == 'true')
		{
			var tabStrip = $('<ul id="tabStrip"></ul>');
			if(options.tabsPosition == 'after') {
			  slideshow.append(tabStrip);
			}
			else if(options.tabsPosition == 'before') {
			  slideshow.prepend(tabStrip);
			}
			var tabStripWidth = 0;
			var tabLi;
			var tabA;
			slideshowElems.each(function(index) {
			  tabLi = $('<li></li>');
			  tabStrip.append(tabLi);
			  tabStripWidth += tabLi.width();
			  if(index==0) {
			    slideshowElems.eq(0).addClass("activeslide");
			    tabA = $('<a href="#" class="activetab"></a>');
			  }
              else {
			    slideshowElems.eq(index).hide();
			    slideshowElems.eq(index).addClass("slide");
			    tabA = $('<a href="#" class="tab"></a>');
              }
		      tabLi.append(tabA);
		      tabA.click(function(e) {
		        e.preventDefault();
		        stop();
		        slideshow.goToSlide(index);
		        start();
		      });
			});
			tabStrip.css({
				width: tabStripWidth,
				position: 'absolute',
				top: height,
				left: slideshowElems.eq(0).width()/2 - tabStripWidth/2
			});
			height += tabStrip.height();
		}
		slideshow.css({
			position: 'relative',
			height: height,
		});
		slideshowElems.css({
			position: 'absolute',
			top: 1
		});
		return slideshow;
    };
    var start = function() {
      timer = setTimeout(iterate, options.timerDuration);
    };
    var stop = function() {
      clearTimeout(timer);
    };
    var iterate = function() {
      stop();
      var newID = currentID + 1;
      if(newID == slideshowElems.length) { newID = 0; }
      slideshow.goToSlide(newID);
      start();
    };
    // SETUP public functions
    this.goToSlide = function(newID) {
      try {
      	isFullScreen = $('iframe', '.activeslide').eq(0).contents().find('#video-js-box')[0].webkitDisplayingFullscreen;
      } catch(e) {}
      if(!isPlaying && !isFullScreen) {
        var prevID = currentID;
        slideshowElems.stop().fadeTo(options.tweenDuration, 0.0, function() {
          slideshowElems.eq(prevID).removeClass('activeslide').addClass('slide');
        });
        slideshowElems.eq(newID).stop().removeClass('slide').addClass('activeslide').fadeTo(options.tweenDuration, 1.0);
        if(options.enableThumbs)
        {
      	  $('#thumbhighlight').stop().animate({ 'top' : newID*($('#thumbhighlight').height()) });
          $('#thumbStrip img').stop().eq(prevID).fadeTo(options.tweenDuration, 0.4);
          $('#thumbStrip a').stop().eq(prevID).removeClass('activethumb').addClass('thumb');
          $('#thumbStrip img').eq(newID).fadeTo(options.tweenDuration, 1.0);
          $('#thumbStrip a').eq(newID).removeClass('thumb').addClass('activethumb');
        }
        if(options.enableTabs)
        {
          $('#tabStrip a').eq(prevID).hide().removeClass('activetab').addClass('tab').show();
          $('#tabStrip a').eq(newID).hide().removeClass('tab').addClass('activetab').show();
        }
        currentID = newID;
      }
    };
    this.show = function() {
      slideshow
        .mouseenter(function() {
          stop(); 
        })
        .mouseleave(function() {
          start(); 
        });
      start();
    };
    return initialize();
    
  };
})( jQuery );
