/**
 * Functions for displaying gallery pictures in a div popup
 */
function initGallery(anchors)
{
	var dim;
	var overlay = null;
	var imgDiv = null;
	var body;
	var details;
	var buttons;
	var text;
	var textArea;
	var textAreaVisible = false;
	var closeButton;
	var showText;
	var img;
	var currentIndex;
	var currentWidth;
	var currentHeight;
	var bottom = null;
	var visible = false;
	var showFile;
	var showTextArea;
	var toggleVisible;
	var title;
	var images = [];
	var goLeft;
	var goRight;
	var borders;
	
	var options = typeof GalleryOptions != "undefined" ? GalleryOptions : {};
	if (!options.buttonImagePrevious)
		options.buttonImagePrevious = common_resource_path + "images/gallery/prev.gif";
	if (!options.buttonImageNext)
		options.buttonImageNext = common_resource_path + "images/gallery/next.gif";
	if (!options.buttonImageClose)
		options.buttonImageClose = common_resource_path + "images/gallery/close.gif";
	if (!options.label)
		options.label = "%d van %d";
	if (!options.css)
		options.css = "css/gallery.css";
	if (!options.overlayColor)
		options.overlayColor = "black";
	if (!options.overlayOpacity)
		options.overlayOpacity = 40;
	
	var bottomHeight = 40;
	include(options.css);
	
	var getIndex = function(anchor)
	{
		if (typeof anchor.index != "undefined")
			return anchor.index;
		
		var i = 0;
		var found = false;
		while(i < anchors.length && !found)
		{
			if (anchors[i] == anchor)
				found = true;
			else
				i++;
		}
		
		return found ? i : -1;
	};
	
	var resize = function()
	{
		var dim = getScreenDimensions();
		overlay.style.top = dim.scrollTop + "px";
		overlay.style.left = dim.scrollLeft + "px";
		overlay.style.width = "100%";
		overlay.style.height = dim.availHeight + "px";
		overlay.style.zIndex = "300000";
		
		imgDiv.style.left = dim.scrollLeft + Math.floor((dim.availWidth - imgDiv.offsetWidth) / 2) + "px";
		imgDiv.style.top = dim.scrollTop + Math.floor((dim.availHeight - imgDiv.offsetHeight) / 2) + "px";
	};
	
	var fadeFromTo = function(obj, from, to, onDone)
	{
		var opacity = from;
		var handler = window.setInterval(function()
		{
			opacity -= from > to ? 10 : -10;
			if ((from > to && opacity <= to) || (from < to && opacity >= to))
			{
				opacity = to;
			}
				
			setOpacity(obj, opacity);
			if (opacity == to)
			{
				window.clearInterval(handler);
				if (onDone)
				{
					onDone();
				}
			}
		}, 40);
		return handler;
	};
	
	var hide = function()
	{
		fadeFromTo(overlay, options.overlayOpacity, 0, function()
		{
			body.removeChild(overlay);
		});
		imgDiv.parentNode.removeChild(imgDiv);
		window_detachEvent("onresize", resize);
		window_detachEvent("onscroll", resize);
		visible = false;
		textAreaVisible = false;
	};
	
	var resizeFromTo = function(w1, h1, w2, h2, onDone)
	{
		var w = w1;
		var h = h1;
		imgDiv.style.width = w  + "px";
		imgDiv.style.height = h + "px";

		var handler = window.setInterval(function()
		{
			w = w + (w2 > w1 ? Math.ceil((w2 - w)/2) : Math.floor((w2 - w)/2));
			h = h + (h2 > h1 ? Math.ceil((h2 - h)/2) : Math.floor((h2 - h)/2));
			if ((w2 > w1 && w > w2) || (w2 < w1 && w < w2))
				w = w2;
			if ((h2 > h1 && h > h2) || (h2 < h1 && h < h2))
				h = h2;
			
			imgDiv.style.width = w  + "px";
			imgDiv.style.height = h + "px";
			imgDiv.style.left = dim.scrollLeft + Math.floor((dim.availWidth - imgDiv.offsetWidth) / 2) + "px";
			imgDiv.style.top = dim.scrollTop + Math.floor((dim.availHeight - imgDiv.offsetHeight) / 2) + "px";
			
			if (w == w2 && h == h2)
			{
				window.clearInterval(handler);
				if (onDone)
					onDone();
			}
		}, 40);
	};
	
	var tempImage = document.createElement("img");
	var counter = 0;
	
	var fadeImage = function()
	{
		fadeFromTo(img, 0, 100);
	};

	var onloadImg = function()
	{
		img.detachEvent("onload", onloadImg);
		window.setTimeout(function()
		{
			fadeImage();
		}, 250);
	};
	
	var replaceImage = function()
	{
	};
	
	var updateButtons = function()
	{
		goLeft.style.display = currentIndex > 0 ? "" : "none";
		goRight.style.display = currentIndex < images.length - 1 ? "" : "none";
	};
	
	var previous = function()
	{
		if (currentIndex > 0)
		{
			if (textAreaVisible)
			{
				setOpacity(textArea, 0);
				textAreaVisible = false;
			}
	 		currentIndex--;
			showFile(images[currentIndex]);
			updateButtons();
		}
	};
	
	var next = function()
	{
		if (currentIndex < images.length - 1)
		{
			if (textAreaVisible)
			{
				setOpacity(textArea, 0);
				textAreaVisible = false;
			}
			currentIndex++;
			showFile(images[currentIndex]);
			updateButtons();
		}
	};
	
	var resizeButtons = function(width, height)
	{
		goLeft.style.width = Math.floor(width / 2) + "px";
		goLeft.style.height = height + "px";
		goRight.style.width = Math.floor(width / 2) + "px";
		goRight.style.height = height + "px";
		goRight.style.marginLeft = (width - Math.floor(width / 2) + 10) + "px";
	};
	
	var showImage = function(image, url, width, height)
	{
		if (visible)
		{
			var newImg = document.createElement("img");
			imgDiv.replaceChild(newImg, img);
			img = newImg;
			img.src = url;
			img.className = "gallery_img";
			
			if (width)
			{
				img.width = width;
			}
			
			if (height)
			{
				img.height = height;
			}
			
			if (width != currentWidth || height != currentHeight)
			{
				resizeButtons(width, height);
				setOpacity(details, 0);
				setOpacity(buttons, 0);
				img.style.display = "none";
				goLeft.style.display = "none";
				goRight.style.display = "none";
				resizeFromTo(currentWidth, currentHeight + bottomHeight, width, height + bottomHeight, function()
				{
					fadeFromTo(buttons, 0, 100);
					fadeFromTo(details, 0, 100);
					img.style.display = "";
					goLeft.style.display = "";
					goRight.style.display = "";
					setOpacity(img, 0);
					if (img.complete || img.readyState == "complete")
					{
						fadeImage();
					}
					else
					{
						img.attachEvent("onload", onloadImg);
					}
				});
				currentWidth = width;
				currentHeight = height;
			}
			else if (!img.loaded && img.readyState != "complete")
			{
				setOpacity(img, 0);
				img.attachEvent("onload", onloadImg);
			}
			
			/**
			 * reset text area height properties
			 */
			text.style.height = "auto";
			text.style.overflow = "hidden";
			
			/**
			 * add new text
			 */
			text.innerHTML = image.text;
			
			/**
			 * hide or show the "toon tekst" button
			 */
			if (text.innerHTML.length > 1)
			{
				showText.style.visibility = "visible";
			}
			else
			{
				showText.style.visibility = "hidden";
			}
			
			title.innerHTML = image.title;
			index.innerHTML = sprintf(options.label, currentIndex+1, images.length);
						
			return;
		}
		currentWidth = width;
		currentHeight = height;
		
		visible = true;
		
		overlay = document.createElement("div");
		overlay.style.overflow = "hidden";
		overlay.style.backgroundColor = options.overlayColor;
		overlay.style.position = "absolute";
		setOpacity(overlay, options.overlayOpacity);
		overlay.attachEvent("onclick", hide);
		
		body = document.getElementsByTagName("body")[0];
		body.appendChild(overlay);
		
		imgDiv = document.createElement("div");
		imgDiv.className = "smi_gallery";
		if (options.loadingImage)
		{
			imgDiv.style.backgroundImage = "url(" + options.loadingImage + ")";
		}
		
		img = document.createElement("img");
		img.src = url;
		img.className = "gallery_img";
		if (width)
		{
			img.width = width;
		}
		if (height)
		{
			img.height = height;
		}
		imgDiv.appendChild(img);
		
		window_attachEvent("onresize", resize);
		window_attachEvent("onscroll", resize);
		resize();
		
		bottom = document.createElement("div");
		bottom.className = "gallery_bottom";
		imgDiv.appendChild(bottom);
				
		// add details
		details = document.createElement("div");
		details.className = "gallery_details";
		bottom.appendChild(details);
		
		title = document.createElement("div");
		title.appendChild(document.createTextNode(image.title));
		title.className = "gallery_title";
		details.appendChild(title);
		
		// add text
		textArea = document.createElement("div");
		textArea.className = "gallery_text";
		bottom.appendChild(textArea);
		
		text = document.createElement("div");
		text.className = "inner_text";
		text.innerHTML = image.text;
		textArea.appendChild(text);
		
		closeButton = document.createElement("div");
		closeButton.appendChild(document.createTextNode("[X]"));
		closeButton.className = "gallery_close";
		textArea.appendChild(closeButton);
		closeButton.attachEvent("onclick", function()
		{
			toggleVisible(textArea, 90, false);
		});
		
		index = document.createElement("div");
		index.appendChild(document.createTextNode(sprintf(options.label, currentIndex+1, images.length)));
		details.appendChild(index);
		
		showText = document.createElement("div");
		var link = document.createElement("a");
		link.appendChild(document.createTextNode("Toon tekst"));
		showText.appendChild(link);
		showText.className = "gallery_showText";
		if (text.innerHTML.length <= 1)
		{
			showText.style.visibility = "hidden";
		}
		details.appendChild(showText);
		showText.attachEvent("onclick", showTextArea);
		
		// add buttons
		buttons = document.createElement("div");
		buttons.className = "gallery_buttons";
		bottom.appendChild(buttons);
		
		goLeft = document.createElement("div");
		goLeft.className = "gallery_button";
		goLeft.attachEvent("onclick", previous);
		goLeft.style.marginLeft = "-10px";
		goLeft.style.backgroundImage = "url(" + options.buttonImagePrevious + ")";
			
		var attachEvents = function(obj)
		{
			var handler = null;
			
			setOpacity(obj, 0);
			obj.attachEvent("onmouseover", function()
			{
				if (handler)
					clearTimeout(handler);
				
				handler = fadeFromTo(obj, 0, 100);
			});
			obj.attachEvent("onmouseout", function()
			{
				if (handler)
					clearTimeout(handler);
				
				handler = fadeFromTo(obj, 100, 0);
			});
		};
		attachEvents(goLeft);
		imgDiv.insertBefore(goLeft, img);
		
		var close = document.createElement("img");
		close.src = options.buttonImageClose;
		close.attachEvent("onclick", hide);
		close.style.cursor = "pointer";
		buttons.appendChild(close);
		
		goRight = document.createElement("div");
		goRight.className = "gallery_button";
		goRight.style.backgroundImage = "url(" + options.buttonImageNext + ")";
		goRight.style.backgroundPosition = "right 15%";
		goRight.attachEvent("onclick", next);
		attachEvents(goRight);
		
		resizeButtons(width, height);
		imgDiv.insertBefore(goRight, img);

		updateButtons();
		
		// finally resize into view
		imgDiv.style.width = "40px";
		imgDiv.style.height = "40px";
		body.appendChild(imgDiv);
		borders = getBorders(imgDiv);
		img.style.display = "none";
		setOpacity(details, 0);
		setOpacity(buttons, 0);
		
		resizeFromTo(40, 40, width, height + bottomHeight, function()
		{
			setOpacity(img, 0);
			img.style.display = "";
			fadeFromTo(buttons, 0, 100);
			fadeFromTo(details, 0, 100);
			if (img.complete || img.readyState == "complete")
			{
				fadeImage();
			}
			else
			{
				img.attachEvent("onload", onloadImg);
			}		
		});
	};
	
	showFile = function(anchor)
	{
		/**
		 * check if there are crop values in the href
		 */
		var crop = anchor.href.match(/(\d\.\d{1,20}|\d{1,20})(?!&|\d|\=|\/|\_)/g);
						
		var result = /cms_file\.php\?fromDB=([^&]+)(&|$)/.exec(anchor.href);
		var fileId = result ? result[1] : -1;
		
		currentIndex = getIndex(anchor);
		dim = getScreenDimensions();
		var image = images[currentIndex];
		
		getItem("item_tree_file", fileId, function(item)
		{
			var resolutions = [[1580, 1000], [1240, 880], [1000, 630], [780, 450], [780, 230]];
			var found = false;
			
			for(var i = 0; i < resolutions.length && !found; i++)
			{
				var res = resolutions[i];
				if (dim.availWidth >= res[0] && dim.availHeight - bottomHeight >= res[1])
				{
					found = res;
				}
			}
			
			if (!found)
			{
				found = resolutions[resolutions.length - 1];
			}
			
			var width = item.width || 4096;
			var height = item.height || 4096;
			var ratio = width / height;
			
			if (width > found[0])
			{
				width = found[0];
				height = Math.floor(width / ratio);
			}
			
			if (height > found[1])
			{
				height = found[1];
				width = Math.floor(ratio * height);
			}
			
			var url = "";
			if (options.useCropping && crop && crop.length >= 6)
			{
				var scaleX = Math.round(width / crop[2]);
				var scaleY = Math.round(height / crop[3]);
				var scale = Math.min(scaleX, scaleY);
				
				var cropWidth = crop[2] * scale;
				var cropHeight = crop[3] * scale;
				
				url = g_baseDir + "cms_file.php?fromDB=" + fileId + "&filter0=crop," + crop[0] + "," + crop[1] + "," + cropWidth + "," + cropHeight + "," + crop[4] + "," + crop[5];
				showImage(image, url, cropWidth, cropHeight);
			}
			else
			{
				url = g_baseDir + "cms_file.php?fromDB=" + fileId + "&maxWidth=" + found[0] + "&maxHeight=" + found[1];
				showImage(image, url, width, height);
			}
			
		});
	};
	
	var onclick = function(_e)
	{
		var e = _e || window.event;
		var target = e.target ? e.target : e.srcElement;
		cancelEvent(e);
		
		var anchor = target;
		while(anchor && anchor.nodeName != "A")
		{
			anchor = anchor.parentNode;
		}
		
		showFile(anchor);
		
		return false;
	};
	
	/**
	 * hide or show a object
	 */
	toggleVisible = function(obj, opacity, show)
	{
		if (!show)
		{
			setOpacity(obj, opacity);
			fadeFromTo(obj, opacity, 0, function()
			{
				obj.style.visibility = "hidden";
				
				if (obj == textArea)
				{
					/**
					 * reset text area height properties
					 */
					text.style.height = "auto";
					text.style.overflow = "hidden";
					
					textAreaVisible = false;
				}
			});
		}
		else if (show)
		{
			setOpacity(obj, 0);
			obj.style.visibility = "visible";
			fadeFromTo(obj, 0, opacity, function()
			{
				if (obj == textArea)
				{
					textAreaVisible = true;
				}
			});
		}
	}
	
	/**
	 * show the text area
	 */
	showTextArea = function()
	{
		if (!textAreaVisible && text.innerHTML.length > 1)
		{
			/**
			 * resize the textarea width to fit the image width
			 */
			textArea.style.width = (img.offsetWidth - 3) + "px";
			
			/**
			 * rescale the text area if it's height is greater then the height of the image
			 * and add a vertical scrollbar
			 */
			if (text.offsetHeight > img.offsetHeight)
			{
				text.style.height = (img.offsetHeight - 13) + "px";
				text.style.overflowX = "hidden";
				text.style.overflowY = "auto";
			}
			else
			{
				text.style.height = "auto";
				text.style.overflow = "hidden";
			}
			toggleVisible(textArea, 90, true);
		}
	}
	
	for(var i = 0; i < anchors.length; i++)
	{
		images[i] = {
			title: anchors[i].getAttribute("title"),
			text: anchors[i].getAttribute("text") ? anchors[i].getAttribute("text") : "",
			href: anchors[i].getAttribute("href"),
			index: i
		};
		anchors[i].attachEvent("onclick", onclick);
	}
}

