/*

Form & Overlay script par Hydromel.

Contient un module de loading, d'overlay par une page, un systeme de tooltip par lecture XML ainsi qu'un système d'envoi de <form> par methode POST

Envoi ajax de formulaire :

	dans la balise <form> mettre : onSubmit="ax_postform(formname, output_type, destination, retfield);" où :
		- formname sera égal à this.form
		- output_type sera égal à "none" "div" ou "alert" :
			* none : ne renvoie aucune information indiquant que le formulaire a bien été pris en compte
			* div : Renvoie dans un <div> la page vers laquelle est envoyée le formulaire. Fonctionne avec retfield. (Attention : renvoie la page complète telle qu'elle arrive et non un return de la fonction de réception !)
			* alert : Comme <div> mais renvoie dans une fenetre de type alert();. Le retfield n'est alors pas requis
		- destination correspond à la page vers laquelle est envoyée le formulaire pour traitement
		- retfield est l'id de la <div> vers laquelle vous renvoyez le résultat du traitement. si vous inscrivez "overlay", celà va renvoyer le résultat sur l'overlay utilisé pour le loading sous forme de fausse popup (voir i-dessous) 
		

Pour une overlay de type loading utiliser la commande affiche_overlay(image); 
								où image sera la location de l'image de loading.
								
Pour une overlay de type page utiliser la commande affiche_overlay(image,url,1); 
						où image sera la location de l'image de loading, et url 
						sera la location de la page à afficher.

Pour afficher un tooltip utiliser onmouseover="tooltip.show(this,file,index)" onmouseout="tooltip.hide(this)
						où file sera le fichier xml a parse et index la balise xml de la recherche.
						
Ne pas oublier de déclarer en début de document :

- Pour le loading :
	<div id="overlay" class="calque"></div>   

- Pour l'overlay (loading à déclarer obligatoirement !):
	<div id="window" class="window"><iframe class = "contemp_window" id = "contempwindow" name = "contempwindow"></iframe></div>

- Pour les tooltip :
	<div id="tooltip"></div>



*/

var w3c=document.getElementById && !document.all;
var ie=document.all;
if (ie||w3c) {
 var overlay;
 var overlay_all;
 var inajax;
 var my_window;
}

function loadXML(dname) 
{
	if (window.XMLHttpRequest)
	{
		xhttp=new XMLHttpRequest();
	}
	else
	{
		xhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xhttp.open("GET",dname,false);
	xhttp.send("");
	return xhttp.responseXML;
}
var tooltip = {
    id:"tooltip",
    offsetx : 10,
    offsety : 10,
    _x : 0,
    _y : 0,
    _tooltipElement:null,
    _saveonmouseover:null
}

function affiche_overlay(load_img,toshow,new_window){ // mettre new_window à 1 si vous souhaitez afficher une page et non un loading
	disploading("<table class = 'image_div' valign = 'center' border = '0' align = 'center' height='100%'><tr><td> <IMG  SRC='"+load_img+"'></td></tr>"); // loading
	toshow ? new_window ? (new_window == 1) ? montrefenetre(toshow) : ajaxtoframe(toshow) : "" : ""
}

function ajaxtoframe(toshow) {
	getXhr();
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4 && xhr.status == 200)
		{
				overlay_all = document.all ? document.all["overlay_all"] : document.getElementById ? document.getElementById("overlay_all") : "";
				overlay = document.all ? document.all["overlay"] : document.getElementById ? document.getElementById("overlay") : "";
				overlay.innerHTML = xhr.responseText;
				overlay.style.opacity = ".80";
				overlay.style.filter = "alpha(opacity=80)";
				inajax = document.all ? document.all["inajax"] : document.getElementById ? document.getElementById("inajax") : "";
				inajax.style.opacity = ".80";
				inajax.style.filter = "alpha(opacity=80)";
				inajax.style.visibility = "visible";
				overlay_all.style.visibility = "visible";
				overlay.style.visibility = "visible";
		}
	}
	xhr.open("GET",toshow,true);
	xhr.send(null);
}

