if (typeof $ === 'function') {
	var currentThreadCount = 1;
	var dataLen = 500000;
	$(document).ready(function () {				
		
		if (typeof postMessage === 'function') {
			$('#runTests').click(function() {				
				runTest(1, dataLen, 't1');				
			})			
		} else {			
			$('#runTests').click(function() { 				
				alert('Web Workers not supported in your browser'); 
			});
			$('#results').html('<td colspan="5">Browser not supported</td>');
		}		
	});

	function testCompleted() {
		if (++currentThreadCount > 5) return;
		runTest(currentThreadCount, dataLen, 't' + currentThreadCount);
	}
}
	
var data;
var threadData = [];
var threadsCompleted = 0;
var startTime;
var resultsID;

function runTest(threadCount, dataLen, resultsControlID) {	
	data = initialiseData(dataLen);
	startTime = new Date().getTime();
	resultsID = resultsControlID;
	threadsCompleted = 0;
	threadData = [];	
	if (threadCount === 1) {
		doCostlyDataOperationsOn(data);
		showResults();
	} else {
		runThreadedTest(threadCount);
	}		
}

function runThreadedTest(threadCount) {	
	$('#' + resultsID).html('Running ...');	
	var blockLen = Math.ceil(data.length * 1.0 / threadCount);	
	for (var i = 0; i < threadCount; i++) {
		var offsetIdx = blockLen * i;
		var worker = new Worker('http://www.picnet.com.au/blogs/guido/extra/web_workers/scripts.js');
		worker.idx = i;
		var subdata = data.slice(offsetIdx, i === (threadCount-1) ? data.length : offsetIdx + blockLen);		
		worker.postMessage(subdata.join(','));
		worker.onmessage = function(event) { workerFinished(threadCount, i, offsetIdx, event.data); }
	}
}

// Worker
onmessage = function(event) {	
	var threadData = event.data.split(',');
	for (var i = 0; i < threadData.length; i++) {
		threadData[i] = parseInt(threadData[i], 10);
	}
	doCostlyDataOperationsOn(threadData);
	postMessage(threadData.join(','));
}

function workerFinished(totalThreads, idx, offetIdx, threadData) {
	threadData = threadData.split(',');
	for (var i = 0; i < threadData.length; i++) {		
		data[offetIdx + i] = parseInt(threadData[i], 10); 
	}
	if (++threadsCompleted === totalThreads) { showResults(); }
}

function doCostlyDataOperationsOn(d) {
	var len = d.length;
	for (var i = 0; i < len; i++) {
		d[i] = Math.ceil(d[i]) * Math.floor(500.0) * Math.floor(Math.random());
		d[i] = Math.ceil(d[i]);
	}
}

function showResults() {
	var tookMs = new Date().getTime() - startTime;	
	$('#' + resultsID).html('Took: ' + tookMs + 'ms');
	
	if (testCompleted) testCompleted();
}

function initialiseData(len) {
	var d = new Array(len);
	for (var i = 0; i < len; i++) {
		d[i] = 1000 * Math.random();
	}
	return d;
}
