var listeCours;
var prixTotal = 0;
var selectCours;
var listeCoursChoisis = new Array();
var coursCharges = false;

function lireListeCours() {
	$.getJSON('liste-cours.php', traiterListeCours)
}

function traiterListeCours(texteCours) {
// Lecture de la reponse
	selectCours = document.getElementById('liste_cours');
	selectCours.remove(0);

	if(texteCours != null) {
		listeCours = texteCours;

		for(compteurCours in listeCours) {
			objetCours = listeCours[compteurCours];
			coursAAjouter = new Option;
			coursAAjouter.value = objetCours.page;
			coursAAjouter.text = objetCours.titre;
			
			try
			{
				selectCours.add(coursAAjouter, null);
			}
			catch(erreurInutile)
			{
				selectCours.add(coursAAjouter, selectCours.selectedIndex); // Pour Internet Explorer qui ne comprend pas la méthode standard
			}
		}
	}
	
	coursCharges = true;
}

function ajouterCours() {
	coursChoisi = selectCours.options[selectCours.selectedIndex];
	coursAjoute = listeCours[coursChoisi.value];
	formulaireInscription = document.getElementById('inscription');
	var numeroProchainCours = 0;

	for(compteurChamp = 1; compteurChamp < 11; compteurChamp++) {
		nomTemporaire = document.getElementById('cours' + compteurChamp);
	// Si l'élément existe, et que sa valeur est égale au cours qu'on tente d'ajouter, ne pas ajouter le cours
	// i.e. il est impossible de s'inscrire deux fois au même cours.
		if(nomTemporaire != undefined) {
			if(nomTemporaire.value == coursAjoute.numero) return;
		}
	}

	for(compteurChamp = 1; compteurChamp < 11; compteurChamp++) {
		if(document.getElementById('cours' + compteurChamp) == undefined) {
			numeroProchainCours = compteurChamp;
			break;
		}
	}

	if (numeroProchainCours == 0) {
		document.getElementById('message_erreur').innerHTML = 'Un maximum de dix cours est permis par inscription';
	} else {
		// Ajout du cours proprement dit
		listeCoursChoisis.push(coursAjoute);

		// Ajout de l'élément caché pour indiquer que le cours a été ajouté
		var nomElement = 'cours' + numeroProchainCours;
		nouveauCours = document.createElement('input');
		nouveauCours.setAttribute('type', 'hidden');
		nouveauCours.setAttribute('id', nomElement);
		nouveauCours.setAttribute('name', nomElement);
		nouveauCours.setAttribute('value', coursAjoute.numero);
		formulaireInscription.appendChild(nouveauCours);
		
		// Ajout de l'élément caché pour indiquer le choix de date & endroit
		var nomElementDateEndroit = 'dateEndroit' + nomElement;
		nouveauCours = document.createElement('input');
		nouveauCours.setAttribute('type', 'hidden');
		nouveauCours.setAttribute('id', nomElementDateEndroit);
		nouveauCours.setAttribute('name', nomElementDateEndroit);
		nouveauCours.setAttribute('value', 0);
		formulaireInscription.appendChild(nouveauCours);

		tableauAModifier = document.getElementById('liste_cours_affichee');
		if(document.getElementById('corpsTableau') != undefined) corpsTableau = document.getElementById('corpsTableau');
		else {
			corpsTableau = document.createElement('tbody');
			corpsTableau.setAttribute('id', 'corpsTableau');
			tableauAModifier.appendChild(corpsTableau);
		}
		
		nouvelleLigne = document.createElement('tr');
		nouvelleLigne.setAttribute('id', 'ligne-' + nomElement);
	
	// Au cas où les valeurs n'existeraient pas encore	
		//if(coursAjoute.Date[0] == undefined) coursAjoute.Date[0] = 1;
		//if(coursAjoute.Endroit[0] == undefined) coursAjoute.Endroit[0] = 1;
	// Création des éléments qui vont former la ligne (du cours)
		nomAbrege = document.createElement('td');
		nomAbrege.setAttribute('className', 'nom_cours');
		nomAbrege.setAttribute('class', 'nom_cours');
		texteNomAbrege = document.createTextNode(coursAjoute.titre);
		nomAbrege.appendChild(texteNomAbrege);
		cout = document.createElement('td');
		texteCout = document.createTextNode(formatterPrix(coursAjoute.prix));
		cout.appendChild(texteCout);
		date = document.createElement('td');
		date.setAttribute('className', 'date');
		date.setAttribute('class', 'date');
		texteDate = document.createTextNode(coursAjoute.dates[0]);
		date.appendChild(texteDate);
		endroit = document.createElement('td');
		texteEndroit = document.createTextNode(coursAjoute.endroits[0]);
		endroit.appendChild(texteEndroit);

	// Création et ajout de l'image pour effacer un cours
		tdimageEffacer = document.createElement('td');
	// D'abord la façon IE (bizarre mais bon...)
		try {
			imageEffacer = document.createElement('<img src="images/effacer.gif" width="16" height="17" alt="Effacer le cours" title="Effacer le cours" onclick="enleverCours(' + nomElement + ')" />');
	// Tous les autres navigateurs
		} catch(erreurInutile) {
			imageEffacer = document.createElement('img');
			imageEffacer.setAttribute('src', 'images/effacer.gif');
			imageEffacer.setAttribute('width', '16');
			imageEffacer.setAttribute('height', '17');
			imageEffacer.setAttribute('alt', 'Effacer le cours');
			imageEffacer.setAttribute('title', 'Effacer le cours');
			imageEffacer.setAttribute('onclick', 'enleverCours(\'' + nomElement + '\')');
		}

		tdimageEffacer.appendChild(imageEffacer);
		
	// Ajout de tous les éléments à la ligne
		nouvelleLigne.appendChild(nomAbrege);
		nouvelleLigne.appendChild(date);
		nouvelleLigne.appendChild(cout);
		nouvelleLigne.appendChild(endroit);
		nouvelleLigne.appendChild(tdimageEffacer);

	// Ajout de l'image pour changer la date/l'endroit, s'il y a lieu
		tdimageChanger = document.createElement('td');
		try {
			if(coursAjoute.dates.length > 1) {
				try {
					imageChanger = document.createElement('<img src="images/changer_date.gif" width="17" height="17" alt="Changer la date" title="Changer la date" onclick="changerDate(' + nomElement + ')" />');
				} catch(erreurInutile) {
					var imageChanger = document.createElement('img');
					imageChanger.setAttribute('src', 'images/changer_date.gif');
					imageChanger.setAttribute('width', '17');
					imageChanger.setAttribute('height', '17');
					imageChanger.setAttribute('alt', 'Changer la date');
					imageChanger.setAttribute('title', 'Changer la date');
					imageChanger.setAttribute('onclick', 'changerDate(\'' + nomElement + '\')');
				}
					tdimageChanger.appendChild(imageChanger);
			}
		} catch(erreurVide) {
			
		}

		nouvelleLigne.appendChild(tdimageChanger);

	// Ajout de la ligne au tableau
		corpsTableau.appendChild(nouvelleLigne);
		
	// Ajout du coût du cours au prix total et modification de l'affichage du prix total
		prixTotal += parseInt(coursAjoute.prix);
		afficherPrixTotal(corpsTableau);

	// Afficher le tableau (au cas où ce serait la première fois qu'on ajoute un cours)
		tableauAModifier.style.visibility = 'visible';
	}
}

