﻿function anigraph_addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function agdebug(id,string) {
	var debugspan = document.getElementById(id+"_debug");
	//debugspan=0; //Override
	if (debugspan) {
		debugspan.innerHTML += string+"<br/>";
	}
	return false;
}

function isString(a) {
    return typeof a == 'string';
}

function resizeFrame(f) {
	f = document.getElementById(f);
	if (f) {
		f.style.height = (f.contentWindow.document.body.scrollHeight+10) + "px";
		//f.style.width = (f.contentWindow.document.body.scrollWidth+10) + "px";
	}
}

function ag_unfilter_chars(str) {
	str = str.replace("{col}",":");
	str = str.replace("{scol}",";");
	str = str.replace("{comma}",",");
	return str;
}

function anigraph_draw(id,width,height,datastring,offset,highlight) {
	//id is id of canvas
	//width height of canvas
	//datastring follows format seriesname:160,170;seriesname2:110,145
	
	var replacepng = true;
	//var replacepng = false;
	
	agdebug(id,"data: "+datastring);
	offset = parseInt(offset);
	
	var hl = {enable:false, id:false, marks:false, color:false};
	if (highlight!=0) { 
		hl['enable']=true;
		hl['id']=highlight;
		//alert('Highlight: '+hl['id'])
	}

	var colors = [
		"#F00","#0F0","#00F",
		"#0FF","#F0F","#DD0",
		"#F77","#7F7","#77F",
		"#7FF","#F7F","#FF7",
		"#07F","#70F","#7F0",
		"#0F7","#F07","#F70",
	];
	
	//var 
	var series = [];
	var drawnum = {};
	if (datastring.match(";")) {
		series = datastring.split(";");
	} else {
		series = [datastring];
	}
	var seriesnames = Array();
	var seriesslugs = Array();
	var seriesmarks = Array();
	var alertdebug = 0;
	max_eplength=0;
	for (var i in series) {
		if (isString(series[i])) {
			this_series_slug=series[i].replace(/\{(.*)\}.*/,"$1");
			this_series_rest=series[i].replace(/\{.*\}(.*)/,"$1");
			this_series=this_series_rest.split(":");
			seriesslugs[i]=this_series_slug;
			seriesnames[i]=this_series[0];
			seriesmarks[i]=this_series[1].split(",");
			//agdebug(id,"series name: "+this_series[0]);
			//agdebug(id,"series name: "+this_series[1]);
			if (seriesmarks[i].length>max_eplength) { max_eplength=seriesmarks[i].length; }
		}
	}
	agdebug(id,"max_eplength: "+max_eplength);
	
	drawnum['classbox'] = 20;
	drawnum['episodenum'] = 15;
	drawnum['right'] = 25;
	//classbox_margin = 20;
	//episodenum_margin = 15;
	//right_margin=25;
	
	drawnum['sqlength']=(height-drawnum['episodenum'])/6;
	drawnum['sqborder']=1;
	drawnum['coredist']=drawnum['sqlength']/3;
	starpos = Array();
	starpos['ex'] = drawnum['episodenum']+(0*drawnum['sqlength'])+(drawnum['sqlength']/2);
	starpos['s'] = drawnum['episodenum']+(1*drawnum['sqlength'])+(drawnum['sqlength']/2);
	starpos['a'] = drawnum['episodenum']+(2*drawnum['sqlength'])+(drawnum['sqlength']/2);
	starpos['b'] = drawnum['episodenum']+(3*drawnum['sqlength'])+(drawnum['sqlength']/2);
	starpos['c'] = drawnum['episodenum']+(4*drawnum['sqlength'])+(drawnum['sqlength']/2);
	starpos['t'] = drawnum['episodenum']+(5*drawnum['sqlength'])+(drawnum['sqlength']/2);
	starcol = Array();
	starcol['ex'] = "#ff947f";
	starcol['s'] = "#ffbb7f";
	starcol['a'] = "#e9e502";
	starcol['b'] = "#7fe8ff";
	starcol['c'] = "#7f82ff";
	starcol['t'] = "#ac7fff";
	
	drawnum['xpos_mult'] = (width-drawnum['classbox']-drawnum['right'])/max_eplength;
	drawnum['ypos_mult'] = (height-drawnum['coredist']-drawnum['episodenum'])/170;
	
	class_font_size=(drawnum['sqlength']/7);
	if (class_font_size>(drawnum['classbox']*60/100)) class_font_size=(drawnum['classbox']*60/100);
	epnum_font_size=(width-drawnum['classbox'])/(max_eplength*1.5);
	if (epnum_font_size>14) epnum_font_size=14;
	
	agdebug(id,"xpos_mult: "+drawnum['xpos_mult']);
	agdebug(id,"ypos_mult: "+drawnum['ypos_mult']);
	
	var canvas = document.getElementById(id);
	var divcontainer = document.getElementById(id+"_div");
	if (canvas) {
		if (canvas.getContext){  
			var ctx = canvas.getContext('2d');  
			// drawing code here
			
			//DRAW BASE GRAPH
			
			ctx.fillStyle = '#FFF'; ctx.fillRect(0,0,width,height);
			
			//CLASS LINES
			ctx.strokeStyle = '#f1f585'; 
			ctx.lineWidth = 1;
			ctx.lineCap = 'butt';
			ctx.beginPath();
			for (var i in starpos) {
				ctx.moveTo(0,starpos[i]-drawnum['coredist']); ctx.lineTo(width,starpos[i]-drawnum['coredist']);
				ctx.moveTo(0,starpos[i]+drawnum['coredist']); ctx.lineTo(width,starpos[i]+drawnum['coredist']);
			}
			ctx.stroke();
			ctx.lineWidth = 2;
			ctx.beginPath();
			for (var i in starpos) {
				ctx.moveTo(0,starpos[i]); ctx.lineTo(width,starpos[i]);
			}
			ctx.stroke();
			
			//CLASS SQUARES
			j=0;
			for (var i in starpos) {
				ctx.fillStyle = starcol[i];
				ctx.fillRect(drawnum['sqborder'],drawnum['sqborder']+(j*drawnum['sqlength'])+drawnum['episodenum'],drawnum['classbox']-(2*drawnum['sqborder']),drawnum['sqlength']-(2*drawnum['sqborder'])); 
				j++;
			}
			
			//CLASS NAMES
			ctx.strokeStyle = '#DDD'; 
			ctx.fillStyle = '#FFF';
			ctx.font = 'bold '+class_font_size+'px Verdana, sans-serif';
			ctx.textAlign = 'center';
			ctx.textBaseline = 'middle';
			ctx.lineWidth = 0;
			fontxalign=drawnum['classbox']/2;
			//fontxalign=classbox_margin/10;
			for (var i in starpos) {
				ctx.fillText("+", 				fontxalign, starpos[i]-drawnum['coredist']);
				ctx.fillText(i.toUpperCase(),	fontxalign, starpos[i]);
				ctx.fillText("-",				fontxalign, starpos[i]+drawnum['coredist']);
			}
			
			//EPISODE VERT LINES
			ctx.strokeStyle = '#555'; 
			ctx.lineWidth = 1;
			ctx.lineCap = 'butt';
			ctx.beginPath();
			for (i=0;i<max_eplength;i++) {
				xpos = drawnum['classbox']+((i+1)*drawnum['xpos_mult']);
				ctx.moveTo(xpos,drawnum['episodenum']); ctx.lineTo(xpos,height);
			}
			ctx.stroke();
			ctx.strokeStyle = '#333333'; 
			ctx.fillStyle = '#FFFFFF';
			ctx.font = epnum_font_size+'px sans-serif';
			ctx.textAlign = 'center';
			ctx.textBaseline = 'bottom';
			for (i=0;i<max_eplength;i++) {
				xpos = drawnum['classbox']+((i+1)*drawnum['xpos_mult']);
				ctx.strokeText( (i+offset+1) , xpos, drawnum['episodenum']);

			}
			
			ctx.strokeStyle = '#111'; 
			ctx.lineWidth = 3;
			ctx.lineCap = 'butt';
			ctx.beginPath();
			midpoint=drawnum['episodenum']+(height-drawnum['episodenum'])/2;
			ctx.moveTo(0,midpoint); ctx.lineTo(width,midpoint);
			ctx.stroke();
			
			var text_on_end = new Array();
			//DRAW DATA
			ctx.lineWidth = 4;
			ctx.lineCap = 'round';
			ctx.lineJoin = 'round';
			for (var i in series) {
				//ctx.strokeStyle = colors[ i % colors.length ];
				
				this_seriesname=ag_unfilter_chars(seriesnames[i]);
				this_seriesmarks=seriesmarks[i];
				if (hl['enable'] && hl['id']==seriesslugs[i]) {
					hl['color'] = colors[ i % colors.length ];
					hl['marks'] = this_seriesmarks;
				}
				agdebug(id,"<h3>Series: "+this_seriesname+"</h3>");
				r = ag_drawline(ctx,drawnum,4,colors[i%colors.length],this_seriesmarks);
				if (r) text_on_end.push(r);
			}
			
			if (text_on_end.length) {
				ag_textonend(ctx,epnum_font_size,text_on_end);
				text_on_end=new Array();
			}
			
			if (hl['enable']) {
				//alert('Highlight draw: '+hl['id']);
				ag_drawline(ctx,drawnum,10,'#333',hl['marks']);
				ag_drawline(ctx,drawnum,8,'#FFF',hl['marks']);
				r = ag_drawline(ctx,drawnum,4,hl['color'],hl['marks']);
				if (r) text_on_end.push(r);
			}
			
			if (text_on_end.length) {
				ag_textonend(ctx,epnum_font_size,text_on_end);
			}
				/*ctx.beginPath();
				ctx.strokeStyle = '#FFF'; 
				ctx.fillStyle = '#222';
				ctx.font = epnum_font_size+'px sans-serif';
				ctx.textAlign = 'center';
				ctx.textBaseline = 'middle';
				for (var i in text_on_end) {
					ctx.lineWidth = 3;
					ctx.strokeText( text_on_end[i][0] , text_on_end[i][1] , text_on_end[i][2] );
					ctx.lineWidth = 1;
					ctx.fillText( text_on_end[i][0] , text_on_end[i][1] , text_on_end[i][2] );
				}*/
					
			var legendspan = document.getElementById(id+"_legend");
			if (legendspan) {
				legendspan.innerHTML="";
				for (var i in series) {
					this_seriesname=ag_unfilter_chars(seriesnames[i]);
					legendspan.innerHTML += '<span onmouseover="anigraph_draw(\''+id+'\',\''+width+'\',\''+height+'\',\''+datastring+'\',\''+offset+'\',\''+seriesslugs[i]+'\')" onmouseout="anigraph_draw(\''+id+'\',\''+width+'\',\''+height+'\',\''+datastring+'\',\''+offset+'\',\'0\')" ><span class="anigraph_legend_colorbox" style="background-color:'+colors[ i % colors.length ]+';" >&nbsp;&nbsp;&nbsp;</span>&nbsp;'+this_seriesname+'</span><br/>';
				}
			}
		
		} else {  
		  // canvas-unsupported code here 
		  agdebug(id,"no context on id: " + id);
		}  
		
	} else {  
	  agdebug(id,"bad id: " + id);
	}
	return 0;
}

