// Copyright (c) 2003-2005 Juerg Lehni, Lineto.com. All rights reserved.
// Copying and reuse is strictly prohibited.

__fdr = Finder.prototype = new Window();

SHOWURL = 4096;

function Finder(id, levels, size, x, y, skin, flags) {
	this.levels = levels;
	this.selWidth = 120;
	var ref = 'gui.' + id + '.', str = '';
	for (var i = 0; i < levels; i++) {
		var p = {tabindex: i + 1, onClick: ref + 'onNavig(' + i + ')', onMouseUp: ref + 'onNavig(' + i + ', false, true)', onChange: ref + 'onNavig(' + i + ', true)', onKeyDown: 'return ' + ref + 'onNavigKey(' + i + ', event)'};
		if (flags & CHOOSER) p.onDblClick = ref + 'onDblClick(' + i + ')';
		str += this.renderSelect('l' + i, size, this.selWidth, p);
	}
	var fixn4 = is.nav4 && is.mac ? '<td><img src="/img/spacer.gif" width="6" height="6" alt=""></td>' : null;
	if (fixn4) str = '<table border="0" cellpadding="0" cellspacing="0"><tr>' + fixn4 + '</tr><tr valign="top"><td></td><td>' + str + '</td></tr></table>';
	str = '<form name="' + id + 'Form" action="javascript:' + ref + 'onEnterDown()" onSubmit="return ' + ref + 'onEnterDown()" autocomplete="off"><table border="0" cellpadding="0" cellspacing="0"><tr><td nowrap>' + str + '</td></tr></table>';
	var end = is.nav4 ? '' : '</form>';
	var showUrl = flags & SHOWURL;
	cbeEval(this, Window, id, x, y, null, null, skin, flags | FIXCONTENT | (showUrl ? HASMORE : 0), str + end);
	if (showUrl) {
		var w = this.content.width();
		var h = this.content.height();
		var s = is.nav4 ? (is.mac ? 'size="131"' : 'size="108"') : 'style="width:100%;visibility:hidden;"'
		str += '<table border="0" cellpadding="0" cellspacing="0" width="' + w + '"><tr>';
		if (fixn4) str += fixn4;
		str += '<td><input name="url" value="" class="small" ' + s + '></td></tr>';
		if (fixn4) str += '<tr>' + fixn4 + '</tr>';
		str += '</table>';
		this.setHtml(str);
		this.diffW = 0;
		this.diffH = this.content.calcHeight() - h;
	}
	this.form = cbeGetFormByName(id + 'Form');
	var f = this.form;
	var ns = this.selects = [];
	for (var i = 0; i < levels; i++)
		ns[i] = this.form['l' + i];

	this.urlTimeout = -1;
	
	if (showUrl) {
		var c = cbeGetCookie(id + '_expand');
		this.expand(c == 1 || c == null);
	}
}

__fdr.init = function(items, parse) {
	var l = items.length;
	this.item = items[l - 1];
	this.aliases = l > 1 ? items[l - 2] : null;
	this.last = this.item.length - 1;
	if (parse) {
		if (this.aliases)
			for (var i in this.aliases) this.aliases[i] = this.aliases[i].split('.');
		this.parsePathRefs(this.item);
	}
	this.setNavig(0, this.item);
	this.currSel = null;
}

__fdr.parsePathRefs = function(item) {
	var chs = item[this.last];
	if (chs && typeof chs != 'string') {
		for (var i = 0; i < chs.length; i++) {
			var ch = chs[i];
			if (typeof ch == 'string') {
				if (this.aliases) {
					var path = this.aliases[parseInt(ch, 16)];
					if (path) {
						var refItem = this.item;
						for (var j = 0; j < path.length; j++) refItem = refItem[this.last][path[j]];
						if (refItem) chs[i] = refItem;
					}
				} else chs[i] = [ch];
			} else this.parsePathRefs(ch);
		}
	}
}

