wmp.provide("wmp.gui");

wmp.gui.comments = new Class({
	initialize: function(baseurl) {
		this.baseurl = baseurl;
		this.nodes = {
			newcomment: $('linktocomment'),
			container: $('comments-container'),
			formcontainer: new Element("div", {'class':'comment commentform'})
		}
		if (!this.nodes.newcomment || !this.nodes.container)
			return;
		
		this.nodes.newcomment.addEvent("click", this.showform.bindWithEvent(this));
		var els = this.nodes.container.getElements('.comment');
		var el, c=0;
		while (el = els[c++]) {
			this.ajaxifyComment(el, false);
		}
		var els = this.nodes.container.getElements('.sub-comments .comment');
		var el, c=0;
		while (el = els[c++]) {
			el.getElement(".comment-body").setStyle('height', '0');
			el.getElement(".comment-body").setStyle('display', 'none');
		}
		
		//show comment in hash
		if (window.location.hash && window.location.hash.substring(1,9) == "comment-") {
			var el = $(window.location.hash.substring(1,100));
			if (el)
				this.show(el, true);
		}
	},
	
	ajaxifyComment: function(el, hide) {
		if (hide) {
			el.getElement(".comment-body").setStyle('height', '0');
			el.getElement(".comment-body").setStyle('display', 'none');
		}
		
		el.getElement("h6").addEvent("dblclick", this.dblclick.bindWithEvent(this,el));
		el.getElement("h6").addEvent("click", this.click.bindWithEvent(this,el));
		el.getElement("a.reply").addEvent("click", this.showform.bindWithEvent(this,el));
	},
	
	show: function(el, open, nohash)
	{
		var body = el.getElement(".comment-body");
		var openFX = new Fx.Tween(body, {'property':'height','duration':150, 'link': 'cancel'});
		
		var height = body.getCoordinates().height;
		if (height<10|| open) {
			el.getElement(".comment-body").setStyle('display', 'block');
			openFX.start(null,body.scrollHeight);
			/*
			if (!nohash) {
				//set hash but do not jump
				var y = window.pageYOffset;
				this.setHash(el);
				console.log(y + " " + window.pageYOffset);
				//window.pageYOffset = 0;
				//todo
				if (window.firefox)
					window.scroll(0, y);
			}*/
		}
		else {
			el.getElement(".comment-body").setStyle('display', 'none');
			openFX.start(null,0);
		}
	},
	
	expandtree: function(el)
	{
		var els = el.getNext().getElements('.comment');
		this.show(el, true);
		var comm, c=0;
		while (comm = els[c++]) {
			this.show(comm, true, true);
		}
	},
	
	dblclick: function(event, el) {
		this.expandtree(el);
	},
	
	click: function(event, el) {
		this.show(el);
	},
	
	showform: function(event, el) {
		event.stop();
		if (el)	{
			this.nodes.formcontainer.inject($(el).getNext(), 'top');
			this.nodes.newcomment.style.display = "block";
			var a = el.getElement("a.reply");
			var href = wmp.url.toRel(a.getAttribute("href"));
			this.posturl = this.baseurl + "reply-ajax" + href.substring(href.lastIndexOf('-'));
		}
		else {
			this.posturl = this.baseurl + 'post-ajax';
			this.nodes.newcomment.style.display = "none";
			if (this.nodes.container)
				this.nodes.formcontainer.inject(this.nodes.container, 'top');
			else
				this.nodes.formcontainer.inject(this.nodes.newcomment, 'after');
		}
		
		this.loading();
		this.ajax = new Request.HTML({
			'onComplete': this.showform_onComplete.bind(this),
			'update': this.nodes.formcontainer
		}).get(this.posturl);
	},
	
	showform_onComplete: function(tree, elements, html) {
		this.nodes.formcontainer.setStyle("height","auto");
		this.postform = $("post-comment");
		if (!this.postform) {
			//user is not logged in: redirect to login page
			var l = window.location;
			l.href = "/account/login/?next=" + wmp.url.toRel(window.location.href, l.protocol+"//"+l.host);
			return;
		}
		this.postform.addEvent("submit", this.submitform.bindWithEvent(this));
		this.postform.setAttribute("action", this.posturl);
		
		try {
		this.editor = new wmp.editor.customize.comment({
			field: $('form_text'),
			startuphelp: false,
			css: ["/static/comment.css", "/static/content.css", "/static/editor-content.css"],
			modules: {
				add: ["p","blockquote", "list", "blockcode"],
				other: ["body_comment", "br", "li"],
				inline: ["a", "strong", "em", "ins", "del", "code"]
			},
			gui: {
				maxFormatters: 10,
				maxAdd: 0
			}
		});
		}
		catch(e) {console.warn("comments: could not start editor");}
	},
	
	submitform: function(event, el) {
		this.editor.stop();
		event.stop();
		this.ajax = new Request.HTML({
			'url':$(this.postform).getProperty('action'), 
			'onComplete': this.submitform_onComplete.bind(this)
		}).post($(this.postform));
		this.loading();
	},
	
	submitform_onComplete: function(tree, elements, html) {
		this.nodes.formcontainer.setStyle("height","auto");
		if (html.indexOf('class="comment"') != -1) {
			//form ok
			var e = new Element("div").set('html', html);
			var comment = e.getFirst();
			comment.replaces(this.nodes.formcontainer);
			this.ajaxifyComment(comment, false);
			var subComments = e.getLast();
			subComments.inject(comment, 'after');
			//this.setHash(comment);
		}
		else {
			//form invalid, retry
			this.nodes.formcontainer.set('html', html);
			this.showform_onComplete(tree, elements, html);
		}
	},
	
	loading: function() {
		var height = this.nodes.formcontainer.getCoordinates().height;
		if (height < 30)
			height = "auto";
		this.nodes.formcontainer.setStyle("height", height);
		this.nodes.formcontainer.empty().appendChild(new Element("div",{'class':'ajax-loading'}));
	},
	
	setHash: function(el)
	{
		window.location.hash = "#" + el.id;
	}
});

