// jQuery dsBanner Plugin
$.dsBanner = function(options) {

	var dsBanner = this; // maintain a reference to this scope
	var timer = null; // hang onto the setInterval reference
	var index = 1; // the current banner
	var jlist = $(options.sources); // jquery list of click-able items
	var jtarget = $(options.target); // the target banner area
	var busy = false; // are we busy animating?
	
	// Initialize dsBanner timer
	this.init = function() {
		
		// Bind event handlers
		dsBanner.bind();
		
		// If no fade duration is given,
		// or swap duration is less than the fade duration
		if(!options.fadeDuration || options.swapDuration < options.fadeDuration) {
			options.fadeDuration = 500;
		}
		
		dsBanner.timer = setInterval(function() {
			
			// Check if we're already busy -- just in case
			if(!dsBanner.busy) {
			
				// Go to the next banner
				dsBanner.flipto(index);
				
				// Increase or reset the counter 
				if(index >= jlist.length-1) {
					index = 0;
				} else {
					index++;
				}
			
			}
			
		}, options.swapDuration);
	};
	
	// Rotate to a specific banner
	this.flipto = function(index) {
	
		// Flag us as busy
		dsBanner.busy = true;
		
		// Highlight the appropriate source list item
		$(options.sources+".current").removeClass("current");
		$(jlist[index]).addClass("current");
		
		// Swap banner content
		var current = $(options.target).find("a");
		var next = $(jlist[index]).html();
		$(options.target).prepend(next);
		current.fadeOut(options.fadeDuration,function(){
			// Remove the old banner and UNflag as busy
			$(this).remove();
			dsBanner.busy = false;
		});
		
	};
	
	// Bind DOM events
	this.bind = function(oThis) {
	
		// Bind sSourceSelector click events
		$(options.sources).click(function(event) {
		
			// Prevent A tags from taking the visitor elsewhere
			event.preventDefault();
			
			// Only if we're not busy and the user clicked on
			// a source link that's not the current banner
			if(!dsBanner.busy && index != jlist.index(this)) {
				// Stop rotating and flip to the clicked banner
				clearInterval(dsBanner.timer);
				index = jlist.index(this);
				dsBanner.flipto(index);
			}
			
		});
		
	};
	
	// Kick off dsBanner
	this.init();
};