/*
 * $Id: toolbar.js,v 1.83 2011/07/26 09:23:27 michael Exp $
 * This is an unpublished work copyright (c) 2006 HELIOS Software GmbH
 * 30827 Garbsen, Germany
 */

/* global array for saving toolbar items that have the class names replaced */
var _ws_tbb = [];
/* global variable for saving the currently replaced comment string id */
var _ws_cmts;
/* global variable for saving if the comment string should be hidden on next call */
var _ws_cmth;
/* suffix to append to the class name of hovered toolbar items */
var _WS_OVER_SUFFIX = " over";
var _WS_WINDOW_NAME = "wsNewWebShareWindow";
/* flag determining if the unload handler has been called */
var _ws_unloaded = false;
/* flag determining if the unload handler should trigger */
var _ws_trigger_unload = true;
var iPhone = (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPod') != -1 || navigator.userAgent.indexOf('iPad') != -1);

/* init function called on every page onload */
function ws_init() {
 if (!iPhone) ws_addEvent(document.getElementsByTagName("body")[0], 'keydown', ws_escapeKeyPressHandler);
 ws_showActiveButtons();
 ws_openSubMenu();
 ws_addEvent(window, 'resize', ws_openSubMenu);
 ws_setDirBannerLinkTarget();
 ws_initFLPMenus();
}

function ws_initSearchFields() {
	var f = ws_getElementsByClassName("searchField");
	for (var i = 0; i < f.length; i++) {
		fieldWithPlaceholder(f[i]);
		autoGrowField(f[i]);
	}
}

/* from http://ajaxcookbook.org/disable-browser-context-menu */
function disableContextMenu(element) {
    element.oncontextmenu = function() {
        return false;
    }
}

function ws_setDirBannerLinkTarget() {
	var _m = document.getElementById("dirBannerMessage");
	if (!_m) return;
	var _a = _m.getElementsByTagName('a');
	for (var i = 0; i < _a.length; i++) {
		_a[i].target = "_blank";
	}

}

/* disable context menu for whole tables */
function ws_disableContextMenuForSharepoints() {
	var tbl = ws_getElementsById("sharepointTable");
	if (tbl)
	 disableContextMenu(tbl);
}

/* disable context menu for whole tables (there is no acion to perform with a right click in any table column) */
function ws_disableDirectDownload() {
	var tbl = ws_getElementsById("fileBrowserTable");
	if (tbl)
		disableContextMenu(tbl);
		
	tbl = ws_getElementsById("searchResultTable");
	if (tbl)
	 disableContextMenu(tbl);
}

function ws_openInNewWindow(senderLink, w, h) {
	/* get unique window id (location.pathname contains context id) */
	var nWindowName = _WS_WINDOW_NAME + Math.random();
	/* IE6 crashes if the window name contains special chars */
	nWindowName = nWindowName.replace(/\./g, "_");
	nWindowName = ws_replaceAll(nWindowName, "/", "_");
	var winOpt = w && h ? ",width=" + w + ",height=" + h : "";
	var winRef = window.open(senderLink.href,  nWindowName, "resizable=yes,scrollbars=yes,location=no,toolbar=no" + winOpt);
	if (winRef)
		winRef.focus();
	return false;
 }
 
 function ws_openFormInNewWindow(formElem, reset, w, h) {
	var winName = _WS_WINDOW_NAME + ("" + Math.random()).replace(/\./g, "_");
	winName = ws_replaceAll(winName, "/", "_");
	formElem.originAction = formElem.action;
	formElem.action += "?rnd=" + winName;
	formElem.setAttribute("target", winName);
	var winOpt = w && h ? ",width=" + w + ",height=" + h : "";
	var winRef = window.open("about:blank",  winName, "resizable=yes,scrollbars=yes,location=no,toolbar=no" + winOpt);
	if (winRef)
		winRef.focus();
	if (reset)
		window.setTimeout( function () {
			formElem.setAttribute("target", "_top");
			formElem.action = formElem.originAction;
		}, 200 );
	return false;
 }

/* register unload handler */
function ws_registerUnloadHandler() {
	if (iPhone) return;
	if (window.onbeforeunload != "undefined")
		window.onbeforeunload = ws_beforeUnloadHandler;
	if (window.onunload != "undefined")
		window.onunload = ws_unloadHandler;
	ws_attachUnloadSwitch();
}

function ws_unloadDisabled() {
	return (_ws_trigger_unload == false || _ws_unloaded == true || (window.name && window.name.indexOf(_WS_WINDOW_NAME) > -1));
}

function ws_beforeUnloadHandler() {
	if (ws_unloadDisabled()) return;
	return "ATTENTION: You are going to leave WebShare!\nPlease log out to terminate your WebShare session first.";
}

function ws_unloadHandler() {
	if (ws_unloadDisabled()) return false;
	_ws_unloaded = true;
	if (document.forms[0] && document.forms[0].tbLogout)
		document.forms[0].tbLogout.click();
}

function ws_attachUnloadSwitch() {
	if (iPhone) return;
	var _a = document.getElementsByTagName('a');
	var _l = _a.length;
	for (var i = 0; i < _l; i++) {
		ws_addEvent(_a[i], 'click', function() { _ws_trigger_unload = false; });
	}
	_a = document.getElementsByTagName('button');
	_l = _a.length;
	for (var i = 0; i < _l; i++) {
		ws_addEvent(_a[i], 'click', function() { _ws_trigger_unload = false; });
	}
	_a = document.getElementsByTagName('input');
	_l = _a.length;
	for (var i = 0; i < _l; i++) {
		ws_addEvent(_a[i], 'click', function() { _ws_trigger_unload = false; });
		ws_addEvent(_a[i], 'change', function() { _ws_trigger_unload = false; });
	}

};

/* add _WS_OVER_SUFFIX to all classnames on hovered sub toolbars and add elements to _ws_tbb array */
function ws_showActiveButtons() {
	var tbs = ws_getElementsByClassName("tbB", ws_getElementsById("tb"));
	for (var level = 1; level <= 4; level++) {
		var sTbs = ws_getElementsByClassName('sTb' + level, ws_getElementsById("tb"), 'ul');
		for (var i = 0; i < sTbs.length; i++) {
			var sTb = sTbs[i];
			ws_addEvent(sTb, "mouseover", function() {	
				if (!this.pB) {
					var s = ws_getPreviousSibling(this);
					while (s) {
						if (s && isDefined(s.className) && s.className.indexOf('tbB') > -1) {
							this.pB = s;
							break;
						}
						s = ws_getPreviousSibling(s);
					}
				}
				if (this.pB) {
					this.pB.className += _WS_OVER_SUFFIX;
					_ws_tbb.push(this.pB);
				}
			});
			ws_addEvent(sTb, "mouseout", function() {
				ws_resetHoverStates();
			});
		}
	}
};

/* remove _WS_OVER_SUFFIX from all classnames in the _ws_tbb array */
function ws_resetHoverStates() {
	for (var i = 0; i < _ws_tbb.length; i++) {
		var tb = _ws_tbb[i];
		tb.className = tb.className.replace(_WS_OVER_SUFFIX, "");
	}
	_ws_tbb = [];
};

/*
 * update the not-fixed position of the body content by setting the margin to the computed value
 * ws_updatePosition(String (anIdOfAContentElement), String (anIdOfAToolbarElement), String (top|left|paddingLeft), Boolean, Boolean)
 */
function ws_updatePosition(anContentId, anTooolbarId, mode, vertical, loaded, modLinks) {
	var _h = document.forms[0].wstbh;
	var _l = document.forms[0].wstbl;
	var v = (vertical != null && vertical == true);
	var head = document.getElementById(anTooolbarId);
	var content = document.getElementById(anContentId);

	if (!content)
		return;

	var _rId = document.getElementById("head");
	var csm = (head ? head.offsetHeight : 0 ) + (v && _rId && _rId.offsetHeight ? _rId.offsetHeight : 0) + 2;

	switch (mode) {
		case "top":	
			/* absolute positioned elements must not be included (file comments textarea) */
			if (anContentId == 'fpContent') csm -= (iPhone ? 45 : 30);
			if (_h) _h.value = csm;
			content.style.marginTop = csm + 'px';
			if (modLinks) ws_tbLinkParam('wstbh', csm);
			break;
		case "left":
			var csl = (head ? head.offsetWidth : 0);
			if (_l) _l.value = csl;
			content.style.marginLeft = csl + 'px';
			if (modLinks) ws_tbLinkParam('wstbl', csl);
			var img = document.getElementById('image');
			if (img)
				img.style.marginLeft = csl + 'px';
			break;
		case "paddingLeft":
            content.style.paddingLeft = "0";
			var csp = head.offsetWidth;
			if (_l) _l.value = csp;
			content.style.paddingLeft = csp + 'px';
			break;
		default: break;
	}

};

/* append URL parameters to a link */
function ws_tbLinkParam(param, value, force) {
	if (!force && document.getElementById("fpContent")
		|| document.getElementById("brandingEditorBody")
		|| document.getElementById("serverPreferencesBody"))
		return;
	var _a = document.getElementsByTagName('a');
	var _l = _a.length;
	var	re1 = new RegExp(".+?.*" + param + "=", 'g');
	var	re2 = new RegExp(param + "=.+$", 'g');
	var reMatches = -1;
	for (var j = 0; j < _l; j++) {
		var l = _a[j];
		if ((l.target && l.target == '_blank')
				|| l.href.indexOf('/webshare.woa/') == -1)
			continue;
		var append = "";
		var pos = l.href.indexOf('#');
		if (pos > -1) {
			append = l.href.substring(pos, l.href.length);
			l.href = l.href.substring(0, pos)
		}
		pos = l.href.indexOf('?');
		if (pos > -1) {
			if (reMatches == -1)
				reMatches = re1.test(l.href) ? 1 : 0;
			if (reMatches == 1)
				l.href = l.href.replace(re2, param + '=' + value);
			else 
				l.href = l.href + '&' + param + '=' + value;
		} else {
			l.href += '?' + param + '=' + value;
		}
		l.href +=  append;
	}
};

/* update the window position if a hash was set in the URL */
function ws_updateHashPosition() {
	if (window.location.hash) {
		window.location.hash = window.location.hash;
		var e = document.getElementById(window.location.hash.substring(1));
		if (e) {
			var h = parseInt(document.forms.wstbh ? document.forms.wstbh.value : 85, 10) + 10;
			var pos = ws_findPosition(e).y - h;
			window.setTimeout('window.scrollTo(0,' + pos + ')', 100);
		}
	}
}

/* select all checkboxes in the file browser table */
function selectAll() {
	var chbxs = ws_getElementsById("fileBrowserTable").getElementsByTagName("input");
	var countMarked = 0;
	var countNotMarked = 0;
	var galleryView = document.getElementById('fileBrowserTable').className;

	for (var i = 0; i < chbxs.length; i++) {
		var bx = chbxs[i];
		if (bx.type == "checkbox") {
			if (bx.checked)
				countMarked++;
			else
				countNotMarked++;
		}
	}

	var check = !(countMarked > countNotMarked);
	for (var i = 0; i < chbxs.length; i++) {
		var bx = chbxs[i];
		if (bx.type.toUpperCase() == "CHECKBOX") {
			bx.checked = check;

			if (bx.id && galleryView == 'fbGalleryView') {
				var el = _getElementById(bx.id.substring(0, bx.id.length - 2));
				if (el) {
					if (bx.checked) {
						el.className += " selected";
					} else {
						el.className = ws_replaceAll(el.className, " selected", "");
					}
				}
			}
		}
	}

	return false;
};

/* replace comment string with input field */
function ws_switch(id, hide, switchmode) {
	var _rId;
	var switchM = (switchmode ? true : false);
	if (_ws_cmts) {
		_rId = document.getElementById(_ws_cmts);
		if (_rId) _rId.style.display = 'none';	
		_rId = document.getElementById('c' + _ws_cmts);
		if (_rId) _rId.style.display = 'inline';
		if (_ws_cmth) {
			_rId = document.getElementById('r' + _ws_cmts);
			if (_rId) _rId.className = _rId.className + ' hidden';
		}
		if (_ws_cmts === id || switchM) {
			_ws_cmts = '';
			return false;
		}
	}

	_rId = document.getElementById('r' + id);
	if (_rId) {
		_rId.style.display = "";
		if (_rId.className)
			_rId.className = _rId.className.replace("hidden", "");
	}
	_rId = document.getElementById('c' + id);
	if (_rId) _rId.style.display = 'none';
	_rId = document.getElementById(id);
	if (_rId) _rId.style.display = 'block';
	_rId = document.getElementById('t' + id);
	if (isDefined(_rId)) { 
		try { _rId.focus(); } catch (e) {}
	}

	_ws_cmts = id;
	_ws_cmth = hide;
	
	return false;
};

function ws_positionComment(source, id) {
	var span = _getElementById(id);
	if (!isDefined(span))
		return;

	var e = ws_getParentNode(span, 1);
	var pos = ws_findPosition(source);
	var wS = ws_getWidth(source);
	var wH = ws_getHeight(source);
	var winProp = ws_getWindowProperties();
	e.style.display = 'block';
	var w = ws_getWidth(e);	var h = ws_getHeight(e);
	var offX = (iPhone ? -25 : (pos.x + w + wS + 10 > winProp.width) ? (w * -1) : wS);
	var offH = (pos.y + h + wH + 10 > winProp.height) ? (h * -1) : wH;

	e.style.position = 'absolute';
	e.style.left = (pos.x + offX) + 'px';
	e.style.top = (pos.y + offH) + 'px';		
	return false;
};

function ws_escapeKeyPressHandler(e) {
	var kC  = (window.event) ? event.keyCode : e.keyCode;
	var esc = (window.event) ? 27 : e.DOM_VK_ESCAPE;
	if(kC == esc) {
		if (_ws_flpMenu)
			ws_hideFLP();
		if(_ws_cmts) {
			_rId = document.getElementById(_ws_cmts);
			if (_rId) _rId.style.display = 'none';	
			_rId = document.getElementById('c' + _ws_cmts);
			if (_rId) _rId.style.display = 'inline';
			if (_ws_cmth) {
				_rId = document.getElementById('r' + _ws_cmts);
				if (_rId) _rId.className = _rId.className + ' hidden';
			}
			_ws_cmts = '';
		}
		if (document.forms[0] && document.forms[0].CancelPrint) {
			document.forms[0].CancelPrint.click();
		}
	}
}

function ws_arrowKeyHandler(evt) {
	if (document.activeElement && document.activeElement.tagName
		&& ((document.activeElement.tagName.toLowerCase() === "input"
		&& document.activeElement.type && document.activeElement.type === "text")
		|| document.activeElement.tagName.toLowerCase() === "textarea"))
		return;
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
    	var e = false;
        switch (evt.keyCode) {
            case 37:
            	e = _getElementById("tbBPreviousPage");
                break;    
            case 39:
               	e = _getElementById("tbBNextPage");
                break;
         }
   		if (e) e.click();
    }
}

