jQuery(document).ready(function() {
	// Get all page objects
	var mxy = $("#mouseXY");
	var cxy = $("#clickXY");
	var w = $("#write");
	var rec = $("#record");
	var res = $("#reset");
	var sub = $("#submit");
	var cls = $("#close");
	
	// Recording marker
	var record = false;
	
	// Reset everything
	resetCanvas();
	
	// Capture mouse movement on the whiteboard
	w.mousemove(function(e) {
		var x = e.pageX - this.offsetLeft;
		var y = e.pageY - this.offsetTop;
		mxy.html(x +', '+ y);
		
		// If recording, trigger capture
		if(record)
			triggerRecord(e, x, y);
	});
	
	// Start each <polyline> tag
	w.mousedown(function(e) {
		beginWrap();
	});
	
	// End the <polyline> tag on mouse up
	w.mouseup(function(e) {
		endWrap();
	});
	
	// Same as above except when the mouse leaves the canvas
	w.mouseout(function(e) {
		endWrap();
	});
	
	// Reset button click
	res.click(function(e) {
		resetCanvas();
	});
	
	// "Submit" button click 
	sub.click(function(e) {
		createSVG();	
	});
	
	// "Close" button click
	cls.click(function(e) {
		resetCanvas();
	});
	
	// Reset everything and create a new SVG header
	function resetCanvas() {
		// Basic SVG
		var svg = '<?xml version="1.0" standalone="no"?>' +
		'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
		'<svg width="27cm" height="19cm" viewBox="0 0" xmlns="http://www.w3.org/2000/svg" version="1.1">' +
		'<desc>SVG Write</desc>' +
		'<rect x="0" y="0" width="800" height="600" fill="none" stroke="lightgray" stroke-width="1" />';

		// Mouse pressed XY positions
		cxy.html('0, 0');
		
		// Hide non-interactive elements for now
		rec.hide();
		cls.hide();
		
		// Set the default SVG code
		rec.val(svg);
		
		// Clean and show the whiteboard
		w.html('');
		w.show();
		
		// Show reset and submit buttons
		res.show();
		sub.show();
		
	};
	
	// Everything is finished and add the </svg> tag and show/hide necessary elements
	function createSVG() {
		rec.val(rec.val() + '</svg>');
		w.hide();
		res.hide();
		sub.hide();
		rec.show();
		cls.show();
	};
	
	// Begin capture
	function triggerRecord(e, x, y) {
		cxy.html(x +', '+ y);
		w.append('<div class="pixel" style="top:'+y+'px; left:'+x+'px;"></div>');
		rec.val(rec.val() + ' ' + x +',' + y);
	};
	
	// Begin <polyline> tag
	function beginWrap() {
		if(!record) {
			record = true;
			rec.val(rec.val() + '<polyline style="fill:none;stroke:black;stroke-width-1" points="');
		}
	};
	
	// End <polyline> tag
	function endWrap() {
		if(record) {
			record = false;
			rec.val(rec.val() + '" />');
		}
	};
});