function disploading(text) {
	if (w3c||ie){
		overlay_all = document.all ? document.all["overlay_all"] : document.getElementById ? document.getElementById("overlay_all") : "";
		overlay = document.all ? document.all["overlay"] : document.getElementById ? document.getElementById("overlay") : "";
		overlay.innerHTML = text 
		overlay_all.style.visibility = "visible";
		overlay.style.visibility = "visible";
	}
}

function montrefenetre(url_s) {
	if (w3c||ie){
		cachetout();
		my_window = document.all ? document.all['window'] : document.getElementById ? document.getElementById('window') : ""
		my_window.style.visibility = "visible";
		my_window = document.all ? document.all['contempwindow'] : document.getElementById ? document.getElementById('contempwindow') : ""
		my_window.style.visibility = "visible";
		frames['contempwindow'].location.href= url_s ;
	}
}

function cachetout() {
	if (w3c||ie){
	my_window = parent.document.getElementById('window');
	my_window.style.visibility = "hidden";
	my_window = parent.document.getElementById('contempwindow');
	my_window.style.visibility = "hidden";
	my_window = document.all ? parent.document.all['overlay'] : parent.document.getElementById ? parent.document.getElementById('overlay') : ""
	my_window.style.visibility = "hidden";
	my_window = document.all ? parent.document.all['overlay_all'] : parent.document.getElementById ? parent.document.getElementById('overlay_all') : ""
	my_window.style.visibility = "hidden";
	my_window = document.all ? parent.document.all['inajax'] : parent.document.getElementById ? parent.document.getElementById('inajax') : ""
	my_window ? my_window.style.visibility = "hidden" : ""
	}
}

tooltip.show = function (htmlelement,xml_file,xml_index) {
	if(document.getElementById){
        this._tooltipElement = document.getElementById(this.id);
	}else if ( document.all ) {
        this._tooltipElement = document.all[this.id].style;
	}

    this._saveonmouseover = document.onmousemove;
    document.onmousemove = this.mouseMove;
	doc=loadXML(xml_file);
	h=doc.getElementsByTagName(xml_index)[0];
    this._tooltipElement.innerHTML = h.childNodes[0].nodeValue;

    this.moveTo(this._x + this.offsetx , this._y + this.offsety);

    if(this._tooltipElement.style){
        this._tooltipElement.style.visibility ="visible";
    }else{
        this._tooltipElement.visibility = "visible";
    }
   return false;
}
tooltip.hide = function (htmlelement) {
    if(this._tooltipElement.style){
        this._tooltipElement.style.visibility ="hidden";
    }else{
        this._tooltipElement.visibility = "hidden";
    }
    document.onmousemove=this._saveonmouseover;
}
tooltip.mouseMove = function (e) {
    if(e == undefined)
        e = event;

    if( e.pageX != undefined){ 
        tooltip._x = e.pageX;
        tooltip._y = e.pageY;
    }else if(event != undefined && event.x != undefined && event.clientX == undefined){ 
        tooltip._x = event.x;
        tooltip._y = event.y;
    }else if(e.clientX != undefined ){
        if(document.documentElement){
            tooltip._x = e.clientX + ( document.documentElement.scrollLeft || document.body.scrollLeft);
            tooltip._y = e.clientY + ( document.documentElement.scrollTop || document.body.scrollTop);
        }else{
            tooltip._x = e.clientX + document.body.scrollLeft;
            tooltip._y = e.clientY + document.body.scrollTop;
        }
    }else{
        tooltip._x = 0;
        tooltip._y = 0;
    }
    tooltip.moveTo( tooltip._x +tooltip.offsetx , tooltip._y + tooltip.offsety);

}
tooltip.moveTo = function (xL,yL) {
    if(this._tooltipElement.style){
        this._tooltipElement.style.left = xL +"px";
        this._tooltipElement.style.top = yL +"px";
    }else{
        this._tooltipElement.left = xL;
        this._tooltipElement.top = yL;
    }
}

