var nbNotes = 0;
var tabNotes = new Array();
var tabObjectNote = new Array();
var user = new Object();
var tabPapiersPeints = new Array();
var tabFrigos = new Array();
var tabCouleurs = new Array();
var TABCOLOR = new Array("aqua","green","orange","white","black","lime","purple","yellow","blue","maroon","red","fuschia","navy","silver","gray","olive","teal");

function getUserInfo(){
	var xhr = getXHR();
		xhr.onreadystatechange  = function(){
			if(xhr.readyState  == 4){ // terminé
				if(xhr.status  == 200){
					var xml = xhr.responseXML;
					// alert(xml);
					var users = xml.getElementsByTagName('user');
					nbUsers = users.length;
					if(nbUsers!=1) alert("Erreur, impossible de charger les informations de l'utilisateur");
					else{
						var userXML = users.item(0);
						user.id = userXML.getAttribute("id");
						user.login = userXML.getElementsByTagName('login')[0].firstChild.nodeValue;
						user.mail = userXML.getElementsByTagName('mail')[0].firstChild.nodeValue;
						user.wall = userXML.getAttribute("wall");
						user.wallperso = userXML.getAttribute("wallperso");
						user.frigo = userXML.getAttribute("frigo");
						user.droit = userXML.getAttribute("droit");
						setUserStyle();
					}
			}else alert("Erreur "+xhr.status);
		}
	};
	xhr.open( "GET", "ajax.php?action=userInfo",true); 
	xhr.send(null);
}

function setUserStyle(){
	var xhr = getXHR();
		xhr.onreadystatechange  = function(){
			if(xhr.readyState  == 4){ // terminé
				if(xhr.status  == 200){
					var xml = xhr.responseXML;
					var walls = xml.getElementsByTagName('wallpaper');
					var frigos = xml.getElementsByTagName('frigo');
					if(user.wallperso == ""){
						for(var i=0;i<walls.length;i++){
							if(walls.item(i).getAttribute("id") == user.wall){
								document.getElementById('back').style.background = walls.item(i).getElementsByTagName('cssCode')[0].firstChild.nodeValue;
							}
						}
					}else document.getElementById('back').style.background = user.wallperso;
					for(var i=0;i<frigos.length;i++){
						if(frigos.item(i).getAttribute("id") == user.frigo){
							document.getElementById('content').style.background = frigos.item(i).getElementsByTagName('cssCode')[0].firstChild.nodeValue+" 50% 20px no-repeat";
						}
					}
					// au passage on récupère les différents couleurs diposnibles
					var notes = xml.getElementsByTagName('note');
					for(var i=0; i<notes.length;i++){
						var n = notes[i];
						var nO = new Object();
						nO.id = n.getAttribute("id");
						nO.label = n.getElementsByTagName('nom')[0].firstChild.nodeValue;
						nO.hexa = n.getElementsByTagName('hexa')[0].firstChild.nodeValue;
						tabCouleurs.push(nO);
					}					
			}else alert("Erreur "+xhr.status);
		}
	};
	
	xhr.open( "GET", "ressources/personalisation.xml",  true); 
	xhr.send(null);
}

function setUpdateUser(){
	var xhr = getXHR();
	xhr.onreadystatechange  = function(){
		if(xhr.readyState  == 4){ // terminé
			if(xhr.status  == 200){
				var res = xhr.responseText;
				if(res != "ok") alert("Nous n'avons pas pu sauvegarder votre dernière modification suite à une erreur serveur. Veuillez nous excuser pour la gêne occasionnée.");
			}else reception.innerHTML = "Erreur "+xhr.status;
		}
	};
	xhr.open( "POST", "ajax.php?action=userUpdate",true); 
	xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	var data = "wall="+user.wall+"&frigo="+user.frigo+"&wallperso="+user.wallperso;
	xhr.send(data);
}

function setNewNote(){
	var xhr = getXHR();
	xhr.onreadystatechange  = function(){
		if(xhr.readyState  == 4){ // terminé
			if(xhr.status  == 200){
				var xml = xhr.responseXML;
				var notes = xml.getElementsByTagName('note');
				if(notes.length==0) alert("Nous n'avons pas pu créer votre nouvelle note, suite à une erreur serveur, veuillez nous excuser pour la gêne occasionnée.");
				else{
					var noteXML = notes.item(0);
					var note = new Object();
					note.id = noteXML.getAttribute("id");
					note.login = noteXML.getAttribute("login");
					//var regexURL = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
					// note.recto = (noteXML.getElementsByTagName('recto')[0].firstChild.nodeValue).replace(regexURL,"<a class=\"noteLien\" title=\"$3\" href=\"$1://$3\">lien</a>");							
					if(noteXML.getElementsByTagName('recto')[0].firstChild != null){
						note.recto = noteXML.getElementsByTagName('recto')[0].firstChild.nodeValue;
					}else note.recto = "";
					note.left = noteXML.getAttribute("left");
					note.top = noteXML.getAttribute("top");
					note.size = 1;
					note.couleur = noteXML.getAttribute("couleur");
					if(noteXML.getElementsByTagName('verso')[0].firstChild != null){
						//note.verso = (noteXML.getElementsByTagName('verso')[0].firstChild.nodeValue).replace(regexURL,"lien");
						note.verso = noteXML.getElementsByTagName('verso')[0].firstChild.nodeValue;
					}else note.verso = "";
					note.date = formStringToDate(noteXML.getElementsByTagName('date')[0].firstChild.nodeValue);
					note.edition =  formDate(new Date());
					document.getElementById('content').appendChild(creerNote(note));
					setContentAction();
					if(document.getElementById("noNote") != null) document.getElementById("content").removeChild(document.getElementById("noNote"));
				}
			}else reception.innerHTML = "Erreur "+xhr.status;
		}
	};
	xhr.open( "GET", "ajax.php?action=newNote",true); 
	xhr.send(null);
}

