function trim(str) {
  var newstr;
  newstr = str.replace(/^\s*/, "").replace(/\s*$/, ""); 
  newstr = newstr.replace(/\s{2,}/, " "); 
  return newstr;
} 

(function($) {
	
	$.fn.apslider = function() {
		var slideTime = 6000;
		var paused = false;
		var numSlides = 0;
		var curSlideIdx = -1;
		var slider = null;
		var curSlide = null;
		var sliderHeight = 0;
		var sliderWidth = 0;
		var timer;
		var nextIdx = '';
		
		setSlide = function(idx) {
			clearTimeout(timer);
			if (idx != curSlideIdx) {
				if (curSlideIdx >= 0) {
					curSlide.fadeOut('slow');
					$('#slider-control-' + (curSlideIdx+1)).removeClass('active');
				}
				curSlide = slider.children('.slide').eq(idx);
				curSlide.fadeIn('slow');
				$('#slider-control-' + (idx+1)).addClass('active');
				curSlideIdx = idx;
			}
			if (!paused)
				timer = setTimeout('nextSlide()', slideTime);
		};
		nextSlide = function() {
			setSlide((curSlideIdx + 1) % numSlides);
		};
		createControls = function() {
			slider.after('<div class="slider-controls"></div>');
			$('.slider-controls').append('<span class="slider-control play-pause pause" title="Pause the slideshow">&nbsp;</span>');
			for (var i = 0; i < numSlides; i++) {
				var title = trim(slider.children('.slide').eq(i).children('h4').text());
				$('.slider-controls').append('<span id="slider-control-'+(i+1)+'" class="slider-control" title="'+title+'">'+(i+1)+'</span>');
			}
			$('.slider-control:not(.play-pause)').each(function(idx) {
				$(this).click(function() {
					setSlide(idx);
				});
			});
			
			addClickEvent = function(cur) {
				if (cur == 'play') {
					$('.slider-control.play').click(function() {
						timer = setTimeout('nextSlide()', 1000);
						paused = false;
						$(this).removeClass('play').addClass('pause').unbind('click');
						$(this).attr('title', 'Pause the slideshow');
						addClickEvent('pause');
					});
				} else if (cur == 'pause') {
					$('.slider-control.pause').click(function() {
						clearTimeout(timer);
						paused = true;
						$(this).removeClass('pause').addClass('play').unbind('click');
						$(this).attr('title', 'Resume playback');
						addClickEvent('play');
					});
				}
			};
			addClickEvent('pause');
		};
		
		slider = this;
		this.css({'position': 'relative'});
		this.children('.slide').each(function(idx) {
			$(this).css('position', 'absolute');
			if ($(this).height() > sliderHeight)
				sliderHeight = $(this).height();
			if ($(this).width() > sliderWidth)
				sliderWidth = $(this).width();
				
			if (idx != 0) {
				$(this).hide();
			} else {
				//curSlide = $(this);
			}
			
			numSlides++;
		});
		
		if (numSlides > 0) {
			this.height(sliderHeight);
			this.children('.slide').height(sliderHeight).width(sliderWidth);
			createControls();
			setSlide(0);
		}
		return this;
	};
	
})(jQuery);

jQuery(document).ready(function() {
	jQuery('#featured-posts .main-post').apslider();
});