function $(id) { return document.getElementById(id); }
function togOn(el)
{
	if (typeof el == "string") el = $(el);
	if ("SPAN" == el.tagName) el.style.display = "inline";
	else if ("DIV" == el.tagName) el.style.display = "block";
	else el.style.display = "";
}
function togOff(el)
{
	if (typeof el == "string") el = $(el);
	el.style.display = "none";
}
function tog(el)
{
	if (typeof el == "string") el = $(el);
	var disp;
	if ("SPAN" == el.tagName) disp = "inline";
	else if ("DIV" == el.tagName) disp = "block";
	else disp = "";
	el.style.display = ((el.style.display == 'none' || el.style.display == '') ? disp : "none");
};
function togIs(el)
{
	if (typeof el == "string") el = $(el);
	return el.style.display != 'none';
}
var Ck = new function()
{
	var CK_YR = 3600*24*30*12;
	this.path = "";
	this.get = function(k)
	{
		var cks = document.cookie.split(";");
		for (var i = 0; i < cks.length; ++i) {
			var a = cks[i].split("=");
			if (a.length == 2) {
				a[0] = a[0].trim();
				a[1] = a[1].trim();
				if (unescape(a[0]) == k) return unescape(a[1]);
			}
		}
		return "";
	};
	this.set = function(k, v, sec)
	{
		if (typeof sec == 'undefined') sec = CK_YR;
		var ck = (escape(k) + "=" + escape(v));
		if (sec) {
			var date = new Date(new Date().getTime()+sec*1000);
			ck += ("; expires="+date.toGMTString());
		}
		ck += (this.path ? "; path="+this.path : "");
		document.cookie = ck;
	};
	this.del = function(k)
	{
		var ck = (k + "=");
		ck += (this.path ? "; path="+this.path : "");
		ck += "; expires=Thu, 01-Jan-70 00:00:01 GMT";
		document.cookie = ck;
	};
};
function Ser()
{
	this.ser = function(o)
	{
		var s = '';
		for (var k in o) {
			if (s) s+= ';';
			s += escape(k)+'='+escape(o[k]);
		}
		return s;
	};
	this.deser = function(s)
	{
		var o = new Object();
		var a1 = s.split(';');
		for (var i1 = 0; i1 < a1.length; i1++) {
			var a2 = a1[i1].split('=');
			if (2 == a2.length) {
				o[unescape(a2[0])] = unescape(a2[1]);
			}
		}
		return o;
	};
}
function evtTarg(e)
{
	var el;
	if (window.event) el = window.event.srcElement;
	else if (e) el = e.target;
	if (el && el.nodeType == 3) el = el.parentNode;
	return el;
}
function evtAdd(el, event, func)
{
	if (el.addEventListener) { el.addEventListener(event, func, false); }
	else if (el.attachEvent) { el.attachEvent("on"+event, func); }
	else { var oldfunc = el["on"+event]; el.onclick = function() { oldfunc(); func(); }  }
}
String.prototype.trim = function()
{
	return this.replace(/^\s*|\s*$/g, "");
};
function objFirstKey(o)
{
	if (typeof o == "object") {
		for (var k in o) {
			return k;
		}
		return null;
	}
	return alert("objFirstKey() not implemented for this type of object: "+(typeof o));
}
function objNextKey(o, curK)
{
	if (typeof o == "object") {
		var doRet = false;
		for (var k in o) {
			if (doRet) return k;
			if (curK == k) doRet = true;
		}
		return null;
	}
	return alert("objNextKey() not implemented for this type of object: "+(typeof o));
}
function objPrevKey(o, curK)
{
	if (typeof o == "object") {
		var prevK;
		for (var k in o) {
			if (curK == k) {
				if (!prevK) return null;
				return prevK;
			}
			prevK = k;
		}
		return null;
	}
	return alert("objPrevKey() not implemented for this type of object: "+(typeof o));
}
function objToArrByKey(o)
{
	var a = [];
	for (var k in o) {
		a.push(k);
	}
	return a;
}
function objLen(o)
{
	var len = 0;
	for (var k in o) {
		len++;
	}
	return len;
}
function objSortNumDesc(o)
{
	var o2 = {};
	for (var k in o) {
		o2[k] = o[k];
	}
	var ret = {};
	var cnt = 0;
	while (cnt < objLen(o))
	{
		var max = null;
		var maxK = null;
		for (var k in o2) {
			if (o2[k] === null) continue;
			if (max === null || Number(o2[k]) > max) {
				max = Number(o2[k]);
				maxK = k;
			}
		}
		ret[maxK] = o2[maxK];
		o2[maxK] = null;
		cnt++;
	}
	return ret;
}
function dbg(o)
{
	var ret = '';
	if (typeof o == 'object') {
		for (var k in o) {
			ret += k+' => '+o[k]+'\n';
		}
	} else if (typeof o == 'array') {
		for (var i = 0; i < o.length; i++) {
			ret += i+' => '+o[i];
		}
	} else {
		ret = o;
	}
	alert(ret);
};
var Tab = new function()
{
	var self = this;
	this.cats = CATS;
	this.curCatId = null;
	this.curSiteId = null;
	this.stateSiteIds = {};
	this.build = function()
	{
		var catTbl = '<table id="catTbl" cellspacing="0" cellpadding="0"><tr>';
		for (var catId in this.cats)
		{
			catTbl += '<td><a catId="'+catId+'" onmouseover="if (Tab.ctrl) Tab.selCat(\''+catId+'\');" id="cat_'+catId+'" href="javascript:Tab.selCat(\''+catId+'\',true);">'+catId+'</a></td>';
			this.buildSite(catId);
		};
		catTbl += '</tr></table>';
		$("cats").innerHTML = catTbl;
	};
	this.buildSite = function(catId)
	{
		var siteTbl = '<table id="siteTbl_'+catId+'" cellspacing="0" cellpadding="0"><tr>';
		for (var siteId in this.cats[catId]) {
			siteTbl += '<td><a catId="'+catId+'" siteId="'+siteId+'" onmouseover="if (Tab.ctrl) Tab.selSite(\''+catId+'\',\''+siteId+'\');" id="site_'+catId+'_'+siteId+'" href="javascript:Tab.selSite(\''+catId+'\',\''+siteId+'\',true);">'+siteId+'</a></td>';
		}
		siteTbl += '</tr></table>';
		$("sites").innerHTML += siteTbl;
	};
	this.selTry = function(catId, siteId)
	{
		if (siteId) this.selSite(catId, siteId);
		else if (catId) this.selCat(catId);
	};
	this.selCat = function(catId, doSrh)
	{
		var cls = "act";
		for (var cId in this.cats) {
			if ($("cat_"+cId).className) cls = $("cat_"+cId).className;
			$("cat_"+cId).className = "";
			$("siteTbl_"+cId).style.display = "none";
		}
		$("cat_"+catId).className = cls;
		$("siteTbl_"+catId).style.display = "";

		var siteId;
		if (this.stateSiteIds[catId]) siteId = this.stateSiteIds[catId];
		if (!this.cats[catId][siteId]) siteId = objFirstKey(this.cats[catId]);

		this.curCatId = catId;
		this.selSite(catId, siteId, doSrh);
	};
	this.selSite = function(catId, siteId, doSrh)
	{
		var cls = "act";
		for (var eId in this.cats[catId]) {
			if ($("site_"+catId+"_"+eId).className) cls = $("site_"+catId+"_"+eId).className;
			$("site_"+catId+"_"+eId).className = "";
		}
		$("site_"+catId+"_"+siteId).className = cls;

		this.curSiteId = siteId;
		this.stateSiteIds[catId] = siteId;
		this.stateSave();
		if (doSrh) Srh.srh();
	};
	this.stateSave = function()
	{
		Ck.set("WSA_catId", this.curCatId);
		var ser = new Ser();
		var stateSiteIds = {};
		for (var k in this.stateSiteIds) {
			if (this.cats[k] && this.cats[k][this.stateSiteIds[k]]) {
				stateSiteIds[k] = this.stateSiteIds[k];
			}
		}
		Ck.set("WSA_siteIds", ser.ser(stateSiteIds));
	};
	this.stateLoad = function()
	{
		catId = Ck.get("WSA_catId");
		if (!this.cats[catId]) catId = null;
		if (!catId) catId = objFirstKey(this.cats);

		var ser = new Ser();
		this.stateSiteIds = ser.deser(Ck.get("WSA_siteIds"));

		this.selCat(catId);
	};
	this.ctrl = false;
	this.onkeydown = function(e)
	{

		if (e.ctrlKey)
		{
			Srh.qFoc();
			if (37 == e.keyCode) { Tab.lt(); return false; }
			if (38 == e.keyCode) { Tab.up(); return false; }
			if (39 == e.keyCode) { Tab.rt(); return false; }
			if (40 == e.keyCode) { Tab.dn(); return false; }

			var mEl = this.mouseEl;
			if (mEl.getAttribute('catId')) {
				this.ctrl = true;
				if (mEl.getAttribute('siteId')) Tab.selSite(mEl.getAttribute('catId'), mEl.getAttribute('siteId'));
				else Tab.selCat(mEl.getAttribute('catId'));
			} else {
				this.ctrl = false;
			}
		}
		else
		{
			this.ctrl = false;
		}
		return true;
	};
	this.mouseEl = null;
	this.onmousemove = function(e)
	{
		self.mouseEl = evtTarg(e);
		return true;
	}
	this.onkeyup = function(e)
	{
		this.ctrl = false;
		return true;
	}
	this.lt = function()
	{
		this.selTry(this.curCatId, objPrevKey(this.cats[this.curCatId], this.curSiteId));
	};
	this.rt = function()
	{
		this.selTry(this.curCatId, objNextKey(this.cats[this.curCatId], this.curSiteId));
	};
	this.up = function()
	{
		this.selTry(objPrevKey(this.cats, this.curCatId));
	};
	this.dn = function()
	{
		this.selTry(objNextKey(this.cats, this.curCatId));
	};
};
var Srh = new function()
{
	this.cats = CATS;
	this.histLastQ;
	this.srh = function()
	{
		if (!this.qGet().length) return;
		if (this.histLastQ != this.qGet()) {
			this.histAdd(this.qGet());
			this.histLastQ = this.qGet();
		}

		var catId = Tab.curCatId;
		var siteId = Tab.curSiteId;
		this.pventRedir();

		togOn("msgLoad");

		var src = this.cats[catId][siteId].replace('%s', Srh.qGet());
		$("iframe").innerHTML = '<iframe onload="Srh.onLoad();" id="iframe_'+catId+'_'+siteId+'" name="iframe_'+catId+'_'+siteId+'" src="'+src+'" style="width: 100%; height: 100%; border: 0px;" frameborder="0"></iframe>';

		var iframe;
		if (document.all) iframe = document.all["iframe_"+catId+"_"+siteId];
		else iframe = $("iframe_"+catId+"_"+siteId);
		iframe.style.height = $("iframe").offsetHeight;
	};
	this.onLoad = function()
	{
		this.pventRedir();
		Srh.qFoc();
		togOff("msgLoad");
	};
	this.pventRedir = function()
	{
		// prevent any redirects done from loaded frames
		try { window.stop(); } catch(e) {}
		try { document.execCommand("stop"); } catch(e) {}
	};
	this.qGet = function() { return $("WSA_q").value.trim(); };
	this.qSet = function(q) { $("WSA_q").value = q; this.qSel(); }
	this.qFoc = function() {  $("WSA_q").focus(); }
	this.qSel = function() { this.qFoc(); $("WSA_q").select(); }
	this.stateSave = function() { Ck.set("WSA_lastQ", this.qGet()); }
	this.stateLoad = function() { if (Ck.get("WSA_lastQ")) this.qSet(Ck.get("WSA_lastQ")); }
	this.histAdd = function(q)
	{
		var h = {};
		var ser = new Ser();
		if (Ck.get('WSA_hist')) h = ser.deser(Ck.get('WSA_hist'));
		h[q] = h[q] ? Number(h[q])+1 : 1;
		Ck.set('WSA_hist', ser.ser(h));
	};
	this.histCln = function(q)
	{
		Ck.del('WSA_hist');
	};
	this.hist = function(sortByCnt)
	{
		tog('hist');
		if (togIs('hist'))
		{
			var htm = '<a class="close" href="javascript:tog(\'hist\');">[close]</a>';
			htm += '<table cellspacing="0" cellpadding="0"><tr><td><b>History</b></td>';
			htm += '<td><a href="javascript:togOff(\'hist\');Srh.hist();">[Sort by Alpha]</a></td>';
			htm += '<td><a href="javascript:togOff(\'hist\');Srh.hist(true);">[Sort by Count]</a></td>';
			htm += '<td><a href="javascript:if(confirm(\'Clean history?\')) { togOff(\'hist\');Srh.histCln();Srh.hist(); }">[Clean history]</a></td>';
			htm += '</tr></table><hr>';
			var hist = Ck.get('WSA_hist');
			if (hist) {
				var ser = new Ser();
				var h = ser.deser(hist);
				if (sortByCnt)
				{
					h = objSortNumDesc(h);
					var first = true;
					for (var k in h) {
						if (!first) htm += ' / ';
						if (first) first = false;
						htm += ' <a href="javascript:Srh.qSet(\''+k+'\');">'+k+'</a> ('+h[k]+') ';
					}
				}
				else
				{
					h = objToArrByKey(h);
					h.sort();
					for (var i = 0; i < h.length; i++) {
						if (i) htm += ' / ';
						htm += ' <a href="javascript:Srh.qSet(\''+h[i]+'\');">'+h[i]+'</a> ';
					}
				}
			} else {
				htm += 'No history yet.';
			}
			$('hist').innerHTML = htm;
		}
	};
};
function reqGet(variable)
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
}
window.onload = function()
{
	// first load
	//if (!Ck.get("WSA_catId")) togOn("hlp");

	$("WSA_srh").onsubmit = function() { Srh.srh(); return false; };
	$("WSA_q").onchange = function() { Srh.stateSave(); };
	$("WSA_q").onclick = function() { Srh.qSel(); }
	$("WSA_q").setAttribute('autocomplete', 'off');

	Tab.build();
	Tab.stateLoad();

	Srh.stateLoad();
	Srh.qSel();

	$('iframe').style.height = $('iframe').offsetHeight;

	if (reqGet('q')) {
		Srh.qSet(reqGet('q'));
	}
};
window.onfocus = function()
{
	Srh.qSel();
};
document.onkeydown = function(e)
{
	e = e ? e : window.event;
	if (!e.ctrlKey && !e.altKey && !e.shiftKey)
	{
		var el = evtTarg(e);
		if ("WSA_q" != el.id && e.keyCode >= 65 && e.keyCode <= 90) {
			Srh.qFoc();
			return false;
		}
	}
	return Tab.onkeydown(e);
};
document.onkeyup = function(e)
{
	e = e ? e : window.event;
	return Tab.onkeyup(e);
}
document.onmousemove = function(e)
{
	e = e ? e : window.event;
	return Tab.onmousemove(e);
}