var imgPreload = new Array();

function addLoadListener(fn) {
    if (typeof window.addEventListener != 'undefined')
        window.addEventListener('load', fn, false);
    else if (typeof document.addEventListener != 'undefined')
        document.addEventListener('load', fn, false);
    else if (typeof window.attachEvent != 'undefined')
        window.attachEvent('onload', fn);
    else {
        var oldfn = window.onload;
        if (typeof window.load != 'function')
            window.onload = fn;
        else {
            window.onload = function() {
                oldfn();
                fn();
            };
        }
    }
}

function attachEventListener(target, eventType, funcRef) {
    var capture = false;
    if (typeof target.addEventListener != 'undefined')
        target.addEventListener(eventType, funcRef, capture);
    else if (typeof target.attachEvent != 'undefined') {
        var fstr = eventType + funcRef;
        target["e"+ fstr] = funcRef;
        target[fstr] = function(event) {
            if (typeof event == 'undefined')
                event = window.event;
            target["e"+ fstr](event);
        };
        target.attachEvent("on"+ eventType, target[fstr]);
    }
    else {
        eventType = "on"+ eventType;
        if (typeof target[eventType] == 'function') {
            var oldListener = target[eventType];
            target[eventType] = function() {
                oldListener();
                return funcRef();
            };
        }
        else
            target[eventType] = funcRef;
    }
}

function detachEventListener(target, eventType, funcRef) {
    var capture = false;
    if (typeof target.removeEventListener != 'undefined')
        target.removeEventListener(eventType, funcRef, capture);
    else if (typeof target.detachEvent != 'undefined') {
        var fstr = eventType + funcRef;
        target.detachEvent("on"+ eventType, target[fstr]);
        target["e"+ fstr] = null;
        target[fstr] = null;
    }
    else target["on"+ eventType] = null;
}

function getElementsByAttribute(attr, attrValue) {
    var elems = new Array();
    var matches = new Array();
    if (document.all)
        elems = document.all;
    else
        elems = document.getElementsByTagName("*");
    for (var i = 0; i < elems.length; i++) {
        if (attr == "class") {
            var pattern = new RegExp("(^| )"+ attrValue +"( |$)");
            if (pattern.test(elems[i].className))
                matches[matches.length] = elems[i];
        }
        else if (attr == "for") {
            if (elems[i].getAttribute("htmlFor") || elems[i].getAttribute("for")) {
                if (elems[i].htmlFor == attrValue)
                    matches[matches.length] = elems[i];
            }
        }
        else if (elems[i].getAttribute(attr) == attrValue)
            matches[matches.length] = elems[i];
    }
    return matches;
}

function hasClass(elem, cls) {
    var p = new RegExp("(^| )"+ cls +"( |$)");
    if (p.test(elem.className)) return true;
    else return false;
}

function addClass(target, cls) {
    var pattern = new RegExp("(^| )"+ cls +"( |$)");
    if (!pattern.test(target.className)) {
        if (target.className == "")
            target.className = cls;
        else
            target.className += " "+ cls;
    }
    return true;
}

function removeClass(target, cls) {
    var cls2 = target.className;
    var pattern = new RegExp("(^| )"+ cls +"( |$)");
    cls2 = cls2.replace(pattern, "$1");
    cls2 = cls2.replace(/ $/, "");
    target.className = cls2;
    return true;
}

function getEventTarget(event) {
    var t = null;
    if (typeof event.target != 'undefined')
        t = event.target;
    else
        t = event.srcElement;
    while (t.nodeType == 3 && t.parentNode != null)
        t = t.parentNode;
    return t;
}

function stopDefaultAction(event) {
    event.returnValue = false;
    if (typeof event.preventDefault != 'undefined')
        event.preventDefault();
}

