
(function($){

	var $p;
	$.fn.procase = $p = function( opts ) {

		return this.each(function(){

			$this = $(this);

			// Get options for this procase instance
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

			// add the procase class
			$this.addClass('procase');

			// add a main container if one doesn't exist
			var _container = $('<div class="procase-container"></div>');
			$this.prepend( _container );

			var _originalItems = $this.find('ul').first().find('li');
			var _items = [];
			
			var totalImages = 0;
			var totalVideos = 0;
			
			var showImageNav = false;
			var showVideoNav = false;
			
			var numGalleryColumns = o['numGalleryColumns'];
			
			// loop through list
			_originalItems.each(function(i) {
				// Is this a video or an image?
				if( $(this).find('object,embed').length ) {
					// find an image
					var _a = $(this).find('a').is('a') ? $(this).find('a'): false;
					var _img = _a.find('img');
					_a.remove();
					var videoHolder = $('<div class="procase-video-item"></div>').append($(this).children());
					var _item = {
						id: i,
						type: 'video',
						caption: _img.attr('title') ? _img.attr('title') : _img.attr('alt'),
						thumb: _img.clone(true).addClass('thumb').css('display','none').css({ height: 'auto'}),
						content: videoHolder,
						target: _a.attr('href'),
						gallery: $(this).metadata().gallery ? $(this).metadata().gallery : 'Videos'
					};
					totalVideos++;
				} else {
					// find an image
					var _a = $(this).find('a').is('a') ? $(this).find('a'): false;
					var _img = $(this).find('img');
					var _item = {
						id: i,
						type: 'image',
						caption: _img.attr('title') ? _img.attr('title') : _img.attr('alt'),
						thumb: _img.clone(true).addClass('thumb').css('display','none').css({ height: 'auto'}),
						content: _img.clone(true).addClass('content'),
						target: _a.attr('href'),
						gallery: $(this).metadata().gallery ? $(this).metadata().gallery : 'Images'
					};
					totalImages++;
				}
				
				_items.push(_item);

			}).error(function () {

				// Error handling
				_container.html('<p class="procase-error">Could not display item</p>');

			}).hide();
			
			function hideControls(ignoreNavigation){
				if(!ignoreNavigation){
					$('.procase-navigation').stop().animate({right: 0}, 500);
				}
				$('.procase-controls').stop().fadeOut(100, function(){
					$(this).css('opacity', 0);
				});
			}
			
			var hideInterval = null;
			
			function showControls(ignoreNavigation){
				if(!ignoreNavigation){
					$('.procase-navigation').stop().animate({right: -28}, 300);
				}
				
				if($this.data('procase-mode') != 'gallery'){
					if(
						($this.data('procase-mode') == 'image' && showImageNav)
						|| ($this.data('procase-mode') == 'video' && showVideoNav)
					){
						$('.procase-controls').stop().fadeIn(100, function(){
							$(this).css('opacity', 1);
						});
					}else{
						$('.procase-controls').css('display', 'none');
					}
				}
				queueHideControls();
			}
			
			function queueHideControls(){
				clearTimeout(hideInterval);
				hideInterval = setTimeout(function() {
					hideControls(false);
				}, 55000);
			}
			
			$(this).hover(
				function(){
					showControls(false);
				}
			);
			
			$(this).mousemove(function(){
				showControls(false);
				queueHideControls();
			})

			// add the controls
			var _controls = $('<div class="procase-controls"><div class="procase-control-items"><a class="next">Next</a><a class="previous">Previous</a><a class="enlarge">Enlarge</a></div><div class="procase-gallery-status"><span class="procase-current"></span>/<span class="procase-total"></span></div></div>');
			$this.prepend( _controls );
			_controls.find('.a').css('cursor','pointer');
			
			// add the navigation
			var _navigation = $('<div class="procase-navigation"><a class="videos" title="View Videos">Videos</a><a class="images" title="View Images">Images</a><a class="gallery" title="View Galleries">Gallery</a></div>');
			$this.prepend( _navigation );
			_navigation.children('a').css('cursor','pointer').click(function(){
				_navigation.find('a').removeClass('selected');
				$(this).addClass('selected');
				return false;
			});
			

			// Create the image view
			var _imageView = $('<div class="image-view"></div>').css('position','relative').hide();
			var hasImages = false;
			for( var i=0; i < _items.length; i++ ) {
				if( _items[i].type == 'image' ) {
					hasImages = true;
					var img = _items[i].content.clone(true).data({item: _items[i]}).show();
					_imageView.append( img );
				}
			}
			
			if( hasImages ) {
				_container.append( _imageView );
				
				if(totalImages > 1){
					showImageNav = true;
				}
			} else {
				_navigation.find('.images').hide();
				_controls.find('.images').hide();
			}

			// Create the video view
			var _videoView = $('<div class="video-view"></div>').css('position','relative').hide();
			var hasVideos = false;
			for( var i=0; i < _items.length; i++ ) {
				if( _items[i].type == 'video' ) {
					hasVideos = true;
					if($.browser.msie) {
						var content = _items[i].content.data({item: _items[i]}).show();
						content.appendTo(_videoView);
					} else {
						var content = _items[i].content.clone(true).data({item: _items[i]}).show();
						_videoView.append( content );
					}
				}
			}
			if( hasVideos ) {
				if($.browser.msie) {
					_videoView.appendTo(_container);
				} else {
					_container.append( _videoView );
				}
				
				if(totalVideos > 1){
					showVideoNav = true;
				}
			} else {
				_navigation.find('.videos').hide();
				_controls.find('.videos').hide();
			}
			
			//Which tab should be selected first
			if(totalVideos){
				_videoView.show();
				$('.procase-navigation .videos').addClass('selected');
				_controls.find('.procase-total').html(totalVideos);
				_controls.find('.procase-current').html(1);
				$(this).data('procase-mode', 'video');
				$this.addClass('procase-mode-videos');
			}else{
				_imageView.show();
				$('.procase-navigation .images').addClass('selected');
				_controls.find('.procase-total').html(totalImages);
				_controls.find('.procase-current').html(1);
				$(this).data('procase-mode', 'image');
				$this.addClass('procase-mode-images');
			}

			// Create the gallery view
			var _galleryView = $('<div class="gallery-view"></div>').css('position','relative').hide();
			var _galleries = {};
			for( var i=0; i < _items.length; i++ ) {
				if( !_galleries[_items[i].gallery] ) {
					_galleries[_items[i].gallery] = [];
				}
				_galleries[_items[i].gallery].push(
					_items[i].thumb.clone(true).data({item: _items[i]}).show() );
				
			}
			
			$.each(_galleries, function(key, value) {
				_galleryView.append( $('<h3></h3>').text( key ) );
				var column = 0;
				$.each(value, function(key, value) {
					value.css('cursor','pointer').click(function() {
						if( $(this).data('item').type == 'image' ) {
							_imageView.find('img').each(function(i){
								if( $(this).data('item').id == value.data('item').id ) {
									_imageView.cycle(i);
									_navigation.find('.images').click();
								}
							});
						} else {
							_videoView.find('.procase-video-item').each(function(i){
								if( $(this).data('item').id == value.data('item').id ) {
									_videoView.cycle(i);
									_navigation.find('.videos').click();
								}
							});
						}
					});
					value.addClass('procase-col-' + column);
					column++;
					column = column % numGalleryColumns;
					_galleryView.append( value );
				});
			});

			_container.append( _galleryView );
			
			var direction = 'left';
			_controls.find('.next').css('cursor','pointer').click(function() {
				direction = 'left';
				switch( $this.data('procase-mode') ) {
					case 'image':
						_imageView.cycle('next');
						break;
					case 'video':
						_videoView.cycle('next');
						break;
					default:
					case 'gallery':
						break;
				}
				queueHideControls();
			});

			_controls.find('.previous').css('cursor','pointer').click(function() {
				direction = 'right';
				switch( $this.data('procase-mode') ) {
					case 'image':
						_imageView.cycle('prev');
						break;
					case 'video':
						_videoView.cycle('prev');
						break;
					default:
					case 'gallery':
						break;
				}
				queueHideControls();
			});
			
			_controls.find('.enlarge').css('cursor','pointer').click(function() {
				if( $this.data('procase-mode','image') ) {
					var fullUrl = _items[$this.data('procase-current-image-slide')]['target'];
					var title = '';
					try{
						title = $(_items[$this.data('procase-current-image-slide')]['content']).attr('title');
					}catch(e){}
					$.fn.colorbox({href: fullUrl, photo:true, title: title});
				}
				queueHideControls();
			});
			
			_navigation.find('.images').css('cursor','pointer').click(function() {
				_imageView.show();
				_videoView.hide();
				_galleryView.hide();
				_imageView.cycle('pause');
				_videoView.cycle('pause');
				$this.data('procase-mode','image');
				_controls.find('.procase-total').html(totalImages);
				_controls.find('.procase-current').html( $this.data('procase-current-image-slide') + 1);
				showControls(true);
				$this.removeClass('procase-mode-videos').removeClass('procase-mode-gallery').addClass('procase-mode-images');
			});

			_navigation.find('.videos').css('cursor','pointer').click(function() {
				_imageView.hide();
				_videoView.show();
				_galleryView.hide();
				_imageView.cycle('pause');
				_videoView.cycle('pause');
				$this.data('procase-mode','video');
				_controls.find('.procase-total').html(totalVideos);
				_controls.find('.procase-current').html( $this.data('procase-current-video-slide') + 1);
				showControls(true);
				$this.removeClass('procase-mode-images').removeClass('procase-mode-gallery').addClass('procase-mode-videos');
			});

			_navigation.find('.gallery').css('cursor','pointer').click(function() {
				_imageView.hide();
				_videoView.hide();
				_galleryView.show();
				_imageView.cycle('pause');
				_videoView.cycle('pause');
				$this.data('procase-mode','gallery');
				hideControls(true);
				$this.removeClass('procase-mode-images').removeClass('procase-mode-videos').addClass('procase-mode-gallery');
			});

			if(hasImages){
				_imageView.cycle({ 
					fx:			'custom', 
					cssBefore: {
						left: direction == 'left' ? 558 : -558,
						display: 'block'
					},
					animIn: {
						left: 0
					},
					animOut: {
						left: direction == 'left' ? -558 : 558
					},
					speed:		300,
					timeout:	3000,
					pause:		1,
					fit:		1,
					before: function(currSlideElement, nextSlideElement, options, forwardFlag){
						options['animOut']['left'] = direction == 'left' ? -558 : 558;
						options['cssBefore']['left'] = direction == 'left' ? 558 : -558;
					},
					after: function (curr,next,opts) {
						$this.data('procase-current-image-slide',opts.currSlide);
						_controls.find('.procase-current').html(opts.currSlide + 1);
					}
				}).cycle('pause');
			}

			if(totalVideos){
				_videoView.cycle({ 
					fx:     'fade', 
					speed:   300,
					timeout: 3000,
					pause:   1,
					after: function (curr,next,opts) {
						$this.data('procase-current-video-slide',opts.currSlide);
						_controls.find('.procase-current').html(opts.currSlide + 1);
					}
				}).cycle('pause');
			}
		});
	};

	$.fn.procase.defaults = {
		
	};

	function debug( item ) {
		if (window.console && window.console.log) {
			window.console.log( item );
		}
	};

})(jQuery);