function ws_openSubMenu() {
	var tbs = ws_getElementsByClassName("tbB", document.getElementById("tb"));
	for (var i = 0; i < tbs.length; i++) {
		var tb = tbs[i];
		/* top level buttons */
		if (tb.className.indexOf("topLevelButton") > -1)
			continue;
		/* button with sub menu */
		else if (ws_getParentNode(tb, 1).className.indexOf("sTb") > -1)
			ws_addOpener(tb);
	}
}

function ws_addOpener(elem) {
	if (ws_getNextSibling(elem, "ul")) {
		ws_addEvent(elem, 'mouseover', function() {
			var uElem = ws_getNextSibling(elem, "ul");
			uElem.style.display = "block";
			var h = ws_getHeight(uElem);
			if (h <= 0 && document.all)
				h = (document.getElementById(uElem.id).offsetHeight > 0 ? document.getElementById(uElem.id).offsetHeight : document.getElementById(uElem.id).clientHeight);
			var p = ws_findPosition(uElem);
			if ((h + p.y) > ws_getWindowProperties().height)
				try {
					uElem.style.top = "-" + ((h + p.y) -  ws_getWindowProperties().height) + "px";
				} catch (err) {}
			uElem.style.display = "";
		});
		if (ws_getFirstChild(elem, "span")) {
			ws_addEvent(ws_getFirstChild(elem, "span"), 'mouseover', function() {
				var uElem = ws_getNextSibling(elem, "ul");
				var h = ws_getHeight(uElem);
				if (h <= 0 && document.all)
					h = (document.getElementById(uElem.id).offsetHeight > 0 ? document.getElementById(uElem.id).offsetHeight : document.getElementById(uElem.id).clientHeight);
				var p = ws_findPosition(uElem);
				try {
					uElem.style.top = "-" + ((h + p.y) -  ws_getWindowProperties().height) + "px";
				} catch (err) {}
			});
		}
	}
}

function ws_selectMe(id, keepState) {
	var e = _getElementById(id);
	if (e && e.type && e.type.toUpperCase() == "CHECKBOX") {
		if (!isDefined(keepState) || !keepState)
			e.checked = !e.checked;
		var el = _getElementById(id.substring(0, id.length - 2));
		if (el) {
			if (e.checked) {
				el.className += " selected";
			} else {
				el.className = ws_replaceAll(el.className, " selected", "");
			}
		}
	}
	return false;
}

function ws_checkSelection() {
	var a = document.getElementsByTagName('input');
	var l = a.length;
	for (var i = 0; i < l; i++) {
		if (a[i] && a[i].id && a[i].type
				&& a[i].type.toUpperCase() == "CHECKBOX"
				&& a[i].checked)
			ws_selectMe(a[i].id, true);
	}	
}

