$(document).ready(function() {
	$("#codeGenBoxTrigger").fancybox({
		'titlePosition' : 'inside',
		'transitionIn' : 'none',
		'transitionOut' : 'none'
	});
});

function showSuccess(message) {
	showMessage('#00FF4D', 'white', message);
}

function showInfo(message) {
	showMessage('#FFE16B', 'grey', message);
}

function showError(message) {
	showMessage('#FF4D00', 'white', message);
}

function interpret() {
	BrainFuck.init();
	var code = $("#codeBox").val();
	$("#outputBox").val(BrainFuck.interpret(code)).attr("readonly", "readonly");
}

function generateCode() {
	BrainFuck.init();
	var text = $("#textBox").val();
	$("#generatedCodeBox").val(BrainFuck.generateCode(text));
}

function select_all(ele) {
	ele.focus();
	ele.select();
}

function debug() {
	BrainFuck.init();
	var code = $("#codeBox").val();
	BrainFuck.loadToDebug(code);
	$("#debug_panel").animate({'width' : 'show'}, 250);
}

function step() {
	var tape = BrainFuck.step();
	if(tape) {
		$.each(tape, function(index, value) {
			createOrUpdateColumn(index, value);
		});
	} else {
		$("#outputBox").val(BrainFuck.getDebugOutput()).attr("readonly", "readonly");
	} 
}

function createOrUpdateColumn(index, value) {
	$('#debugResultTable tr:eq(1)').each(function() {
		var colSelector = "td:eq("+index+")";
	    var col = $(this).find(colSelector).html();
	    if(!col) {
	    	$(this).append("<td>"+value+"</td>");
	    } else {
	    	$(this).find(colSelector).html(value);
	    }
	});
	console.log(index +"\t"+ value);
}

function refreshInterpreter() {
	BrainFuck.init();
	$("#codeBox").val('');
	$("#outputBox").val('').attr("readonly", "readonly");
}

function saveProgram() {	
	$('#shareCodePanel').show();
	$('#shareCodePanel input').hide();
	$('#shareCodePanel img').animate({'height' : 'show'}, 250);
	$.post('/save', 
			{code : $("#codeBox").val()},
			function(data) {
				showSuccess("Successfully saved !");		
				var link = "brainfk.com/" + data;
				$('#shareCodePanel img').hide();
				$('#shareCodePanel input').val(link).show();
			}).complete(function() { $('#shareCodePanel img').hide(); });
}

var interval = null;

function showMessage(bgcolor, color, msg) {
	$('#smsg').remove();
	clearInterval(interval);

	if (!$('#smsg').is(':visible')) {
		if (!$('#smsg').length) {
			$('<div id="smsg">' + msg + '</div>').appendTo($('body')).css({
				position : 'fixed',
				top : 0,
				left : 0,
				width : '100%',
				height : '30px',
				lineHeight : '30px',
				background : bgcolor,
				color : color,
				zIndex : 1000,
				padding : '10px',
				fontWeight : 'bold',
				fontSize : '18px',
				textAlign : 'center',
				opacity : 0.8,
				margin : 'auto',
				display : 'none'
			}).slideDown('show');

			interval = setTimeout(function() {
				$('#smsg').animate({
					'height' : 'hide'
				}, function() {
					$('#smsg').remove();
				});
			}, 3000);
		}
	}
}