function updateNote(idNote,action,editDate){
	var xhr = getXHR();
	xhr.onreadystatechange  = function(){
		if(xhr.readyState  == 4){ // terminé
			if(xhr.status  == 200){
				var res = xhr.responseText;
				if(res != "ok") alert("Nous n'avons pas pu éxécuter votre dernière action suite à une erreur serveur. Veuillez nous excuser pour la gêne occasionnée. (action:"+action+")");
				else if(action=="update"){
					var n = findById(idNote);
					var title = "Créée le "+n.date+"<br/>Dernière édition le "+formDate(new Date());
					document.getElementById("info"+id).setAttribute("title",title);
					$("#info"+id).ToolTip({className: 'tooltipInfo',position: 'mouse',delay: 200});
				}
			}else reception.innerHTML = "Erreur "+xhr.status;
		}
	};
	var n = document.getElementById(idNote);
	var id = idNote.substr(1,idNote.length);
	var left = n.style.left;
	left = left.substr(0,left.length-2);
	var top = n.style.top;
	top = top.substr(0,top.length-2);
	var recto = document.getElementById("contentW"+id).value;
	var size = document.getElementById("w"+id).className == "note" ? 1 : 0;
	var couleur = n.style.backgroundColor;
	couleur = RGBToHex(couleur).substr(1,RGBToHex(couleur).length).toUpperCase();
	var verso = "";
	if(action=="update"){
		xhr.open( "POST", "ajax.php?action=updateNote",true); 
		xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			var data = "editdate="+editDate+"&id="+id+"&recto="+recto+"&verso="+verso+"&left="+left+"&top="+top+"&size="+size+"&couleur="+couleur;
		xhr.send(data);
	}else{
		xhr.open( "POST", "ajax.php?action=deleteNote",true); 
		xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		var data = "id="+id;
		xhr.send(data);

	}
}
function valUpdateNote(){
	var idtmp = this.id;
	var idNote = idtmp.substr(3,idtmp.length);
	updateNote("w"+idNote,"update",true);
}


function creerNotes(){
	var xhr = getXHR();
	var reception = document.getElementById('content');
	document.getElementById('openMenuBouton').style.display = "block";
	reception.innerHTML = "";
	var divEcrire = document.createElement("div");
	var ecrire = document.createElement("a");
	ecrire.setAttribute("href","#");
	divEcrire.setAttribute("id","divWrite");
	ecrire.onclick = setNewNote;
	divEcrire.appendChild(ecrire);
	reception.appendChild(divEcrire);
	if(xhr == null) reception.innerHTML = "Votre navigateur ne supporte pas AJAX, et ne peut afficher correctement les informations.";
	else{
	    xhr.onreadystatechange  = function(){
	        if(xhr.readyState  == 4){ // terminé
			    if(xhr.status  == 200){
						var xml = xhr.responseXML;
						//alert(xml);
						var notes = xml.getElementsByTagName('note');
						nbNotes = notes.length;
						if(nbNotes==0){
							var divCadre = document.createElement("div");
							divCadre.className = "cadre";
							divCadre.setAttribute("id","noNote");
							divCadre.innerHTML = "Vous n'avez pas encore créé de note.<br/>Pour celà, ouvrez le menu en cliquant sur la note en haut à gauche, et suivez le lien \"créer une nouvelle note\".";
							reception.appendChild(divCadre);
						}
						for(var i=0;i<nbNotes;i++){
							var noteXML = notes.item(i);
							var note = new Object();
							note.id = noteXML.getAttribute("id");
							note.login = noteXML.getAttribute("login");
							//var regexURL = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
							// note.recto = (noteXML.getElementsByTagName('recto')[0].firstChild.nodeValue).replace(regexURL,"<a class=\"noteLien\" title=\"$3\" href=\"$1://$3\">lien</a>");							
							if(noteXML.getElementsByTagName('recto')[0].firstChild != null){
								note.recto = noteXML.getElementsByTagName('recto')[0].firstChild.nodeValue;
							}else note.recto = "";
							note.left = noteXML.getAttribute("left");
							note.top = noteXML.getAttribute("top");
							note.size = noteXML.getAttribute("size");
							note.couleur = noteXML.getAttribute("couleur");
							if(noteXML.getElementsByTagName('verso')[0].firstChild != null){
								//note.verso = (noteXML.getElementsByTagName('verso')[0].firstChild.nodeValue).replace(regexURL,"lien");
								note.verso = noteXML.getElementsByTagName('verso')[0].firstChild.nodeValue;
							}else note.verso = "";
							note.date = formStringToDate(noteXML.getElementsByTagName('date')[0].firstChild.nodeValue);
							note.edition = formStringToDate(noteXML.getElementsByTagName('edition')[0].firstChild.nodeValue);
							creerNote(note);
						}
						getUserInfo();
						placerNotes();
						setContentAction();						
				}else reception.innerHTML = "Erreur "+xhr.status;
	         }
	    };
		xhr.open( "GET", "ajax.php?action=notes",  true); 
		xhr.send(null); 
	}
}