/* allow selection of preview images to be opened in proof window - only if proof link is available and clickable */
var pImgSelection = {
	pI: false, link: false, tmp: false,
	init: function(linkId, containerId, objectClass, selectedClass) {
		pImgSelection.pI = ws_getElementsByClassName(objectClass, _getElementById(containerId), 'img');
		pImgSelection.link = _getElementById(linkId);
		if (!pImgSelection.pI || pImgSelection.pI.length <= 1 || !pImgSelection.link)
			return;
		pImgSelection.link = pImgSelection.link.parentNode;
		if (!pImgSelection.link || !pImgSelection.link.href)
			return;
		pImgSelection.pImgClass = objectClass;
		pImgSelection.sB = selectedClass;		
		pImgSelection.tmp = pImgSelection.link.href;
		pImgSelection.deselect();
		for (var e in pImgSelection.pI) {
			pImgSelection.pI[e].pNum = /\d+$/.exec(pImgSelection.pI[e].alt);
			ws_addEvent(pImgSelection.pI[e], 'click', function() {
				if (this.selected === true) {
					pImgSelection.link.href = pImgSelection.tmp;
					pImgSelection.deselect();
				} else {
					pImgSelection.deselect();
					this.selected = true;
					ws_addClass(this, pImgSelection.sB);
					pImgSelection.link.href = pImgSelection.link.href.replace(/p=\d+$/, 'p=' + this.pNum);
				}
			});
		}
	}, deselect: function() {
		for (var e in pImgSelection.pI) {
			ws_removeClass(pImgSelection.pI[e], pImgSelection.sB);
			pImgSelection.pI[e].selected = false;
		}
	}
};

function ws_openDocument(link) {
	var sfx = ws_updateOpenDocumentLink(link),
		imgTypes,
		img,
		body,
		inline = false,
		inlineParam = "&amp;inline=true";
	if (sfx) {
		imgTypes = {
			"tif": {
				data: "SUkqAA4AAACAP+BQEAARAP4ABAABAAAAAAAAAAABAwABAAAAAQAAAAEBAwABAAAAAQAAAAIBAwADAAAA4AAAAAMBAwABAAAABQAAAAYBAwABAAAAAgAAAA0BAgAzAAAA5gAAABEBBAABAAAACAAAABIBAwABAAAAAQAAABUBAwABAAAAAwAAABYBAwABAAAAQAAAABcBBAABAAAABQAAABoBBQABAAAAGgEAABsBBQABAAAAIgEAABwBAwABAAAAAQAAACgBAwABAAAAAgAAAD0BAwABAAAAAgAAAAAAAAAIAAgACAAvaG9tZS9taWNoYWVsL0Rlc2t0b3AvZHVtbXkvZHVtbXlfaW1hZ2VzL2R1bW15LnRpZgAAAAAASAAAAAEAAABIAAAAAQ==",
				mime: "image/tiff"
			}
			,"psd": {
				data: "OEJQUwABAAAAAAAAAAMAAAABAAAAAQAIAAMAAAAAAAAAKjhCSU0D7QAAAAAAEABIAAAAAQABAEgAAAABAAE4QklNBAAAAAAAAAIAAAAAAIgAAACEAAEAAAAAAAAAAAAAAAEAAAABAAMAAAAAAAYAAQAAAAYAAgAAAAY4QklNbm9ybf8AAAAAAAA8AAAAAAAAAAALSGludGVyZ3J1bmQ4QklNbHVuaQAAABwAAAALAEgAaQBuAHQAZQByAGcAcgB1AG4AZAAAAAEAAgD/AAEAAgD/AAEAAgD/AAEAAgACAAIA/wD/AP8=",
				mime: "image/photoshop"
			}
			,"jp2": {
				data: "AAAADGpQICANCocKAAAAFGZ0eXBqcDIgAAAAAGpwMiAAAAAtanAyaAAAABZpaGRyAAAAAQAAAAEAAwcHAAAAAAAPY29scgEAAAAAABAAAADwanAyY/9P/1EALwAAAAAAAQAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAAAwcBAQcBAQcBAf9SAAwAAAABAAUEBAAB/1wAE0BASEhQSEhQSEhQSEhQSEhQ/2QAIwABQ3JlYXRlZCBieSBPcGVuSlBFRyB2ZXJzaW9uIDAuOf+QAAoAAAAAAGsAAf9TAAkBAAUEBAAB/10AFAFAQEhIUEhIUEhIUEhIUEhIUP9TAAkCAAUEBAAB/10AFAJAQEhIUEhIUEhIUEhIUEhIUP+Tz6QIAM+kCADPpAgAgICAgICAgICAgICAgICA/9k=",
				mime: "image/jp2"
			}
			,"bmp": {
				data: "Qk06AAAAAAAAADYAAAAoAAAAAQAAAAEAAAABABgAAAAAAAQAAAATCwAAEwsAAAAAAAAAAAAA////AA==",
				mime: "image/bmp"
			}
			,"jpg": true
			,"jpeg": true
			,"png": true
			,"gif": true
		};
		if (imgTypes[sfx]) {
			if (typeof(imgTypes[sfx]) !== "object") {
				inline = (imgTypes[sfx] === true);
			} else {
				img = document.createElement("img");
				img.src = "data:" + imgTypes[sfx].mime + ";base64," + imgTypes[sfx].data;
				body = document.getElementsByTagName("body")[0]
				body.appendChild(img);
				inline = (img.width === 1 && img.height === 1);
				body.removeChild(img);
			}
		} 
	}
	if (inline) {
		link.href += inlineParam;
	} else {
		link.href = link.href.replace(new RegExp(inlineParam, "g"), "");
	}
	return ws_openInNewWindow(link);
}

function ws_updateOpenDocumentLink(link) {
	var list = document.getElementById("fileBrowserTable");
	if (!list)
		return false;
	var galleryView = (list.className === "fbGalleryView"),
		name = false,
		sfx = false,
		a = list.getElementsByTagName("input"),
		l = a.length;
	for (var i = 0; i < l && !name; i++) {
		if (a[i].type
				&& a[i].type.toUpperCase() == "CHECKBOX"
				&& a[i].checked) {
			if (galleryView) {
				ws_selectMe(a[i].id, true);
				var cellName = isDefined(document._ws_gallery_details) && document._ws_gallery_details ? "noEllipsis" : "ellipsis",
					cell = ws_getElementsByClassName(cellName, a[i].parentNode.parentNode, "span")[0];
				if (!cell)
					return false;
				if (cell && cell.firstChild // Firefox
						&& cell.firstChild.tagName
						&& cell.firstChild.tagName.toUpperCase() === "WINDOW") {
					name = cell.firstChild.firstChild.value;
				} else { // others
					name = cell.innerHTML;
				}
			} else {
				if (a[i].id) {
					name = a[i].id.substring(0, a[i].id.length - 2);
				} else {
					var cell = ws_getElementsByClassName("colName", a[i].offsetParent.parentNode, "td")[0];
					if (!cell)
						return false;
					name = cell.firstChild.innerHTML;
				}
			}
		}
	}
	if (!name) {
		return false;
	} else if (name.indexOf(".") == -1) {
		cell = ws_getElementsByClassName("colType", cell.parentNode, "td")[0];
		if (cell) {
			sfx = cell.innerHTML;
			if (sfx.indexOf(".") > -1) {
				sfx = sfx.substring(sfx.lastIndexOf(".") + 1);
			}
		} else {
			return false;
		}
	} else {
		sfx = name.substring(name.lastIndexOf(".") + 1);
	}
	if (!sfx) {
		sfx = "undefined";
	} else if (sfx === "dir") {
		return false;
	}
	var	mime = (ws_getMimetypeForSuffix(sfx) || "undefined"),
		s = link.href.replace(/&amp;/g, "&"),
		n = link.href.substring(0, link.href.indexOf("?")),
		params = s.split("&");
	for (var p = 0; p < params.length; p++) {
		if (/MIME/.test(params[p])) {
			params[p] = "MIME=" + encodeURIComponent(mime);
		} else if (/file/.test(params[p])) {
			params[p] = "file=" + encodeURIComponent(name);			
		}
		if (p == 0) {
			n += "?" + params[p];
		} else {
			n += "&amp;" + params[p];
		}
	}
	link.href = n;
	return sfx;
}

/*
 *		********** LIB FUNCTIONS **********
 */
 
function ws_getMimetypeForSuffix(sfx) {
	navigator.plugins.refresh(false);
	var	numPlugins = navigator.plugins.length;
	for (var i = 0; i < numPlugins; i++) {
		var plugin = navigator.plugins[i];
		if (plugin) {
			var numTypes = plugin.length,
				mimetype;
			for (var j = 0; j < numTypes; j++) {
				mimetype = plugin[j];
				if (mimetype
						&& mimetype.enabledPlugin
						&& (mimetype.enabledPlugin.filename == plugin.filename))
				{
					var	mimes = mimetype.suffixes.split(","),
						numMimes = mimes.length;
					for (var k = 0; k < numMimes; k++) {
						if (mimes[k] === sfx)
							return mimetype.type;
					}
				}
			}
		}
	}
	return false;
}

function ws_switchDisplay(e, visString, element, align, visible, setHeight) {
	e = _getElementById(e);
	if (!e) return;
	var _s = e.style;
	visString = visString || 'block';
	var show = visible || _s.display === 'none';
	_s.display = (show ? visString : 'none');
	if (show && element) {
		element = _getElementById(element);
		var pos = ws_findPosition(element);
		_s.top = (pos.y + ws_getHeight(element)) + "px";
		var alignOffset = pos.x;
		if (align === "left")
			alignOffset -= (ws_getWidth(e) - ws_getWidth(element));
		_s.left =  alignOffset + "px";
	}
	return false;
}

