var MAX = 1000;

var fills = [
	['lightblue', 'blue'],
	['lightgreen', 'green'],
	['pink', 'red'],
	['gray', 'black']
];

$(function() {
	$.get('proxy.php?url=http://steveersinghaus.com/mediaplay/?feed=rss2&cat=13', begin, 'xml');
});
 
function begin(data) {
	$('#svg')
		.css({
			width		: (MAX || letters.length)*10,
			height		: $(document).height() - 100
		})
		.svg({
			onLoad: function () {
				initialize_graph();
				$(data).find('item').each(process_data);
			}
		})
	;
}

function initialize_graph() {
	var svg = $('#svg').svg('get'); 
	//console.log(svg);
	svg.graph
		.noDraw()
		.area(75, 75, $('#svg').width() - 500, $('#svg').height() - 50)
		.type('line')
		.title('Steve\'s Fingers - First '+MAX+' characters of each story')
		.gridlines({stroke: 'gray', 'stroke-dasharray': '2,2'}, 'gray')
	; 
	svg.graph.xAxis.title('Location in Story').scale(0, (MAX || letters.length)).ticks(100, 50);
	svg.graph.yAxis.title('Character').scale(0, 160).ticks(10, 5);
	svg.graph.legend
		.settings({fill: 'white', stroke: 'gray'})
		.show(true)
		.area($('#svg').width() - 500, 75, 75, $('#svg').height() - 50);
	resetSize(svg);
	return svg;
}

function process_data (item_index) {	
	
	if (item_index > 3) return;
	
	var svg = $('#svg').svg('get'); 
	var $item = $(this);
	var title = $item.find('title').text();
	var letters = $item.find('content\\:encoded').text().replace(/(<[^>]+>|\&[^;]+;)/g, '');
	
	//console.log(letters);
	var codes = [];
	for (var i = 0; i < (MAX || letters.length); i++) {
		codes.push(letters.charCodeAt(i));
	}
	
	//console.log(codes);
	//console.log(codes.length);
	//svg.graph;
	//console.log(item_index, fills);
	svg.graph
		.addSeries(title, codes, fills[item_index][0], fills[item_index][1], 1)
		.redraw();
}

function resetSize(svg, width, height) {
	svg.configure({width: width || $(svg._container).width(),
		height: height || $(svg._container).height()});
}