var ItemPrice = {

	/**
	 * set some properties
	 */
	"unit_id": 0, 
	"unit_price": 0, 
	"unit_vat": 0, 
	"unit_price_vat": 0, 

	/**
	 * function clear()
	 *
	 *	remove any elements within defined element
	 */
	"clear": function(element) {
		var wrap = document.getElementById(element);
		while (wrap.hasChildNodes()) wrap.removeChild(wrap.lastChild);
	}, 

	/**
	 * function error()
	 *
	 * display error message
	 *
	 *	@param string $message "message to show"
	 */
	"error": function(message) {
		this.clear("error");

		var error_message = document.createElement("p");
		error_message.className = "msg_error";
		error_message.innerHTML = message;
		document.getElementById("error").appendChild(error_message);
	}, 

	/**
	 * function get_data()
	 *
	 *	get unit data by AJAX call
	 *
	 *	@param int $unit_id "desired unit ID"
	 */
	"get_data": function(unit_id) {
		this.unit_id = unit_id;
		$.ajax({url: "/inc/inc.item_price.php?unit_id=" + ItemPrice.unit_id, success: function(data) { ItemPrice.display_data(data); }, error: function() { TP.error("Při načítání informací o jednotce zboží se vyskytla chyba. Kontaktujte prosím správce obchodu."); }, cache: false});
	}, 

	/**
	 * function display_data()
	 *
	 *	display basic unit data
	 *
	 *	@param object data "XML data object"
	 */
	"display_data": function(data) {

		/**
		 * clear prices wrap, evaluate JSON data string and append payments
		 */
		this.clear("detail_discounts");
		var data = eval("(" + data + ")");

		/**
		 * append data into elements
		 */
		$("#availability").html(data.ammount_available ? "skladem: " + Math.round(data.ammount_available) : data.availability_text);
		$("#code").html(data.kod);
		$("#price").html(Math.round(data.price) + " Kč");
		$("#vat").html(Math.round(data.vat) + " Kč");
		$("#price_vat").html(Math.round(data.price_vat) + " Kč");
		$("#total_price").html(Math.round(data.total_price) + " Kč");
		$("#total_vat").html(Math.round(data.total_vat) + " Kč");
		$("#total_price_vat").html(Math.round(data.total_price_vat) + " Kč");
		$("#unit_id").val(data.id);
		$("#unit_name").html(data.jednotka);

		/**
		 * if there are some discounts, append them now
		 */
		if (data.discounts) {
			for (var i in data.discounts) {
			 	$("#detail_discounts").append("<p>" + data.discounts[i].nazev + " <em>(tato sleva není do výše uvedené ceny započítána)</em></p>");
			}
		}
	}
}


