/*=====================================================

======================================================*/

Zeddic = new (function() {

	this.CurrentArea = "";
	this.SelectedElement = "";
	this.TimerId = 0;
	this.OverNavItem = false;
	this.Init = function() {

		this.Setup();
	}

	this.HoverTitle = function(area) {
	}

	//this.ClearSpaces = function(data)
	//{
	//	return data.replace(/ /g,"+");
	//}

	this.Setup = function() {
		Event.observe(window,'load', Zeddic.SetupOnLoad);
	}

	this.SetupOnLoad = function() {
		Zeddic.SetupNavLinks();
		Zeddic.SetupTooltips();
		Zeddic.SetupSortTables();
		//DKP.SetupButtons();
		//DKP.SetupSimpleTables();
	}

	this.SetupNavLinks = function() {
		var links = $$('a.barlink');
		for ( var i = 0 ; i < links.size() ; i++ ) {
			var element = links[i];
			Event.observe(element,'mouseover', Zeddic.NavOver );
			//Event.observe(element,'mousemove', Zeddic.NavMove);
			Event.observe(element,'mouseout', Zeddic.NavOut);
		}

		var selected = $$('#bar_holder .selected');
		if(selected.size() > 0 ) {
			Zeddic.SelectedElement = selected[0];
		}
	}

	this.NavOver = function(event) {
		Zeddic.OverNavItem = true;
		var element = event.element();
		if (element.getAttribute("area") != null) {
			var area = element.getAttribute("area");

			if(Zeddic.CurrentArea == "" )
				Zeddic.CurrentArea = $("bar_under").className;

			$("bar_under").className = "bar_under_"+area;



		}
		if(	Zeddic.SelectedElement != "" ) {
			Zeddic.SelectedElement.removeClassName("selected");
		}

	}

	/*this.NavMove = function(event) {

	}*/

	this.NavOut = function(event) {
		Zeddic.OverNavItem = false;

		if(	Zeddic.SelectedElement != "" ) {
			clearTimeout(Zeddic.TimerId);
			Zeddic.TimerId = setTimeout(function(){
				if(!Zeddic.OverNavItem) {
					Zeddic.SelectedElement.addClassName("selected");
					$("bar_under").className = Zeddic.CurrentArea;
				}
			}, 500);

		}
	}

	this.SetupTooltips = function() {
		var links = $$('a.tooltip');
		for ( var i = 0 ; i < links.size() ; i++ ) {
			Zeddic.SetupTooltip(links[i]);
		}
	}

	this.SetupTooltip = function(element) {
		Event.observe(element,'mouseover', Zeddic.TooltipOver );
		Event.observe(element,'mousemove', Zeddic.TooltipMove);
		Event.observe(element,'mouseout', Zeddic.TooltipOut);
	}


	this.TooltipOver = function(event) {
		var element = event.element();
		if (element.getAttribute("tooltip") != null) {
			var tooltip = element.getAttribute("tooltip");
			var icon = '';
			if(element.getAttribute("icon") != null) {
				icon = element.getAttribute("icon");
				$WowheadPower.showTooltip(event, tooltip, icon);
			}
			else {
				$WowheadPower.showTooltip(event, tooltip);
			}
		}
	}

	this.TooltipOut = function(event) {
		$WowheadPower.hideTooltip(event);
	}

	this.TooltipMove = function(event) {
		$WowheadPower.moveTooltip(event);
	}

	this.ButtonOver = function(event) {
		//var element = event.element();
		this.addClassName("dkpbuttonover");
	}

	this.ButtonOut = function(event) {
		//var element = event.element();
		this.removeClassName("dkpbuttonover");
	}

	this.SetupButtons = function() {
		var links = $$('a.dkpbutton');
		for ( var i = 0 ; i < links.size() ; i++ ) {
			Event.observe(links[i],'mouseover', Zeddic.ButtonOver);
			Event.observe(links[i],'mouseout', Zeddic.ButtonOut);
		}
	}

	this.SetupSortTables = function() {
		var tables = $$('table.sorttable');
		for ( var i = 0 ; i < tables.size() ; i++ ) {
			table = new SortTable(tables[i].id);
			table.Draw();
		}
	}
})();


