// Code JS pour site ArcanaPercipio

// Browser sniffer
var IS_IE6 = navigator.userAgent.toLowerCase().indexOf("msie 6.") != -1;

function helloWorld() {
	var _txt;
	var _rdm = Math.floor(20 * Math.random());
	switch (_rdm) {
		case 1: _txt = "Un site pour (presque) apprendre en s'amusant (presque)."; break;
		case 2: _txt = "Félicitations, vous êtes le 0000000" + (1 + Math.floor(5 * Math.random())) + "ème visiteur sur ce site !"; break;
		case 3: 
			_rdm = ["(résolûment optimiste)", "(visiblement sous-exploité)", "(désespérement vide)"];
			_txt = "Espace annonceurs : ... " + _rdm[Math.floor(_rdm.length * Math.random())] + "."; 
			break;
		case 4: _txt = "Site hébergé en France puisque sans but lucratif."; break;
		case 5: _txt = "Le premier site mondial en Web 0.0"; break;
		case 6: _txt = "Elu \"Meilleur site en chantier\" sans interruption depuis 2001."; break;
		case 7: _txt = "En mémoire de notre graphiste, parti bien trop tôt..."; break;
		case 8: _txt = "Un petit site sur les départementales de l'information."; break;
		case 9: _txt = "Un site révolutionnaire, garanti sans aucune technologie AJAX."; break;
		case 10: 
			_rdm = ["Google", "Bill", "Microsoft", "Hacker", "Pentium", "Bug"];
			_txt = "Nous sommes le " + new Date().toLocaleDateString() + ": Saint " + _rdm[Math.floor(_rdm.length * Math.random())] + ".";
			break;
		case 11: _txt = "Résultats du sondage d'hier - ne se sont pas prononcés: 100%"; break;
		case 12: _txt = "L'informatique pour les (anciens) nuls."; break;
		case 13: _txt = "\"Sexe, gros seins, Paris Hilton, comment payer moins d'impôts...\" (subtile politique de référencement)"; break;
		case 14:
			_rdm = ["comptable", "graphiste", "expert en référencement"];
			 _txt = "Donne " + _rdm[Math.floor(_rdm.length * Math.random())] + ", très peu servi, contre bons soins..."; 
			 break;
		case 15: _txt = "Attention, peinture fraîche."; break;
		default:
			var _now = new Date();
			var K_WEEK_DAYS = ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"];
			var _hour = _now.getHours();
			_txt = " de " + (_hour ? _hour - 1 : _hour) + "h00 à " + ((_hour < 24) ? _hour + 1 : _hour) + "h00.";
			_txt = "Horaires d'ouverture du site: le " + K_WEEK_DAYS[_now.getDay()] + _txt;
			break;
	}
	document.getElementById("hello").appendChild(document.createTextNode(_txt));
}

function switchVisibility(node, visibility) {
	// node: Noeud ou nom du noeud concerné
	// visibility: true / false ou none / block ou hidden / visible. Si non renseigné, inverse la propriété courante
	// PS: "inherit" serait préférable à "block" mais IE7 refuse display: inherit
	if (typeof node == "string") node = document.getElementById(node);
	if (node == null) return;
	if ((visibility == false) || (visibility == "hidden")) visibility = "none";
	if ((visibility == true) || (visibility == "visible")) visibility = "block";							
	if ((visibility != "none") && (visibility != "block")) visibility = (node.style.display == "none" ? "block" : "none");
	node.style.display = visibility;
}

function openMenuWindow(wndName) {
	var menu_wnds = ["plan", "feedback", "technotes", "wanted", "copyright"];
	for(var i = 0; i < menu_wnds.length; i++)
		switchVisibility(menu_wnds[i], (menu_wnds[i] == wndName) ? null : false)
}

function createAndInsert(tag, attributes, node, mode) {
	// Création d'un noeud et insertion dans le document
	var _new = document.createElement(tag);
	for(var _attr in attributes) {_new[_attr] = attributes[_attr];}
	switch (mode) {
		case "insert": // Insertion juste avant node
			node.parentNode.insertBefore(_new, node); break;
		case "replace": // Substitution de node (qui est alors effacé)
			node.parentNode.replaceChild(_new, node); break;
		case "swallow": // Insertion à la place de node (qui devient enfant du noeud créé)
			node.parentNode.insertBefore(_new, node);
			_new.appendChild(node.parentNode.removeChild(node));
			break;
		case "append": // Ajout comme dernier enfant de node
		default:
			node.appendChild(_new);
	}
	return _new;
}