function ws_hide(e) {
	_getElementById(e).style.display = "none";
	return false;
}
 
 /* ws_getElementsByClassName(String ('aClassName') [, Object (aHTMLElement [, anotherHTMLElement])] [, String ('aTagName')]) */
function ws_getElementsByClassName(sClass, oObj, sTag) {
	oObj = oObj || document;
	if (!oObj.length) { oObj = [oObj]; }
	var aElements = [];
	for(var i = 0; i < oObj.length; i++) {
		oEl = oObj[i];
		if (oEl.getElementsByTagName) {
			oObj.children = oEl.getElementsByTagName(sTag || '*');
			var _l = oObj.children.length;
			for (var j = 0; j < _l; j++) {
				oObj.child = oObj.children[j];
				if (oObj.child.className && (new RegExp('\\b' + sClass + '\\b').test(oObj.child.className))) {
					aElements.push(oObj.child);
				}
			}
		}
	}
	return aElements;
};

/* ws_getElementsById(String ('anId' [, 'anotherId'])) */ 
function ws_getElementsById() {
	var aElems = [];
	for (var i=0; i < arguments.length; i++) {
		var soElem = arguments[i];
		if (typeof soElem == 'string') {
			if(document.getElementById) 
				soElem = document.getElementById(soElem);
			else if(document.all)
				soElem = document.all[soElem];
		}
		if (arguments.length == 1) return soElem;
		aElems.push(soElem);
	}
	return aElems;
};

function ws_getWidth(e,w) {
	if(!(e=ws_getElementsById(e))) return 0;
	if (isNumber(w)) {
		if (w<0) w = 0;
		else w=Math.round(w);
	}
	else w=-1;
	var css=isDefined(e.style);
	if (e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
		w = xClientWidth();
	} else if(css && isDefined(e.offsetWidth) && isString(e.style.width)) {
		if(w>=0) {
			var pl=0,pr=0,bl=0,br=0;
			if (document.compatMode=='CSS1Compat') {
				var gcs = _getComputedStyle;
				pl=gcs(e,'padding-left',1);
				if (pl !== null) {
					pr=gcs(e,'padding-right',1);
					bl=gcs(e,'border-left-width',1);
					br=gcs(e,'border-right-width',1);
				} else if(isDefined(e.offsetWidth,e.style.width)){
					e.style.width=w+'px';
					pl=e.offsetWidth-w;
				}
			}
			w-=(pl+pr+bl+br);
			if(isNaN(w)||w<0) return;
			else e.style.width=w+'px';
		}
		w=e.offsetWidth;
	} else if(css && isDefined(e.style.pixelWidth)) {
		if(w>=0) e.style.pixelWidth=w;
		w=e.style.pixelWidth;
	}
	return w;
}

function ws_getHeight(e,h) {
	if(!(e=ws_getElementsById(e))) return 0;
	if (isNumber(h)) {
		if (h<0) h = 0;
		else h=Math.round(h);
	} else h=-1;
	var css=isDefined(e.style);
	if (e == document || !e.tagName || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
		h = ws_getWindowProperties().height;
	}
	else if(css && isDefined(e.offsetHeight) && isString(e.style.height)) {
		if(h>=0) {
			var pt=0,pb=0,bt=0,bb=0;
			if (document.compatMode=='CSS1Compat') {
				var gcs = _getComputedStyle;
				pt=gcs(e,'padding-top',1);
				if (pt !== null) {
					pb=gcs(e,'padding-bottom',1);
					bt=gcs(e,'border-top-width',1);
					bb=gcs(e,'border-bottom-width',1);
				} else if(isDefined(e.offsetHeight,e.style.height)){
					e.style.height=h+'px';
					pt=e.offsetHeight-h;
				}
			}
			h-=(pt+pb+bt+bb);
			if(isNaN(h)||h<0) return;
			else e.style.height=h+'px';
		}
		h=e.offsetHeight;
	} else if(css && isDefined(e.style.pixelHeight)) {
		if(h>=0) e.style.pixelHeight=h;
		h=e.style.pixelHeight;
	}
	return h;
}

function _getComputedStyle(e, p, i) {
	if (document.getElementById) e = document.getElementById(e);
	else if (document.all) e = document.all[e];
	else e = null;
	if(!(e = _getElementById(e))) return null;
	var s, v = 'undefined', dv = document.defaultView;
	if(dv && dv.getComputedStyle){
		s = dv.getComputedStyle(e,'');
		if (s) v = s.getPropertyValue(p);
	}
	else if(e.currentStyle) {
		v = e.currentStyle[getCamelized(p)];
	}
	else return null;
	return i ? (parseInt(v) || 0) : v;
}


/* add events without replacing previously added events */
function ws_addEvent(obj, evType, fn) {
	if (obj.addEventListener)
		obj.addEventListener(evType, fn, false);
	else if (obj.attachEvent) {
		try {
			obj["e" + evType + fn] = fn;
			obj[evType + fn] = function() { obj["e" + evType + fn] ( window.event ); }
			obj.attachEvent("on" + evType, obj[evType + fn] );
		} catch (err) { /* object does not support attaching events */ }
	} else
		obj["on" + evType] = fn;
};

function ws_removeEvent(obj, evType, fn){
	if (obj.removeEventListener)
		obj.removeEventListener(evType, fn, false);
	else if (obj.detachEvent) {
		try {
			obj.detachEvent("on" + evType, obj[evType + fn]);
			obj[evType + fn] = null;
			obj["e" + evType + fn] = null;
		} catch (err) { /* event does not exist anymore or cannot be removed */ }
	} else
		obj["on" + evType] = null;
};

/* add events without replacing previously added events */
function ws_addAttributeEvent(obj, evType, fn) {
	try {
		var onEvent = obj.getAttribute("on" + evType, 0);
		if (onEvent) {
			onEvent += eval(fn);
			obj.setAttribute("on" + evType, onEvent);
		} else {
			obj.setAttribute("on" + evType, eval(fn));
		}
	} catch (err) { /* object does not support attaching events */}
};

/* select partial string of a text field: ws_selectFieldValue((Object|String) ('elementOrID'), (String) ('stringBeforeSelectionEnds')) */
function ws_selectFieldValue(id, c) {
	var subject = _getElementById(id);
	var str = subject.value;
	var pos = str.lastIndexOf(c);
	subject.focus();
	if (document.selection) {
		subject.select();
		var range = document.selection.createRange();
		if (range.parentElement() == subject) {
			if (pos > -1)
				range.moveEnd('character', -1 * (str.length - pos));
			range.select();
		}
	} else if (subject.selectionStart || subject.selectionStart == '0') { 
		subject.selectionStart = 0;
		subject.selectionEnd = (pos > -1 ? pos : str.length);
	}
};

