(function( $ ){
  $.fn.deckSlideshow = function( options ) {
  
  	// default settings
	var settings = {
      'slides'	    : '',
      'img_path'    : '',
      'auto_change' : false, // don't auto change by default
      'interval'    : 6000 // 6 seconds
    };
    
    // merge options and settings 
    if ( options ) { $.extend( settings, options ); }
    
    // make sure we have images
    if ( settings.slides == '' ) { throw new Error(alert("Slideshow creation aborted\n\nThere were no images defined.")); }

	var container = this; // id or class of the container (include the . or # marker)
	var img_path = settings.img_path; // path to images
	var slides = settings.slides;
	window.auto_change = settings.auto_change;
	window.interval = settings.interval;
	
	function build_slideshow(container,img_path,slides,active_slide) {
		
		// add the containers for the slides and controls
		$(container).append('<div class="slideshow_slides"></div><div class="slideshow_controls"></div>');
		
		// loop through the images
		for ( var i=1, len=slides.length; i<len; ++i ) { 
			if (i==1) var active = 'active'; else var active = '';
			$('.slideshow_slides',container).append('<div class="'+active+'" id="slide_'+i+'"><a href="'+slides[i]['href']+'"><img src="'+img_path+slides[i]['image']+'" alt="" /></a></div>');
			$('.slideshow_controls',container).append('<a class="link_'+i+' '+active+'" href="#slide_'+i+'" rel="'+i+'">'+i+'</a>');
		}
		
		// assign max amount of slides to window var
		window.slides_count = --i;
		
		 // call the first slide
		if (active_slide == null) change_slide(1);
	}
	
	function change_slide(to) {
		if (window.auto_change) { clearTimeout(window.slide_timeout); } // reset timer (only fire if auto_change = true)
		
		// check if we're using the next slide
		if (to == 'next') {
			to = $('.slideshow_controls .active').attr('rel'); // get the # of the current slide
			to = ++to; // get the slide # after current
		}
		
		// if 'next' slide is greater than last slide, send to first
		if (to > window.slides_count) to = 1;
		
		// define slide and controller vars
		var to_slide = '#slide_'+to;
		var to_control = '.link_'+to;
		
		//  perform slide change
		$('.slideshow_slides .active').fadeOut( function() {
			$('.active').removeClass('active');
			$(to_control).addClass('active');
			$(to_slide).addClass('active').fadeIn();
		});
		
		if (window.auto_change) { window.slide_timeout = setTimeout(function() { change_slide('next') }, window.interval); }  // start timer (only fire if auto_change = true)
	}
	
	// watch for slide control click to change the slide
	$('.slideshow_controls a').live('click',function() {
		change_slide($(this).attr('rel')); // change the slide
		return false;
	})
	
	// do it!
	build_slideshow(container,img_path,slides);

  };
})( jQuery );

