﻿function LiveSearch() {
	var a = this;
	this.searchField = {};
	this.searchButton = {};
	this.searchList = {};
	this.searchUrl = {};
	this.searchPlaceHolder = {};
	this.targetUrl = {};
	this.targetPlaceHolder = {};
	this.searchText = {};
	this.searchTimer = null;

	this.attach = function () {
		this.searchField = $(this.searchField);
		this.searchField.attr('autocomplete', 'off');
		this.searchButton = $(this.searchButton);
		this.searchList = $(this.searchList);

		if (this.searchField.val() === '') {
			this.searchField.val(this.searchText);
		}

		this.searchButton.click(function () {
			if (a.searchField.val() === a.searchText) {
				a.searchField.val('');
			}
		});

		this.searchField.focus(function () {
			if (a.searchField.val() === a.searchText) {
				a.searchField.val('');
			}
		});

		this.searchField.blur(function () {
			if (a.searchField.val() === '') {
				a.searchField.val(a.searchText);
			}
		});

		this.searchField.keyup(function () {
			if (a.searchTimer != null) {
				window.clearTimeout(a.searchTimer);
			}
			if (a.searchField.val().length > 2) {
				a.searchTimer = window.setTimeout(function () {
					var url = a.searchUrl.replace(a.searchPlaceHolder, Base64.encode(a.searchField.val()));
					var result = '';
					$.getJSON(url, function (data) {
						if (data.length > 0) {
							result += '<ul>';
							for (i = 0; i < data.length; i++) {
								target = a.targetUrl.replace(a.targetPlaceHolder, Base64.encode(data[i]));
								result += '<li><a href="' + target + '" title="' + data[i] + '">' + data[i] + '</a></li>';
							}
							result += '</ul>';
							a.searchList.html(result);
							a.searchList.visible = true;
						}
					});
				}, 500);
			} else {
				a.searchList.visible = false;
				a.searchList.html('');
				window.clearTimeout(this.searchTimer);
			}
		});
	};
};
