/*
 * jQuery UI Tabs 1.6rc6
 *
 * Copyright (c) 2009 AUTHORS.txt (http://ui.jquery.com/about)
 * 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(jQuery) {

jQuery.widget("ui.tabs", {

	_init: function() {
		// create tabs
		this._tabify(true);
	},

	_setData: function(key, value) {
		if ((/^selected/).test(key))
			this.select(value);
		else {
			this.options[key] = value;
			this._tabify();
		}
	},

	_tabId: function(a) {
		return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '')
			|| this.options.idPrefix + jQuery.data(a);
	},

	_sanitizeSelector: function(hash) {
		return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":"
	},

	_cookie: function() {
		var cookie = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + jQuery.data(this.list[0]));
		return jQuery.cookie.apply(null, [cookie].concat(jQuery.makeArray(arguments)));
	},
	
	_ui: function(tab, panel) {
		return {
			tab: tab,
			panel: panel,
			index: this.jQuerytabs.index(tab)
		};
	},

	_tabify: function(init) {

		this.list = this.element.is('div') ? this.element.children('ul:first, ol:first').eq(0) : this.element;
		this.jQuerylis = jQuery('li:has(a[href])', this.list);
		this.jQuerytabs = this.jQuerylis.map(function() { return jQuery('a', this)[0]; });
		this.jQuerypanels = jQuery([]);

		var self = this, o = this.options;

		var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash
		this.jQuerytabs.each(function(i, a) {
			var href = jQuery(a).attr('href');

			// inline tab
			if (fragmentId.test(href))
				self.jQuerypanels = self.jQuerypanels.add(self._sanitizeSelector(href));

			// remote tab
			else if (href != '#') { // prevent loading the page itself if href is just "#"
				jQuery.data(a, 'href.tabs', href); // required for restore on destroy

				// TODO until #3808 is fixed strip fragment identifier from url
				// (IE fails to load from such url)
				jQuery.data(a, 'load.tabs', href.replace(/#.*jQuery/, '')); // mutable data

				var id = self._tabId(a);
				a.href = '#' + id;
				var jQuerypanel = jQuery('#' + id);
				if (!jQuerypanel.length) {
					jQuerypanel = jQuery(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom')
						.insertAfter(self.jQuerypanels[i - 1] || self.list);
					jQuerypanel.data('destroy.tabs', true);
				}
				self.jQuerypanels = self.jQuerypanels.add(jQuerypanel);
			}

			// invalid tab href
			else
				o.disabled.push(i + 1);
		});

		// initialization from scratch
		if (init) {

			// attach necessary classes for styling
			if (this.element.is('div')) {
				this.element.addClass('ui-tabs ui-widget ui-widget-content ui-corner-all');
			}
			this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
			this.jQuerylis.addClass('ui-state-default ui-corner-top');
			this.jQuerypanels.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');

			// 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.jQuerytabs.each(function(i, a) {
						if (a.hash == location.hash) {
							o.selected = i;
							return false; // break
						}
					});
				}
				else if (o.cookie)
					o.selected = parseInt(self._cookie(), 10);

				else if (this.jQuerylis.filter('.ui-tabs-selected').length)
					o.selected = this.jQuerylis.index(this.jQuerylis.filter('.ui-tabs-selected'));

				else
				 	o.selected = 0;

			}
			else if (o.selected === null)
				o.selected = -1;

			// sanity check
			o.selected = ((o.selected >= 0 && this.jQuerytabs[o.selected]) || o.selected < 0) ? o.selected : 0; // default to first tab

			// Take disabling tabs via class attribute from HTML
			// into account and update option properly.
			// A selected tab cannot become disabled.
			o.disabled = jQuery.unique(o.disabled.concat(
				jQuery.map(this.jQuerylis.filter('.ui-state-disabled'),
					function(n, i) { return self.jQuerylis.index(n); } )
			)).sort();
			if (jQuery.inArray(o.selected, o.disabled) != -1)
				o.disabled.splice(jQuery.inArray(o.selected, o.disabled), 1);

			// highlight selected tab
			this.jQuerypanels.addClass('ui-tabs-hide');
			this.jQuerylis.removeClass('ui-tabs-selected ui-state-active');
			if (o.selected >= 0 && this.jQuerytabs.length) { // check for length avoids error when initializing empty list
				this.jQuerypanels.eq(o.selected).removeClass('ui-tabs-hide');
				var classes = ['ui-tabs-selected ui-state-active'];
				if (o.deselectable) classes.push('ui-tabs-deselectable');
				this.jQuerylis.eq(o.selected).addClass(classes.join(' '));

				// seems to be expected behavior that the show callback is fired
				var onShow = function() {
					self._trigger('show', null,
						self._ui(self.jQuerytabs[o.selected], self.jQuerypanels[o.selected]));
				};

				// load if remote tab
				if (jQuery.data(this.jQuerytabs[o.selected], 'load.tabs'))
					this.load(o.selected, onShow);
				// just trigger show event
				else onShow();
			}

			// states
			if (o.event != 'mouseover') {
				var handleState = function(state, el) {
					if (el.is(':not(.ui-state-disabled)')) el.toggleClass('ui-state-' + state);
				};
				this.jQuerylis.bind('mouseover.tabs mouseout.tabs', function() {
					handleState('hover', jQuery(this));
				});
				// TODO focus/blur don't seem to work with namespace
				this.jQuerytabs.bind('focus.tabs blur.tabs', function() {
					handleState('focus', jQuery(this).parents('li:first'));
				});
			}

			// clean up to avoid memory leaks in certain versions of IE 6
			jQuery(window).bind('unload', function() {
				self.jQuerylis.add(self.jQuerytabs).unbind('.tabs');
				self.jQuerylis = self.jQuerytabs = self.jQuerypanels = null;
			});

		}
		// update selected after add/remove
		else
			o.selected = this.jQuerylis.index(this.jQuerylis.filter('.ui-tabs-selected'));

		// set or update cookie after init and add/remove respectively
		if (o.cookie) this._cookie(o.selected, o.cookie);

		// disable tabs
		for (var i = 0, li; li = this.jQuerylis[i]; i++)
			jQuery(li)[jQuery.inArray(i, o.disabled) != -1 && !jQuery(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled');

		// reset cache if switching from cached to not cached
		if (o.cache === false) this.jQuerytabs.removeData('cache.tabs');

		// set up animations
		var hideFx, showFx;
		if (o.fx) {
			if (jQuery.isArray(o.fx)) {
				hideFx = o.fx[0];
				showFx = o.fx[1];
			}
			else hideFx = showFx = o.fx;
		}

		// Reset certain styles left over from animation
		// and prevent IE's ClearType bug...
		function resetStyle(jQueryel, fx) {
			jQueryel.css({ display: '' });
			if (jQuery.browser.msie && fx.opacity) jQueryel[0].style.removeAttribute('filter');
		}

		// Show a tab...
		var showTab = showFx ?
			function(clicked, jQueryshow) {
				jQueryshow.hide().removeClass('ui-tabs-hide') // avoid flicker that way
					.animate(showFx, 500, function() {
						resetStyle(jQueryshow, showFx);
						self._trigger('show', null, self._ui(clicked, jQueryshow[0]));
					});
			} :
			function(clicked, jQueryshow) {
				jQueryshow.removeClass('ui-tabs-hide');
				self._trigger('show', null, self._ui(clicked, jQueryshow[0]));
			};

		// Hide a tab, jQueryshow is optional...
		var hideTab = hideFx ?
			function(clicked, jQueryhide, jQueryshow) {
				jQueryhide.animate(hideFx, hideFx.duration || 'normal', function() {
					jQueryhide.addClass('ui-tabs-hide');
					resetStyle(jQueryhide, hideFx);
					if (jQueryshow) showTab(clicked, jQueryshow);
				});
			} :
			function(clicked, jQueryhide, jQueryshow) {
				jQueryhide.addClass('ui-tabs-hide');
				if (jQueryshow) showTab(clicked, jQueryshow);
			};

		// Switch a tab...
		function switchTab(clicked, jQueryli, jQueryhide, jQueryshow) {
			var classes = ['ui-tabs-selected ui-state-active'];
			if (o.deselectable) classes.push('ui-tabs-deselectable');
			jQueryli.removeClass('ui-state-default').addClass(classes.join(' '))
				.siblings().removeClass(classes.join(' ')).addClass('ui-state-default');
			hideTab(clicked, jQueryhide, jQueryshow);
		}

		// attach tab event handler, unbind to avoid duplicates from former tabifying...
		this.jQuerytabs.unbind('.tabs').bind(o.event + '.tabs', function() {

			var jQueryli = jQuery(this).parents('li:eq(0)'),
				jQueryhide = self.jQuerypanels.filter(':visible'),
				jQueryshow = jQuery(self._sanitizeSelector(this.hash));

			// If tab is already selected and not deselectable 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 ((jQueryli.hasClass('ui-state-active') && !o.deselectable)
				|| jQueryli.hasClass('ui-state-disabled')
				|| jQuery(this).hasClass('ui-tabs-loading')
				|| self._trigger('select', null, self._ui(this, jQueryshow[0])) === false
				) {
				this.blur();
				return false;
			}

			o.selected = self.jQuerytabs.index(this);

			// if tab may be closed TODO avoid redundant code in this block
			if (o.deselectable) {
				if (jQueryli.hasClass('ui-state-active')) {
					o.selected = -1;
					if (o.cookie) self._cookie(o.selected, o.cookie);
					jQueryli.removeClass('ui-tabs-selected ui-state-active ui-tabs-deselectable')
						.addClass('ui-state-default');
					self.jQuerypanels.stop();
					hideTab(this, jQueryhide);
					this.blur();
					return false;
				} else if (!jQueryhide.length) {
					if (o.cookie) self._cookie(o.selected, o.cookie);
					self.jQuerypanels.stop();
					var a = this;
					self.load(self.jQuerytabs.index(this), function() {
						jQueryli.addClass('ui-tabs-selected ui-state-active ui-tabs-deselectable')
							.removeClass('ui-state-default');
						showTab(a, jQueryshow);
					});
					this.blur();
					return false;
				}
			}

			if (o.cookie) self._cookie(o.selected, o.cookie);

			// stop possibly running animations
			self.jQuerypanels.stop();

			// show new tab
			if (jQueryshow.length) {
				var a = this;
				self.load(self.jQuerytabs.index(this), jQueryhide.length ?
					function() {
						switchTab(a, jQueryli, jQueryhide, jQueryshow);
					} :
					function() {
						jQueryli.addClass('ui-tabs-selected ui-state-active').removeClass('ui-state-default');
						showTab(a, jQueryshow);
					}
				);
			} 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 via CSS
			// in modern browsers; blur() removes focus from address bar in Firefox
			// which can become a usability and annoying problem with tabs('rotate').
			if (jQuery.browser.msie) this.blur();

			return false;

		});

		// disable click if event is configured to something else
		if (o.event != 'click') this.jQuerytabs.bind('click.tabs', function(){return false;});

	},
	
	destroy: function() {
		var o = this.options;

		this.element
			.removeClass('ui-tabs ui-widget ui-widget-content ui-corner-all');

		this.list.unbind('.tabs')
			.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all')
			.removeData('tabs');

		this.jQuerytabs.each(function() {
			var href = jQuery.data(this, 'href.tabs');
			if (href)
				this.href = href;
			var jQuerythis = jQuery(this).unbind('.tabs');
			jQuery.each(['href', 'load', 'cache'], function(i, prefix) {
				jQuerythis.removeData(prefix + '.tabs');
			});
		});

		this.jQuerylis.unbind('.tabs').add(this.jQuerypanels).each(function() {
			if (jQuery.data(this, 'destroy.tabs'))
				jQuery(this).remove();
			else
				jQuery(this).removeClass(
					'ui-state-default ' +
					'ui-corner-top ' +
					'ui-tabs-selected ' +
					'ui-state-active ' +
					'ui-tabs-deselectable ' +
					'ui-state-disabled ' +
					'ui-tabs-panel ' +
					'ui-widget-content ' +
					'ui-corner-bottom ' +
					'ui-tabs-hide');
		});

		if (o.cookie)
			this._cookie(null, o.cookie);
	},

	add: function(url, label, index) {
		if (index == undefined)
			index = this.jQuerytabs.length; // append by default

		var self = this, o = this.options;
		var jQueryli = jQuery(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label));
		jQueryli.addClass('ui-state-default ui-corner-top').data('destroy.tabs', true);

		var id = url.indexOf('#') == 0 ? url.replace('#', '') : this._tabId( jQuery('a:first-child', jQueryli)[0] );

		// try to find an existing element before creating a new one
		var jQuerypanel = jQuery('#' + id);
		if (!jQuerypanel.length) {
			jQuerypanel = jQuery(o.panelTemplate).attr('id', id).data('destroy.tabs', true);
		}
		jQuerypanel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide');
		if (index >= this.jQuerylis.length) {
			jQueryli.appendTo(this.list);
			jQuerypanel.appendTo(this.list[0].parentNode);
		}
		else {
			jQueryli.insertBefore(this.jQuerylis[index]);
			jQuerypanel.insertBefore(this.jQuerypanels[index]);
		}

		o.disabled = jQuery.map(o.disabled,
			function(n, i) { return n >= index ? ++n : n });

		this._tabify();

		if (this.jQuerytabs.length == 1) { // after tabify
			jQueryli.addClass('ui-tabs-selected ui-state-active');
			jQuerypanel.removeClass('ui-tabs-hide');
			var href = jQuery.data(this.jQuerytabs[0], 'load.tabs');
			if (href) this.load(0, function() {
				self._trigger('show', null,
					self._ui(self.jQuerytabs[0], self.jQuerypanels[0]));
			});
		}

		// callback
		this._trigger('add', null, this._ui(this.jQuerytabs[index], this.jQuerypanels[index]));
	},

	remove: function(index) {
		var o = this.options, jQueryli = this.jQuerylis.eq(index).remove(),
			jQuerypanel = this.jQuerypanels.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 (jQueryli.hasClass('ui-tabs-selected') && this.jQuerytabs.length > 1)
			this.select(index + (index + 1 < this.jQuerytabs.length ? 1 : -1));

		o.disabled = jQuery.map(jQuery.grep(o.disabled, function(n, i) { return n != index; }),
			function(n, i) { return n >= index ? --n : n });

		this._tabify();

		// callback
		this._trigger('remove', null, this._ui(jQueryli.find('a')[0], jQuerypanel[0]));
	},

	enable: function(index) {
		var o = this.options;
		if (jQuery.inArray(index, o.disabled) == -1)
			return;

		this.jQuerylis.eq(index).removeClass('ui-state-disabled');
		o.disabled = jQuery.grep(o.disabled, function(n, i) { return n != index; });

		// callback
		this._trigger('enable', null, this._ui(this.jQuerytabs[index], this.jQuerypanels[index]));
	},

	disable: function(index) {
		var self = this, o = this.options;
		if (index != o.selected) { // cannot disable already selected tab
			this.jQuerylis.eq(index).addClass('ui-state-disabled');

			o.disabled.push(index);
			o.disabled.sort();

			// callback
			this._trigger('disable', null, this._ui(this.jQuerytabs[index], this.jQuerypanels[index]));
		}
	},

	select: function(index) {
		if (typeof index == 'string')
			index = this.jQuerytabs.index(this.jQuerytabs.filter('[hrefjQuery=' + index + ']'));
		this.jQuerytabs.eq(index).trigger(this.options.event + '.tabs');
	},

	load: function(index, callback) { // callback is for internal usage only

		var self = this, o = this.options, jQuerya = this.jQuerytabs.eq(index), a = jQuerya[0],
				bypassCache = callback == undefined || callback === false, url = jQuerya.data('load.tabs');
				// TODO bypassCache == false should work

		callback = callback || function() {};

		// no remote or from cache - just finish with callback
		// TODO in any case: insert cancel running load here..!
		
		if (!url || !bypassCache && jQuery.data(a, 'cache.tabs')) {
			callback();
			return;
		}

		// load remote from here on

		var inner = function(parent) {
			var jQueryparent = jQuery(parent), jQueryinner = jQueryparent.find('*:last');
			return jQueryinner.length && jQueryinner.is(':not(img)') && jQueryinner || jQueryparent;
		};
		var cleanup = function() {
			self.jQuerytabs.filter('.ui-tabs-loading').removeClass('ui-tabs-loading')
					.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 = jQuery.extend({}, o.ajaxOptions, {
			url: url,
			success: function(r, s) {
				jQuery(self._sanitizeSelector(a.hash)).html(r);
				cleanup();

				if (o.cache)
					jQuery.data(a, 'cache.tabs', true); // if loaded once do not load them again

				// callbacks
				self._trigger('load', null, self._ui(self.jQuerytabs[index], self.jQuerypanels[index]));
				try {
					o.ajaxOptions.success(r, s);
				}
				catch (er) {}

				// 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();
		}
		jQuerya.addClass('ui-tabs-loading');
		self.xhr = jQuery.ajax(ajaxOptions);
	},

	url: function(index, url) {
		this.jQuerytabs.eq(index).removeData('cache.tabs').data('load.tabs', url);
	},
	
	length: function() {
		return this.jQuerytabs.length;
	}

});

jQuery.extend(jQuery.ui.tabs, {
	version: '1.6rc6',
	getter: 'length',
	defaults: {
		ajaxOptions: null,
		cache: false,
		cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
		deselectable: false,
		disabled: [],
		event: 'click',
		fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }
		idPrefix: 'ui-tabs-',
		panelTemplate: '<div></div>',
		spinner: 'Loading&#8230;',
		tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>'
	}
});

/*
 * Tabs Extensions
 */

/*
 * Rotate
 */
jQuery.extend(jQuery.ui.tabs.prototype, {
	rotation: null,
	rotate: function(ms, continuing) {

		var self = this, t = this.options.selected;

		function rotate() {
			clearTimeout(self.rotation);
			self.rotation = setTimeout(function() {
				t = ++t < self.jQuerytabs.length ? t : 0;
				self.select(t);
			}, ms);
		}

		// start rotation
		if (ms) {
			this.element.bind('tabsshow', rotate); // will not be attached twice
			this.jQuerytabs.bind(this.options.event + '.tabs', !continuing ?
				function(e) {
					if (e.clientX) { // in case of a true click
						clearTimeout(self.rotation);
						self.element.unbind('tabsshow', rotate);
					}
				} :
				function(e) {
					t = self.options.selected;
					rotate();
				}
			);
			rotate();
		}
		// stop rotation
		else {
			clearTimeout(self.rotation);
			this.element.unbind('tabsshow', rotate);
			this.jQuerytabs.unbind(this.options.event + '.tabs', stop);
		}
	}
});

})(jQuery);
