/*
	Author:
		A Coates
	
	Description:
		Animations through a series of slides, moving a pointer next to a list of boxes
*/
var HandySlide = function(element,options) {
	this.element = element;
	this.config = jQuery.extend({}, this.defaults, options);
	this.slides = element.contents(this.config.slidesContainer).children();
	this.pointer = element.find(this.config.pointerElement);
	this.menu = element.find(this.config.menuContainer);
	this.attachMouseEvents();
	this.init();
};

HandySlide.prototype = {
	
	defaults: {
		menuContainer: "#menu",
		slidesContainer: "#slides",
		pointerElement: "#pointer img",
		interval: 3000,
		transitionSpeed: 500,
		pointerOffset: -9,
		currentIndex: 0,
		active: true
	},
	
	transitionTo: function(index) {

		// fade the right slides
		var self = this;
		this.slides.eq(index).fadeIn(this.config.transitionSpeed/*, function() { self.transitionFinished(index) }*/).siblings().fadeOut(this.config.transitionSpeed);
		
		var timer = setTimeout(function(){ self.transitionHalfway(index) }, this.config.transitionSpeed/2);
		
		var top = this.menu.children().eq(index).position().top + this.config.pointerOffset;
		this.pointer.stop(true,false);
		this.pointer.animate( { top: top+"px" } , {duration:this.config.transitionSpeed} );
		
	},
	
	transitionHalfway: function(index) {
		// add an active class to the menu items so we can style if necessary
		this.menu.children().eq(index).addClass('active').siblings().removeClass('active');
	},
	
	transition: function() {
		
		var self = this;
		if (this.config.active) this.transitionTo(this.config.currentIndex);
		
		this.config.currentIndex = (this.config.currentIndex >= this.slides.length-1) ? 0 : this.config.currentIndex+1 ;
		
		var timer = setTimeout(function(){ self.transition() }, this.config.interval);
		
	},
	
	init: function() {
		// hide all except first
		this.slides.eq(0).show().siblings().hide();
		// start the animation
		this.transition();
	},
	
	// attach the mouse hover over menu items functionality
	attachMouseEvents: function() {
		
		var self = this;
		
		this.element.find(this.config.menuContainer).children().mouseover(function() {											
			// make sure the animation doesn't keep rolling while we're hovering
			self.config.active = false;
			// find the index of this element
			var changeToNum = $(this).index();
			self.transitionTo(changeToNum);	
			
		}).mouseout(function() {
			// re-allow animation to continue
			self.config.active = true;
		});
		
	}
	
	
};

(function($) {
	// extend the jQuery fn with our object
	$.fn.handySlide = function(options) {
		new HandySlide(this,options);
		return this;
	};
}) (jQuery);