/* get visible height and width of the browser window */
function ws_getWindowProperties() {
	var x,y;
	if (self.innerHeight) {
		x = self.innerWidth;
		y = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	} else if (document.body) {
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return {height:y, width:x};
};

/* find position of element <obj> */
function ws_findPosition(obj, computeScroll) {
	var curleft = curtop = 0;
	if (obj && isDefined(obj) && obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	if (computeScroll && _isIE6) {
		curtop -= (document.documentElement.scrollTop + document.body.scrollTop);
		curleft -= (document.documentElement.scrollLeft + document.body.scrollLeft);
	}
	return {x:curleft, y:curtop};
};

function ws_getPreviousSibling(e, t) {
  e = _getElementById(e);
  var s = e ? e.previousSibling : null;
  while (s) {
    if (s.nodeType == 1 && (!t || s.nodeName.toLowerCase() == t.toLowerCase()))
    	break;
    s = s.previousSibling;
  }
  return s;
}

function ws_getNextSibling(e, t) {
  e = _getElementById(e);
  var s = e ? e.nextSibling : null;
  while (s) {
    if (s.nodeType == 1 && (!t || s.nodeName.toLowerCase() == t.toLowerCase()))
    	break;
    s = s.nextSibling;
  }
  return s;
}

function ws_getParentNode(ele, n) {
  while(ele && n--){ ele = ele.parentNode; }
  return ele;
}
 
function ws_getFirstChild(e, t) {
  e = _getElementById(e);
  var c = e ? e.firstChild : null;
  while (c) {
    if (c.nodeType == 1 && (!t || c.nodeName.toLowerCase() == t.toLowerCase()))
		break;
    c = c.nextSibling;
  }
  return c;
}

function ws_request(xLoc) {
	var xI = new Image;
	xI.src = xLoc;
}

function _getElementById(e) {
	if(typeof(e)=='string') {
		if (document.getElementById) e = document.getElementById(e);
		else if (document.all) e = document.all[e];
		else e = null;
	}
	return e;
}

function isDefined() {
	for(var i = 0; i < arguments.length; ++i) { if (typeof(arguments[i]) == 'undefined') return false; }
	return true;
}

function isNumber() {
	for(var i = 0; i < arguments.length; ++i) { if (isNaN(arguments[i]) || typeof(arguments[i]) != 'number') return false; }
	return true;
}

function isString() {
	for(var i = 0; i < arguments.length; ++i) { if (typeof(arguments[i]) != 'string') return false; }
	return true;
}

function getCamelized(cssPropStr) {
	var i, c, a = cssPropStr.split('-');
	var s = a[0];
	for (i=1; i<a.length; ++i) {
		c = a[i].charAt(0);
		s += a[i].replace(c, c.toUpperCase());
	}
	return s;
}

/* trim function to remove leading and trailing whitespaces of a string */
function trimAll(sString) {
	while (sString.substring(0, 1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0, sString.length-1);
	}
	return sString;
}

function ws_replaceAll(string, search, replacement) {
	while (string.indexOf(search) != -1) {
		string = string.replace(search, replacement);
	}
	return string;
}

function ws_hasClass(obj, cName) {
	return obj.className.match(new RegExp('(\\s|^)' + cName + '(\\s|$)'));
}

function ws_addClass(obj, cName) {
	if (!ws_hasClass(obj, cName))
		obj.className += ' ' + cName;
}

function ws_removeClass(obj, cName) {
	if (ws_hasClass(obj, cName)) {
		var reg = new RegExp('(\\s|^)' + cName + '(\\s|$)', 'g');
		obj.className = obj.className.replace(reg, '');
	}
}

function autoGrowField(f, minWidth, maxWidth) {
	var minWidth = minWidth || ws_getWidth(f),
		val = "",
		input = f,
		testSubject = document.createElement("div"),
		spacing = 45,
		maxWidth = maxWidth || 260,
		s = testSubject.style,
		fs = input.style;
	s.position =  "absolute";
	s.top = "-9999px";
	s.left = "-9999px";
	s.width = "auto";
	s.whiteSpace = "nowrap";
	s.fontSize = fs.fontSize;
	s.fontFamily = fs.fontFamily;
	s.fontWeight = fs.fontWeight;
	s.letterSpacing = fs.letterSpacing;
	check = function() {
		if (val === (val = input.value)) return;
		var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
		testSubject.innerHTML = escaped;
		var testerWidth = ws_getWidth(testSubject),
			newWidth = (testerWidth + spacing) >= minWidth ? testerWidth + spacing : minWidth,
			currentWidth = ws_getWidth(f),
			isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
				|| (newWidth > minWidth && newWidth < maxWidth);
		if (isValidWidthChange) ws_getWidth(input, newWidth);
	};
	document.getElementsByTagName("body")[0].appendChild(testSubject);
	ws_addEvent(f, "keyup", check);
	ws_addEvent(f, "keydown", check);
	ws_addEvent(f, "blur", check);
	ws_addEvent(f, "update", check);
	check();
}

function fieldWithPlaceholder(target, form) {
	var blurClass = "placeholderBlur";
	var focusClass = "placeholderFocus";

	if (navigator.userAgent.indexOf("WebKit") == -1) {
		target.onfocus = searchfieldFocus;
		target.onblur = searchfieldBlur;
		target.placeholder = target.getAttribute("placeholder") || "";
		form = form || document.forms[0];
		ws_addEvent(form, "submit", function() { setFocus(target); return true; });
		if (!target.hasFocus)
			setBlur(target);
	}
	
	function searchfieldFocus() { setFocus(this); };
	
	function searchfieldBlur() { setBlur(this); };

	function setFocus(f) {
		if (ws_hasClass(f, blurClass)) {
			ws_removeClass(f, blurClass);
			ws_addClass(f, focusClass);
			f.value = '';
		}
	};
	
	function setBlur(f) {
		if (f.value === "") {
			ws_removeClass(f, focusClass);
			ws_addClass(f, blurClass);
			f.value = f.placeholder;
		}
	};
}

/* namespace Util START */
var Util = {
	opera: function() { return window.opera != null },
	ie:  function() { return ((navigator.appVersion.indexOf("MSIE")!= -1) && !this.opera()) },
	ie6: function() { return (this.ie() && !window.XMLHttpRequest) },
	ie7: function() { return (navigator.appVersion.indexOf("MSIE 7.0") > -1) },
	selectable: function(elem, bool) { 
		if (!elem) return;
		elem.unselectable = bool ? 'off' : 'on';
		elem.onselectstart = function() { return bool; };
		if (elem.style) with (elem.style) {
			MozUserSelect = bool ? CSS.DEFAULT : CSS.NONE;
			KhtmlUserSelect = bool ? CSS.DEFAULT : CSS.NONE;
		}
	},	
	cursorPosition: function(e) {
		if (!e) e = window.event;
		if (e.targetTouches) {
			e = e.targetTouches[0];
		}
		var x, y;
		var off = this.pageOffset();
		if (e.pageX || e.pageY) {
			x = parseInt(e.pageX + off.x);
			y = parseInt(e.pageY + off.y);
		} else if (e.clientX || e.clientY) 	{
			x = parseInt(e.clientX + off.x);
			y = parseInt(e.clientY + off.y);
		}
		return {x: x, y: y};
	},
	pageOffset: function() {
		var x, y;
		if (window.pageXOffset) {
			x = window.pageXOffset;
			y = window.pageYOffset;
		} else {
			x = document.body.scrollLeft + document.documentElement.scrollLeft;
			y = document.body.scrollTop + document.documentElement.scrollTop
		}
		return {x: x, y: y};			
	},
	elementPosition: function (e, elemPos) {
		var pos = this.cursorPosition(e);
		if (this.ie()) {
			pos.x -= elemPos.x;
			pos.y -= elemPos.y;
		} else {
			var posPage = this.pageOffset();
			pos.x -= (elemPos.x + posPage.x);
			pos.y -= (elemPos.y + posPage.y);
		}
		return pos;
	},
	target: function(evt) {
		var target;
		if (evt.target) target = evt.target;
		else if (evt.srcElement) target = evt.srcElement;
		if (target.nodeType == 3) target = target.parentNode;
		return target;
	},
	createXMLHttpRequest: function() {
	   try { return new XMLHttpRequest(); } catch(e) {}
	   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
	   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
	   return null;
	},
	xmlHttpPost: function(url, formname, elem, msg, submitSelectText) {
		var xhr = this.createXMLHttpRequest();
		xhr.open("POST", url, true);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		if (typeof(msg) === "function") {
			xhr.onreadystatechange = function() {
				msg(xhr);
			};
		} else {
			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					this.updatePage(xhr.responseText, elem);
				} else {
					this.updatePage(msg, elem);
				}
			};
		}
		xhr.send(this.serializeForm(formname, submitSelectText));
	},
	serializeForm: function(formname, submitSelectText) {
		var form = document.forms[formname],
			qstr = "";
		function serializeElementValue(name, value) {
			qstr += (qstr.length > 0 ? "&" : "")
				+ encodeURIComponent(name).replace(/\+/g, "%2B") + "="
				+ encodeURIComponent(value ? value : "").replace(/\+/g, "%2B");
		}
		var elemArray = form.elements;
		for (var i = 0; i < elemArray.length; i++) {
			var element = elemArray[i],
				eType = element.type.toUpperCase(),
				eName = element.name;
			if (!eName) continue;
			if (eType == "TEXT" || eType == "TEXTAREA" || eType == "PASSWORD"
				|| eType == "BUTTON" || eType == "RESET" || eType == "SUBMIT"
				|| eType == "FILE" || eType == "IMAGE" || eType == "HIDDEN")
				serializeElementValue(eName, element.value);
			else if (eType == "CHECKBOX" && element.checked)
				serializeElementValue(eName, element.value ? element.value : "checked");
			else if (eType == "RADIO" && element.checked)
				serializeElementValue(eName, element.value);
			else if (eType.indexOf("SELECT") != -1)
			for (var j = 0; j < element.options.length; j++) {
				var o = element.options[j];
				if (o.selected)
					serializeElementValue(eName, submitSelectText ? o.text : o.value);
			}
		}
		return qstr;
	},
	updatePage: function(str, elem) {
		_getElementById(elem).innerHTML = str;
	},
	disable: function(elems, bool) {
		elems = elems.length ? elems : [elems];
		for (var i = 0; i < elems.length; i++) {
			if (elems[i]) {
				if (bool)
					_getElementById(elems[i]).setAttribute("disabled", "disabled");
				else
					_getElementById(elems[i]).removeAttribute("disabled");
			}
		}
	}
}
/* namespace Util END */

/* namespace CSS START */
var CSS = {
	POS_FIX: (Util.ie6() ? 'absolute' : 'fixed'),
	POS_ABS: 'absolute',
	POS_REL: 'relative',
	INLINE: 'inline',
	BLOCK: 'block',
	NONE: 'none',
	SCROLL: 'scroll',
	HIDDEN: 'hidden',
	PX: 'px',
	CURSOR_CROSSHAIR: 'crosshair',
	DEFAULT: '',
	Z_INDEX_TOP: 100
}
/* namespace CSS END */

/*
 *		********** FILE LISTING POPUP  **********
 */