function creerNote(note){
	tabObjectNote.push(note);
	var divWindow = document.createElement("div");
	if(note.size==0) divWindow.className = "littleNote";
	else divWindow.className = "note";
	divWindow.style.left = note.left+"px";
	divWindow.style.top = note.top+"px";
	divWindow.setAttribute("id","w"+note.id);							
	divWindow.style.backgroundColor = "#"+note.couleur;

	var topMenu = document.createElement("div");
	topMenu.className = "topMenu";
	var secureWidth = document.createElement("div");
	secureWidth.className = "secureWidth";
	var secureHeight = document.createElement("div");
	secureHeight.className = "secureHeight";
	
	var textAreaContent = document.createElement("textarea");
	textAreaContent.setAttribute("id","contentW"+note.id);
	textAreaContent.setAttribute("rows","20");
	textAreaContent.setAttribute("cols","1");
	textAreaContent.className = "content";
	textAreaContent.innerHTML = note.recto;
	textAreaContent.style.zIndex = 5;
	
	var divOption = document.createElement("div");
	divOption.className = "noteOptionMenu";
	var imgEnregistrer = document.createElement("img");
	imgEnregistrer.setAttribute("src","images/bval.png");
	imgEnregistrer.setAttribute("src","images/bval.png");
	imgEnregistrer.setAttribute("alt","valider");
	imgEnregistrer.setAttribute("title","Cliquez ici pour enregistrer les modifications de texte de cette note.");
	imgEnregistrer.setAttribute("id","val"+note.id)
	imgEnregistrer.className = "boutonVal";	
	imgEnregistrer.onclick = valUpdateNote;	
	divOption.appendChild(imgEnregistrer);
	
	var divSize = document.createElement("div");
	divSize.className = "sizeMenu";	
	var boutonReduce = document.createElement("img");
	boutonReduce.setAttribute("src","images/breduce.png");
	boutonReduce.setAttribute("alt","_");
	boutonReduce.setAttribute("id","red"+note.id);
	boutonReduce.className = "boutonReduce";	
	boutonReduce.onclick = resizeNote;
	divSize.appendChild(boutonReduce);
	var boutonAgrandir = document.createElement("img");
	boutonAgrandir.setAttribute("src","images/bagrand.png");
	boutonAgrandir.setAttribute("alt","+");
	boutonAgrandir.setAttribute("id","agr"+note.id);
	boutonAgrandir.className = "boutonAgrand";	
	boutonAgrandir.onclick = resizeNote;
	divSize.appendChild(boutonAgrandir);
	
	var divInfo = document.createElement("div");
	divInfo.className = "infoMenu";	
	divInfo.setAttribute("title","Créée le "+note.date+"<br/>Dernière édition le "+note.edition);
	var boutonInfo = document.createElement("img");
	boutonInfo.setAttribute("src","images/binfo.png");
	boutonInfo.setAttribute("alt","?");
	boutonInfo.setAttribute("id","info"+note.id);
	divInfo.appendChild(boutonInfo);
	
	var divDel = document.createElement("div");
	divDel.className = "deleteMenu";	
	var boutonDel = document.createElement("img");
	boutonDel.setAttribute("src","images/bdel.png");
	boutonDel.setAttribute("alt","x");
	boutonDel.setAttribute("id","del"+note.id);
	boutonDel.className = "boutonDel";	
	boutonDel.onclick = delNote;
	divDel.appendChild(boutonDel);
	
	var divCouleur = document.createElement("div");
	divCouleur.setAttribute("id","col"+note.id);
	divCouleur.className = "colorMenu";
	divCouleur.style.backgroundColor = "#"+note.couleur;
	divCouleur.onclick = nextColor;
	
	// pour faire les cotés de la note
	var divT = document.createElement("div"); 	divT.setAttribute("id","T"+note.id);	divT.className = "noteT";	divWindow.appendChild(divT);
	var divR = document.createElement("div"); 	divR.setAttribute("id","R"+note.id);	divR.className = "noteR";	divWindow.appendChild(divR);
	var divB = document.createElement("div"); 	divB.setAttribute("id","B"+note.id);	divB.className = "noteB";	divWindow.appendChild(divB);
	var divTL = document.createElement("div");	divTL.setAttribute("id","TL"+note.id);	divTL.className = "noteTL"; divWindow.appendChild(divTL);
	var divL = document.createElement("div"); 	divL.setAttribute("id","L"+note.id);	divL.className = "noteL";	divWindow.appendChild(divL);
	var divTR = document.createElement("div");	divTR.setAttribute("id","TR"+note.id); 	divTR.className = "noteTR";	divWindow.appendChild(divTR);
	var divBL = document.createElement("div");	divBL.setAttribute("id","BL"+note.id); 	divBL.className = "noteBL";	divWindow.appendChild(divBL);
	var divBR = document.createElement("div"); 	divBR.setAttribute("id","BR"+note.id);	divBR.className = "noteBR";	divWindow.appendChild(divBR);
	
	topMenu.appendChild(divInfo);
	topMenu.appendChild(divCouleur);
	topMenu.appendChild(divOption);
	topMenu.appendChild(divSize);
	topMenu.appendChild(divDel);
	// divWindow.appendChild(divDrag);
	divWindow.appendChild(topMenu);
	divWindow.appendChild(secureWidth);
	divWindow.appendChild(secureHeight);
	divWindow.appendChild(textAreaContent);
	tabNotes.push(divWindow);
	return divWindow;
}

