/*!
 * trevor.Tabs.js
 * http://trevor.sh
 *
 * Copyright 2011, Trevor Sheridan
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Date: Thu May 5 01:13:31 2011 -0600
 */

//Class constructor
Tabs = function (tabs, targets) {
	
	//Some sanity checks
	if (typeof jQuery == 'undefined')
		throw('Hey there! This this object relies on the jQuery library. Please get it!');
	
	if (tabs.length != targets.length)
		throw('Tabs and targets arrays must be the same size. A one-to-one relationship between an action and it\'s target must exist.');
	
	if (tabs.length == 0 && targets.length == 0)
		throw 'Tabs & targets are both empty, aborting...';
	
	//Object properties
	this.active = null;
	this.hash = window.location.hash.substr(1);
	this.tabs = tabs;
	this.targets = targets;
	
	var that = this;
		
	if ("onhashchange" in window)
		window.onhashchange = function() { that.hashChanged(); }
		
	this.findActiveElement();

};

Tabs.prototype.findActiveElement = function() {
	
	var that = this;
	var calledUpdate = false;
	
	//Check if this hash is an integer, if it is then check if there is an associated action with it.
	if (this.hash.length > 0 && parseInt(this.hash) < this.tabs.length) {
	    this.update(this.hash);
	    calledUpdate = true;
	}
	
	//Check if there is an associated rel on an action for the given hash.
	if (calledUpdate == false) {
		$.each(this.tabs, function(key, value) {
			if (that.hash.length > 0 && $(value).attr('rel') == that.hash) {
				that.update(key);
				calledUpdate = true;
				return false;
			}
		});
	}
	
	//Finally, if no hash exists then see if there is an active class already set on an action.
	if (calledUpdate == false) {
		$.each(this.tabs, function(key, value) {
			if ($(value).attr('class', 'active')) {
				that.update(key);
				calledUpdate = true;
				return false;
			}
		});
	}
	
};

//Update method
Tabs.prototype.update = function(key) {	
	
	var that = this;
	
	this.active = key;
	
	$.each(this.tabs, function(key, value){
		$(this).removeClass('active');
		$(that.targets[key]).css('display', 'none');
	});
	
	$(this.tabs[this.active]).addClass('active');
	$(this.targets[this.active]).css('display', 'block');
	
};

//hashChanged method
Tabs.prototype.hashChanged = function() {
	if (window.location.hash != this.hash) {
		this.hash = window.location.hash.substr(1); //Set the hash to whatever the browser specified.
		this.findActiveElement();
	}
}

//Swap method
Tabs.prototype.updateActive = function(element) {
	this.update($.inArray(element, this.tabs));
	if (this.active != null) {
		window.location.hash = (this.tabs[this.active].rel != "") ? this.tabs[this.active].rel : this.active;
		this.hash = window.location.hash;
	}
}