function formatterPrix(prixBrut) {
	return prixBrut + ',00$';
}

function enleverCours(nomElementAEnlever) {
	formulaireInscription = document.getElementById('inscription');
	tableau = document.getElementById('corpsTableau');
	toutLeTableau = document.getElementById('liste_cours_affichee');

	elementAEffacer = document.getElementById(nomElementAEnlever);
	if(elementAEffacer == undefined) elementAEffacer = document.getElementById(nomElementAEnlever.name);
	if(elementAEffacer == undefined) return;
	ligneAEffacer = document.getElementById('ligne-' + nomElementAEnlever);
	if(ligneAEffacer == undefined) ligneAEffacer = document.getElementById('ligne-' + nomElementAEnlever.name);
	if(ligneAEffacer == undefined) return;
	objetTraite = trouverCours(elementAEffacer.value);
	prixTotal -= parseInt(objetTraite.prix);
	
// Retrait de la ligne du tableau et de l'élément du formulaire
	tableau.removeChild(ligneAEffacer);
	formulaireInscription.removeChild(elementAEffacer);

// Cacher le tableau si le dernier élément en a été enlevé (la rangée 0 est l'en-tête)
	if(toutLeTableau.rows[2] == undefined) toutLeTableau.style.visibility = 'hidden';
	else afficherPrixTotal(tableau);
}

