/**
 * Faktum reference lightbox
 */

function lightbox_contentChanged(callback) {
	// Recenter the lightbox content
	var lb = $("#lightbox");
	var container = $("#lightbox_container");
	var content = $("#lightbox_content");

	if (lb.length > 0 && content.length > 0 && container.length > 0) {
		var oldwidth = container.css("width");
		var oldheight = container.css("height");

		/*container
			.css("visibility", "hidden")
			.css("width", "auto")
			.css("height", "auto");*/

		// Width is dependant on the image... if the image exists.

		var firstimg = $("#lightbox_image img:first");
		var lastimg = $("#lightbox_image img:last");

		var width = $("#lightbox_image").width();
		if (lastimg.length > 0) {
			width = lastimg.width();
		}

		width += 320;

		$("#lightbox_description").css("width", (width) + "px");
		var height = $("#lightbox_image").height();
		var dh = $("#lightbox_description").height()
		if (dh > height) {
			$("#lightbox_image").css("position", "relative").css("top", ((dh - height) / 2).toString() + "px");
			height = dh;
		} else {
			$("#lightbox_description").height(height);
			$("#lightbox_image").css("top", "0");
		}

		container
			.css("width", oldwidth)
			.css("height", oldheight)
			.css("visibility", "visible");

		/*var img = $("#lightbox_image")

		if (img.length > 0) {
			img
				.css("width", firstimg.width()+"px")
				.css("height", firstimg.height()+"px")
				.animate({
					width: lastimg.width()+"px",
					height: lastimg.height()+"px"
				}, 500, "swing", function(){
					$(this)
						.css("width", "auto")
						.css("height", "auto");
				});
		}*/

		container
			.animate({
				left: (lb.width() / 2 - width / 2).toString() + "px",
				top: ((lb.height()) / 2 - height / 2).toString() + "px",
				width: (width.toString() + "px"),
				height: (height.toString() + "px")
			}, 500, "swing", callback);
	}
}

