// THIS IS THE OLD QA-WIDGET FROM THE DRUPAL SYSTEM
// DO NOT EDIT THIS FILE!!!
// -Paul

// All QA Widgets on the page
var vhm_qawidgets = new Array(0);


function vhm_cookie_check() {
	document.cookie = 'vhm_cookiecheck';

	var s = (document.cookie != "");
	if (!s)
		alert("COOKIES need to be enabled!");
	return s;
}

function vhm_getCookie(c)
{
	var ck = document.cookie;
	if (ck.length>0)
	{
			c_st = ck.indexOf(c + "=");
			if (c_st!=-1)
			{ 
					c_st = c_st + c.length+1; 
					c_end = ck.indexOf(";", c_st);
					if (c_end == -1) 
							c_end = ck.length;
					return unescape(ck.substring(c_st, c_end));
			} 
	}
	return null;
}


function vhm_appendNew(e, type) {
	var r = document.createElement(type);
	e.appendChild(r);
	return r;
}


// div-frame, table-row
function vhm_scrollIntoView(fr, el) {

	if(fr && el) {
		// Bottom visible
		if( el.offsetTop+el.offsetHeight-fr.scrollTop > fr.clientHeight )
			fr.scrollTop = el.offsetTop + el.offsetHeight - fr.clientHeight;
		// Top visible
		if( el.offsetTop < fr.scrollTop ) 
			fr.scrollTop = el.offsetTop;
	}
}


function vhm_loadJs(fname) {
	var fr = document.createElement('script');
	fr.setAttribute("type","text/javascript");
	fr.setAttribute("src", fname);
	if (typeof fr != "undefined")
		document.getElementsByTagName("head")[0].appendChild(fr);
}


function vhm_loadCss(fname) {
	var fr = document.createElement("link")
	fr.setAttribute("rel", "stylesheet")
	fr.setAttribute("type", "text/css")
	fr.setAttribute("href", fname)
	if (typeof fr != "undefined")
		 document.getElementsByTagName("head")[0].appendChild(fr)
}

function vhm_makeLink(el) {
	el.className += 'link';
	el.style.cursor = 'pointer';
	el.style.cursor = 'hand';
}


// == end util functions ==

