window.addEvent("domready",function () 
{
	// get the widths of an expanded and contracted element for use later on
		var contracted_width = $("column_width").getStyle("width");
		var expanded_width = $("expanded_column_width").getStyle("width");

	// get tabs
		var tabs = $$("#wrapper_columns div.tab div.menu_item a");

	// javascript cache
		var href2index = [];
		var html = [];


	/******** SCROLLBAR ***********/

		var ScrollBar = new Class({

				Implements: [Events, Options],

				options: {
					maxThumbSize: 10,
					wheel: 8
				},

				initialize: function(content, track, thumb, options){
					this.setOptions(options);

					this.content = $(content);
					this.track = $(track);
					this.thumb = $(thumb);

					this.bound = {
						'start': this.start.bind(this),
						'end': this.end.bind(this),
						'drag': this.drag.bind(this),
						'wheel': this.wheel.bind(this),
						'page': this.page.bind(this)
					};

					this.position = {};
					this.mouse = {};

					if (this.update())
						this.attach();
					else
						this.track.destroy();
				},

				update: function(){

					this.contentSize = this.content.offsetHeight;
					this.contentScrollSize = this.content.scrollHeight;

					if (this.contentScrollSize <= this.contentSize)
						return false;

					this.content.setStyle("overflow", "hidden");
	
					this.trackSize = this.track.offsetHeight;

					this.contentRatio = this.contentSize / this.contentScrollSize;

					this.thumbSize = (this.trackSize * this.contentRatio).limit(this.options.maxThumbSize, this.trackSize);

					this.scrollRatio = this.contentScrollSize / this.trackSize;

					this.thumb.setStyle('height', this.thumbSize);

					this.updateThumbFromContentScroll();
					this.updateContentFromThumbPosition();

					return true;
				},

				updateContentFromThumbPosition: function(){
					this.content.scrollTop = this.position.now * this.scrollRatio;
				},

				updateThumbFromContentScroll: function(){
					this.position.now = (this.content.scrollTop / this.scrollRatio).limit(0, (this.trackSize - this.thumbSize));
					this.thumb.setStyle('top', this.position.now);
				},

				attach: function(){
					this.thumb.addEvent('mousedown', this.bound.start);
					if (this.options.wheel)
					{
						this.content.addEvent('mousewheel', this.bound.wheel);
						this.thumb.addEvent('mousewheel', this.bound.wheel);
					}
					this.track.addEvent('mouseup', this.bound.page);
				},

				wheel: function(event){
					this.content.scrollTop -= event.wheel * this.options.wheel;
					this.updateThumbFromContentScroll();
					event.stop();
				},

				page: function(event){
					if (event.page.y > this.thumb.getPosition().y) this.content.scrollTop += this.content.offsetHeight;
					else this.content.scrollTop -= this.content.offsetHeight;
					this.updateThumbFromContentScroll();
					event.stop();
				},

				start: function(event){
					this.mouse.start = event.page.y;
					this.position.start = this.thumb.getStyle('top').toInt();
					document.addEvent('mousemove', this.bound.drag);
					document.addEvent('mouseup', this.bound.end);
					this.thumb.addEvent('mouseup', this.bound.end);
					event.stop();
				},

				end: function(event){
					document.removeEvent('mousemove', this.bound.drag);
					document.removeEvent('mouseup', this.bound.end);
					this.thumb.removeEvent('mouseup', this.bound.end);
					event.stop();
				},

				drag: function(event){
					this.mouse.now = event.page.y;
					this.position.now = (this.position.start + (this.mouse.now - this.mouse.start)).limit(0, (this.trackSize - this.thumbSize));
					this.updateContentFromThumbPosition();
					this.updateThumbFromContentScroll();
					event.stop();
				}

			});


		function AddScrollbar(obj) 
		{
			if (typeof(obj) == "string" && obj.match(/[\.#]/i))
				obj = $$(obj).pop();
			else
				obj = $(obj);

			// see if there's a track and thumb
				var parent = obj.parentNode;

				var track = $(parent).getElement("div.track");
				var thumb = $(parent).getElement("div.track div.thumb");

				if (!track || !thumb)
				{
					var track = new Element("div", { "class" : "track" } );//, styles : { "height" : "700px" } });
					var thumb = new Element("div", { "class" : "thumb" } );

					thumb.inject(track);
					track.inject(parent);
				}

			var scr = new ScrollBar(obj, track, thumb);

			/*new Drag(obj, {
				'modifiers': {y: 'height', x: false},
				onDrag: function(){
					scr.update();
				}
			});*/

		}


	/******** ANIMATION FUNCTION ********/

		function DoTabAnimation(a) 
		{
			var to_expand = null;
			var to_contract = null;

			$$("#wrapper_columns div.tab").each(function (tab) 
			{
				// if its selected at the moment and isn't the tab we've clicked on contract it
					if (tab.hasClass("expanded_column") && tab.id != a.parentNode.parentNode.id)
						to_contract = tab;

				// if its not selected at the moment but is the tab we've clicked on expand it
					if (!tab.hasClass("expanded_column") && tab.id == a.parentNode.parentNode.id)
						to_expand = tab;
			});


			// create completion function
				var contract_complete = function (obj) {
					obj.removeClass("expanded_column");
					var scroll = obj.getElement("div.track");
					if (scroll) scroll.destroy();
				}

				var expand_complete = function (obj)
				{
					obj.addClass("expanded_column");
					AddScrollbar(obj.getElement("div.page_content"));
				}

			// do transformations
				if (to_contract && contracted_width)
				{
					$(to_contract).getElement("div.page_content").setStyle("overflow", "hidden");

					var fx_contract = new Fx.Morph($(to_contract), {duration: 500, transition: Fx.Transitions.Sine.easeOut, onComplete: contract_complete });
					fx_contract.start({"width" : contracted_width});
				}

				if (to_expand && expanded_width)
				{
					var fx_expand = new Fx.Morph($(to_expand), {duration: 700, transition: Fx.Transitions.Sine.easeOut, onComplete: expand_complete});
					fx_expand.start({"width" : expanded_width});
				}
		
			return false;
		}

		function HidePleaseWait() 
		{
			if ($("please_wait")) $("please_wait").destroy();
			if ($("wrapper_please_wait")) $("wrapper_please_wait").destroy();
		}

		function DoPleaseWait() 
		{
			var wrapper_please_wait = new Element("div", { "id" : "wrapper_please_wait", "opacity" : 0.5});
			var please_wait = new Element("div", { "id" : "please_wait" });

			// amend them a bit
				please_wait.innerHTML = "Loading, please wait...";
				please_wait.addEvent("click", function () {
					HidePleaseWait();
				});
				wrapper_please_wait.addEvent("click", function () {
					HidePleaseWait();
				});

			wrapper_please_wait.inject(document.body);
			please_wait.inject(document.body);

			return false;
		}


	/***** AJAX ******/

		function DoTabAjax(a) 
		{
			var parent = a.parentNode.parentNode;
			var content = parent.getElement("div.page_content");

			var i = href2index[a.href] || 0;

			// if cache use it
				if (html[i] && html[i].length)
				{
					document.title = html[i][0];
					content.innerHTML = html[i][1];

					//AddScrollbar(content);

					HidePleaseWait();

					return;
				}

			//content.innerHTML = '<div id="wrapper_loading"><h4>Loading...</h4><img src="images/loading.gif" width="56" height="21" alt="Loading..." title="Loading..."></div>';			

			// create Ajax Request
				new Request({
					url: a.href,
					method: 'get',
					//data: req,
					onSuccess: function(response_text) {
					
						var bits = response_text.match(/^([^\|]+)\|/i);
						var title = bits[1];

						// browser title
							document.title = title;

						// get rid of first part of response to leave just HTML
							response_text = response_text.replace(bits[0], "");
							content.innerHTML = response_text;

						// cache results
							html[i] = [title, response_text];

						//AddScrollbar(content);

						HidePleaseWait();

					},
					onFailure: function () 
					{
						window.location.href = a;
					},
					onException: function (headerName, value) 
					{
						window.location.href = a;
					}
				}).send("is_ajax=1");
		}



	/***** HISTORY *****/

		HistoryManager.initialize();

		// function to simulate the click
			function DoMoveHistory(a_index) 
			{
				if (!$defined(a_index)) return;

				// updating the history
					reqHistory.setValue(0, a_index);

				DoPleaseWait();

				DoTabAnimation(tabs[a_index]);
				DoTabAjax(tabs[a_index]);
			}

		// function to set up the history
			var reqHistory = HistoryManager.register(
				'pg-hist',						// key
				[],								// defaults - default, page 0 - empty array breaks it

				function(values) {				// onMatch
					DoMoveHistory(values[0]);
				},

				function(values) {				// on Generate
					return 'pg-hist(' + values[0] + ')';
				},

				/pg-hist\((\d+)\)/			// the regexp to match "pg-hist(0)"
			);


	// attach animation to each tab

		// get each menu item
			tabs.each(function (a, i) 
			{
				// create relationship with link address and index
					href2index[a.href] = i;

				// add click event to each menu item
					a.addEvent("click",function () 
					{
						DoMoveHistory(i);

						return false;
					});

				// cache the page content
					var parent = a.parentNode.parentNode;
					if (parent.className.match(/expanded/i))
						html[i] = [document.title, $(parent).getElement("div.page_content").innerHTML];
			});



	// start history
		HistoryManager.start();


	// add scrollbar
		AddScrollbar("div.expanded_column div.page_content");

});

