/* TurtleMessenger.js */
/* Yoshinori Hayakawa */
/* CITE, Tohoku university */
/* July 18, 2014  */

var commentData = null;
var messageData = null;
var voteCountData = null;

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

var messageBoxList = new Array() ;

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(type) {
    var data_path = "/";

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

    if (httpRequesting) {
        httpRetryCnt++;
        if (httpRetryCnt > 100) {
            httpRequesting = false;
            return;
        } else {
            setTimeout(loadTMData(type), 10);
        }
    }
    else if (httpObj) {
        switch (type) {
            case 1:
                data_path = "/cmt";
                break;
            case 2:
                data_path = "/msg";
                break;
            case 3:
                data_path = "/vote";
                break;
            default:
                data_path = "";
                break;
        }

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

function httpCallback(type) {
    // if (httpObj.readyState == 4 && httpObj.status == 200) {
    if (httpObj.status == 200) {
        var obj = eval("(" + httpObj.responseText + ")");
        switch (type) {
            case 1:
                commentData = obj;
                updateComment();
                break;
            case 2:
                messageData = obj;
                updateMessage();
                break;
            case 3:
                voteCountData = obj;
                updateVoteCount();
                break;
            default:
                break;
        }
    }
    httpRequesting = false;
    // dumpData(type); /* for debug */
}

function dumpData(type) {
    var i, buff;
    if (type == 1) {
        buff = "<pre>";
        document.getElementById("result").innerHTML = commentData.length;
        buff += ("comment: " + String(commentData.comment) + "\n");
        buff += "</pre>"
        document.getElementById("result").innerHTML = buff;
    }
    else if (type == 2) {
        buff = "<pre>";
        document.getElementById("result").innerHTML = messageData.length;
        for (i = 0; i < messageData.length; i = i + 1) {
            // document.getElementById("result").innerHTML = i;
            buff += ("id: " + String(messageData[i].id) + "  ");
            buff += ("time: " + String(messageData[i].time) + " ");
            buff += ("nickname: " + String(messageData[i].nickname) + " ");
            buff += ("message: " + String(messageData[i].message) + "\n");
        }
        buff += "</pre>"
        document.getElementById("result").innerHTML = buff;
    }
    else if (type == 3) {
        buff = "<pre>";
        document.getElementById("result").innerHTML = voteCountData.length;
        for (i = 0; i < voteCountData.length; i = i + 1) {
            // document.getElementById("result").innerHTML = i;
            buff += ("item: " + String(voteCountData[i].item) + "  ");
            buff += ("count: " + String(voteCountData[i].count) + "\n");
        }
        buff += "</pre>"
        document.getElementById("result").innerHTML = buff;
    }
}

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

function updateComment() {
    var commentsObj = document.getElementById("comments") ;
    commentsObj.innerHTML = commentData.comment ;
}

function updateMessage() {
    var vpos=0 ;
    var msgbox,emid ;
    var messagesObj = document.getElementById("messages") ;
    if (messageData.length==0) return ;
    
    for (i = 0; i < messageData.length; i = i + 1) {
        emid = "msgbox_" + String(messageData[i].id);
        msgbox = document.getElementById(emid) ;
        if (msgbox === null) {
            msgbox = document.createElement("div");
            msgbox.id = emid;
            msgbox.className = "msgbox" ;
            msgbox.style.backgroundColor = "PowderBlue" ;
            messagesObj.appendChild(msgbox) ;
            messageBoxList[messageData[i].id] = msgbox;
            
            var h_msg=0 ;
            if (messageData[i].message.length > 0) {
                var msgbody = document.createElement("div");
                msgbody.className = "msgbody";
                msgbody.innerHTML = messageData[i].message;
                msgbox.appendChild(msgbody);
                h_msg=msgbody.clientHeight ;
            }
            
            var h_err=0 ;
            if (messageData[i].error.length>0) {
                var errmsg = document.createElement("div") ;
                errmsg.className="errbody" ;
                errmsg.innerHTML = messageData[i].error; ;
                errmsg.style.top = String(22 + h_msg + 5) + "px" ;
                msgbox.appendChild(errmsg) ;
                h_err=errmsg.clientHeight ;
            }
            
            var nickname = document.createElement("div");
            nickname.className="nickname" ;
            nickname.innerHTML = messageData[i].nickname;
            msgbox.appendChild(nickname) ;
            
            var time = document.createElement("div");
            time.className="time" ;
            time.innerHTML = messageData[i].time;
            msgbox.appendChild(time) ;
            
            msgbox.style.height = String(22 + h_msg + h_err + 5) + "px" ;
        } else {
            msgbox.style.backgroundColor = "azure" ;
        }
           
        msgbox.style.top = String(vpos) + "px" ;
        vpos = vpos + msgbox.clientHeight + 5 ;
    }
    var lastId = messageData[messageData.length-1].id ;
    
    for (id in messageBoxList) {
        if (id<lastId) {
            removeChildNodesOf(messageBoxList[id]) ;
            messagesObj.removeChild(messageBoxList[id]) ;
            delete messageBoxList[id] ;
        }
    }

}

function updateVoteCount() {
    var total = 0 ;
    for (var i = 0; i < voteCountData.length; i = i + 1) {
        total = total + voteCountData[i].count;
    }
    
    var ntotal = document.getElementById("ntotal") ;
    ntotal.innerHTML = String(total) ;
    
    //                      0        1       2     3        4        5       6     7        8      9 
    var chartColor = Array('black', 'brown','red','darkorange','gold','green','blue','purple','grey','lightgrey' ) ;
    
    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)) ;
        var bar = document.getElementById("bar" + String(item)) ;
        ncount.innerHTML = String(count) ;
        ncount.style.color = chartColor[item] ;
        if (item==9) bar.style.color="darkgrey" ;
        else bar.style.color="lightgrey" ;
        // bar.style.color="lightgrey" ;
        bar.style.backgroundColor=chartColor[item] ;
        // bar.style.backgroundColor="grey" ;
        bar.style.display="block" ;
        bar.style.position="relative" ;
        if (count>0) {
            bar.innerHTML=String(Math.floor(count/total*100.0)) + "%" ;
        } else {
            bar.innerHTML="" ;
        }
        if (total>0) {
            bar.style.width=String(count/total*100) + "%" ;
        } else {
            bar.style.width="0%" ;
        }
    }
}


function startFetching() {
    loadTMData(1); /* comments */   
    loadTMData(2); /* messages */
    loadTMData(3); /* voting results */ 
    setTimeout("startFetching()", 10000); /* interval: 10 sec */
}