__fdr.setNavig = function(level, item) {
	for (var i = this.selects.length - 1; i >= level; i--) {
		var sel = this.selects[i];
		if (sel && sel.options.length > 0) {
			sel.selectedIndex = -1;
			sel.options.length = 0;
		}
		// ff bugfix
		sel.style.color = 'white';
	}
	var chs = item[this.last];
	if (item && chs && typeof chs == "object") {
		var sel = this.selects[level];
		if (sel) {
			for (var i = 0; i < chs.length; i++) {
				var n = chs[i][0];
				if (fix.tm) n = n.replace(/\u2122/g, '');
				push(sel.options, new Option(n));
			}
			// ff bugfix
			sel.style.color = '';
		}
	}
}

__fdr.getSelection = function(level, corrIndex) {
	var item = this.item;
	var items = [];
	var path = [];
	for (var i = 0; i <= level; i++) {
		var sel = this.selects[i];
		if (sel.length == 0) break;
		var index = sel.selectedIndex;
		if (index < 0) {
			if (corrIndex) index = 0;
			else return null;
		}
		item = item[this.last][index];
		items[i] = item;
		if (item[0]) path[i] = item[0];
	}
	return {
		item: item, index: index, items: items, level: level,
		path: '/' + path.join('/').replace(/\+/g, '%2b').replace(/ /g, '+').replace(/\?/g, '%253f') + (path.length > 0 ? '/' : '')
	};
}

__fdr.navigIndex = function(level, set, corrIndex, params, noWait, dontLoad) {
	var sel = this.getSelection(level, corrIndex);
	if (sel && (!this.currSel || (this.currSel.level != level || this.currSel.index != sel.index))) {
		this.currSel = sel;
		if (set) this.setNavig(level + 1, sel.item);
		if (this.onSelect && !dontLoad) this.onSelect(sel, params, noWait);
	}
	if (fix.autoscroll) self.scrollTo(0, 0);
}

__fdr.selectPath = function(path, refresh, dontLoad) {
	if (!this.open) this.zoom(true);
	if (refresh == null) refresh = 1;
	if (!path || path == '/') {
		this.setNavig(0, this.item);
		this.navigIndex(-1, false, false, null, true, dontLoad);
	} else {
		var path = unescape(path).replace(/\+/g, ' ').split('/');
		if (path) {
			if (!path[path.length-1]) path.length--;
			var start = 0;
			if (path[0] != '' && this.loadedSel) { // rel -> abs
				var p = [];
				start = Math.min(this.loadedSel.level, this.currSel.level);
				for (var i = 1; i <= this.loadedSel.level; i++) p[i] = this.loadedSel.items[i-1][0];
				for (var j = 0; j < path.length; j++) p[i+j] = path[j];
				path = p;
			}
			var item = this.item;
			var max = path.length-1;
			for (i = 1; i<=max; i++) {
				var p = path[i], q = p.indexOf('?'), n;
				if (q != -1 && p.lastIndexOf('=') > q) p = p.split('?');
				else p = [p];
				n = p[0];
				if (n == '') {
					this.currSel = null;
					if (i > start) this.navigIndex(i-2, true, false, p[1], true, dontLoad);
				} else {
					var ch = item[this.last];
					if (ch) {
						for (var k=0; k<ch.length; k++) if (ch[k][0] == n) break;
						if (k < ch.length) {
							var sel = this.selects[i-1];
							if (sel && (refresh || sel.selectedIndex != k || i == max)) {
								sel.selectedIndex = k;
								this.selectDelayed(i-1, k); // sfr scrl fix
								if (i > start) {
									sel.focus();
									if (i == max)
										this.currSel = null;
									this.navigIndex(i-1, true, false, p[1], i == max, dontLoad);
									refresh = 1;
								}
							}
							item = ch[k];
						} else break;
					} else break;
				}
			}
		}
	}
}

__fdr.selectDelayed = function(i, j) {
	setTimeout(this.getRef() + ".selects[" + i + "].selectedIndex=" + j, 1);
}

