﻿function jspoll(strVotes1, tblid) {
    this.value = "";
    this.checkbox = "";
    this.tbl = document.getElementById(tblid);
    this.votes = new Array();
    this.arrColor = new Array("green", "red", "blue", "gray");
    this.total = 0;
    this.strVotes = strVotes1;

    this.click = function() {
        this.getvotessofar();
        this.iterate(this.tbl);
        if (this.value == "") {
            this.invalid();
        }
        else {
            this.castvote();
            this.displayresults();
        }
    }

    this.castvote = function() {
        var vote = parseInt(this.value)
        this.votes[vote - 1] += 1
        this.total += 1;
        var voteimage = new Image();
        var strurl = "/Polls/CastVote.aspx?Vote=" + this.checkbox;
        voteimage.src = strurl;
    }

    this.getvotessofar = function() {
        var arrstrVotes;
        arrstrVotes = this.strVotes.split(",");
        var intcount;
        for (intcount = 0; intcount < arrstrVotes.length; intcount++) {
            this.votes[intcount] = parseInt(arrstrVotes[intcount]); //
            this.total += this.votes[intcount];
        }
    }

    this.displayresults = function() {
        this.tbl.rows[this.tbl.rows.length - 1].cells[0].innerHTML = "";
        var intcount;
        for (intcount = 0; intcount < this.votes.length; intcount++) {
            this.displayrow(this.tbl.rows[intcount], this.votes[intcount], this.total, this.arrColor[intcount]);
        }
    }

    this.displayrow = function(tblrow, value1, total1, strColor) {
        tblrow.cells[0].style.borderRight = "solid 1px white";
        tblrow.cells[1].style.padding = "2px 0px 2px 0px";
        tblrow.cells[1].innerHTML = "<div style='float:left;margin:0px;padding:0px;background-color:" + strColor + ";width:" + Math.floor(150 * value1 / total1) + "px'>&nbsp;</div>&nbsp;" + Math.floor(100 * value1 / total1) + "%";
    }

    this.invalid = function() {
        window.alert("you must select a choice before you can vote");
    }

    this.iterate = function(objelem) {
        var intcount;
        for (intcount = 0; intcount < objelem.childNodes.length; intcount++) {
            if (objelem.childNodes[intcount].tagName == "INPUT" && objelem.childNodes[intcount].id.search("radyesno") > -1) {
                if (objelem.childNodes[intcount].checked == true) {
                    this.value = objelem.childNodes[intcount].value;
                    this.checkbox = objelem.childNodes[intcount].id;
                }
            }
            if (objelem.childNodes[intcount].childNodes.length > 0) {
                this.iterate(objelem.childNodes[intcount]);
            }
        }
    }

}

function poll(strVotes, strID) {
    var objpoll = new jspoll(strVotes, strID);
    objpoll.click();
}