document.cookie='hasJS=1;path=/';
var HUBDUB = {};
function HDUser(id,newWindow){this.id=id;this.newWindow=newWindow;}
user = new HDUser();
function sih(id, data) { obj = _(id); if (!obj) return; obj.innerHTML=data;}
function _(id) {return document.getElementById(id);}
function show(id, how) {setDisplayById(id,true,how);}
function hide(id) {setDisplayById(id,false);}
function toggle(id, how) {
	obj = _(id); if (!obj) return;
	if (obj.style.display == 'none') show(id, how); else hide(id);
}
function setcp(c, p, p2){
	if (c.createTextRange) { //ie support
		c.focus();
		var s = c.createTextRange(); s.collapse();
		s.moveEnd('character', p2); s.moveStart('character', p);
		s.select();
	} else { //others
		c.focus();c.setSelectionRange(p,p2);
	}
}

function setDisplayById(id, display, how) {
	if (typeof id == 'object') o = id; else o = _(id); if (!o) return;
	dispnow = o.style.display;
	o.visibledisplay = how ? how : o.visibledisplay ? o.visibledisplay : ((dispnow && dispnow!='none')? dispnow : 'block');
	disp = display ? o.visibledisplay : 'none';
	if (disp == 'table-row' && navigator.appName == "Microsoft Internet Explorer") { disp = ''; }// IE compatibility issues with table-row
	o.style.display = disp;
}

function setDropDown(id, value) {
	for(i=0; i<_(id).options.length; i++) if (_(id).options[i].value == value) _(id).selectedIndex=i;
}

function cancelLink(){return false;}
function disableLink (link) {
  if (link.onclick) link.oldOnClick = link.onclick;
  link.onclick = cancelLink;
  if (link.style) link.style.cursor = 'default';
  link.disabled = true;
}
function enableLink (link) {
  link.onclick = link.oldOnClick ? link.oldOnClick : null;
  if (link.style) link.style.cursor = document.all ? 'hand' : 'pointer';
  link.disabled = false;
}
function toggleLink (link) {
  if (link.disabled) enableLink (link)
  else disableLink (link);
}

function popUp(URL, width, height) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=" + width + ",height=" + height + "');");
}

function popUpWithScrollBars(URL, width, height) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=" + width + ",height=" + height + "');");
}