var TP = {

	/**
	 * set some properties...
	 */
	"transport_id": 0, 
	"payment_id": 0,
	"check_error": false, 

	/**
	 * function clear()
	 *
	 *	remove any elements within defined element
	 */
	"clear": function(element) {
		var wrap = document.getElementById(element);
		while (wrap.hasChildNodes()) wrap.removeChild(wrap.lastChild);
	}, 

	/**
	 * function error()
	 *
	 * display error message
	 *
	 *	@param string $message "message to show"
	 */
	"error": function(message) {
		this.clear("error");

		var error_message = document.createElement("p");
		error_message.className = "msg_error";
		error_message.innerHTML = message;
		document.getElementById("error").appendChild(error_message);
	}, 

	/**
	 * function set_transport()
	 *
	 *	set transport type, load payment types
	 *
	 *	@param int $transport_id "selected transport ID"
	 *	@param boolean $reset_payment	"reset payment ID?"
	 */
	"set_transport": function(transport_id, reset_payment) {

		/**
		 * clear payment types and display "loading" message
		 */
		this.clear("payment_content");
		var loading_message = document.createElement("p");
		loading_message.innerHTML = "Načítám způsoby plateb...";
		document.getElementById("payment_content").appendChild(loading_message);

		/**
		 * reset payment type?
		 */
		if (reset_payment == true) this.payment_id = 0;

		/**
		 * send request
		 */
		$.ajax({url: "/inc/inc.tp.php?type=transport&transport_id=" + transport_id + "&reset_payment=" + (reset_payment == true ? "yes" : "no"), success: function(data) { TP.build_payments(data); TP.transport_id = transport_id; }, error: function() { TP.error("Při načítání způsobů plateb se vyskytla chyba. Kontaktujte prosím správce obchodu."); }, cache: false});
	}, 

	/**
	 * function set_payment()
	 *
	 *	set payment type
	 *
	 *	@param int $payment_id "selected payment ID"
	 */
	"set_payment": function(payment_id) {

		/**
		 * send request
		 */
		$.ajax({url: "/inc/inc.tp.php?type=payment&payment_id=" + payment_id, success: function(data) { TP.payment_id = payment_id; }, error: function() { TP.error("Při výběru typu platby se vyskytla chyba. Kontaktujte prosím správce obchodu."); }, cache: false});
	}, 

	/**
	 * function build_payments()
	 *
	 *	build list of payment types
	 *
	 *	@param string $data "data represented as JSON string"
	 */
	"build_payments": function(data) {

		/**
		 * clear payment content, evaluate JSON data string and append payments
		 */
		this.clear("payment_content");
		var data = eval(data);

		/**
		 * go through data, create and append HTML contents
		 */
		for (var i in data) {
			var html_content = "<p>";
			html_content += "<input type=\"radio\" name=\"payment_type\" id=\"p_" + data[i].id + "\" value=\"" + data[i].id + "\" class=\"radio\" onclick=\"TP.set_payment(this.value);\"" + (this.payment_id == data[i].id ? " checked=\"checked\"" : "") + " />";
			html_content += "<label class=\"pointer\" for=\"p_" + data[i].id + "\">" + data[i].nazev + "</label>";
			if (data[i].popis != "") html_content += " <a href=\"/upresneni/platba/" + data[i].id + "/\" title=\"Informace o způsobu platby " + data[i].nazev + "\" class=\"fancybox_iframe\"><strong>?</strong></a>";

			switch (data[i].typ_poplatku) {
				case "castka":
					html_content += "<br /><em>" + (data[i].cena_dph == 0 ? "zdarma" : Math.round(data[i].cena_dph) + " Kč") + "</em>";
					break;

				case "procenta":
					html_content += "<br /><em>" + (Math.round(data[i].cena_procenta * 10) / 10) + "% z ceny nákupu</em>";
					break;
			}

			html_content += "</p>";

			$("#payment_content").append(html_content);
		}

		/**
		 * because fancybox searches for element when DOMready is fired, we must
		 * recall it here to be able to display descriptions in fancybox
		 */
		$(".fancybox_iframe").fancybox({width: 600, height: 400, padding: 15, overlayOpacity: "0.7", overlayColor: "#052043", titleShow: false, transitionIn: "none", transitionOut: "none", autoScale: false, type: "iframe"});
	}, 

	/**
	 * function check()
	 */
	"check": function() {
		this.check_error = false;

		/**
		 * check if transport and payment types were selected
		 */
		if (this.check_error == false && this.transport_id == 0) this.check_error = "Vyberte způsob dopravy.";
		if (this.check_error == false && this.payment_id == 0) this.check_error = "Vyberte způsob platby.";

		/**
		 * check transport/payment combination
		 */
		if (this.check_error == false) {
			$.ajax({url: "/inc/inc.tp.php?type=check", success: function(data) { TP.check_error = data == "ok" ? false : "Byla vybrána neplatná kombinace dopravy a platby."; }, error: function() { TP.check_error = "Při kontrole vybrané dopravy a platby se vyskytla chyba. Kontaktujte prosím správce obchodu."; }, cache: false});
		}

		/**
		 * display error and return false, if any
		 */
		if (this.check_error != false) {
			this.error(this.check_error);
			return false;
		}
	}
}