function randomBetween(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

function imagePreload(imgs) {
    if (document.images) {
        for (var i = 0; i < imgs.length; i++) {
            var im = new Image();
            im.src = imgs[i];
            imgPreload[imgPreload.length] = im;
        }
        return true;
    }
    else
        return false;
}

var	g_ajax = new c_ajax;

function c_ajax() {};

c_ajax.prototype.GetNewRequestObject = function() {
	/*@cc_on @*/
	
	/*@if (@_jscript_version >= 5)
		try {
			this.dreqobj = new ActiveXObject("Msxml2.XMLHTTP");
			}
		catch (e) {
			try {
				this.dreqobj = new ActiveXObject("Microsoft.XMLHTTP");
				}
			catch (e2) {
				this.dreqobj = false;
				}
			}
	@end @*/
	
	if ( !this.dreqobj && (typeof XMLHttpRequest != 'undefined') )
		this.dreqobj = new XMLHttpRequest();
};

c_ajax.prototype.dreqobj=null;
c_ajax.prototype.dcbfunc=null;
c_ajax.prototype.dparm=null;
c_ajax.prototype.dpcb_func=null;
c_ajax.prototype.dparm2=null;
c_ajax.prototype.dphase=0;
c_ajax.prototype.dq=new Array();
c_ajax.prototype.dq_state=true;
c_ajax.prototype.dcommitted=false;
c_ajax.prototype.dpre_q_in_url=null;
c_ajax.prototype.dpre_q_in_cb=null;
c_ajax.prototype.dpre_q_in_method=null;
c_ajax.prototype.dpre_q_in_p=null;
c_ajax.prototype.dpre_q_in_pcb=null;
c_ajax.prototype.dpre_q_in_p2=null;
c_ajax.prototype.dpre_queue_in_c2_phase=0;

c_ajax.prototype.QueueFlush = function() {
	this.dq = new Array();
	this.QueueResume();
}

c_ajax.prototype.QueuePause = function() {
	this.dq_state = false;
}

c_ajax.prototype.QueueResume = function() {
	this.dq_state = true;
	this.Dequeue();
}

c_ajax.prototype.QueueInterrupt = function(in_url, in_cb, in_method, in_p, in_pcb, in_p2, in_phase) {
	var url = in_url;
	this.dcbfunc = in_cb;
	var method = in_method;
	this.dparm = in_p;
	this.dpcb_func = in_pcb;
	this.dparm2 = in_p2;
	this.dphase = in_phase;
	if (url && method)
		ret = this._CallXMLHTTPObject (url, method);
	return ret;
}

c_ajax.prototype.QueueInject = function (in_url, in_cb, in_method, in_p, in_pcb, in_p2, in_phase) {
	this.dq_state = false;
	for (var cnt = this.dq.length; cnt > 0; cnt--)
		this.dq[cnt] = this.dq[cnt - 1];
	this.dq[0] = new Array(in_url, in_cb, in_method, in_p, in_pcb, in_p2, in_phase);
	this.dq_state = true;
}

c_ajax.prototype.CallXMLHTTPObjectGET = function(in_url, in_cb) {
	return this.CallXMLHTTPObject(in_url, in_cb, "GET", null, null, 0);
}

c_ajax.prototype.CallXMLHTTPObjectGETParam = function(in_url, in_cb, in_p) {
	return this.CallXMLHTTPObject(in_url, in_cb, "GET", in_p, null, 0);
}

c_ajax.prototype.CallXMLHTTPObjectGETParamPartial = function(in_url, in_cb, in_p, in_pcb, in_p2) {
	return this.CallXMLHTTPObject(in_url, in_cb, "GET", in_p, in_pcb, in_p2, 0);
}

c_ajax.prototype.CallXMLHTTPObjectGETParamPartialPhase = function(in_url, in_cb, in_p, in_pcb, in_p2, in_phase) {
	return this.CallXMLHTTPObject(in_url, in_cb, "GET", in_p, in_pcb, in_p2, in_phase);
}

c_ajax.prototype.CallXMLHTTPObjectPOST = function(in_url, in_cb) {
	return this.CallXMLHTTPObject(in_url, in_cb, "POST", null, null, 0);
}

c_ajax.prototype.CallXMLHTTPObjectPOSTParam = function(in_url, in_cb, in_p) {
	return this.CallXMLHTTPObject(in_url, in_cb, "POST", in_p, null, 0);
}

c_ajax.prototype.CallXMLHTTPObjectPOSTParamPartial = function(in_url, in_cb, in_p, in_pcb, in_p2) {
	return this.CallXMLHTTPObject(in_url, in_cb, "POST", in_p, in_pcb, in_p2, 0);
}

c_ajax.prototype.CallXMLHTTPObjectPOSTParamPartialPhase = function(in_url, in_cb, in_p, in_pcb, in_p2, in_phase) {
	return this.CallXMLHTTPObject(in_url, in_cb, "POST", in_p, in_pcb, in_p2, in_phase);
}

c_ajax.prototype.CallXMLHTTPObject = function(in_url, in_cb, in_method, in_p, in_pcb, in_p2, in_phase) {
	this.dpre_q_in_url=in_url;
	this.dpre_q_in_cb=in_cb;
	this.dpre_q_in_method=in_method;
	this.dpre_q_in_p=in_p;
	this.dpre_q_in_pcb=in_pcb;
	this.dpre_q_in_p2=in_p2;
	this.dpre_queue_in_c2_phase=in_phase;
	if ((this.dpre_queue_in_c2_phase < 1) || (this.dpre_queue_in_c2_phase > 3))
		this.dpre_queue_in_c2_phase = 3;
	this.Enqueue();
	return true;
};

c_ajax.prototype.Enqueue = function() {
	this.dq[this.dq.length] = new Array(this.dpre_q_in_url, this.dpre_q_in_cb,
		this.dpre_q_in_method, this.dpre_q_in_p, this.dpre_q_in_pcb,
		this.dpre_q_in_p2, this.dpre_queue_in_c2_phase);
	this.dpre_q_in_url=null;
	this.dpre_q_in_cb=null;
	this.dpre_q_in_method=null;
	this.dpre_q_in_p=null;
	this.dpre_q_in_pcb=null;
	this.dpre_q_in_p2=null;
	this.dpre_queue_in_c2_phase=0;
	if (!this.dreqobj)
		this.Dequeue();
};

c_ajax.prototype.Dequeue = function() {
	var cmd = null;
	var ret=false;
	if (this.dq.length && this.dq_state) {
		cmd = this.dq[0];
		var url = cmd[0];
		this.dcbfunc = cmd[1];
		var method = cmd[2];
		this.dparm = cmd[3];
		this.dpcb_func = cmd[4];
		this.dparm2 = cmd[5];
		this.dphase = cmd[6];
		for (var cnt = 1; cnt < this.dq.length; cnt++)
			this.dq[cnt - 1] = this.dq[cnt];
		this.dq.length = cnt - 1;
	}
	if (url && method)
		ret = this._CallXMLHTTPObject(url, method);
	return ret;
};

c_ajax.prototype._CallXMLHTTPObject = function(in_url, in_method) {
	try {
		var sVars = null;
		if (in_method == "POST") {
			var rmatch = /^([^\?]*)\?(.*)$/.exec(in_url);
			in_url = rmatch[1];
			sVars = unescape(rmatch[2]);
		}
		this.dcommitted = false;
		this.GetNewRequestObject();
		this.dreqobj.open(in_method, in_url, true);
		if (in_method == "POST") {
            this.dreqobj.setRequestHeader("Method", "POST "+in_url+" HTTP/1.1");
            this.dreqobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}
		this.dreqobj.onreadystatechange = hndlFunc;
		this.dreqobj.send(sVars);
		return true;
	}
	catch(z) {}
	return false;
};

function hndlFunc() {
	var ie = navigator.appName=='Microsoft Internet Explorer';
	if (g_ajax && g_ajax.dreqobj) {
		if (g_ajax.dreqobj.readyState == 0) {}
		else {
			if (g_ajax.dreqobj.readyState == 1) {
				if (g_ajax.dphase == g_ajax.dreqobj.readyState) {
					if (g_ajax.dpcb_func) {
						var resp;
						if(!ie && g_ajax.dreqobj.responseText)
							resp=g_ajax.dreqobj.responseText;
						g_ajax.dpcb_func(resp, g_ajax.dparm2 ? g_ajax.dparm2 : g_ajax.dparm);
					}
				}
			}
			else {
				if (g_ajax.dreqobj.readyState == 2) {
					if (g_ajax.dphase == g_ajax.dreqobj.readyState) {
						if (g_ajax.dpcb_func) {
							var resp;
							if(!ie && g_ajax.dreqobj.responseText)
								resp=g_ajax.dreqobj.responseText;
							g_ajax.dpcb_func(resp, g_ajax.dparm2 ? g_ajax.dparm2 : g_ajax.dparm);
						}
					}
				}
				else {
					if (g_ajax.dreqobj.readyState == 3) {
						g_ajax.dcommitted = true;
						if (g_ajax.dphase == g_ajax.dreqobj.readyState) {
							if (g_ajax.dpcb_func) {
								var resp;
								if(!ie && g_ajax.dreqobj.responseText)
									resp=g_ajax.dreqobj.responseText;
								g_ajax.dpcb_func(resp, g_ajax.dparm2 ? g_ajax.dparm2 : g_ajax.dparm);
							}
						}
					}
					else {
						if (g_ajax.dreqobj.readyState == 4) {
							g_ajax.dcbfunc(g_ajax.dreqobj.responseText, g_ajax.dparm, g_ajax.dparm2);
							g_ajax.dreqobj = null;
							g_ajax.dcommitted = false;
							g_ajax.dphase = 0;
							g_ajax.Dequeue();
						}
					}
				}
			}
		}
	}
    return true;
};

if (typeof SupportsAjax == 'undefined'){
	function SupportsAjax() {
		var test_obj = new c_ajax;
		test_obj.GetNewRequestObject();
		if ( test_obj.dreqobj ) {
			test_obj.dreqobj = null;
			test_obj = null;
			return true;
		}
		test_obj = null;
		return false;
	};
}

function SimpleAJAXCall(in_uri, in_cb, in_method, in_p ) {
	if ((typeof in_method == 'undefined') || ((in_method != 'GET')&&(in_method != 'POST')))
		in_method = 'GET';
	in_method = in_method.toUpperCase();
	if (SupportsAjax() && (typeof in_uri != 'undefined') && in_uri && (typeof in_cb == 'function')) {
		if ( in_method == 'POST' )
			return g_ajax.CallXMLHTTPObjectPOSTParam(in_uri, in_cb, in_p);
		else
			return g_ajax.CallXMLHTTPObjectGETParam(in_uri, in_cb, in_p);
	} 
    else
        return false;
};

var polldiv = new Array();
var divbars = new Array();
var barpct  = new Array();
var divsize = new Array();
var cursize = new Array();
//these two lines preload the bar image, although it would be rad if we didn't have to hardcode it here =/
var prld = new Image();
prld.src = '/img/pollbar.gif';

function initPolls() {
    var polls = getElementsByAttribute("class", "gotopoll");

    for (var i = 0; i < polls.length; i++) {
        var frm = polls[i].getElementsByTagName("form")[0];
        var btn = frm['btn'];
        attachEventListener(btn, 'click', showResults);
        var ht = polls[i].offsetHeight;
        polls[i].style.height = (ht - 16) +"px";
    }
}
//addLoadListener(initPolls);

function triggerPoll() {
    showResultsForPoll(getElementsByAttribute("class", "gotopoll")[0]);
}

function showResults(event) {
    if (typeof event == 'undefined')
        event = window.event;


    showResultsForPoll(getEventTarget(event).parentNode.parentNode);
}

function showResultsForPoll(target) {
    if (typeof target == 'undefined' || !hasClass(target, "gotopoll"))
        return false;
    var pollnum = polldiv.length;
    polldiv[pollnum] = target;
    
    //hide the button
    var frm = target.getElementsByTagName("form")[0];
    if (typeof frm['btn'] != 'undefined')
        frm['btn'].style.display = 'none';

    //hide the pollnote
    var divs = target.getElementsByTagName("div");
    var plswaitexist = false;
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].className == 'pollnote')
            divs[i].style.display = 'none';
        if (divs[i].className == 'pls')
            plswaitexist = true;
    }

    //show a "please wait"
    if (!plswaitexist) {
        var plsdiv = document.createElement("div");
        plsdiv.appendChild(document.createTextNode("Please wait..."));
        addClass(plsdiv, "pls");
        target.appendChild(plsdiv);
    }

    //get the pollkey
    var pollkey = frm['poll_key'].value;

    //get the selectedanswer
    var answ = '';
    if (typeof frm['ans'] != 'undefined') {
        for (var i = 0; i < frm['ans'].length; i++) {
            if (frm['ans'][i].checked)
                answ = frm['ans'][i].value;
        }
    }

    //make ajax call
    g_ajax.CallXMLHTTPObjectPOSTParam('/pollvote.php?poll_key='+ pollkey +'&answer='+ answ, pollCallback, pollnum);
}