_ws_flpMenu = null;
_ws_flpContent = null;
_ws_flpMenuInit = false;
var FLP_MENU_BUTTONS = ['Download', 'Preview', 'OpenProof', 'Copy', 'Duplicate', 'Delete', 'Rename', 'Permissions', 'Open'];
var FLP_MENU_SFX = 'cntn';
var FLPITEM_ID_SFX = 'flp';
var FLPITEM_CLASS = 'noIcon';
var FLPITEM_CLASS_ADD = 'vis';
var FLPITEM_CLASS_DISABLED = 'tbBDisabled';
var _FLP_MENU_MOUSE_PADDING = 25; // additional pixels the mouse can hover wo triggering the hide event
var _FLP_MENU_WIDTH = 120;
var _FLP_MENU_HEIGHT = 150;
var _FLP_BTN_HEIGHT = 14;
var _FLP_BTN_WIDTH = 21;
var _isIE = ((navigator.appVersion.indexOf("MSIE")!= -1) && !window.opera) ? true : false;
var _isIE6 = (_isIE && !window.XMLHttpRequest) ? true : false;

function ws_initFLPMenus() {
	if (_ws_flpMenuInit)
		return;
	_ws_flpContent = new Array(); // build menu content once
	_ws_flpContent.cnt = 0;
	for (var i = 0; i < FLP_MENU_BUTTONS.length; i++)
		addButton(FLP_MENU_BUTTONS[i]);
	_ws_flpMenuInit = true;
};

function addButton(idsfx) {
	var e = _getElementById('tbB' + idsfx);
	if (!e) return;
	if (e.tagName.toLowerCase() === "span") {
		e = e.parentNode;
		e.id = new Date().getTime();
	}
	var cpy = e.cloneNode(true);
	cpy.removeAttribute('title');
	cpy.className = FLPITEM_CLASS;
	if (cpy.getAttribute('disabled') || ws_hasClass(e, FLPITEM_CLASS_DISABLED)) // add disabled class
		ws_addClass(cpy, FLPITEM_CLASS_DISABLED);
	else {
		cpy.onmousedown = function () {
			if (this.clicked) {
				this.clicked = false;
				return false;
			}
			ws_selectFLP();
			this.clicked = true;
		};
		cpy.onmouseup = function() {
			if (this.clicked) {
				this.clicked = false;
				return false;
			}
			if (ws_selectFLP()) {
				try {
					this.click();
				} catch (error) {
					this.onclick();
				}
				this.clicked = true;
			}
		};
	}
	// add _WS_NOICON_ACTIVE_CLASS (IE6)
	cpy.onmouseover = function() { ws_addClass(cpy, 'noIconHover'); }
	cpy.onmouseout = function() { ws_removeClass(cpy, 'noIconHover'); }
	cpy.id += FLPITEM_ID_SFX;
	if (idsfx === 'Open')
		flpOpenId = cpy.id;
	_ws_flpContent.push(cpy);
	_ws_flpContent.cnt++;
};

function ws_showFLP(e) {
	if (_ws_flpMenu != null && !_ws_flpMenu.clicked && (e == _ws_flpMenu))
		return ws_hideFLP();
	else if (_ws_flpMenu != null && _ws_flpMenu.clicked)
		return false;
	_ws_flpMenu = _getElementById(e);
	if (!_ws_flpMenu) return false;
	_ws_flpMenu.mCntn = _getElementById(_ws_flpMenu.id + FLP_MENU_SFX);
	if (!_ws_flpMenu.mCntn) return false;
	Util.selectable(_ws_flpMenu, false);
	// append child nodes
	for (var i = 0; i < _ws_flpContent.cnt; i++) {
		_ws_flpContent[i].style.display = '';
		_ws_flpMenu.mCntn.appendChild(_ws_flpContent[i]);
	}
	// append visible class
	ws_addClass(_ws_flpMenu.mCntn, FLPITEM_CLASS_ADD);
	// compute position
	var sy = _isIE ? document.body.scrollTop + document.documentElement.scrollTop : window.pageYOffset;
	var pos = ws_findPosition(_ws_flpMenu);
	var w = ws_flpWidth();
	w = (!w || !isNumber(w) || isNaN(w)) ? _FLP_MENU_WIDTH : w;
	var h = ws_flpHeight();
	h = (!h || !isNumber(h) || isNaN(h)) ? _FLP_MENU_HEIGHT : h;
	var wprop = ws_getWindowProperties();
	var specialPos = {
		x: (pos.x + w + (_FLP_MENU_MOUSE_PADDING * 2)) > wprop.width,
		y: ((pos.y + _FLP_BTN_HEIGHT + h) - sy) > wprop.height
	};
	var x, y;
	if (specialPos.x)
		x = parseInt( (pos.x + _FLP_BTN_WIDTH) - w ) + 'px';
	else
		x = parseInt(pos.x) + 'px';

	if (specialPos.y)
		y = parseInt( pos.y - h + (_isIE ? parseInt(_FLP_BTN_HEIGHT / 2) : 0) ) + 'px';	
	else
		y = parseInt(pos.y + (_isIE6 ? parseInt(_FLP_BTN_HEIGHT / 2) : _FLP_BTN_HEIGHT)) + 'px';

	_ws_flpMenu.mCntn.style.left = x;
	_ws_flpMenu.mCntn.style.top = y;
	if (_isIE) // IE
		_ws_flpMenu.mCntn.style.display = 'block';
	if (isDefined(flpOpenId)) {
		// hide open entry for direcories
		var parent = ws_getParentNode(_ws_flpMenu, isDefined(document._ws_max_gallery_preview) ? 4 : 2),
			img = false;
		if (isDefined(document._ws_max_gallery_preview)) {
			img = ws_getElementsByClassName('galleryImage', parent, 'img')[0];
		} else if (parent = ws_getElementsByClassName('colIcon', parent, 'td')[0]) {
			img = parent.firstChild.firstChild;
		}
		if (img) {
			_getElementById(flpOpenId).style.display = /dir$/.test(img.src) ? 'none' : '';
		}
		// disable "Proof", "Preview" and "Open" buttons if no preview link is available) { // disable "Proof", "Preview" and "Open" buttons if no preview link is available
		if (!img || ((img = ws_getParentNode(img, 1)) && img.tagName.toLowerCase() !== "a")) {
			var disableIds = [
				"tbBOpenProof" + FLPITEM_ID_SFX,
				"tbBPreview" + FLPITEM_ID_SFX,
				"tbBDownload" + FLPITEM_ID_SFX,
				"tbBCopy" + FLPITEM_ID_SFX,
				"tbBDuplicate" + FLPITEM_ID_SFX,
				flpOpenId],
				elem, i;
			for (i = 0; i < disableIds.length; i++) {
				elem = _getElementById(disableIds[i]);
				if (elem) {
					elem.style.display = 'none';
				}
			}
		}
	}
	_ws_flpMenu.borders = ws_getBorders(_ws_flpMenu, _FLP_MENU_MOUSE_PADDING);
	_ws_flpMenu.mCntn.borders = ws_getBorders(_ws_flpMenu.mCntn);
	ws_addEvent(document, 'mousemove', ws_flpMousePositionHandler);
	return true;
};

function ws_hideFLP() {
	if (_ws_flpMenu && _ws_flpMenu.mCntn) {
		ws_removeClass(_ws_flpMenu.mCntn, FLPITEM_CLASS_ADD);
		for (var i = 0; i < _ws_flpContent.cnt; i++)
			_ws_flpMenu.mCntn.removeChild(_ws_flpContent[i]);
		ws_removeEvent(document, 'mousemove', ws_flpMousePositionHandler);
		_ws_flpMenu.mCntn.style.display = 'none';
		if (!_isIE) // not IE
			_ws_flpMenu.mCntn.style.display = '';
		_ws_flpMenu.mCntn = null;
	}
	if (_ws_flpMenu) _ws_flpMenu = null;
};

function ws_selectFLP() {
	if (!_ws_flpMenu) return false;
	var chbx = null;
	if (_getElementById("galleryControls")) {
		chbx = ws_getFirstChild(ws_getPreviousSibling(_ws_flpMenu, 'span'), 'input');
	} else {
		var td = ws_getElementsByClassName('colLabel', ws_getParentNode(_ws_flpMenu, 2), 'td')[0];
		for (var i = 0; i < td.childNodes.length && !chbx; i++)
			if (td.childNodes[i].type && td.childNodes[i].type.toLowerCase() == 'checkbox')
				chbx = td.childNodes[i];
	}
	if (chbx) {
		var chbxs = _getElementById('fileBrowserTable').getElementsByTagName('input');
		// set _ws_selection
		var l = chbxs.length;
		for (var i = 0; i < l; i++) // deselect all
			if (chbxs[i].type.toLowerCase() == 'checkbox') chbxs[i].checked = false;
		chbx.checked = true; // select current
		ws_checkSelection();
		if (!ws_unloadDisabled()) _ws_trigger_unload = false;
		_ws_flpMenu.clicked = true;
		return true;
	}
};

