/**
 * Search suggestions facility
 */

(function ($) {

	$(function () {

		var cache = [];

		$.extend($.ui.autocomplete.prototype, {

			_renderItem: function(ul, item) {

				var addclass = '';
				var label = $("<span>" + item.label + "</span>");

				if (item.image) {

					var img = $("<img style='display: inline-block;' src='" + item.image + "' " + " class='ui-menu-image' align='top' />");

					if (item.image_w)
						img.width(parseInt(item.image_w));

					if (item.image_h)
						img.height(parseInt(item.image_h));

					label = ($("<div class='ui-menu-image-container'></div>").append(img)).append(label.addClass('ui-menu-image-text'));
				}

				if (item.add_autosubmit)
					label = label.append($("<div class='ui-menu-submit-btn' onclick='window.location = \"" + xcart_web_dir + "/search.php?mode=search&substring=" + item.value + "\";'></div>"));

				var li = $("<li " + addclass + "></li>");

				if (item.last_item)
					li.addClass('ui-menu-item-last');

				if (item.spelling_suggestion)
					li.addClass('ui-menu-item-spelling-suggestion');

				if (item.href) {
					return li.data("item.autocomplete", item).append($("<a href='" + item.href + "'></a>").append(label)).appendTo(ul);
				} else {
					return li.data("item.autocomplete", item).append($("<a></a>").append(label)).appendTo(ul);
				}

			},

			_renderMenu: function(ul, items) {
				var self = this;

				$.each(items, function(index, item) {

					if (item.separator) {
						ul.append("<li class='ui-menu-separator'><span>" + item.label + "</span></li>");

					} else {
						self._renderItem( ul, item );
					}

				});
			}

		});

		var search_field = $("form[name='productsearchform'] input[name='posted_data[substring]']");

		search_field.attr('autocomplete', 'off');

		search_field.autocomplete({

			source: function(request, response) {

				var term = request.term.toLowerCase();
				if (term in cache) {
					response(cache[term]);
					return;
				}

				//search_field.addClass('search-waiting');
				lastXhr = $.getJSON(xcart_web_dir + "/suggest.php", request, function(data, status, xhr) {
					//console.log(xhr);
					cache[term] = data;
					//if (xhr === lastXhr) {
						response(data);

						//search_field.removeClass('search-waiting');
					//}
				});

			},

			position: {
				my: "right top",
				at: "right bottom",
				collision: "none",
				offset: "0 3"
			},

			minLength: Search_Suggestions['minLength'],
			delay: Search_Suggestions['delay'],

			select: function(event, ui) {

				if (ui.item.href)
					window.location = ui.item.href;

				if (ui.item.autosubmit)
					$(this).closest('form').submit();

				if (ui.item.reopen) {
					search_field.autocomplete('search', ui.item.value);
				}

			}

		});

	});

})(jQuery);

