// Program to show chart type opengatem usage log in web page
// used in macupdate.html in lang(ja/en) directory
//
//  Programmed by Yoshiaki Watanabe, 2013
//  Revised by Minoru Kishira, 2013
//
// canvas.js by Satoru Takabayashi is used partially.
//  http://0xcc.net/blog/archives/canvas.js
//
// You can redistribute it and/or modify it under the terms of 
// the GNU General Public License version 2.
//

// variables
var nTime=24; // time division per day
var beginTime;
var endTime;
var cellWidth="20px";
var cellHeight="8px";
var deviceList=[]; // devices used

var colorList={0:"LimeGreen", 1:"Orange", 2:"SkyBlue", 3:"Tan", 4:"Thistle",
	 "none":"WhiteSmoke", "sunday":"Pink","saturday":"LightBlue", "blank":"white", "popup":"yellow"};
var weekString = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var today = new Date();
var weekday;
var monthday;

////////////////////////////
// make handler of mouseover
function onmouseoverHandler(element, logItemNo) {

    // save local values
    var day=monthday;
    var week=weekday;

    // return the mandler 
    return function(e) {
    
    // if log item is found, show the item as popup
    if(logItemNo[0]>=0){

		// popup style
		popup.style.position = "fixed"; 
		popup.style.left = e.clientX+20; 
		popup.style.top  = e.clientY+10; 
		popup.style.background = colorList["popup"]; 
		popup.style.display = "block";

		// popup string
		popup.innerHTML=loglist[logItemNo[0]].device +" ["+loglist[logItemNo[0]].macAddress+"]<BR>";
		for(var i=0; i<logItemNo.length; i++){
			popup.innerHTML+="Used at "+ loglist[logItemNo[i]].gateway+"<BR>"
				+"( "+loglist[logItemNo[i]].openTime+" -> "+loglist[logItemNo[i]].closeTime+" )<BR>";
			}
        }
    }
}

////////////////////////////
// make handler of mouseout
function onmouseoutHandler(element) {

    // off the display
    return function() {
        popup.style.display = "none";
    }
}

////////////////////////////
// make cells to show every date-time range
function makeCells() {

    // make html table
    var table = document.createElement("table");
    var tbody = document.createElement("tbody");
    table.border ="2px #808080 solid";

    // grouping columns (title, 0-5, 6-11, 12-17, 18-23 hours)
    table.rules ="groups";
    cgroup0=document.createElement("colgroup"); cgroup0.span=1; table.appendChild(cgroup0);
    cgroup1=document.createElement("colgroup"); cgroup1.span=6; table.appendChild(cgroup1);
    cgroup2=document.createElement("colgroup"); cgroup2.span=6; table.appendChild(cgroup2);
    cgroup3=document.createElement("colgroup"); cgroup3.span=6; table.appendChild(cgroup3);
    cgroup4=document.createElement("colgroup"); cgroup4.span=6; table.appendChild(cgroup4);

    // add header to display the hours
    tbody.appendChild(makeHeaderRow());

    // make row for each day and each device 
	var nDate=loglist["info"].dateCount;
	var nDevice=deviceList.length;
    for (var date = 0; date < nDate; date++) {
        for(var iDevice = 0; iDevice < nDevice+1; iDevice++){
            var tr = document.createElement("tr");

            // make leftmost title column spanning 6 rows
            if(iDevice==0) tr.appendChild(makeHeaderColumn(date));

            // make column representing 0 hour to 23 hour
            for (var time = 0; time < nTime; time++) {
                var td = document.createElement("td");
                setupCellProperties(td, date, time, iDevice);
                if(iDevice==nDevice) td.style.background=colorList["blank"];
                tr.appendChild(td);
            }

            tbody.appendChild(tr);
        }
    }
    table.appendChild(tbody);
    return table;
}

////////////////////////////
// make the top title row to display hours
function makeHeaderRow(){
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    tr.appendChild(td);
    for (var time = 0; time < nTime; time++) {
        var td = document.createElement("td");
        var text = document.createTextNode(time);
        td.appendChild(text);
        tr.appendChild(td);
    }
    return tr;
}

////////////////////////////
// make the leftmost title comumn spanning to all devices row
function makeHeaderColumn(date){
    var td = document.createElement("td");
	var nDevice=deviceList.length;

    td.rowSpan=nDevice+1;
    dateStr=getRealDate(date);
    var text = document.createTextNode(dateStr);
    td.appendChild(text);
    if(dateStr.indexOf(weekString[0])!=-1)
        td.style.background=colorList["sunday"];
    else if(dateStr.indexOf(weekString[6])!=-1)
        td.style.background=colorList["saturday"];
    return td;
}

////////////////////////////
// get the real date string from date number(0 means begin date)
function getRealDate(date){
    var beginTime=new Date(loglist["info"].beginTime.replace(/-/g, "/"));
    var y=beginTime.getFullYear();
    var m=beginTime.getMonth();
    var d=beginTime.getDate();
    var realDate = new Date(y, m, d+date);
    return (realDate.getMonth()+1)+"/"+realDate.getDate()+" "+ weekString[realDate.getDay()];
}