function ws_flpMousePositionHandler(evt) {
    if (!_ws_flpMenu) return;
	if (!evt) evt = window.event;
	var x, y;
    if (evt.pageX || evt.pageY) {
		x = parseInt(evt.pageX + + window.pageXOffset);
		y = parseInt(evt.pageY + window.pageYOffset);
	} else if (evt.clientX || evt.clientY) 	{
		x = parseInt(evt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft);
		y = parseInt(evt.clientY + document.body.scrollTop + document.documentElement.scrollTop);
		y += _isIE ? document.body.scrollTop + document.documentElement.scrollTop : 0; //window.pageYOffset;

	}
	if ( isOver(x, y, _ws_flpMenu.borders, true) || isOver(x, y, _ws_flpMenu.mCntn.borders, true) )
		return;
	ws_hideFLP();
};

function ws_flpHeight() {
	if (_ws_flpMenu.mCntn == null)
		return;
	var h = 0;
	if(window.getComputedStyle) {
		h = parseInt(window.getComputedStyle(_ws_flpMenu.mCntn, null).height);
	} else if(_ws_flpMenu.mCntn.currentStyle) {
		h = parseInt(ws_getHeight(_ws_flpMenu.mCntn.id));
	}
	if (isNaN(h) && _ws_flpMenu.mCntn.offsetHeight)
		h = _ws_flpMenu.mCntn.offsetHeight;
	return h;
};

function ws_flpWidth() {
	if (_ws_flpMenu.mCntn == null)
		return;
	var w = 0;
	if(window.getComputedStyle) {
		w = parseInt(window.getComputedStyle(_ws_flpMenu.mCntn, null).width);
	} else if(_ws_flpMenu.mCntn.currentStyle) {
		w = parseInt(_ws_flpMenu.mCntn.currentStyle.width);
	}
	if (isNaN(w) && _ws_flpMenu.mCntn.offsetWidth)
		w = _ws_flpMenu.mCntn.offsetWidth;
	return w;
};

function ws_getBorders(obj, padding) {
	padding = padding || 0;
	var sy = _isIE ? document.body.scrollTop + document.documentElement.scrollTop : window.pageYOffset;
	var t = Math.max(parseInt(sy + getPageY(obj) - padding), 0);
	var l = Math.max(parseInt(getPageX(obj) - padding), 0);
	return {
		top: t,
		bottom: parseInt(sy + getPageY(obj) + ws_getHeight(obj) + padding),
		left: l,
		right: parseInt(getPageX(obj) + ws_getWidth(obj) + padding)
	};
};

function ws_cloneNode(o, deepBool) {
	function copyEvents(o, clone) {
		for(var i = 0; i < o.childNodes.length; i++) {
			if(o.childNodes[i].onclick)
				clone.childNodes[i].onclick = o.childNodes[i].onclick;
			if(o.childNodes[i].onmouseover)
				clone.childNodes[i].onmouseover = o.childNodes[i].onmouseover;
			if(o.childNodes[i].onmouseout)
				clone.childNodes[i].onmouseout = o.childNodes[i].onmouseout;
			copyEvents(o.childNodes[i], clone.childNodes[i]);
		}
	}
	var clone = o.cloneNode(deepBool);
	copyEvents(o, clone);
	return clone;
}

function ws_zoomFontSize(selector, decrease, unit, sheetIndex) {
	var fs = parseInt(ws_setSelectorStyle(sheetIndex || 1, selector, "font-size"), 10);
	fs = decrease ? --fs : ++fs;
	if (fs <= 6) {
		return;
	}
	ws_setSelectorStyle(sheetIndex || 1, selector, "font-size", fs + (unit || "px"));
	return false;
}

function ws_setSelectorStyle(sheetIndex, selector, classStyle, styleValue) {
	var sheet = document.styleSheets[sheetIndex];
	if (!sheet) {
		return false;
	}
	var sRules = sheet.cssRules || sheet.rules;
	if (sheet.imports) {
	try {
		sRules = sheet.imports[0].cssRules || sheet.imports[0].rules;
	} catch (error) {}
	} else if (!sRules.styleSheet) { // maybe an instance of CSSImportRule
		for (var i = 0; i < sRules.length; i++) {
			if (sRules[i].styleSheet) {
				sRules = sRules[i].styleSheet;
				sRules = sRules.cssRules || sRules.rules;
				break;
			}
		}
	}
	var camelized = getCamelized(classStyle);
	var l = sRules.length;
	for (var j = 0; j < l; j++) {
		var sS = sRules[j];
		if(sS.selectorText && sS.selectorText.toLowerCase() === selector.toLowerCase()) {
			if (styleValue) {
				if (sS.style[camelized]) {
					sS.style[camelized] = styleValue;					
				} else {
					sS.style[classStyle] = styleValue;
				}
			}
			return (sS.style[classStyle] || sS.style[camelized]);
		}
	}
}

function ws_getIndexServerAttributes(link, id, input) {
	var e = _getElementById(id) || false;
	if (!e)
		return false;
	else if (e.tmpContent)
		return switchContent();
	var xhr = Util.createXMLHttpRequest();
	xhr.open("GET", link.href, true);
	xhr.send(null);
	xhr.onreadystatechange = function() {
		if (xhr.readyState != 4)
			return;
		var content = eval("(" + xhr.responseText + ")");
		if (!content.properties)
			return false;
		var	t = document.createElement("table"),
			tmpTable = ws_getFirstChild(e, "table"),
			header = t.insertRow(-1),
			headers = ["name", "aliase", "type"];
		// header row
		for (var h = 0; h < headers.length; h++) {
			header.insertCell(h).appendChild(
				document.createTextNode(
					_getElementById(headers[h] + "String").innerHTML));
		}
		e.tmpContent = ws_cloneNode(tmpTable, true);
		e.replaceChild(t, tmpTable);
		for (var p in content.properties) {
			var tr = t.insertRow(-1),
				td1 = tr.insertCell(0);
			// attribute name
			td1.appendChild(document.createTextNode(p));
			if (document.activeSearchField) {
				td1.onclick = function() {
					var input = document.activeSearchField;
					input.focus();
					input.value += " " + this.innerHTML;
					input.blur();
				};
			}
			// aliase name
			var tdA = tr.insertCell(1);
			if (content.properties[p].aliases) {
				var str = "";
				for (var a in content.properties[p].aliases) {
					if (str.length > 0)
						str += ", ";
					str += content.properties[p].aliases[a];
				}
				tdA.appendChild(document.createTextNode(str));
			}
			// type
			if (content.properties[p].type) {
				var td2 = tr.insertCell(2).appendChild(
					document.createTextNode(content.properties[p].type));
			}
		}
		// back link
		var tr = t.insertRow(-1),
			td = tr.insertCell(0),
			a = document.createElement("a");
		a.setAttribute("href", "#");
		a.setAttribute("id", e.id + "BackLink");
		a.appendChild(document.createTextNode("<<"));
		a.onclick = switchContent;
		td.appendChild(a);
		updateElementPosition(e, document.activeSearchField);
		if (_ws_searchHelp)
			_ws_searchHelp.show();
	};
	function switchContent() {
		var tmp = e.tmpContent,
			tbl = ws_getFirstChild(e, "table");
		e.tmpContent = ws_cloneNode(tbl, true);
		e.replaceChild(tmp, tbl);
		updateElementPosition(e, document.activeSearchField);
		e.scrollTop = 0;
		return false;
	};
	return false;
}


function updateElementPosition(e, field) {
	e = _getElementById(e);
	field = _getElementById(field);
	var pos = ws_findPosition(field);
	e.style.left = pos.x - (ws_getWidth(e) - ws_getWidth(field)) + "px";
	e.style.top = (pos.y + ws_getHeight(field)) + "px";
}

var HelpText = function(element, helpText, handler) {
	this.element = _getElementById(element);
	this.helpText = _getElementById(helpText);
	var timeout = false;

	function start() {
		if (!timeout)
			timeout = window.setTimeout(function() {
				handler({ show: false });
			}, 700);
	}
	
	function callHandler(b) {
		if (timeout) {
			window.clearTimeout(timeout);
			timeout = false;
		}
		handler({ show: b });
	}
	
	ws_addEvent(this.element, "mouseover", function() { callHandler(true); });
	ws_addEvent(this.element, "focus", function () { callHandler(true); start(); });
	ws_addEvent(this.element, "mouseout", function () { start(); });
	ws_addEvent(this.helpText, "mouseout", function() { callHandler(false); });
	ws_addEvent(this.helpText, "mouseover", function() { callHandler(true); });
};