/* formats a Date object to a presentable string */
function giDateToString(d, inctime) { 
	var d_names = new Array("Sun","Mon", "Tue","Wed", "Thu", "Fri", "Sat");
	var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
	var curr_day = d.getDay();
	var curr_date = d.getDate();
	var sup = "";
	if (curr_date == 1 || curr_date == 21 || curr_date ==31) sup = "st";
	else if (curr_date == 2 || curr_date == 22) sup = "nd";
	else if (curr_date == 3 || curr_date == 23) sup = "rd";
	else sup = "th";
	var curr_month = d.getMonth();
	var curr_year = d.getFullYear();
	var out = (d_names[curr_day] + " " + curr_date + sup + ' ' + m_names[curr_month] + " " + curr_year);
	if (inctime) out += ' '+d.getHours()+':'+(d.getMinutes() < 10 ? '0' : '')+d.getMinutes();
	return out; 

}
function isObject(o) { return typeof o == 'object'; }
function initialFocus(id) { setTimeout("_('" + id + "').focus()", 100); }
function iss(v) { return v == 1 ? '' : 's'; }
function timestampDiffAsString(t1, t2) {
	var secs = Math.abs(t1-t2);
	if (secs<60) return secs + " sec" + iss(secs);
	if ((mins = Math.floor(secs/60)) && mins < 60) return mins + " min" + iss(mins);
	if ((hours = Math.floor(mins/60)) && hours < 24) return hours + " hour" + iss(hours);
	if ((days = Math.floor(hours/24)) && days < 7) return days + " day" + iss(days);
	if ((weeks = Math.floor(days/7)) && weeks < 52) return weeks + " week" + iss(weeks);
	if ((years = Math.floor(days/365))) return years + " year" + iss(years);
}
function String_mreplace(search, replace) {
	var out = this; var i=0;
	for(var k=0; k<search.length; k++) while((i=out.indexOf(search[k], i))>-1)
		out = out.replace(search[k], replace[k]);
	return out;
};
String.prototype.mreplace = String_mreplace;
graph_shown=false;
function showBigGraph(mid) {
	if (!graph_shown) _('history_graph').innerHTML= "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='615' height='480' align='left' style='clear: left;'>" +
			  "<param name='movie' value='/scripts/basic_wide.swf'>" +
			  "<param name=FlashVars value='marketId="+mid+"'>" + 
			  "<param name='quality' value='high'>" +
			  "<embed src='/scripts/basic_wide.swf' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='615' height='480' FlashVars='marketId="+mid+"'></embed>" +
			"</object>";
	graph_shown=true;
}
function imgToBounds(img, w, h) {
	if(w<=0)w=80;if(h<=0)h=80;
	var prop=Math.max(img.width/w,img.height/h);
	img.width/=prop;img.height/=prop;
}
function handleAjax() {
	var r=ajax_link;
	if (!r||!r.readyState||r.readyState!=4) return;
	if (r.status!=200) {location.reload(true); return;}
//	if (location.host.search(/hubdub\.com/)<0) alert(r.responseText);
	var data = JSON.parse(r.responseText); 
	r.abort();
	for (d in data) if (typeof window[data[d]['clienthandler']] == 'function') 
		window[data[d]['clienthandler']](data[d]);
} 
function selectSetOpts(s, aa) {
	while(s.options.length)s.remove(0);
	for(a in aa){var o=document.createElement("option");o.text=aa[a];o.value=a;try{s.add(o)}catch(e){s.add(o,null)}}
}
function setonload(data) { eval(data['data']); }
var ajax_link=null, ajax_queue=null;
function queueAjax(commands) {
	if (ajax_queue)ajax_queue=ajax_queue.concat(commands);else ajax_queue=commands;
}
function sendAjax(commands) {
	var url = '/ajax';
	var r=null;
	if (ajax_queue) {commands = commands.concat(ajax_queue); ajax_queue=null; }
	commands.unshift({'type':'PageURL','data':document.location.href});
//	if (location.host.search(/hubdub\.com/)<0) alert(JSON.stringify(commands));
	if(window.XMLHttpRequest)try{r=new XMLHttpRequest();}catch(e){}
	if(!r && window.ActiveXObject)try{r=new ActiveXObject('Msxml2.XMLHTTP');}catch(e){}
	if(!r && window.ActiveXObject)try {r=new ActiveXObject('Microsoft.XMLHTTP');}catch(e){}
	if(r){
		ajax_link = r;
		r.onreadystatechange=handleAjax;
		r.open('POST',url,true);
		r.send(JSON.stringify(commands));
	}
}
function redirect(data) { location.href=data.data; }
function windowopen(data) { window.open(data.data); }
function updateDiv(data) { var div=_(data['clientid']); if (div) div.innerHTML=data['data']; }
function formBack(data) {
	var elem;
	var f=_(data['clientid']);
	var errs=data['data']['errors'];if (!errs) errs=[];
	for (var e=0;e<f.elements.length; e++) { var n = f.elements[e].name;
		f.elements[e].disabled = f.elements[e].oldenabled;
		if (elem=_(data['clientid']+'.'+n+'.e')) {
			if (errs[n]) { elem.innerHTML=errs[n]; show(elem); }
			else { hide(elem);}
		}
	}
	document.body.style.cursor=document.body.oldcursor;
	if (formhandlers[f.id]) {
		formhandlers[f.id](data); formhandlers[f.id]=false;
	}
}
var formhandlers = {};
function sendForm(cc, form, handler) {
	var data = new Object();
	if (handler) formhandlers[form.id] = handler;
	for (var i=0;i<form.elements.length; i++) { var e = form.elements[i];
		e.oldenabled = e.disabled ? true : false; e.disabled = true;
		switch (e.type) {
			case 'checkbox': data[e.name] = e.checked ? 1 : 0; break;
			case 'radio': if (e.checked) data[e.name] =  e.value; break;
			case 'select': data[e.name] = e.options[e.selectedIndex].value; break;
			default: data[e.name] = e.value;
		}
	}
	document.body.oldcursor=document.body.style.cursor; document.body.style.cursor='wait';
	var msg = { 'type':'c', 'serverhandler':cc, 'data':data, 'clienthandler': 'formBack', 'clientid': form.id }
	sendAjax([msg]);
}
function hideChallenge(data) {
	if (!data.data.result) return;
	var f=_(data['clientid']);
	var id;
	for (i=0;i<f.elements.length;i++) if (f.elements[i].name=='challenge_id') { id=f.elements[i].value; break;}
	_('challengeform_'+id).innerHTML = '<span class="smallgrey">challenge declined</span>';
}
function hideClosed(data) {
	if (!data.data.result) return;
	var f=_(data['clientid']);
	var id, btnType;
	for (i=0;i<f.elements.length;i++) {
		if (f.elements[i].name=='position_id') id=f.elements[i].value;
		if (f.elements[i].name=='submit') btnType=f.elements[i].value;
	}
	if (btnType) btnType=btnType+'ed'; else btnType ='cashed in';
	var tr = _('pos_'+id);
	tr.innerHTML='<span class="smallgrey">'+btnType+' successfully</span>';
}