var NewsTicker = {

	/**
	 * set some properties...
	 */
	"ticking": null, 
	"current_id": null, 
	"current_index": null, 
	"available": [], 
	"timeout_animation": 500, 
	"timeout_tick": 5000, 

	/**
	 * function move()
	 *
	 *	manually move to next strip
	 *
	 * @param int $id (target strip ID)
	 */
	"move": function(id) {
	
		/**
		 * disable automatic ticking if running
		 */
		if (this.ticking != null) {
		 	clearTimeout(this.ticking);
		 	this.ticking = null;
		}

		/**
		 * tick
		 */
		this.tick(id);
	}, 

	/**
	 * function tick()
	 *
	 *	switch stripes with opacity animation
	 *
	 * @param int $id (target strip ID)
	 */
	"tick": function(id) {

		/**
		 * if something is displayed, hide it (we will set display to none for
		 * MSIE, in all other browsers we can use opacity animation)
		 */
		if (this.current_id != null && id != this.current_id) {
			if ("\v" == "v") {
				$("#nt_" + this.current_id).css("display", "none");
			} else {
				$("#nt_" + this.current_id).animate({opacity: 0}, this.timeout_animation);
			}
		}

		/**
		 * display selected strip, animate for non-MSIE browsers
		 */
		$("#nt_" + id).css("display", "block");
		if ("\v" != "v") $("#nt_" + id).animate({opacity: 1}, this.timeout_animation);

		/**
		 * set currently displayed strip to selected one
		 */
		this.current_id = id;
	}, 

	/**
	 * function autotick()
	 *
	 *	determine next item to display and automatically update
	 */
	"autotick": function() {

		/**
		 * determine key of next strip from array
		 */
		if (this.current_id != null) {
			this.current_index++;
			if (!this.available[this.current_index]) this.current_index = 1;
		} else {
			this.current_index = 1;
		}

		/**
		 * move to next strip
		 */
		this.move(this.available[this.current_index]);		

		/**
		 * call self, set autotick to true
		 */
		this.ticking = setTimeout("NewsTicker.autotick();", this.timeout_tick);
	}
}


