jQuery(document).ready(function($) {
	
	if(!$("html").hasClass("loggedIn"))
		return;
	
	var search_input = $("div.search input.autocomplete");
	var selected_item = [];
	var selection = false;
	var lock = false;
	var items = [false];

	$.getJSON("/api2/buyable/item", function(data) {
		if(data.error === undefined) {
			source = [];

			$.each(data, function(key, item) {
				items[item.id] = item;
				
				source.push({
					value: item.id,
					label: "<span class='preview pk" + item.id + "'><img src='" +
						MEDIA_URL + item.image + "' alt='" +
						item.name + "' /></span>" +
						"<span class='meta'>" + item.name +
						"<br />Preis: " + parseFloat(item.price).toFixed(2) +
						" €</span><span class='buy'></span>"
				});
			});

			search_input.val("");
			$("div.search form").removeAttr("action")
				.children("input[type='submit']").remove();

			search_input.autocomplete({
				source: source,
				html: true,
				appendTo: ".search",
				close: function(event, ui) {

				},
				focus: function(event, ui) {
					selection = ui.item;
					
					//search_input.val(items[selection.value].fields.name);
					$("ul.ui-autocomplete").children().removeClass("focus");
					$(".pk" + selection.value).parent().parent()
						.addClass("focus");

					event.preventDefault();
				},
				select: function(event, ui) {
					location.href = "/store/show/" + ui.item.value + "/";

					search_input.val(items[ui.item.value].fields.name);
					event.preventDefault();
				}
			});

			search_input.keydown(function(event) {
				selected_item = $(".pk" + selection.value).siblings(".buy");
				
				if(lock && event.keyCode === 39) {
					selected_item.addClass("load");
					
					$.post("/api2/buyable/item/" + selection.value, {
						"deposit": "1"
					}, function(data, status) {
						selected_item.removeClass("load");
						
						if(status === "success") {
							selected_item.addClass("success");
							//TODO neuer kontostand wär schnaffte
						} else {
							selected_item.addClass("failure");
						}
						
						lock = false;
					});
				} else {
					lock = (event.keyCode === 18 && selection)
				}

				if(!lock)
					selected_item.removeClass("lock");
				else
					selected_item.addClass("lock");
				
				selected_item.removeClass("failure success");
			});

			search_input.removeAttr("disabled"); search_input.focus();
		} else {
			search_input.val("Fehler beim Laden der Daten...");
		}
	});
});