function lightbox_Load(id, lb, container, content) {
	// Show loading animation...
	var loader = $("<div id=\"lightbox_loader\"></div>");
	loader
		.prependTo(lb)
		.css("position", "absolute")
		.css("left", lb.width() / 2 - 18)
		.css("top", lb.height() / 2 - 18)

	$.get(
		_ROOT_PATH+_LANGUAGE+"/ajax/reference/"+id,
		function(data){
			// Have the data, don't show loading
			loader.hide();

			var obj;
			// Don't know if this is the right solution for processing
			// JSON data, but it seems, that even if "json" type gets
			// specified to jQuery, it does not do this for us. So
			// it is needed to be able to access the data.
			eval("obj = "+data);

			// Create the lightbox content.

			// First is the image.
			$("<div />")
				.appendTo(content)
				.attr("id", "lightbox_image")
				.css("position", "relative");
				//.css("overflow", "hidden");

			var desc = $("<div />")
				.attr("id", "lightbox_description")
				.css("position", "relative")
				.appendTo(content);
			desc = $("<div />")
					.attr("class", "desc")
					.appendTo(desc);

			// Show the details
			$("<h3>"+obj["Reference"]["Reference"]["project_"+_LANGUAGE]+"</h3>").appendTo(desc);

			$("<div class=\"referenceMeta clear\"></div>")
				.append("<strong>"+obj["TxtClient"]+":</strong> "+obj["Reference"]["Client"]["name"]+"&nbsp;<br />")
				.append("<strong>"+obj["TxtYear"]+":</strong> "+obj["Reference"]["Reference"]["year"]+"&nbsp;<br /><br />")
				.append(obj["Reference"]["Reference"]["range_"+_LANGUAGE]+"&nbsp;<br />")
				.append(obj["Reference"]["Reference"]["description_"+_LANGUAGE]+"<br />")
				.appendTo(desc);

			$("<div class=\"clear\"></div>").appendTo(desc);

			var btm = $("<div class=\"bottom\"></div>").appendTo(desc);

			// Then the gallery
			var gallery = $("<ul class=\"referenceGallery\"></ul>");
			for (var X = 0; X < obj["ReferenceGallery"].length; X++) {
				$("<li></li>")
					.append(
						$("<img />")
							.attr("src", _ROOT_PATH+"img/upload/"+obj["ReferenceGallery"][X]["ReferenceGallery"]["image_small"])
							.data("large", _ROOT_PATH+"img/upload/"+obj["ReferenceGallery"][X]["ReferenceGallery"]["image_large"])
							.click(function(){
								loader.show();
								$("<img />")
									.hide()
									.load(function(){
										loader.hide()

										// Show last image
										var old_image = $("#lightbox_image img");
										var new_image = $(this);

										if (old_image.length > 0) {
											// Resize lightbox to the new image
											new_image
												.css("visiblity", "hidden")
												.css("position", "absolute")
												.css("left", "0")
												.css("top", "0")
												.css("z-index", "1")
												.show()
												.appendTo($("#lightbox_image"));

											$("#lightbox_image")
												.css("width", new_image.width()+"px")
												.css("height", new_image.height()+"px");

											// Fade out old image
											old_image
												//.show()
												.fadeOut(function(){
													// Remove the image
													old_image.remove();
												});

											// Fade in new image
											new_image
												.hide()
												.css("visibility", "visible")
												.fadeIn(function(){
													//$(this).css("position", "static")
													//lightbox_contentChanged();
												});

											lightbox_contentChanged();

										} else {
											new_image
												.appendTo($("#lightbox_image"))
												.css("z-index", "1")
												.css("position", "absolute")
												.css("left", "0")
												.css("top", "0")
												.show();

											$("#lightbox_image")
												.css("width", new_image.width()+"px")
												.css("height", new_image.height()+"px");

											lightbox_contentChanged();
										}
									})
									.error(function(){
										loader.hide()
									})
									.attr("src", $(this).data("large"));
							})
					)
					.appendTo(gallery);
			}
			gallery.appendTo(btm);

			$("<div class=\"clear\"></div>").appendTo(btm);

			var nextid = (obj["PreviousReference"]?obj["PreviousReference"]["Reference"]["id"]:false);
			var previd = (obj["NextReference"]?obj["NextReference"]["Reference"]["id"]:false);

			// Try to find matching a.

			$(".references li").each(function(){
				var a = $($("a", this).get(0));
				if (a.length > 0) {
					if (a.data("myid") == id) {
						nextid = a.data("nextid");
						previd = a.data("previd");
					}
				}
			});

			// Links to previous and next project
			$("<div class=\"prevReference\"></div>")
				.append(
					(previd)?
					$("<a href=\""+_ROOT_PATH+_LANGUAGE+"/reference/"+previd+"\">&nbsp;</a>")
						.click(function(){
							lightbox_Show(previd, lightbox_Load);
							return false;
						}):
					""
				)
				.appendTo(btm);

			$("<div class=\"nextReference\"></div>")
				.append(
					(nextid)?
					$("<a href=\""+_ROOT_PATH+_LANGUAGE+"/reference/"+nextid+"\">&nbsp;</a>")
						.click(function(){
							lightbox_Show(nextid, lightbox_Load);
							return false;
						}
					):
					""
				)
				.appendTo(btm);

			$("<div id=\"lightbox_close\"></div>")
				.click(function(){ lb.click() })
				.appendTo(btm);

			$("<div class=\"clear\"></div>").appendTo(btm);

			// Show first image
			content.fadeIn();
			var img = $("li img", gallery).get(0);
			if (img) {
				$(img).click();
			} else {
				lightbox_contentChanged();
			}
		},
		"json"
	);
}