function resizeNote(){
	var idNote = this.id.substr(3,this.id.length);
	var n = document.getElementById("w"+idNote);
	if(this.id.substr(0,3) == "red") n.className = "littleNote";
	else{
		n.className = "note";
		$('.note .content').Autoexpand([260,200]);
	}
	updateNote("w"+idNote,"update",false);
}

function delNote(){
	var idB = this.id;
	var idNote = idB.substr(3,idB.length);
	supprimerNote('w'+idNote);
}
function supprimerNote(idDiv){
	if(confirm("Voulez vous vraiment jeter cette note ?")){
		updateNote(idDiv,"delete");
		$('#'+idDiv).Shrink(500);
	}
}

function placerNotes(){
	var reception = document.getElementById('content');
	for(var i=0;i<tabNotes.length;i++){
		var div = tabNotes[i];
		reception.appendChild(div);	
		changeCouleur(tabNotes[i].id,tabNotes[i].style.backgroundColor);
	}
}

function setContentAction(){
	$('.note').Draggable({
		handle:		'div',
		zIndex: 	1000,
		opacity:	0.8,
		snapDistance: 20
	});
	$('.littleNote').Draggable({
		handle:		'div',
		zIndex: 	1000,
		opacity:	0.8,
		snapDistance: 20
	});
	$('.dropzone').Droppable({
		accept :	'note', 
		tolerance:	'pointer',
		ondrop:	function (drag){
			if(this.id == "back"){
				supprimerNote(drag.id);
			}else{
				updateNote(drag.id,"update",false);
				drag.style.zIndex = getNextHighestDepth();
			}
		}
	});
	document.getElementById('menu').style.display = "none";
	
	
	function panelMenu(){
		display(document.getElementById('menu'));
		if(document.getElementById('menu').style.display=="block") 
		menuPrincipal();
	}

	function fermerMenu(){
		if(document.getElementById('menu') != null) document.getElementById('menu').style.display = "none";
	}
	document.getElementById('content').onmouseover = fermerMenu;
	document.getElementById('openMenuBouton').onclick = panelMenu;
	$('.infoMenu').ToolTip({className: 'tooltipInfo',position: 'mouse',delay: 200});
	$('.noteLien').ToolTip({className: 'tooltip',position: 'mouse',delay: 200});
	$('.boutonVal').ToolTip({className: 'tooltip',position: 'mouse',delay: 200});
	$('.note .content').Autoexpand([260,200]);
}

function changerMenu(){
	switch(this.id){
		case "LMpersonalisation": menuPersonalisation(); break;
		default: menuPrincipal();
	}
}

