// JavaScript Document

(function($) {

	$.extend($.ui.tabs.prototype, {
		ID: null,
		slideContainer: null,
		slider: null,
		slideTimer: null,
		minWidth: 200,
		scrollSpeed: 30,
		acceleration: 2,
		useAnimation: true,
		listTimer: null,



		/*Public methods*/
		SlideToTab: function(_index) {
			var sl = $(this.slideContainer).scrollLeft();
			var left = $(this.$tabs[_index])[0].offsetLeft;
			if (left > $(this.slideContainer).width() + sl - $(this.$tabs[_index]).width()) {
				//Move from right
				var _toX = $(this.$tabs[_index]).width() + $(this.$tabs[_index])[0].offsetLeft - $(this.slideContainer).width();
			} else if (left < sl) {
				//move from left
				var mar = parseInt($(this.slideContainer).css("margin-left")) + parseInt($(this.slideContainer).css("padding-left"));
				var _toX = $(this.$tabs[_index])[0].offsetLeft - mar;
			} else return;
			this.slideTo(_toX);
		},

		MoveToNextTab: function() {
			var mar = parseInt($(this.slideContainer).css("margin-left")) + parseInt($(this.slideContainer).css("padding-left"));
			if ($(this.slideContainer).scrollLeft() + $(this.slideContainer).width() >= this.slideContainer.scrollWidth - mar) { return }
			var ind = this.getRightVisibleTab();
			if (ind != -1) {
				var _toX = $(this.$tabs[ind]).width() + $(this.$tabs[ind])[0].offsetLeft - $(this.slideContainer).width() + mar;
				this.slideTo(_toX);
			} else {
				this.turnNextTabButton(false);
			}
			this.turnPrevTabButton(true);
		},

		MoveToPrevTab: function() {
			var mar = parseInt($(this.slideContainer).css("margin-left")) + parseInt($(this.slideContainer).css("padding-left"));
			if ($(this.slideContainer).scrollLeft() <= mar + 2) { return }
			var ind = this.getLeftVisibleTab();
			if (ind != -1) {
				var _toX = $(this.$tabs[ind])[0].offsetLeft - mar;
				this.slideTo(_toX);
			} else {
				this.turnPrevTabButton(false);
			}
			this.turnNextTabButton(true);
		},

		ChangeTab: function(e) {
			var _id = e.data;
			this.SlideToTab(_id);
			var href = $(this.$tabs[_id]).attr("href");
			if (href.indexOf("#") != 0) {
				window.location = href;
			} else {
				this.select(_id);
				this.HideList();
			}
		},

		ShowHideList: function() {
			if ($(this.ListPath).css("display") == "none") this.ShowList();
			else this.HideList();
		},

		HideList: function() {
			$(this.ListPath).hide();
		},

		ShowList: function() {
			$(this.ListPath).show();
		},
		/*-end of public*/

		stopHideList: function() {
			if (this.listTimer != null) clearTimeout(this.listTimer);
		},

		startHideList: function() {
			var t = this;
			this.listTimer = setTimeout(function() { t.HideList() }, 400);
		},

		seek4init: function(_args) {

			_args = eval(_args);
			this.ID = _args.toolbar;
			this._urls = _args.urls;
			this._onClick = _args.onclick;
			this.select(_args.selected);

			this.$tabs = this.anchors;
			this.createDOMObjects();
			this.bindEvents();
			this.resizeContainer();
			this.initWidths();
			this.buildList();
			this.SlideToTab(_args.selected);
		},

		initWidths: function() {
			var w = this.totalWidth();
			$(this.slider).width(w);
		},

		createDOMObjects: function() {
			this.btnNextTabPath = this.ID + " .btn_nextTab";
			this.btnPrevTabPath = this.ID + " .btn_prevTab";
			this.slider = this.element;
			this.slideContainer = this.slider[0].parentNode;
			this.btnShowListPath = this.ID + " .btn_showList";
			this.ListPath = this.ID + " .list";
			this.Container = this.slideContainer.parentNode;
			this.RemoveIconsPath = "#" + this.element[0].id + " .icn_remove";
		},

		bindEvents: function() {
			var self = this;
			this.element.bind("tabsselect", function(e, ui) {
				if (self._urls[ui.index] != null) { window.location = self._urls[ui.index]; return false; }
				if (self._onClick != null) self._onClick(e, ui);
			});

			$(this.btnNextTabPath).bind("click", function() { self.MoveToNextTab() });
			$(this.btnPrevTabPath).bind("click", function() { self.MoveToPrevTab() });
			$(this.btnShowListPath).bind("click", function() { self.ShowHideList() });
			$(this.ListPath).bind("mouseover", function() { self.stopHideList() });
			$(this.ListPath).bind("mouseout", function() { self.startHideList() });

			$(window).bind("resize", function() { self.resizeContainer() });
			var l = this.$tabs.length;
			for (var i = 0; i < l; i++) {
				//alert($(this.anchors[i]).attr("href")+":"+$(this.$tabs[i]).attr("href").indexOf("#"));
				if ($(this.$tabs[i]).attr("href").indexOf("#") == 0 || $(this.$tabs[i]).attr("href") == "javascript:") {
					$(this.$tabs[i]).bind('click', i, function(e) { self.tabSelectClick(e) });
				} else { $(this.$tabs[i]).unbind('click'); }
				$(this.$tabs[i]).bind('mouseover', i, function(e) { self.tabMouseOver(e) });
			}
			$(this.RemoveIconsPath).bind("click", function(e) { self.OnRemoveClick(e) });

		},

		OnRemoveClick: function(e) {
			var _tab = $(e.target).parent("span").parent("a");
			var _index = this.$tabs.index(_tab);
			var _data = { tab: _tab, selectedIndex: _index };
			var r = this.element.triggerHandler("onremoveclick", [e, this.PrepareRemoveEvent(_data)], e.stopPropagation());
			if (!r) return;
			this.remove(_index);
		},

		PrepareRemoveEvent: function(e) {
			return e;
		},

		resizeContainer: function() {
			var padd = 0
			var padd = parseInt($(this.Container).css("padding-left")) + parseInt($(this.Container).css("padding-right"));
			var margin = 0
			var margin = parseInt($(this.Container).css("margin-left")) + parseInt($(this.Container).css("margin-right"));
			var border = 0;
			if (typeof ($(this.ID).css("border-left-width")) == "Number" && typeof ($(this.ID).css("border-left-width")) == "Number") {
				border = parseInt($(this.ID).css("border-left-width")) + parseInt($(this.ID).css("border-left-width"));
			}
			//    alert($(this.Container).outerWidth() - $(this.ID).outerWidth());
			$(this.slideContainer).width($(this.Container).outerWidth() - $(this.ID).outerWidth() - 10);
		},

		tabSelectClick: function(e) {
			var _tab = $(e.target).parent("span").parent("a");
			var _i = this.$tabs.index(_tab);
			var i = e.data;
			if (_i == i) {
				//if(this._urls[i] == null) window.location.reload(true);
				//else
				if (this._urls[i] != null) window.location = this._urls[i];
			}
			this.SlideToTab(e.data);
		},

		tabMouseOver: function(e) {
			var i = e.data;
			if (this._urls[i] != null) window.status = this._urls[i];
		},

		slideTo: function(_toX) {
			if (this.useAnimation) {
				var sl = this.slideContainer.scrollLeft;
				if (Math.abs(sl - _toX) < 2) { return }   //4 - approximate for tab position: TODO - move ta parameters
				var newSl = sl + (_toX - sl) / this.acceleration;
				this.slideContainer.scrollLeft = newSl;
				var t = this;
				if (this.slideTimer != null) clearTimeout(this.slideTimer);
				this.slideTimer = setTimeout(function(e) { t.slideTo(_toX) }, this.scrollSpeed);
			} else {
				this.slideContainer.scrollLeft = _toX;
			}
		},

		turnNextTabButton: function(_on) {

		},

		turnPrevTabButton: function(_on) {

		},

		totalWidth: function() {
			var l = this.$tabs.length; var tw = 0;
			for (var i = 0; i < l; i++) {
				tw += $(this.$tabs[i]).outerWidth() + 20;
			}

			return tw;
		},

		getLeftVisibleTab: function() {
			var l = this.$tabs.length;
			var s = "";
			var sl = $(this.slideContainer).scrollLeft();
			for (var i = 0; i < l; i++) {
				var tab = this.$tabs[i];
				var w = $(tab).width();
				var left = $(tab)[0].offsetLeft;
				if (sl - 10 > left && sl - 10 < left + w) {
					//alert($(tab).text());
					return i;
				}
			}
			return -1;
		},

		getRightVisibleTab: function() {
			var l = this.$tabs.length;
			var s = "";
			var mar = parseInt($(this.slideContainer).css("margin-left")) + parseInt($(this.slideContainer).css("padding-left"));
			var sl = $(this.slideContainer).scrollLeft() + $(this.slideContainer).width() + mar;
			for (var i = 0; i < l; i++) {
				var tab = this.$tabs[i];
				var w = $(tab).width();
				var left = $(tab)[0].offsetLeft;
				if (sl + 10 > left && sl + 10 < left + w) {
					return i;
				}
			}
			return -1;
		},

		buildList: function() {
			var l = this.$tabs.length;
			var t = this;
			for (var i = 0; i < l; i++) {
				$(this.$tabs[i]).css("z-index", 140 - i);
				var path = "listitem_" + i;
				var label = $(this.$tabs[i]).children(".middle").children(".label").text();
				var _html = "<li class='" + path + "'><a href='javascript:'>" + label + "</a></li>";
				$(this.ListPath).append(_html);
				var fp = this.ListPath + " ." + path;
				$(fp).bind("click", i, function(e) { t.ChangeTab(e) });
			}
		},

		_tabify: function(init) {

			this.list = this.element.children('ul:first');
			this.lis = $('li:has(a[href])', this.list);
			this.anchors = this.lis.map(function() { return $('a', this)[0]; });
			this.panels = $([]);
			var self = this, o = this.options;

			var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash
			this.anchors.each(function(i, a) {
				var href = $(a).attr('href');
				if ($(a).attr('inlineTabs') == 'true') {
					// For dynamically created HTML that contains a hash as href IE < 8 expands
					// such href to the full page url with hash and then misinterprets tab as ajax.
					// Same consideration applies for an added tab with a fragment identifier
					// since a[href=#fragment-identifier] does unexpectedly not match.
					// Thus normalize href attribute...
					var hrefBase = href.split('#')[0], baseEl;
					if (hrefBase && (hrefBase === location.toString().split('#')[0] ||
					(baseEl = $('base')[0]) && hrefBase === baseEl.href)) {
						href = a.hash;
						a.href = href;
					}

					// inline tab
					if (fragmentId.test(href)) {
						self.panels = self.panels.add(self._sanitizeSelector(href));
					}


					// remote tab
					else if (href != '#') { // prevent loading the page itself if href is just "#"
						$.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)
						$.data(a, 'load.tabs', href.replace(/#.*$/, '')); // mutable data

						var id = self._tabId(a);
						a.href = '#' + id;
						var $panel = $('#' + id);
						if (!$panel.length) {
							$panel = $(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom')
						.insertAfter(self.panels[i - 1] || self.list);
							$panel.data('destroy.tabs', true);
						}
						self.panels = self.panels.add($panel);
					}

					// invalid tab href
					else {
						o.disabled.push(i);
					}
				}
			});

			// initialization from scratch
			if (init) {

				// attach necessary classes for styling
				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.lis.addClass('ui-state-default ui-corner-top');
				this.panels.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.anchors.each(function(i, a) {
							if (a.hash == location.hash) {
								o.selected = i;
								return false; // break
							}
						});
					}
					if (typeof o.selected != 'number' && o.cookie) {
						o.selected = parseInt(self._cookie(), 10);
					}
					if (typeof o.selected != 'number' && this.lis.filter('.ui-tabs-selected').length) {
						o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
					}
					o.selected = o.selected || 0;
				}
				else if (o.selected === null) { // usage of null is deprecated, TODO remove in next release
					o.selected = -1;
				}

				// sanity check - default to first tab...
				o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0;

				// Take disabling tabs via class attribute from HTML
				// into account and update option properly.
				// A selected tab cannot become disabled.
				o.disabled = $.unique(o.disabled.concat(
				$.map(this.lis.filter('.ui-state-disabled'),
					function(n, i) { return self.lis.index(n); })
			)).sort();

				if ($.inArray(o.selected, o.disabled) != -1) {
					o.disabled.splice($.inArray(o.selected, o.disabled), 1);
				}

				// highlight selected tab
				this.panels.addClass('ui-tabs-hide');
				this.lis.removeClass('ui-tabs-selected ui-state-active');
				if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list
					this.panels.eq(o.selected).removeClass('ui-tabs-hide');
					this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active');

					// seems to be expected behavior that the show callback is fired
					self.element.queue("tabs", function() {
						self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected]));
					});

					this.load(o.selected);
				}

				// clean up to avoid memory leaks in certain versions of IE 6
				$(window).bind('unload', function() {
					self.lis.add(self.anchors).unbind('.tabs');
					self.lis = self.anchors = self.panels = null;
				});

			}
			// update selected after add/remove
			else {
				o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
			}

			// update collapsible
			this.element[o.collapsible ? 'addClass' : 'removeClass']('ui-tabs-collapsible');

			// 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.lis[i]); i++) {
				$(li)[$.inArray(i, o.disabled) != -1 &&
				!$(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled');
			}

			// reset cache if switching from cached to not cached
			if (o.cache === false) {
				this.anchors.removeData('cache.tabs');
			}

			// remove all handlers before, tabify may run on existing tabs after add or option change
			this.lis.add(this.anchors).unbind('.tabs');

			if (o.event != 'mouseover') {
				var addState = function(state, el) {
					if (el.is(':not(.ui-state-disabled)')) {
						el.addClass('ui-state-' + state);
					}
				};
				var removeState = function(state, el) {
					el.removeClass('ui-state-' + state);
				};
				this.lis.bind('mouseover.tabs', function() {
					addState('hover', $(this));
				});
				this.lis.bind('mouseout.tabs', function() {
					removeState('hover', $(this));
				});
				this.anchors.bind('focus.tabs', function() {
					addState('focus', $(this).closest('li'));
				});
				this.anchors.bind('blur.tabs', function() {
					removeState('focus', $(this).closest('li'));
				});
			}

			// set up animations
			var hideFx, showFx;
			if (o.fx) {
				if ($.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($el, fx) {
				$el.css({ display: '' });
				if ($.browser.msie && fx.opacity) {
					$el[0].style.removeAttribute('filter');
				}
			}

			// Show a tab...
			var showTab = showFx ?
			function(clicked, $show) {
				$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
				$show.hide().removeClass('ui-tabs-hide') // avoid flicker that way
					.animate(showFx, showFx.duration || 'normal', function() {
						resetStyle($show, showFx);
						self._trigger('show', null, self._ui(clicked, $show[0]));
					});
			} :
			function(clicked, $show) {
				$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
				$show.removeClass('ui-tabs-hide');
				self._trigger('show', null, self._ui(clicked, $show[0]));
			};

			// Hide a tab, $show is optional...
			var hideTab = hideFx ?
			function(clicked, $hide) {
				$hide.animate(hideFx, hideFx.duration || 'normal', function() {
					self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
					$hide.addClass('ui-tabs-hide');
					resetStyle($hide, hideFx);
					self.element.dequeue("tabs");
				});
			} :
			function(clicked, $hide, $show) {
				self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
				$hide.addClass('ui-tabs-hide');
				self.element.dequeue("tabs");
			};

			// attach tab event handler, unbind to avoid duplicates from former tabifying...
			this.anchors.bind(o.event + '.tabs', function() {
				var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.ui-tabs-hide)'),
					$show = $(self._sanitizeSelector(this.hash));
				// If tab is already selected and not collapsible 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 (($li.hasClass('ui-tabs-selected') && !o.collapsible) ||
				$li.hasClass('ui-state-disabled') ||
				$li.hasClass('ui-state-processing') ||
				self._trigger('select', null, self._ui(this, $show[0])) === false) {
					this.blur();
					return false;
				}

				o.selected = self.anchors.index(this);

				self.abort();

				// if tab may be closed
				if (o.collapsible) {
					if ($li.hasClass('ui-tabs-selected')) {
						o.selected = -1;

						if (o.cookie) {
							self._cookie(o.selected, o.cookie);
						}

						self.element.queue("tabs", function() {
							hideTab(el, $hide);
						}).dequeue("tabs");

						this.blur();
						return false;
					}
					else if (!$hide.length) {
						if (o.cookie) {
							self._cookie(o.selected, o.cookie);
						}

						self.element.queue("tabs", function() {
							showTab(el, $show);
						});

						self.load(self.anchors.index(this)); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171

						this.blur();
						return false;
					}
				}

				if (o.cookie) {
					self._cookie(o.selected, o.cookie);
				}

				// show new tab
				if ($show.length) {
					if ($hide.length) {
						self.element.queue("tabs", function() {
							hideTab(el, $hide);
						});
					}
					self.element.queue("tabs", function() {
						showTab(el, $show);
					});

					self.load(self.anchors.index(this));
				}
				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 ($.browser.msie) {
					this.blur();
				}

			});

			// disable click in any case
			this.anchors.bind('click.tabs', function() { return false; });

		}

	});
})(jQuery);