var categories=Array('hammer','compile','vbsp','vvis','vrad','ingame','steam','max_map', 'reference','search');
function show_category(oWhich)
{
	getid('cat_none').style.display='none';
	var which=oWhich;
	if (which != 'search')
	{
		getid("cat_href").href="errors/"+which;
		if (which != 'search') startSearchResult();
	}
	if (which == 'compile') which += '.vbsp.vvis.vrad';
	else if (which == 'vrad' || which == 'vbsp' || which == 'vvis') which += '.compile';
	for (x in errors)
	{
		var element = getid('error_'+x);
		if (!element) continue;
		element.style.display = ( which.indexOf( element.attributes.getNamedItem('category').value ) == -1 ? 'none' : '' );
	}
	for(x in categories)
	{
		getid('button_'+categories[x]).className  = ( categories[x]==oWhich ? 'selectedLi' : 'unselectedLi');
		getid('cat_'+categories[x]).style.display = ( categories[x]==oWhich ? '' : 'none');
	}
}
function mainsearch(query)
{
	startSearchResult();
	if(query.length==0)
	{
		finishSearchResult();
		return;
	}
	var output='';
	query=query.toLowerCase().replace("\r\n"," ");
	//special for the log finder
	if (getid('islog').checked)
	{
		var t = new Array("vbsp","vvis","vrad");
		for (var x in t)
		{
			var c = substr_count(query, "valve software - "+t[x]);
			if (c==0) output+="<p><b>Note: It appears "+t[x]+" was not included in this compile log.</b><br /> Not running "+t[x]+" may cause various errors, make sure you run all compile tools if you are stuck on an unnamed error.</p>";
			else if (c>1) output+="<p><b>Warning: "+t[x]+" was included more than once in this compile log.</b><br />For more accurate problem solving, only post your latest compile output.</p>";
		}
		var mapname=query.match(/loading[\s\S]*?\\([^\\]+)\.vmf\s+fixing\s+up\s+env_cubemap\s+materials/im);
		if (mapname!=null && mapname[1].match(" "))
			output+="<p><b>Error: space detected in mapname '"+mapname[1]+'.vmf" mapnames can\'t have spaces in them.</b><br />Recommended to rename map to e.g. \''+mapname[1].replace(" ","_")+"' or '"+mapname[1].replace(" ","")+"'</p><p class=\"noSearch\"><br /><span class=\"e_type e_lvl4\">This error will cause your map to fail compiling correctly</span></p>";
		if (output != '')
		{
			//write it!
			getid("error_info").innerHTML="<h3>General information</h3>"+output+'<p class="post-info">Last contribution: <a href="forum/memberlist.php?mode=viewprofile&amp;u=0">Anonymous</a></p>';
			var theDiv = getid("error_info").cloneNode(true);
			theDiv.style.display='';
			getid('search_startlist').parentNode.appendChild(theDiv);
		}
		for (var x in errors)
		{
			if (getid('islog').checked && !errors[x][0]) continue;
			var match = query.match(errors[x][1]);
			if (match != null) addSearchResult( x, true, match, query.indexOf(match));
		}
		finishSearchResult();
		return;
	}
	if (query.length>10)
	{
		for (var x in errors)
		{
			var match = query.match(errors[x][1]);
			if (match != null)
			{
				addSearchResult( x, true, match);
			}
		}
	}
	if (searchResults.length == 0)
	{
		for (var x in errors)
		{
			searchNodeForWhole(x, query);
		}
	}
	if (searchResults.length == 0)
	{
		for (var y in errors)
		{
			searchNode(y, query);
		}
	}
	finishSearchResult();
}
window.onload=function()
{
	var url=location.href;
	for(var x in categories)
	{
		if (url.indexOf(categories[x]) != -1)
		{
			show_category(categories[x]);
			return;
		}
	}
	var str='';
	if (url.search(/show=[^&]+/)!=-1) {
		str = unescape(url.match(/show=[^&]+/).toString().substr(5));
		var a = str.split(',');
		var results='';
		var link=Array();
		for(var x in a)
		{
			if (typeof(errors[a[x]])=='undefined') continue;
			addSearchResult(a[x]);
		}
		finishSearchResult();
		return;
	}
	if (url.search(/q=[^&]+/)!=-1) {
		str = unescape(url.match(/q=[^&]+/).toString().substr(2));
		getid('islog').checked=false;
		getid('log').value=str;
		mainsearch(str);
		return;
	}
	show_category('compile');
}
function searchNode(id, item)
{
	var theDiv = getid('error_'+id).cloneNode(true);
	theDiv.id = "search_"+id;
	theDiv.style.display='';
	var found=0;
	item = item.replace('"','&quot;');
	item = item.replace('"','&amp;');
	item = item.replace('>','&qt;');
	item = item.replace('<','&lt;');
	var items = item.split(' ');
	var done = '';
	for (var x in items)
	{
		if (done.indexOf(items[x])!=-1) return;
		done+=items[x]+' ';
		var reg = new RegExp(items[x].replace(' ','\\s+')+'(?=[^>]*(<|\$))','ig');
		cwd = theDiv.firstChild;
		while(cwd.nextSibling)
		{
			if ((cwd.nodeName == 'P' || cwd.nodeName=='H4') && cwd.className != 'noSearch')
			{
				var text = cwd.innerHTML;
				var newText = text.replace(reg,  '<span class="hilite">'+items[x]+'</span>');
				if (text != newText)
				{
					found += substr_count(newText,'<span class="hilite">');
					cwd.innerHTML = newText;
				}
			}
			if (cwd.nodeName=='H4') found*=5; //for sorting purposes
			cwd = cwd.nextSibling;
		}
	}
	if (found>0) searchResults[id]=Array(found, theDiv);
}