wmp.gui.checkInput = new Class({
	initialize: function(options)
	{
		this.options = options;
		this.oldc = this.getValue();
		$(this.options.node).addEvent("focus", this.onfocus.bind(this));
		this.options.node.addEvent("blur", this.onblur.bind(this));
		this.options.node.addEvent("change", this.onchange.bind(this));
		this.options.node.addEvent("keypress", this.onkeypress.bindWithEvent(this));
		this.options.node.addEvent("click", this.checkchange.bindWithEvent(this));
	},
	interval: 1000,
	stop: function() {
		this.options.node.removeEvents();
		this.active = false;
	},
	onfocus: function() {
		this.active = true;
		this.checkchange();
	},
	onblur: function() {
		this.active = false;
	},
	onchange: function() {
		this.checkchange();
	},
	onkeypress: function(e) {
		if (e.key == "enter") {
			e.preventDefault();
			if (this.options.onEnter)
				this.options.onEnter();
		}
		this.checkchange();
	},
	checkchange: function(e) {
		//debug, todo: to prevent a strange error in ff, where the focus is stoelen from the field after clicking
		if (e && e.target)
			e.preventDefault();
		if (this.active) {
			if (!this.options.node.parentNode)
				this.active = false;
			var c = this.getValue();
			if (c != this.oldc) {
				//console.log("changed, old: '" + this.oldc + "' new: '" + c + "'");
				this.oldc = c;
				this.options.onchange();
			}
			window.setTimeout(this.checkchange.bind(this), this.interval);
		}
	},
	getValue: function() {
		if (this.options.getValue)
			return this.options.getValue().toString();
		else
			return this.options.node.value.toString();
	}
});


