function checkInput(id)
{
	var o = $('#'+id);
	if (isNaN(o.val()))
		o.addClass('err');
	else
		o.removeClass('err');
	var val = Number(o.val());
	if (val == 0)
		o.val('0');
	return val;
}

function solveForX()
{
	var a = 0, b = 0, c = 0, descrim, x1, x2, solutions;

	a = checkInput('a');
	b = checkInput('b');
	c = checkInput('c');

	if (isNaN(a) || isNaN(b) || isNaN(c))
	{
		$('#err').html("<span class='err'>All coefficients must be real numbers.</span>");
		return 1;
	}

	if (a == 0)
	{
		if (b == 0)
		{
			if (c == 0)
				solutions = -1; // all values
			else
				solutions = 0; // no solution
		}
		else
		{
			solutions = 1;
			x1 = -c / b;
		}
	}
	else // a != 0
	{
		descrim = (b*b) - (4*a*c);
		if (descrim == 0)
		{
			solutions = 1;
			x1 = -(b/(2*a));
		}
		else if (descrim > 0)
		{
			solutions = 2;
			x1 = (-b + Math.sqrt(descrim)) / (2*a);
			x2 = (-b - Math.sqrt(descrim)) / (2*a);
		}
		else // descrim < 0
		{
			solutions = -2;
			x1 = -b / (2*a);
			x2 = Math.sqrt((4*a*c) - (b*b)) / (2*a);
		}	
	}

	$('input.out').val('none');
	switch (solutions)
	{
	case 2:
		$('#x1').val(x1);
		$('#x2').val(x2);
		break;
	case 1:
		$('#x1').val(x1);
		break;
	case -1:
		$('#x1').val('all numbers');
		break;
	case -2:
		$('#x1').val(x1+' + '+x2+'i');
		$('#x2').val(x1+' - '+x2+'i');
		break;
	}
	return 0;
}

$(document).ready(function() {
	$('#appClose').click(function() {
		window.location = '../';
	});
	$('#clear').click(function() {
		$("input[type='text']").val('');
		$("input[type='text']").removeClass('err');
		$('#err').html('&nbsp;');
	});
	$('#solve').click(function() {
		$('#err').html('&nbsp;');
		solveForX();
	});
	$("input[type='text'].in").keyup(function(event) {
		if (event.keyCode==13)
			$("#solve").click();
	});
	$('#clear').click();
});