function attachTooltip(node, tooltip, href) {
	if (typeof(tooltip) == "string") {
		tooltip = document.createTextNode(tooltip);
	}
	if (href == undefined) href = "javascript:void(0)";
	var ttip_node = createAndInsert("a", {className: "tt", href: href}, node, "swallow");
	var ttip_span = createAndInsert("span", {className: "tt"});
	ttip_span.appendChild(tooltip);
	ttip_node.appendChild(ttip_span);
}

function onLoad() {
	// Fonction de rappel de fin de chargement de page
	// Fonctions locales-------------------------------------------------------------------------------------------------------------------
	function buildPlan() {
		function registerTitles(node, titles_arr) {
			for(var _node = node.firstChild; _node != null; _node = _node.nextSibling) {
				if (_node.nodeType == 1 && _node.nodeName.length == 2 && _node.nodeName.charAt(0).toUpperCase() == "H") {
					var _lvl = parseInt(_node.nodeName.charAt(1));					
					var anchor_name = "title" + titles_arr.length;
					createAndInsert("a", {name: anchor_name, id: anchor_name}, _node, "insert"); // Création de l'ancre au niveau du titre
					titles_arr.push({level: _lvl, text: _node.firstChild.nodeValue});
				}
				else {registerTitles(_node, titles_arr);}
			}
		}
		//
		var _titles = [];
		var base_url = "http://www.arcanapercipio.com/design/"
		registerTitles(document.getElementById("content"), _titles); // Recensement des titres de la leçon
		var plan_html = "<img src=\"" + base_url + "plan_23.png\" width=\"20\" height=\"20\" /><a href=\"#introduction\">Introduction</a><br />"; // Introduction
		// Création de l'arborescence du plan
		var is_last = [false, false, false, false, false, false, false]; // Tableau indiquant si le dernier titre d'un niveau donné est le dernier ou non
		var _nb = _titles.length;
		for(var _idx = 0; _idx < _nb; _idx++) {
			var _lvl = _titles[_idx]["level"];
			if (_lvl != 1) { // Les titres H1 ne sont jamais les derniers de la hiérarchie (puisque la conclusion clot le plan)
				is_last[_lvl] = true;
				for(var _sub = _idx + 1; _sub < _nb; _sub++) {
					if (_titles[_sub]["level"] > _lvl) continue;
					is_last[_lvl] = ! (_titles[_sub]["level"] == _lvl);
					break;
				}
			}
			for(var i = 1; i <= _lvl; i++) { // Dessin de l'arborescence pour la ligne donnée
				if (_lvl > i) plan_html += ("<img src=\"" + base_url + (is_last[i] ? "plan_0" : "plan_13") + ".png\" width=\"20\" height=\"20\" />");
				else plan_html += ("<img src=\"" + base_url + (is_last[i] ? "plan_12" : "plan_123") + ".png\" width=\"20\" height=\"20\" />");
			}
			plan_html += ("<a href=\"#title" + _idx + "\">" + _titles[_idx]["text"] + "</a><br />");
		}
		plan_html += "<img src=\"" + base_url + "plan_12.png\" width=\"20\" height=\"20\" /><a href=\"#conclusion\">Conclusion</a><br />"; // Conclusion
		document.getElementById("treeplan").innerHTML = plan_html;
	}
	//
	function buildKeywordsList() { // Constitution de la liste des mots clefs
		function sortKeywords(a, b) {
			if (a.firstChild.nodeValue.toUpperCase() < b.firstChild.nodeValue.toUpperCase()) return -1;
				else return 1;
		}
		//
		var _keywords = new Array();
		var _nodes = document.getElementsByTagName("span");
		var _nb = _nodes.length;
		for(var i = 0; i < _nb; i++) { // Recensement des mots-clefs
			if (_nodes[i].className == "kw") _keywords.push(_nodes[i]);
		}
		_nb = _keywords.length;
		_keywords.sort(sortKeywords); // Tri alphabétique des mots clefs
		var keylist_html = "";
		var last_initial = ""; // Utilisé pour la mise en valeur de l'initiale du premier mot-clef commençant par une lettre donnée
		for(var i = 0; i < _nb; i++) {
			var _node = _keywords[i];
			var _kw = _node.firstChild.nodeValue;
			var anchor_name = "kw" + i;
			createAndInsert("a", {name: anchor_name, id: anchor_name}, _node, "insert"); // Création de l'ancre au niveau du mot-clef
			var _initial = _kw.charAt(0).toUpperCase();
			keylist_html += ("<a href=\"#kw" + i + "\">");
			if (_initial == last_initial) keylist_html += _kw;
				else {
					keylist_html += ("<span class=\"kwi\">" + _initial + "</span>" + _kw.substr(1));
					last_initial = _initial;
				}
			keylist_html += ("</a>. ");
		}
		document.getElementById("kw_list").innerHTML = keylist_html;
	}
	//
	function processDisplay() { // Formatage des balises
		// Gestion des div ctx / xpd
		var _nodes = document.getElementsByTagName("div");
		var _nb = _nodes.length;
		for(var i = 0; i < _nb; i++) {
			if (_nodes[i].className == "ctx") {
				var _node = _nodes[i];
				var parent_div = _node.parentNode;
				var xpd_div = _node.nextSibling;
				parent_div.onclick = function() {// Gestionnaire onClick
					var _child = this.firstChild;
					while(_child = _child.nextSibling) {
						if (_child.className == "xpd") {
							_child.style.display = (_child.style.display == "block") ? "none" : "block";
							break;
						}
					}
				}
			}
		}
		// Gestion des liens
		var _nodes = document.getElementById("lesson").getElementsByTagName("a");
		var _nb = _nodes.length;
		for(var i = 0; i < _nb; i++) {
			var _node = _nodes[i];
			var _href = _node["href"];
			if ((_node.className == "tt") && (_href.substr(-1, 1) == "#")) _node["href"] = "javascript:void()";
			else if ((_href.indexOf("http") == 0) && (_href.indexOf("arcanapercipio")== -1))
				createAndInsert("img", {className: "icon", src: "http://www.arcanapercipio.com/design/i_extlink.png"}, _node, "insert"); // lien externe
		}
	}
	// ------------------------------------------------------------------------------------------------------------------------------------------
	openMenuWindow(); // Initialise les fenêtres de menu
	helloWorld();
	if (document.getElementById("plan")) {
		buildPlan(); // Création du plan	
		buildKeywordsList(); // Création de la liste des mots clefs
		processDisplay(); // Formatage des DIV
	}
}

