﻿Type.registerNamespace("SitefinityWebApp.Widgets.SearchBox");

SitefinityWebApp.Widgets.SearchBox.SearchBoxCustom = function (element) {
	SitefinityWebApp.Widgets.SearchBox.SearchBoxCustom.initializeBase(this, [element]);

	this._searchBox = null;
}

SitefinityWebApp.Widgets.SearchBox.SearchBoxCustom.prototype = {

	initialize: function () {
		SitefinityWebApp.Widgets.SearchBox.SearchBoxCustom.callBaseMethod(this, "initialize");

		if (this._searchBox) {
			this._keyPressDelegate = Function.createDelegate(this, this._keyPressHandler);
			$addHandler(this._searchBox.get_element(), "keypress", this._keyPressDelegate);
		}
	},

	dispose: function () {
		if (this._searchBox && this._keyPressDelegate) {
			if (this._searchBox) {
				$removeHandler(this._searchBox.get_element(), "keypress", this._keyPressDelegate);
			}
			delete this._keyPressDelegate;
		}
		SitefinityWebApp.Widgets.SearchBox.SearchBoxCustom.callBaseMethod(this, "dispose");
	},

	/* -------------------- Public methods ---------------- */

	navigateToResults: function (e) {
		if (!e) var e = window.event;

		if (e.stopPropagation) {
			e.stopPropagation();
		}
		else {
			e.cancelBubble = true;
		}
		if (e.preventDefault) {
			e.preventDefault();
		}
		else {
			e.returnValue = false;
		}

		if (this._searchBox.get_value() && this._indexCatalogue) {
			window.location = this.getLocation();
		}
	},

	getLocation: function () {
		var query = this._searchBox.get_value();
		var separator = (this._resultsUrl.indexOf("?") == -1) ? "?" : "&";
		var indexCatalogue = String.format("{0}indexCatalogue={1}", separator, Url.encode(this._indexCatalogue));
		var searchQuery = String.format("&searchQuery={0}", Url.encode(query));
		var wordsMode = String.format("&wordsMode={0}", this._wordsMode);
		var url = this._resultsUrl + indexCatalogue + searchQuery + wordsMode;

		return url;
	},

	/* -------------------- properties ---------------- */

	get_searchBox: function () {
		return this._searchBox;
	},
	set_searchBox: function (value) {
		this._searchBox = value;
	}
};

SitefinityWebApp.Widgets.SearchBox.SearchBoxCustom.registerClass("SearchBoxCustom", Telerik.Sitefinity.Services.Search.Web.UI.Public.SearchBox);
