/**
 * @author jallen
 */
(function($){
	$.fn.extend({
		svImgBoxTabInit: function(options) {
			var defaults = {
				'container': '.imgBox.tabbed'
				,'tabs': '.imgBox-tabs li'
				,'trigger': '.imgBox-tabs li a[rel=tab]'
				,'content': '.imgBox-content'
				,'hiddenClass': 'imgBox-tab-hidden'
				,'openTab': ':first'
			};
			
			var options = $.extend(defaults, options);
			
			this.each(function() {
				var o = options;
				$(o.container).each(function() {
					// calculate and assign height to the containing element
					var maximum = $(this)._maxHeight(o.content);
					var extra = $(this)._extraHeight(o.content,maximum);
					$(this).find(o.content).parent().height($(this).find(o.content).parent().height() - extra - 26); // 10px padding
					$(this).find(o.content).height(maximum.height);
					
					// assign hidden class to hidden content and tab
					$(this).find(o.content + ':not(' + o.openTab + ')').addClass(o.hiddenClass);
					$(this).find(o.content + o.openTab).removeClass(o.hiddenClass);
					$(this).find(o.tabs + '[rel!=' + $(this).find(o.content + o.openTab).attr('id') + ']').addClass(o.hiddenClass);
				});
				// set the triggers up to do what they are supposed to do (switch the
				// visible tabs with the hidden ones)
				$(o.container + ' ' + o.trigger).click(function() {
					var tabBox = $(this).parents(o.container);
					tabBox.find(o.content + ':not(' + $(this).attr('href') + ')').addClass(o.hiddenClass);
					tabBox.find(o.content + $(this).attr('href')).removeClass(o.hiddenClass);
					tabBox.find(o.tabs + '[rel!=' + $(this).attr('href').slice(1) + ']').addClass(o.hiddenClass);
					tabBox.find(o.tabs + '[rel=' + $(this).attr('href').slice(1) + ']').removeClass(o.hiddenClass);
					return false;
				});
			});
			
			return this;
		}
		,_maxHeight: function(selector) {
			var ii = 0;
			var elHeight = 0;
			var maxEl = 0;
			$(this).find(selector).each(function() {
				if ($(this).height() > elHeight) {
					elHeight = $(this).height();
					maxEl = ii;
				}
				ii++;
			});
			return {'index': maxEl,'height': elHeight};
		}
		,_extraHeight: function(selector,notExtra) {
			var height = 0;
			$(this).find(selector).each(function() {
				height += $(this).height();
			});
			return height - notExtra.height;
		}
	});
})(jQuery);

$(document).ready(function() {
	$(document).svImgBoxTabInit({'openTab': ':last'});
});