//Idee: ü -> ue, Müll -> M+ü+e+l+l+, Phonetische Suche, Fuzzy suche
wmp.gui.filter = new Class({
	initialize: function(searchbox, selector)
	{
		this.searchbox = searchbox;
		this.selector = selector;
		this.container = document;
		this.elements = this.container.getElements(selector);
		this.checker = new wmp.gui.checkInput({
			node:this.searchbox,
			onchange:this.filter.bind(this)
		});
		this.filter();
	},
	
	filter: function()
	{
		var value = wmp.encodeRegex(this.searchbox.value);
		var el, c=0;
		while (el = this.elements[c++]) {
			var reg = new RegExp(value, "im");
			if ( reg.test(el.innerHTML.stripTags()) )
				this.fadeIn(el);
			else
				this.fadeOut(el);
		}
	},
	
	fadeIn: function(node)
	{
		if (node._wmpStatusShow == true)
			return;
		//node.setStyle("opacity", 1);
		//node.setStyle("color", "#000");
		node.setStyle("display", "");
		node._wmpStatusShow = true;
	},
	
	fadeOut: function(node)
	{
		
		if (node._wmpStatusShow == false)
			return;
		//node.setStyle("opacity", .3);
		//node.setStyle("color", "#eee");
		node.setStyle("display", "none");
		node._wmpStatusShow = false;
	}
});


wmp.gui.dropdown = new Class({
	options: {
		timeout: 300,
		minLength: 2,
		searchvar: 'search'
	},
	initialize: function(options) {
		$extend(this.options, options);
		
		if (!this.options.field)
			this.field = new Element("input");
		else
			this.field = $(this.options.field);
		
		this.field.setAttribute("autocomplete", "off");
		
		this.div = new Element("div", {'class': 'autocomplete'});
		this.div.setStyle("width", this.field.getCoordinates().width - 2);
		//this.div.setStyle("left", this.field.getPosition().x);
		this.div.inject(this.field, 'after');
		this.hide();
		
		this.request = new Request.JSON({'url': this.options.dataurl, 'onComplete': this.onDataComplete.bind(this), 'method': 'get'});
		this.checker = new wmp.gui.checkInput({
			node:this.field,
			onchange:this.inputchanged.bind(this)
		});
		this.field.addEvent("keyup", this.show.bind(this));
		this.field.addEvent("click", this.show.bind(this));
		this.field.addEvent("focus", this.show.bind(this));
		this.field.addEvent("blur", this.hide.bind(this));
		
		this.items = [];
	},
	doTimeout: function(func, waittime) {
		if (this.timeout)
			clearTimeout(this.timeout);
		this.timeout = window.setTimeout(func,waittime||this.options.timeout);
	},
	getData: function() {
		var search = this.field.get('value').trim();
		if (search.length>=this.options.minLength) {
			var data = {}
			data[this.options.searchvar] = search
			this.request.get(data);
		}
		else
			this.removeItems();
	},
	onDataComplete: function(jsonObj) {
		this.data = jsonObj;
		this.filterData();
	},
	filterData: function() {
		if (this.options.filter) {
			if (this.search.trim().length<this.options.minLength-1)
				return this.removeItems();
			var reg = new RegExp(wmp.encodeRegex(this.search), "i");
			this.results = {};
			var n;
			for (n in this.data) {
				if (reg.test(this.data[n]) && this.data[n]!=this.search) {
					this.results[n] = this.data[n];
				}
			}
		}
		else
			this.results = this.data;
		this.showItems();
	},
	showItems: function() {
		this.removeItems();
		for (var n in this.results) {
			var item = new wmp.gui[this.options.dropdownitem || "dropdownitem"](this.results[n], n);
			this.items.push(item);
			item.autocomplete = this;
			this.div.appendChild(item.div);
		}
		this.show();
	},
	
	removeItems: function() {
		while (this.items.length)
			this.items.pop().remove();
	},
	
	inputchanged: function() {
		this.search = this.field.value;
		this.doTimeout(this.getData.bind(this));
	},
	
	setValue: function(value) {
		this.field.value = value;
		this.field.focus();
	},
	
	hide: function() {
		this.div.style.display='none';
	},
	
	show: function() {
		if (this.div.innerHTML.length<8)
			return this.hide();
		this.div.style.display='block';
	}
});

wmp.gui.dropdownitem = new Class({
	initialize: function(obj, name) {
		this.name = name;
		this.obj = obj;
		this.div = new Element("div");
		this.div.set('text', name).addClass("item").addEvent("mousedown", this.click.bind(this));
	},
	click: function() {
		this.autocomplete.setValue(this.name);
	},
	remove: function(){
		this.div.removeEvents();
		this.div.dispose();
		delete(this.div);
	}
});


