/* Any JavaScript here will be loaded for all users on every page load. */
/**************                 TEST                    ***************/

// Funzioni (8) per generare i test
// Autore: MFH
// Parametri:
// opArray: Array con operatori e numeri
// posArray: Array delle posizioni
function opSolve(opArray, posArray) {
	var opDivided = new Array(Array(opArray[posArray[0]][0]));
	var posDivided = new Array(Array(posArray[0], 0));	// Posizione, length-1
	var opDivInd = 0;
	for(var i = 1; i < posArray.length; i++) {	// Separa le differenti parentesi
		if(posArray[i] == posArray[i-1] + 1) {
			opDivided[opDivInd].push(opArray[posArray[i]][0]);
			posDivided[opDivInd][1] = posDivided[opDivInd][1] + 1;
		}
		else {
			opDivInd = opDivInd + 1;
			posDivided.push(Array(posArray[i], 1));
		}
	}
	for(var i = 0; i <= opDivInd; i++) {
		for(var j = 1; j < opDivided[opDivInd].length - 1; j++) {
			if(opDivided[i][j] == '^') {
				opDivided[i][j-1] = Math.pow(parseFloat(opDivided[i][j-1]),parseFloat(opDivided[i][j+1]));
				opDivided[i].splice(j, 2);
				j = j - 1;
			}
		}
		for(var j = 1; j < opDivided[opDivInd].length - 1; j++) {
			if(opDivided[i][j] == '*') {
				opDivided[i][j-1] = parseFloat(opDivided[i][j-1])*parseFloat(opDivided[i][j+1]);
				opDivided[i].splice(j, 2);
				j = j - 1;
			}
			if(opDivided[i][j] == '/') {
				opDivided[i][j-1] = parseFloat(opDivided[i][j-1])/parseFloat(opDivided[i][j+1]);
				opDivided[i].splice(j, 2);
				j = j - 1;
			}
		}
		for(var j = 1; j < opDivided[opDivInd].length - 1; j++) {
			if(opDivided[i][j] == '+') {
				opDivided[i][j-1] = parseFloat(opDivided[i][j-1])+parseFloat(opDivided[i][j+1]);
				opDivided[i].splice(j, 2);
				j = j - 1;
			}
			if(opDivided[i][j] == '-') {
				opDivided[i][j-1] = parseFloat(opDivided[i][j-1])-parseFloat(opDivided[i][j+1]);
				opDivided[i].splice(j, 2);
				j = j - 1;
			}
		}
	}
	for(var i = posDivided.length -1; i >= 0; i--) {
		opArray[posDivided[i][0]] = Array(opDivided[i][0], opArray[posDivided[i][0]][1] - 1);
		opArray.splice(posDivided[i][0]+1, posDivided[i][1]);
	}
	return opArray;
}

// Parametri:
// operation: Stringa contenente l'espressione da risolvere
// xValue: Valore della variabile x nella stringa
function mathParser(operation, xValue) {
var opArray = new Array();
var brInd = 0;		/* Bracket index */
var brIndMax = 0;

	for(var i = 0; i < operation.length; i++) {	// Divide la stringa in singoli caratteri
		var textChunk = operation.substr(i,1);
		if(textChunk != ' ') {		// Rimuove spazi inutili
			if(textChunk == '(') {		// Rimuove le parentesi conservando l'informazione
				brInd = brInd + 1;
				if(brInd > brIndMax) {
					brIndMax = brInd;
				}
			}
			else if(textChunk == ')') {
				brInd = brInd - 1;
			}
			else if(textChunk == 'x') {
				opArray.push(Array(xValue, brInd));
			}
			else {
				opArray.push(Array(textChunk, brInd));
			}
		}
	}
	i = 0;
	while(i < opArray.length - 1) {	// Rimette assieme i numeri
		if((opArray[i][0].match(/[0-9\.]/) || (opArray[i][0].match(/-/) && (i == 0 || opArray[i-1][1] < opArray[i][1]))) && opArray[i+1][0].match(/[0-9\.]/)) {
			// Se è un numero o una virgola, o se c'è un meno all'inizio di una parentesi; e il carattere successivo è un numero o una virgola
			opArray[i][0] = opArray[i][0] + opArray[i+1][0];
			opArray.splice(i+1, 1);
		}
		else {
			i++;
		}
	}
	for(var i = brIndMax; i >= 0; i--) {
		var posArray = new Array();
		for(var j = 0; j < opArray.length; j++) {
			if(opArray[j][1] == i) {
				posArray.push(j);
			}
		}
		opArray = opSolve(opArray, posArray);
	}
	return opArray[0][0];
}

function chooseTag() {
    if (mw.config.get('wgNamespaceNumber') < 0) {
        return false;
    }
    return 'mw-content-text';
}

var testGroups = new Array(); // Array associativo, ogni elemento è associato al nome del gruppo del test
	// Sintassi: testGroups[nomeGruppo][domanda][risposta]
	// nomeGruppo: Nome dato attraverso l'attributo group nel tag test
	// domanda: Numero che identifica la domanda, solo ad uso interno
	// risposta: Numero che identifica il testo della risposta, alternato al valore di ogni risposta