function lightbox_LoadNews(id, lb, container, content) {
	// Show loading animation...
	var loader = $("<div id=\"lightbox_loader\"></div>");
	loader
		.prependTo(lb)
		.css("position", "absolute")
		.css("left", lb.width() / 2 - 18)
		.css("top", lb.height() / 2 - 18)

	$.get(
		_ROOT_PATH+_LANGUAGE+"/ajax/news/"+id,
		function(data){
			// Have the data, don't show loading
			loader.hide();

			var obj;
			// Don't know if this is the right solution for processing
			// JSON data, but it seems, that even if "json" type gets
			// specified to jQuery, it does not do this for us. So
			// it is needed to be able to access the data.
			eval("obj = "+data);

			var c = $("<div />").attr("id", "lightbox_description").appendTo(content);
			c = $("<div />").attr("class", "desc").appendTo(c);

//			c.html("<div class=\"news\"><h2>"+obj["News"]["created"]+"</h2>"+obj["News"]["longtext"]+"</div>");
			c.html("<div class=\"news\">"+obj["News"]["longtext"]+"</div>");

			$("<div id=\"lightbox_close\"></div>")
				.click(function(){ lb.click() })
				.appendTo(c);

			$("<div class=\"clear\"></div>").appendTo(c);

			lightbox_contentChanged();
		}
	);
}

function lightbox_LoadNewsEx(id, lb, container, content) {
	// Show loading animation...
	var loader = $("<div id=\"lightbox_loader\"></div>");
	loader
		.prependTo(lb)
		.css("position", "absolute")
		.css("left", lb.width() / 2 - 18)
		.css("top", lb.height() / 2 - 18)

	$.get(
		_ROOT_PATH+_LANGUAGE+"/ajax/news/"+id,
		function(data){
			// Have the data, don't show loading
			loader.hide();

			var obj;
			// Don't know if this is the right solution for processing
			// JSON data, but it seems, that even if "json" type gets
			// specified to jQuery, it does not do this for us. So
			// it is needed to be able to access the data.
			eval("obj = "+data);

			// Create the lightbox content.

			// First is the image.
			$("<div />")
				.appendTo(content)
				.attr("id", "lightbox_image")
				.css("position", "relative");
				//.css("overflow", "hidden");

			var desc = $("<div />")
				.attr("id", "lightbox_description")
				.css("position", "relative")
				.appendTo(content);
			desc = $("<div />")
					.attr("class", "desc")
					.appendTo(desc);

			var btm = $("<div class=\"bottom\"></div>").appendTo(desc);

			// Then the gallery
			var gallery = $("<ul class=\"referenceGallery\"></ul>");
			for (var X = 0; X < obj["NewsGallery"].length; X++) {
				$("<li></li>")
					.append(
						$("<img />")
							.attr("src", _ROOT_PATH+"img/upload/"+obj["NewsGallery"][X]["NewsGallery"]["image_small"])
							.data("large", _ROOT_PATH+"img/upload/"+obj["NewsGallery"][X]["NewsGallery"]["image_large"])
							.click(function(){
								loader.show();
								$("<img />")
									.hide()
									.load(function(){
										loader.hide()

										// Show last image
										var old_image = $("#lightbox_image img");
										var new_image = $(this);

										if (old_image.length > 0) {
											/*old_image
												.hide()
												.css("position", "absolute")
												.css("left", "0")
												.css("right", "0")
												.css("z-index", "0");*/

											// Resize lightbox to the new image
											new_image
												.css("visiblity", "hidden")
												.css("position", "absolute")
												.css("left", "0")
												.css("top", "0")
												.css("z-index", "1")
												.show()
												.appendTo($("#lightbox_image"));

											$("#lightbox_image")
												.css("width", new_image.width()+"px")
												.css("height", new_image.height()+"px");

											// Fade out old image
											old_image
												//.show()
												.fadeOut(function(){
													// Remove the image
													old_image.remove();
												});

											// Fade in new image
											new_image
												.hide()
												.css("visibility", "visible")
												.fadeIn(function(){
													//$(this).css("position", "static")
													//lightbox_contentChanged();
												});

											lightbox_contentChanged();

										} else {
											new_image
												.appendTo($("#lightbox_image"))
												.css("z-index", "1")
												.css("position", "absolute")
												.css("left", "0")
												.css("top", "0")
												.show();

											$("#lightbox_image")
												.css("width", new_image.width()+"px")
												.css("height", new_image.height()+"px");

											lightbox_contentChanged();
										}
									})
									.error(function(){
										loader.hide()
									})
									.attr("src", $(this).data("large"));
							})
					)
					.appendTo(gallery);
			}
			gallery.appendTo(btm);

			// Show the details
//			$("<div class=\"news\"><h2>"+obj["News"]["created"]+"</h2>"+obj["News"]["longtext"]+"</div>").appendTo(desc);
			$("<div class=\"news\">"+obj["News"]["longtext"]+"</div>").appendTo(desc);

			$("<div class=\"clear\"></div>").appendTo(btm);

			$("<div id=\"lightbox_close\"></div>")
				.click(function(){ lb.click() })
				.appendTo(btm);

			$("<div class=\"clear\"></div>").appendTo(btm);

			btm.appendTo(desc);

			// Show first image
			content.fadeIn();
			var img = $("li img", gallery).get(0);
			if (img) {
				$(img).click();
			} else {
				lightbox_contentChanged();
			}
		},
		"json"
	);
}