function vhm_qawidget(_wid) {

	// Tab enum
	var tab_t = { mostPopular:0, mine:1, help:2, newest:3, channels:4, ask:5, count:6 };
	
	// Settings
	this.widgetId = _wid;
	this.eventId = null;
	this.orgId = null;
	this.baseUrl = "http://vhmengine.com/";
	this.url = this.baseUrl+"oldWidget.jsp";
	this.admin = false;
	this.showAsk = 1;

	// Layout
	this.element = null;
	this.tbody = null;
	this.win = null;

	// State
	this.expandedResponseQId = null;
	this.expandedResponseRow = null;
	this.tab = tab_t.mostPopular;
	this.tabs = null;
	this.selected = new Array(0);
	this.interval = 0;

	this.requests = new Array(0);

	this.oldAsks = new Array(0);
	this.singleView = false;

	// Todo: Fetch this from the server periodically
	this.networks = [
		{
			'name': 'WBIR',
			'networkid': 1,
			'channels': [
				{
					'name': 'WBIR',
					'channelid': 2148,
					'events': [
						{
							'title': 'Sunday Sports Talk',
							'date': '10/5/2008',
							'desc': 'Will, Brent, and Steve answer your questions.',
							'eventid': 2840
						},
						{
							'title': 'Sunday Sports Talk',
							'date': '9/28/2008',
							'desc': 'Will, Brent, and Steve answer your questions.',
							'eventid': 2155
						},
						{
							'title': 'Sunday Sports Talk',
							'date': '9/21/2008',
							'desc': 'Will, Brent, and Steve answer your questions.',
							'eventid': 2154
						},
						{
							'title': 'Sunday Sports Talk',
							'date': '9/14/2008',
							'desc': 'Will, Brent, and Steve answer your questions.',
							'eventid': 2153
						},
						{
							'title': 'Sunday Sports Talk',
							'date': '9/7/2008',
							'desc': 'Will and Steve answer your questions.',
							'eventid': 2152
						}
					]
				}
			]
		},
		{
			'name': 'NFL',
			'networkid': 2,
			'channels': [
				{
					'name': 'Atlanta Falcons',
					'channelid': 1652,
					'events': [
						{
							'title': 'Interview with D.J. Shockley',
							'date': '5/13/2008, 12:00pm-12:30pm Eastern',
							'desc': 'J. Mike interviews Falcons QB D.J. Shockley',
							'eventid': 1765
						}
					]
				}
			]
		},
		{
			'name': 'Knoxville News Sentinel',
			'networkid': 2,
			'channels': [
				{
					'name': 'Knoxville News Sentinel',
					'channelid': 2086,
					'events': [
						{
							'title': 'Ask John Adams - 9/13 - 9/16/2008',
							'date': '9/13/2008 - 9/16/2008',
							'desc': 'John Adams answers your questions about the second game of the season.',
							'eventid': 2385
						},
						{
							'title': 'Ask John Adams - 9/10 - 9/13/2008',
							'date': '9/10/2008 - 9/13/2008',
							'desc': 'John Adams answers your questions about the second week of the season.',
							'eventid': 2365
						},
						{
							'title': 'Ask John Adams - 9/1 - 9/8/2008',
							'date': '9/1/2008 - 9/10/2008',
							'desc': 'John Adams answers your questions about the first week of the season.',
							'eventid': 2141
						}
					]
				}
			]
		}
	];


this.newRequest = function(a, q, cb) {
	var fr = document.createElement('script');
	fr.setAttribute("type","text/javascript");
	var req_slot = a+'/'+cb;
	var uri = this.url +'?a='+ a +'&'+ q +'&_cb='+ cb + '&_ln=vhm_qawidgets%5B'+ this.widgetId + '%5D.listener';

	var uhandle = vhm_getCookie("vhm_userhandle");
	if (uhandle != null)
		uri += "&userhandle="+ uhandle;

	if (this.orgId != null)
		uri += '&orgid=' + escape(this.orgId);
	if (this.eventId != null)
		uri += "&eventid=" + escape(this.eventId);

	uri += "&ts=" + parseInt(new Date().getTime().toString().substring(0, 10));

	fr.setAttribute("src", uri );
	if (typeof fr != "undefined") {
		var oldFr = this.requests[req_slot];
		if (oldFr) {
			oldFr.parentNode.removeChild(oldFr);
		}
		document.getElementsByTagName("head")[0].appendChild(fr);

		this.requests[req_slot] = fr;
	}
}


this.listener = function(r) {
	// Handle special stuff
	if (r['eventid'] != null)
		this.eventId = parseInt(r['eventid']);
	if (r['orgid'] != null)
		this.orgId = parseInt(r['orgid']);
	if (r['userhandle'] != null) {
		var date = new Date();
		date.setTime(date.getTime()+(7*24*60*60*1000));
		document.cookie = "vhm_userhandle="+ r['userhandle'] +
				"; path=/; expires="+date.toGMTString();
	}

	// Callback
	this[r.cb](r.cb_data);
}


// Hides the response by removing the row
// args: table-row
this.hideResponse = function (e) {
	var v = e.parentNode.parentNode;
	e.parentNode.removeChild(e);

	this.expandedResponseQId = null;
	this.expandedResponseRow = null;
}


// Adds a response row with the specified text
// cell, response text
this.showResponse = function (e, txt) {
	var ans = vhm_appendNew(e, 'span');
	ans.innerHTML = txt;
	
	e.widget = this;
	e.onclick = function(){ this.widget.hideResponse(this.parentNode); };
	e.style.cursor = 'pointer';
}


// Fetch and display response 
// args: widgetcount, responseID, row node, make visible
this.response = function (rid, e, qid) {
	var w = this;
	var d = document;
	var tbody = this.tbody;

	// Toggle response off (clicked See-answer again)
	if (e.nextSibling && e.nextSibling.className == 'resp') {
		w.hideResponse(e.nextSibling)
			return;
	}

	// Hide previous response
	var oldRespRow = w.expandedResponseRow;
	if (oldRespRow != null) {
		// scroll back past the deleted space
		if (oldRespRow.offsetTop < e.offsetTop) {
			w.win.scrollTop -= oldRespRow.offsetHeight;
		}

		tbody.removeChild(oldRespRow);
		w.Row = null;
	}

	w.expandedResponseQId = qid;

	// Get table and add cell and loading text
	var row = d.createElement("tr");
	row.className = "resp"; 
	var cell = vhm_appendNew(row, "td");
	cell.innerHTML = "loading...";

	tbody.insertBefore(row, e.nextSibling);

	// Prepare callback data
	this.responseCB.cell = cell;
	
	// Do request
	var q = "respid=" + escape(rid);
	this.newRequest("getresponse", q, "responseCB");
}

//if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept

this.responseCB = function (r) {
	var cell = this.responseCB.cell;
	var row = cell.parentNode;
	var tbody = row.parentNode;
	var fr = tbody.parentNode.parentNode;
	// Show results
	cell.removeChild(cell.firstChild);

	
	// div, row
	vhm_scrollIntoView(fr, row);

	
    if( r.video != null ) {
/*        vhm_appendNew(cell, "div").id = "super_preview";
        var s1 = new SWFObject('http://vhmengine.com/demo/mediaplayer.swf','ply','320','240','9','#ffffff');
        s1.addParam('allowfullscreen','false');
        s1.addParam('allowscriptaccess','always');
        s1.addParam('wmode','opaque');
        s1.addParam('flashvars', 'file=' + r.video.url);
        s1.write('super_preview');
        */
        var d = vhm_appendNew(cell, "div");
        d.innerHTML =
            '<embed src="http://vhmengine.com/mediaplayer.swf" width="160" height="130" allowscriptaccess="always" allowfullscreen="false"' +
            'flashvars="width=160&height=130&&autostart=true&repeat=false&file='+r.video.url+'" />';
        d.style.float = 'left'

        /*var e = vhm_appendNew(cell, "embed");
        e.flashvars="width=160&height=120&&autostart=true&repeat=false&file=" + unescape(r.video.url);
        e.src = "http://vhmengine.com/demo/mediaplayer.swf"
        e.width = "160";
        e.height = "120";
        e.allowscriptaccess = "always"
        e.allowfullscreen="false"
        */
    }   

	cell.appendChild(document.createTextNode(r.txt));

	this.expandedResponseRow = row;
	//this.expandedResponseText = r.txt;
}


// casts a vote and re-polls the list 
// args: questionid, weight
this.castVote = function (qid, we) {
	alert("This is an archived event. Voting is disabled.");
	return;
	if (vhm_cookie_check()) {
		var q = "qid=" + escape( qid ) + "&weight=" + escape( we );
		this.newRequest("castvote", q, "poll");
	}
}


this.getHelp = function() {
	this.newRequest( "gethelp", "foo=bar", "getHelpCB" );
}

this.getHelpCB = function(r) {
	this.clear();
	this.addRow('row0').innerHTML = r; 
}

// Ad
this.drawAd = function() {
	this.addRow( 'row0' ).innerHTML = '<img src="http://vhmengine.com/images/ads/placeholder-full.gif" style="margin-left: auto; margin-right: auto;" />';
//	onclick="window.open(\'http://www.voicesheardmedia.com/advertising.html\');"
}


// Ask
this.ask = function(btn) {
	alert("This is an archived event. Voting is disabled.");
		return;
	var w = this;
	var t = btn.textarea;

	for( var vi=0; vi < w.oldAsks.length; ++vi ) {
		var lowVal = t.value.toLowerCase();
		var oldVal = w.oldAsks[vi];
		if( oldVal.indexOf(lowVal) >= 0 ) {
			t.value = '';
			return;
		}
		else if( Math.abs(lowVal.length - oldVal.length) <= 2 &&
				lowVal.indexOf(oldVal) >= 0 ) {
			t.value = '';
			return;
		} 
	}

	w.showLoading();
	w.singleView = true;
	w.oldAsks.push( t.value.toLowerCase() );
	
	var q = "q=" + escape(t.value);
	w.askCB.textarea = t;
	w.newRequest("ask", q, "askCB");
}

this.askCB = function(r) {
	if (r)
	{
		var w = this;
		// TODO: don't append, replace
		w.askCB.textarea.value = '';
		w.singleView = true;
		w.filter( tab_t.mine );
	}
}




// widget_index
// args: none
this.poll = function() {
	var d = document;
	
	var w = this;
	var t = w.tbody;
	var c = w.widgetId;
	var v = w.win; //d.getElementById("vhm_qawindow"+c);

	var oldTab = w.tab;

	// Special tabs
	switch( w.tab ) {
		case tab_t.help:
			w.getHelp();
			return;

		case tab_t.channels:
			w.clear();

			// Big giant file above
			var row = vhm_appendNew(t,'tr');
			row.className = 'row0';
			var cell = vhm_appendNew(row,'td');
			cell.style.padding = '8px';

			// No network selection for now 
			
			// Instead, just show events for channel:
			var events = null;
			for (n=0; n<w.networks.length; n++) {
				var network = w.networks[n];
				for (c=0; c<network.channels.length; c++) {
					var channel = network.channels[c];
					if (channel.channelid == w.orgId) {
						events = channel.events;
						break;
					}
				}
			}
			if (events != null)
				w.fillEvents( cell, events );

			cell.style.verticalAlign = 'top';
			cell.style.padding = '8px';
			cell.style.height = '100%';
			v.style.height = '100%';
			return;

		case tab_t.ask:
			while( t.hasChildNodes() )
				t.removeChild(t.childNodes[0]);
			var row = vhm_appendNew(t,'tr');
			row.className = 'row0';
			var cell = vhm_appendNew(row,'td');
			cell.style.padding = '8px';

			cell.appendChild( d.createTextNode('Type your question below and click on the "Ask It" button.') );
			vhm_appendNew(cell, 'br');
			cell.appendChild( d.createTextNode('Your question will appear in the list for others to vote on.') );
			vhm_appendNew(cell, 'br');
			
			var ta = vhm_appendNew(cell, 'textarea');
			ta.cols = 40;
			ta.rows = 4;
			ta.text = '';

			var btn = vhm_appendNew(cell, 'img');
			btn.src = 'http://vhmengine.com/widgets/img/button-askit.gif';
			btn.alt = 'Ask question';
			//btn.align = 'right';
			btn.widget = w;
			btn.textarea = ta;
			btn.onclick = Function('this.widget.ask(this);');

			btn.className = 'ask';
			btn.style.cursor = 'pointer';
			btn.style.cursor = 'hand';
			return;

		default:
			break;
	}

	// Question Lists
	if (t != undefined) {
		var q = "foo=bar";
		if ( w.tab == tab_t.newest ) {
			if ( w.admin ) 
				q += "&view=recent_admin";
			else
				q += "&view=recent";
		}

		w.pollCB.oldTab = oldTab;
		w.newRequest("questionlist", q, "pollCB");
	}
}


this.pollCB = function(r) {
	var w = this;
	var v = w.win;
	
	var oldTab = w.pollCB.oldTab;
	var t = w.tbody;
	var d = document;
	var showmine = (oldTab == tab_t.mine);

	// This request is expired
	if( oldTab != w.tab)
		return;

	// Clean it
	w.clear(w.expandedResponseRow);

	// Shrink table after loading is hidden
	v.style.height = null;
	var oldSel = w.selected.slice();
	w.selected = new Array(0);

    var insertBefore = false;
    if( w.expandedResponseQId != null)
        insertBefore = true;

	var ad_idx = 5;
	var j = 0;

	// Header
	if ( w.admin && w.tab == tab_t.newest ) {
		var row = vhm_appendNew(t,'tr');
		row.className = "row0";
		vhm_appendNew(row,'td').innerHTML = '<em>Question</em>';
		vhm_appendNew(row,'td').innerHTML = '<em>Parent</em>';
	}

	var pack = r; //eval('('+r+')');
	var res = pack.contents;

	// Crop out single-quesiton if needed
	if( w.singleView ) {
		var maxqid = 0;
		var maxi = -1;
		for( var i=0; i<res.length; i++ ) {
			if( res[i].mine != 0 && res[i].id > maxqid ) {
				maxqid = res[i].id;
				maxi = i;
			}
		}
		var tmp = res[maxi];
		res = new Array(0);
		if( maxi >= 0 ) {
			res[0] = tmp;
		}
	}

	for( var i=0; i<res.length; i++ ) {
		if (res[i].mine <= 0 && showmine == 1)
			continue;
		
		if (j == ad_idx && !w.admin)
			w.drawAd();
		var qid = res[i].id;

		// rebuild selection
		var sel = (oldSel.indexOf(parseInt(qid)) >= 0);
		if( sel ) {
			w.selected.push(parseInt(qid));
		}

        var row = d.createElement('tr');
        if( insertBefore && w.expandedResponseRow != null )
            t.insertBefore( row, w.expandedResponseRow );
        else
            t.appendChild( row );

	//  w.expandedResponseRow = null;
		//var row = vhm_appendNew(t,'tr');
		if( res[i].resp != null )
			row.className = "rowanswered";
		else
			row.className = "row" + j%2;

		var cell = vhm_appendNew(row,'td');

		// Op
		if( w.admin ) {
			var cbox = d.createElement('input');
			cbox.title = 'Select this question';
			cbox.type = 'checkbox';
			cbox.checked = sel;
			cbox.widget = w;
			cbox.onclick = Function('this.widget.select('+qid+',this.checked);');
			cell.appendChild(cbox);
		}

		// Question
		cell.appendChild( d.createTextNode(res[i].txt) );

		// Voter
		var nowrap = d.createElement('span');
		nowrap.style.whiteSpace = 'nowrap';
		nowrap.appendChild( showmine ?
				d.createTextNode(" [" + res[i].num + " votes, rank: "+(i+1)+"] ") :
				d.createTextNode(" [" + res[i].num + " votes] ")
				);

		if( !w.admin ) {
			//var votebtn = vhm_appendNew(nowrap,'a');

			if( res[i].mine <= 0 ) {
				var votebtn = vhm_appendNew(nowrap,'img');
						vhm_makeLink(votebtn);
				votebtn.title = 'Vote this question up';
				votebtn.widget = w;
				votebtn.src = "http://vhmengine.com/widgets/img/icon-vote.gif";
				votebtn.onclick= Function('this.widget.castVote('+qid+',1);');
			}
			if( res[i].mine != 0 ) {
				var votebtn = vhm_appendNew(nowrap,'img');
				votebtn.title = 'My question';
				votebtn.src = "http://vhmengine.com/widgets/img/icon-mine.gif";
			}
			if( res[i].mine >= 0 ) {
				var votebtn = vhm_appendNew(nowrap,'img');
						vhm_makeLink(votebtn);
				votebtn.title = 'Vote this question down';
				votebtn.widget = w;
				votebtn.src = "http://vhmengine.com/widgets/img/icon-votedown.gif";
				votebtn.onclick= Function('this.widget.castVote('+qid+',-1);');
			}
			cell.appendChild( nowrap );
		}

		// Answer button
		var resp = res[i].resp;
		if( w.admin ) {
			var mark = d.createElement('span');
					vhm_makeLink(mark);
			mark.widget = w;
			if( resp == 'asked' ) {
				mark.innerHTML = 'Unmark as answering';
				mark.onclick = Function('this.widget.markAsked('+qid+',0);');
				vhm_appendNew(cell,'br');
				cell.appendChild( mark );

				var mark = d.createElement('span');
                vhm_makeLink(mark);
				mark.widget = w;
				mark.innerHTML = 'Answer';
				mark.onclick = Function('this.widget.answer('+qid+',window.prompt("Enter response:",""));');
				//vhm_appendNew(cell,'br');
                //TODO: Bug? cell.appendChild( mark );
			}
			else if( resp == null ) {
				mark.innerHTML = 'Mark as answering';
				mark.onclick = Function('this.widget.markAsked('+qid+');');
			}
			else {
				mark.innerHTML = 'Answered';
				mark.onclick = Function('this.widget.editAnswer('+resp+');');
			}
			vhm_appendNew(cell,'br');
			cell.appendChild( mark );

			// Second column for admins
			if( w.tab == tab_t.newest && w.admin ) {
				cell = vhm_appendNew(row,'td');
				cell.style.width = '50%';
				// Question
				var p = res[i].parent_txt;
				if( p == undefined )
					p = "--";
				cell.appendChild( d.createTextNode(p) );
			}
		}
		else {
			if( resp == "asked" ) {
				var asked = d.createElement('span');
				asked.innerHTML = 'Answering';
				asked.className = 'answer_status';
				vhm_appendNew(cell,'br');
				cell.appendChild( asked );
			}
			else if( resp!=null) {
				var ans = d.createElement('span');
						vhm_makeLink(ans);
				ans.innerHTML = 'See answer';
				ans.className = 'see_answer';
				ans.widget = w;
				ans.onclick = Function('this.widget.response('+resp+', this.parentNode.parentNode, '+qid+');');
				ans.title = 'See answer to this question';
				vhm_appendNew(cell,'br');
				cell.appendChild( ans );

				// Response
				if( qid == w.expandedResponseQId ) {
                   insertBefore = false;
                       /*t.appendChild( w.expandedResponseRow );

					row = vhm_appendNew(t,'tr');
					row.className = 'resp';
					cell = vhm_appendNew(row,'td');
					cell.innerHTML = '';
					w.expandedResponseRow = row;

					w.showResponse(cell, w.expandedResponseText);
                */
				}
			}
		}
		j++;

	} // end for

	if (j==0) {
		// No rows, give feedback
		var row = vhm_appendNew(t,'tr');
		row.className = 'row0';
		var cell = vhm_appendNew(row,'td');
		cell.innerHTML = '[ No questions found ]';
	}
	else {
		var row = vhm_appendNew(t,'tr');
		row.className = 'row0';
		var cell = vhm_appendNew(row,'td');
		var head = pack.header;
		cell.innerHTML = 'Questions: ' + head.questions + '&nbsp; &nbsp;Votes: ' + head.votes;
		if( !w.admin ) {
			cell.innerHTML += '&nbsp; &nbsp;Mine: ' + head.mine;
			if( w.singleView ) {
				cell.appendChild(d.createTextNode(" - "));
				var sp = vhm_appendNew( cell, 'span' );
						vhm_makeLink(sp);
				sp.innerHTML = 'expand list';
				sp.widget = w;
				sp.onclick = Function('this.widget.singleView = false; this.widget.poll();');

			}
		}
		else if( w.tab == tab_t.newest )
			cell.colSpan = 2;
		cell.style.textAlign = 'center';
		cell.style.fontWeight = 'bold';
	}

	if( !w.singleView ) {
		if( j <= ad_idx && !w.admin )
			w.drawAd();
	}
	else { 
		var row = vhm_appendNew(t,'tr');
		row.className = 'row0';
		var cell = vhm_appendNew(row,'td');
		cell.innerHTML = "" // TODO: Add adverts.
	}	

	clearInterval(w.interval);
	w.interval = setInterval('vhm_qawidgets['+w.widgetId+'].poll()', 180000);
} 


this.findTab = function(tab) {
	for(var i in this.tabs) {
		var t = this.tabs[i];
		if( t.tab == tab )
			return t;
	}
	return null;
}


this.clear = function(preserveRow) {
	var t = this.tbody;
    //ivar preserveRow = null;
	while (t.hasChildNodes && t.childNodes[0] != preserveRow)
		t.removeChild( t.childNodes[0] );
    while (t.childNodes.length > 1)
		t.removeChild( t.childNodes[1] );
}

this.addRow = function(rowClass) {
	var r = vhm_appendNew(this.tbody,'tr');
	r.className = rowClass;
	return vhm_appendNew(r,'td');
}

this.fillSelect = function(sel, list) {
	sel.options.length = 0;
	//sel.value = undefined;
	for(var i in list) {
		var n = list[i];
		var opt = vhm_appendNew(sel, 'option');
		opt.value = i;
		opt.innerHTML = n.name;

		if( sel.value == undefined ) {
			sel.value = i;
		}
	}
	if(sel.onchange)
		sel.onchange();
	//alert(sel.onchange());
	//sel.onchange();
}

this.fillEvents = function(elem, list) {
	elem.innerHTML = '';
	var	ul = vhm_appendNew(elem, 'ul');
    for(var i=0; i< list.length; i++) {
		ev = list[i];
		li = vhm_appendNew(ul, 'li');
		li.style.marginBottom = '1ex';
		
		vhm_makeLink( span = vhm_appendNew(li, 'span') );
		span.style.fontWeight = 'bold';
		span.innerHTML = ev.title + ' ';
		span.widget = this;
		span.onclick = Function('this.widget.eventId = '+ ev.eventid +'; this.widget.filter( 0 );');

		span = vhm_appendNew(li, 'span');
		span.style.whiteSpace = 'nowrap';
		span.style.font = 'smaller bold';
		span.innerHTML = ev.date;
		vhm_appendNew(li, 'br');

		span = vhm_appendNew(li, 'span');
		span.innerHTML = ev.desc;
	}
}

this.showLoading = function() {
	this.clear();

	var row = vhm_appendNew(this.tbody,'tr');
	row.className = "row0";
	var cell = vhm_appendNew(row,'td');
	cell.style.backgroundImage='url("http://vhmengine.com/widgets/img/spinner.gif")';
	cell.style.backgroundPosition='50% 50%';
	cell.style.backgroundRepeat='no-repeat';
	cell.innerHTML="&nbsp;";
	this.win.style.height = '100%';
}

// Changes the filter(tab) and causes a poll
// args: tab-index
this.filter = function(m) {
	var w = this;
	
	clearInterval( w.interval );
	if( w.tab == tab_t.mine )
	{
		w.singleView = false;
	}

	// TODO: FINISH
	var tt = w.findTab( w.tab );
	tt.element.className = tt.element.className.replace(/active/,"");

	w.tab = m;
	tt = w.findTab( m );
	tt.element.className += ' active';

	w.showLoading();
	w.poll();
}


this.init = function() {
	// Layout
	var w = this;
	var wid = w.widgetId;
	
	w.element = document.getElementById("vhm_qawidget"+wid);
	w.win = document.getElementById("vhm_qawindow"+wid);
	w.tbody = w.win.tBodies[0];


	w.tabs = [
		{ 'title': 'Most Popular',
			'tab': tab_t.mostPopular,
			'desc': 'The most requested questions' },
		{ 'title': 'Most Recent',
			'tab': tab_t.newest,
			'desc': 'The latest questions' } ,
		{ 'title': 'My Questions',
			'tab': tab_t.mine,
			'desc': 'Questions asked or voted on by you' }
		];

	if( w.showAsk ) {
		w.tabs.push( ({ 'title': 'Ask Your Question',
			'tab': tab_t.ask,
			'desc': 'Ask your question',
			'className': 'highlight' }) );
	}

	if( w.showChannels ) {
		w.tabs.push( ({ 'title': 'Archive',
			'tab': tab_t.channels,
			'desc': '--' }) );
	}

	w.tabs.push( ({ 'title': 'Help',
				'tab': tab_t.help,
				'desc': 'Get help using VHM' }) );

	var ul = w.element.firstChild.firstChild;

	for(var i = 0; i < w.tabs.length; ++i) {
		var t = w.tabs[i];

		var li = vhm_appendNew( ul, 'li' );
		var sp = vhm_appendNew( li, 'span' );
		sp.widget = w;
		sp.onclick = Function( 'this.widget.filter('+t.tab+');' );
		sp.title = t.desc;
		sp.innerHTML = t.title;
        if( t.className != null )
            sp.className = t.className;
		t.element = li;
	}

	w.filter( w.tab );
}

} // End class