function changerDate(nomElementAChanger) {
	elementCourant = document.getElementById(nomElementAChanger);
	if(elementCourant == undefined) return;
	ligneCourante = document.getElementById('ligne-' + nomElementAChanger);
	if(ligneCourante == undefined) return;
	elementDateEndroitCourant = document.getElementById("dateEndroit" + nomElementAChanger);
	if(elementDateEndroitCourant == undefined) return;

	objetAChanger = trouverCours(elementCourant.value);

	var nombreDates = objetAChanger.dates.length;
	var indexProchaineDate = -1;

	for(compteurDate = 0; nombreDates > 1 && compteurDate < nombreDates; compteurDate++) {
		var dateCourante = objetAChanger.dates[compteurDate];
		var endroitCourant = objetAChanger.endroits[compteurDate];

		if(dateCourante == ligneCourante.cells[1].innerHTML && endroitCourant == ligneCourante.cells[3].innerHTML) {
			if(compteurDate + 1 == nombreDates) indexProchaineDate = 0;
			else indexProchaineDate = compteurDate + 1;
			break;
		}
	}
	
// Mise à jour de l'élément caché pour avoir la bonne date et le bon endroit
	elementDateEndroitCourant.value = indexProchaineDate;

// Mise à jour de la date et de l'endroit
	ligneCourante.cells[1].innerHTML = objetAChanger.dates[indexProchaineDate];
	ligneCourante.cells[3].innerHTML = objetAChanger.endroits[indexProchaineDate];
}

function trouverCours(numeroCoursATrouver) {
	for(cours in listeCours) {
		objetCours = listeCours[cours];
		if(objetCours.numero == numeroCoursATrouver) return objetCours;
	}
}

function afficherPrixTotal(corpsTableau) {
	var lignePrixTotal = document.getElementById('ligne-prix-total');
	if(lignePrixTotal != undefined) corpsTableau.removeChild(lignePrixTotal);
	lignePrixTotal = document.createElement('tr');
	lignePrixTotal.setAttribute('id', 'ligne-prix-total');

// Création des éléments qui vont former la ligne (du cours)
	champTextePrixTotal = document.createElement('td');
	champTextePrixTotal.setAttribute('className', 'nom_cours');
	champTextePrixTotal.setAttribute('class', 'nom_cours');
	textePrixTotal = document.createTextNode('Coût total des cours choisis:');
	champTextePrixTotal.appendChild(textePrixTotal);
	champPrixTotal = document.createElement('td');
	champPrixTotal.setAttribute('className', 'date');
	champPrixTotal.setAttribute('class', 'date');
	//champPrixTotal.setAttribute('id', 'prix-total');
	texteVraiPrixTotal = document.createTextNode(formatterPrix(prixTotal));
	champPrixTotal.appendChild(texteVraiPrixTotal);
	champVide = document.createElement('td');
	champVide.colSpan = "4";

// Ajout des éléments à la ligne et de la ligne au tableau
	lignePrixTotal.appendChild(champTextePrixTotal);
	lignePrixTotal.appendChild(champPrixTotal);
	lignePrixTotal.appendChild(champVide);
	corpsTableau.appendChild(lignePrixTotal);
}

function ajouterInscription() {
// à faire pour tous les cours de listeCoursChoisis
	var nomElement = 'cours' + numeroProchainCours;

}