function lightbox_Show(id, load_callback) {
	var lb = $("#lightbox");
	var container;
	var content;

	if (lb.size() == 0) {
		lb = $("<div></div>")
			.attr("id", "lightbox")
			.hide()
			.prependTo($("body"));

		// Close the lightbox when clicking it.
		lb.click(function(){
			lb.fadeOut(function(){
				lb.remove();
			});
		});

		container = $("<div></div>");
		container
			.attr("id", "lightbox_container")
			.html("<div></div>")
			.appendTo(lb)
			.css("position", "absolute")
			.css("width", "2px")
			.css("height", "2px")
			.css("left", (lb.width() / 2 - container.width() / 2).toString() + "px")
			.css("top", (lb.height() / 2 - container.height() / 2).toString() + "px");
			//.css("overflow", "hidden");

		container = $("div", container);

		// Create lightbox content
		content = $("<div></div>");
		content
			.attr("id", "lightbox_content")
			.appendTo(container)
			.click(function(e){
				// Stop propagation of the click event when content area
				// has been clicked.
				e.stopPropagation();
			});

		lb.fadeIn();
		load_callback(id, lb, container, content);
	} else {
		container = $("#lightbox_container");
		content = $("#lightbox_content");
		content.fadeOut(function(){
			content.html("");
			load_callback(id, lb, container, content);
		});
	}
}

var lightbox_goNextId = false;
var lightbox_goPrevId = false;

$(function(){
	// Install lightbox callbacks
	var previd = false;
	var prevelem = false;
	$(".references li").each(function(){
		var id = $($("a", this).get(0)).attr("href").match(/[0-9]+$/);

		if (prevelem) {
			prevelem.data("nextid", id);
		}

		$($("a", this).get(0))
			.data("previd", previd)
			.data("myid", id)
			.data("nextid", false);

		$(this).click(function(){
			if (id) {
				lightbox_Show(id, lightbox_Load);

				// Stop the default handler
				return false;
			} else {
				// Unabled to get ID of the reference, something is wrong
				// here. So stop and do nothing.
			}
		});

		previd = id;
		prevelem = $($("a", this).get(0));
	});

	$("#news .news_item.news a.longtext").click(function(){
		var id = $(this).attr("href").match(/[0-9]+$/);
		lightbox_Show(id, lightbox_LoadNewsEx);
		return false;
	});

	$("#news .news_item.reference a.longtext").click(function(){
		var id = $(this).attr("href").match(/[0-9]+$/);
		lightbox_Show(id, lightbox_Load);
		return false;
	});
});