function wallPerso(){
	if(document.getElementById("changeWallperso") == null){
		var wallpersoO = decryptWallPerso();
		var div = document.createElement("div");
		div.setAttribute("id","changeWallperso");
		
		var inputCP = document.createElement("input");
		inputCP.setAttribute("id","CP");
		inputCP.className = "field";
		inputCP.setAttribute("value",wallpersoO.url);
		var labelCP = document.createElement("label");
		labelCP.setAttribute("for","CP");
		labelCP.innerHTML = "URL de votre papier-peint";
		labelCP.className = "texte";
		
		var inputColor = document.createElement("input");
		inputColor.setAttribute("id","CWcolor");
		inputColor.setAttribute("value",wallpersoO.color);
		inputColor.className = "field";
		var labelColor = document.createElement("label");
		labelColor.setAttribute("for","CWcolor");
		labelColor.innerHTML = "Couleur de fond";
		labelColor.className = "texte";
		
		var valide = document.createElement("input");
		valide.setAttribute("value","Valider");
		valide.setAttribute("type","submit");
		valide.setAttribute("id","wpValide");
		valide.onclick = applyWallPerso;
		var annule = document.createElement("input");
		annule.setAttribute("value","Annuler");
		annule.setAttribute("type","submit");
		annule.setAttribute("id","wpAnnule");
		annule.onclick = applyWallPerso;
		var previ = document.createElement("input");
		previ.setAttribute("value","Prévisualiser");
		previ.setAttribute("type","submit");
		previ.setAttribute("id","wpPrevi");
		previ.onclick = applyWallPerso;
		
		
		var repeatx = document.createElement("input");
		repeatx.className = "field";
		if(wallpersoO.repeatx)	repeatx.setAttribute("checked","checked");
		var labelx = document.createElement("label");
		labelx.className = "texte";
		labelx.setAttribute("for","wprx");
		labelx.innerHTML = "Mosaique horizontale";
		repeatx.setAttribute("type","checkbox");
		repeatx.setAttribute("id","wprx");
		repeatx.onclick = applyWallPerso;
		var repeaty = document.createElement("input");
		if(wallpersoO.repeaty)	repeaty.setAttribute("checked","checked");
		repeaty.className = "field";
		var labely = document.createElement("label");
		labely.className = "texte";
		labely.setAttribute("for","wpry");
		labely.innerHTML = "Mosaique verticale";
		repeaty.setAttribute("type","checkbox");
		repeaty.setAttribute("id","wpry");
		repeaty.onclick = applyWallPerso;
		
		var div1 = document.createElement("div");
		var div2 = document.createElement("div");
		var div3 = document.createElement("div");
		var div4 = document.createElement("div");
		var div5 = document.createElement("div");
		var div6 = document.createElement("div");
		var div7 = document.createElement("div");
		
		div1.appendChild(labelCP);
		div1.appendChild(inputCP);
		div2.appendChild(labelColor);
		div2.appendChild(inputColor);
		div3.appendChild(labelx);
		div3.appendChild(repeatx);
		div4.appendChild(labely);
		div4.appendChild(repeaty);
		div5.appendChild(previ);
		div5.className = "bEnvoi";
		div6.appendChild(annule);
		div6.appendChild(valide);
		div6.className = "bEnvoi";
		
		div.appendChild(div1);
		div.appendChild(div2);
		div.appendChild(div3);
		div.appendChild(div4);
		div.appendChild(div5);
		div.appendChild(div6);
		div.appendChild(buildSelectPosition());
		document.getElementById("wrap").appendChild(div);
	}else{
		document.getElementById("wrap").removeChild(document.getElementById("changeWallperso"));
	}
}
function applyWallPerso(){
	var u = "";
	var erreur = false;
	var co = document.getElementById("CWcolor").value;
	if(co != ''){
		if(!tabExists(TABCOLOR,co)){ // si c est pas une couleur "nommée"
			if(co.charAt(0) == '#') co = co.substr(1,co.length);
			if(co.length == 6 || co.length == 3){
				if(!isHexa(co)){
					alert("Votre code couleur ne semble par être correct.");
					erreur = true;
				}else co = "#"+co;
			}else{
				erreur = true;
				alert("Votre code couleur ne semble par être correct.");
			}
		}
	}
	if(erreur) u = '';
	else{	
		u = co+" url("+document.getElementById("CP").value+")";
		var rx = document.getElementById("wprx").checked;
		var ry = document.getElementById("wpry").checked;
		if(!rx && !ry) u += " no-repeat";
		else if(rx && !ry) u += " repeat-x";
		else if(ry && !rx) u += " repeat-y";
		
		var tabPo = new Array("HG","H","HD","G","C","D","BG","B","BD");
		var k=0;
		for(var i=0;i<3;i++){
			for(var j=0;j<3;j++){
				if(document.getElementById("pos"+tabPo[k]).className == "selected"){
					var x = j*50;
					var y = i*50;
					u += " "+x+"% "+y+"%";
				}
				k++;
			}
		}
		
		document.getElementById("back").style.background = u;
	}	
	if(this.type == "submit"){
		if(this.id == "wpAnnule") document.getElementById("back").style.background = tabPapiersPeints[user.wall];
		else{
			if(!erreur){
				user.wallperso = u;
				setUpdateUser();
			}
		}
		if(this.id != "wpPrevi")wallPerso(); // pour refermer
	}
}