__fdr.selectUrl = function(url, refresh, dontLoad) {
	var s = hostName + urlPrefix;
	if (url.indexOf(s) == 0) url = url.substring(s.length, url.length);
	if (url.charAt(0) == '/') this.selectPath(url, refresh, dontLoad);
	else window.open(url);
}

__fdr.onEnterDown = function() {
	if (this.form.url) this.selectUrl(this.form.url.value, true);
	return false;
}

__fdr.onNavig = function(level, corrIndex, click) {
	if (click) this.moveToFront();
	var sel = this.selects[level];
	if (sel && sel.length > 0) {
		if (click && (!is.ie || !is.mac || event.offsetX < this.selWidth - 16))
			this.currSel = null;
		this.navigIndex(level, true, corrIndex);
	}
}

__fdr.onNavigKey = function(level, e) {
	if (e.metaKey) return true;
	var key = e.which ? e.which : e.keyCode;
	var navigLevel = -1;
	if (key == 37) { // l
		if (level > 0) navigLevel = level - 1;
	} else if (key == 39) { // r
		if (level < this.selects.length - 1) navigLevel = level + 1;
	} else if (key == 13) {
		this.callOnChoose(level, true);
	} else if (key == 27) {
		if (this.onCancel) this.onCancel();
	} else {
		var c = String.fromCharCode(key).toLowerCase();
		if (key == 8 || /\w/.test(c)) {
			var t = getNow();
			var diff = this.queryTime ? t - this.queryTime : -1;
			this.queryTime = t;
			if (this.lastKey != key || diff > 50) {
				if (!this.query || diff > 1000) this.query = "";
				if (key == 8) this.query = this.query.substring(0, this.query.length - 1);
				else this.query += c;
				// search for this one:
				var sel = this.selects[level];
				if (sel && sel.length > 0) {
					var cur = sel.selectedIndex;
					var os = sel.options;
					for (var i = 0; i < os.length; i++)
						if (os[i].text.replace(/[\s\._]/g, '').substring(0, this.query.length).toLowerCase() == this.query)
							break;
					if (i < os.length && i != cur)
						sel.selectedIndex = i;
					this.navigIndex(level, true);
				}
			}
			this.lastKey = key;
			return false;
		}
	}
	if (navigLevel >= 0) {
		var sel = this.selects[navigLevel];
		if (sel && sel.length > 0) {
			var index = sel.selectedIndex;
			sel.focus();
			this.navigIndex(navigLevel, navigLevel > level, true);
			if (index < 0) this.selectDelayed(navigLevel, 0);
			else sel.selectedIndex = index;
			return false;
		}
	}
	return true;
}

__fdr.onDblClick = function(level) {
	this.callOnChoose(level);
}

__fdr.callOnChoose = function(level, enter) {
	if (this.onChoose) {
		var sel = this.getSelection(level, false);
		while (sel && sel.item[0] == "")
			sel = this.getSelection(--level, false);
		if (sel) this.onChoose(sel, enter);
	}
}

__fdr.onExpand = function(expand) {
	this.form.url.blur();
	var s = this.form.url.style;
	if (s) s.visibility = expand ? 'visible' : 'hidden';
	this.moveTo(this.left(), this.top() - this.diffH * (expand ? 1 : -1));
	var e = new Date();
	e.setTime(new Date().getTime() + 86400000 * 365);
	cbeSetCookie(this.id + '_expand', expand ? 1 : 0, e);
};

__fdr.onEndLoad = function() {
	if (fix.move) this.fixMove();
	this.loadedSel = this.currSel;
}

__fdr.focus = function() {
	if (this.currSel) this.selects[this.currSel.level].focus();
	else {
		var s = this.form.l0;
		s.selectedIndex = 0;
		this.navigIndex(0, true);
		s.focus();
	}
	if (fix.autoscroll) self.scrollTo(0, 0);
}