function ag_textonend(ctx,textsize,text_on_end) {
	ctx.beginPath();
	ctx.strokeStyle = '#FFF'; 
	ctx.fillStyle = '#222';
	ctx.font = textsize+'px sans-serif';
	ctx.textAlign = 'center';
	ctx.textBaseline = 'middle';
	for (var i in text_on_end) {
		ctx.lineWidth = 3;
		ctx.strokeText( text_on_end[i][0] , text_on_end[i][1] , text_on_end[i][2] );
		ctx.lineWidth = 1;
		ctx.fillText( text_on_end[i][0] , text_on_end[i][1] , text_on_end[i][2] );
	}
	return false;
}

function ag_drawline(ctx,drawnum,linewidth,color,this_seriesmarks){
	ctx.beginPath();
	ctx.lineWidth = linewidth;
	ctx.strokeStyle = color;
	ctx.lineCap = 'round';
	ctx.lineJoin = 'round';
	last_mark = 0; last_xpos = 0; last_ypos = 0; last_mark_exists = false; first_mark = true; r= false;
	for (var j in this_seriesmarks) {
		this_mark = this_seriesmarks[j];
		this_mark_exists = (this_mark!=-1);
		this_smarks = 0;
		chapter = (parseInt(j)+1);
		//agdebug(id,"Chapter "+chapter+" of series "+this_seriesname+" ("+this_seriesmarks[j]+")");
		if (this_mark.match(/\|/)) {
			//agdebug(id,"Special mark found");
			this_smarks = this_mark.split("|")[1].split(",");
			this_mark = this_mark.split("|")[0];
			//agdebug(id,"Parsed as "+this_mark+" and "+this_smarks[0]);
		}
		xpos = drawnum['classbox']+(chapter*drawnum['xpos_mult']);
		
		if (this_mark>170) this_mark=170;
		if (this_mark<0) this_mark=0;
		ypos = drawnum['episodenum']+(drawnum['coredist']/2)+(170-this_mark)*drawnum['ypos_mult'];
		
		if (this_mark_exists) {
			if (last_mark_exists) {
				//Last was a mark, like this
				//Nothing to do
			} else {
				if (first_mark) {
					//Time to start the line
					ctx.moveTo(drawnum['classbox'],ypos);
				} else {
					//Time to restart the line
					middle_to_current = drawnum['classbox']+(chapter*drawnum['xpos_mult'])-(drawnum['xpos_mult']/2);
					ctx.moveTo(middle_to_current,ypos);
				}
			}
			//Finally, we draw the mark because it exists
			ctx.lineTo(xpos,ypos);
		} else {
			if (last_mark_exists) {
				//Time to cut the line
				ctx.lineTo(last_xpos+(drawnum['xpos_mult']/2),last_ypos);
				ctx.stroke();
				ctx.beginPath();
			} else {
				//Last was nothing, like this
				//Nothing to do
			}
		}
		
		//agdebug(id,"line to "+xpos+","+ypos);
		//ctx.lineTo(xpos,ypos);
		last_mark = this_mark;
		last_xpos = xpos;
		last_ypos = ypos;
		last_mark_exists = this_mark_exists;
		first_mark = false;
		
		if (this_smarks) {
			for (var k in this_smarks) {
				if (this_smarks[k]) {
					r = [this_smarks[k], xpos, ypos];
				}
			}
		}
		
	}
	ctx.stroke();
	return r;
}

function ag_savecanvas(id) {
	var canvas = document.getElementById(id);
	var s = "";
	if (canvas) {
		s = canvas.toDataURL("image/png");
		s = s.replace("image/png", "image/octet-stream");
		document.location.href = s;
	}
	return 0;
}

function ag_convertcanvas(id) {
	var canvas = document.getElementById(id);
	var divcontainer = document.getElementById(id+"_div");
	var s = "";
	if (canvas && divcontainer) {
		try {
			s = canvas.toDataURL("image/png");
			divcontainer.innerHTML = '<img src="'+s+'" title="'+id+'" />';
		} catch(err) {
			//Nothing
		}
	}
	return 0;
}