(function(t) {

	var d = document;
	var c = vhm_qawidgets.length;
    var style = 'default';

	var w = vhm_qawidgets[c] = new vhm_qawidget( c );
	if( typeof vhm_widget_showask != "undefined" )
		w.showAsk = vhm_widget_showask;
	if( typeof vhm_widget_theme != "undefined" )
		style = vhm_widget_theme;
	if( typeof vhm_eventid != "undefined" )
		w.eventId = vhm_eventid;
	if( typeof vhm_channelid != "undefined" )
		w.orgId = vhm_channelid;
	if( typeof vhm_widget_showchannels != "undefined" )
		w.showChannels = vhm_widget_showchannels;
	else if( w.eventId == 1765 || w.orgId == 1652 )
		w.showChannels = false;
    else
        w.showChannels = true;

	// Write out CSS Stuff
	vhm_loadCss(w.baseUrl+'widgets/qawidget/'+style+'.css');
	d.write("<style> .vhm_qawidget ul.tabs { width: "+ vhm_widget_width +"px; } </style>");

	// Widget main-div
	d.write('<div id="vhm_qawidget'+c+'" class="vhm_qawidget_'+style+'" style="width: '+ vhm_widget_width +'px;">');
	d.write('<div style="height: 32px; width: 100%; position: relative;" class="tab_cont" >' + 
			'<ul class="tabs">' +
			'</ul></div>');
	d.write("<div style=\"overflow: auto; border-left: 1px solid black; border-right: 1px solid black" +
			"; width: " + (vhm_widget_width-2) + 
			"px; height: " + (vhm_widget_height-32) + "px;\">" +
			"<table id=\"vhm_qawindow" + c + "\"><tbody></tbody></table></div>");
	d.write('</div>');
	
	// IE Fixes - TODO: Move to external file
	if(!Array.indexOf){
		Array.prototype.indexOf = function(obj){
			for(var i=0; i<this.length; i++){
				if(this[i]==obj){
					return i;
				}
			}
			return -1;
		}
	}
	// END IE Fixes

	var timer=setTimeout("vhm_qawidgets["+c+"].init()", 0);

})(this)