var DailyOffer = {

	/**
	 * set some properties...
	 */
	"datetime_from": null, 
	"datetime_to": null, 
	"discount_start": null, 
	"discount_end": null, 
	"id": null, 
	"nazev": null, 
	"nazev_rewrite": null, 
	"vyrobce": null, 
	"popis1": null, 
	"unit_id": null, 
	"jednotka": null, 
	"cena": null, 
	"dph": null, 
	"cena_dph": null, 
	"cena_formatted": null, 
	"dph_formatted": null, 
	"cena_dph_formatted": null, 
	"image_id": null, 
	"image_file": null, 
	"hour_from": null, 
	"minute_from": null, 
	"second_from": null, 
	"hour_to": null, 
	"minute_to": null, 
	"second_to": null, 
	"type": null, 
	"discount": null,
	"ticking": null,  
	"d": null, 

	/**
	 * function construct()
	 *
	 *	construct HTML elements required to display product
	 */
	"construct": function() {
		switch (this.type) {

			/**
			 * discount on homepage
			 */
			case "homepage":
				$("#hp_daily_offer").append('<h2>Nabídka dne</h2><div class="homepage_product"><h3><a href="/detail/' + this.nazev_rewrite + '/" title="' + this.nazev + '">' + this.nazev + '</a></h3>' + (this.image_file == '' ? '' : '<a href="/detail/' + this.nazev_rewrite + '/" title="' + this.nazev + '" class="img"><img src="/images/cache/' + this.id + '/' + this.image_id + '/max/86/93/no/255-255-255/' + this.image_file + '" alt="' + this.nazev + '" /></a>') + '<p class="product_description">' + this.popis1 + '</p><p class="product_price"><strong>' + this.cena_dph_formatted + ',-</strong></p><p class="discount_actual">Aktuální sleva: <strong id="discount_actual"></strong></p><p class="discount_description">Neváhejte! Tato sleva se každou minutu zmenšuje. Čím dříve koupíte, tím větší slevu od nás dostanete!</p><form action="/" method="post"><fieldset><input type="hidden" name="product_id" value="' + this.id + '" /><input type="hidden" name="unit_id" value="' + this.unit_id + '" /><input type="hidden" name="unit_ammount" value="1" /><button type="submit" name="add_to_cart" class="unit_add"><span>Koupit</span></button></fieldset></form></div>');
				break;
		}

		/**
		 * set discount range, set seconds range, count ammount of percent for
		 * each second of the day
		 */
		this.discount_range = this.discount_end - this.discount_start;
		this.datetime_range = this.datetime_to - this.datetime_from;
		this.second_percent = this.discount_range / this.datetime_range;
		this.tick();
	}, 

	/**
	 * function destruct()
	 *
	 *	destruct product
	 */
	"destruct": function() {
		switch (this.type) {

			/**
			 * discount on homepage
			 */
			case "homepage":
				$("#hp_daily_offer").empty();
				break;
		}
	}, 

	/**
	 * function tick()
	 */
	"tick": function() {
		this.d = new Date();
		this.current_timestamp = this.d.getTime();
		this.spent_seconds = this.current_timestamp - this.datetime_from;

		/**
		 * compute discount 
		 */
		this.discount_add = this.spent_seconds * this.second_percent;
		this.discount = parseFloat(this.discount_start) + parseFloat(this.discount_add);
		this.discount = Math.round(this.discount * 1000) / 1000;

		/**
		 * show discount if higher than 0, else hide offer
		 */
		if ((parseFloat(this.discount_end) < parseFloat(this.discount_start) && parseFloat(this.discount) > parseFloat(this.discount_end)) || (parseFloat(this.discount_end) > parseFloat(this.discount_start) && parseFloat(this.discount) < parseFloat(this.discount_end))) {
			var discount_decimals = this.discount.toString().split(".")[1];
			if (discount_decimals.length == 2) this.discount = this.discount + "0";
			if (discount_decimals.length == 1) this.discount = this.discount + "00";
			if (discount_decimals.length == 0) this.discount = this.discount + ".000";

			$("#discount_actual").html(this.discount + "%");
			this.ticking = setTimeout("DailyOffer.tick()", 50);
		} else {
			clearTimeout(this.ticking);
			$("#hp_daily_offer").animate({opacity: 0, height: 0}, 1000, "linear", function() { $("#hp_daily_offer").empty(); });
		}
	}
}

/**
 * function delivery_address()
 *
 * show/hide delivery addres fields depending on whether checkbox is checked
 *
 * @param boolean $checked "checkbox checked status"
 */
function delivery_address(checked) {
	switch (checked) {
		case true:
			document.getElementById("delivery_address").style.display = "none";
			break;

		case false:
			document.getElementById("delivery_address").style.display = "block";
			break;
	}
}


/**
 * function manufacturers_selector()
 *
 * determine whether list of manufacturers is displayed or not and change
 *
 *	no params needed ;-)
 */
function manufacturers_selector() {

	/**
	 * switch display property, change link content
	 */
	switch ($("#manufacturers_list").css("display")) {
		case "block":
			$("#manufacturers_list").css("display", "none");
			$("#manufacturers_selector").html("vybrat výrobce");
			$("#manufacturers_selector").blur();
			break;

		case "none":
			$("#manufacturers_list").css("display", "block");
			$("#manufacturers_selector").html("schovat seznam výrobců");
			$("#manufacturers_selector").blur();
			break;
	}

	/**
	 * always return false
	 */
	return false;
}