function searchNodeForWhole(id, item)
{
	item = item.replace('"','&quot;');
	item = item.replace('"','&amp;');
	item = item.replace('>','&qt;');
	item = item.replace('<','&lt;');
	var reg = new RegExp(item.replace(' ','\\s+')+'(?=[^>]*(<|\$))','ig');
	var theDiv = getid('error_'+id).cloneNode(true);
	theDiv.id = "search_"+id;
	theDiv.style.display='';
	var cwd = theDiv.firstChild;
	var found=0;
	while(cwd.nextSibling)
	{
		if ((cwd.nodeName == 'P' || cwd.nodeName=='H4') && cwd.className != 'noSearch')
		{
			var text = cwd.innerHTML;
			var newText = text.replace(reg,  '<span class="hilite">'+item+'</span>');
			if (text != newText)
			{
				found += substr_count(newText,'<span class="hilite">');
				cwd.innerHTML = newText;
			}
		}
		if (cwd.nodeName=='H4') found*=5; //for sorting purposes
		cwd = cwd.nextSibling;
	}
	if (found>0) searchResults[id]=Array(found, theDiv);
}

var searchResults=Array();
function startSearchResult()
{
	getid('button_search').innerHTML='Search results ( 0 )';
	searchResults=Array();
	var div = getid('search_startlist');
	var p = div.parentNode;
	while (p.lastChild != div)
	{
		p.removeChild(p.lastChild);
	}
}
function addSearchResult(id, parseTitle, title, sorting)
{
	var theDiv = getid('error_'+id).cloneNode(true);
	theDiv.id = "search_"+id;
	theDiv.style.display='';
	var origTitle = theDiv.childNodes[1].innerHTML; //+1
	if (title == undefined) title = Array(origTitle);
	else if (parseTitle)
	{
		var divContents = theDiv.childNodes[3];//+2
		divContents.innerHTML = parse(divContents.innerHTML, id, title, origTitle);
		theDiv.childNodes[1].innerHTML =title[0];
	}
	searchResults[id]=Array(sorting || title[0], theDiv);
}
function finishSearchResult()
{
	var c=0;
	var s='';
	for (var x in searchResults)
	{
		s+= ','+x;
		c++;
	}
	searchResults.sort(sort_results);
	var p = getid('search_startlist').parentNode;
	for(var x in searchResults)
	{
		p.appendChild(searchResults[x][1]);
	}
	show_category('search');
	getid('button_search').innerHTML='Search results ( '+c+' )';
	getid('cat_href').href = 'http://www.interlopers.net/errors/show=' + s.substr(1);
}
function showerror(id)
{
	var doc = window.open('','Viewerror','height=600,width=700,status=yes,menubar=no,scrollbars=yes,resizable=yes,location=no');
	doc.document.write('<html><head><title>Interlopers.net - News &amp; Design Resource - Half-Life 2 Tutorials</title><base href="http://www.interlopers.net" /><link rel="stylesheet" type="text/css" media="screen" title="Site Styles" href="css/screen_v41.css"/><script type="text/javascript">\nfunction showerror(id) { window.opener.showerror(id);}</scr');
	doc.document.write('ipt></head><body><style type="text/css">body,html{height:100%;}\n#Etop_bar{background:#000;padding:8px 5px;font-size:1.1em;color:#fff;color:#e4e2e3;}\n#Ebanner{background:url(images/errorpage/banner2.jpg) no-repeat top left;display: block;height:126px;width:650px;border-bottom:1px solid #000;}');
	doc.document.write('\n#Ewrap{background-color:#fff;width:650px;margin:0 auto;height:auto !important;min-height:100%;height:100%;text-align:left;border-left:1px solid #000;border-right:1px solid #000;}</style><div id="Ewrap"><div id="Etop_bar">View error</div><div id="Ebanner"></div><div id="Epage_content">');
	doc.document.write('<div class="content_box" style="margin-top:20px">'+getid('error_'+id).innerHTML+'</div>');
	doc.document.write('<div id="footer"><h2>Site Info</h2><p>All content copyright &copy; Interlopers.net 2004 - 2009</p><ul><li><a href="/">Home</a></li><li><a href="faq/">FAQ</a></li><li><a href="userbars/">Userbars</a></li><li><a href="staff/">Staff</a></li><li><a href="community/">Community</a></li><li><a href="contact/">Contact</a></li></ul></div></div></body></html>');
	doc.document.close();
	doc.focus();
}
var allItems = Array('[x]','[y]','[z]','[number]','[maximum]','[brush-id]','[entity-id]','[portal-id]','[linenumber]','[brushside-id]','[visleaf-id]','[entity-name]','[entity-type]','[texture]','[sprite]','[sound]','[model]','[mapname]','[filename]' );
function parse(text, id, matches, origTitle)
{
	var items = Array();
	for (var x in allItems)
	{
		var i = origTitle.indexOf(allItems[x]);
		if (i != -1) items.push(new Array(i, allItems[x]));
	}
	items.sort(sort_results);
	for (var x in items)
	{
		text = text.replace(new RegExp('\\['+items[x][1].substring(1,items[x][1].length-1).replace('-','\\-')+'\\]','g'),matches[parseInt(x)+1]);
	}
	return text;
}
function substr_count(szS, szN)
{
	var c=0;
	for(var x=szS.indexOf(szN);x!=-1;x=szS.indexOf(szN, x+1)) c++;
	return c;
}
function getid(id){var ret=document.getElementById(id);return (ret==null)?false:ret;}
function sort_results(a,b){return a[0]-b[0];}