var testResults = new Array(); // Array associativo, contiene i risultati dei test
	// Sintassi: testResults[nomeGruppo][profilo]
	// nomeGruppo: Come sopra
	// profilo: Numero che identifica il testo dei profili, alternato al valore massimo di ogni profilo
function createTags() {
        if(window.location.href.toLowerCase().indexOf("test:") == -1) return;
	var parentTag = chooseTag();
	if(!parentTag) {
		return;
	}
	var page = $('#' + parentTag);
	var pageOld = page.clone(true);
	pageOld = pageOld.remove('table.diff:first').html();
	var pageNew = pageOld.replace(/\&lt; ?(\/?) ?test(result)?\b(.*?)\&gt\;/g, '<$1test$2$3>').replace(/\&lt; ?(\/?) ?abc(result)?\b(.*?)\&gt\;/g, '<$1abc$2$3>');
	page.html(page.html().replace(pageOld, pageNew));
	return;
}

function displayTest() {
	var tagId = chooseTag();
	if(!tagId) {
		return;
	}
	$('test').each(function() {
		var test = $(this);
		if(test.attr('group')) {
			var testGroup = test.attr('group');
		}
		else {
			var testGroup = 'test';
		}
		if(test.attr('type')) {
			var testType = test.attr('type');
		}
		else {
			var testType = 'mct';
		}
		if(testGroups[testGroup]) {
			testGroups[testGroup].push(test.html().split('|'));
		}
		else {
			testGroups[testGroup] = new Array(test.html().split('|'));
		}
		var testPos = testGroups[testGroup].length - 1;
		var testStructure = $('<form></form>');
		var testTitle = $('<div></div>').css('font-weight', '700').html(testGroups[testGroup][testPos][0]);
		testStructure.append(testTitle);
		for(var i = 0; i < (testGroups[testGroup][testPos].length - 1) / 2; i++) {
			var testInput = $('<input />').attr('class', 'test');
			var testLabel = $('<label></label>');
			if(testType == 'sct' || testType == 'single') {
				testInput.attr({
					'type': 'radio',
					'name': testGroup,
					'value': testGroups[testGroup][testPos][2 * i + 2]
				});
				testLabel.html(testGroups[testGroup][testPos][2 * i + 1]);
				testStructure.append(testInput, ' ', testLabel, '<br />');
			}
			else if(testType == 'ins' || testType == 'insert') {
				testInput.attr({
					'type': 'text',
					'name': testGroup,
					'value': '0',
					'alt': testGroups[testGroup][testPos][2 * i + 2]
				});
				testLabel.html(testGroups[testGroup][testPos][2 * i + 1]);
				testStructure.append(testLabel, ' ', testInput, '<br />');
			}
			else { // For testType == 'mct' or testType == 'multi'
				testInput.attr({
					'type': 'checkbox',
					'name': testGroup,
					'value': testGroups[testGroup][testPos][2 * i + 2]
				});
				testLabel.html(testGroups[testGroup][testPos][2 * i + 1]);
				testStructure.append(testInput, ' ', testLabel, '<br />');
			}
		}
		test.replaceWith(testStructure);
	});

	$('testresult').each(function() {
		var testResult = $(this);
		if(testResult.attr('group')) {
			var resultGroup = testResult.attr('group');
		}
		else {
			var resultGroup = 'test';
		}
		if(testResult.html().split('|').length > 1) {
			testResults[resultGroup] = testResult.html().split('|');
		}
		else {
			testResults[resultGroup] = null;
		}
		var resultStructure = $('<div></div>');
		var resultSubmit = $('<input />').attr({
			'type': 'submit',
			'name': resultGroup,
			'value': 'Risultato',
		}).click(function() {
			calculateTestResult(resultGroup);
		});
		var resultText = $('<div></div>').attr('id', resultGroup);
		resultStructure.append(resultSubmit, resultText);
		testResult.replaceWith(resultStructure);
	});
	return;
}

// Parametri:
// group: Nome del gruppo
function calculateTestResult(group) {
	if (testGroups[group]) {
		var resultScore = 0;
		$('input.test[name=' + group + ']:checked(:checkbox,:radio)').each(function() {
			resultScore += parseFloat($(this).attr('value'));
		});
		$('input.test[name=' + group + ']:text').each(function() {
			if(!$(this).attr('value')) {
				resultScore += mathParser($(this).attr('alt'), 0);
			}
			else {
				resultScore += mathParser($(this).attr('alt'), $(this).attr('value'));
			}
		});
		if (testResults[group]) {
			var resultProfile = '';
			if(resultScore <= parseFloat(testResults[group][2])) {
				resultProfile = testResults[group][1];
			}
			else if(testResults[group].length >= 4) {
				for(var i = 1; i < testResults[group].length / 2 - 1; i++) {
					if(resultScore > parseFloat(testResults[group][2 * i]) && resultScore <= parseFloat(testResults[group][2 * i + 2])) {
						resultProfile = testResults[group][2 * i + 1];
					}
				}
				if(!resultProfile) {
					resultProfile = testResults[group][testResults[group].length - 1];
				}
			}
			var resultTitle = $('<div></div>').css('font-weight', '700').html(testResults[group][0]);
			$('#' + group).html('').append(resultTitle, 'Hai ottenuto ' + resultScore + ' punti.<br />', resultProfile);
		}
		else {
			$('#' + group).html('Hai ottenuto ' + resultScore + ' punti.');
		}
	}
	else {
		$('#' + group).html('Errore! Gruppo non riconosciuto. Ricontrollare il codice per favore.');
	}
	return;
}

