/*
 * jQuery UI Tabs
 *
 * Copyright (c) 2007, 2008 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 *
 */
(function(jQ) {

jQ.widget("ui.tabs", {
	init: function() {
		this.options.event += '.tabs'; // namespace event
		
		// create tabs
		this.tabify(true);
	},
	setData: function(key, value) {
		if ((/^selected/).test(key))
			this.select(value);
		else {
			this.options[key] = value;
			this.tabify();
		}
	},
	length: function() {
		return this.jQtabs.length;
	},
	tabId: function(a) {
		return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '')
			|| this.options.idPrefix + jQ.data(a);
	},
	ui: function(tab, panel) {
		return {
			options: this.options,
			tab: tab,
			panel: panel
		};
	},
	tabify: function(init) {

		this.jQlis = jQ('li:has(a[href])', this.element);
		this.jQtabs = this.jQlis.map(function() { return jQ('a', this)[0]; });
		this.jQpanels = jQ([]);

		var self = this, o = this.options;

		this.jQtabs.each(function(i, a) {
			// inline tab
			if (a.hash && a.hash.replace('#', '')) // Safari 2 reports '#' for an empty hash
				self.jQpanels = self.jQpanels.add(a.hash);
			// remote tab
			else if (jQ(a).attr('href') != '#') { // prevent loading the page itself if href is just "#"
				jQ.data(a, 'href.tabs', a.href); // required for restore on destroy
				jQ.data(a, 'load.tabs', a.href); // mutable
				var id = self.tabId(a);
				a.href = '#' + id;
				var jQpanel = jQ('#' + id);
				if (!jQpanel.length) {
					jQpanel = jQ(o.panelTemplate).attr('id', id).addClass(o.panelClass)
						.insertAfter( self.jQpanels[i - 1] || self.element );
					jQpanel.data('destroy.tabs', true);
				}
				self.jQpanels = self.jQpanels.add( jQpanel );
			}
			// invalid tab href
			else
				o.disabled.push(i + 1);
		});

		if (init) {

			// attach necessary classes for styling if not present
			this.element.addClass(o.navClass);
			this.jQpanels.each(function() {
				var jQthis = jQ(this);
				jQthis.addClass(o.panelClass);
			});

			// Selected tab
			// use "selected" option or try to retrieve:
			// 1. from fragment identifier in url
			// 2. from cookie
			// 3. from selected class attribute on <li>
			if (o.selected === undefined) {
				if (location.hash) {
					this.jQtabs.each(function(i, a) {
						if (a.hash == location.hash) {
							o.selected = i;
							// prevent page scroll to fragment
							if (jQ.browser.msie || jQ.browser.opera) { // && !o.remote
								var jQtoShow = jQ(location.hash), toShowId = jQtoShow.attr('id');
								jQtoShow.attr('id', '');
								setTimeout(function() {
									jQtoShow.attr('id', toShowId); // restore id
								}, 500);
							}
							scrollTo(0, 0);
							return false; // break
						}
					});
				}
				else if (o.cookie) {
					var index = parseInt(jQ.cookie('ui-tabs' + jQ.data(self.element)),10);
					if (index && self.jQtabs[index])
						o.selected = index;
				}
				else if (self.jQlis.filter('.' + o.selectedClass).length)
					o.selected = self.jQlis.index( self.jQlis.filter('.' + o.selectedClass)[0] );
			}
			o.selected = o.selected === null || o.selected !== undefined ? o.selected : 0; // first tab selected by default

			// Take disabling tabs via class attribute from HTML
			// into account and update option properly.
			// A selected tab cannot become disabled.
			o.disabled = jQ.unique(o.disabled.concat(
				jQ.map(this.jQlis.filter('.' + o.disabledClass),
					function(n, i) { return self.jQlis.index(n); } )
			)).sort();
			if (jQ.inArray(o.selected, o.disabled) != -1)
				o.disabled.splice(jQ.inArray(o.selected, o.disabled), 1);
			
			// highlight selected tab
			this.jQpanels.addClass(o.hideClass);
			this.jQlis.removeClass(o.selectedClass);
			if (o.selected !== null) {
				this.jQpanels.eq(o.selected).show().removeClass(o.hideClass); // use show and remove class to show in any case no matter how it has been hidden before
				this.jQlis.eq(o.selected).addClass(o.selectedClass);
				
				// seems to be expected behavior that the show callback is fired
				var onShow = function() {
					jQ(self.element).triggerHandler('tabsshow',
						[self.ui(self.jQtabs[o.selected], self.jQpanels[o.selected])], o.show);
				}; 

				// load if remote tab
				if (jQ.data(this.jQtabs[o.selected], 'load.tabs'))
					this.load(o.selected, onShow);
				// just trigger show event
				else
					onShow();
				
			}
			
			// clean up to avoid memory leaks in certain versions of IE 6
			jQ(window).bind('unload', function() {
				self.jQtabs.unbind('.tabs');
				self.jQlis = self.jQtabs = self.jQpanels = null;
			});

		}

		// disable tabs
		for (var i = 0, li; li = this.jQlis[i]; i++)
			jQ(li)[jQ.inArray(i, o.disabled) != -1 && !jQ(li).hasClass(o.selectedClass) ? 'addClass' : 'removeClass'](o.disabledClass);

		// reset cache if switching from cached to not cached
		if (o.cache === false)
			this.jQtabs.removeData('cache.tabs');
		
		// set up animations
		var hideFx, showFx, baseFx = { 'min-width': 0, duration: 1 }, baseDuration = 'normal';
		if (o.fx && o.fx.constructor == Array)
			hideFx = o.fx[0] || baseFx, showFx = o.fx[1] || baseFx;
		else
			hideFx = showFx = o.fx || baseFx;

		// reset some styles to maintain print style sheets etc.
		var resetCSS = { display: '', overflow: '', height: '' };
		if (!jQ.browser.msie) // not in IE to prevent ClearType font issue
			resetCSS.opacity = '';

		// Hide a tab, animation prevents browser scrolling to fragment,
		// jQshow is optional.
		function hideTab(clicked, jQhide, jQshow) {
			jQhide.animate(hideFx, hideFx.duration || baseDuration, function() { //
				jQhide.addClass(o.hideClass).css(resetCSS); // maintain flexible height and accessibility in print etc.
				if (jQ.browser.msie && hideFx.opacity)
					jQhide[0].style.filter = '';
				if (jQshow)
					showTab(clicked, jQshow, jQhide);
			});
		}

		// Show a tab, animation prevents browser scrolling to fragment,
		// jQhide is optional.
		function showTab(clicked, jQshow, jQhide) {
			if (showFx === baseFx)
				jQshow.css('display', 'block'); // prevent occasionally occuring flicker in Firefox cause by gap between showing and hiding the tab panels
			jQshow.animate(showFx, showFx.duration || baseDuration, function() {
				jQshow.removeClass(o.hideClass).css(resetCSS); // maintain flexible height and accessibility in print etc.
				if (jQ.browser.msie && showFx.opacity)
					jQshow[0].style.filter = '';

				// callback
				jQ(self.element).triggerHandler('tabsshow',
					[self.ui(clicked, jQshow[0])], o.show);

			});
		}

		// switch a tab
		function switchTab(clicked, jQli, jQhide, jQshow) {
			/*if (o.bookmarkable && trueClick) { // add to history only if true click occured, not a triggered click
				jQ.ajaxHistory.update(clicked.hash);
			}*/
			jQli.addClass(o.selectedClass)
				.siblings().removeClass(o.selectedClass);
			hideTab(clicked, jQhide, jQshow);
		}

		// attach tab event handler, unbind to avoid duplicates from former tabifying...
		this.jQtabs.unbind('.tabs').bind(o.event, function() {

			//var trueClick = e.clientX; // add to history only if true click occured, not a triggered click
			var jQli = jQ(this).parents('li:eq(0)'),
				jQhide = self.jQpanels.filter(':visible'),
				jQshow = jQ(this.hash);

			// If tab is already selected and not unselectable or tab disabled or 
			// or is already loading or click callback returns false stop here.
			// Check if click handler returns false last so that it is not executed
			// for a disabled or loading tab!
			if ((jQli.hasClass(o.selectedClass) && !o.unselect)
				|| jQli.hasClass(o.disabledClass) 
				|| jQ(this).hasClass(o.loadingClass)
				|| jQ(self.element).triggerHandler('tabsselect', [self.ui(this, jQshow[0])], o.select) === false
				) {
				this.blur();
				return false;
			}

			self.options.selected = self.jQtabs.index(this);

			// if tab may be closed
			if (o.unselect) {
				if (jQli.hasClass(o.selectedClass)) {
					self.options.selected = null;
					jQli.removeClass(o.selectedClass);
					self.jQpanels.stop();
					hideTab(this, jQhide);
					this.blur();
					return false;
				} else if (!jQhide.length) {
					self.jQpanels.stop();
					var a = this;
					self.load(self.jQtabs.index(this), function() {
						jQli.addClass(o.selectedClass).addClass(o.unselectClass);
						showTab(a, jQshow);
					});
					this.blur();
					return false;
				}
			}

			if (o.cookie)
				jQ.cookie('ui-tabs' + jQ.data(self.element), self.options.selected, o.cookie);

			// stop possibly running animations
			self.jQpanels.stop();

			// show new tab
			if (jQshow.length) {

				// prevent scrollbar scrolling to 0 and than back in IE7, happens only if bookmarking/history is enabled
				/*if (jQ.browser.msie && o.bookmarkable) {
					var showId = this.hash.replace('#', '');
					jQshow.attr('id', '');
					setTimeout(function() {
						jQshow.attr('id', showId); // restore id
					}, 0);
				}*/

				var a = this;
				self.load(self.jQtabs.index(this), jQhide.length ? 
					function() {
						switchTab(a, jQli, jQhide, jQshow);
					} :
					function() {
						jQli.addClass(o.selectedClass);
						showTab(a, jQshow);
					}
				);

				// Set scrollbar to saved position - need to use timeout with 0 to prevent browser scroll to target of hash
				/*var scrollX = window.pageXOffset || document.documentElement && document.documentElement.scrollLeft || document.body.scrollLeft || 0;
				var scrollY = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop || 0;
				setTimeout(function() {
					scrollTo(scrollX, scrollY);
				}, 0);*/

			} else
				throw 'jQuery UI Tabs: Mismatching fragment identifier.';

			// Prevent IE from keeping other link focussed when using the back button
			// and remove dotted border from clicked link. This is controlled in modern
			// browsers via CSS, also blur removes focus from address bar in Firefox
			// which can become a usability and annoying problem with tabsRotate.
			if (jQ.browser.msie)
				this.blur();

			//return o.bookmarkable && !!trueClick; // convert trueClick == undefined to Boolean required in IE
			return false;

		});

		// disable click if event is configured to something else
		if (!(/^click/).test(o.event))
			this.jQtabs.bind('click.tabs', function() { return false; });

	},
	add: function(url, label, index) {
		if (index == undefined) 
			index = this.jQtabs.length; // append by default

		var o = this.options;
		var jQli = jQ(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label));
		jQli.data('destroy.tabs', true);

		var id = url.indexOf('#') == 0 ? url.replace('#', '') : this.tabId( jQ('a:first-child', jQli)[0] );

		// try to find an existing element before creating a new one
		var jQpanel = jQ('#' + id);
		if (!jQpanel.length) {
			jQpanel = jQ(o.panelTemplate).attr('id', id)
				.addClass(o.hideClass)
				.data('destroy.tabs', true);
		}
		jQpanel.addClass(o.panelClass);
		if (index >= this.jQlis.length) {
			jQli.appendTo(this.element);
			jQpanel.appendTo(this.element[0].parentNode);
		} else {
			jQli.insertBefore(this.jQlis[index]);
			jQpanel.insertBefore(this.jQpanels[index]);
		}
		
		o.disabled = jQ.map(o.disabled,
			function(n, i) { return n >= index ? ++n : n });
			
		this.tabify();

		if (this.jQtabs.length == 1) {
			jQli.addClass(o.selectedClass);
			jQpanel.removeClass(o.hideClass);
			var href = jQ.data(this.jQtabs[0], 'load.tabs');
			if (href)
				this.load(index, href);
		}

		// callback
		this.element.triggerHandler('tabsadd',
			[this.ui(this.jQtabs[index], this.jQpanels[index])], o.add
		);
	},
	remove: function(index) {
		var o = this.options, jQli = this.jQlis.eq(index).remove(),
			jQpanel = this.jQpanels.eq(index).remove();

		// If selected tab was removed focus tab to the right or
		// in case the last tab was removed the tab to the left.
		if (jQli.hasClass(o.selectedClass) && this.jQtabs.length > 1)
			this.select(index + (index + 1 < this.jQtabs.length ? 1 : -1));

		o.disabled = jQ.map(jQ.grep(o.disabled, function(n, i) { return n != index; }),
			function(n, i) { return n >= index ? --n : n });

		this.tabify();

		// callback
		this.element.triggerHandler('tabsremove',
			[this.ui(jQli.find('a')[0], jQpanel[0])], o.remove
		);
	},
	enable: function(index) {
		var o = this.options;
		if (jQ.inArray(index, o.disabled) == -1)
			return;
			
		var jQli = this.jQlis.eq(index).removeClass(o.disabledClass);
		if (jQ.browser.safari) { // fix disappearing tab (that used opacity indicating disabling) after enabling in Safari 2...
			jQli.css('display', 'inline-block');
			setTimeout(function() {
				jQli.css('display', 'block');
			}, 0);
		}

		o.disabled = jQ.grep(o.disabled, function(n, i) { return n != index; });

		// callback
		this.element.triggerHandler('tabsenable',
			[this.ui(this.jQtabs[index], this.jQpanels[index])], o.enable
		);

	},
	disable: function(index) {
		var self = this, o = this.options;
		if (index != o.selected) { // cannot disable already selected tab
			this.jQlis.eq(index).addClass(o.disabledClass);

			o.disabled.push(index);
			o.disabled.sort();

			// callback
			this.element.triggerHandler('tabsdisable',
				[this.ui(this.jQtabs[index], this.jQpanels[index])], o.disable
			);
		}
	},
	select: function(index) {
		if (typeof index == 'string')
			index = this.jQtabs.index( this.jQtabs.filter('[hrefjQ=' + index + ']')[0] );
		this.jQtabs.eq(index).trigger(this.options.event);
	},
	load: function(index, callback) { // callback is for internal usage only
		
		var self = this, o = this.options, jQa = this.jQtabs.eq(index), a = jQa[0],
				bypassCache = callback == undefined || callback === false, url = jQa.data('load.tabs');

		callback = callback || function() {};
		
		// no remote or from cache - just finish with callback
		if (!url || !bypassCache && jQ.data(a, 'cache.tabs')) {
			callback();
			return;
		}

		// load remote from here on
		
		var inner = function(parent) {
			var jQparent = jQ(parent), jQinner = jQparent.find('*:last');
			return jQinner.length && jQinner || jQparent;
		};
		var cleanup = function() {
			self.jQtabs.filter('.' + o.loadingClass).removeClass(o.loadingClass)
						.each(function() {
							if (o.spinner)
								inner(this).parent().html(inner(this).data('label.tabs'));
						});
			self.xhr = null;
		};
		
		if (o.spinner) {
			var label = inner(a).html();
			inner(a).wrapInner('<em></em>')
				.find('em').data('label.tabs', label).html(o.spinner);
		}

		var ajaxOptions = jQ.extend({}, o.ajaxOptions, {
			url: url,
			success: function(r, s) {
				jQ(a.hash).html(r);
				cleanup();
				
				if (o.cache)
					jQ.data(a, 'cache.tabs', true); // if loaded once do not load them again

				// callbacks
				jQ(self.element).triggerHandler('tabsload',
					[self.ui(self.jQtabs[index], self.jQpanels[index])], o.load
				);
				o.ajaxOptions.success && o.ajaxOptions.success(r, s);
				
				// This callback is required because the switch has to take
				// place after loading has completed. Call last in order to 
				// fire load before show callback...
				callback();
			}
		});
		if (this.xhr) {
			// terminate pending requests from other tabs and restore tab label
			this.xhr.abort();
			cleanup();
		}
		jQa.addClass(o.loadingClass);
		setTimeout(function() { // timeout is again required in IE, "wait" for id being restored
			self.xhr = jQ.ajax(ajaxOptions);
		}, 0);

	},
	url: function(index, url) {
		this.jQtabs.eq(index).removeData('cache.tabs').data('load.tabs', url);
	},
	destroy: function() {
		var o = this.options;
		this.element.unbind('.tabs')
			.removeClass(o.navClass).removeData('tabs');
		this.jQtabs.each(function() {
			var href = jQ.data(this, 'href.tabs');
			if (href)
				this.href = href;
			var jQthis = jQ(this).unbind('.tabs');
			jQ.each(['href', 'load', 'cache'], function(i, prefix) {
				jQthis.removeData(prefix + '.tabs');
			});
		});
		this.jQlis.add(this.jQpanels).each(function() {
			if (jQ.data(this, 'destroy.tabs'))
				jQ(this).remove();
			else
				jQ(this).removeClass([o.selectedClass, o.unselectClass,
					o.disabledClass, o.panelClass, o.hideClass].join(' '));
		});
	}
});