function getXhr()
{
	if(window.XMLHttpRequest) xhr = new XMLHttpRequest(); 
	else if(window.ActiveXObject)
	{  
    	try
	    {
	    	xhr = new ActiveXObject("Msxml2.XMLHTTP");
	    }
		catch (e)
     	{
		    xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	else 
	{ 
		alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest, veuillez le mettre à jour"); 
		xhr = false; 
	} 
}
 


function ax_postform(theform,output_type,destination,retfield)//,output_type,destination,retfield)
{
	var url='';
	theform = document.forms[theform];
	for (i=0; i<theform.elements.length; i++)
	{
		if(((theform.elements[i].type=='radio' ||theform.elements[i].type=='checkbox') && theform.elements[i].checked==true) || (theform.elements[i].type!='radio' && theform.elements[i].type!='checkbox'))
		{
			if(theform.elements[i].type=='select-multiple' || theform.elements[i].type=='select' )
			{
				for(j = theform.elements[i].length-1; j >= 0; j-=1)
				{
					if(theform.elements[i].options[j].selected)
					{
						if(url){url+='&';}
						url+=theform.elements[i].name+'='+theform.elements[i].options[j].value;
					}
				}
			}
		if(url){url+='&';}
		if(theform.elements[i].type!='select-multiple'){  url+=theform.elements[i].name+'='+theform.elements[i].value;}
		}
	}
	affiche_overlay('/images/ajax_loading.gif'); //effacer ca si on en veut pas !
	getXhr();
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4 && xhr.status == 200)
		{
			if(output_type == "none") { cachetout(); }
	  		if(output_type == "alert") { alert(xhr.responseText); cachetout();}
			if(output_type == "div") { 
				var repvalue = xhr.responseText;
				(retfield = "overlay") ? disploading('<table valign="center" border="0" align="center" height="100%"><tr><td><center><font color="#FFFFFF" size="+1">' + repvalue + '</font><br><br><input type="Submit" value="OK" onclick="cachetout();"></center></td></tr></table>') : document.getElementById(retfield).innerHTML =  '<table valign="center" border="0" align="center" height="100%"><tr><td><center><font color="#FFFFFF" size="+1">' + repvalue + '</font><br><br><input type="Submit" value="OK" onclick="cachetout();"></center></td></tr></table>'
			}
		}
	}
	xhr.open("POST",destination,true);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send(url);
	return false;
}

function createRaid(){
	getXhr();
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4 && xhr.status == 200)
		{
			var raidDivObj = document.getElementById('raidcomp');
			raidDivObj.innerHTML = xhr.responseText;
			firstInitDnDScript();
		}
	}
	var urlToEditRaid = "getraidcomp.php?type=newraid";
	xhr.open("GET",urlToEditRaid,true);
	xhr.send(null);
	return false;
}

function editThisRaid(raidId){
	getXhr();
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4 && xhr.status == 200)
		{
			var raidDivObj = document.getElementById('raidcomp');
			var raidDivContent = raidDivObj.innerHTML;
			raidDivObj.innerHTML = xhr.responseText;
			firstInitDnDScript();
		}
	}
	var urlToEditRaid = "getraidcomp.php?type=editraid&raidid=" + raidId;
	xhr.open("GET",urlToEditRaid,true);
	xhr.send(null);
	return false;
}

function showThisRaid(raidId){
	getXhr();
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4 && xhr.status == 200)
		{
			var raidDivObj = document.getElementById('showraidDiv');
			raidDivObj.innerHTML = xhr.responseText;
			if(document.getElementById('raidcomp').innerHTML != ""){
				initDragDropScript();
			}
		}
	}
	var urlToShowRaid = "getraidcomp.php?type=showraid&raidid=" + raidId;
	xhr.open("GET",urlToShowRaid,true);
	xhr.send(null);
	return false;
}

function getInvitString(raidId){
	getXhr();
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4 && xhr.status == 200)
		{
			var raidDivObj = document.getElementById('showraidDiv');
			raidDivObj.innerHTML = xhr.responseText;
			if(document.getElementById('raidcomp').innerHTML != ""){
				initDragDropScript();
			}
		}
	}
	var urlToShowRaid = "getraidcomp.php?type=invitstring&raidid=" + raidId;
	xhr.open("GET",urlToShowRaid,true);
	xhr.send(null);
	return false;
}