////////////////////////////
// setup cell properties
function setupCellProperties(td, date, time, iDevice){

    td.width=cellWidth; td.height=cellHeight;

    // search log for the time range;
	var logItemNo = searchLog(date, time, iDevice);

    td.onmouseover = onmouseoverHandler(td, logItemNo);
    td.onmouseout = onmouseoutHandler(td);
 
	//set background color of the cell
	//if two or more items are found, display red border
	if(logItemNo.length > 1){
		td.style.background=colorList[iDevice%5];
 		td.style.border="3px solid Red";
 	}
	// one item is found (if the item number == -1, no log is matched)
	else if(logItemNo.length == 1){
		if(logItemNo[0] == -1)  td.style.background=colorList["none"];
		else td.style.background=colorList[iDevice%5];
	}
	// no item
	else td.style.background=colorList["blank"];
}

////////////////////////////
// search the usage log corresponding to to the time range and the device number
function searchLog(date, hour, iDevice){

    var y=beginTime.getFullYear();
    var m=beginTime.getMonth();
    var d=beginTime.getDate();

    var timeRangeBegin = new Date(y, m, d+date, hour);
    var timeRangeEnd = new Date(y, m, d+date, hour+1);

    // omit the range before beginTime or after endTime
    if(timeRangeEnd < beginTime || endTime < timeRangeBegin) return -2;

    // make the week number and month/date string
    weekday=timeRangeBegin.getDay();
    monthday=timeRangeBegin.getFullYear()+"/"+(timeRangeBegin.getMonth()+1)+"/"+timeRangeBegin.getDate();

    // search the device in loglist 
    var logItemNoArray = new Array();
    
    nList=loglist["info"].listCount;
    for (var i=0; i<nList; i++){
        if(deviceList[iDevice] == loglist[i].device){

            // loglist includes '2000-10-10 00:00:00' but Date() reads '2000/10/10 00:00:00'
            var openTime = new Date(loglist[i].openTime.replace(/-/g, "/"));
            var closeTime = new Date(loglist[i].closeTime.replace(/-/g, "/"));

            // if the device is used in the time range, return the log item number
            // second line check the device not closed yet
            if(timeRangeBegin < closeTime && openTime < timeRangeEnd) logItemNoArray.push(i);
            
            if(loglist[i].closeTime=="0000-00-00 00:00:00" && openTime < timeRangeEnd) logItemNoArray.push(i);
        }
    }

    // cannot found
    if(logItemNoArray.length==0) logItemNoArray.push(-1);
    return logItemNoArray;
}

////////////////////////////
// make table for the legend of devices
function makeDevicesLegend() {

    var table = document.createElement("table");
    table.border ="2px #808080 solid";
    var tbody = document.createElement("tbody");
	var nDevice=deviceList.length;

    if(nDevice>0){
        for (var iDevice = 0; iDevice<nDevice; iDevice++) {
            var tr = document.createElement("tr");
            var td = document.createElement("td");
            td.innerHTML=deviceList[iDevice];
            tr.appendChild(td);
            var td = document.createElement("td");
            td.width=50;
            td.style.background=colorList[iDevice%5];
            tr.appendChild(td);
            tbody.appendChild(tr);
        }
    }else{
        var tr = document.createElement("tr");
        var td = document.createElement("td");
        td.innerHTML="No device is used in this period";
        tr.appendChild(td);
        tbody.appendChild(tr);
    }

    table.appendChild(tbody);
    return table;
}

////////////////////////////
// get the device names in loglist
function getDeviceList(){

    var nList=loglist["info"].listCount;
    var deviceList = new Array();
    for (var i=0; i<nList; i++){
        logItem=loglist[i];
        if(deviceList.indexOf(logItem.device)==-1){
            deviceList.push(logItem.device);
        }
    }
	return deviceList;
}

// make canvas to display usage log
function makeCanvas() {
    var canvas = document.getElementById("usagelog");
    if (canvas) {
        var cell = makeCells();
        canvas.appendChild(cell);
        var devicesLegend = makeDevicesLegend();
        canvas.appendChild(devicesLegend);
    }
}

////////////////////////////
// set up event listner
function addOnLoadEvent(func) {
  if (window.addEventListener) {
    window.addEventListener("load", func, false);
  } else if (window.attachEvent) {  // for IE
    window.attachEvent("onload", func);
  } else  {
    window.onload = func;
  }
}

////////////////////////////
// initialize
function init(){

    // get loglist info
    beginTime=new Date(loglist["info"].beginTime.replace(/-/g, "/"));
    endTime=new Date(loglist["info"].endTime.replace(/-/g, "/"));
    // get device names in loglist
    deviceList=getDeviceList();

	// set up onLoad event listner
	addOnLoadEvent(makeCanvas);
}

////////////////////////////
// startup from here
init();

