 toJSON = (filename) ->
 	"diagrams/" + filename + ".json"
 
-loadDiagram = (filename) ->
-	clearAll()
-	CANVAS.css "background", "url(" + toImg(filename) + ") no-repeat"
+ajaxPreloadDiagram = (filename, game, i) ->
 	$.getJSON(toJSON(filename),
 		(data, status, xhr) ->
 			diagram = new Diagram(data)
-			$("#head_title").html(diagram.source)
-			updateSidebar()
+			game.diagrams[i] = diagram
 	).error( # chain
 		(jqXhr, textStatus, error) ->
 			alert textStatus + " : " + error
 	)
+
+loadDiagram = (diagram) ->
+	console.log("Loading")
+	console.log(diagram)
+	clearAll()
+	updateSidebar()
+	$("#head_title").html(diagram.source)
+	CANVAS.css "background", "url(" + toImg(diagram.filename) + ") no-repeat"
+
 # }}}
 # Canvas art and Button UI {{{
 # Low-level things

	markAllActive()

onDiagramClick = (e) ->
	o = new Point("", e.pageX-this.offsetLeft, e.pageY-this.offsetTop)
		# where user clicked
	# Grab the closest point to the click

	assignScore: () ->
		if @allFound()
			if @mistakes <= 1
				7
			else if @mistakes <= 3
				6
			else
				5
		else
			if @found >= @max_found/2
				2
			else if @found >= @max_found/3
				1
			else
				0

class Game
	constructor: (@diagram_names) ->
		@length = @diagram_names.length
		@i = 0 # player's current progress
		@score = 0
		@diagrams = (null for [1..@length])
		@preloadDiagrams()
		@alive = true
	preloadDiagrams: () ->
		for name, i in @diagram_names
			ajaxPreloadDiagram name, @, i
	currDiagram: () ->
		if @i >= @length
			null
		@diagrams[@i]
	setDiagram: (i) ->
		@i = i
		loadDiagram(@diagrams[i])
	startGame: () ->
		@setDiagram(0)
	endGame: () ->
		@alive = false
		alert("You win, lol")
	processCorrectDone: () ->
		@currDiagram().complete = true
		if (@i + 1 < @length)
			@setDiagram(@i+1)
		else
			@endGame()
	processIncorrectDone: () ->
		@currDiagram().mistakes += 1