addInnerHTML = function(e, html) {
	if (!e) return false;
	e.innerHTML = e.innerHTML+html;
}

fillTemplate = function(template, values) {
	for(k in values) template = template.replace('%'+k+'%',values[k]);
	return template;
}
/* set the grey text in a text input box when empty */
function setEmptyText(id, text) {
	var o = _(id);
	o.emptyText = text;
	o.onblur = function() {
		if (this.value=="" || this.value==this.emptyText) {
			this.value = this.emptyText;
			this.style.color="#999";
			if (this.type=="password") {
				this.isPassword = true; // remember it was a password
				this.type="text";
			}
		}
	}
	o.onfocus = function() {
		if (this.value==this.emptyText) {
			this.value=""; this.style.color="#000"; if (this.isPassword) this.type="password";
		}
	}
	o.onblur();
}

/* Animation */
function shrink(id) {
	obj = _(id); obj.style.height = obj.clientHeight+'px'; obj.style.overflow = 'hidden';
	shrinkIterate(id);
}
function shrinkIterate(id) {
	obj = _(id); h = parseInt(obj.style.height); 
	if (h<10) { hide(id); _(id).style.opacity=1; return;
	} else {
		obj.style.height = (h-10)+"px";
		setTimeout("shrinkIterate('"+id+"');",20);
	}
}
function fade(id) { obj = _(id); obj.style.opacity=1; fadeIterate(id); }
function fadeIterate(id) {
	obj = _(id);
	if (obj.style.opacity<=0) { shrink(id); return;
	} else {
		obj.style.opacity -= 0.04; 
		setTimeout("fadeIterate('"+id+"');",10);
	}
}
function findPosX(obj) {
	var curleft = 0;
	if(obj.offsetParent) while(1) {
		curleft += obj.offsetLeft;
		if(!obj.offsetParent) break;
		obj = obj.offsetParent;
	} else if(obj.x) curleft += obj.x;
	return curleft;
}
function findPosY(obj) {
	var curtop = 0;
	if(obj.offsetParent) while(1) {
		curtop += obj.offsetTop;
		if(!obj.offsetParent) break;
		obj = obj.offsetParent;
	} else if(obj.y) curtop += obj.y;
	return curtop;
}
window.size=function() {
	var w=0,h=0;
	if(!window.innerWidth) { //IE, strict or quirks
		var e=(document.documentElement.clientWidth==0)?document.body:document.documentElement;
		w=e.clientWidth;h=e.clientHeight;
	}else{w=window.innerWidth;h=window.innerHeight;} //w3c
	return {width:w,height:h};
}

function addClassName(elem, cname) {
	if (!elem.className){elem.className=cname;return;}
	removeClassName(elem, cname);elem.className+=' '+cname;
}
function removeClassName(elem, cname) {
	if (!elem.className) return;
	var a = elem.className.split(' ');
	var cnUp = cname.toUpperCase();
	for (var i=0;i<a.length;i++) if (a[i].toUpperCase()==cnUp) {a.splice(i,1);i--;}
	elem.className = a.join(' ');
}

