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
		 */
		clearTimeout(this.ticking);
		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(); });
		}
	}
}


var Discounts = {

	/**
	 * set some properties...
	 */
	"items": null,
	"d": null,
	"timestamp": null,
	"ticking": null,
	"visible_discounts": 0,

	/**
	 * function traverse()
	 *
	 *	basic loop through discounts
	 */
	"traverse": function() {
		this.d = new Date;
		this.timestamp = Math.round(this.d.getTime() / 1000);
		this.visible_discounts = 0;

		/**
		 * go through descounts
		 */
		for (var i in this.items) {

			/**
			 * timestamp is within discount range, optionally construct
			 */
			if (this.items[i].datetime_from <= this.timestamp && this.items[i].datetime_to >= this.timestamp) {
				this.visible_discounts++;
				if (!document.getElementById("homepage_discount_" + this.items[i].id)) $("#hp_discount_products").append('<div class="homepage_product" id="homepage_discount_' + this.items[i].id + '"><h3><a href="/detail/' + this.items[i].nazev_rewrite + '/" title="' + this.items[i].nazev + '">' + this.items[i].nazev + '</a></h3>' + (this.items[i].image_file == '' ? '' : '<a href="/detail/' + this.items[i].nazev_rewrite + '/" title="' + this.items[i].nazev + '" class="img"><img src="/images/cache/' + this.items[i].id + '/' + this.items[i].image_id + '/max/86/93/no/255-255-255/' + this.items[i].image_file + '" alt="' + this.items[i].nazev + '" /></a>') + '<p class="product_description">' + this.items[i].popis1 + '</p><p class="product_price"><strong>' + this.items[i].cena_dph_formatted + ',-</strong></p><form action="/" method="post"><fieldset><input type="hidden" name="product_id" value="' + this.items[i].id + '" /><input type="hidden" name="unit_id" value="' + this.items[i].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><p class="discount_percent">Sleva ' + this.items[i].discount_percent + '%</p><p class="discount_time">Sleva bude platit ještě<br /><span></span></p></div>');

				/**
				 * count how much days/hour/minutes/seconds the discount has left
				 */
				var r_seconds = this.items[i].datetime_to - this.timestamp;
				$("#homepage_discount_" + this.items[i].id + " p.discount_time span").html(this.format_time(r_seconds));

			/**
			 * timestamp is not within discount range, remove element
			 */
			} else {
				$("#homepage_discount_" + this.items[i].id).remove();
			}
		}

		/**
		 * insert heading if any discount is found and no heading exists yet
		 * if no discount is visible, remove heading		 
		 */
		if (this.visible_discounts > 0 && !document.getElementById("hpdp")) $("#hp_discount_products").prepend("<h2 id=\"hpdp\">Sleva</h2>");
		if (this.visible_discounts == 0) $("#hp_discount_products").empty();

		/**
		 * set timeout for traversing
		 */
		clearTimeout(this.ticking);
		this.ticking = setTimeout("Discounts.traverse()", 500);
	}, 

	/**
	 * function formatted_time()
	 *
	 *	create formatted time string from given ammount of seconds
	 */
	"format_time": function(r_seconds) {
		var string = "";

		// days
		var r_days = Math.floor(r_seconds / 86400);
		if (r_days > 0) {
			string += r_days + " ";
			if (r_days == 1) string += "den";
			if (r_days > 1 && r_days < 5) string += "dny";
			if (r_days > 4) string += "dnů";
			string += ", ";
		}
		r_seconds -= r_days * 86400;

		// hours
		var r_hours = Math.floor(r_seconds / 3600);
		if (r_hours > 0) {
			string += r_hours + " ";
			if (r_hours == 1) string += "hodinu";
			if (r_hours > 1 && r_hours < 5) string += "hodiny";
			if (r_hours == 0 || r_hours > 4) string += "hodin";
			string += ", ";
		}
		r_seconds -= r_hours * 3600;

		// minutes
		var r_minutes = Math.floor(r_seconds / 60);
		if (r_minutes > 0) {
			string += r_minutes + " ";
			if (r_minutes == 1) string += "minutu";
			if (r_minutes > 1 && r_minutes < 5) string += "minuty";
			if (r_minutes == 0 || r_minutes > 4) string += "minut";
			string += ", ";
		}
		r_seconds -= r_minutes * 60;

		// minutes
		string += r_seconds + " ";
		if (r_seconds == 1) string += "vteřinu";
		if (r_seconds > 1 && r_seconds < 5) string += "vteřiny";
		if (r_seconds == 0 || r_seconds > 4) string += "vteřin";

		return string;
	}
}


/**
 * 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;
	}
}


var B = {
	
	/**
	 * function create()
	 *
	 *	create and append overlay and banner
	 */
	"create": function() {

		// check referrer
		this.ref = document.referrer;
		if (this.ref.indexOf("beko.cz") == -1) {

			// create and append overlay
			this.overlay = document.createElement("div");
			this.overlay.id = "banner_overlay";
			this.overlay.style.position = "fixed";
			this.overlay.style.left = "0";
			this.overlay.style.top = "0";
			this.overlay.style.width = "100%";
			this.overlay.style.height = "100%";
			this.overlay.style.background = "#00529c";
			this.overlay.style.opacity = "0.5";
			this.overlay.style.filter = "alpha(opacity=50)";
			this.overlay.style.cursor = "pointer";
			this.overlay.style.zIndex = "1500";

			this.overlay.onclick = this.remove;

			$("body").append(this.overlay);

			// create and append banner
			this.wrap = document.createElement("div");
			this.wrap.id = "banner_wrap";
			this.wrap.style.position = "fixed";
			this.wrap.style.left = (($(window).width() / 2) - 363) + "px";
			this.wrap.style.top = (($(window).height() / 2) - 215) + "px";
			this.wrap.style.width = "727px";
			this.wrap.style.height = "429px";
			this.wrap.style.background = "#fff";
			this.wrap.style.border = "4px #fff solid";
			this.wrap.style.cursor = "pointer";
			this.wrap.style.zIndex = "1501";
			this.wrap.innerHTML = "<a href=\"/informace/vanocni-slosovani-vyhra/\"><img src=\"/images/vanoce_2011.jpg\" alt=\"\" /></a>";

			this.wrap.onclick = this.remove;

			$("body").append(this.wrap);
		}
	}, 

	/**
	 * function remove()
	 *
	 *	remove banner and overlay
	 */
	"remove": function() {
		$("#banner_wrap").remove();
		$("#banner_overlay").remove();
	}
}


/**
 * function extend_assurance()
 */
function extend_assurance(product_id, unit_id) {
	document.getElementById("ea_product_id").value = product_id;
	document.getElementById("ea_unit_id").value = unit_id;
	document.getElementById("extend_assurance_form").submit();
}