var SearchHelp = function(elem, helpText, field) {
	var hText = helpText,
		elem = _getElementById(elem),
		paddingBottom = 12,
		field = field;
		
	function getField() {
		return _getElementById(field);
	};
	
	function updatePosition() {
		updateElementPosition(elem, getField());
		updateSize();
	};

	function updateSize() {
		var winH = ws_getWindowProperties().height,
			pos = parseInt(elem.style.top),
			px = (pos + ws_getHeight(elem));
		if (px > winH) { 
			px = winH - pos - paddingBottom + "px";
		} else if (px + paddingBottom < winH) {
			px = "";
		}
		elem.style.height = px;
	}

	this.setElements = function(anElement, aHelpText) {
		field = anElement;
		hText.helpText = aHelpText;
		document.activeSearchField = getField();
		updatePosition();
	};

	this.show = function() {
		hText.helpText.style.visibility = "hidden";
		ws_switchDisplay(elem, _isIE6 ? "inline" : false, getField(), "left", true);
		ws_addEvent(window, "resize", updatePosition);
		updatePosition();
		elem.scrollTop = 0;
		return false;
	};
	
	this.hide = function() {
		var a = _getElementById(elem.id + "BackLink");
		if (a && a.onclick) a.onclick();
		ws_hide(elem);
		hText.helpText.style.visibility = "visible";
		ws_removeEvent(window, "resize", updatePosition);
		elem.style.height = "";
		return false;
	};
};

function switchSearchfield() {
	var dlg = document.getElementById("fileSearchDialog");
	if (!dlg) return
	ws_switchDisplay(dlg, Util.ie6() || Util.ie7() ? "block" : "table");
	var e = document.getElementById("fbSearchField");
	if (e)
		try {
			e.focus();
		} catch (error) {}
	e = _getElementById("fbSearchFieldToggle");
	if (e)
		e.src = /down/.test(e.src) ? e.src.replace(/down/, "right") : e.src.replace(/right/, "down");
	e = _getElementById("fbSearchFieldDisplay");
	if (e) {
		e.value = dlg.style.display == "none";
		ws_tbLinkParam("wsSDMin", e.value, true);
	}
	return false;
}

function ws_decodeHeliosUTF8(str) {
	var hutf8First = "2357",
		hutf8Second = ["2af", "acef", "ce", "c"],
		hutf8Replace = ["\"*/", ":<>?", "\\^", "|"],
		i = str.indexOf('^'),
		l = str.length,
		pos = 0,
		cpos = 0,
		decoded = "";
	if (l < 3 || i < 0)
		return str;
	decoded += str.substring(0, i);
	while (l - i >= 3) {
		switch (str.charAt(i)) {
			case '^':
				if ( (pos = hutf8First.indexOf(str.charAt(++i))) > -1
						&& (cpos = hutf8Second[pos].indexOf(str.charAt(i + 1))) > -1) {
					decoded += hutf8Replace[pos].charAt(cpos);
					i += 2;
					continue;
				} else
					decoded += str.charAt(i - 1);
				break;
			default:
				decoded += str.charAt(i++);
				break;
		}
	}
	return decoded += str.substring(i);
}

function ws_getObjectForFilename(name) {
	name = ws_decodeHeliosUTF8(name);
	name = name.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;");
	var t = _getElementById("fileBrowserTable"),
		tr = false,
		i = false,
		item = false,
		link = false,
		level = 4,
		galleryView = document._ws_max_gallery_preview;
	if (t)
		tr = t.getElementsByTagName("tr");
	else
		return false;
	for (var i in tr) {
		if (!isDefined(tr[i]) || !tr[i].tagName)
			continue;
		item = ws_getElementsByClassName(
			galleryView ? (_getElementById("detailCheckbox").checked ? "noEllipsis" : "ellipsis") : "colName",
			tr[i],
			galleryView ? "span" : "td")[0];
		if (item) {
			var itemName = item.innerHTML;
			// Firefox uses window and description tags for cropping in gallery view
			if (item.firstChild && item.firstChild.tagName
				&& item.firstChild.tagName.toLowerCase() === "window"
				&& item.firstChild.firstChild.value) {
				itemName = item.firstChild.firstChild.value;
			}
			if (itemName === name) {
				if (galleryView && ws_getParentNode(item, level).tagName.toLowerCase() === "tbody")
					level = 5;
				return galleryView ? ws_getParentNode(item, level) : item;
			}
			link = ws_getFirstChild(item, "a");
			if (link && link.innerHTML === name)
				return tr[i];
		}
	}
	return false;
}

function WSJavaScriptCommandException(message) {
	this.message = message;
	this.name = "WSJavaScriptCommandException";
}
	 
WSJavaScriptCommandException.prototype.toString = function() {
  return this.name + ': "' + this.message + '"';
}


var WSJavaScriptCommand = (function () {
	var FileParamName = document._jsCommandFileParam || "ws_files",
		FileParamSeparator = document._jsCommandFileSeparator || ";",
		ShareParamName = document._jsCommandShareParam || "ws_share",
		NamefieldParamName = document._jsCommandNamefieldParam || "ws_namefield",
		xhr, postString, fileString, shareName, actionName, namefieldContent, callback;

	function init() {
		postString = "";
		fileString = "";
		shareName = "";
		namefieldContent = "";
		callback = false;
		actionName = false;
	}

	function addParameter(key, value) {
		if (isDefined(key, value) && value.length)
			postString += (postString.length > 0 ? "&" : "")
				+ encodeURIComponent(String(key))
				+ (String(value) ? "=" + encodeURIComponent(String(value)) : "");
	}

	function addFile(e) {
		if (_getElementById("filepreviewBody") || _getElementById("pagePreviewBody")) {
			name = "ws_currentPreviewFile";
		} else {
			e = _getElementById(e);
			if (!e || !e.tagName)
				return;
			var t = e.tagName.toLowerCase(),
				name = false;
			if ((t === "table" && ws_hasClass(e, "fileItem")) || t === "tr") {
				addFile(e.getElementsByTagName("a")[0]);
			} else if (t === "a") {
				if (e && e.href && /.*f=([a-f0-9]*)/.exec(e.href) != null)
					name = RegExp.$1;
			} else {
				addFile(ws_getParentNode(e, 1));
			}
		}
		if (name) {
			fileString += (fileString.length > 0 ? FileParamSeparator : "")
				+ encodeURIComponent(name);
		}
	}

	init();
	
	return {
		setCommand: function(name) {
			actionName = name;
		},
		addParameters: function(parameters) {
			if (namefieldContent && parameters)
				throw new WSJavaScriptCommandException("Post parameters can not be set if name field content is set!");
			if (parameters && typeof(parameters) === "object") {
				for (var p in parameters)
					addParameter(p, parameters[p])
			}
		},
		addFiles: function(files) {
			if (!files)
				return false;
			if (typeof(files) === "object" && files.length) {
				for (var f in files)
					addFile(files[f]);
			} else {
				addFile(files);
			}
			return true;
		},
		setSharepoint: function(name) {
			if (!document._jsCommandShareParam && name)
				throw new WSJavaScriptCommandException("Sharepoint can not be overridden in this component!");
			shareName = name;
		},
		setNamefieldContent: function(content) {
			if (postString && content)
				throw new WSJavaScriptCommandException("Name field content can not be set if post parameters are set!");
			namefieldContent = content;
		},
		setCallback: function(func) {
			callback = function() { func(xhr); };
		},
		send: function() {
			if (!document._jsCommandURL)
				return false;
			if (!actionName)
				throw new WSJavaScriptCommandException("No command set!");
			addParameter(FileParamName, fileString);
			addParameter(NamefieldParamName, namefieldContent);
			addParameter(ShareParamName, shareName);
			xhr = Util.createXMLHttpRequest();
			if (callback)
				xhr.onreadystatechange = callback;
			xhr.open("POST", document._jsCommandURL + actionName, true);
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8; encoding=UTF-8");
			xhr.send(postString || null);
			init();
			return true;
		}
	}
})();

var WSProperties = (function () {
	var PropertyParamName = document._jsPropertyKey || "ws_propertyKey",
		PropertyParamValue = document._jsPropertyValue || "ws_propertyValue",
		xhr, propertyKey, propertyValue, postString, callback;

	function init() {
		postString = "";
		propertyKey = "";
		propertyValue = "";
		callback = false;
	}

	function addParameter(key, value) {
		if (isDefined(key, value))
			postString += (postString.length > 0 ? "&" : "")
				+ encodeURIComponent(String(key))
				+ (String(value) ? "=" + encodeURIComponent(String(value)) : "");
	}

	function send() {
		if (!document._jsCommandURL)
			return false;
		addParameter(PropertyParamName, propertyKey);
		addParameter(PropertyParamValue, propertyValue);
		var response = undefined;
		xhr = Util.createXMLHttpRequest();
		if (callback)
			xhr.onreadystatechange = callback;
		xhr.open("POST", document._jsCommandURL + document._jsPropertyAction, callback !== false);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8; encoding=UTF-8");
		xhr.send(postString || null);
		if (callback === false) {
			if (xhr.responseText && xhr.responseText.charAt(0) === '{') {
				var obj = eval("(" + xhr.responseText + ")");
				return isDefined(obj.propertyValue) ? obj.propertyValue : null;
			} else
				return xhr.responseText;
		}
		return true;
	}

	init();
	
	return {
		setCallback: function(func) {
			callback = function() { func(xhr); };
		},
		getProperty: function(key) {
			propertyKey = key;
			var ret = send();
			init();
			return ret;
		},
		setProperty: function(key, value) {
			propertyKey = key;
			propertyValue = value;
			var ret = send();
			init();
			return ret;
		}
	}
})();

