yg = window.yg || {};


yg.multistep = (function() {
	var M = function(node) {
		if (!node) {
			return false;
		}
		this.view = node;
		this.view.multistep = this; // allow access to controller from HTML node
		this.delay = this.view.getAttribute('delay') || 4000;
		this.timeout = {};
		this.activeStep = 0;
		this.min = 0;
		this.steps = $(this.view).find('.step-button');
		this.max = this.steps.length - 1;
		this.width = $(this.view).find('.multi-step-block').first().outerWidth() + 10;
		this.wrapper = $(this.view).find('.multi-step-wrapper').first();
		
		this.getState();
		var self = this;
		$(this.view).delegate('.step-button', 'click', function() {
			self.gotoStep(this);
		})
	}
	
	M.prototype.getState = function() {
		var active = $(this.view).find('.step-button-active');
		var self = this;
		if (active.length > 0) {
			this.steps.each(function(index) {
				if (this == active[0]) self.activeStep = index;
			});
		}
		else this.activeStep = 0;
		
		this.updateState();
	}
	
	M.prototype.updateState = function() {
		var active = this.activeStep;
		this.steps.each(function(index) {
			$(this).removeClass('step-button-active');
			if (index == active) $(this).addClass('step-button-active');
		});
		
		var margin = this.width * this.activeStep * -1;
		this.wrapper.animate({'margin-left': margin + 'px'}, 'slow');
		clearTimeout(this.timeout);
		var self = this;
		this.timeout = window.setTimeout(function() {self.nextStep()}, this.delay);
	}
	
	M.prototype.gotoStep = function(step) {
		var active = step;
		var self = this;
		this.steps.each(function(index) {
			$(this).removeClass('step-button-active');
			if (this == active) {
				self.activeStep = index;
				$(this).addClass('step-button-active');
			}
		});
		
		this.updateState();
	}
	
	M.prototype.nextStep = function() {
		if (this.activeStep < this.max) this.activeStep++;
		else this.activeStep = this.min;

		this.updateState();
	}
	
	M.prototype.previousStep = function() {
		if (this.activeStep > this.min) this.activeStep--;
		else this.activeStep = this.max;
		
		this.updateState();
	}
	
	return M;
})();
