/**
 * AdminMenu()
 * Erzeugt ein dynamisches Menue, in dem ein DIV mit den 
 * Menueinhalt (Liste mit Links) angelegt und ins Dokument 
 * eingehangen wird.
 * Autor: Micheal Lösler <derletztekick.com>
 *
 * version 0.2 (last mofified: 22.01.2008)
 *
 * - bestimme optimale Groesse des Menues via offsetWidth|Height
 * - schliesse Menu bei onmousout-Event
**/
AdminMenu = function() {

	//CSS
	this.finalOpacity = 1;
	this.finalWidth  = 180; // Wert hier setzen oder in setVisible() setzen lassen
	this.finalHeight = 0;

	//Der Hauptcontainer
	this.mainDIV = document.createElement("div");
	this.mainDIV.id = "javBoardAdminMenu";
	this.mainDIV.style.position = "absolute";

	this.mainDIV.Instanz = this;
	this.mainDIV.onmouseout = function(e) {
		// Event-Bubble, da das ueberfahren von Child-Elementen den
		// mouseout-Event feuert. 
		// http://forum.de.selfhtml.org/archiv/2006/11/t140567/#m913521
		if(!this.parentNode) 
			return;
		if(!e) 
			e = window.event;
			
    var related = e.relatedTarget || e.toElement;
    while (related && related != this) {
			related = related.parentNode;
      if (related == this)
				return;
		}
		if (related != this) //Modifiziert: Scheint trotzdem noetig zu sein
			this.Instanz.setVisible(false);
	};
	
	
/*
> - Thema löschen --> TopciEdit(ID, 'DeleteRestore') 
> - Thema aktivieren --> TopciEdit(ID, 'AktivateReActivate')
> - Thema schließen --> TopciEdit(ID, 'DeleteRestore')
> - Thema oben festhalten --> TopciEdit(ID, 'Sticky')
> - Präfix bearbeiten --> TopciEdit(ID, 'EditPrefix')
> - Titel umbenennen --> TopciEdit(ID, 'ThreadTopic')
*/
	
	//Das Menue
	this.postOptions = new Object();	
  this.postOptions.comDelete = document.createElement("a");
	this.postOptions.Delete = document.createElement("a");
	this.postOptions.Activ  = document.createElement("a");
	this.postOptions.Topic = document.createElement("a");
	this.postOptions.EditComment = document.createElement("a");
	this.postOptions.EditTopic = document.createElement("a");
  /*
  this.postOptions.comDelete.icon = "./images/menuIcons/isDelete.png";
	this.postOptions.Delete.icon = "./images/menuIcons/isDelete.png";
	this.postOptions.Activ.icon  = "./images/menuIcons/isActiv.png";
	this.postOptions.Topic.icon  = "./images/menuIcons/isClose.png";	
	this.postOptions.EditComment.icon  = "./images/menuIcons/isClose.png";	
	this.postOptions.EditTopic.icon  = "./images/menuIcons/isClose.png";
*/
	this.postOptions.comDelete.msg = [" ", "Endgültig Löschen"];
	this.postOptions.Delete.msg = ["Löschen", "Wiederherstellen"];
	this.postOptions.Activ.msg  = ["Aktivieren", "Deaktivieren"];
	this.postOptions.Topic.msg  = ["Titel umbenennen", "Titel umbenennen"]; 
	this.postOptions.EditComment.msg  = ["Beitrag schnell editieren", "Beitrag schnell editieren"]; 
	this.postOptions.EditTopic.msg  = ["Beitrag editieren", "Beitrag editieren"]; 
	   
	this.postOptions.comDelete.key = "isDelete";
	this.postOptions.Delete.key = "isDelete";
	this.postOptions.Activ.key  = "isActiv";
	this.postOptions.Topic.key  = "isTopic"; 
	this.postOptions.EditComment.key  = "isComment"; 
	this.postOptions.EditTopic.key  = "isComment";
	
	this.postOptions.comDelete.value = "CompleteDelete";
	this.postOptions.Delete.value = "DeleteRestore";
	this.postOptions.Activ.value  = "ActivateReActivate";
	this.postOptions.Topic.value  = "PostTopic";
	this.postOptions.EditComment.value  = "QuickEditPost";
	this.postOptions.EditTopic.value  = "EditPost";
	
	this.postOptions.comDelete.permissions = "candelcompletePost";
	this.postOptions.Delete.permissions = "candelPost";
	this.postOptions.Activ.permissions  = "canactivatePost";
	this.postOptions.Topic.permissions  = "canrenamePost";	
	this.postOptions.EditComment.permissions  = "caneditPost";	
	this.postOptions.EditTopic.permissions  = "caneditPost";
	  
	this.postOptions.comDelete.appendChild(document.createTextNode( String.fromCharCode(160) ));
	this.postOptions.Delete.appendChild(document.createTextNode( String.fromCharCode(160) ));
	this.postOptions.Activ.appendChild( document.createTextNode( String.fromCharCode(160) ));
	this.postOptions.Topic.appendChild( document.createTextNode( String.fromCharCode(160) ));
	this.postOptions.EditComment.appendChild( document.createTextNode( String.fromCharCode(160) ));
	this.postOptions.EditTopic.appendChild( document.createTextNode( String.fromCharCode(160) ));
	  
	//keine Mehrfach Initialisierung
	this.isInitialized = false;	
	
	/**
	* init()
	* @return: void
	* Adminmenue erzeugen und mit Grundfunktionen ausstatten 
	* Menue ist unsichtbar!
	**/	
  this.init = function() {
		if (this.isInitialized)
			return;
		
		// Erzeugt Liste, die Links ausnimmt
		var uList = document.createElement("ul");
		var ii=1;
		for (var el in this.postOptions){
			if (window.perm[ this.postOptions[el].permissions ] == 1) {
				var listEl = document.createElement("li");
				listEl.style.listStyleImage = "url("+this.postOptions[el].icon+")";
				listEl.appendChild(this.postOptions[el]);
				uList.appendChild(listEl);
			}
		}		
		
		this.mainDIV.appendChild( uList );   

		// Suche alle SPANs im Dokument mit num. ID	
		var docSpans = document.getElementsByTagName("span");            
		for (var i=0; i<docSpans.length; i++){      
			if (/\d+/.test(docSpans[i].id)) {            
				docSpans[i].topic = topic[docSpans[i].id];
				docSpans[i].Instanz = this;
				
				// Fuege Event-Handler hinzu
				// Zeige beim Klick das Menue 
				// an Klick- bzw. Mausposition
				docSpans[i].onclick = function(e)
				{
					if (this.topic != undefined && this.topic['isEdit'] == 1)  // nur wenn das Obekte existiert und belegt ist
					{
						var m_pos = getMousepos(e);
						this.Instanz.mainDIV.style.left = m_pos.scrollLeft+5+"px";
						this.Instanz.mainDIV.style.top  = m_pos.scrollTop-15 +"px";
						this.Instanz.setOptions(this.topic);          
						this.Instanz.setVisible(true);
					}
				};       

			}			
		}		

		//this.setVisible(false);	
		document.getElementsByTagName("body")[0].appendChild(this.mainDIV);	
		this.isInitialized = true;
	}
	
	/**
	* setVisible()
	* @param: <Boolean>setVisible
	* @return: void
	* Legt Sichtbarkeit des Menues fest
	* 
	**/
	this.setVisible = function(setVisible){
		this.mainDIV.style.display = setVisible?"block":"none";
		this.finalHeight = this.finalHeight==0?this.mainDIV.offsetHeight:this.finalHeight;
		this.finalWidth  = this.finalWidth==0?this.mainDIV.offsetWidth+10:this.finalWidth;
		this.fadeIn();
	}
	
	/**
	* setOptions()
	* @param: <Thread>t
	* @return: void
	* aendert die Eintraege im Menue
	*	+ Linktitel
	*	+ Linkziel
	* 
	**/	
	this.setOptions = function(t){
		for (var el in this.postOptions){
			for (var tOptions in t) {		 
      	if (this.postOptions[el].key == tOptions && window.perm[ this.postOptions[el].permissions ] == 1) {
					//Ermittle den Status aus post t, um Linktext anzupassen.
					//zulässiges Intervall [0,1]         
					var status = parseInt(t[this.postOptions[el].key]);
					status = (isNaN(status) || status<0 || status>1)?0:status;
					
					//Linktext anpassen
					this.postOptions[el].firstChild.replaceData(0, this.postOptions[el].firstChild.nodeValue.length, this.postOptions[el].msg[ status ]); 
					//Title-Attribut setzen
					this.postOptions[el].title = this.postOptions[el].msg[ status ]; 
					//HREF-hinzufuegen
					this.postOptions[el].href = "javascript:TopicEdit("+ t['isFolder'].replace(/\D+/, '') +", '"+this.postOptions[el].value+"','post')";
					//automatisches Schliessen nach Klick
					this.postOptions[el].Instanz = this;
					this.postOptions[el].onclick = function(e) { this.Instanz.setVisible(false); };
				}        
			}
		}
	}
	

	/**
	* fadeIn()
	* @param: <Double>opac
	* @return: void
	* @uri: http://www.dustindiaz.com/sweet-titles/ 
	* @modified: Michael Loesler
	* laesst das Menue einfaden
	* 
	**/

	this.fadeIn = function (opac) {
		opac = opac || 0;
		var newOpac   = opac + 0.1;
		var newWidth  = parseInt(this.finalWidth*newOpac);
		var newHeight = parseInt(this.finalHeight*newOpac);
		if (newOpac < this.finalOpacity) {
			this.mainDIV.style.opacity = newOpac;
			this.mainDIV.style.filter = "alpha(opacity:" + (newOpac * 100) + ")";
			this.mainDIV.style.height = newHeight+"px";
			this.mainDIV.style.width  = newWidth+"px";
			window.setTimeout(function () {
				adminMenu.fadeIn(newOpac);
			}, 30);

		} else {
			this.mainDIV.style.opacity = this.finalOpacity;
			this.mainDIV.style.filter = "alpha(opacity:" + (this.finalOpacity * 100) + ")";
			this.mainDIV.style.height = this.finalHeight+"px";
			this.mainDIV.style.width  = this.finalWidth+"px";
		}
	}
	
}