var abcGroups = new Array(); // Array associativo, ogni elemento è associato al nome del gruppo del test abc
	// Sintassi: abcGroups[nomeGruppo][domanda][risposta]
	// nomeGruppo: Nome dato attraverso l'attributo group nel tag abc
	// domanda: Numero che identifica la domanda, solo ad uso interno
	// risposta: Numero che identifica il testo della risposta
var abcResults = new Array();	// Array associativo, contiene i risultati dei test abc
	// Sintassi: abcResults[nomeGruppo][profilo]
	// nomeGruppo: Come sopra
	// profilo: Numero che identifica il testo dei profili
function displayAbc() {
	var tagId = chooseTag();
	if(!tagId) {
		return;
	}
	$('abc').each(function() {
		var abc = $(this);
		if(abc.attr('group')) {
			var abcGroup = abc.attr('group');
		}
		else {
			var abcGroup = 'abc';
		}
		if(abcGroups[abcGroup]) {
			abcGroups[abcGroup].push(abc.html().split('|'));
		}
		else {
			abcGroups[abcGroup] = new Array(abc.html().split('|'));
		}
		var abcPos = abcGroups[abcGroup].length - 1;
		var abcStructure = $('<form></form>');
		var abcTitle = $('<div></div>').css('font-weight', '700').html(abcGroups[abcGroup][abcPos][0]);
		abcStructure.append(abcTitle);
		for(var i = 0; i < abcGroups[abcGroup][abcPos].length - 1; i++) {
			var abcInput = $('<input />').attr({
				'class': 'abc',
				'type': 'radio',
				'name': abcGroup,
				'value': i
			});
			var abcLabel = $('<label></label>').html(String.fromCharCode(i + 65) + ': ' + abcGroups[abcGroup][abcPos][i + 1]);
			abcStructure.append(abcInput, ' ', abcLabel, '<br />');
		}
		abc.replaceWith(abcStructure);
	});

	$('abcresult').each(function() {
		var abcResult = $(this);
		if(abcResult.attr('group')) {
			var resultGroup = abcResult.attr('group');
		}
		else {
			var resultGroup = 'abc';
		}
		if(abcResult.html().split('|').length > 1) {
			abcResults[resultGroup] = abcResult.html().split('|');
			for(var i = 1; i < abcResults[resultGroup].length; i++) {
				abcResults[resultGroup][i] = '<span style="font-weight: 700;">Maggioranza di ' + String.fromCharCode(i + 64) + ":</span> " + abcResults[resultGroup][i];
			}
		}
		var resultStructure = $('<div></div>');
		var resultSubmit = $('<input />').attr({
			'type': 'submit',
			'name': resultGroup,
			'value': 'Risultato',
		}).click(function() {
			calculateAbcResult(resultGroup);
		});
		var resultText = $('<div></div>').attr('id', resultGroup);
		resultStructure.append(resultSubmit, resultText);
		abcResult.replaceWith(resultStructure);
	});
	return;
}

// Parametri:
// group: Nome del gruppo
function calculateAbcResult(group) {
	if (abcGroups[group]) {
		var inputButtons = document.getElementsByTagName('input');
		var resultScore = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
		var resultMax = 0;
		var resultMaxProfiles = new Array();
		$('input.abc[name=' + group + ']:radio:checked').each(function() {
			resultScore[parseInt($(this).attr('value'))] += 1;
		});
		for(var i = 0; i < resultScore.length; i++) {
			if(resultScore[i] > resultMax) {
				resultMax = resultScore[i];
			}
		}
		for(var i = 0; i < resultScore.length; i++) {
			if(resultScore[i] == resultMax) {
				resultMaxProfiles.push(i);
			}
		}
		if(abcResults[group]) {
			var resultTitle = $('<div></div>').css('font-weight', '700').html(abcResults[group][0]);
			$('#' + group).html('').append(resultTitle);
			for(var i = 0; i < resultMaxProfiles.length; i++) {
				if(abcResults[group][resultMaxProfiles[i] + 1] != undefined) {
					$('#' + group).append('<br />' + abcResults[group][resultMaxProfiles[i] + 1]);
				}
			}
		}
		else {
			
			var resultResponse = 'Hai ottenuto una maggioranza di ';
			for (var j = 0; j < resultMaxProfiles.length; j++) {
				resultResponse += String.fromCharCode(resultMaxProfiles[j] + 65) + ', ';
			}
			resultResponse = resultResponse.slice(0, resultResponse.length - 2);
			$('#' + group).html('').append(resultResponse);
		}
	}
	else {
		$('#' + group).html('Errore! Gruppo non riconosciuto. Ricontrollare il codice per favore.');
	}
	return;
}