// Matemàgic - Maths for kids
//
// Copyright (C) 2006-2010 Siegfried-Angel Gevatter Pujals <rainct@eurion.net>
// All rights reserved.

// Data variables
var tries = 0;
var lastValue = '';
var currentType = 0;
var operations = new Array();
for(i = 1; i < 5; i++) {
	operations[i] = new Array();
	operations[i]['correct'] = 0;
	operations[i]['total'] = 0;
	operations[i]['points'] = 0;
	operations[i]['custom_difficulty'] = 0;
}
operations[1]['nom'] = 'Sumes';
operations[2]['nom'] = 'Restes';
operations[3]['nom'] = 'Multiplicacions';
operations[4]['nom'] = 'Divisions';

// Support functions

function $(name) {
	return document.getElementById(name);
}

function updateStats(correct, total) {
	if(correct > 0) {
		operations[currentType]['correct'] += 1;
		operations[currentType]['points'] += (3 - tries);
	}
	if(total == 1) {
		operations[currentType]['total'] += 1;
		if(tries > 0) {
			operations[currentType]['points'] -= 2;
			tries = 0;
		}
	}
	$('stats').innerHTML = operations[currentType]['correct'] + '/' + operations[currentType]['total'];
}

function setOpacity(element, opacity) {
	element.style.opacity = opacity;
	element.style.filter = "alpha(opacity = '"+opacity*100+"')";
}

var opacity;
function fadeSuccessImage() {
	element = 'form_calcul';
	opacity = 0.0;
	setOpacity($(element), opacity);
	setOpacity($('happy'), 0.0);
	$('happy').style.display = '';
	function update_effect_1() {
		opacity = opacity + 0.05;
		setOpacity($('happy'), opacity);
		if (opacity < 1.0) {
			setTimeout(update_effect_1, 30);
		} else {
			opacity = 0.0;
			setTimeout(update_effect_2, 30);
		}
	}
	function update_effect_2() {
		opacity = opacity + 0.05;
		setOpacity($(element), opacity);
		if (opacity >= 0.5) {
			setOpacity($('happy'), 1.0 - (opacity * 2));
		} else {
			$('happy').style.display = 'none';
		}
		
		if (opacity < 1.0) {
			setTimeout(update_effect_2, 70);
		}
	}
	setTimeout(update_effect_1, 30)
}

// Main functions
function loaded() {
	$('happy').style.display = 'none';
	$('carregant').style.display = 'none';
	$('menu').style.display = 'block';
	$('inicial').style.display = 'block';
}

function newAjax(method, url, bool) {
	var xmlhttp = false; 
	try {
		// For real web browsers
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
		try {
			// For IE
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		} catch(e) { xmlhttp=false; }
	}
	if(!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	
	xmlhttp.open(method, url, bool);
	xmlhttp.send(null);
	return xmlhttp;
}

function changeType(idop) {
	if(idop != currentType && idop > 0 && idop < 5) {
		currentType = idop;
		$('inicial').style.display = 'none';
		$('form_calcul').style.display = 'block';
		$('answer').focus();
		$('text_operacio').innerHTML = operations[currentType]['nom'];
		$('bigfail').style.display = 'none';
		$('write_answer').innerHTML = '';
		updateStats();
		newQuestion();
		updateDifficultyMenu();
	}
}

function changeDifficulty(id) {
	if(id != operations[currentType]['custom_difficulty']) {
		operations[currentType]['custom_difficulty'] = id;
		newQuestion();
		updateDifficultyMenu();
	}
}

function updateDifficultyMenu() {
	elements = $('secondary_menu').getElementsByTagName('a')
	for(var num in elements) {
		if(elements[num].id == ('d' + operations[currentType]['custom_difficulty'])) {
			elements[num].className = 'selected_difficulty';
		} else {
			elements[num].className = '';
		}
	}
}

function checkAnswer() {
	// Reset the status message
	$('write_answer').innerHTML = '';
	$('answer').focus();
	$('answer').select();
	
	if($('answer').value == '') {
		// The answer is empty
		$('write_answer').innerHTML = '<img src="./images/img_noinput.gif" width="22" height="22" class="notify" /> Has d\'escriure una resposta...';
		return false;
	}
	
	if(isNaN($('answer').value)) {
		// The answer is not a number
		$('write_answer').innerHTML = '<img src="./images/img_invalid.gif" width="22" height="22" class="notify" /> La resposta ha de ser un nombre...';
		return false;
	}
	
	if($('answer').value == lastValue) {
		return false;
	} else {
		lastValue = $('answer').value;
	}
	
	$('bigfail').style.display = 'none';
	if($('answer').value == currentAnswer) {
		$('write_answer').innerHTML = '';
		$('answer').value = '';
		$('correct').style.display = 'block';
		fadeSuccessImage();
		updateStats(correct=1, total=1);
		newQuestion();
	} else {
		$('correct').style.display = 'none';
		if(tries == 0) {
			msg = 'Ui, intenta-ho una altra vegada.'
		} else if(tries == 1) {
			msg = 'No l\'has encertada... Torna-ho a provar!'
		} else {
			$('write_answer').innerHTML = '';
			$('bigfail').style.display = 'block';
			newQuestion();
			return false;
		}
		$('write_answer').innerHTML = '<img src="./images/img_no.gif" width="22" height="22" class="notify" /> '+msg;
		tries += 1;
	}
}

function newQuestion() {
	lastValue = '';
	customDifficulty = operations[currentType]['custom_difficulty']
	if($('write_answer').innerHTML != '' || $('bigfail').style.display != 'none') {
		updateStats(correct=0, total=1)
	}
	$('question_text').innerHTML = 'Carregant...';
	if(customDifficulty == 1) {
		level = 0;
	} else if(customDifficulty == 2) {
		// Warning: Remember to change the "60" if we change it in ajax.php.
		level = 60 + operations[currentType]['points'];
	} else {
		level = operations[currentType]['points'];
	}
	ajax = newAjax('GET', './ajax.php?opt=get&type='+currentType+'&level='+level, true);
	ajax.onreadystatechange = function() {
		if(ajax.readyState == 4) {
			array = ajax.responseText.split('\n', 2);
			if(array[0] == $('question_text').innerHTML) {
				return newQuestion();
			} else {
				currentAnswer = array[1];
				$('question_text').innerHTML = array[0];
				$('answer').focus();
			}
		}
	};
}

