+SILENCE_CONSOLE = "console.debug = function() {}; console.info = function() {}; console.error = function() {}; console.log = function() {};"
+
 LOOP_MAX_ITERATIONS = 5000
+LOOP_TIMEOUT = 1000
 
 editor = ace.edit "editor"
 analysis = ace.edit "analysis"
 
 editor.setTheme "ace/theme/monokai"
 editor.getSession().setMode "ace/mode/javascript"
+editor.$blockScrolling = Infinity
 
 analysis.setReadOnly true
 analysis.setShowPrintMargin false
 analysis.renderer.setShowGutter false
 analysis.setHighlightActiveLine false
+analysis.$blockScrolling = Infinity
 
 # *************************************************************************************************
 tryEval = (code) ->

	# 	console.log(error)
	# 	return -1

	tryEval modifiedCode

parse = (rootNode, source) ->
	codeAnalysis = []


	window.sandbox = iframe.contentWindow
	tryEval "window.typeOf = #{typeOf.toString()}"
	tryEval SILENCE_CONSOLE

typeOf = (obj) ->
	({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1]

countIterations = (rootNode, block, source, callback) ->
	modifiedCode = "#{SILENCE_CONSOLE}
					var __jsPlaygroundCount__ = 0;
					#{source.substring(rootNode.range[0], block.body.range[0] + 1)}
					__jsPlaygroundCount__++;
					#{source.substring(block.body.range[0] + 1, block.range[1])}
					postMessage({\"line\": #{block.loc.start.line}, \"iterations\": __jsPlaygroundCount__});"

	# console.log modifiedCode

	# worker = new Worker "data:text/javascript;base64,#{btoa(modifiedCode)}"
	blob = new Blob [modifiedCode], type: "application/javascript"
	worker = new Worker URL.createObjectURL blob
	
	workerTimer = setTimeout (-> worker.terminate.call worker; callback {line: block.loc.start.line}, true), LOOP_TIMEOUT
	worker.onmessage = (event) ->
		clearTimeout workerTimer
		callback event.data

	worker.postMessage()
	# worker.terminate()

	# tryEval modifiedCode
	# console.log modifiedCode

countCalls = (rootNode, block, source, callback) ->
	modifiedCode = "#{SILENCE_CONSOLE}
					var __jsPlaygroundCount__ = 0;
					#{source.substring(rootNode.range[0], block.body.range[0] + 1)}
					__jsPlaygroundCount__++;
					#{source.substring(block.body.range[0] + 1, rootNode.range[1])}
					postMessage({\"line\": #{block.loc.start.line}, \"calls\": __jsPlaygroundCount__});"
	# console.log(modifiedCode)

	blob = new Blob [modifiedCode], type: "application/javascript"
	worker = new Worker URL.createObjectURL blob
	
	workerTimer = setTimeout (-> worker.terminate.call worker; callback {line: block.loc.start.line}, true), LOOP_TIMEOUT
	worker.onmessage = (event) ->
		clearTimeout workerTimer
		callback event.data, false

	worker.postMessage()
	
	# try
	# 	tryEval modifiedCode
