function setup() {
	document.getElementById('start').addEventListener( 'click', detectImage );
}

function detectImage( ev ) {
	if ( ev && ev.preventDefault ) {
		ev.preventDefault();
	}

	var sourceImage = document.getElementById( 'source' );
	var sourceCanvas = document.getElementById( 'csource' );
	var sourceContext = sourceCanvas.getContext( '2d' );
	sourceContext.drawImage( sourceImage, sourceCanvas.width * 0.25, sourceCanvas.height * 0.25, sourceCanvas.width * 0.5, sourceCanvas.height * 0.5 );

	doImage( 'full' );
	doImage( 'fullside' );
}

function doImage( name ) {
	var canvas = document.getElementById( 'c' + name );
	var context = canvas.getContext( '2d' );
	var image = document.getElementById( name );

	var sourceCanvas = document.getElementById( 'csource' );
	var sourceContext = sourceCanvas.getContext( '2d' );

	context.drawImage( image, 0, 0, canvas.width, canvas.height );

	var imageDataTarget = context.getImageData( 0, 0, canvas.width, canvas.height );
	var imageDataSource = sourceContext.getImageData( 0, 0, sourceCanvas.width, sourceCanvas.height );

	var grayTarget = tracking.Image.grayscale(
		tracking.Image.blur( imageDataTarget.data, canvas.width, canvas.height, 3 ),
		canvas.width, canvas.height
	);

	var graySource = tracking.Image.grayscale(
		tracking.Image.blur( imageDataSource.data, sourceCanvas.width, sourceCanvas.height, 3 ),
		sourceCanvas.width, sourceCanvas.height
	);

	var cornersTarget = tracking.Fast.findCorners( grayTarget, canvas.width, canvas.height );
	var cornersSource = tracking.Fast.findCorners( graySource, sourceCanvas.width, sourceCanvas.height );

	var descriptorsTarget = tracking.Brief.getDescriptors( grayTarget, canvas.width, cornersTarget );
	var descriptorsSource = tracking.Brief.getDescriptors( graySource, sourceCanvas.height, cornersSource );

	//var matches = tracking.Brief.reciprocalMatch( cornersSource, descriptorsSource, cornersTarget, descriptorsTarget );
	var matches = tracking.Brief.reciprocalMatch( cornersTarget, descriptorsTarget, cornersSource, descriptorsSource );

	matches.sort( function(a, b) {
		return b.confidence - a.confidence
	});

	for (var i = 0; i < matches.length; i++) {
	  console.log(name,matches[i].confidence);
	  var color = '#' + Math.floor(Math.random()*16777215).toString(16);
	  //var color = '#ff0000';
	  context.fillStyle = color;
	  context.strokeStyle = color;
	  context.fillRect(normalizePoint(matches[i].keypoint1[0]), normalizePoint(matches[i].keypoint1[1]), 4, 4);
	  context.fillRect(normalizePoint(matches[i].keypoint2[0])/* + canvas.width*/, normalizePoint(matches[i].keypoint2[1]), 4, 4);

	  context.beginPath();
	  context.moveTo(normalizePoint(matches[i].keypoint1[0]), normalizePoint(matches[i].keypoint1[1]));
	  context.lineTo(normalizePoint(matches[i].keypoint2[0])/* + canvas.width*/, normalizePoint(matches[i].keypoint2[1]));
	  context.stroke();
	}
}

function normalizePoint( x ) {
	return x;
}