(function($) {

	$.extend({
		carousel: function() {
		
			// cache vars
			var $container = $('#carousel');
			var $panels = $container.find('ul li').eq(0).addClass('current').end();
			var noOfPanels = $panels.length; // number of panels
			var panelIndex = 0; // keeps track of current panel
			
			if (noOfPanels > 1) {
			
				// add IDs to panels and numbered links
				var numberLinks = [];
				$panels.each(function(i) {
					$(this).attr('id', 'panel-' + i);
					numberLinks[i] = '<li><a href="#' + i + '">' + (i + 1) + '</a></li>';
				});
				// append numbered links
				var $numbers = $('<ol />').html(numberLinks.join(''));
				$numbers.find('a:eq(0)').css('opacity', '0.7').end().appendTo($container);
			
				// animate panel function
				var switchPanel = function() {
				
					// swtich current class top previous
					var $currentPanel = $('.current', $container).addClass('previous').removeClass('current');
					var $nextPanel = $panels.eq(panelIndex);
				
					// animate panel
					$nextPanel.css({'opacity': 0})
						.addClass('current')
						.animate({'opacity': 1}, 500, function() {
							$currentPanel.removeClass('previous');
						});
						
					// highlight current index
					$numbers.find('a').css('opacity', '1').eq(panelIndex).css('opacity', '0.7');
				
				};
				
				// bind click event
				$numbers.click(function(e) {
					var $thisAnchor = $(e.target);
					
					if ($thisAnchor.is('a') && $thisAnchor.attr('href') !== '#' + panelIndex) {
							
						var href = $thisAnchor.attr('href').split('#')[1]; // store href
						panelIndex = href; // set panel index for number highlighting
						switchPanel();
					}
					return false;
				});
				
				// interval function
				var intervalFunction = function() {
					panelIndex++
				
					// check if last panel
					if (panelIndex === Number(noOfPanels)) {
						panelIndex = 0;
					}
					
					switchPanel();
				};
				
				// set interval
				var interval = setInterval(intervalFunction, 3000);
				
				// bind hover event to stop / start interval
				$container.hover(function() {
					clearInterval(interval);
				}, function() {
					interval = setInterval(intervalFunction, 3000);
				});
			}
		}
	});

})(jQuery);

jQuery(document).ready(function($) {

	if ($('#carousel')) {$.carousel();}
	
});