function pollCallback(in_text, pollnum) {
    var target = polldiv[pollnum];
    if (in_text.substring(0, 7) != "SUCCESS") {
        var vals = in_text.split(',');
        var ansdiv = target.getElementsByTagName("div");
        for (var i = 0; i < ansdiv.length; i++) {
            if (ansdiv[i].className == "pls")
                ansdiv[i].innerHTML = 'ERROR: '+ vals[1];
        }
        return;
    }
    var vals = in_text.split(',');
    var pct = new Array();
    var multfactor = 0;
    for (var i = 2; i < vals.length; i++) {
        pct[i-2] = Math.round(100 * parseInt(vals[i], 10) / parseInt(vals[1], 10));
        if (pct[i-2] > multfactor)
            multfactor = pct[i-2];
    }
    multfactor = (target.offsetWidth - 60) / multfactor;

    target.style.height = 'auto';
    
    var ansdiv = target.getElementsByTagName("div");
    for (var i = 0; i < ansdiv.length; i++) {
        clearDiv(ansdiv[i]);
        if (ansdiv[i].className == "pls") // set it to display votes taken
            ansdiv[i].innerHTML = 'Total Votes: '+ vals[1];
    }

    var spans = target.getElementsByTagName("span");
    for (var i = 0; i < spans.length; i++) {
        if (typeof spans[i].style.styleFloat != 'undefined')
            spans[i].style.styleFloat = "none";
        else
            spans[i].style.cssFloat = "none";
        spans[i].style.display = "block";
        addClass(spans[i], 'shrink');
    }

    //set a placeholder in the arrays
    var quiznum = divbars.length;
    divbars[quiznum] = new Array();
    barpct[quiznum]  = pct;
    divsize[quiznum] = new Array();
    cursize[quiznum] = new Array();

    var barcnt = 0;
    for (var i = 0; i < ansdiv.length; i++) {
        var tmp = addBar(ansdiv[i]);
        if (tmp) {
            divbars[quiznum][barcnt] = tmp;
            divsize[quiznum][barcnt] = Math.round(pct[barcnt] * multfactor);
            cursize[quiznum][barcnt] = 30;
            barcnt++;
        }
    }

    growBars(quiznum);
}

function clearDiv(dv) {
    if (dv.className == "ans") {
        var inp = dv.getElementsByTagName("input")[0];
        if (typeof inp != 'undefined')
            dv.removeChild(inp);
    }
}

function addBar(dv) {
    if (dv.className == "ans") {
        var divbar = document.createElement("div");
        addClass(divbar, "bar");
        var chld = document.createElement("div");
        chld.appendChild(document.createTextNode("-"));
        addClass(chld, "pct");
        divbar.appendChild(chld);
        return dv.appendChild(divbar);
    }
    else
        return false;
}

function growBars(quiznum) {
    var bars = divbars[quiznum];
    var ln = bars.length;
    var stop = true;
    for (var i = 0; i < ln; i++) {
        cursize[quiznum][i] += 4;
        var cur = cursize[quiznum][i];
        if (cur < (divsize[quiznum][i] +30)) {
            bars[i].style.width =  cur +"px";
            stop = false;
        }
    }
    if (!stop)
        setTimeout("growBars("+ quiznum +")", 25);
    else {
        for (var i = 0; i < ln; i++)
            bars[i].getElementsByTagName("div")[0].innerHTML = barpct[quiznum][i] +"%";
    }
}


