/*
 * Drives the testimonals tabs on the home page
 */
(function($){
	$.fn.testimtabs = function(config) {
		var defaults = {
			panel: ".testimtab",
			tabset: "testimonialtabs_tabset",
			tab: ".tab"
		};
		panelset = {
			panels : {},
			tabs : {},
			opt : $.extend(defaults, config)	
		};
		showTab = function(tabIdx){
			panelset.panels.each(function(idx){
				if(idx == tabIdx) $(this).fadeIn();
				else $(this).hide();
			});
			panelset.tabs.each(function(idx){
				if(idx == tabIdx) $(this).addClass("selected");
				else $(this).removeClass("selected");
			});
		};
		return this.each(function() {
			//For the found element
			var $panelset = $(this),
				$panels = $panelset.find(panelset.opt.panel),
				$tabs = $panelset.find(panelset.opt.tab),
				$tabset = $("<ul>", {"class":panelset.opt.tabset}),
				panelnum = $panels.length;
			
			//Insert the tab holding <ul> before the panelset
			$panelset.before($tabset);
			
			//Switch the tabs to be <li>'s. They are probably <p>'s
			$tabs.replaceWith(function() {
  				return $("<li>",{"class":"tab"}).append($(this).contents());
			});
			//Rebuild $tabs : Need to do this due to replacement above
			$tabs = $panelset.find(panelset.opt.tab);
			//Detach the tabs from the blocks and put them into the tab holder			
			$tabs.detach().appendTo($tabset).css({cursor:"pointer"}).click(function(ev){
				showTab($(this).index());
			}).first().addClass("selected");
			//store a ref to the panels and tabs in the panelset obj
			panelset.panels = $panels;
			panelset.tabs = $tabs;
			
			//Hide all but the first panel
			$panels.each(function(idx){
				if(idx > 0) $(this).hide();
			});
			
			//Position the tabset above and outside the parent			
			$tabset.css({position:"absolute", top:-$tabset.outerHeight(true)+"px" });
		});		
	};

})(jQuery);

