function printfire(text) {
    //$('#debug').append('<li>' + text + '</li>');
}

var useCanvas = false;

function GraphSize(x, y) {
	//printfire("GraphSize(" + x + ", " + y + ")");
	this.width = x;
	this.height = y;
}

GraphSize.prototype.fits = function(x, y) {
	//printfire("fits(" + x + ", " + y + ") < " + this.toString());
	if(x >= this.width && y >= this.height) {
		return true;
	}
	return false;
}

GraphSize.prototype.toString = function() {
	return this.width + "x" + this.height;
}

var sizes = new Array();
sizes[0] = new GraphSize(1024, 768);
sizes[1] = new GraphSize(800, 600);
sizes[2] = new GraphSize(640, 480);

function GraphProperties() {
	this.lines = {};
	this.range = 'all';
}

GraphProperties.prototype.url = function() {
	var result = '/graph/show/' + 
		this.size.toString() + '/'
		 + this.range;
	if(this.lines) {
		var ln = new Array();
		for(var color in this.lines) {
			ln[ln.length] = color;
		}
		ln.sort();
		for(var i = 0; i < ln.length; i++) {
			var lcol = ln[i];
			var code = this.lines[lcol].code;
			if(i > 0) {
				result += '_';
			} else {
				result += '/';
			}
			result += lcol + '-' + code;
		}
		result += '.png';
	}
	return result;
}

GraphProperties.prototype.addCode = function (color, code) {
	this.lines[color] = {code: code, data: []};	
}

GraphProperties.prototype.removeCode = function (color) {
	delete this.lines[color];
}

GraphProperties.prototype.getData = function () {
    if(useCanvas) {
    for(var color in this.lines) {
	var obj = this.lines[color];
        if(!obj.data[this.range]) {
	    $.getJSON("/graph/data/" + obj.code + '/' + this.range, null, gotData);
        }
    }
    }
}

GraphProperties.prototype.gotData = function(data) {
 if(useCanvas) {
    	printfire("gotData " + this.lines);
    var dataRanges = [];
    
    for(var color in this.lines) {
	printfire(color);
	var obj = this.lines[color];
	printfire(obj.code);
        if(obj.code == data.code) {
	    printfire('new data');
	    obj.data[data.range] = data;
        }
	
	if(obj.data[this.range]) {
	    printfire('range data for ' + obj.code);
	    dataRanges.push({
		label: obj.code,
		data: obj.data[this.range].rates,
		color: colors[color]
	    });
	}
    }
    
    $.plot($('#graphflot'), dataRanges, { xaxis: { mode: "time", minTickSize: [1, "day"], ticks: 3}, yaxis: { min: 0}, legend: { noColumns: dataRanges.length}} );
    }
}

var graphProperties = new GraphProperties();

function gotData(data) {
    graphProperties.gotData(data);
}

function _get_size() {
	var g = $('#graph').get(0);
	var w = g.clientWidth - 40;
	var h = g.clientHeight - 40;
	/* note this is arranged so we always end up with the last size 
	even if it doesn't fit */
	for(var i = 0; i < sizes.length; i++) {
		var testsize = sizes[i];
		//printfire("testsize = " + testsize);	
		graphProperties.size = testsize;
		if(testsize.fits(w, h)) {
			break;
		}
	}
	//printfire(graphProperties.size);
}

function _show_graph() {
    if(!useCanvas) {
	var g = $('#graphinner').get(0);
	g.src = graphProperties.url();
    }

	graphProperties.getData();
	graphProperties.gotData({code: 'x'});
}

function show_initial_graph() {
	_get_size();
	_show_graph();
}

function resize_graph() {
	show_initial_graph();
}

function dropped(a, b) {
    if(a && b) {
	var color = b.id.split("-")[1];
	var code = a.id.split("-")[1];
	var crossbut = '<img src="images/action_delete.png" class="closebut" width="16" height="16" alt="remove" title="remove" onclick="remove(\'' + color + '\');"/>';
	$(b).find('div.boxcontent').append('<span class="currency">' + code + '</span>' + crossbut);

	$('.closebut').hover(
	     function () { $(this).attr( 'src', 'images/action_delete_o.png' ); },
	     function () { $(this).attr( 'src', 'images/action_delete.png'); }
	);
	graphProperties.addCode(color, code);
	_show_graph();
    }
}

function remove(color) {
	graphProperties.removeCode(color);
	var cdiv = $('#color-' + color).find('div.boxcontent').get(0);
	cdiv.innerHTML = '';
	_show_graph();
}

function setrange(newrange) {
	if(newrange != graphProperties.range) {
		graphProperties.range = newrange;
		_show_graph();
	}
}

function testCanvas()
{
    $('body').append('<canvas id="testcanvas" style="display: none;"></canvas>');
    var testObject = $('#testcanvas').get(0);
    
    return testObject.getContext || typeof(G_vmlCanvasManager) != 'undefined';
}

//jquery document ready magic
$(function(){
	$('.jshide').hide();
	$('.starthidden').show();
	
	$('.colorbar').Droppable({
		accept: 'currency',
		activeclass: 'dropactive',
		hoverclass: 'drophover',
		tolerance: 'pointer',
		ondrop: function(drag) {
			dropped(drag, this);
		}
	});
	$('.currency').Draggable({
		revert: true,
		ghosting: true
	});
	$('.rangebar').cssRadio();
	
	$('body').resize(resize_graph);
	$("label").click(function(e){
		setrange(e.target.htmlFor.split("-")[1]);
	});

	show_initial_graph();

	if(testCanvas()) {
	    useCanvas = true;
	    $('#graphinner').after('<div id="graphflot" style="width: ' 
		+ graphProperties.size.width + 'px; height: ' 
		+ graphProperties.size.height + 'px;"></div>');
	    $('#graphinner').hide();
	    
	    //defaults
	    dropped($('#currency-USD').get(0), $('#color-g').get(0));
	    dropped($('#currency-EUR').get(0), $('#color-b').get(0));
	    dropped($('#currency-ABC').get(0), $('#color-g').get(0));
	}

	$(window).bind('load', function(){
	    var preload = [
		'/images/action_delete_o.png'
	    ];         
	    $(document.createElement('img')).bind('load', function(){
		if(preload[0]) this.src = preload.shift();
	    }).trigger('load');                
	});
});