/*
 * E-Knip Grafiek Klasse
 * Volgende variabelen moeten mee worden gegeven
 * gX, gY, gW, gH, gMaxX, gMaxY, gDivX, gDivY, legend, highlight, iDag, tStart, tStop, datax, datay, xLabels, usr linkoverride
*/



// Maakt een assenstelsel op x,y met breedte w, h, en maximale waarden xVal, yVal
Raphael.fn.makeGrid = function (x,y,w,h,xDiv,yDiv,xMax,yMax) {
	color = "#CCCCCC";
	rowHeight = h/yDiv;
	colWidth = w/xDiv;
	w -= colWidth;
	// Begin lijn
	var path = ["M",x,y,"L",x+w,y,x+w,y+h,x,y+h,x,y];
	for (var i = 0; i < yDiv; i++) {
		path = addLine(path,x,y+i*rowHeight,x+w,y+i*rowHeight);
	}
	var div = xMax - 1;
	// Teken geen lijntjes op minder dan 10 pixels afstand
	while ((w / div) < 10) {
		--div;
	}
	colWidth = w/div;
	for (var i = 0; i < div; i++) {
		// Als hoeveelheid lijnen toch nog gerelateerd worden aan de view
		/*if (tLevel < 3) {
			path = addLine(path,x+i*colWidth,y,x+i*colWidth,y+h);
		} else if(tLevel < 4) {
			if(i % 4 == 0) {
				path = addLine(path,x+i*colWidth,y,x+i*colWidth,y+h);
			}
		} else {
			if(i % 8 == 0) {
				path = addLine(path,x+i*colWidth,y,x+i*colWidth,y+h);
			}
		}*/
		path = addLine(path,x+i*colWidth,y,x+i*colWidth,y+h);
		
	}
	
	return this.path(path.join(",")).attr({stroke: color});
}

// Maakt een lijn in SVG path stijl
addLine = function (path,fx,fy,tx,ty) {
	path = path.concat(["M",fx,fy,"L",tx,ty]);
	return path;
}

// Plot een legenda item
Raphael.fn.plotLine = function (xd,yd,celw,celh,colour,stroke){
	// Als lijn hoger dan de grafiek begint, op maximale hoogte beginnen
	if (xd.length == 1) {
		return this.circle((gX + (xd[0]-1)*celw),(gY + gH - yd[0] * celh),stroke*1).attr({"fill": colour, "stroke": colour});
	}
	if ( yd[0] > gMaxY ) {
		var path = ["M",(gX + (xd[0]-1)*celw),(gY + gH - gMaxY*celh),"L"];
	} else {
		var path = ["M",(gX + (xd[0]-1)*celw),(gY + gH - yd[0]*celh),"L"];
	}
	for (var i=1;i<xd.length;i++) {
		// Als er lege dagen tussen zitten, zet deze op nul
		var dx = Math.abs(xd[i-1] - xd[i]);
		if (dx > 1) {
			// Als alle data 0 is (oftewel e-knip stond uit) gewoon doortrekken
			if ( makeDayArray(i) > 0 ) {
				while (dx > 1) {
					var x = gX + (xd[i] - dx) * celw;
					path.push(x,gY + gH);
					--dx;
				}
			}
		}
		var x = gX + (xd[i] - 1) * celw;
		// Afknippen pieken boven de maximale y-as
		if (yd[i] > gMaxY) {
			// Vind uit if het vorige data deel ook boven yMax zat
			if (yd[i-1] > gMaxY) {
				var y = gY + gH - gMaxY * celh;
			} else {
				//var y = gY + gH - gMaxY * celh;
				//var x = gX + ((xd[i-1] - 1) + (Math.abs(yd[i-1]-yd[i]) / gMaxY))  * celw;
				var dx = Math.abs(xd[i-1] - xd[i]);
				var dy = Math.abs(yd[i-1] - yd[i]);
				var rc = dy / dx;
				var x = gX + ((xd[i-1] - 1) + (dx/2)) * celw + (gMaxY / rc);
				var y = gY + gH - gMaxY * celh;
			}
		} else {
			if (yd[i-1] > gMaxY) {
				var dx = Math.abs(xd[i-1] - xd[i]);
				var dy = Math.abs(yd[i-1] - yd[i]);
				var rc = dy / dx;
				var x = gX + ((xd[i-1] - 1) + (dx/2)) * celw + gMaxY / rc
				var y = gY + gH - gMaxY * celh;
			} else {
				var y = gY + gH - yd[i] * celh;
			}
		}
		path.push(x,y);
	}
	return this.path(path.join(",")).attr({stroke: colour, "stroke-width": stroke});
}