wmp.gui.string = new Class({
	initialize: function(options) {
		this.options = options;
		this.node = this.field = new Element("input");
		if (this.options.value)
			this.setValue(this.options.value);
		
		this.checker = new wmp.gui.checkInput({
			node:this.field,
			onchange:this.onchange.bind(this),
			getValue: this.getValue.bind(this),
			onEnter: this.options.onEnter
		});
	},
	getValue: function() {
		if (this.options.trim)
			return this.field.value.trim();
		return this.field.value;
	},
	setValue: function(value) {
		this.field.value = value || "";
	},
	onchange: function() {
		this.options.onchange();
	}
});

wmp.gui.url = new Class({
	initialize: function(options) {
		this.options = options;
		this.node = this.field = new Element("input");
		if (this.options.value)
			this.setValue(this.options.value);
		
		this.checker = new wmp.gui.checkInput({
			node:this.field,
			onchange:this.onchange.bind(this),
			getValue: this.getValue.bind(this),
			onEnter: this.options.onEnter
		});
	},
	getValue: function() {
		if (this.options.trim)
			return this.field.value.trim();
		return this.field.value;
	},
	setValue: function(value) {
		this.field.value = value || "";
	},
	onchange: function() {
		this.options.onchange();
	}
});


wmp.gui.checkbox = new Class({
	initialize: function(options) {
		this.options = options;
		this.node =  new Element("div", {"class": "checkboxcontainer", "text":options.text||""});
		this.field = new Element("input", {"type":"checkbox"}).inject(this.node, 'top')
		if (this.options.value)
			this.setValue(this.options.value);
		this.field.addEvent("change", this.onchange.bind(this));
	},
	getValue: function() {
		return this.field.checked;
	},
	setValue: function(value) {
		this.field.checked = value;
	},
	onchange: function() {
		this.options.onchange();
	}
});

wmp.gui.select = new Class({
	initialize: function(options) {
		this.options = options;
		this.node = this.field = document.createElement("select");
		if (this.options.options)
			this.setOptions(this.options.options);
		if (this.options.selectedValues)
			this.setSelectedValues(this.options.selectedValues);
		this.checker = new wmp.gui.checkInput({
			node:this.field,
			onchange:this.onchange.bind(this),
			getValue: this.getSelectedValues.bind(this)
		});
	},
	
	getValue: function() {
		//field.value does not work for ie (i guess if only text is specified and no value)
		return this.field.value || this.field.options[this.field.selectedIndex].text;
	},
	
	setValue: function(value) {
		var option, c=0;
		while (option = this.field.options[c++]) {
			if (option.value == value || option.text == value)
				option.selected = true;
		}
	},
	
	setSelectedValues: function(values) {
		var option, c=0;
		while (option = this.field.options[c++]) {
			option.selected = (values.contains(option.value) || values.contains(option.text));
		}
	},
	
	getSelectedValues: function() {
		var option, c=0, result =[];
		while (option = this.field.options[c++]) {
			if (option.selected)
				result.push(option.value);
		}
		return result;
	},
	
	setOptions: function(options) {
		var c=0;
		for(var prop in options) {
			c++;
			var option = new Element("option",{"value":prop,"text":options[prop]}).inject(this.field);
		}
		/*if (c > 8)
			this.field.setAttribute("size", 8);*/
	},
	onchange: function(option) {
		this.options.onchange();
	}
});