function changeWallpaper(){
	user.wall = this.id;
	user.wallperso = '';
	setUpdateUser();
	document.getElementById('back').style.background = tabPapiersPeints[this.id];
}
function changeFrigo(){
	user.frigo = this.id;
	setUpdateUser();
	document.getElementById('content').style.background = tabFrigos[this.id]+" 50% 20px no-repeat";
}
function nextColor(){
	var idn = "w"+this.id.substr(3,this.id.length);
	var thisColor = this.style.backgroundColor;
	var code = RGBToHex(thisColor).substr(1,RGBToHex(thisColor).length);
	code = code.toUpperCase();
	var trouve = false;
	for(var i=0;i<tabCouleurs.length;i++){
		if(code == tabCouleurs[i].hexa){
			trouve = true;
			if(i==tabCouleurs.length-1) changeCouleur(idn,"#"+tabCouleurs[0].hexa);
			else changeCouleur(idn,"#"+tabCouleurs[i+1].hexa);
		}
	}
	if(!trouve) changeCouleur(idn,"#"+tabCouleurs[0].hexa);
	updateNote(idn,"update",false);
}
function changeCouleur(idNote,couleur){
	var idn = idNote.substr(1,idNote.length);
	document.getElementById(idNote).style.backgroundColor = couleur;
	document.getElementById("col"+idn).style.backgroundColor = couleur;
	var code = RGBToHex(couleur).substr(1,RGBToHex(couleur).length);
	code = code.toUpperCase();
	if(code == "FF9500") code = "FF9560";
	document.getElementById("w"+idn).style.backgroundColor = "#"+code;
	document.getElementById("col"+idn).style.backgroundColor = "#"+code;
	document.getElementById("L"+idn).style.background = "url(images/notes/"+code+"/left.png) repeat-y";
	document.getElementById("R"+idn).style.background = "url(images/notes/"+code+"/right.png) repeat-y";
	document.getElementById("T"+idn).style.background = "url(images/notes/"+code+"/top.png) repeat-x";
	document.getElementById("B"+idn).style.background = "url(images/notes/"+code+"/bottom.png) repeat-x";
	document.getElementById("TL"+idn).style.background = "url(images/notes/"+code+"/tl.png) no-repeat";
	document.getElementById("TR"+idn).style.background = "url(images/notes/"+code+"/tr.png) no-repeat";
	document.getElementById("BL"+idn).style.background = "url(images/notes/"+code+"/bl.png) no-repeat";
	document.getElementById("BR"+idn).style.background = "url(images/notes/"+code+"/br.png) no-repeat";
}


function menuPrincipal(){
	var menu = document.getElementById('menu');
	document.getElementById('menu').innerHTML = "";
	var div = document.createElement("div");
	var titre = document.createElement("h2");
	var ul = document.createElement("ul");
	var li1 = document.createElement("li");
	var a1 = document.createElement("a");
	var li2 = document.createElement("li");
	var a2 = document.createElement("a");
	ul.appendChild(li1);
	ul.appendChild(li2);
	li1.appendChild(a1);
	li2.appendChild(a2);
	div.appendChild(titre);
	div.appendChild(ul);
	menu.appendChild(div);
	
	div.className = "menuContent";
	titre.innerHTML = "Menu";
	
	a1.innerHTML = "Créer une nouvelle note";
	a1.setAttribute("id","LMcreation");
	a1.onclick = setNewNote;
	
	a2.setAttribute("id","LMpersonalisation");
	a2.onclick = changerMenu;
	a2.innerHTML = "Personaliser votre cuisine";	
}


