/* TurtleMessenger.js */
/* Yoshinori Hayakawa */
/* CITE, Tohoku university */
/* April 17, 2015  */


var voteCountData = null;

var httpObj = null;
var httpRequesting = false;
var httpRetryCnt = 0;

function createXMLHttpRequest(cbFunc) {
    var XMLhttpObject = null;
    try {
        XMLhttpObject = new XMLHttpRequest();
    }
    catch (e) {
        try {
            XMLhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                XMLhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                return null;
            }
        }
    }
    if (XMLhttpObject)
        XMLhttpObject.onreadystatechange = cbFunc;
    return XMLhttpObject;
}

function loadTMData() {
    var data_path = "/";

    if (httpObj == null) {
        httpObj = createXMLHttpRequest(null);
    }

    if (httpRequesting) {
        httpRetryCnt++;
        if (httpRetryCnt > 100) {
            httpRequesting = false;
            return;
        } else {
            setTimeout(loadTMData(), 10);
        }
    }
    else if (httpObj) {
        data_path = "/vote";
        if (window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
            // alert("firefox") ;
            httpObj.onload =  httpObj.onerror = httpObj.onabort = function() {
                    httpCallback();
            };
        } else {
            httpObj.onreadystatechange = function() {
                if (httpObj.readyState == 4)
                    httpCallback();
                else 
                    httpRequesting = false;
            };
        }
        httpRequesting = true;
        httpRetryCnt = 0;
        httpObj.open("GET", data_path, false);
        httpObj.send(null);
    }
}

function httpCallback() {
    // if (httpObj.readyState == 4 && httpObj.status == 200) {
    if (httpObj.status == 200) {
        voteCountData = eval("(" + httpObj.responseText + ")");
        updateVoteCount();        
    }
    httpRequesting = false;
    // dumpData(type); /* for debug */
}



function removeChildNodesOf(node) {
    for (child in node.childNodes) {
        node.removeChild(child);
    }
}


function updateVoteCount() {
    var total = 0 ;
    for (var i = 0; i < voteCountData.length; i = i + 1) {
        total = total + voteCountData[i].count;
    }
    
    var canvas = document.getElementById("circle_chart") ;
    
    if (!canvas.getContext) return ;
    
    var txt = canvas.textContent ;
    var cs = canvas.getContext('2d') ;
    var size = canvas.height ;
    
    //                      0        1       2     3        4        5       6     7        8      9 
    var chartColor = Array('black', 'brown','red','darkorange','gold','green','blue','purple','grey','lightgrey' ) ;
    
    
    var x0 = size/2 ; 
    var y0 = size/2 ;
    var rad = size/2 ;
    cs.beginPath() ;

    cs.fillStyle = "darkgrey" ;
    cs.arc(x0, y0, rad, 0, Math.PI*2.0, false) ;
    cs.fill() ;
    
    var ntotal = document.getElementById("ntotal") ;
    ntotal.innerHTML = String(total) ;
    
    var start = -Math.PI/2 ;
    var end,step ;
    for (var i = 0; i < voteCountData.length; i = i + 1) {
        var item = voteCountData[i].item;
        var count = voteCountData[i].count;
        var ncount = document.getElementById("ncount" + String(item)) ;
        ncount.innerHTML = String(count) ;
        ncount.style.color = chartColor[item] ;
        cs.beginPath() ;
        cs.fillStyle = chartColor[item] ;
        cs.moveTo(x0,y0) ;
        step = Math.PI * 2.0 * count/total ;
        end = start + step ;
        cs.arc(x0,y0,rad-1,start,end,false) ;
        cs.closePath() ;
        cs.fill() ;
        start = end ;
    }
    
    start = -Math.PI/2 ;
    cs.font = 'normal bold 12px sans-serif';
    cs.fillStyle="white";
    for (var i = 0; i < voteCountData.length; i = i + 1) {
        var item = voteCountData[i].item;
        var count = voteCountData[i].count;
        step = Math.PI * 2.0 * count/total ;
        xshift = -6.0 ;
        if (count/total > 0.1) {
            var str ;
            if (item==1) { str = "1/YES" ; xshift -= 14 ; }
            else if (item==2) { str = "2/NO" ; xshift -= 14 ; }
            else if (item==0) { str = "0/?" ; xshift -= 6 ; }
            else str = item ;
            cs.fillText(str,
                x0 + Math.cos(start+step*0.5) * rad * 0.8 + xshift, 
                y0 + Math.sin(start+step*0.5) * rad * 0.8) ;
        }
        start = start + step ;
    }
    
}


function startFetching() {
    loadTMData(); /* voting results */ 
    setTimeout("startFetching()", 2000); /* interval: 2 sec */
}
