/**
 * EA.com Tab jQuery Plug-in - Compatible with jQuery-1.2.6.js
 *
 * @author Karl Stanton (Fi)
 * @version 2.0 (Now includes logic for single tab calls and extending widths of tabs to stretch the entire component)
 * @version 2.1 Fixed calculation of tab widths when the number of tabs is not evenly dividable by the container width
 *
 * Usage: 
 *   - Use all h3 Objects in passed element to create UL List of Tabs
 *   - Each h3 relates to it's sibling DIV, which is the content to be paginated.
 *   	- <h3>Title</h3><div class="tabContent">Content of the tab</div><h3>Title 2</h3><div class="tabContent">Content of the second tab</div>
 *   - In a 'document ready' function, execute the plug in as follows:
 *   
	$(document).ready(function () {
		// Without defining options (will paginate all children)
		$("[element containing children]").eatabs();

		// Defining options
		$("[element containing children]").eatabs({
			N / A
		});

	});
 * 
 *
 * Order of programming execution:
 *   - Loop through parent div, use h3's to create tabs
 *	 - Set height of tab to equal height of first tabbed content
 *	 - Bind event listeners to the A elements
 *     - When events are triggered, DOM order index of A will triger DOM order index of tabbed component
**/

/*
var $ = {};
var jQuery = {};
var EA = {};
var config = {};
*/

