﻿(function($) {
	$.fn.tabify = function(settings) {
		var config = { selectedCssClass : 'selected' };
		if (settings) $.extend(config, settings);
		// Here 'this' refers to the jquery object(s) selected
		this.each(function() {
			var currContainer = $(this);
			var links = currContainer.find('a');
			// Here 'this' refers to a specific html element in the list of selected jquery objects
			links.each(function() {
				// Here 'this' refers to an html link that is contained in the current jquery object
				var currLink = $(this);
				
				// If the link points to the ID of an element, tabify it
				if (currLink.attr('href').indexOf('#') == 0) {
					currLink.click(function() {
						var target = $($(this).attr('href'));
						if (target) {
							// Hide the currently selected tab
							if (currContainer.data('current-tab')) {
								currContainer.data('current-tab').hide();
							}
							
							// Remove the css class from the currently selected link
							if (config.selectedCssClass && currContainer.data('selected-link')) {
								currContainer.data('selected-link').removeClass(config.selectedCssClass);
							}
							
							// Fade in the new target
							target.fadeIn();
							
							// Capture the current items as data
							currContainer.data('current-tab', target);
							currContainer.data('selected-link', currLink);
							
							// Set the CSS class on the current link
							if (config.selectedCssClass) {
								currLink.addClass(config.selectedCssClass);
							}
						}
						
						// Prevent the default link behavior for these links
						return false;
					});
				}
			});
			
			// Simulate a click on the first link in the list
			if (links.length > 0) {
				$(links[0]).trigger('click');
			}
		});
		return this;
	};
})(jQuery);
