/* Simpeler faster hsb2rgbhex */
function hsb2rgbhex(hue, brightness)
{
	var red,
        green,
        blue;

	var i = Math.floor(hue * 6),
            f = (hue * 6) - i,
            q = brightness * (1 - f),
            t = brightness * f;

	red = [brightness, q, 0, 0, t, brightness, brightness][i];
	green = [t, brightness, brightness, q, 0, 0, t][i];
	blue = [0, 0, t, brightness, brightness, q, 0][i];

	red *= 255;
	green *= 255;
	blue *= 255;
	
	r = Math.round(red).toString(16),
	g = Math.round(green).toString(16),
	b = Math.round(blue).toString(16);

	if (r.length == 1) {
		r = "0" + r;
	}
	if (g.length == 1) {
		g = "0" + g;
	}
	if (b.length == 1) {
		b = "0" + b;
	}

	return "#" + r + g + b;
}

Raphael.fn.pieChart = function (cx, cy, r, values, labels)
{
	var paper = this,
	rad = Math.PI / 180,
	chart = this.set();
	
	function sector(cx, cy, r, startAngle, endAngle, params)
	{
		var calc0 = -startAngle * rad;
		calc1 = -endAngle * rad;

		var x1 = cx + r * Math.cos(calc0),
			x2 = cx + r * Math.cos(calc1),
			y1 = cy + r * Math.sin(calc0),
			y2 = cy + r * Math.sin(calc1);
		return paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
	}
	
	var angle = 0,
	total = 0,
	start = 0,
	lastTextX = 0,
	lastTextY = 0,
	process = function (j)
	{
		var percentage = values[j] / total,
		angleplus = 360 * percentage,
		popangle = angle + (angleplus / 2),
		color = "hsb(" + start + ", 1, .6)",
		ms = 500,
		bcolor = "hsb(" + start + ", 1, 1)";
		
		// Draw percentage text
		var textX = cx + (r + 15) * Math.cos(-popangle * rad);
		var textY = cy + (r + 15) * Math.sin(-popangle * rad);

		if( Math.abs(lastTextY - textY) < 10 )
			textY -= 5;

		txt = paper.text
		(
			textX,
			textY,
			Math.round(percentage * 100) + "%"
		).attr({
			fill: 'black',
				stroke: "none",
				opacity: 1,
				"font-family": 'Fontin-Sans, Arial',
				"font-size": "9px"
		});
		
		// Draw part of graph
		var p = sector(cx, cy, r, angle, angle + angleplus, {
			gradient: "90-" + bcolor + "-" + color,
			stroke: "#fff",
			"stroke-width": 2
		});
		
		// Update legend
		var legend = $(labels[j]);
		legend.children('.square').css('backgroundColor', hsb2rgbhex(start, .9));
		
		// Mouseover effect
		p.mouseover(function () {
			p.animate({scale: [1.1, 1.1, cx, cy]}, ms, "elastic");
			legend.css('fontWeight', 'bold');
		}).mouseout(function () {
			p.animate({scale: [1, 1, cx, cy]}, ms, "elastic");
			legend.css('fontWeight', 'normal');
		});
		
		// Do the same for label mouseover (for some reason can't combine p and our element)
		legend.mouseover(function () {
			p.animate({scale: [1.1, 1.1, cx, cy]}, ms, "elastic");
			$(this).css('fontWeight', 'bold');
		}).mouseout(function () {
			p.animate({scale: [1, 1, cx, cy]}, ms, "elastic");
			$(this).css('fontWeight', 'normal');
		});
		
		// Add to Raphael
		chart.push(txt);
		chart.push(p);

		angle += angleplus;
		start += 0.15;
		lastTextX = textX;
		lastTextY = textY;
	};
	
	// Calculate total
	for (var i = 0, ii = values.length; i < ii; i++) {
		total += values[i];
	}
	// Process everything in 
	for (var i = 0; i < ii; i++) {
		process(i);
	}
	
	return chart;
};

var numCharts = 0;
function showPieChart( raphael, tableEl, radius )
{
	var id = "pie" + (++numCharts);
	var values = [],
	labelElements = [];
	var legendContent = '';
	
	// Parse table, grab data and build content for legend
	var i = 0;
	$("tr", tableEl).each(function ()
	{
		if( $('th', this).length == 0 )
		{
			var val = parseInt($("td:last", this).text(), 10);
			if( val > 0)
			{
				values.push(val);
				labelElements.push("#" + id + "label" + i);
				
				legendContent += '<li id="' + id + 'label' + i + '"><span class="square"></span>' + jQuery.trim($("td:first", this).text()) + '</li>';
				
				i++;
			}
		}
	});
	
	if( values.length > 0 )
	{
		// Inject HTML for graph and hide table
		tableEl.hide().after('<div class="piegraph" id="container' + id + '"><div class="graph" id="' + id + '"></div><div class="legend"><small><a href="javascript:switchGraphTable(\'' + id + '\')">[Show table]</a></small><br><br>' + legendContent + '</div></div>');
	
		// Show graph
		tableEl.data('graph', id);
		$('#container' + id).data('table', tableEl);
		raphael(id, radius*2, radius*2).pieChart(radius, radius, radius*0.7, values, labelElements);
	}
}

function switchGraphTable(id)
{
	$('#container' + id ).toggle();
	$('#container' + id ).data('table').toggle();
}