/***************************************************************
*
*  JavaScript DHTML foldout menu for TYPO3
*
*  Copyright notice
*
*  (c) 2004-2006 Peter Klein
*  All rights reserved
*
*  Released under GNU/GPL (see license file in tslib/)
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*  This copyright notice MUST APPEAR in all copies of this script
*
*    Tested on: Internet Explorer 4.0-6.0 (PC)
*               Mozilla 1.0 (PC + Mac)
*               Opera 7.0 (PC)
*               Safari 1.0 (Mac)
*               Konqueror 3.4 (Linux)
*
***************************************************************/

// Fixed bugs:
// Cookie path was incorrectly set for each each page, instead of global for entire site.
// javascript error returned if altSwap wasn't set when using imageSwap.
// this.displayMode wasn't set in the setMenu function, which caused problems when autoFold was enabled.
// Treemenu - minus & plus had to be swapped in the Constants so the output is correct.
// Treemenu - error in TS where the wrong TMENU objects got copied. Thanks to Volker Hochgürtel for reporting this one..

// Additions:
// Now works with ordered lists as well (OL/LI)
// Parameter added to the PHP userfunction, in order to generate a list of prefixed ids for use in ExpandAll/CollapseAll buttons.
// Parameter added to the main javascript function to explicit set the menu to Expand or Collapse (default mode is Toggle.) - Only functioning if "autoFold=0"
// Examples are now working with MountPoint.