jQ.ui.tabs.defaults = {
	// basic setup
	unselect: false,
	event: 'click',
	disabled: [],
	cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
	// TODO history: false,

	// Ajax
	spinner: 'Loading&#8230;',
	cache: false,
	idPrefix: 'ui-tabs-',
	ajaxOptions: {},

	// animations
	fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }

	// templates
	tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>',
	panelTemplate: '<div></div>',

	// CSS classes
	navClass: 'ui-tabs-nav',
	selectedClass: 'ui-tabs-selected',
	unselectClass: 'ui-tabs-unselect',
	disabledClass: 'ui-tabs-disabled',
	panelClass: 'ui-tabs-panel',
	hideClass: 'ui-tabs-hide',
	loadingClass: 'ui-tabs-loading'
};

jQ.ui.tabs.getter = "length";

/*
 * Tabs Extensions
 */

/*
 * Rotate
 */
jQ.extend(jQ.ui.tabs.prototype, {
	rotation: null,
	rotate: function(ms, continuing) {
		
		continuing = continuing || false;
		
		var self = this, t = this.options.selected;
		
		function start() {
			self.rotation = setInterval(function() {
				t = ++t < self.jQtabs.length ? t : 0;
				self.select(t);
			}, ms); 
		}
		
		function stop(e) {
			if (!e || e.clientX) { // only in case of a true click
				clearInterval(self.rotation);
			}
		}
		
		// start interval
		if (ms) {
			start();
			if (!continuing)
				this.jQtabs.bind(this.options.event, stop);
			else
				this.jQtabs.bind(this.options.event, function() {
					stop();
					t = self.options.selected;
					start();
				});
		}
		// stop interval
		else {
			stop();
			this.jQtabs.unbind(this.options.event, stop);
		}
	}
});

})(jQuery);