// Maakt van een dag een array met data
makeDayArray = function (iDay) {
	pie = [];
	for (var i = 0; i < legend.length; i++) {
		for (var j = 0; j < datax[legend[i]].length; j++) {
			if (datax[legend[i]][j] == iDay) {
				pie.push([legend[i],datay[legend[i]][j],colours[i],i]);
			}
		}
	}
	return pie;
}

// Om te zoeken door elementen van arrays in plaats van sleutels met in
function oc(a) {
	var o = {};
	for(var i=0;i<a.length;i++) {
		o[a[i]]='';
	}
	return o;
}

// Begin met tekenen als de pagina geladen is
draw = function () {
	
	// Laat een waarschuwing zien als er geen data is
	if (legend.length < 1 || legend[0] == "") {
		canvas.text(350, (gY + gH) / 2, "No data for this period.").attr({'font-weight':'bold','font-size':'18'});
		return;
	}
	
	canvas.makeGrid(gX,gY,gW,gH,gDivX,gDivY,gMaxX,gMaxY);
	
	// Stapgrootte
	var rowHeight = gH / gDivY;
	var colWidth = gW / gDivX;
	
	// Het blokje met info in de lijngrafiek
	var infoRect = canvas.rect(40, 50, 100, 20, 5).attr({fill: "#000", stroke: "#474747", "stroke-width": 2}).hide();
	var infoText = canvas.text(90, 60, "Minister").attr({fill: "#FFF", "font-weight":"bold"}).hide();
	
	// Teken de lijnen in de lijngrafiek
	var lines = [];
	for (var i = 0; i < legend.length; i++) {
		// Als er een array met met lijnen om te laten zien is toegevoegd, alleen deze tekenen
		if (typeof(inclArray) != 'undefined') {
			if (!(qNrs[i] in oc(inclArray))){
				continue;
			}
		}
		// Maak een dikgedrukte lijn als daarom gevraagd word
		if (highlight == qNrs[i]) {
			lines[i] = canvas.plotLine(datax[legend[i]], datay[legend[i]], gW/gDivX, gH/gMaxY, colours[i],4);
			// Zet de ge'highlighte' lijn boven alle andere getekende objecten
			lines[i].toFront();
		} else {
			lines[i] = canvas.plotLine(datax[legend[i]], datay[legend[i]], gW/gDivX, gH/gMaxY, colours[i],2);
		}
		// Laat text zien bij het mouseoveren van de lijnen.
		(function(rtext,iLegend) {				
			rtext = rtext.split(' ');
			rtext.shift();
			rtext = rtext.join(' ');
			lines[i].mouseover(function(event) {
				infoRect.show();
				infoText.show();
				infoText.attr({text:rtext});
			});
			lines[i].click(function(event) {
				parent.window.location.href = "?day="+iDag+"&start="+tStart+"&stop="+tStop
											 +"&legend=" + iLegend + plusParam;
			});
		})(legend[i],i);
		lines[i].mouseout(function(event) {
			infoRect.hide();
			infoText.hide();
		});
	}
	
	// X-as labels maken, controleren of er data is die dag
	var days = [];
	// Maanden pointer
	var mPointer = 0;
	
	for (var i = 0; i < gDivX; i++) {
		if (xLabels.length < 60) {
			// Als de dagen fatsoenlijk op de x-as zijn te projecteren
			days[i] = canvas.text(gX + i * colWidth, gY + gH + 15, xLabels[i]);
			if ((i + 1) == iDag) {
				days[i].attr({'font-weight':'bold','font-size':'18pt'});
			} else {
				if (makeDayArray(i + 1).length > 0){
					(function(j) {
						days[j].click( function(event) {
							window.location.href = "?start="+tStart+"&stop="+tStop+"&yMax="+gMaxY+"&day="+(j+1)+"&legend="+highlight+ plusParam;
						});
					})(i);
					days[i].mouseover(function(event) {
						this.attr({"font-weight":'bold','font-size':'18pt'});
					});
					days[i].mouseout( function(event) {
						this.attr({"font-weight":"normal",'font-size':'10pt'});
					});
				} else {
					days[i].attr({"font-weight":"normal",'font-size':'10pt', "fill":"#cccccc"});
				}
			}
		} else {
			// Zet maanden neer
			if ( (i > 0 && xLabels[i] == "01") || i == 0) {
				days[i] = canvas.text(gX + i * colWidth + 3, gY + gH + 15, mLabels[mPointer]).attr({'text-anchor':'start'});
				// Zet ook een lijntje neer om te laten zien bij welk vak aan strepen deze maand hoort
				var line = addLine([],gX + i * colWidth, gY + gH, gX + i * colWidth, gY + gH + 10);
				canvas.path(line.join(',')).attr({'fill':'#CCCCCC','stroke':'#CCCCCC'});
				// Zet bij de eerste ook meteen even een lijntje op het eind neer...
				if ( i == 0 ) {
					var line = addLine([],gX + gW - 3, gY + gH, gX + gW - 3, gY + gH + 10);
					canvas.path(line.join(',')).attr({'fill':'#CCCCCC','stroke':'#CCCCCC'});
				}
				(function(j,n) {
					days[n].click( function(event) {
						window.location.href = mURLs[j] + plusParam;
					});
				
				})(mPointer,i);
				days[i].mouseover(function(event) {
					this.attr({"font-weight":'bold','font-size':'18pt'});
				});
				days[i].mouseout( function(event) {
					this.attr({"font-weight":"normal",'font-size':'10pt'});
				});
				++mPointer;
			}
		}
	}
	
	// Knop om y-as schaal te resetten
	var normalScale = canvas.text(gX - 15, gY, "^").attr({'font-size':'14pt'});
	normalScale.click( function(event) {
		window.location.href =  "?start="+tStart+"&stop="+tStop+"&day="+iDag + plusParam;
	});
	normalScale.mouseover( function(event) {
		normalScale.attr({'font-weight':'bold'});
	});
	normalScale.mouseout( function(event) {
		normalScale.attr({'font-weight':'normal'});
	});
	
	// Maak de y-as text en labels
	var yLabels = [];
	for (var i=0; i < gDivY; i++) {
		// Y-as word op helen afgerond - kan beter
		yLabels[i] = canvas.text(gX - 15, gY + gH - (i * rowHeight), Math.round((i * gMaxY / gDivY) * 10)/10);
		if((i * gMaxY / gDivY) > 20) {
			(function(h,j) {
				yLabels[j].click( function(event) {
					window.location.href = "?start="+tStart+"&stop="+tStop+"&day="+iDag+"&yMax="+h + plusParam;
				});
			})((i * gMaxY / gDivY), i);
			yLabels[i].mouseover( function(event) {
				this.attr({'font-weight':'bold'});
			});
			yLabels[i].mouseout( function(event) {
				this.attr({'font-weight':'normal'});
			});
		} else {
			// Automatisch naar 20, als er een kleinere schaalverdeling word gekozen.
			(function(h,j) {
				yLabels[j].click( function(event) {
					window.location.href = "?start="+tStart+"&stop="+tStop+"&day="+iDag+"&yMax="+ 20 + plusParam;
				});
			})((i * gMaxY / gDivY), i);
			yLabels[i].mouseover( function(event) {
				this.attr({'font-weight':'bold'});
			});
			yLabels[i].mouseout( function(event) {
				this.attr({'font-weight':'normal'});
			});
		}
	}
	
		
}

