/***** demotive tabs object *************************
OPTIONS:
Can be sent as an object in the function call to override defaults i.e.: DEMOTIVE.tabs.init($j(element), {callEvent:'mouseover', matchHeight:'false'});

callEvent :
	the event you want to use as a trigger - ie 'mouseover'
matchHeight : 
	'true' - all tab content areas are matched in height
*********************************************************/

// init DEMOTIVE object
if (!DEMOTIVE) {
	var DEMOTIVE = {};	
}

// tabbing functionality
DEMOTIVE.tabs = {
	opts : {
		callEvent : 'click',
		matchHeight : 'true'
	},
	init : function($els, opts) {
		// $els is a jQuery collection
		$els.each(function(i) {
			// for each tab container:
			// set any options to the elements data
			var dataObj = {};
			dataObj.callEvent = DEMOTIVE.tabs.opts.callEvent;
			dataObj.matchHeight = DEMOTIVE.tabs.opts.matchHeight;
			if (opts) {
				if (opts.callEvent) {
					dataObj.callEvent = opts.callEvent
				}
				if (opts.matchHeight) {
					dataObj.matchHeight = opts.matchHeight
				}
			}
			jQuery(this).data('tab-props', dataObj);
			// if matchHeight is true, find the tallest element and match heights
			if (jQuery(this).data('tab-props').matchHeight == 'true') {
				var $cEls = jQuery(this).find('.dem-tab-content');
				var hMax = 0;
				$cEls.each(function(i) {
					var myH = jQuery(this).outerHeight(true);
					if (myH > hMax) {
						hMax = myH;
					}
				});
				$cEls.css('height', hMax);
			}
			// set all link items, and add selected class to first one
			var nameEvent = jQuery(this).data('tab-props').callEvent;
			var $controlEls = jQuery(this).find('.dem-tab-control').children();
			$controlEls
				.bind('click', function(e) {
					e.preventDefault();
				})
				.bind(nameEvent + '.tabControl', function() {
					DEMOTIVE.tabs.swap(jQuery(this));
				});
			// erm... keyboard access... erm...
			if (nameEvent != 'click') {
				$controlEls.bind('click.tabControl', function() {
					DEMOTIVE.tabs.swap(jQuery(this));
				});
			}
			$controlEls.eq(0).addClass('dem-active');
			// collapse all target divs
			jQuery(this)
				.find('.dem-tab-content')
				.hide()
				.eq(0)
				.show();
		});
	},
	swap : function($el) {
		var $els = $el.parents('.dem-tabbed').find('.dem-tab-content');
		$els.each(function(i) {
			jQuery(this).hide();
		});
		var elId = $el.find('a:first').attr('href');
		jQuery(elId).show();
		$el.siblings().removeClass('dem-active');
		$el.addClass('dem-active');
	}
}
