var searchbox = function () {
	var $;
	var searchbox_destinations_full;
	
	function add_helptext(selector, text) {
		var $inputs = $(selector);
		
		function _removetext() {
			if (this.value == text) {
				this.value = "";
			}
			$(this).removeClass("searchbox-input-helptext");
			return true;
		}
		$inputs.focus(_removetext);
		
		function _addtext() {
			if (this.value == "" || this.value == text) {
				this.value = text;
				$(this).addClass("searchbox-input-helptext");
			}
			else {
				$(this).removeClass("searchbox-input-helptext");
			}
			return true;
		}
		$inputs.blur(_addtext);
		
		$inputs.each(_addtext);
		
		return { addText: _addtext, removeText: _removetext };
	}
	
	function init(jquery, selected, baseUrl) {
		$ = jquery;
		
		var destTree = $("#destinations-tree");
		
		var datepicker_helptext_callbacks = add_helptext(".searchform-datepicker", "pp.kk.vvvv");
		
		$(".searchform-datepicker").each(function () {
			$(this).datepicker({
				dateFormat: "d.m.yy",
				showWeek: true,
				minDate: "+0",
				// these make sure that the help text works with datepicker
				beforeShow: datepicker_helptext_callbacks.removeText,
				onClose: datepicker_helptext_callbacks.addText
			});
		});
		
		// make searchbox resizable
		var col_height_diff = Math.max(0, $("#searchbox-column-2").height() - $("#searchbox-column-1").height());
		var searchbox_grip = $('<div id="searchbox-grip" class="ui-resizable-handle ui-resizable-s ui-icon ui-icon-grip-dotted-horizontal" />');
		$("#searchbox-content").append(searchbox_grip);
		searchbox_grip.css({
			position: 'absolute',
			bottom: 0,
			width: 16,
			height: 12,
			left: ($("#searchbox").width() / 2) - 8
		});
		$("#searchbox").resizable({
			handles: { s: "#searchbox-grip" },
			alsoResize: "#destinations-tree",
			minHeight: $("#searchbox").height() - col_height_diff
		});
		
		// make search box collapsible
		$("#searchbox > .ui-widget-header")
			.prepend('<span class="ui-icon ui-icon-triangle-1-e searchform-collapsible-icon" />&nbsp;')
			.css("padding-left", 0)
			.toggle(
				function () {
					$(this).parent().children(".searchform-collapsible").show("blind");
					$(".searchform-collapsible-icon:first", this)
						.addClass(   "ui-icon-triangle-1-s")
						.removeClass("ui-icon-triangle-1-e");
					$(".searchbox-title-text", this).text("Haku");
				},
				function () {
					$(this).parent().children(".searchform-collapsible")
						.parent()
							.css("height", "auto")
							.end()
						.hide("blind");
					$(".searchform-collapsible-icon:first", this)
						.removeClass("ui-icon-triangle-1-s")
						.addClass(   "ui-icon-triangle-1-e");
					$(".searchbox-title-text", this).text("Äkkilähtöjen hakuehtojen muokkaus");
				}
			);
		$(".ui-widget:has(.searchform-collapsible) > .ui-widget-header")
			.css("cursor", "pointer");
		
		var help_dialog = $('<div>tekstihakua ei vielä toteutettu</div>')
			.dialog({
				title: "Tekstihaun ohje",
				autoOpen: false,
				closeText: "sulje",
				close: function () { $("#words-help").removeClass("ui-state-active"); }
			});
		$("#words-help")
			.hover(
				function () { $(this).addClass(   "ui-state-hover"); },
				function () { $(this).removeClass("ui-state-hover"); }
			)
			.click(function () {
				if (help_dialog.dialog("isOpen")) {
					help_dialog.dialog("close");
				}
				else {
					help_dialog.dialog("open");
					$("#words-help").addClass("ui-state-active");
				}
			});
		
		$.spin.btnClass = "searchbox-spinner-buttons";
		$.spin.imageBasePath = baseUrl + "jquery-spin/img/spin1/";
		$.spin.min = 0;
		$.spin.timeInterval = 333;
		$.spin.changed = function (val) {
			if (val == 0) {
				this.val("");
			}
		};
		$.spin.decimal = ",";
		$("#duration_min, #duration_max, #num_people_min, #num_people_max").spin();
		$("#price_max").spin({ interval: 50 });
		$("#hotel_star_rating_min").spin({ interval: 0.5, max: 5 });
		
		// hover effect for various UI elements
		$("#searchform-submit, #searchbox > .ui-widget-header, #words-help").each(function () {
			var val = $(this).hasClass("ui-state-default");
			function hasUiStateDefaultOriginally() { return val; }
			$(this).hover(
				function () { $(this).addClass(   "ui-state-hover").filter(hasUiStateDefaultOriginally).removeClass('ui-state-default'); },
				function () { $(this).removeClass("ui-state-hover").filter(hasUiStateDefaultOriginally).addClass(   'ui-state-default'); }
			);
		});
		
		// collapse search box
		$("#searchbox-content").hide();
		
		
		//---------------------------------------------------------------
		// jsTree for destination select box:
		
		// reformat destination list structure so that jsTree can use it
		$(".destination-item").each(function (i) {
			$("label", this).replaceWith($("label", this).contents());
			var checkbox = $(".destination-checkbox", this);
			$(this).parent().attr("data-destination-item-id", checkbox.attr("value"));
			checkbox.replaceWith("&nbsp;");
			var a = $('<a href="#" />');
			a.append($(this).contents());
			$(this).replaceWith(a);
		});
		
		// create a jsTree instance
		destTree.tree({
//			ui: { theme_name: "checkbox" },
			ui: {
				theme_name: "akkilahdot",
				theme_path: baseUrl + "jstree-theme/style-solidline.css"
			},
			plugins: {
				checkbox: {}
//				hotkeys: {
//					hover_mode: true,
//					functions: {
//						"return": function () { $.tree.plugins.checkbox.toggle(this); return false; },
//						"space": function () {alert(123); return false;},
//						"up"	: function () {
//							$.tree.plugins.hotkeys.get_prev.apply(this);
//							$("#destinations-tree .destination-li").removeClass("ui-state-highlight");
//							$(this).addClass("ui-state-highlight");
//							return false;
//						},
//						"down"	: function () {
//							$.tree.plugins.hotkeys.get_next.apply(this);
//							$("#destinations-tree .destination-li").removeClass("ui-state-highlight");
//							$(this).addClass("ui-state-highlight");
//							return false;
//						}
//					}
//				}
			},
			types: {
				"default": { draggable: false }
			}
		});
		// open all subtrees
//		$.tree.reference("#destinations-tree").open_all();
		
		// save a copy of the tree so that we can restore it after filtering
		searchbox_destinations_full = destTree.clone();
		
		// select currently selected destinations
		if (selected != "") {
			$(selected).each(function() {
				$.tree.plugins.checkbox.check(this);
			});
		}
		
		// create a filter textbox that filters the contents of the tree
		$("#destinations-container").prepend(
			'<input type="text" id="destination_filter" value="" size="40" class="searchform-stretching-textbox" autocomplete="off" />' );
		add_helptext("#destination_filter", "anna hakusana");
		
		function filter () {
//			var filterText = $.trim($(this).val().toLowerCase());
			var filterText = $.trim($("#destination_filter").val().toLowerCase());
			
			var fulltree = searchbox_destinations_full.clone();
			$(".destination-li > a").each(function () {
				$("#" + $(this).parent().attr("id") + " > a", fulltree).replaceWith(this);
			});
			// this is needed for resizable behaviour
			fulltree.height($("#destinations-tree").height());
			$("#destinations-tree").replaceWith(fulltree);
			
			var tree = $.tree.reference("#destinations-tree");
			
			function refreshCheckboxes() {
				// unselect and re-select selected leaf nodes so that parent nodes get correct statuses
				// (checked or undetermined)
//				$.tree.plugins.checkbox.get_checked(tree).each(function () {
				$("#destinations-tree .destination-li > a.checked").each(function () {
					if (tree.children(this).length === 0) {
						$.tree.plugins.checkbox.uncheck(this);
						$.tree.plugins.checkbox.check(this);
					}
				});
			}
			
			function deleteSubtree() {
				var a = $("a:first", this);
				if (!(
					a.hasClass("checked") || // also show all checked nodes
					filterText == "" ||
//					a.text().toLowerCase().indexOf(filterText) != -1 ))
					$(this).attr("x:aliases").toLowerCase().indexOf(filterText) !== -1 ))
				{
					tree.children(this).each(deleteSubtree);
					// if no children left after processing, delete the node
					if (tree.children(this).length === 0) {
						tree.remove(this);
					}
				}
			}
			
			refreshCheckboxes();
			
			$("#destinations-tree > ul > .destination-li").each(deleteSubtree);
			
			refreshCheckboxes();
		}
		$("#destination_filter").bind("change keyup", filter);
		
		// add buttons below the tree component
		$('<div id="destination-tree-buttons"></div>')
			.insertAfter("#destinations-container")
			.append(
				$('<button id="destination-tree-selectall">Valitse kaikki</button>')
					.click(function () {
						$("#destinations-tree .destination-li > a").each(function () {
							$.tree.plugins.checkbox.check(this);
						});
						return false;
					}))
			.append(
				$('<button id="destination-tree-deselectall">Poista valinnat</button>')
					.click(function () {
						$("#destinations-tree .destination-li > a.checked").each(function () {
							$.tree.plugins.checkbox.uncheck(this);
						});
						return false;
					}))
//			.append(
//				$('<button id="destination-tree-openall">Avaa kaikki</button>')
//					.click(function () {
//						$.tree.reference("#destinations-tree").open_all();
//						return false;
//					}))
//			.append(
//				$('<button id="destination-tree-openall">Sulje kaikki</button>')
//					.click(function () {
//						$.tree.reference("#destinations-tree").close_all();
//						return false;
//					}))
			.children()
				.addClass('ui-button ui-widget ui-state-default ui-corner-all')
				.hover(
					function () { $(this).addClass(   "ui-state-hover"); },
					function () { $(this).removeClass("ui-state-hover"); }
				);
		
		// form submit handler
		// adds fields hidden fields corresponding to the checkboxes of the tree to the form
		$("#searchbox-form").submit(function (e) {
			// remove filter
			$("#destination_filter").val("");
			$("#destination_filter").each(filter);
			
			var input = $('<input type="hidden" name="destinations[]" value="" />');
			function processSubtree() {
				if ($("a:first", this).hasClass("checked")) {
					var inp = input.clone();
					inp.attr("value", $(this).attr("data-destination-item-id"));
					$("#searchbox-form").append(inp);
				}
				else //if ($("a:first", this).hasClass("undetermined"))
				{
					$("ul:first > .destination-li", this).each(processSubtree);
				}
			}
			$("#destinations-tree > ul > .destination-li").each(processSubtree);
			return true;
		});
	}
	
	return { init: init };
}();

