(function($, window, undefined) {
	var ti;
	var textarea;
	var searchboxInitialized = false;
	
	function initSearchbox() {
		if (searchboxInitialized) return;
		ti = $('<input type="text"/>').hide();
		ti.appendTo('body');
		ti.keydown(function(e){
			if (e.keyCode == 27) {
				ti.hide();
				textarea.focus();
			}
		});
		
		ti.blur(function(){
			ti.hide();
			textarea.focus();
		});
		ti.nmgSearchbox({cssClass:'nmg-searchbox', minLength:2, dataUrl:'/autocomplete/loadSuggestions', menuRenderer:'_renderSearchboxMenu', suggestionSelected:function(v) {
			textarea.surroundSelectedText('<a href="'+v.link+'">', '</a>');
			ti.hide();
			ti.val('');
		}});
		searchboxInitialized = true;
	}
	
	$.fn.nmgLinkEditor = function() {
		return this.each(function(){
			$(this).keydown(function(e){
				var sel = $(this).getSelection();
				if (e.keyCode == 40 && sel.length > 0) {
					e.preventDefault();
					textarea = $(this);
					initSearchbox();
					ti.show();
					ti.position({my:'right bottom', at:'right top', of:textarea});
					ti.focus();
				}
			});
		});
	}
	
})(jQuery, window);
