var ie = (document.all)? true:false;
var urlAjax = 'http://www.kerkristal.com/v2/post.php5';
var boundaryString = '001176:28234324-kerkristal-2324:9823';
var boundary = '--' + boundaryString;


/* Renvoie un style selon le navigateur */
function myGetStyle(el) {
	if (ie)
		return el.className
	else
		return el.getAttribute('class');
}

/* Bascule droite/gauche d'une image */
function inverserImage(idImgContenu) {
        var styleActuel = myGetStyle(document.getElementById(idImgContenu));
        alert("styleActuel = " + styleActuel);
	if (styleActuel == "imgContenu")
		mySetStyle(document.getElementById(idImgContenu), "imgContenuDroite");
	else
		mySetStyle(document.getElementById(idImgContenu), "imgContenu");
        var newStyle = myGetStyle(document.getElementById(idImgContenu));
        alert("newStyle = " + newStyle);
}

/* Affichage d'une notification AJAX */
function notifyUser(text) {
	document.getElementById('infosAjax').textContent = text;
	mySetStyle(document.getElementById('infosAjax'), "infosAjax");
}

/* Masquage de la zone de notifications AJAX */
function hideNotify() {
	mySetStyle(document.getElementById('infosAjax'), "hiddenElement");
}

/* Monte la position d'un menu */
function monterMenu(myid, numeroMenu) {
	var idlang = document.getElementById('IdLang').value;
	var upperNode = document.getElementById('pageMenu'+numeroMenu).previousSibling;

	if (upperNode == null) return;
	if (upperNode.id.substr(0,8) != 'pageMenu') return;

	//inverser les menus (haut/bas)
	document.getElementById('menu').insertBefore(document.getElementById('pageMenu'+numeroMenu), upperNode);

	notifyUser("Envoi numero...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="NumeroMenu"\n'
	+ '\n'
	+ '-1' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="class"\n'
	+ '\n'
	+ 'sousMenu' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdLang"\n'
	+ '\n'
	+ idlang + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdMenu"\n'
	+ '\n'
	+ myid + '\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}

/* Baisse la position d'un menu */
function baisserMenu(myid, numeroMenu) {
	var idlang = document.getElementById('IdLang').value;
	var lowerNode = document.getElementById('pageMenu'+numeroMenu).nextSibling;

	if (lowerNode == null) return;
	if (lowerNode.id.substr(0,8) != 'pageMenu') return;

	//inverser les menus (haut/bas)
	document.getElementById('menu').insertBefore(lowerNode, document.getElementById('pageMenu'+numeroMenu));

	notifyUser("Envoi numero...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="NumeroMenu"\n'
	+ '\n'
	+ '1' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="class"\n'
	+ '\n'
	+ 'sousMenu' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdLang"\n'
	+ '\n'
	+ idlang + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdMenu"\n'
	+ '\n'
	+ myid + '\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}

/* Monte la position d'une page au sein d'un menu */
function monterPage(myid, classPage, numeroPage, pere) {
	var idlang = document.getElementById('IdLang').value;
	var upperNode = document.getElementById(classPage+numeroPage).previousSibling;

	if (upperNode == null) return;
	if (upperNode.id.substr(0, classPage.length) != classPage) return;

	//inverser les menus (haut/bas)
	document.getElementById(pere).insertBefore(document.getElementById(classPage+numeroPage), upperNode);

	notifyUser("Envoi numero...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="NumeroPage"\n'
	+ '\n'
	+ '-1' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="class"\n'
	+ '\n'
	+ 'page' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdLang"\n'
	+ '\n'
	+ idlang + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdPage"\n'
	+ '\n'
	+ myid + '\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}

/* Baisse la position d'une page au sein d'un menu */
function baisserPage(myid, classPage, numeroPage, pere) {
	var idlang = document.getElementById('IdLang').value;
	var lowerNode = document.getElementById(classPage+numeroPage).nextSibling;

	if (lowerNode == null) return;
	if (lowerNode.id.substr(0, classPage.length) != classPage) return;

	//inverser les menus (haut/bas)
	document.getElementById(pere).insertBefore(lowerNode, document.getElementById(classPage+numeroPage));

	notifyUser("Envoi numero...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="NumeroPage"\n'
	+ '\n'
	+ '1' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="class"\n'
	+ '\n'
	+ 'page' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdLang"\n'
	+ '\n'
	+ idlang + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdPage"\n'
	+ '\n'
	+ myid + '\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}

/* Ajout d'un contenu */
function addContenuForm(){
	var newEl = document.createElement('div');
	var ran_number=Math.floor(Math.random()*(-50));
	/* On lui affecte un identifiant temporaire */
	newEl.setAttribute('id','contenu'+ran_number);
	
	/* On prépare la page en y ajoutant un contenu temporaire */
	newEl.appendChild(document.createTextNode("Creation..."));
	if (document.getElementById('liste_contenus').firstChild.id == "pageVide") {
		document.getElementById('liste_contenus').removeChild(document.getElementById('liste_contenus').firstChild);
	}
	document.getElementById('liste_contenus').appendChild(newEl);
	/* Et on envoie la requète AJAX */
	ajax_texte(ran_number, "");
}

/* Suppression d'un contenu */
function deleteContenu(myid) {
	if (confirm('Etes-vous sur de vouloir supprimer ce contenu ?')) {
		notifyUser("Suppression contenu...");

		var requestbody = boundary + '\n'
		+ 'Content-Disposition: form-data; name="action"\n'
		+ '\n'
		+ 'delete\n'
		+ boundary + '\n'
		+ 'Content-Disposition: form-data; name="IdContenu"\n'
		+ '\n'
		+ myid + '\n'
		+ boundary;

		sendData('POST', urlAjax, requestbody, myid);
	}
}

/* On monte un contenu */
function monterContenu(myid) {
	var idpage = document.getElementById('IdPage').value;
	var idlang = document.getElementById('IdLang').value;

	var upperNode = document.getElementById('contenu'+myid).previousSibling;
	if (upperNode == null) return;

	//inverser les images de cote
	var upperImgId = upperNode.id.replace("contenu", "imgContenu");
	inverserImage(upperImgId);
	inverserImage('imgContenu'+myid);

	//inverser les contenus (haut/bas)
	
	// On recupere la valeur du texte
	var oldTexte = dijit.byId('divTexte'+myid).attr("value");
	// on detruit l'ancien composant DOJO (qui ne supporte pas trop le deplacement)
	dijit.byId('divTexte'+myid).destroy();
	// On deplace notre contenu
	document.getElementById('liste_contenus').insertBefore(document.getElementById('contenu'+myid), upperNode);
        // on recréée le DIV contenant le composant DOJO
	document.getElementById('texte'+myid).innerHTML = ' <div class="divTexte" id="divTexte'+myid+'" >' + oldTexte + '</div>';
	
 	// et on recree le composant DOJO lui-même
        var edit = new dijit.InlineEditBox({onChange:function (value)
		{
		   ajax_texte(myid, value);
		}, editor: "dijit.Editor", editorParams: "{height: '12px', extraPlugins: ['dijit._editor.plugins.AlwaysShowToolbar']}", renderAsHtml: true, autoSave: false}, dojo.byId('divTexte'+myid));
			
        // Maintenant envoyons tout ca par AJAX
	notifyUser("Envoi numero...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdContenu"\n'
	+ '\n'
	+ myid + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="NumeroContenu"\n'
	+ '\n'
	+ '-1' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdPage"\n'
	+ '\n'
	+ idpage + '\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}

/* On baisse un contenu */
function baisserContenu(myid) {
	var idpage = document.getElementById('IdPage').value;
	var idlang = document.getElementById('IdLang').value;

	var lowerNode = document.getElementById('contenu'+myid).nextSibling;
	if (lowerNode == null) return;

	//inverser les images de cote
	var lowerImgId = lowerNode.id.replace("contenu", "imgContenu");
	inverserImage(lowerImgId);
	inverserImage('imgContenu'+myid);

	//inverser les contenus (haut/bas)
	
	// On recupere la valeur du texte
	var oldTexte = dijit.byId('divTexte'+myid).attr("value");
	// on detruit l'ancien composant DOJO (qui ne supporte pas trop le deplacement)
	dijit.byId('divTexte'+myid).destroy();
	// On deplace notre contenu
	document.getElementById('liste_contenus').insertBefore(lowerNode, document.getElementById('contenu'+myid));
        // on recréée le DIV contenant le composant DOJO
	document.getElementById('texte'+myid).innerHTML = '<div class="divTexte" id="divTexte'+myid+'" >' + oldTexte + '</div>';
	// et on recree le composant DOJO lui-même
        var edit = new dijit.InlineEditBox({onChange:function (value)
		{
		   ajax_texte(myid, value);
		}, editor: "dijit.Editor", editorParams: "{height: '12px', extraPlugins: ['dijit._editor.plugins.AlwaysShowToolbar']}", renderAsHtml: true, autoSave: false}, dojo.byId('divTexte'+myid));
		
        // Maintenant envoyons tout ca par AJAX
	notifyUser("Envoi numero...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdContenu"\n'
	+ '\n'
	+ myid + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="NumeroContenu"\n'
	+ '\n'
	+ '1' + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdPage"\n'
	+ '\n'
	+ idpage + '\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}


/* Envoi d'une modification de titre par AJAX */
function ajax_titre(myid, mytitre) {
	var idpage = document.getElementById('IdPage').value;
	var idlang = document.getElementById('IdLang').value;

	notifyUser("Envoi titre...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="titre"\n'
	+ '\n'
	+ mytitre + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="class"\n'
	+ '\n'
	+ 'page\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdLang"\n'
	+ '\n'
	+ idlang + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdPage"\n'
	+ '\n'
	+ idpage + '\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}

/* Envoi d'une modification de titre de menu par AJAX */
function ajax_titreMenu(myid, mytext) {
	var idlang = document.getElementById('IdLang').value;

	notifyUser("Envoi texte...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="titre"\n'
	+ '\n'
	+ mytext + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdLang"\n'
	+ '\n'
	+ idlang + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdMenu"\n'
	+ '\n'
	+ myid + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="class"\n'
	+ '\n'
	+ 'sousMenu\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}

/* Envoi d'une modification de texte de contenu par AJAX */
function ajax_texte(myid, mytext) {
        /* Si myId n'est pas un nombre, c'est probablement qu'un seul argument nous a ete fourni : le texte */
	if (isNaN(myid)) {
		mytext = myid;
		myid = this.id.replace("divTexte", "");
	}
	var idpage = document.getElementById('IdPage').value;
	var idlang = document.getElementById('IdLang').value;

	notifyUser("Envoi texte...");

	var requestbody = boundary + '\n'
	+ 'Content-Disposition: form-data; name="texte"\n'
	+ '\n'
	+ mytext + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdLang"\n'
	+ '\n'
	+ idlang + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdContenu"\n'
	+ '\n'
	+ myid + '\n'
	+ boundary + '\n'
	+ 'Content-Disposition: form-data; name="IdPage"\n'
	+ '\n'
	+ idpage + '\n'
	+ boundary;

	sendData('POST', urlAjax, requestbody, myid);
}

/* Envoi d'une photo par AJAX */
function jsUpload(upload_field)
{
    var re_text = /\.jpg|\.JPG/i;
    var filename = upload_field.value;

    /* Checking file type */
    if (filename.search(re_text) == -1)
    {
        alert("Ce fichier n\'est pas une image valide !");
        upload_field.form.reset();
        return false;
    }
	notifyUser("Envoi photo...");
    upload_field.form.submit();
    return true;
}

/* Suppression d'une photo par AJAX */
function ajax_photo(myid) {
	if (confirm('Etes-vous sûr de vouloir supprimer cette photo ?')) {
		var myfichier = "";
		document.getElementById('photo'+myid).value = "";

		var idpage = document.getElementById('IdPage').value;

		// prepare the MIME POST data
		var requestbody = boundary + '\n'
		+ 'Content-Disposition: form-data; name="IdContenu"\n'
		+ '\n'
		+ myid + '\n'
		+ boundary + '\n'
		+ 'Content-Disposition: form-data; name="IdPage"\n'
		+ '\n'
		+ idpage + '\n'
		+ boundary + '\n'
		+ 'Content-Disposition: form-data; name="photo"\n'
		+ '\n'
		+ '\n'
		+ boundary;

		// do the AJAX request
		sendData('POST', urlAjax, requestbody, myid);
	}
}

/* Envoi technique AJAX */
function sendData(method, url, data, oldid) {
	var xmlhttp = getHTTPObject();
	if (!xmlhttp)
	    return false;

	/* on definit ce qui doit se passer quand la page repondra */
    xmlhttp.onreadystatechange= function() {
    	if (xmlhttp.readyState == 4) { /* 4 : etat "complete" */
        	if (xmlhttp.status == 200) { /* 200 : code HTTP pour OK */
				requestdone(xmlhttp, oldid);
			}
		}
	}
	xmlhttp.open(method, url, true);
	xmlhttp.setRequestHeader("Content-type", "multipart/form-data; charset=utf-8; boundary=\"" + boundaryString + "\"");
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.setRequestHeader("Content-length", data.length);
	xmlhttp.send(data);
}

/* Recuperation d'une requete AJAX selon le navigateur */
function getHTTPObject() {
	var xmlhttp;
	/* Compilation conditionnelle d'IE */
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
	    	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
	        try {
	           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	        } catch (E) {
	           xmlhttp = false;
	        }
		}
  	@else
 		xmlhttp = false;
  	@end @*/

	/* on essaie de creer l'objet si ce n'est pas deja fait */
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
        	xmlhttp = new XMLHttpRequest();
     	} catch (e) {
        	xmlhttp = false;
     	}
	}
	return xmlhttp;
}


/* Gestion des reponses AJAX */
function requestdone(xmlhttp, oldid) {
	//alert("reponse : "+xmlhttp.responseText);
	hideNotify();
	var resultXML = xmlhttp.responseXML;
	if (resultXML.getElementsByTagName('error').length != 0) {
		notifyUser("Error !!!");
		alert('An error occured : '+resultXML.getElementsByTagName('error')[0].textContent);
	} else {
		if (resultXML.getElementsByTagName('id').length == 1) {
			var newid = resultXML.getElementsByTagName('id')[0].textContent;
			// Suppression 
			if (newid == "-1") {
				if (resultXML.getElementsByTagName('class')[0].textContent == 'contenu') {
					var nextContenu = document.getElementById('contenu'+oldid).nextSibling;
					while (nextContenu != null) {
						var lowerImgId = nextContenu.id.replace("contenu", "imgContenu");
						inverserImage(lowerImgId);
						nextContenu = document.getElementById(nextContenu.id).nextSibling;
					}
					document.getElementById('liste_contenus').removeChild(document.getElementById('contenu'+oldid));
					if (document.getElementById('liste_contenus').childNodes.length == 0) {
						document.getElementById('liste_contenus').innerHTML = '<div id="pageVide">Il n\'y a actuellement aucun contenu pour cette page !</div>';
					}
					var di = dijit.byId('divTexte'+oldid);
					di.destroy();
				} else if (resultXML.getElementsByTagName('class')[0].textContent == 'photo') {
					 document.getElementById('divPhoto'+oldid).innerHTML = '';
				}
		        // Creation 
			} else if (oldid != newid) {
				var imgClass = 'imgContenuDroite';
				var old=document.getElementById('contenu'+oldid);
				old.id = 'contenu'+newid;

				//calcul du cote de l'image
				var upperNode = document.getElementById('contenu'+newid).previousSibling;
				if (upperNode != null) {
					var upperImgId = upperNode.id.replace("contenu", "imgContenu");
                                        var style = myGetStyle(document.getElementById(upperImgId));
					if (style == "imgContenuDroite") {
			 			imgClass = "imgContenu";
					}
				}

				var pwet = '<div class="formContenu">' +
							' <div class="numContenu">' +
								' <div class="monterContenu" onclick="monterContenu(\''+newid+'\')"></div>' +
								' <div class="unBouton supprimer" onclick="deleteContenu(\''+newid+'\')"></div>' +
								' <div class="baisserContenu" onclick="baisserContenu(\''+newid+'\')"></div>' +
							' </div>' +
							' <div id="imgContenu'+newid+'" class="'+imgClass+'">' +
								'<div class="boutonSupprimer" onclick="ajax_photo(\''+newid+'\')"></div>' +
								' <div class="divPhoto" id="divPhoto'+newid+'"></div>' +
								' <div class="champPhoto">' +
									'<form action="post.php5" target="upload_iframe" method="post" enctype="multipart/form-data">' +
										'<input type="hidden" name="IdContenu" value="'+newid+'">' +
										'<input id="photo'+newid+'" type="file" name="photo'+newid+'" class="buttonTransparent" onmouseover="this.className=\'buttonForm\'" onmouseout="this.className=\'buttonTransparent\'" onChange="jsUpload(this)" />' +
									'</form>\n' +
								' </div>' +
							' </div>' +
							' <div class="texteContenu" id="texte'+newid+'">' +
								' <div class="divTexte" id="divTexte'+newid+'">' +
								'</div>' +
							' </div>' +
						' </div>';
				document.getElementById('contenu'+newid).innerHTML = pwet;
				var inlineTextBox = new dijit.InlineEditBox({onChange:function (value)
				{
				        ajax_texte(newid, value);
				}, editor: "dijit.Editor", editorParams: "{height: '12px', extraPlugins: ['dijit._editor.plugins.AlwaysShowToolbar']}", renderAsHtml: true, autoSave: false}, dojo.byId('divTexte'+newid));
			}
			// Pas de "else modification" : la page est deja a jour
                        // Dans tous les cas : envoi OK.
			notifyUser("Envoi reussi !");
		}
		window.setTimeout("hideNotify()",2000);
	}
}