// Maak een pie chart
// @params x positie, y positie, straal, array met data
// Verder nodig; array met lengte van data met legenda strings, en zelfde geld voor een kleuren array
Raphael.fn.makePie = function (x,y,r,info) {
	// Reken totaal uit
	var total = 0;
	for (var i=0; i < info.length; i++) {
		if (typeof(inclArray) != 'undefined') {
			if (!(qNrs[info[i][3]] in oc(inclArray))){
				continue;
			}
		}
		total += info[i][1];
	}
	// Begin met deeltjes maken
	var angle = 0;
	for (var i=0; i < info.length; i++) {
		if (typeof(inclArray) != 'undefined') {
			if (!(qNrs[info[i][3]] in oc(inclArray))){
				continue;
			}
		}
		// Teken alle taartpunten
		var subAngle = (info[i][1] / total) * 360;
		if (subAngle > 358 && subAngle != 360 ) {
			subAngle = 358;
		}
		if (showPerc) {
			var label = info[i][0] + " " + (Math.round((info[i][1] / total) * 1000) / 10) + "%";
		} else {
			var label = info[i][0];
		}
		if (qNrs[info[i][3]] == highlight) {
			var part = this.drawSector(x, y, 1.1*r, angle, angle+subAngle, label, {fill:info[i][2],stroke:info[i][2]});
			part[1].attr({'font-weight':'bold','fill':'#000000','font-size':'15pt'});
			hText = part[1];
		} else {
			var part = this.drawSector(x, y, r, angle, angle+subAngle, label, {fill:info[i][2],stroke:info[i][2]});
		}
		angle += subAngle;
		// Voeg event handlers toe
		(function(p, n, t, l, st){
			st.click(function() {
				if (linkoverride) {
					parent.window.location.href = plusParam + "?legend=" + qNrs[n];
				} else if (usr) {
					parent.window.location.href = "knipsels?date=" + date + "&search[query]==" + t.split(" ")[0] + plusParam;
				} else {
					parent.window.location.href = "?day="+iDag+"&start="+tStart+"&stop="+tStop+"&yMax="+gMaxY
											     +"&legend=" + qNrs[n] + plusParam;
				}
			});
			st.mouseover(function(event) {
				p.animate({scale: [1.1, 1.1, x, y]}, 500, "elastic");
				l.attr({'fill':'#000000','font-weight':'bold','font-size':'15pt'});
				l.toFront();
			});
			if ( n == highlight ) {
				st.mouseout(function(event) {
					p.animate({scale: [1, 1, x, y]}, 500, "elastic");
					l.attr({'fill':'#000000','font-weight':'bold','font-size':'15pt'});
				});
			} else {
				st.mouseout(function(event) {
					p.animate({scale: [1, 1, x, y]}, 500, "elastic");
					l.attr({'fill':'#CCCCCC','font-weight':'normal','font-size':'10pt'});
				});
			}
		})(part[0], info[i][3], info[i][0], part[1], part[2]);
	}
	if (typeof(htText) != 'undefined' && highlight > 0){
		hText.toFront();
	}
	// Laat waarschuwing zien als er geen data is
	if (info.length < 1) {
		this.text(x, y, "Geen data op deze dag");
	}
}