wmp.gui.multiselect = new Class({
	initialize: function(options)
	{
		this.options = options;
		this.node = this.field = $(document.createElement("div"));
		this.field.addClass("select");
		if (this.options.options)
			this.setOptions(this.options.options);
		if (this.options.selectedValues)
			this.setSelectedValues(this.options.selectedValues);
		if (this.options.value)
			this.setSelectedValues([this.options.value]);

	},
	
	setSelectedValues: function(values)
	{
		var option, c=0;
		var options = this.field.getElements("div");
		while (option = options[c++]) {
			if (values.contains(option._value))
				option.addClass("selected");
			else
				option.removeClass("selected");
		}
	},
	
	getSelectedValues: function()
	{
		var option, c=0, result =[];
		var options = this.field.getElements("div");
		while (option = options[c++]) {
			if (option.hasClass("selected"))
				result.push(option._value);
		}
		
		return result;
	},
	
	setOptions: function(options) {
		for(var prop in options) {
			var option = $(document.createElement("div"));
			option._value = prop;
			option.set('text', options[prop]);
			option.addEvent("click", this.changed.bind(this, option));
			this.field.appendChild(option);
		}
	},
	
	changed: function(option) {
		if (option.hasClass("selected"))
			option.removeClass("selected");
		else
			option.addClass("selected");
		this.options.onchange();
	}
});



wmp.gui.imagechooser = new Class({
	initialize: function(options)
	{
		this.options = options;
		this.node = this.field = $(document.createElement("div"));
		this.field.addClass("imagechooser");
		if (this.options.options)
			this.setOptions(this.options.options);
	},
	
	setValue: function(value)
	{
		this.value = value;
	},
	
	getValue: function()
	{
		return this.value || "";
	},
	
	setOptions: function(options) {
		this.field.empty();
		for(var prop in options) {
			var option = new Element("div");
			var l = window.location;
			var pathname = l.pathname;
			if (!(pathname.lastIndexOf('/') == pathname.length-1))
				pathname += '/';
			var url = l.protocol+"//"+l.host+pathname + prop + '/icon/';
			option.style.backgroundImage = "url("+url+")";
			option.title = options[prop];
			option._value = prop;
			//option.set('text', options[prop]);
			option.addEvent("click", this.clicked.bind(this, option));
			this.field.appendChild(option);
		}
	},
	
	clicked: function(option) {
		this.value = option._value;
		this.title = option.title;
		this.options.onchange();
	}
});


wmp.gui.upload = new Class({
	Implements: Options,
	options: {
		'filenamePattern': 'filename="([^"]*)"',
		'target':'',
		'fieldname':'file',
		'onchange': $empty,
		'errorNodeId': 'error'
	},
	initialize: function(options)
	{
		this.id = "uform"+Math.floor(Math.random()*2000);
		this.setOptions(options);
		
		this.node = new Element("div",	{'class': 'wmpe-upload'	});
		
		this.form = new Element("form",	{'enctype':"multipart/form-data", 'method':"post", 'action': this.options.target, 'target': this.id }).inject(this.node);
		this.form.target = this.id; //ie
		this.iframe = new IFrame(
			{
			'src':'',
			'name': this.id,
			'styles': {
				'position': 'absolute',
				'left': '-3000px'
				}
			}
		).inject(this.form);
		this.iframe.name= this.id; //ie
		this.statusnode = new Element("div",	{'class': 'wmpe-upload-status'	}).inject(this.form);
		
		
		this.button = new Element("div", {
			'class': 'wmpe-uploadbutton',
			'text': 'Datei wählen'
		}).inject(this.form);
		this.file = new Element("input", {
			'type': 'file',
			'name': this.options.fieldname,
			'styles': {
				'opacity': .01,
				'z-index': 2
				}
			}).inject(this.button);
		this.file.addEvent("change", this.startupload.bind(this));
	},
	
	
	getValue: function() {
		return this.value || "";
	},
	
	getName: function() {
		return this.name || "";
	},
	
	startupload: function() {
		this.idoc = this.iframe.contentWindow.document;
		this.idoc.open();
		this.idoc.write("uploading");
		this.idoc.close(); 
		this.form.submit();
		this.statusnode.set('text', 'wird hochgeladen');
		window.setTimeout(this.checkstatus.bind(this),150);
	},
	
	checkstatus: function() {
		var win = new Window(this.iframe.contentWindow);
		var doc = new Document(win.document);
		//$extend(win.Element.prototype, Element.Prototype);
		var html = doc.documentElement.innerHTML;
		//console.log(html);
		if (html.indexOf("uploading")!=-1)
			return window.setTimeout(this.checkstatus.bind(this),150);
		var reg = new RegExp(this.options.filenamePattern, "im");
		var result = reg.exec(html);
		
		if (!result) {
			var msgnode = doc.getElementById(this.options.errorNodeId);
			if (msgnode)
				var msg = msgnode.innerHTML;
			else
				var msg = "Konnte Upload nicht starten";
			this.statusnode.set('text', 'Fehler beim Upload:' + msg);
			//this.options.onchange(); //activate only for debug-environment
		}
		else {
			this.statusnode.set('text', 'Datei wurde hochgeladen.');
			this.value = result[1];
			this.options.onchange();
		}
	}
	
});