function menuPersonalisation(){
	var xhr = getXHR();
	var reception = document.getElementById('menu');
	if(xhr == null) reception.innerHTML = "Votre navigateur ne supporte pas AJAX, et ne peut afficher correctement les informations.";
	else{
	    xhr.onreadystatechange  = function(){
	        if(xhr.readyState  == 4){ // terminé
			    if(xhr.status  == 200){
					var xml = xhr.responseXML;
					var walls = xml.getElementsByTagName('wallpaper');
					document.getElementById('menu').innerHTML = "";
					var ulW = document.createElement("ul");
					for(var i=0; i<walls.length;i++){
						var wall = walls[i];
						var idW = wall.getAttribute("id");
						var wallValue = wall.getElementsByTagName('cssCode')[0].firstChild.nodeValue;
						var wallNom = wall.getElementsByTagName('nom')[0].firstChild.nodeValue;
						var li = document.createElement("li");
						var a = document.createElement("a");
						ulW.appendChild(li);
						li.appendChild(a);
						a.onclick = changeWallpaper;
						a.setAttribute("id",idW);
						a.setAttribute('title','<div style="width:50px;height:50px;background:'+wallValue+';"></div>');
						a.className = "lienWallpaper";
						a.innerHTML = wallNom;
						tabPapiersPeints[idW] = wallValue;
					}
					
					var frigos = xml.getElementsByTagName('frigo');
					var ulF = document.createElement("ul");
					for(var i=0; i<frigos.length;i++){
						var frigo = frigos[i];
						var idF = frigo.getAttribute("id");
						var frigoValue = frigo.getElementsByTagName('cssCode')[0].firstChild.nodeValue;
						var frigoNom = frigo.getElementsByTagName('nom')[0].firstChild.nodeValue;
						var li = document.createElement("li");
						var a = document.createElement("a");
						ulF.appendChild(li);
						li.appendChild(a);
						a.onclick = changeFrigo;
						a.setAttribute("id",idF);
						a.innerHTML = frigoNom;
						tabFrigos[idF] = frigoValue;
					}
					var div = document.createElement("div");
					div.className = "menuContent";
					var titre1 = document.createElement("h2");
					titre1.innerHTML = "Papiers Peints";
					
					var titre2 = document.createElement("h2");
					titre2.innerHTML = "Frigidaires";
					
					var retour = document.createElement("a");
					retour.innerHTML = "retour";
					retour.setAttribute("id","LMprincipal");
					retour.onclick  = changerMenu;
					
					var aPerso = document.createElement("a");
					aPerso.onclick = wallPerso;
					aPerso.setAttribute("id","wallPerso");
					aPerso.setAttribute('title','<div style="width:50px;height:50px;background:'+user.wallperso+';"></div>');
					aPerso.className = "lienWallpaper";
					aPerso.innerHTML = "Créez votre papier-peint!";
					
					div.appendChild(titre1);
					div.appendChild(aPerso);
					
					div.appendChild(ulW);
					div.appendChild(titre2);
					div.appendChild(ulF);
					div.appendChild(retour);
					document.getElementById('menu').appendChild(div);
					$('.lienWallpaper').ToolTip({className: 'previewWallPaper',position: 'mouse',delay: 200});
				}else reception.innerHTML = "Erreur "+xhr.status;
	         }
		};
		xhr.open( "GET", "ressources/personalisation.xml",  true); 
		xhr.send(null); 
	}
}

function afficheLogin(){
	var div = document.getElementById("login");
	var reception = document.getElementById("wrap");
	if(div==null){
		var divLogin = document.createElement("div");
		divLogin.className = "login";
		divLogin.setAttribute("id","login");
		
		var formLogin = document.createElement("form");
		formLogin.setAttribute("id","formLogin");
		formLogin.setAttribute("method","post");
		formLogin.setAttribute("action","forms.php?action=login");
		
		var labelLogin = document.createElement("label");
		labelLogin.setAttribute("for","login");
		labelLogin.innerHTML = "Identifiant";
		var inputLogin = document.createElement("input");
		inputLogin.setAttribute("type","text");
		inputLogin.setAttribute("name","login");
		inputLogin.setAttribute("size","12");
		inputLogin.setAttribute("maxlength","12");
		inputLogin.className = "inputText";	
		var spanLogin = document.createElement("span");
		spanLogin.appendChild(labelLogin);
		spanLogin.appendChild(inputLogin);
		
		var labelPass = document.createElement("label");
		labelPass.setAttribute("for","pass");
		labelPass.innerHTML = "Mot de passe";
		var inputPass = document.createElement("input");
		inputPass.setAttribute("type","password");
		inputPass.setAttribute("name","pass");
		inputPass.setAttribute("size","12");
		inputPass.setAttribute("maxlength","12");
		inputPass.className = "inputText";
		var spanPass = document.createElement("span");
		spanPass.appendChild(labelPass);
		spanPass.appendChild(inputPass);
		
		var inputSubmit = document.createElement("input");
		inputSubmit.setAttribute("type","submit");
		inputSubmit.setAttribute("name","submit");
		inputSubmit.setAttribute("value","ok");
		inputSubmit.className = "inputSubmit";
		var spanSubmit = document.createElement("span");
		spanSubmit.appendChild(inputSubmit);

		formLogin.appendChild(spanLogin);
		formLogin.appendChild(spanPass);
		formLogin.appendChild(spanSubmit);
		divLogin.appendChild(formLogin);
		reception.appendChild(divLogin);
		inputLogin.focus();
	}else{
		if(div.style.display == "block") div.style.display = "none";
		else div.style.display = "block";
	}
}

function isUrl(s){
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}
function isHexa(s){
	var regexp = /[^0-9a-f]/gi
	return !regexp.test(s);
}

function formDate(dO){
	var joursSemaine = new Array("Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi");
	var moisAnnee = new Array("Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre");
	var h = dO.getHours();
	var mi = dO.getMinutes();
	if(h.length==1) h = "0"+h;
	if(mi.length==1) mi = "0"+mi;
	return "<span class=\"date\">"+dO.getDate()+" "+moisAnnee[dO.getMonth()]+" "+dO.getFullYear()+" à "+h+":"+mi+"</span>";
}

function formStringToDate(str){
	var datHeure = str.split(" ");
	var date = datHeure[0].split("-");
	var heure = datHeure[1].split(":");
	var a = date[0];
	var mo = date[1]-1;
	var j = date[2];
	var h = heure[0];
	var mi = heure[1];
	if(heure.length>2) var s = heure[2];
	return formDate(new Date(a, mo, j, h, mi, s));
}

