/* jQuery Content Rotator Plugin */
/* copyright: SiteOrganic 2010 */
/* coded by Matt Blasi */

(function($) {
	$.fn.features = function(options) {

	var defaults = {
		name:	'features',			// name for feature wrapper & for timer - NO SPACES
		autoplay: true,				// to auto play rotation or not
		delay:	6000,				// time between changing features
		fadeDelay: 1000,			// time fade during change features
		showPanel: true,			// show the title.description panel
		showControls: false,		// show prev.next controls
		showPlayBack: false,		// show play.pause controls
		showPlayTxt: 'Play',		// text string for play button
		showPauseTxt: 'Pause', 		// text string for pause button
		thumbControl: false,		// use.display thumbnails
		thumbLimit: 5,				// limit thumbnails to this number
		addCount: false,            // adds list count of items
		addCountOf: false,			// adds 1 of # count
		transition: 'fade',			// transition type
		addMoreLink: false,			// dynamically adds a more link, gets the url for the feature
		addMoreText: 'more',		// text to display in link
		supportVideo: false,		// support video in tag?
		videoLightbox: false,		// always show video in lightbox
		tabControl: false,			// create tabs using title
		truncate: false,			// truncate description
		truncateLength: 100,		// truncate character count
		titleSplit: false,			// split title string
		titleSplitCharacter: '/~/', // character at which to split the string
		showCount: 1				// how many features to show
	};
	
	var options = $.extend(defaults, options); 
	
	return this.each(function(){
	
		//alert(window['timer-' + options.name]);
	
		obj = $(this);
		obj.addClass(options.name);
		
		var main = obj.find('ul:first');
		var feature = main.find('li');
		var thumbs = obj.find('ul.thumbs');
		
		// Hides all features - Fade in first
		feature.css({opacity: 0.0});
		thumbs.css({opacity: 0.0});
		feature.parent().find('li:first').addClass('shown').fadeTo(options.fadeDelay,1.0, function() { descPanel('up'); });
		main.find('li').find('div.panel-overlay').css({'top' : main.outerHeight()});
		
		// Check if has image
		var imgCount = 0;
		feature.each(function(){
			var imgSource = $('.main li a').eq(imgCount).find('img').attr("src");
			if(imgSource!=''){
				$('.main li a').eq(imgCount).parent().addClass('image');
			} else {
				$('.main li a').eq(imgCount).find('img').css('display', 'none');
			}	
			imgCount++;
		});
		
		featureCount = main.find('li:last').prevAll().length;
		if(featureCount == 0) {
			options.autoplay = false;
			options.showControls = false;
			options.showPlayBack = false;
			options.addCountOf   = false;
		}
		
		// Activate Options
		if(options.autoplay == true) 	 	{ window['timer-' + options.name] = setInterval(fnTransition, options.delay); }
		if(options.truncate == true) 	 	{ truncateText();   }
		if(options.tabControl   == true) 	{ controlsTabs();   }
		if(options.showControls == true) 	{ controlsArrows(); }
		if(options.thumbControl == true) 	{ controlsThumbs(); }
		if(options.addCountOf   == true) 	{ controlsNumber(); }
		if(options.showPlayBack == true) 	{ controlsPlay();   }
		if(options.addMoreLink  == true) 	{ addMoreLink();    }
		if(options.supportVideo == true)	{ videoSupport();   }
		if(options.showCount >= 2)			{ showMultiples();  }
		
		
		// PAUSE ON HOVER
		feature.mouseenter(function(){
			clearInterval(window['timer-' + options.name]);
		}).mouseleave(function(){
			if (options.showPlayBack == true && $('.pbControl').hasClass('play') ) { options.autoplay = false; } else { 
				if(featureCount != 1) { options.autoplay = true; } 
			}
			if (options.supportVideo == true && options.autoplay == true) { 
				if(videoURL != undefined) {
					thisVideo = $(main).find('.shown div video').attr('id');
					var video = document.getElementById(thisVideo);
					if (video.paused) { options.autoplay = true; } else { options.autoplay = false; }
				}
			} 
			if (options.autoplay == true){ window['timer-' + options.name] = setInterval(fnTransition, options.delay); }
		});
		
		// ADD IN NUMBER COUNT
		if(options.addCount == true) {
			main.after('<ul class="count"></ul>');
			featureCounter = 0;
			feature.each(function() {
				featureCounter ++;
				$('ul.count').append('<li><a href="javascript:void(0);">'+featureCounter+'</a></li>');
			});
			$('ul.count li:first').addClass('shown');
			$('ul.count').find('li a').bind('click', function(){
				newCount = $(this).parent().prevAll().length;
				changeTransition(newCount);
				changeControls();
			});
			
			if(options.addCount == true){$('.count li:first').next().addClass('shown2');}  
		}
		
		// PRIMARY FUNCTIONT TO RUN TRANSITIONS
		function fnTransition() {
			changeTransition('next');
		}
		
		function changeTransition($next) {
			
			if (options.supportVideo == true && main.find('.shown div').hasClass('player')) { 
				thisVideo     = $(main).find('.shown div video').attr('id');
				var videoURL  = $(this).find('div video').attr('src');
				if(videoURL != undefined) {
					var video = document.getElementById(thisVideo);
					video.pause();
				}
			}
			
			descPanel('down');
			
			countCurrent  = main.find('li.shown').prevAll().length;
			countFull     = main.find('li:last').prevAll().length;
			
			// get next & previous counts for eq()
			countPrev  = main.find('li.shown').prev().prevAll().length;
				if (countCurrent == 0){ countPrev = countFull; }
			countNext  = main.find('li.shown').next().prevAll().length;
				if (countCurrent == countFull ) { countNext = 0; }
				
			// set eq() value
			if ($next == 'next') { eq = countNext; } else if ($next == 'prev') { eq = countPrev; } else { eq = parseInt($next); }
		
			if (options.transition == 'slide') {
				// slide left right affect like in carousel
				slideWidth   = main.find('.shown').outerWidth();				
				slideCurrent = main.find('.shown');
				slideNext    = main.find('li').eq(eq);
				fullWidth    = main.outerWidth();
				fullWidth    = fullWidth/(countFull+1);
				fullWidth    = fullWidth*(countFull-1);
			
				if(options.showCount!=1){
					// HANDLES MULTIPLE SLIDES
					//alert(eq+' '+countFull);
					if($next=='next') {
						if(eq== 0){
							feature.animate({ left: '+='+fullWidth }); 
							slideNext = main.find('li').eq(0);
							main.find('li:first').fadeTo(500,1.0);
							main.find('li:first').next().fadeTo(500,1.0);
							main.find('li.shown').fadeTo(500,0.0);
							main.find('li.shown').prev().fadeTo(500,0.0);
						} else if (eq==countFull){
						} else { 
							feature.animate({ left: '-='+slideWidth }); 
							main.find('li.shown').fadeTo(500,1.0);
							main.find('li.shown2').next().fadeTo(500,1.0);
							main.find('li.shown').prev().fadeTo(500,0.0);
						}
					} else if ($next=='prev'){
						if(eq == countFull){
							feature.animate({ left: '-='+fullWidth });
							slideNext = main.find('li').eq(countFull);
							main.find('li:last').fadeTo(500,1.0);
							main.find('li:last').prev().fadeTo(500,1.0);
							main.find('li.shown').fadeTo(500,0.0);
							main.find('li.shown').next().fadeTo(500,0.0);
						} else if(eq==countFull-1){
						} else { 
							feature.animate({ left: '+='+slideWidth }); 
							main.find('li.shown').next().fadeTo(500,0.0);
							main.find('li.shown').prev().fadeTo(500,1.0);
						}
					} else {
						countDiff = eq-countCurrent;
						if(countCurrent==countFull) { countDiff++; }
						if(eq==countFull) {
							currentLeft = countCurrent * slideWidth * -1;
							lastLeft = currentLeft + fullWidth;
							feature.animate({ left: '-='+lastLeft });
						} else {
							slideWidth = slideWidth*countDiff;
							feature.animate({ left: '-='+slideWidth });
						}
						
						if (eq==countFull) {
							main.find('li').fadeTo(500,0.0);
							main.find('li:last').fadeTo(500,1.0);
							main.find('li:last').prev().fadeTo(500,1.0);
						} else if(countDiff==1){
							main.find('li.shown').prev().fadeTo(500,0.0);
							main.find('li.shown2').next().fadeTo(500,1.0);
						} else if (countDiff==-1){
							main.find('li.shown2').fadeTo(500,0.0);
							main.find('li.shown').prev().fadeTo(500,1.0);
						} else {
							main.find('li.shown').fadeTo(500,0.0);
							main.find('li.shown2').fadeTo(500,0.0);
							slideNext.fadeTo(500,1.0).next().fadeTo(500,1.0);
						}
						
					}
					
					slideCurrent.removeClass('shown');
					slideNext.addClass('shown');
				
				} else {
					// HANDLES SINGLE SLIDE
					slideCurrent.animate({
						left: parseInt(slideCurrent.css('left'),10) == 0 ?
						-slideCurrent.outerWidth() : 0
					}).removeClass('shown');
				
					slideNext.css({opacity: 1.0}).css({left:slideCurrent.outerWidth()+'px'}).animate({
						left: parseInt(slideNext.css('left'),10) == 0 ? slideNext.outerWidth() : 0
						}, function() { descPanel('up');
					}).addClass('shown');
				}
				
			} else if (options.transition == 'slice') {
				// slice effect like in nivo slider
		
			} else {
				// standard fade effect
				main.find('.shown').removeClass('shown').fadeTo(options.fadeDelay, 0.0);
				main.find('li').eq(eq).fadeTo(options.fadeDelay, 1.0, function() { descPanel('up'); }).addClass('shown');
			}
			changeControls();
			
		} 
		// END CHANGE TRANSITIONS
		
		function changeControls() {
			
			eq = main.find('li.shown').prevAll().length;
			cf = main.find('li:last').prevAll().length;
			
			if(options.showCount!=1 && options.transition == 'slide'){
				main.find('.shown2').removeClass('shown2');
				if(options.addCount == true)     {$('.count li.shown2' ).removeClass('shown2');}   
				if(options.thumbControl == true) {$('.thumbs li.shown2').removeClass('shown2');}
				if(options.tabControl == true)   {$('.tabs li.shown2').removeClass('shown2');}
			}
			
			// Update controls & counter shown status
			if(options.addCount == true) { 
				$('.countOf .itemNumber').text(eq+1);
			}
		
			if(options.addCount == true) {
				$('.count li.shown').removeClass('shown');
				$('.count li').eq(eq).addClass('shown');
			}
			
			if(options.tabControl == true) {
				$('.tabs li.shown').removeClass('shown');
				$('.tabs li').eq(eq).addClass('shown');
			}
		
			if(options.thumbControl == true) {
				// get current series
				thumbSeries = $('.thumbs li.shown').attr('class');
				thumbSeries = thumbSeries.replace(' shown','');
				thumbSeries = thumbSeries.replace('shown ','');
				
				// get new series
				newSeries = $('.thumbs li').eq(eq).attr('class');
				newSeries = newSeries.replace(' shown','');
				newSeries = newSeries.replace('shown ','');
				
				// if new series show new hide old
				if (newSeries != thumbSeries) {
					$('.thumbs li.'+thumbSeries).fadeTo(options.fadeDelay, 0.0).css('display','none');
					$('.thumbs li.'+newSeries).fadeTo(options.fadeDelay, 1.0).css('display','block');
				}
				
				//trasnition thumbs
				$('.thumbs li.shown').removeClass('shown');
				$('.thumbs li').eq(eq).addClass('shown');
			}
			
			if(options.showCount!=1 && options.transition == 'slide'){		
				if(eq==cf){
					main.find('.shown').prev().addClass('shown2');
					if(options.addCount == true)     {$('.count li.shown').prev().addClass('shown2');}   
					if(options.thumbControl == true) {$('.thumbs li.shown').prev().addClass('shown2');}
					if(options.tabControl == true)   {$('.tabs li.shown').prev().addClass('shown2');}
				} else {
					main.find('.shown').next().addClass('shown2');
					if(options.addCount == true)     {$('.count li.shown').next().addClass('shown2');}   
					if(options.thumbControl == true) {$('.thumbs li.shown').next().addClass('shown2');}
					if(options.tabControl == true)   {$('.tabs li.shown').next().addClass('shown2');}
				}
			}
			
			
		} // END CHANGE CONTROLS
		
		function controlsTabs() {
			main.after('<ul class="tabs"></ul>');
			countTabs = 0;
			feature.each(function() {
			    tabName = $(this).find('.panel-overlay h2').text();
			    if(options.titleSplit == true) {
			    	splitTest = tabName.search(options.titleSplitCharacter);
			    	if(splitTest != -1) {
			    		newTabs = tabName.split(options.titleSplitCharacter);
			    		tabName = newTabs[0];
			    		$(this).find('.panel-overlay h2').text(newTabs[1]);
					}
			    }
			    if (tabName !='') {
				    $('ul.tabs').append('<li id="tab'+countTabs+'"><a href="javascript:void(0);" class="tabLink">'+tabName+'</a></li>');
				}
			    countTabs++;
			});
			$('ul.tabs li:first').addClass('shown');
			$('a.tabLink').bind('click', function(){
				if($(this).parent().hasClass('shown')) {
					return false;
				} else {
					tabClicked = $(this).parent().prevAll().length;
					changeTransition(tabClicked);
					changeControls();
				}
			});
		} // END TAB CONTROLS
		
		function controlsArrows() {
			playCount = main.find('li:last').prevAll().length;
			var timer = options.name;
			
			if(playCount != 0) {
			main.after('<div class="pnControl"><a class="prev" href="javascript:void(0);">Prev</a><a class="next" href="javascript:void(0);">Next</a></div>');
			
			obj.find('.pnControl .next').bind('click', function() { 
				if(options.autoplay == true) { clearInterval(window['timer-' + options.name]); }
				changeTransition('next'); 
				if(options.autoplay == true) { window['timer-' + options.name] = setInterval(fnTransition, options.delay); }
			});
			obj.find('.pnControl .prev').bind('click', function() { 
				if(options.autoplay == true) { clearInterval(window['timer-' + options.name]); }
				changeTransition('prev'); 
				if(options.autoplay == true) { window['timer-' + options.name] = setInterval(fnTransition, options.delay); }
			});
			
			}
		} // END CONTROLS ARROWS (PREV/NEXT)
		
		function controlsThumbs() {
			thumbs.fadeTo(options.fadeDelay,1.0);
			$('.thumbs li:first').addClass('shown');
			thumbs.find('li a').bind('click', function(){
				if($(this).parent().hasClass('shown')) {
					return false;
				} else {
					if(options.autoplay == true) { clearInterval(window['timer-' + options.name]); }
					newThumb = $(this).parent().prevAll().length;
					changeTransition(newThumb);
					changeControls();
					if(options.autoplay == true) { window['timer-' + options.name] = setInterval(fnTransition, options.delay); }
				}
			});
			thumbnailLimits();
		} // END CONTROLS THUMBNAILS
		
		function controlsNumber() {
			main.after('<div class="countOf"></div>');
			featureCounter = 0;
			$('.countOf').append('<span class="itemNumber">1</span> of ');
			feature.each(function() {
				featureCounter ++;
			});
			$('.countOf').append('<span class="totalNumber">'+featureCounter+'</span>');
		} // END CONTROLS NUMBERS
		
		function controlsPlay() {
			var playButtonTxt = options.showPauseTxt;
			var play  = options.showPlayTxt;
			var pause = options.showPauseTxt;
			var timer = options.name;
			main.after('<a href="#" class="pbControl pause">'+ playButtonTxt +'</a>');
			$('.pbControl').bind('click', function() {
				if(playButtonTxt == pause) {
					if(options.autoplay == true) { clearInterval(window['timer-' + options.name]); }
					$('.pbControl').removeClass('pause').addClass('play');
					playButtonTxt = play;
				} else {
					if(options.autoplay == true) { window['timer-' + options.name] = setInterval(fnTransition, options.delay); }
					$('.pbControl').removeClass('play').addClass('pause');
					playButtonTxt = pause;
				}
				$('.pbControl').text(playButtonTxt);
			});
		} // END CONTROLS PLAY/PAUSE BUTTON
		
		function descPanel($direction) {
			if(options.showPanel == true) { 
				paneHeight = main.find('.shown').find('.panel-overlay').height();		
				panel = main.find('.shown').find('div.panel-overlay');
		
				panelHeight   = panel.outerHeight();
				hideHeight    = main.outerHeight();
				panelPosition = panel.position();
			
				if($direction == 'up'){
					panel.css({'top' : hideHeight});
					panel.animate({'top': '-='+panelHeight},500);
				} else {
					panel.css({'top': '-='+panelHeight});
					panel.animate({'top' : hideHeight},500);
				}
			} else {
				return false;
			}
		} // END DESCRIPTION PANEL SLIDE
		
		function addMoreLink() {
			featureCount = 0;
			feature.each(function() {
				var moreLinkURL = $(this).find('a').attr('href');
				$(this).append('<a href="'+moreLinkURL+'" class="more-link">'+options.addMoreText+'</a>');
				featureCount++;	
			});
		}
		
		function truncateText() {
			feature.each(function() {
			var panelText = $('.panel-overlay p').html();
					
			if(panelText.length > options.truncateLength) {
				var splitLocation = panelText.indexOf(' ', options.truncateLength);
				if(splitLocation != -1) {
					var splitLocation = panelText.indexOf(' ', options.truncateLength);
					var str1 = panelText.substring(0, splitLocation);
					$('.panel-overlay p').html(str1 + '<span>&hellip;</span>');
				}
			}
			});
		} // END TRUNCATE TEXT
		
		function thumbnailLimits() {
			count  = 0;
			series = 0; 
			countTotal = $('.thumbs li:last').prevAll().length;
			$('.thumbs li').each(function(){
				if (options.thumbLimit == count) {
					series++;
					count = 0;
				}
				$(this).addClass('series-'+series);
				count++;
			});
			$('.thumbs li').css({opacity: 0.0});
			$('.thumbs li.series-0').css({opacity: 1.0});
			if (countTotal >= options.thumbLimit) {
				$('.thumbs').after('<div class="thumbSeriesControls"><a class="prev" href="javascript:void(0);">&laquo;</a><a class="next" href="javascript:void(0);">&raquo;</a></div>');
				
				obj.find('.thumbSeriesControls a').bind('click', function() { 
					currentSeries = $('.thumbs li.shown').attr('class');
					currentSeries = currentSeries.replace(' shown','');
					currentSeries = currentSeries.replace('shown ','');
					currentSeriesNum = parseInt(currentSeries.replace('series-',''));
					nextSeries = currentSeriesNum + 1;
					if(currentSeriesNum!=0){
						prevSeries = currentSeriesNum - 1;
					} else {
						prevSeries = series;
					}
					$('.thumbs li.'+currentSeries).fadeTo(options.fadeDelay, 0.0).css('display','none');
					newShown = parseInt(options.thumbLimit);
					if($(this).hasClass('prev')){
						$('.thumbs li.series-'+prevSeries).fadeTo(options.fadeDelay, 1.0).css('display','block');
						newShown = newShown*prevSeries;
					} else {
						$('.thumbs li.series-'+nextSeries).fadeTo(options.fadeDelay, 1.0).css('display','block');
						newShown = newShown*nextSeries;
					}
					changeTransition(newShown); 
				});
			}
		}
		
		function videoSupport(){
			featureCount = 0;	
			feature.each(function() {
				featureCount++;	
				if($(this).find('div').hasClass('player')){
					var videoURL  = $(this).find('div video').attr('src');
					var posterURL = $(this).find('div video').attr('poster');
					// checking the video url determines html5 video support
					if(videoURL == undefined) {
						videoObj = $(this).find('div.player').html();
						videoFlash();
					} else {
						videoObj = $(this).find('div.player').html();
						videoHtml5();
					}
				}
			});
		} // END VIDEO SUPPORT DETECTION
		
		function videoHtml5(){
			feature.find('div.player video').bind('click', function() {
				if(options.autoplay == true) { clearInterval(window['timer-' + options.name]); }
			});
		
			$('video').bind('ended',function(){
				fnTransition();
				window['timer-' + options.name] = setInterval(fnTransition, options.delay);
			});
		} // END HTML5 VIDEO FUNCTIONS
		
		function videoFlash(){
		} // END FLASH VIDEO FUNCTIONS
		
		function showMultiples() {
		  fWidth   = feature.outerWidth();
		  
		  fCount   = main.find('li:last').prevAll().length;
		  fCount++;
		  
		  newWidth = fWidth*fCount;
		  
		  main.css('width',newWidth+'px');
		  
		  main.find('li').css({opacity:0.0, display:'inline'});
		  main.find('li.shown').css({opacity:1.0, display:'inline'});
		  main.find('li.shown').next().css({opacity:1.0, display:'inline'}).addClass('shown2');
		   
		  if(options.thumbControl == true) {$('.thumbs li:first').next().addClass('shown2');}
		  if(options.tabControl == true)   {$('.tabs li:first').next().addClass('shown2');}
		  
		}
		
	});

	};//END
})(jQuery);