function deleteThisRaid(raidId,raidmsg){
	var deleteIsOk = confirm('Vous êtes sur le point de supprimer le raid ' + raidmsg + '. Voulez vous continuer ?');
	if(deleteIsOk){
		getXhr();
		xhr.onreadystatechange = function()
		{
			if(xhr.readyState == 4 && xhr.status == 200)
			{
				showRaidTable();
			}
		}
		var urlToShowRaid = "getraidcomp.php?type=deleteraid&raidid=" + raidId;
		xhr.open("GET",urlToShowRaid,true);
		xhr.send(null);
		return false;
	}
}

function closeRaid(){
	saveDragDropNodes();
	document.getElementById('raidcomp').innerHTML = "";
}

function hideRaidDiv(){
	document.getElementById('showraidDiv').innerHTML = "";
	if(document.getElementById('raidcomp').innerHTML != ""){
		initDragDropScript();
	}
}

function showRaidTable(archives){ // 0 ou 1 selon si l'ont veut afficher les raids archivés.
	getXhr();
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4 && xhr.status == 200)
		{
			var raidDivObj = document.getElementById('raidlist');
			raidDivObj.innerHTML = xhr.responseText;
		}
	}
	var urlToShow = "getraidcomp.php?type=getraidtable";
	xhr.open("GET",urlToShow,true);
	xhr.send(null);
	return false;	
}

function duplicateThisRaid(raidId){
	disploading('<center><input id="newDuplicateRaidName" value="Entrez le nom du raid"><br><input id="submitRaidName" type="submit" onFocus="checkRaidName(this)"></center>');
	var duplicateRaidNameInput = document.getElementById('newDuplicateRaidName');
	document.getElementById('submitRaidName').onclick = function(){
		if((duplicateRaidNameInput.value == "Entrez le nom du raid") || (duplicateRaidNameInput.value == "")){
			alert('Vous devez spécifier un nom de raid !');
		}else{
			getXhr();
			xhr.onreadystatechange = function()
			{
				if(xhr.readyState == 4 && xhr.status == 200)
				{
					var raidDivObj = document.getElementById('raidcomp');
					var resultDuplication = xhr.responseText;
					if(resultDuplication.indexOf("raidIsError") != '-1'){
						cachetout();
						alert('Une erreur s\'est produite, la duplication est impossible');
					}
					else if(resultDuplication.indexOf("raidIsMultiple") != '-1'){
						cachetout();
						alert('Plusieurs raids du même nom existent pour cette semaine. Veuillez sélectionner le raid dans la liste pour l\'éditer' + resultDuplication);
						showRaidTable();
					}else{
						cachetout();
						showRaidTable();
						raidDivObj.innerHTML = resultDuplication;
						initDragDropScript();
					}
				}
			}
			var postToSend = 'raidid=' + raidId + '&newname=' + duplicateRaidNameInput.value;
			var urlToShow = "getraidcomp.php?type=duplicate";
			xhr.open("POST",urlToShow,true);
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			xhr.send(postToSend);
			return false;
		}
	}
}

function archiveThisRaid(raidId,raidmsg){
	var archiveIsOk = confirm('Vous êtes sur le point d\'archiver le raid ' + raidmsg + '. Voulez vous continuer ?');
	if(archiveIsOk){
		getXhr();
		xhr.onreadystatechange = function()
		{
			if(xhr.readyState == 4 && xhr.status == 200)
			{
				document.getElementById('raidcomp').innerHTML = xhr.responseText;
				showRaidTable();
			}
		}
		var postToSend = 'raidid=' + raidId ;
		var urlToShow = "getraidcomp.php?type=archive";
		xhr.open("POST",urlToShow,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(postToSend);
		return false;
	}
}

function updateGuild(){
	getXhr();
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4 && xhr.status == 200)
		{
			document.getElementById('raidcomp').innerHTML = xhr.responseText;

		}
	}
	var url = "getraidcomp.php?type=updateguild";
	xhr.open("POST",url,true);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send(null);
}

function viewArchives(){
	var divArchives = document.getElementById('divArchives');
	var linkArchives = document.getElementById('raidArchiveLink');
	if(divArchives.style.display == 'none'){
		divArchives.style.display = 'block';
		linkArchives.innerHTML = 'Masquer les raids archivés';
	}else{
		divArchives.style.display = 'none';
		linkArchives.innerHTML = 'Voir les raids archivés';
	}
}