function padZeros(num,len){var o=num+'';while(o.length<len)o="0"+o;return o;}

/* Entity section */
function BO() {}
function BOList(data) {
	var out=[];
	for (classname in data) {
		datalist = data[classname];
		for (i in datalist) out.push(new Window[classname](datalist[i]));
	}
	return out;
}
function showFooter(){document.write('<div id="footer"><div id="footer_content"><div id="footer_contentright"></div><div id="footer_contentleft"></div><div id="footer_main"><div id="links" style="width:227px;padding-right:20px;"><h3>Get Hubdubbing</h3><p>Hubdub is a news prediction game that lets you find out how well you really know the news! Compete at predicting the outcomes of real running news stories. <a href="/public/whatishubdub">Learn more</a></p></div><div id="links" style="width:115px;"><h3>About</h3><dl><dt><a href="/public/whatishubdub">What is hubdub?</a></dt><dt><a href="/public/theteam">Team</a></dt><dt><a href="http://blog.hubdub.com">Blog</a></dt><dt><a href="/public/contact">Contact</a></dt><dt><a href="/public/jobs">Jobs</a></dt></dl></div><div id="links" style="width:128px;"><h3>Resources</h3><dl><dt><a href="http://www.hubdub.com/public/tour">Tour</a></dt><dt><a href="http://www.hubdub.com/public/help">FAQ</a></dt><dt><a href="http://www.hubdub.com/public/goodquestion">Question guidelines</a></dt><dt><a href="http://www.hubdub.com/public/noticeboard">Noticeboard</a></dt><dt><a href="http://www.hubdub.com/public/aboutwidgets">Widgets</a></dt><dt><a href="http://hubdub.spreadshirt.com/">US Store</a> | <a href="http://hubdub.spreadshirt.net/">UK Store</a></dt></dl></div><div id="links" style="width:130px;"><h3>Extras</h3><dl><dt><a href="http://www.fanduel.com/">Fanduel</a></dt><dt><a href="http://www.fanduel.com/fantasybaseball">Fantasy baseball</a></dt><dt><a href="http://www.fanduel.com/fantasyfootball">Fantasy football</a></dt><dt><a href="http://www.hubdub.com/public/press">Press</a></dt><dt><a href="http://www.hubdub.com/public/advertise">Advertise with us</a></dt><dt><a href="http://www.new.facebook.com/pages/Hubdub/26367668088">Hubdub on Facebook</a></dt></dl></div><div id="terms"><div id="copyright">Copyright &copy; 2009 Hubdub Ltd. All rights reserved.</div><a href="/public/privacy">Privacy Policy</a> &nbsp; | &nbsp; <a href="/public/terms">Terms of Use</a></div></div></div>');}
function showSearch(){document.write('<form action="/p/search_results" method="get"><div align="right" class="searchbox">Search <input type="hidden" name="qtype" value="m"><input type="text" name="q" style="width: 175px; margin-left:5px;"><select name="ent"><option>Questions</option><option>Users</option></select><input type="submit" value="Go" style="height:22px; width:30px; font-size:11px;"></div></form>');}
function showWorth(level,levelname,net,cash,preds){document.write('<div style="float:right;width: 20px;margin: 4px 0 0 5px;"><img title="Level '+level+', '+levelname+' (H$'+net+')"  src="/images/icon_star_'+level+'.gif" style="margin-left: 2px; position: relative; top: 2px;"></div><div class="networth"><a href="/p/MyDashboard" class="networth">Net worth: <span class="figure">H$'+net+'</span></a></div><div class="networthheader">Cash: <b><span ><img title="Hubdub play dollars" src="/images/hd_dollar.gif" alt="hd$" style="vertical-align:middle"><span>'+cash+'</span></span></b>&nbsp;&nbsp;&nbsp;<a href="/p/MyPositionsOpen" class="networthheader">Predictions: <b><span ><img title="Hubdub play dollars" src="/images/hd_dollar.gif" alt="hd$" style="vertical-align:middle"><span>'+preds+'</span></span></b></a><div class="helpicon" onMouseOver="_(\'help6067338\').style.left = (window.size().width - findPosX(this) < 250) ? \'-220px\' : \'0px\';show(\'help6067338\');" onMouseOut="hide(\'help6067338\');"><img src="/images/help_icon.gif"><div class="helpcontainer" id="help6067338"><div class="helptop"></div><div class="helpmid"><div class="inner">You currently have <span ><img title="Hubdub play dollars" src="/images/hd_dollar.gif" alt="hd$" style="vertical-align:middle"><span>'+cash+'</span></span> (Hubdub dollars), Hubdub\'s virtual currency, to stake on your predictions. Your predictions are currently worth <span ><img title="Hubdub play dollars" src="/images/hd_dollar.gif" alt="hd$" style="vertical-align:middle"><span>'+preds+'</span></span></div></div><div class="helpbtm"></div></div></div></div></div>');}
function hideUmd(){ _('usermessage').style.visibility='hidden';}
function umd(out) { var o='';
	if (out.data.w) o='<div class="warning">'+out.data.w.join('<br>')+'</div>';
	if (out.data.i) o+='<div class="info">'+out.data.i.join('<br>')+"</div>";
	if (out.data.s) o+='<div class="success">'+out.data.s.join('<br>')+"</div>";
	_('usermessage').innerHTML=o; _('usermessage').style.visibility='';
	setTimeout('hideUmd()', 3000);
}
function encSpc(str) { 
	str = str.replace(/&(?:#\d+|\w+);/g, "").replace(/<[^>]*>/g, "");
	return escape(str.replace(/[^a-z0-9 ]/ig, '').replace(/ /g, "_"));
}
function unEncSpc(str) { return unescape(str).replace(/_/g, ' '); }
function updateObj(gobbet, div, etyp, eid, pr) { 
	if (!pr) pr='view';
	return { 'type':'eg', 'serverhandler':etyp+'/'+eid+'/'+pr+'/'+gobbet, 
				'clienthandler': 'updateDiv', 'clientid': div };
}
var settview_current=false; 
function showSettview(pane, etyp, eid, page, func){
	if (!page) page=pane; if (!func) func='showForm';
	if (page+'/'+pane!=settview_current) {
		settview_current=page+'/'+pane;
		_('settview_inner').innerHTML='<h1 style=\"text-align:center;padding:50px\">Loading</h1>';
		sendAjax([updateObj(func+'/'+pane, 'settview_inner', etyp, eid, page)]);
	}
	show('settview');
} 
function hidesettview(data) {if(!data.data.result) return;hide('settview');}

function getEntityURL(type,id,title,cx,gobbet) { if (cx && cx.toLowerCase()=='view') cx='';var c='';
	if (type=='Tag' && !gobbet && title==unEncSpc(encSpc(title))) {
		switch (title.toLowerCase()) { 
			case 'election 08 by state': gp='election_map'; break;
			case 'olympics': gp='olympics'; break;
			case 'nfl': gp='nfl'; break;
			default: gp='tag'; c = encSpc(title);
		}
	} else if (type=='User') { gp='users'; c=title;
	} else {
		gp = gobbet?'eg':'e';
		if (type=='Market' && id>6700 && !cx) {
			gp = 'm'+id; c = encSpc(title);
		} else c = type+"/"+encSpc(title)+"_"+id;
	}
	if (cx) c+="/"+cx;
	return location.protocol+'//'+location.host+'/'+gp+'/'+c;
}
/* in-page tab switching with working back/forward navigation */
/*KEEP THIS CODESECTION WE NEED IT SOON
function getUrlFrag() { return window.location.href.split("#")[1]; }
function whereat(){
	var f=getUrlFrag();
	if ((f!=whereatnow)) {
		//call to do something about selected tab goes here
		whereatnow = f;
	}
}
var whereatnow=window.location.href.split("#")[1];
setInterval("whereat()", 50);
*/
/* JSON section - from JSON project */
if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case'string':return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}else{delete v[i];}}}}
return filter(k,v);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('parseJSON');}};}();}
