/**
 * jQuery --> Simple Tags Plugin (STP) 
 * v1.0
 *
 * The plugin will bind specific events to the passed selector elements.
 * Ensure you pass the relevant <a> tags with standard anchor IDs in the
 * the HREF attribute e.g. <a href="#myanchor"></a>
 *
 * @copyright	Start Creative, 2007
 * @author		Paul Campbell <paulc@startcreative.co.uk>
 * @author		Matthew Lane <matthewl@startcreative.co.uk>
 *
 * @option		defaultSelection	(Integer) 	Element to be selected by default upon execution
 * @option		activeClass			(String)	Class applied to selected element
 * @option		transition			(String)	Style of transition on click (current options: none, fade)
 *
 * @return		Array
 */
(function() {
	
	jQuery.fn.tabbing = function(settings) {
		
		settings = jQuery.extend({
			defaultSelection: 0,
			activeClass: "current",
			lastClass: "last",
			titles: "h2",
			tabsTarget: "tab-area",
			tabsClass: "tabs"
		}, settings);
		
		var elements = this;
		var target = $("#" + settings.tabsTarget);
		var tabs = new Array();
		var current = false;
		var i = 0;
		
		elements.each(function() {
			
			// Get jQuery object for current element
			var el = $(this);
			
			// Get tab data and hide title
			var title = el.children(settings.titles);
			tabs.push(
				{ anchor: el.attr("id"), text: title.hide().html() }
			);
			el.hide();
			
		});
		
		// Create tabs
		target.prepend('<ul class="' + settings.tabsClass + '"></ul>');
		var list = target.children("." + settings.tabsClass);
		
		for(var i = 0; i<tabs.length; i++) {
			
			list.append('<li><a href="#' + tabs[i].anchor + '">' + tabs[i].text + '</a></li>');
			var link = list.children(":last");
			
			if(i == tabs.length - 1) {
				link.addClass("last");
			}
			
			// Bind click method
			link.children("a").click(function() {
				
				var focus = $(this);
				// Only call for a non-active element
				var state = focus.attr("class");
				if(state == undefined || state.indexOf( settings.activeClass ) == -1) {
					

					focus.parent().parent().children().each(function() { 						
						// Remove active class from focus element
						var a = $(this).children("a");
						a.removeClass( settings.activeClass );		
						// Hide target element
						$("#" + a.attr("href").split("#").pop()).hide();
					});
					
					elements.hide();
					$("#" + focus.attr("href").split("#").pop()).show();
					focus.addClass( settings.activeClass );
				}
				if(current) {
					current.removeClass()
				}
				// Save the current object
				current = focus;
				
				return(false);
			});
		
		}
		
		// Append last class
		list.children(":last").addClass(settings.lastClass);
		// Set default
		$("#" + settings.tabsTarget + " ul li a").eq(settings.defaultSelection).trigger("click");
		
		//////////////////////// Apply ////
		return( elements );		
	}
	
})(jQuery)