/* This file is part of k4ever, a point-of-sale system
 *   Contact............  <k4ever@lists.someserver.de>
 *   Website............  http://k4ever.someserver.de/
 *   Bug tracker........  http://k4ever.someserver.de/report
 *
 * Licensed under GNU Affero General Public License v3 or later
 */

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];

	var buyItem = function(id, callback, options) {
		if(typeof options === "undefined") options = {};

		$.post("/api2/buyable/item/" + id, $.extend({
			"POSTDATA": "Y U NO CANT BE EMPTY"
		}, options), callback);
	};

	var updateBalance = function(newBalance) {
		var balanceString = $("span.balance").text().split(": ");
		balanceString[1] = parseFloat(newBalance).toFixed(2).replace(".", ",") + " €";

		$("span.balance").text(balanceString.join(": "));
	}

	$.extend($.gritter.options, {
		position: "bottom-right",
		fade_in_speed: 250,
		fade_out_speed: 500,
		time: 4000
	});

	$("a.buy").click(function(evt) {
		var button = $(this);
		evt.preventDefault();

		if(button.hasClass("locked"))
			return;

		dataContainer = button.parent();
		dataContainer.children().addClass("locked");

		var id = dataContainer.attr("data-id");
		var name = dataContainer.attr("data-name");
		var image = dataContainer.attr("data-image");
		var options = {};

		if(button.hasClass("inclDeposit")) {
			options.deposit = 2;
		} else if(button.hasClass("onlyDeposit")) {
			options.deposit = 1;
		}

		buyItem(id, function(data, status) {
			$.gritter.add({
				title: name + " gekauft",
				text: "Der Artikel wurde erfolgreich gebucht",
				image: image
			});

			dataContainer.children().removeClass("locked");
			updateBalance(data.balance);
		}, options);
	});

	$.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;

					$("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");

					buyItem(selection.value, function(data, status) {
						selected_item.removeClass("load");

						if(status === "success") {
							selected_item.addClass("success");
							updateBalance(data.balance);
						} 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...");
		}
	});
});