function initFoldMenu() {
	// ------------- Config Stuff -----------------------------------------------
	this.autoFold = 0;				// Autofold the unfolded item when clicking on a new item?
	this.foldCurrent = 0;			// Allow currrent unfolded item to be folded? (Only active if "autoFold = 1")
	this.startFolded = 0;			// Should menu start with all items folded (Only active if "autoFold = 0")
	this.enableCookie = 0;			// Save current menu state in a cookie?
	this.cookieLifetime = 0;		// Lifetime of persistant cookie, in days. If set to 0 then a session cookie is set.
	this.direction = 0;				// What direction should the menu fold/unfold?
	this.imagePath = "fileadmin/";	// Path to image files.
	this.imageSwap = new Array();	// Array of images to swap. (1st image is "closed image(s)", 2nd is "expanded image(s)"
	this.altSwap = new Array();		// If imageSwap is set, then you can set the optional array "altSwap" to ALT/TITLE text you want on the images.
	this.prefix = "foldoutMenu";	// Prefix of menu

	// ------------- Main function ----------------------------------------------
	this.foldMenu = function() {
		if (!document.getElementById && !document.all) return; // Old Browsers
		this.displayMode = (this.direction)?"inline":"block";
		if (this.enableCookie) {
			this.foldout_expand = this.parseString(this.prefix+'_expand')
			this.foldout_collapse = this.parseString(this.prefix+'_collapse')
		}
		var id = arguments[0].split(',');
		for (var k=0;k<id.length;k++) {
			var el = this.getElById(id[k]);
			if (this.autoFold) {
				var els = el.parentNode.parentNode.childNodes;
				for (var i=0;i<els.length;i++) {
					if (els[i].nodeName=="LI" && (els[i].lastChild.nodeName=="UL" || els[i].lastChild.nodeName=="OL")) {
						var cel = els[i].lastChild;
						var cidParts = cel.id.split('-');
						if (cel==el) {
							this.fold(cel,cidParts[1],(cel.style.display==this.displayMode && this.foldCurrent)?0:1)
						}
						else if (cel.style.display==this.displayMode) this.fold(cel,cidParts[1],0);
					}
				}
			}
			else {
				var idParts = id[k].split('-');
				var foldMode = arguments[1];
				this.fold(el,idParts[1],isNaN(foldMode)?(el.style.display=="none"?1:0):foldMode);
			}
			if (this.enableCookie) {
				this.saveString(this.prefix+'_expand',this.foldout_expand)
				this.saveString(this.prefix+'_collapse',this.foldout_collapse)
			}
		}
	}

	this.fold = function(el,uid,mode) {
		el.style.display = (mode)?this.displayMode:"none";
		this.swapImage(el.id,mode);
		this.foldout_expand[uid] = mode;
		this.foldout_collapse[uid] = !mode;
	}

	this.swapImage = function(id,mo) {
		for (var j=0;j<this.imageSwap.length;j++) {
			if (imgEl = this.getElById(id+"-"+j)) {
				imgEl.setAttribute("src",this.imagePath+this.imageSwap[j][mo]);
				if (this.altSwap.length>=j && isNaN(this.altSwap)) {
					imgEl.setAttribute("alt",this.altSwap[j][mo]);
					imgEl.setAttribute("title",this.altSwap[j][mo]);
				}
			}
		}
	}

	this.getElById = function(idVal) {
		return (document.getElementById)?document.getElementById(idVal):(document.all)?document.all[idVal]:null;
	}

	//ghis
	function getElementsByClassName(oElm, strTagName, strClassName){
	    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	    var arrReturnElements = new Array();
	    strClassName = strClassName.replace(/\-/g, "\\-");
	    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	    var oElement;
	    for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
		    arrReturnElements.push(oElement);
		}
	    }
	    return (arrReturnElements)
	}
	//fin ghis

	this.setMenu = function(uids) {
		this.foldout_expand = this.parseString(this.prefix+'_expand')
		this.foldout_collapse = this.parseString(this.prefix+'_collapse')
		this.displayMode = (this.direction)?"inline":"block";
		var uid = uids.split(",");
		for (var i=0; i<uid.length; i++) {
			var el = this.getElById(this.prefix+"-"+uid[i]);
			/// MODIF THOMAS LEROY // 08/11/2007 ///
			if (el) {
				if (this.foldout_expand[uid[i]] == 1 && this.enableCookie) this.fold(el,uid[i],1);
				else if (el.style.display!=this.displayMode) {
					this.fold(el,uid[i],(!this.startFolded && !this.autoFold)?1:0)
				}
			}
		}
		//ghis
		var list_actif = getElementsByClassName(document.getElementById(this.menuselector), "a", "act");
		for (var j=0; j<list_actif.length; j++) {
			var uid_actif = list_actif[j].getAttribute("class");

			if(uid_actif){
				uid_actif = uid_actif.substr(15,30);
			}else{ // test special IE
				uid_actif = list_actif[j].getAttribute("className").substr(15,30);
			}
			var el_actif = this.getElById(this.prefix+"-"+uid_actif);
			if (el_actif){
				this.fold(el_actif,uid_actif,1);
			}
		}
		//fin ghis
	}

	// ------------- Cookie functions --------------------------------------
	this.setCookie = function(name, value, lifespan, access_path) {
		var CookieString = name + "=" + escape(value);
		if (lifespan>0) {
			var today = expiredate = new Date();
			expiredate.setTime(today.getTime() + 1000*60*60*24*lifespan);
			CookieString += "; expires=" + expiredate.toGMTString();
		}
		CookieString += "; PATH="+((access_path != null)?access_path:"");
		document.cookie = CookieString;
	}

	this.getCookie = function(name) {
		var search = name + "=";
		var CookieString = document.cookie;
		var result = null;
		if (CookieString.length > 0) {
			var offset = CookieString.indexOf(search);
			if (offset != -1) {
				offset += search.length;
				end = CookieString.indexOf(";", offset)
				if (end == -1) end = CookieString.length;
				result = unescape(CookieString.substring(offset, end));
			}
		}
		return result;
	}

	this.deleteCookie = function(name, path) {
		this.setCookie(name,"Deleted", -1, path)
	}

    // ------------- Cookie parse functions --------------------------------
	this.parseString = function(cookieName) {
		var cookieString = this.getCookie(cookieName);
		var uids = new Array();
		if (cookieString) {
			var uid = cookieString.split('|');
			for (var i=0; i<uid.length-1; i++) {
				uids[uid[i]] = 1;
			}
		}
		return uids;
	}

	this.saveString = function(cookieName,uids) {
		var cookieString = '';
		for (var i=0; i<uids.length; i++) {
			if (uids[i] == 1) cookieString += i + '|';
		}
		this.setCookie(cookieName, cookieString,this.cookieLifetime,'/');
	}

}