/*
function createWindow(htmlTitle, htmlContent, wndWidth, wndHeight, wndX, wndY) {
	// Création d'une fenêtre de type DIV.window
	var screen_width = window.screen.availWidth; // Largeur et hauteur de la fenêtre du navigateur
	var screen_height = window.screen.availHeight;
	if (isNaN(wndWidth) || (wndWidth < 50)) wndWidth = 500; // Largeur par défaut
	if (isNaN(wndHeight) || (wndHeight < 50)) wndHeight = 375; // Hauteur par défaut
	window.alert("wN = " + screen_width + " hN = " + screen_height + " wW = " + wndWidth + " wH = " + wndHeight);
	if (isNaN(wndX)) wndX = (screen_width - wndWidth) / 2;
	if (isNaN(wndY)) wndY = (screen_height - wndHeight) / 2;
	var _wnd = document.createElement("DIV");
	_wnd["className"] = "window";
	document.getElementById("wrapper").appendChild(_wnd);
	_wnd.style.width = wndWidth + "px"; // Dimensionnement et positionnement de la fenêtre
	_wnd.style.height = wndHeight + "px";
	_wnd.style.left = wndX + "px";
	_wnd.style.top = wndY + "px";
	var _title = document.createElement("DIV"); // Création du champ titre de la fenêtre
	_title["className"] = "title";
	_title.innerHTML = htmlTitle;
	_wnd.appendChild(_title);
	var _closeBtn = document.createElement("DIV") // Création du bouton de fermeture
	_closeBtn["className"] = "close_btn";
	_closeBtn.onClick = _wnd.parentNode.removeChild(_wnd);
	_wnd.appendChild(_closeBtn);
	var _content = document.createElement("DIV"); // Création du contenu de la fenêtre
	_content["className"] = "content";
	_content.innerHTML = htmlContent;
	_wnd.appendChild(_content);
}
*/