function findById(idN){
	for(var i=0;i<tabObjectNote.length;i++){
		if("w"+tabObjectNote[i].id == idN) return tabObjectNote[i];
	}
	return null;
}

var profondeurMax = 100;
function getNextHighestDepth(){
	document.getElementById("menu").style.zIndex = profondeurMax+100;
	profondeurMax++;
	return profondeurMax;
}

function display(bloc){
	bloc.style.display = bloc.style.display=="none"?"block":"none";
}

function redirection(page){
	document.location.href=page;
}

function tabExists(tab,elem){
	for(var i=0;i<tab.length;i++){
		if(tab[i] == elem) return true;
	}
	return false;
}	
	
function decryptWallPerso(){
	var res = new Object();
	var tab = user.wallperso.split(" ");
	if(tabExists(TABCOLOR,tab[0]) || tab[0].charAt(0) == "#"){
		res.color = tab[0];
		res.url = tab[1].substr(4,tab[1].length-5);
	}else res.url = tab[0].substr(4,tab[0].length-5);
	var rxX = new RegExp("repeat-x");
	var rxY = new RegExp("repeat-y");
	var rxNR = new RegExp("no-repeat");
	var rx = rxX.test(user.wallperso);
	var ry = rxY.test(user.wallperso);
	var rnr = rxNR.test(user.wallperso);
	
	res.repeatx = rxX.test(user.wallperso);
	res.repeaty = rxY.test(user.wallperso);
	
	if(!rx && !ry && !rnr){
		res.repeatx = true;
		res.repeaty = true;
	}else if(rnr){
		res.repeatx = false;
		res.repeaty = false;
	}
	return res;	
}

function buildSelectPosition(){
	var div = document.createElement("div");
	div.setAttribute("id","positionSelector");
	var divHG = document.createElement("div"); divHG.setAttribute("id","posHG"); divHG.onclick = changeWallpersoPos;
	var divH = document.createElement("div"); divH.setAttribute("id","posH");	 divH.onclick = changeWallpersoPos;
	var divHD = document.createElement("div"); divHD.setAttribute("id","posHD"); divHD.onclick = changeWallpersoPos;
	var divG = document.createElement("div"); divG.setAttribute("id","posG");	 divG.onclick = changeWallpersoPos;
	var divC = document.createElement("div"); divC.setAttribute("id","posC");	 divC.onclick = changeWallpersoPos;
	var divD = document.createElement("div"); divD.setAttribute("id","posD");	 divD.onclick = changeWallpersoPos;
	var divBG = document.createElement("div"); divBG.setAttribute("id","posBG"); divBG.onclick = changeWallpersoPos;
	var divB = document.createElement("div"); divB.setAttribute("id","posB");	 divB.onclick = changeWallpersoPos;
	var divBD = document.createElement("div"); divBD.setAttribute("id","posBD"); divBD.onclick = changeWallpersoPos;
	div.appendChild(divHG); div.appendChild(divH); div.appendChild(divHD);
	div.appendChild(divG); 	div.appendChild(divC); div.appendChild(divD);
	div.appendChild(divBG); div.appendChild(divB); div.appendChild(divBD);
	return div;
}

function changeWallpersoPos(){
	var tabPo = new Array("HG","H","HD","G","C","D","BG","B","BD");
	for(var i=0;i<tabPo.length;i++){
		document.getElementById("pos"+tabPo[i]).style.backgroundColor = "#FFFFFF";
		document.getElementById("pos"+tabPo[i]).className = "";
	}
	this.style.backgroundColor = "#AAA";
	this.className = "selected";
	applyWallPerso();
}

function RGBToHex(colorString) {
	HexDigits = "0123456789abcdef";
	if (colorString.charAt(0) == '#') return colorString;
	else {
		colorString = colorString.substr(4);
		pos = colorString.indexOf(',');
		Result = '#' + HexDigits.substr(Math.floor(colorString.substr(0, pos) / 16), 1) + HexDigits.substr(colorString.substr(0, pos) % 16, 1);
		colorString = colorString.substr(pos + 1);
		pos = colorString.indexOf(',');
		Result = Result + HexDigits.substr(Math.floor(colorString.substr(0, pos) / 16), 1) + HexDigits.substr(colorString.substr(0, pos) % 16, 1);
		colorString = colorString.substr(pos + 1);
		Result = Result + HexDigits.substr(Math.floor(colorString.substr(0, pos) / 16), 1) + HexDigits.substr(colorString.substr(0, pos) % 16, 1);
		return Result;
	}
}

function getXHR(){
	var xhr = null;
    try{
		xhr = new ActiveXObject('Msxml2.XMLHTTP');
	}catch (e){
        try{
			xhr = new ActiveXObject('Microsoft.XMLHTTP');
		}catch (e2){
	        try{
				xhr = new XMLHttpRequest();
			}catch(e3){
				xhr = false;
			}
        }
    }
	return xhr;
}
