/**
* SVG Sketch JavaScript 
* Copyright Tom Coote (tomcoote.co.uk)
* 21 June 2010
*/

(function (raphael) {

	var sketchPanel = raphael('sketchPanel', 700, 450),
		canvas = sketchPanel.rect(0, 0, 700, 450),
		startX = 100,
		startY = 100,
		currentX = 100,
		currentY = 100,
		currentPath,
		currentDirection,
		LEFT = 37,
		UP = 38,
		RIGHT = 39,
		DOWN = 40,
		allPaths = [],
		position = {'top': 8, 'left': $(document).width() / 2 - 410 },
		moveInterval;
	
	/**
	* Place the sketcher back in the middle of the screen.
	*/
	function resetPosition() {
		$('#frame').css({
			'top': position.top + 'px',
			'left': position.left + 'px'
		});	
	}
	
	/**
	* Draw a line on the canvas in the direction given.
	*/
	function drawLine(keyCode) {
		// If we were previously moving along the horizontal or vertical
		// but are now moving along the opposite plane then change the 
		// starting position to the end of the last line drawn.
		if ((currentDirection === RIGHT || currentDirection === LEFT) &&
		    (keyCode === DOWN || keyCode === UP)) {
			startX = currentX;
			startY = currentY;
		}
		if ((currentDirection === DOWN || currentDirection === UP) &&
		    (keyCode === RIGHT || keyCode === LEFT)) {
			startX = currentX;
			startY = currentY;
		}
		
		// move right
		if (keyCode === RIGHT) {
			currentX += 3;
			$('#horizontalControls img:last').css('opacity', 0.5);
		}
		// move left
		if (keyCode === LEFT) {
			currentX -= 3;
			$('#horizontalControls img:first').css('opacity', 0.5);
		}
		// move down
		if (keyCode === DOWN) {
			currentY += 3;
			$('#vericalControls img:last').css('opacity', 0.5);
		}
		// move up
		if (keyCode === UP) {
			currentY -= 3;
			$('#vericalControls img:first').css('opacity', 0.5);
		}
		
		// don't allow the line to go outside the panel
		if (currentX < 5) {
			currentX = 5;
		}
		if (currentY < 5) {
			currentY = 5;
		}
		if (currentX > 695) {
			currentX = 695;
		}
		if (currentY > 445) {
			currentY = 445;
		}
		
		// Remove the current line if moving in the
		// same direction before redrawing at new length.
		if (currentPath) {
			if (currentDirection === keyCode) {
				currentPath.remove();
			}
			else {
				allPaths.push(currentPath);
			}
		}
		
		currentDirection = keyCode;
		currentPath = sketchPanel.path('M' + startX + ' ' + startY + 'L' + currentX + ' ' + currentY);
		
		return !(keyCode === DOWN || keyCode === UP || keyCode === LEFT || keyCode === RIGHT);
	}
	
	/**
	* Clear the canvas of the current sketch and draw another
	* from the path strings given.
	*/
	function drawSketch(pathStrings) {
		// clear
		sketchPanel.clear();
		canvas = sketchPanel.rect(0, 0, 700, 450);
		canvas.attr('fill', '#9a9a9a');
		canvas.attr('opacity', '0.9');
	
		// re-draw
		allPaths = [];
		for (var i = 0; i < pathStrings.length; i++) {
			allPaths.push(sketchPanel.path(pathStrings[i]));
		}
		
		currentPath = allPaths[allPaths.length - 1];
		var coords = currentPath.attr('path').toString().replace('M', '').replace(/L|,/ig, ' ').split(' ');
		startX = parseInt(coords[2], 10);
		startY = parseInt(coords[3], 10);
		currentX = parseInt(coords[2], 10);
		currentY = parseInt(coords[3], 10);
	}
		
	// center the sketch area and keep it there
	$(window).resize(function() {
		position = {'top': 8, 'left': $(document).width() / 2 - 400 };
		resetPosition();
	});
	resetPosition();
	
	// make the sketch panel a nice grey.
	canvas.attr('fill', '#9a9a9a');
	canvas.attr('opacity', '0.9');
	
	// events for drawing
	$(document).bind('keydown', function(e) {
		return drawLine(e.keyCode);
	}).bind('keyup', function() {
		$('.controlBtn').css('opacity', 1);
	});
	$('#horizontalControls img:first').bind('mousedown', function() {
		moveInterval = window.setInterval(function() { drawLine(LEFT) }, 40);
	});
	$('#horizontalControls img:last').bind('mousedown', function() {
		moveInterval = window.setInterval(function() { drawLine(RIGHT) }, 40);
	});
	$('#vericalControls img:first').bind('mousedown', function() {
		moveInterval = window.setInterval(function() { drawLine(UP) }, 40);
	});
	$('#vericalControls img:last').bind('mousedown', function() {
		moveInterval = window.setInterval(function() { drawLine(DOWN) }, 40);
	});
	$('.controlBtn').bind('mouseleave', function() {
		moveInterval = window.clearInterval(moveInterval);
		$('.controlBtn').css('opacity', 1);
	});
	$('.controlBtn').bind('mouseup', function() {
		moveInterval = window.clearInterval(moveInterval);
		$('.controlBtn').css('opacity', 1);
	});
	
	// event for shaking the sketch panel clean.
	$('#frame').draggable({
		'stop': function(e, ui) {
			var paths = allPaths;
			if (currentPath) {
				paths.push(currentPath);
			}
			
			for (var i = 0; i < paths.length; i++) {
				if (paths[i].attr('opacity') < 1) {
					paths[i].attr('opacity', 0);
				}
				else {
					paths[i].attr('opacity', 0.1);
				}
			}
			
			startX = currentX;
			startY = currentY;
			currentPath = undefined;
			
			resetPosition();
		},
		'handle': '#shakeHandle'
	});
	
	// events for posting a sketch
	$('#postLink').click(function() {
		var paths = allPaths;
			pathStrings = '';
		if (currentPath) {
			paths.push(currentPath);
		}
		
		for (var i = 0; i < paths.length; i++) {
			if (typeof paths[i].attr('opacity') !== 'number' || paths[i].attr('opacity') > 0.1) {
				pathStrings += paths[i].attr('path') + '|';
			}
		}
		pathStrings = pathStrings.replace(/\|$/, '');
		
		if (!pathStrings) {
			alert('You need to draw a sketch before posting. Get to it!');
			return false;
		}
		
		$('#pathStrings').val(pathStrings);
		document.forms[0].submit();
		
		return false;
	});
	
	// draw a sketch if one has been sent from the gallery
	$(function() {
		var viewSketch = $('#viewSketch').html();
		if (viewSketch) {
			drawSketch(viewSketch.split('|'));
		}
	});
	
})(Raphael.ninja());