wmp.gui.elTaggor = new Class({
	initialize: function(options) {
		this.options = {
			dataurl:"/tag/ajax",
			timeout: 300
		}
		$extend(this.options , options);
		this.node = new Element("div", {'class': 'taggor'});
		this.mytags = new Element("div", {'class': 'mytags'}).inject(this.node);
		
		//this.node.appendChild(document.createTextNode("Tag suchen/hinzufügen: "));
		this.searchfield = new Element("input", {'events':{'change': this.typeTags.bind(this), 'keyup': this.typeTags.bind(this), 'keypress': this.keypress.bindWithEvent(this)}}).inject(this.node);
		this.popcont = new Element("div", {'class': 'taggor-popc'}).inject(this.node);
		
		this.pop = new Element("div", {'class': 'taggor-pop'}).inject(this.popcont);
		this.tagpool = new Element("div", {'class': 'tagpool'}).inject(this.pop);
		this.helptext = new Element("div", {'class': 'taggor-help'}).set("html", "Geben Sie einen Suchbegriff ein um schon vergeben Tags zu finden. Diese können Sie dann hinzufügen. <br/> Drücken Sie die <em>Eingabetaste</em> um einen neuen Tag, den es noch nicht gibt zu erstellen.").inject(this.pop);
		this.start();
	},
	start: function() {
		this.request = new Request.JSON({'url': this.options.dataurl, 'onComplete': this.onDataComplete.bind(this)});
		this.node.inject(this.options.field, 'after');
		$(this.options.field).setStyle('display', 'none');
		
		this.searchfield.addEvent('focus', this.onFocus.bind(this));
		this.searchfield.addEvent('blur', this.onBlur.bind(this));
		this.onBlur();
		
		this.importTags();
	},
	importTags: function() {
		var value = $(this.options.field).get('value');
		var tags = value.split(",");
		for(var i=0;i<tags.length;i++) {
			var name = tags[i].trim();
			if (name!="")
				this.spawnTag(name, this.mytags);
		}
	},
	exportTags: function() {
		var value = "";
		var tags = this.mytags.getChildren();
		for(var i=0;i<tags.length;i++)
			value += tags[i].innerHTML + ", ";
		$(this.options.field).value = value.substring(0,value.length-2);
	},
	hasTag: function(name, pool) {
		var tags = pool.getChildren();
		var name = name.toLowerCase();
		for(var i=0;i<tags.length;i++) {
			if (tags[i].innerHTML && (tags[i].innerHTML.toLowerCase() == name)) {
				return tags[i];
			}
		}
		return false;
	},
	toggleTag: function(tag) {
		if (tag.parentNode == this.tagpool) {
			if (this.hasTag(tag.innerHTML, this.mytags))
				return;
			this.addTag(tag, this.mytags);
		}
		else {
			this.addTag(tag, this.tagpool);
		}
		this.searchfield.focus();
		this.exportTags();
	},
	removeTags: function(tagpool) {
		tagpool.empty();
	},
	typeTags: function() {
		var value = this.searchfield.get('value').trim();
		if (this.searchvalue!=value) {
			clearTimeout(this.timeout);
			this.searchvalue = value;
			this.timeout = setTimeout(this.loadTags.bind(this), this.options.timeout);
		}
	},
	loadTags: function(search) {
		this.request.cancel();
		if (this.searchvalue.length>1)
			this.request.get({'search': this.searchvalue});
	},
	onDataComplete: function(jsonObj) {
		this.data = jsonObj;
		this.spawnTagsFromData();
	},
	spawnTagsFromData: function() {
		this.removeTags(this.tagpool);
		for (tag in this.data) {
			this.spawnTag(this.data[tag], this.tagpool);
		}
	},
	spawnTag: function(name, pool) {
		var tag = new Element("div", {'class': 'tag'}).set('html', name);
		tag.addEvent('mousedown', this.toggleTag.bind(this, tag));
		this.addTag(tag, pool);
	},
	addTag: function(tag, pool) {
		tag.inject(pool);
		pool.appendChild(document.createTextNode(" "));
	},
	keypress: function(event) {
		if (event.key == "enter") {
			event.preventDefault();
			this.createTag(this.searchfield.get('value'));
			this.searchfield.value = "";
		}
	},
	createTag: function(name) {
		var tag;
		if (this.hasTag(name, this.mytags))
			return;
		if (tag = this.hasTag(name, this.tagpool))
			this.toggleTag(tag);
		else
			this.spawnTag(name, this.mytags);
		this.exportTags();
	},
	onFocus: function(name) {
		this.pop.setStyle('display', 'block');
	},
	onBlur: function(name) {
		this.pop.setStyle('display', 'none');
	}
});


