﻿var canvas;
var rgraph;

// 날짜별 추가 그래프 요소 정리 객체
var graph_ts = {};

var attend_data  = [];
var attend_count = [];

var plot_color = ["rgb(63,63,223)","rgb(223,63,63)","rgb(63,223,63)","rgb(191,191,223)","rgb(255,255,63)","rgb(95,95,95)"];

// 릴레이 시작 및 종료일
var startday = 6;
var endday   = 26;

var currentday = 0;
var t;

var Log = {
    elem: false,
    write: function(text) {
        if (!this.elem) 
            this.elem = document.getElementById('log');
        this.elem.innerHTML = text;
        this.elem.style.left = (700 - this.elem.offsetWidth / 2) + 'px';
    }
};

function startRelay() {
	canvas.clear();
	initRGraph();
	rgraph.fx.clearLabels();
	currentday = startday;
	
	for (var i=0; i<6; i++) {
		attend_data[i] = [];
		attend_count[i] = 0;
	}
	
	step();
}

function stopRelay() {
	clearTimeout(t);
	currentday = 0;
}

function recordAttendData(addgraph) {
	if (addgraph != null) {
		for (var i=0; i<addgraph.length; i++) {
			switch (addgraph[i].data.platform) {
				case "텍스트큐브":
					attend_count[0] ++;
				case "티스토리":
					attend_count[1] ++;
				case "네이버":
					attend_count[2] ++;
				case "이글루스":
					attend_count[3] ++;
				case "미투데이":
					attend_count[4] ++;
				default:
					attend_count[5] ++;
					break;
			}
		}
	}
	for (var j=0; j<attend_count.length; j++) {
		attend_data[j].push( [currentday-startday, attend_count[j]] );
	}
}

function step() {
	if (graph_ts["2009-06-"+dateStr(currentday)] !== undefined) {
		var addgraph = graph_ts["2009-06-"+dateStr(currentday)];
		recordAttendData(addgraph);
		if (currentday != startday) {
			for (var i=0; i<addgraph.length; i++)
				rgraph.graph.addNode(addgraph[i]);
			
			for (var j=0; j<addgraph.length; j++) {
				for (var k=0, adj=addgraph[j].adjacencies; k<adj.length; k++) {
					var node = adj[k], data;
					if (typeof adj[k] != 'string') {
						data = node.data;
						node = node.nodeTo;
					}
					rgraph.graph.addAdjacence(addgraph[j], rgraph.graph.getNode(node), data);
				}
			}
		}
	} else {
		recordAttendData(null);
	}
	// 현재 진행 날짜 표시
	Log.write("2009년 6월 "+currentday+"일");
	rgraph.compute();
	// 왜 그런지는 모르겠으나 두 번 실행시켜줘야 제대로 나옴
	rgraph.plot();
	rgraph.plot();
	
	//alert(''+attend_data[5].length);
	
	var dopts = [];
	var mx = attend_count.length-1;
	for (var n=0; n<=mx; n++) {
		dopts[n] = {};
		dopts[n].data  = attend_data[mx-n];
		dopts[n].color = plot_color[mx-n];
		dopts[n].shadowSize = 0;
		dopts[n].lines = { show:false, fill:1, fillColor: plot_color[mx-n] };
	}
	$.plot( $("#graph-holder"), dopts, {
		xaxis: {
			tickFormatter: function (v, axis) {
				if (v%1 > 0.001 || v<0)
					return '';
				else
					return 'D+'+v.toFixed(0);
			}
		}
	});
	/*
	$.plot( $("#graph-holder"), [
	{
		data: attend_data[5],
		lines: { show: true }
	}
	]); */
	
	for (var e=0; e<attend_count.length; e++) {
		var html = '';
		if (e!=0)
			html += (attend_count[e]-attend_count[e-1]).toFixed(0);
		else
			html += attend_count[e].toFixed(0);
		document.getElementById('count'+e).innerHTML = html;
		document.getElementById('count'+e).style.color = plot_color[e];
		document.getElementById('count'+e).style.fontWeight = 'bold';
	}
	
	// 1.5초마다 업데이트
	if (currentday++ < endday) {
		t = setTimeout("step()",1500);
	} else
		clearTimeout(t);
}