// Maak een pie chart deel
// @params x positie, y positie, straal, starthoek, eindhoek, label, kleur enzo
Raphael.fn.drawSector = function (cx, cy, r, start, stop, label, params) {
	// Label goed formatten, Javascript stopt niet de rest van de split erachter dus zelf plakken
	label = label.split(' ');
	label.shift();
	lText = label.join(' ');
	// Als er een cirkel moet worden getekend, niet verdergaan
	if ((stop - start) == 360) {
		var l = this.text(cx + r + 30, cy + r + 30, lText);
		var sect = this.circle(cx,cy,r).attr(params);
		var st = this.set();
		var infoRect = this.rect(cx - 82, cy-10, 164, 20, 5).attr({fill: "#000", stroke: "#474747", "stroke-width": 2}).hide();
		if (usr) {
			var infoText = this.text(cx, cy, "Klik om de knipsels te zien").attr({fill: "#FFF", "font-weight":"bold"}).hide();
		} else {
			var infoText = this.text(cx, cy, "Klik om de lijngrafiek te markeren").attr({fill: "#FFF", "font-weight":"bold"}).hide();
		}
		st.push(sect,infoRect,infoText);
		st.mouseover(function(event) {
			infoRect.show();
			infoText.show();
			infoRect.toFront();
			infoText.toFront();
		});
		
		st.mouseout(function(event) {
			infoRect.hide();
			infoText.hide();
		});
		return [sect,l,st];
	}
	var rad = Math.PI/180;
	var x1 = cx + r * Math.cos(-start * rad);
	var y1 = cy + r * Math.sin(-start * rad);
	var x2 = cx + r * Math.cos(-stop * rad);
	var y2 = cy + r * Math.sin(-stop * rad);
	// Laat de tekstlabels zien
	path =  ["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(stop - start > 180), 0, x2, y2, "z"];
	if ( (stop - start) < 10 ) {
		var xt = cx + (r + 40) * Math.cos((-start-((stop - start) / 2)) * rad);
		var yt = cy + (r + 40) * Math.sin((-start-((stop - start) / 2)) * rad);
	} else {
		var xt = cx + (r + 30) * Math.cos((-start-((stop - start) / 2)) * rad);
		var yt = cy + (r + 30) * Math.sin((-start-((stop - start) / 2)) * rad);
	}
	
	var l = this.text(xt, yt, lText);
	
	l.attr({'fill':'#CCCCCC'});
	
	// Het blokje met info voor de pie chart
	var ix =  cx + 0.5 * r * Math.cos((-start-((stop - start) / 2)) * rad);
	var iy =  cy + 0.5 * r * Math.sin((-start-((stop - start) / 2)) * rad);
	var infoRect = this.rect(ix-82, iy-10, 164, 20, 5).attr({fill: "#000", stroke: "#474747", "stroke-width": 2}).hide();
	if (usr) {
		var infoText = this.text(ix, iy, "Klik om de knipsels te zien").attr({fill: "#FFF", "font-weight":"bold"}).hide();
	} else {
		var infoText = this.text(ix, iy, "Klik om de lijngrafiek te markeren").attr({fill: "#FFF", "font-weight":"bold"}).hide();
	}
	
	var sect = this.path(path).attr(params);
	
	var st = this.set();
	st.push(sect,infoRect,infoText);
	
	st.mouseover(function(event) {
		infoRect.show();
		infoText.show();
		infoRect.toFront();
		infoText.toFront();
	});
	
	st.mouseout(function(event) {
		infoRect.hide();
		infoText.hide();
	});
	
	return [sect,l,st];
}

// Een functie om alle grafiekdelen te selecteren
selectAll = function() {
	elements = document.legendForm.elements;
	for (var i = 0; i < elements.length; i++) {
		if (elements[i].name = 'view[]') {
			elements[i].checked = true;
		}
	}
}
// Een functie om alle grafiekdelen te deselecteren
deselectAll = function() {
	elements = document.legendForm.elements;
	for (var i = 0; i < elements.length; i++) {
		if (elements[i].name = 'view[]') {
			elements[i].checked = false;
		}
	}
}

// Maakt een grafiek met de aantallen gecorrigeerd voor het totale aantal knipsels die dag.
drawRelative = function () {
	
	// Laat een waarschuwing zien als er geen data is
	if (legend.length < 1 || legend[0] == "") {
		canvas.text(350, (gY + gH) / 2, "No data for this period.").attr({'font-weight':'bold','font-size':'18'});
		return;
	}
	
	// Bepaal het totale aantal knipsels voor elke dag
	var sumDays = [];
	for (var i = 0; i < legend.length; i++) {
		for (var j = 0; j < datax[legend[i]].length; j++) {
			sumDays[datax[legend[i]][j]] = 0;
		}
	}
	for (var i = 0; i < legend.length; i++) {
		for (var j = 0; j < datax[legend[i]].length; j++) {
			sumDays[datax[legend[i]][j]] += datay[legend[i]][j];
		}
	}
	
	gMaxY = 100;
	gDivY = 10;
	
	canvas.makeGrid(gX,gY,gW,gH,gDivX,gDivY,gMaxX,gMaxY);
	
	// Stapgrootte
	var rowHeight = gH / gDivY;
	var colWidth = gW / gDivX;
	
	// Het blokje met info in de lijngrafiek
	var infoRect = canvas.rect(40, 50, 100, 20, 5).attr({fill: "#000", stroke: "#474747", "stroke-width": 2}).hide();
	var infoText = canvas.text(90, 60, "Minister").attr({fill: "#FFF", "font-weight":"bold"}).hide();
	
	// Teken de lijnen in de lijngrafiek
	var lines = [];
	for (var i = 0; i < legend.length; i++) {
		// Maak een vervangende y array met de relatieve hoeveelheid knipsels
		relArray = [];
		for (var j = 0; j < datax[legend[i]].length; j++) {
			relArray.push( (datay[legend[i]][j] / sumDays[datax[legend[i]][j]])*100 );
		}
		// Als er een array met met lijnen om te laten zien is toegevoegd, alleen deze tekenen
		if (typeof(inclArray) != 'undefined') {
			if (!(qNrs[i] in oc(inclArray))){
				continue;
			}
		}
		// Maak een dikgedrukte lijn als daarom gevraagd word
		if (highlight == qNrs[i]) {
			lines[i] = canvas.plotLine(datax[legend[i]], relArray, gW/gDivX, gH/gMaxY, colours[i],4);
			// Zet de ge'highlighte' lijn boven alle andere getekende objecten
			lines[i].toFront();
		} else {
			lines[i] = canvas.plotLine(datax[legend[i]], relArray, gW/gDivX, gH/gMaxY, colours[i],2);
		}
		// Laat text zien bij het mouseoveren van de lijnen.
		(function(rtext,iLegend) {
			rtext = rtext.split(' ');
			rtext.shift();
			rtext = rtext.join(' ');
			lines[i].mouseover(function(event) {
				infoRect.show();
				infoText.show();
				infoText.attr({text:rtext});
			});
			lines[i].click(function(event) {
				parent.window.location.href = "?day="+iDag+"&start="+tStart+"&stop="+tStop
											 +"&legend=" + iLegend + plusParam;
			});
		})(legend[i],i);
		lines[i].mouseout(function(event) {
			infoRect.hide();
			infoText.hide();
		});
	}
	
	// X-as labels maken, controleren of er data is die dag
	var days = [];
	// Maanden pointer
	var mPointer = 0;
	
	for (var i = 0; i < gDivX; i++) {
		if (xLabels.length < 60) {
			// Als de dagen fatsoenlijk op de x-as zijn te projecteren
			days[i] = canvas.text(gX + i * colWidth, gY + gH + 15, xLabels[i]);
			if ((i + 1) == iDag) {
				days[i].attr({'font-weight':'bold','font-size':'18pt'});
			} else {
				if (makeDayArray(i + 1).length > 0){
					(function(j) {
						days[j].click( function(event) {
							window.location.href = "?start="+tStart+"&stop="+tStop+"&yMax="+gMaxY+"&day="+(j+1)+"&legend="+highlight+ plusParam;
						});
					})(i);
					days[i].mouseover(function(event) {
						this.attr({"font-weight":'bold','font-size':'18pt'});
					});
					days[i].mouseout( function(event) {
						this.attr({"font-weight":"normal",'font-size':'10pt'});
					});
				} else {
					days[i].attr({"font-weight":"normal",'font-size':'10pt', "fill":"#cccccc"});
				}
			}
		} else {
			// Zet maanden neer
			if ( (i > 0 && xLabels[i] == "01") || i == 0) {
				days[i] = canvas.text(gX + i * colWidth + 3, gY + gH + 15, mLabels[mPointer]).attr({'text-anchor':'start'});
				// Zet ook een lijntje neer om te laten zien bij welk vak aan strepen deze maand hoort
				var line = addLine([],gX + i * colWidth, gY + gH, gX + i * colWidth, gY + gH + 10);
				canvas.path(line.join(',')).attr({'fill':'#CCCCCC','stroke':'#CCCCCC'});
				// Zet bij de eerste ook meteen even een lijntje op het eind neer...
				if ( i == 0 ) {
					var line = addLine([],gX + gW - 3, gY + gH, gX + gW - 3, gY + gH + 10);
					canvas.path(line.join(',')).attr({'fill':'#CCCCCC','stroke':'#CCCCCC'});
				}
				(function(j,n) {
					days[n].click( function(event) {
						window.location.href = mURLs[j] + plusParam;
					});
				
				})(mPointer,i);
				days[i].mouseover(function(event) {
					this.attr({"font-weight":'bold','font-size':'18pt'});
				});
				days[i].mouseout( function(event) {
					this.attr({"font-weight":"normal",'font-size':'10pt'});
				});
				++mPointer;
			}
		}
	}
	
	// Maak de y-as text en labels
	var yLabels = [];
	for (var i=0; i <= gDivY; i++) {
		// Y-as word op helen afgerond - kan beter
		yLabels[i] = canvas.text(gX - 15, gY + gH - (i * rowHeight), Math.round((i * gMaxY / gDivY) * 10)/10);
	}
}