wmp.gui.usersearch = function(field) {
	if (!field)
		return;
	field.setStyle("display","none");
	var hp;
	if(field && field.parentNode && (hp = $(field.parentNode).getElement(".helptext"))) 
		hp.setStyle("display","none");
	
	var userdisplay = new Element('div', {'class':'userdisplay','text': "nicht gewählt..."}).inject(field, 'before');
	var autofield = new Element('input', {'value': '','styles':{'width':'12em'}}).inject(field, 'before');
	
	
	var completer = new Autocompleter.Ajax.Json(autofield, '/user/ajax', {
		'delay': 300,
		'postVar': 'search',
		'method': 'get', 
		'markQuery': false,
		'minLength': 3,
		'selectMode': false,
		'indicatorClass': 'autocompleter-loading',
		'injectChoice': function(token) {
			var name = token.name.trim() || token.user;
			var choice = new Element('li', {'text': this.markQueryValue(name)})
				.adopt(new Element('i').set('text', this.markQueryValue(token.user)));
			choice._value = token;
			choice.inputValue = name;
			this.addChoiceEvents(choice).inject(this.choices);
		},
		'onSelection': function(input,el) {
			var user = el._value;
			setUser(user);
		}
	});
	
	
	var setUser = function(user) {
		field.value = user.user;
		var name = user.name.trim() || user.user;
		userdisplay.set("html",'<a href="/user/'+user.user +'/">'+name+'</a>');
	}
	
	var getUsername = function(user) {
		var request;
		request = new Request.JSON({
			'url': '/user/ajax',
			'onSuccess': function(json) {
				setUser(json[0]);
			},
			'onFailure': function(instance) {
				console.error("usergetFailure", instance);
			}
		}).get({"username": user });
	}
	if ((field.value.length||"")>3)
		getUsername(field.value);
}


wmp.gui.linker = function(field, urlField, onSelection) {
	//var field = new Element('input', {'value': orgField.value}).inject(orgField, 'before');
	
	var completer = new Autocompleter.Ajax.Json(field, '/search/results/ajax', {
		'delay': 300,
		'postVar': 'search',
		'method': 'get',
		'markQuery': false,
		'minLength': 3,
		'className': 'autocompleter-choices autocompleter-links',
		'indicatorClass': 'autocompleter-loading',
		'selectMode': false,
		'onSelection': function(input,el) {
			urlField.value = el._value.url;
			onSelection();
		},
		'injectChoice': function(token) {
			var choice = new Element('li', {'html': this.markQueryValue(token.title)});
				//.adopt(new Element('i').set('html', this.markQueryValue(choice.url)));
			choice._value = token;
			choice.inputValue = token.title;
			this.addChoiceEvents(choice).inject(this.choices);
		}
	});
	
	completer.query = function() {
		var data = {"search": this.queryValue};
		this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
		//strange hack:
		//this.request.get({'json': '{"search": "'+this.queryValue+'", "content_type":"article.article"}'});
		this.request.get({'json': '{"search": "'+this.queryValue+'"}'});
	}
}


