/// <reference path="../../../js/jquery-1.4.1-vsdoc.js" />
/// <reference path="../../../js/MicrosoftAjax.debug.js" />

Function.prototype.delegate = function(ref) {
	var f = this;
	return function() { return f.apply(ref, arguments); };
};
(function() {
	function responseParser(onSuccess, onError) {
		return function(data, textStatus, XMLHttpRequest) {
			Sys.Debug.traceDump(data);
			if (!data)
				return onError({ "_FORM": "Data not found" });
			if (data.Errors)
				return onError(data.Errors);
			return onSuccess(data);
		}
	}
	function requestErrorParser(onError) {
		return function(XMLHttpRequest, textStatus, errorThrown) {
			onError({ "_FORM": "Request error." });
		}
	}

})();
(function() {
	$ = jQuery;
	var servicePath = '/getsuggestions/';

	function suggestionParser(request, response) {
		return function(data) {
			if (data != null && jQuery.isArray(data)) {
				var re = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi");
				response($.map(data, function(d) {
					return {
						id: d.ID,
						label: d.DisplayName.replace(re, "<strong>$1</strong>"),
						value: d.DisplayName
					};
				}));
				return;
			}
			response([]);
		}
	}
	function getTargetList(element) {
		var p = $(element).parent(), list = p.find('ul.selected');
		if (list.length)
			return list;
		return $('<ul class="selected"></ul>').appendTo(p);
	}
	function renderItem(data, obj) {
		$('input[type="hidden"][name="' + obj.name + '"]').remove();
		return $('<input type="hidden"/>').attr("name", obj.name).val(data.id || data.ID);
	}
	function checkValues(el, obj) {
		var values = $(el).parent().find('input:hidden[name=' + obj.name + ']');
		if (!values.length)
			return;
		var target = getTargetList(el);
		values.each(function() {
			var tf = $(this), val = tf.val(); tf.remove();

			$.getJSON(servicePath + obj.type + '/Item/' + val, function(data) {
				if (data != null) {
					el.val(data.DisplayName);
					obj.renderItem(data, obj).insertAfter(el);
				}
			});
		});
	}
	$.fn.entitySuggestion = function(opts) {
		this.filter('input').each(function() {
			var targetInput = $(this);
			var obj = {
				delay: opts.delay || 1500,
				type: opts.type,
				name: targetInput.attr("name"),
				source: opts.source || function(request, response) {
					$.getJSON(servicePath + obj.type, { input: request.term }, suggestionParser(request, response));
				},
				appendTo: opts.appendTo || targetInput.parent(),
				renderItem: opts.renderItem || renderItem,
				targetList: opts.targetList || getTargetList(targetInput)[0],
				select: opts.select || function(event, ui) {
					targetInput.val(ui.value);

					obj.renderItem(ui.item, obj).insertAfter(targetInput);
				},
				close: opts.close || function() {
					//targetInput.val('');
				}
			};
			targetInput.data('MSport.filterSuggestions', obj);
			try {
				targetInput[0].removeAttribute("name");
			}
			catch (e) { targetInput.attr("name", null); }
			checkValues(targetInput, obj);

			targetInput.autocomplete({
				appendTo: obj.appendTo,
				source: obj.source,
				delay: 500,
				select: obj.select,
				close: obj.close,
				open: function(event, ui) {
					$("ul.ui-autocomplete li a").each(function(){
						$(this).html($(this).html().replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
					});
				}
			});

			targetInput.data("autocomplete").menu.element.wrapAll('<div class="suggest"  style="position:absopute;"><div class="tl"><div class="bl"><div class="tr"><div class="br"><div class="top"><div class="bottom"><div class="left"><div class="right"><div class="c"/></div></div></div></div></div></div></div></div></div>'); // = wrapper;
			targetInput.data("autocomplete")._suggest = function(a) {
				var c = this.menu.element.empty().zIndex(this.element.zIndex() + 1), d;
				this._renderMenu(c, a);
				this.menu.deactivate();
				this.menu.refresh();
				var menuWrapper = this.menu.element.parent().parent().parent().parent().parent().parent().parent().parent().parent().parent();
				menuWrapper.show().position({ my: "left top", at: "left bottom", of: this.element, collision: "none" });
				this.menu.element.show()
				a = c.width("").width();
				d = this.element.width();
				c.width("100%");
				menuWrapper.width(Math.max(a, d))
			};
			targetInput.data("autocomplete").close = function(event) {
				clearTimeout(this.closing);
				if (this.menu.element.is(":visible")) {
					this._trigger("close", event);
					this.menu.element.hide();
					this.menu.deactivate();
				}
				var menuWrapper = this.menu.element.parent().parent().parent().parent().parent().parent().parent().parent().parent().parent();
				menuWrapper.hide();


			};
		});
		return this;
	}

	$('ul.selected a.delete').live('click', function() {
		$(this).parent().remove();
		return false;
	});
})();