var SortTable = Class.create({

	initialize: function(name) {
		this.tableName = name;
		this.table = $(name);
		this.tableBody = this.table.getElementsByTagName("tbody")[0];
		this.tableHead = this.table.getElementsByTagName("thead")[0];
		this.items = [];
		this.sortTypes = [];
		this.sortedCol = -1;
		this.sortedReverseCol = -1;
		this.activeSortedCol = 0;
		this.headersHooked = false;
		this.rowObjects = [];
	},

	Add: function(item) {
		this.items.push(item);
	},

	Draw: function() {
		this.HookHeaders();
		for ( var i = 0 ; i < this.tableBody.rows.length ; i++ ) {
			var row = this.tableBody.rows[i];
			this.rowObjects[i] = row;
			Event.observe(row,'mouseover', this.OnRowOver);
			Event.observe(row,'mouseout', this.OnRowOut);
		}
	},

	DrawAdvanced: function() {
		Event.observe(window,'load', this.DrawOnLoad.bindAsEventListener(this));
	},

	Redraw: function() {
		this.Sort(this.activeSortedCol,true);
	},

	Clear: function() {
		//clear all rows other than the first row and the last row
		for ( var i = 0 ; i < this.tableBody.rows.length ; i++ ) {
			if( this.tableBody.rows[i] != this.firstRow && this.tableBody.rows[i]!=this.lastRow ) {
				this.tableBody.removeChild(this.tableBody.rows[i]);
				i--;
			}
		}
	},

	Erase: function() {
		this.Clear();
		this.items = [];
		this.sortedCol = -1;
		this.sortedReverseCol = -1;
		this.activeSortedCol = 0;
		this.rowObjects = [];
	},

	DrawOnLoad: function() {

		this.HookHeaders();

		for(var i = 0 ; i < this.items.length; i++ ) {
			row = this.GetRow(i);
			if(!row)
				continue;
			this.rowObjects[i] = row;
			this.tableBody.appendChild(row);
		}
	},

	OnHeaderClick: function(event) {
		var data = $A(arguments);
		data.shift();

		var col = data[0];

		this.Sort(col);
		var z = 5;
	},

	HookHeaders: function(){
		if(this.headersHooked)
			return;

		this.headersHooked = true;

		var row = this.tableHead.rows[0];
		for(var i = 0 ; i < row.cells.length ; i++ ) {
			if(!Element.hasClassName(row.cells[i],"nosort")) {

				var sortby = this.SortAlpha;
				if (row.cells[i].getAttribute("sort") != null) {
			    	var sortName =  row.cells[i].getAttribute("sort");
			    	sortby = this.GetSortFunc(sortName);
			    }
			    this.sortTypes[i] = sortby;

				row.cells[i].onselectstart = function() {
			        return false;
			    };
			    row.cells[i].unselectable = "on";
			    row.cells[i].style.MozUserSelect = "none";
			    row.cells[i].style.cursor = "default";

				Event.observe(row.cells[i],'click', this.OnHeaderClick.bindAsEventListener(this,i));
			}
		}
	},



	OnRowOver: function(event) {
		this.addClassName("over");
	},

	OnRowOut: function(event) {
		this.removeClassName("over");
	},

	GetRow: function(i) {
		//var url = Site.SiteRoot + "dkp/" + this.items[i].name;

		var row = Builder.node('tr');
		row.appendChild(Builder.node('td',{},"..."));
		row.appendChild(Builder.node('td',{className:"center"},"..."));

		Event.observe(row,'mouseover', this.OnRowOver);
		Event.observe(row,'mouseout', this.OnRowOut);
		//Event.observe(row,'click', this.OnRowClick.bindAsEventListener(this, url));

		return row;
	},

	AddUpChar: function(col) {
		var char = Prototype.Browser.IE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
		this.AddCharToCol(col,char);
	},

	AddDownChar: function(col) {
		var char = Prototype.Browser.IE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
		this.AddCharToCol(col,char);
	},

	AddCharToCol: function(col, char) {

		this.RemoveCharFromCol(col);

		var toadd = Builder.node('span',{id:'sortchar_'+this.tableName});
		toadd.innerHTML = char;

		var cell = this.tableHead.rows[0].cells[col];
		var el = cell.firstChild;

		el.appendChild(toadd);

	},

	RemoveCharFromCol: function(col) {

		var cell = this.tableHead.rows[0].cells[col];
		var toDelete = document.getElementById('sortchar_'+this.tableName);
		if(toDelete) {
			toDelete.parentNode.removeChild(toDelete);
		}
	},

	Sort: function(col) {

		if(this.sortedCol == col )
			return this.SortReverse(col);

		this.AddDownChar(col);

		this.sortedCol = col;
		row_array = [];

        rows = this.rowObjects;
        for (var i=0; i<rows.length; i++) {
			row_array[row_array.length] = [this.GetInnerText(rows[i].cells[col]), rows[i]];
        }

        var sortFunc = this.sortTypes[col];

		//this.shaker_sort(row_array, sortFunc);
        row_array.sort(sortFunc);

		this.Clear();
		for ( var i = 0 ; i < row_array.length ; i++ ) {
			this.tableBody.appendChild(row_array[i][1]);
		}

        delete row_array;
	},

	SortReverse: function(col) {

		this.AddUpChar(col);

		this.sortedReverseCol = col;
		this.sortedCol = -1;

		row_array = [];
        rows = this.rowObjects;
        for (var i=0; i<rows.length; i++) {
          	row_array[row_array.length] = [this.GetInnerText(rows[i].cells[col]), rows[i]];
        }

        var sortFunc = this.sortTypes[col];

		//this.shaker_sort(row_array, sortFunc);
		row_array.sort(sortFunc);

		this.Clear();
		for ( var i = row_array.length-1 ; i >=0  ; i-- ) {
			this.tableBody.appendChild(row_array[i][1]);
		}

        delete row_array;

	},


	shaker_sort: function(list, comp_func) {
		// A stable sort function to allow multi-level sorting of data
		// see: http://en.wikipedia.org/wiki/Cocktail_sort
		// thanks to Joseph Nahmias
		var b = 0;
		var t = list.length - 1;
		var swap = true;

		while(swap) {
		    swap = false;
		    for(var i = b; i < t; ++i) {
		        if ( comp_func(list[i], list[i+1]) > 0 ) {
		            var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
		            swap = true;
		        }
		    } // for
		    t--;

		    if (!swap) break;

		    for(var i = t; i > b; --i) {
		        if ( comp_func(list[i], list[i-1]) < 0 ) {
		            var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
		            swap = true;
		        }
		    } // for
		    b++;

		} // while(swap)
	},

	GetCellValue: function(row, col) {

	},

	GetSortFunc: function(name) {
		switch(name)
		{
			case "number":
				return this.SortNumber;
			case "string":
				return this.SortAlpha;
		}
		return this.SortAlpha;
	},

	SortAlpha: function(a,b) {
		if (a[0]==b[0]) return 0;
		if (a[0]<b[0]) return -1;
		return 1;
	},

	SortNumber: function(a,b) {
		aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
	    if (isNaN(aa)) aa = 0;
	    bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
	    if (isNaN(bb)) bb = 0;
	    return aa-bb;
	},

	GetInnerText: function(node) {
	    // gets the text we want to use for sorting for a cell.
	    // strips leading and trailing whitespace.
	    // this is *not* a generic getInnerText function; it's special to sorttable.
	    // for example, you can override the cell text with a customkey attribute.
	    // it also gets .value for <input> fields.

	    hasInputs = (typeof node.getElementsByTagName == 'function') &&
	                 node.getElementsByTagName('input').length;

	    if (node.getAttribute("sortkey") != null) {
	      return node.getAttribute("sortkey");
	    }
	    else if (typeof node.textContent != 'undefined' && !hasInputs) {
	      return node.textContent.replace(/^\s+|\s+$/g, '');
	    }
	    else if (typeof node.innerText != 'undefined' && !hasInputs) {
	      return node.innerText.replace(/^\s+|\s+$/g, '');
	    }
	    else if (typeof node.text != 'undefined' && !hasInputs) {
	      return node.text.replace(/^\s+|\s+$/g, '');
	    }
	    else {
	      switch (node.nodeType) {
	        case 3:
	          if (node.nodeName.toLowerCase() == 'input') {
	            return node.value.replace(/^\s+|\s+$/g, '');
	          }
	        case 4:
	          return node.nodeValue.replace(/^\s+|\s+$/g, '');
	          break;
	        case 1:
	        case 11:
	          var innerText = '';
	          for (var i = 0; i < node.childNodes.length; i++) {
	            innerText += sorttable.getInnerText(node.childNodes[i]);
	          }
	          return innerText.replace(/^\s+|\s+$/g, '');
	          break;
	        default:
	          return '';
	      }
	    }
	  }

});


Zeddic.Init();