var bp = "/bots";
addEvent(window, "DOMContentLoaded", init);

function init() {
	standardistaTableSortingInit();
	externalLinks();
	//suggestInit();
	startFloatTitle();
}

function externalLinks() {
	if(!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for(var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if(anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}

function loading(status) {
	if(status) {
		$("container").ancestors()[0].insert(new Element("div", {
			id: "loading"
		}).setStyle({
			position: "absolute",
			backgroundColor: "black",
			color: "red",
			fontSize: "2em",
			padding: "5px 5px 10px 10px",
			borderLeft: "1px solid #808080",
			borderBottom: "1px solid #808080"
		}).insert("Processing..."));
		$("loading").setStyle({
			top: document.viewport.getScrollOffsets().top + "px",
			left: document.viewport.getWidth() - $("loading").getWidth() + "px"
		});
	}
	else $("loading").remove();
}

function Dialog() {

	this.errors = $("error").select("li").size();
	this.warnings = $("warning").select("li").size();
	this.notes = $("note").select("li").size();

	this.addError = function(msg, id) {
		if(this.errors == 0) $("error").insert(new Element("ul"));
		if(!$(id)) {
			this.errors++;
			$("error").select("ul")[0].insert(new Element("li", { id: id }).insert(msg));
		}
		$("error").show();
		$("error").scrollTo();
	}

	this.removeError = function(id) {
		if($(id)) {
			this.errors--;
			$(id).remove();
			if(this.errors == 0) {
				$("error").select("ul")[0].remove();
				$("error").hide();
			}
		}
	}

	this.addWarning = function(msg, id) {
		if(this.warnings == 0) $("warning").insert(new Element("ul"));
		if(!$(id)) {
			this.warnings++;
			$("warning").select("ul")[0].insert(new Element("li", { id: id }).insert(msg));
		}
		$("warning").show();
		$("warning").scrollTo();
	}

	this.removeWarning = function(id) {
		if($(id)) {
			this.warnings--;
			$(id).remove();
			if(this.warnings == 0) {
				$("warning").select("ul")[0].remove();
				$("warning").hide();
			}
		}
	}

	this.addNote = function(msg, id) {
		if(this.notes == 0) $("note").insert(new Element("ul"));
		if(!$(id)) {
			this.notes++;
			$("note").select("ul")[0].insert(new Element("li", { id: id }).insert(msg));
		}
		$("note").show();
		$("note").scrollTo();
	}

	this.removeNote = function(id) {
		if($(id)) {
			this.notes--;
			$(id).remove();
			if(this.notes == 0) {
				$("note").select("ul")[0].remove();
				$("note").hide();
			}
		}
	}

}

var currentQuery = "";
var selectedSuggestion = -1;
var maxSuggestion = -1;

function suggestInit() {
	$("suggest-text").observe("keydown", function(event) {
		//$("foo").insert(event.keyCode);
		switch(event.which || event.keyCode) {
			case Event.KEY_UP:
				if(maxSuggestion != -1 && selectedSuggestion != -1) {
					//alert("selectedSuggestion is " + selectedSuggestion);
					var foo = parseInt(selectedSuggestion);
					suggest.deselect(selectedSuggestion);
					selectedSuggestion = foo - 1;
					if(selectedSuggestion != -1) {
						suggest.select(selectedSuggestion);
					}
				}
				break;
			case Event.KEY_DOWN:
				if(maxSuggestion != -1 && selectedSuggestion != maxSuggestion) {
					//alert("selectedSuggestion is " + selectedSuggestion);
					var foo = parseInt(selectedSuggestion);
					if(selectedSuggestion != -1) {
						suggest.deselect(selectedSuggestion);
					}
					selectedSuggestion = foo+1;
					suggest.select(selectedSuggestion);
				}
				break;
		}
	});

	$("suggest").setStyle({
		top: ($("suggest-text").cumulativeOffset()[1] + 16) + "px"
	});
}

function Suggest() {

	this.search = function(elt) {
		var query = trim($F(elt));
		if(query != currentQuery) {
			currentQuery = query;

			if(currentQuery.length == 0) {
				$("suggest").hide();
				$("search-loading").hide();
				maxSuggestion = -1;
				selectedSuggestion = -1;
			}
			else {
				new Ajax.Request(bp + "/ajax/suggest.php?query=" + currentQuery, {
					method: "get",
					onSuccess: function(transport) {
						var json = transport.responseText.evalJSON();
						if(currentQuery == json.query) {
							if(!json.results) {
								$("suggest").hide();
							}
							else {
								// Remove existing results
								$("suggest").childElements().each(function(child) {
									if(child.tagName != "DIV") {
										child.remove();
									}
								});

								// Prepare highlighting stuff
								var words = new Array();
								words = json.query.split(" ");

								// Add updated results
								var count = 0;
								json.results.each(function(result) {
									// Make the entire box a link
									var link = new Element("a", {
										href: bp + result.url,
										id: "suggestion_" + count++/*,
										onmouseover: "alert('foo');",
										onmouseover: "suggest.select(" + count++ + ")",
										onmouseout: "suggest.deselect(selectedSuggestion)"*/
									}).setStyle({
										color: "white",
										padding: "0px"
									}).observe("mouseover", function(event) {
										//alert(Event.element(event).ancestors()[0].identify());
										var id;
										if(event.element().tagName != "a") {
											//id = event.element().ancestors()[0].identify();
											id = event.element().up("a").identify();
											//$("foo").insert("up'd type is " + event.element().tagName + "<br />");
										}
										else {
											id = event.element().identify();
											//$("foo").insert("type is " + event.element().tagName + "<br />");
										}
										//$("foo").insert("1) found " + id + "<br />");
										var idNumber = id.substring(id.search("_")+1, id.length);
										//$("foo").insert(event.element().ancestors()[0].tagName + "<br />");
										suggest.select(idNumber);
									});

									// Container div for an individual result
									var div = new Element("div").setStyle({
										borderBottom: "1px solid #808080",
										padding: "3px 2px"
									});

									// Icon
									var icon = new Element("img", {
										src: bp + "/images/suggest/" + result.type + ".png",
										width: "16px",
										height: "16px",
										alt: ""
									}).setStyle({
										float: "left",
										clear: "both",
										padding: "4px",
										border: "1px solid #808080",
										backgroundColor: "black",
										margin: "0px 3px 0px 1px"
									});

									// Container div for the 2 lines
									var textDiv = new Element("div").setStyle({
										marginLeft: "30px"
									});

									// Line 1 of 2 - name
									var highlight = new Array();
									var tempName = result.name;
									for(var i=0; i<words.length; i++) {
										//var index = tempName.toLowerCase().search("([ |-](" + words[i].toLowerCase() + "))|(^" + words[i].toLowerCase() + ")");
										var index = tempName.toLowerCase().search("([ |-](" + words[i].toLowerCase() + "))|(^" + words[i].toLowerCase() + ")");
										if(index != -1) {
											// Bump it up a space to avoid space if necessary
											if(index > 0) {
												index++;
											}
											highlight.push(new Array(index, index+words[i].length));
											tempName = replace(tempName, "*", index, index+words[i].length);
										}
									}
									highlight.sort(function(a, b) {
										return a[0] - b[0];
									});
									var name = result.name;
									for(var i=highlight.length-1; i>=0; i--) {
										name = insert(name, '</span>', highlight[i][1]);
										name = insert(name, '<span style="color: yellow; font-weight: bold;">', highlight[i][0]);
									}
									name = name + "<br />";

									//var name = result.name + "<br />";

									// Line 2 of 2 - type
									var typeText;
									switch(result.type) {
										case "weapon":
											typeText = "Weapon";
											break;
										case "body":
											typeText = "Armor - Body";
											break;
										case "body_unique":
											typeText = "Armor - Body (Unique)";
											break;
										case "helmet":
											typeText = "Armor - Helmet";
											break;
										case "helmet_unique":
											typeText = "Armor - Helmet (Unique)";
											break;
										case "gloves":
											typeText = "Armor - Gloves";
											break;
										case "gloves_unique":
											typeText = "Armor - Gloves (Unique)";
											break;
										case "boots":
											typeText = "Armor - Boots";
											break;
										case "boots_unique":
											typeText = "Armor - Boots (Unique)";
											break;
										case "shield":
											typeText = "Shield";
											break;
										case "bot_green":
											typeText = "Bot (Green)";
											break;
										case "bot_blue":
											typeText = "Bot (Blue)";
											break;
									}
									var type = new Element("span").setStyle({
										color: "#808080",
										fontSize: "0.8em"
									}).insert(typeText);

									// Combine it all and add it to page
									link.insert(div.insert(icon).insert(textDiv.insert(name).insert(type)));
									//div.insert(icon).insert(textDiv.insert(name).insert(type));
									$("suggest").insert(link);
								});

								maxSuggestion = count-1;
								selectedSuggestion = -1;

								$("suggest").show();
								//alert($("suggest-text").cumulativeOffset()[1]);
							}
							$("search-loading").hide();
						}
					},
					onCreate: function() {
						$("search-loading").show();
					},
					onComplete: function() {
						//$("search-loading").hide();
					}
				});
			}
		}
	}

	this.select = function(idNumber) {
		var elt = $("suggestion_" + idNumber);
		if(idNumber != selectedSuggestion && selectedSuggestion != -1) {
			//alert("deselecting");
			this.deselect(selectedSuggestion);
		}
		//$("foo").insert("selecting " + idNumber + "<br />");
		elt.setStyle({
			backgroundColor: "#060"
		});
		selectedSuggestion = idNumber;
	}

	this.deselect = function(idNumber) {
		var elt = $("suggestion_" + idNumber);
		//$("foo").insert("deselecting " + idNumber + "<br />");
		elt.setStyle({
			backgroundColor: "#272727"
		});
		selectedSuggestion = -1;
	}

}

// Remove spaces from the end of a string
function trim(s) {
	for(var i=s.length-1; i>=0; i--) {
		if(s.charAt(i) == " ") {
			s = s.substring(0, i);
		}
		else {
			return s;
		}
	}
	return s;
}

// String insert - insertion into s at i
function insert(s, insertion, i) {
	return s.substring(0, i) + insertion + s.substring(i, s.length);
}

// String replace - fill i...j of s with replacement
function replace(s, replacement, i, j) {
	var foo = "";
	for(var k=0; k<j-i; k++) {
		foo += replacement;
	}
	return s.substring(0, i) + foo + s.substring(j, s.length);
}

function Benchmark() {

	this.start = new Date().getTime();

	this.report = function() {
		alert((new Date().getTime() - this.start)/1000 + " seconds");
	};

}