function init() {
	for (var i=0; i<json.length; i++) {
		node = json[i];
		if (graph_ts[node.data.postdate] === undefined)
			graph_ts[node.data.postdate] = [];
		graph_ts[node.data.postdate].push(node);
	}

	initCanvas();
	initRGraph();
}

function initCanvas() {
    var infovis = document.getElementById('infovis');
    var w = infovis.offsetWidth, h = infovis.offsetHeight;
    
    //init canvas
    //Create a new canvas instance.
    canvas = new Canvas('mycanvas', {
        //Where to append the canvas widget
        'injectInto': 'infovis',
        'width' : w,
        'height': h,
        
        //Optional: create a background canvas and plot
        //concentric circles in it.
        'backgroundCanvas': {
            'styles': {
                'strokeStyle': '#333'
            },
            'impl': {
                'init': function(){},
				// 가이드 원주를 그리고 싶다면
				'plot': function(canvas, ctx){
                    var times = 15, d = 24;
                    var pi2 = Math.PI * 2;
                    for (var i = 1; i <= times; i++) {
                        ctx.beginPath();
                        ctx.arc(0, 0, i * d, 0, pi2, true);
                        ctx.stroke();
                        ctx.closePath();
                    }
                }
            }
        }
    });
}

function initRGraph() {
    rgraph = new RGraph(canvas, {
		levelDistance: 12,
		
        //Set Node and Edge colors.
        Node: {
			overridable: true,
            color: '#CDE'
        },
        
        Edge: {
			overridable: true,
			type: 'line',
            color: '#727',
			lineWidth: 1
        },
		
		onBeforePlotNode: function(node){
			var pDate = parseInt(node.data.postdate.substr(8,2));
			if (pDate <= currentday) {
				if (node.data.platform == "네이버") {
					node.data.$type = 'square';
					node.data.$color = '#0C0';
				} else if (node.data.platform == "티스토리") {
					node.data.$type = 'circle';
					node.data.$color = '#C00';
				} else if (node.data.platform == "이글루스") {
					node.data.$type = 'star';
					node.data.$color = '#FFF';
					node.data.$dim = 5;
				} else if (node.data.platform == "텍스트큐브") {
					node.data.$type = 'square';
					node.data.$color = '#00F';
				} else if (node.data.platform == "미투데이") {
					node.data.$type = 'triangle';
					node.data.$color = '#FF0';
				} else {
					node.data.$type = 'circle';
					node.data.$color = '#CDE';
				}
			} else {
				node.data.$type='none';
			}
        },		
		onBeforePlotLine: function(adj) {
			var pDate = parseInt(adj.nodeFrom.data.postdate.substr(8,2));
			var qDate = parseInt(adj.nodeTo.data.postdate.substr(8,2));
			if (pDate <= currentday && qDate <= currentday) {
				adj.data.$type='line';
			} else {
				adj.data.$type='none';
			}
		}
    });
	
	rgraph.loadJSON(graph_ts["2009-06-"+dateStr(startday)], 0);
    //compute positions and make the first plot
    rgraph.refresh();
    //end
    //append information about the root relations in the right column
    rgraph.controller.onBeforeCompute(rgraph.graph.getNode(rgraph.root));
    rgraph.controller.onAfterCompute();
}

function addEvent(obj, type, fn) {
    if (obj.addEventListener) obj.addEventListener(type, fn, false);
    else obj.attachEvent('on' + type, fn);
}

function dateStr(dateInt) {
	if (dateInt < 10)
		return "0"+dateInt.toString();
	else
		return dateInt.toString();
}