(function ($) {
	$.fn.eatab = function ($options) {
	
		var $defaults = {
			setwidth: true,			// by default, set the width of the tabs.
			setheight: true,		// by default, set the height of the tabs.
			outerWidthExtra: 37,	// the padding and margin set in style sheet for the yet non-existing span
			equalizecols: null,		// provide a selector for content to equalize heights for on a page update
			cookieKey:null
		};
		
		// extend the options
		var $opts = jQuery.extend($defaults, $options);
		
		// bring the options to the pagination object
		for (var i in $opts) {
			if (i) {
				jQuery.eatab[i] = $opts[i];
			}
		}
		
		return this.each(function () {
			// Get the element
			var el = jQuery(this);
			
			el.show();
			
			var opts = jQuery.meta ? jQuery.extend({}, $opts, el.data()) : $opts;
	
			//attach a reference to these options to the element
			jQuery.data(el.get(0), "options", {	options: opts });
	
			// We will use h3 as our tab titles
			var h3 = el.children("h3");
		
			// Build our tab menu
			var ul = jQuery("<ul class=\"nav\">");

			// Number of tabs
			var n = h3.length;

			var spanWidth;
			var pixelFill = 0;
			if (n > 1 && opts.setwidth) {
				// Get the width of our component, subtract the padding/width of each tab and divide by the width of the component
				var w = el.outerWidth(true);

				// Margins to consider ((num tabs - 1) * 10 pixels per magin)
				var m = ((n - 1) * 10);
				
				// Extra width for the spans such as margin and padding
				var e = opts.outerWidthExtra * n;
				
				// calculate the largest size for each tab (integer)
				spanWidth = Math.floor((w - m - e) / n);
				
				// check if we have any remaining pixels to fill (incase the number of tabs isn't evenly diviable by the width)
				pixelFill = w % (m + e + (spanWidth * n));
			}
			
			// Use the values of the h3's to build our tab menu
			h3.each(function (index) {
				
				var span = "<span>";
				
				//add width to tab if requested
				if (n > 1 && opts.setwidth) {
					
					// pixel corrent last tab if needed
					if ((index == (n - 1)) && (pixelFill > 0)) {
						spanWidth = spanWidth + pixelFill;
					}

					span = '<span style="width:' + spanWidth + 'px;">';
				}

				// Create the LI
				var li = jQuery("<li><a href=\"#\" onclick=\"return false;\">" + span + jQuery(this).html() + "</span></a></li>");
				// Add it to the UL
				ul.append(li);
			});

			ul.children("li:first").addClass("ui-tabs-selected-first").addClass("first").children("a").addClass("selected");//.end()
			ul.children("li:last").addClass("last");

			// Now delete the h3's
			h3.remove();
			h3 = null;
			
			// Hide the div's, except the first one which is defaulted on
			el.children("div:not(:first)").hide();
			el.children().wrapAll("<div class=\"sections\">");

			// Bind an event to that fresh LI
			var tabs = ul.find("a");
			tabs.each(function(idx){
				this['idx'] = idx;
				var tab = $(this);
				tab.click(function(){
					if (!jQuery(this).hasClass("selected")) {
						jQuery.eatab.tabulate(tabs, this, el);
						if($opts.cookieKey){
							EA.framework.setSessionOnlyCookie($opts.cookieKey, this['idx']); 
						}
					}				
				});
			});
			//tabs.click(function () {
				//if (!jQuery(this).hasClass("selected")) {
					//jQuery.eatab.tabulate(tabs, this, el);
				//}
			//});

			// Insert the UL
			el.prepend(ul);
			

			// Enable the bottomCap/bottomClosed images to be seen
			el.addClass("tabs").find(".tab-more").removeClass("tab-more");
			
			el.show();
			




			/* removed initial height calculation and just tab to first tab instead - (5 march 2009 - david.lindkvist) */
			/*
			var sections = el.children(".sections");
			// Now set the height of the sections div
			var div = sections.children("div.tabContent:first");
			var h = div.outerHeight(true);
			*/
			
			/* the following code was already removed */
			/*if($.browser.msie) {
				h += 8;
			}*/
				
			/* removed initial height calculation and just tab to first tab instead - (5 march 2009 - david.lindkvist) */
			//sections.height(h);
			
			
			
	
			//check if we want to equalize the height of something inside the tab content
			if (opts.equalizecols !== null && jQuery.fn.equalizeCols !== undefined) {
				
				el.find(".sections div.tabContent").each(function() {
				
					var div = $(this);
					
					//show element with hidden visibility, equalize heights and hide it again
					div.css({visibility: 'hidden'});
					div.show();
					$(opts.equalizecols, div).equalizeCols();
					div.hide();
					div.css({visibility: 'visible'});	
				});
			}
			
			//added instead of the height calculation above (5 march 2009 - david.lindkvist)
			jQuery.eatab.tabulate(tabs, ul.find("a:first"), el);
			
		});
	};
	
	$.extend({eatab: {
		tabulate : function (tabs, a, el) {
			
			var opts = el.data("options").options;
			
			var sections = el.children(".sections");
			sections.stop();

			var i = tabs.index(a);

			// Style
			jQuery("#" + el.attr("id") +  " .nav li a")
				.removeClass("selected")
				.parent()
				.removeClass("ui-tabs-selected")
				.removeClass("ui-tabs-selected-first")
				.removeClass("ui-tabs-selected-last");
			
			if (i === 0) {
				jQuery(a).addClass("selected").parent().addClass("ui-tabs-selected-first").addClass("ui-tabs-selected");
			} else if (i < (tabs.length - 1)) {
				jQuery(a).addClass("selected").parent().addClass("ui-tabs-selected");
			} else {
				jQuery(a).addClass("selected").parent().addClass("ui-tabs-selected-last").addClass("ui-tabs-selected");
			}

			// Hide all the other tabs, show the requested one
			sections.children("div").hide();

			var div = sections.children("div.tabContent:eq(" + i + ")");

			jQuery.eatab.resizeAndShow(sections, div, opts);
		},
		
		resizeAndShow : function (sections, div, opts){
			// Resize the tab gracefully
			var h = div.outerHeight(true);
			
			// && $.browser.version < 7
			if ($.browser.msie) {
				if (opts.setheight) {
					sections.height(h);
				}
				div.show();
			} else {
				if (sections.outerHeight() !== h && opts.setheight) {
					// Animate
					sections.animate({
						height: h
					}, 100, function () {
						div.fadeIn("fast");
					});
				}
				else {
					div.fadeIn("fast");
				}
			}
		}
	}});

})(jQuery);