var companyLogos = new Array();

function CompanyLogo(data) {
	this.teamName = data[0];
	this.company = data[1];
	this.logoURL = data[2];
	this.homeURL = data[3];
}

function getLogos(round) {
	jQuery.ajax({
		async: false,
		dataType: 'json',
		url: '/jqplot/graphGenerator/output/round' + round + '/logos.json',
		success: function(data) {
			for (var i = 0; i < data.length; i++) {
				companyLogos[data[i][0]] = new CompanyLogo(data[i]); 
			}
		}
	});
}

function GraphLabel(label) {
	this.label = label;
}

function GroupGraph(round, number) {
	this.url = "/jqplot/graphGenerator/output/round" + round + "/group" + number + ".json";
	this.title = "Gruppe " + number;
	this.labels = new Array();
	this.container = "groupGraph" + number;
	this.data = null;
	instance = this;
	
	jQuery.ajax({
		async: false,
		dataType: 'json',
		url: instance.url,
		success: function(data) {
			instance.data = data;
		}
	});
	
	for (i = 0; i < this.data[0].length; i++) {
		this.labels[i] = new GraphLabel(this.data[0][i]);
		this.labels[i].label = this.data[0][i] + " - " + this.data[1][i][this.data[1][i].length-1][1];
		if (typeof companyLogos[this.data[0][i]] != 'undefined') {
			this.labels[i].label += " <a href=\"" + companyLogos[this.data[0][i]].homeURL + "\"><img src=\"" + companyLogos[this.data[0][i]].logoURL + "\"></a>";
		}
	}
	
	this.plot = jQuery.jqplot(this.container, this.data[1], {
		title: this.title,
		legend: {
			show: true,
			placement: "outside",
			location: "s",
			yoffset: 25,
			rendererOptions: {
				numberRows: 4
			}
		},
		grid: {
			background: "#ffffff",
			drawGridlines: false,
			borderWidth: 0.1,
			borderColor: "#55555"				
		},
		axes: {
			xaxis: {
				min: 0,
				tickOptions: {
					formatString: "%d"
				}
			},
			yaxis: {
				tickOptions: {
					formatString: "%d"
				}
			}
		},
		series: this.labels,
		seriesDefaults: {
			markerOptions: {
				show: false
			},
		}
	});
}
	
jQuery(document).ready(function() {
	jQuery("div.groupGraphContainer").each(function() {
		var classes = jQuery(this).attr("class").split(" ");
		var round = classes[1].replace("round-", "");
		var groups = classes[2].replace("groups-", "");
		getLogos(round);
		var groupGraphs = new Array();
		for (var i = 1; i <= groups; i++) {
			jQuery(this).append('<div id="groupGraph' + i + '" style="margin: 20px 20px 220px 20px; height: 300px; width: 585px;"></div>');
			jQuery(this).append("<hr>");
			groupGraphs[i] = new GroupGraph(round, i);
		}
		jQuery(this).children("hr").last().remove();
	});
});

