(function($){
	$.fn.videoCarousel = function(options) {
		// ===== append events to each carousel =====
		return this.each(function(){
			$.videoCarousel(this, options);
		});
	};
	$.videoCarousel = function(container,options){
		var settings = {
			'speed': 1000
		};
		var options = $.extend(settings, options);
		
		// ===== Internal Variables =====
		var current = 0;
		var viewed = 1;
		var open = false;
		var $player = null;
		var selected = null;
		var selectedIndex = 0;
		var $tweening = false;
		var scroller = $("li.scroller ul", $(container));
		var elements = $("li.scroller li a", $(container));
		var arrowTOP = $("li.btnTop a", $(container));
		var arrowBTM = $("li.btnBtm a", $(container));
		var video = $(".videoContainer", $(container));
		var tab = $('li.tab a', $(container));
		
		// ~~~~~ VIDEO TRAY ~~~~~
		tab.bind('click', function(e){
			e.preventDefault();
			open = ($(container).width() > 500)? true : false;
			
			// reset video player
			$(container).find('li.videoPlayer object').remove();
			$(container).find('li.videoPlayer').html('<div id="videoPlayer"></div><div id="closeBtn"></div>');
			
			$('#closeBtn').bind('click', function(e){
				tab.trigger('click');
			});
			
			$(container).animate(
				{ width: open? 131 : 624 }, 
				{ duration: options.speed, easing: 'easeInOutQuint', 
				complete:function(){
					open = ($(container).width() > 500)? true : false;
					tab.removeClass('open close').addClass(open?'close':'open');
					window.carousel_autostart = !open;
					if(!open){
						elements.removeClass('selected');
						$('#mainContent').find('.galleryIndex').simpleCarousel.next();
					};
				}
			});
			// hide background carousel images while video container is open.
			$('#mainContent').find('.photos').animate({ opacity: open? 1 : 0 },{ duration: open? 750 : 1500, easing: 'easeInOutQuint'});
			
			$(container).find('li.videoPlayer').animate(
				{ opacity: open? 0 : 1 }, 
				{ duration: open? 750 : 1500, 
				  easing: 'easeInOutQuint',
				complete:function(){
					if($(container).width() > 500){
						if(selected === null){
							var $first = $(elements[0]);
							$first.addClass('selected');
							embedVideoPlayer($first.attr('rel'));
							switchSlide(0);
						} else {
							embedVideoPlayer(selected.attr('rel'));
						};
					};
				}
			});
		});
		
		if(scroller.height() < scroller.parent().height()){
			arrowTOP.css('cursor','default').bind('click', function(e){ e.preventDefault() });
			arrowBTM.css('cursor','default').bind('click', function(e){ e.preventDefault() });
		} else {
			// ~~~~~ SCROLLER ~~~~~ 
			arrowTOP.bind('click', function(e){
				e.preventDefault();
				var slide = Math.min(0, parseInt(scroller.css('marginTop'))+(56*4));
				switchSlide(slide);
			});
			arrowBTM.bind('click', function(e){
				e.preventDefault();
				var slide = Math.max(parseInt(scroller.css('marginTop'))-(56*4), (scroller.height() - scroller.parent().height())*-1);
				switchSlide(slide);
			});
		};
		// ===== Primary Slider Function =====
		var switchSlide = function(n){
			if($tweening) return;
			
			$tweening = true;
			$(scroller).animate(
				{ marginTop: n }, 
				{ duration: 1000, easing: 'easeInOutQuint', 
					complete:function(){
						$tweening = false;
					}
				}
			);
		};
		
		$.fn.videoCarousel.next = function(){
			selectedIndex = (parseFloat(selectedIndex)+1) %  elements.size();
			var slide = Math.max((56*selectedIndex)*-1, (scroller.height() - scroller.parent().height())*-1);
			if(scroller.height() < scroller.parent().height()) slide = 0;
			if(selectedIndex == 0) slide = 0;
			
			if(viewed < elements.size()){
				elements.eq(selectedIndex).trigger('click');
				switchSlide(slide);
				viewed++;
			} else {
				tab.trigger('click');
			};
		};
		
		// ===== Thumbnail Tooltip(s) =====
		var $liveTip = $('<div id="livetip"></div>').hide().appendTo('body');
		var tipTitle = '';
		
		scroller.bind('mouseover mouseout mousemove', function(event) {
			var $link = $(event.target).closest('a');
			if (!$link.length) { return; }
			var link = $link[0];
			
			if (event.type == 'mouseover' || event.type == 'mousemove') {
				$liveTip.css({
					top: event.pageY + 12,
					left: event.pageX + 12
				});
			};
			
			if (event.type == 'mouseover') {
				tipTitle = link.title;
				link.title = '';
				$liveTip.html('<div>' + tipTitle + '</div>').show();
			};
			
			if (event.type == 'mouseout') {
				$liveTip.hide();
				if (tipTitle) link.title = tipTitle;
			}
		});
	
		// ===== Gather All Elements =====
		elements.each(function(i, btn){
			$(btn).bind('click', function(e){
				e.preventDefault();
				elements.removeClass('selected');
				$(this).addClass('selected');
				selected = $(this);
				selectedIndex = i;
				
				var open = ($(container).width() > 500)? true : false;
				if(!open){
					tab.trigger('click');
				} else {
					// reset video player
					$(container).find('li.videoPlayer object').remove();
					$(container).find('li.videoPlayer').html('<div id="videoPlayer"></div><div id="closeBtn"></div>');
					embedVideoPlayer($(this).attr('rel'));
					$('#closeBtn').bind('click', function(e){
						tab.trigger('click');
					});
				};
			});
		});
		
		function embedVideoPlayer(file){
			var aFlashVars = [
				"&skin=/media/flash/overlay.swf",
				"&frontcolor=ffffff",
				"&lightcolor=cc9900",
				"&controlbar=over",
				"&stretching=fill",
				"&autostart=true",
				"&file=" + file
			];
			
			var att = { id:"videoPlayer", name:"videoPlayer", data:"/media/flash/player.swf", width:"451", height:"260" };
			var par = { allowScriptAccess:"always", allowFullScreen:true, wmode:"transparent", bgcolor:"#000000", flashvars:aFlashVars.join('') };
			var id = "videoPlayer";
			setTimeout(function(){ swfobject.createSWF(att, par, id); }, 250);
		};
	};
})(jQuery);


// ~~~~~ VIDEO PLAYER ~~~~~
function playerReady(thePlayer) {
	$player = document.getElementById(thePlayer.id);
	addListeners();
};

function addListeners() {
	if ($player) {
		$player.addModelListener("STATE", "stateMonitor");
	} else {
		setTimeout(addListeners,100);
	}
};
var currentState = "NONE"; 
var previousState = "NONE"; 
function stateMonitor(obj) {
	currentState = obj.newstate; 
	previousState = obj.oldstate; 
	if ((currentState == "COMPLETED") && (previousState == "PLAYING")) {
		$('body.index .videoContainer').videoCarousel.next();
	};
};