/**
* getMousepos()
* @param: <Event>evt
* @return: <Objekt>pos
* @url: http://javascript.jstruebig.de/javascript/54/
* Ermittelt die Mauskkordinaten im Dokument
* .top / .left             - Position im Fenster
* .scrollTop / .scrollLeft - Position im Dokument
**/	
getMousepos = function (evt){
    if(!evt) evt = window.event;
    var pos = new Object();
    pos.left = evt.clientX;
    pos.top = evt.clientY;
    var b = (window.document.compatMode && window.document.compatMode == "CSS1Compat") ? window.document.documentElement : window.document.body || null;
    if (b) {
        pos.scrollLeft= pos.left + b.scrollLeft;
        pos.scrollTop = pos.top + b.scrollTop + 10;
    }
    else if(document.layers) {
        // Netscape 4.
        pos.scrollLeft = evt.pageX;
        pos.scrollTop = evt.pageY;
        pos.left = evt.pageX - window.pageXOffset;
        pos.top = evt.pageY - window.pageYOffset;
    }
    return pos;
}

/**
  * Funktion starten beim Laden des Dokumentes
  *
  */
var adminMenu = new AdminMenu();
var isDOMContentLoaded = false;
function addContentLoadListener () {
	if (document.addEventListener) {
	var DOMContentLoadFunction = function () {
		isDOMContentLoaded = true;
		adminMenu.init();
	};
	document.addEventListener("DOMContentLoaded", DOMContentLoadFunction, false);
}
var oldonload = (window.onload || new Function());
	window.onload = function () {
		if (!isDOMContentLoaded) {
			oldonload();
			adminMenu.init();
		}
	};
}
addContentLoadListener();
