/*
	IOSPIRIT Gallery Script
	(C) 2009 by IOSPIRIT GmbH, Felix Schwarz
	All rights reserved.
	
	DO NOT COPY THIS SCRIPT OR USE IT ON YOUR WEBSITE.	
	THIS SCRIPT MAY NOT BE USED AT ANY WEBSITE OTHER THAN THE IOSPIRIT WEBSITE.
*/

/*
	Documentation:

	<!-- ######## the gallery object's size determines width and height of the total gallery.
		      Adding orientation="horizontalleft" presents thumbs on the left.
		      If startWithCaption is set (value currently ignored), the caption is displayed right from the start, otherwise only on mouseover.
		      If captionHideIntervalSeconds is set, captions are automatically hidden after captionHideIntervalSeconds seconds. Default value: 3 seconds.
 	-->
	<div class="gallery" style="width:600px; height: 460px; margin-top: 20px;" startWithCaption="true" captionHideIntervalSeconds="3.0">
		<div class="showroom">
			<div class="contentDiv"></div>
			<div class="contentDiv"></div>
		</div>
		<div class="controls">
			<div class="label">Images:</div>
			<!-- ######## Images are displayed as background-images. Right now gif, png, jpg and jpeg recognized as images -->
			<!-- ######## Anything you specify as title argument to the link will be shown as caption text inside the viewer -->
			<a href="downloadBoxBackground.png" class="button" title="This is displayed as caption text"></a>
			<!-- ######## thumbnailhref can point to a thumbnail that differs from href - the gallery script will automatically display it inside the button -->
			<a href="remoteBuddyLogo.png" thumbnailhref="remoteBuddyLogoMini.png" class="button"></a>
			<div class="label">QuickTime:</div>
			<!-- ######## Quicktime movies can be displayed as well. Right now mov, mp4 recognized as quicktime movies -->
			<a href="demo.mp4" thumbnailhref="demoVideoStillMini.png" class="button"></a>	
			<!-- ######## YouTube movies can be displayed as well. The controls are permanently visible. -->
			<div class="label">YouTube:</div>
			<a href="http://www.youtube.com/watch?v=abcdefghi" thumbnailhref="youtubevideomini.png" class="button"></a>
			<!-- ######## Vimeo movies can be displayed as well. The controls are only temporarily visible. -->
			<div class="label">Vimeo:</div>
			<a href="http://vimeo.com/1234567" thumbnailhref="vimeovideomini.png" class="button"></a>
		</div>
	</div>

*/


function setupGallery()
{
	var divs, i;
	
	divs = document.getElementsByTagName("div");
	
	for (i=0;i<divs.length;i++)
	{
		if (divs[i].className == "gallery")
		{
			var newGallery;
			
			newGallery = new Gallery(divs[i]);
		}
	}
}

function Gallery(galleryDivObj)
{
	var i, thisGallery = this;
	var anchorName; 

	// Store main gallery div obj
	this._galleryDivObj = galleryDivObj;

	// Initialize other vars
	this._transitionStartTime = 0;
	this._transitionTimer = 0;

	this._startWithoutCaption = true;
	this._alwaysDisplayCaptionOnImageChange = false;
	this._captionIsVisible = false;
	this._captionHideTimeIntervalInMilliseconds = 3000;
	
	this._initialAutoPlay = true;
	
	// Get caption options
	if (galleryDivObj.getAttribute('startWithCaption'))
	{
		this._startWithoutCaption = false;
		this._alwaysDisplayCaptionOnImageChange = true;
	}

	if (galleryDivObj.getAttribute('captionHideIntervalSeconds'))
	{
		this._captionHideTimeIntervalInMilliseconds = parseFloat(galleryDivObj.getAttribute('captionHideIntervalSeconds')) * 1000;
	}
	
	if (galleryDivObj.getAttribute("noInitialAutoPlay"))
	{
		this._initialAutoPlay = false;
	}
	
	// Find child divs
	for (i=0; i<this._galleryDivObj.childNodes.length; i++)
	{
		var childObj="", className="";
		
		try
		{
			childObj = this._galleryDivObj.childNodes[i];
			className = childObj.className;

			if (className)
			{
				if (className == "showroom")
				{
					this._showroomObj = childObj;
					this._containerWidth  = this._showroomObj.offsetWidth-2;
					this._containerHeight = this._showroomObj.offsetHeight-2;
				}

				if (className == "controls")
				{
					this._controlsObj = childObj;
				}
			}
		}
		catch(e)
		{
		}
	}
	
	if (this._showroomObj)
	{
		var divCnt=0;
	
		for (i=0; i<this._showroomObj.childNodes.length; i++)
		{
			var childObj="", className="";
			
			try
			{
				childObj = this._showroomObj.childNodes[i];
	
				if (childObj.className == "contentDiv")
				{
					if (divCnt == 0)
					{
						this._contentObj1 = childObj;
					}
					else
					{
						this._contentObj2 = childObj;
					}
				
					divCnt++;
				}
			}
			catch(e)
			{
			}
		}
	}

	// Install onclick handlers
	this._onclickHandler = function(event) { return (thisGallery.handleOnClick(this, event)); }

	this._activeContentObj = 0;
	this._activeButtonObj = 0;

	this._anchorNameObjectMap = new Object;

	if (this._controlsObj)
	{
		var divCnt=0, firstButton=0, fallbackButton=0;
		var hashName = 0;
		
		if (document.location.hash)
		{
			hashName = unescape(document.location.hash.substring(1));
		}
	
		for (i=0; i<this._controlsObj.childNodes.length; i++)
		{
			var childNode = this._controlsObj.childNodes[i];
			
			if (childNode.className == "button")
			{
				var thumbnailHref, nodeName;
			
				if (!fallbackButton)
				{
					fallbackButton = childNode;
				}

				if (anchorName = childNode.getAttribute("anchorname"))
				{
					this._anchorNameObjectMap[anchorName.toLowerCase()] = childNode;
				}
				
				if (!firstButton)
				{
					if (hashName)
					{
						if (anchorName)
						{
							if (anchorName == hashName)
							{
								firstButton = childNode; 
							}
						}
					}
					else
					{
						firstButton = childNode; 
					}
				}
				
				if (childNode.innerHTML.length == 0)
				{
					if (thumbnailHref = childNode.getAttribute("thumbnailhref"))
					{
						childNode.style.backgroundImage = "url('" + thumbnailHref + "')";
					}
					else
					{
						if (!childNode.style.backgroundImage)
						{
							childNode.style.backgroundImage = "url('" + childNode.href + "')";
						}
					}
				}
				
				childNode.onclick = this._onclickHandler;
			}
		}
		
		if (!firstButton)
		{
			firstButton = fallbackButton;
		}
		
		if (firstButton)
		{
			this.handleClickOnButton(firstButton, false);
		}
	}
	
	// Install "anchor click" handlers
	if (window.addEventListener)
	{
		document.addEventListener("click", function(event) { return (thisGallery.handleOnClick(thisGallery.findParentNodeWithTagName(event.target, "a"), event)); }, false);
	}
	else
	{
		document.attachEvent("onclick", function() { return (thisGallery.handleOnClick(thisGallery.findParentNodeWithTagName(event.srcElement, "a"), event)); });
	}
}

Gallery.prototype._galleryDivObj;
Gallery.prototype._showroomObj;
Gallery.prototype._contentObj1;
Gallery.prototype._contentObj2;
Gallery.prototype._controlsObj;
Gallery.prototype._onclickHandler;
Gallery.prototype._activeContentObj;
Gallery.prototype._activeButtonObj;
Gallery.prototype._initialAutoPlay;

Gallery.prototype._anchorNameObjectMap;

Gallery.prototype._containerWidth;
Gallery.prototype._containerHeight;

Gallery.prototype._transitionTimer;
Gallery.prototype._transitionStartTime;

Gallery.prototype._startWithoutCaption;
Gallery.prototype._alwaysDisplayCaptionOnImageChange;
Gallery.prototype._captionIsVisible;

Gallery.prototype._captionHideTimeIntervalInMilliseconds;

Gallery.prototype.findParentNodeWithTagName = function(inspectObj, tagName)
{
	while (inspectObj && (inspectObj.tagName != tagName.toUpperCase()))
	{
		inspectObj = inspectObj.parentNode;
	}
	
	return (inspectObj);
}

Gallery.prototype.handleOnClick = function(thisObj, event)
{
	if (thisObj)
	{
		if (thisObj.className == "button")
		{
			this.handleClickOnButton(thisObj, true);
			return (false);
		}
		else
		{
			if (thisObj = this.getButtonForAnchor(thisObj))
			{
				return (this.handleOnClick(thisObj, true));
			}
		}
	}
		
	return (true);
}

Gallery.prototype.handleClickOnButton = function(buttonObj, transition)
{
	var thisGallery = this;
	var targetSuffix = "", targetSuffixOffset = -1;
	var targetDivName = "", targetDivNameOffset = -1, targetDivObj = 0;
	var newHTMLCode = "", newCSSBackgroundCode="", newCaption = "";
	var loadFunction = 0;
	var autoPlay = true;
	
	// Change active state
	if (this._activeButtonObj)
	{
		if (this._activeButtonObj != buttonObj)
		{
			this._activeButtonObj.removeAttribute("selected");
		}
		else
		{
			return;
		}
	}

	this._activeButtonObj = buttonObj;
	buttonObj.setAttribute("selected", "yes");
	
	if (transition)
	{
		try
		{
			if (buttonObj.getAttribute("anchorname"))
			{
				document.location.hash = "#" + buttonObj.getAttribute("anchorname");
			}
		}
		catch(e)
		{
		}
	}
	else
	{
		autoPlay = this._initialAutoPlay;
	}
	
	if (autoPlay)
	{
		try
		{
			if (buttonObj.getAttribute("noautoplay"))
			{
				autoPlay = false;
			}
		}
		catch(e)
		{
		}
	}
	
	// Find out the file type and link type
	targetSuffixOffset = buttonObj.href.lastIndexOf(".");
	
	if (targetSuffixOffset != -1)
	{
		targetSuffix = buttonObj.href.substring(targetSuffixOffset+1, buttonObj.href.length);

		switch (targetSuffix.toLowerCase())
		{
			case "png":
			case "jpg":
			case "jpeg":
			case "gif":
				// newHTMLCode = '<img src="' + buttonObj.href + '">';
				
				if (buttonObj.title)
				{
					newCaption = buttonObj.title;
				}
				
				newCSSBackgroundCode = "url('"+ buttonObj.href +"')";
				
				loadFunction = 	function()
					       	{
					       		var newImage;
					       		
					       		newImage = new Image();
					       		newImage.onload = function()
					       				  {
										thisGallery.showNewContent(newCSSBackgroundCode, newHTMLCode, newCaption, transition);
					       				  }
					       		newImage.src = buttonObj.href;
					       	}
			break;
			
			case "mp4":
			case "mov":
				newHTMLCode = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="' + this._containerWidth + '" height="' + this._containerHeight + '"><param name="movie" value="' + buttonObj.href + '"><param name="src" value="' + buttonObj.href + '">' + (autoPlay ? '<param name="autoplay" value="true">' : '') + '<param name="controller" value="true"><param name="scale" value="tofit"> <embed width="' + this._containerWidth + '" height="' + this._containerHeight + '" src="' + buttonObj.href + '" pluginspage="http://www.apple.com/quicktime/download/" type="video/quicktime" controller="true" ' + (autoPlay ? 'autoplay="true" ' : '') + 'scale="tofit"></object>';
			break;
			
			default:
				targetDivNameOffset = buttonObj.href.lastIndexOf("#");
				
				if (targetDivNameOffset != -1)
				{
					targetDivName = buttonObj.href.substring(targetDivNameOffset+1, buttonObj.href.length);
					
					if (targetDivObj  = document.getElementById(targetDivName))
					{
						newCSSBackgroundCode = targetDivObj.style.backgroundImage;
						newHTMLCode = targetDivObj.innerHTML;
					}
				}
			break;
		}
	}
	
	if (!newHTMLCode.length && !newCSSBackgroundCode.length)
	{
		// Youtube
		if (buttonObj.href.indexOf("youtube.com") != -1)
		{
			var youTubeId, ytIDstartOffset, ytIDendOffset;
			
			ytIDstartOffset = buttonObj.href.indexOf("v=");
			
			if (ytIDstartOffset != -1)
			{
				ytIDstartOffset += 2;

				ytIDendOffset = buttonObj.href.indexOf("&", ytIDstartOffset);
				
				if (ytIDendOffset == -1)
				{
					ytIDendOffset = buttonObj.href.length;
				}
				
				youTubeId = buttonObj.href.substring(ytIDstartOffset, ytIDendOffset);
				
				newHTMLCode = '<iframe width="' + this._containerWidth + '" height="' + this._containerHeight + '" src="http://www.youtube.com/embed/' + youTubeId + '?rel=0&amp;hd=1' + (autoPlay ? '&amp:autoplay=1' : '') + '" frameborder="0" allowfullscreen></iframe>';
				
				/*
				newHTMLCode = '<object width="' + this._containerWidth + '" height="' + this._containerHeight + '"><param name="movie" value="http://www.youtube.com/v/' + youTubeId + '&fs=1&ap=%2526fmt%3D18' + (autoPlay ? '&autoplay=1' : '') + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + youTubeId + '&fs=1&ap=%2526fmt%3D18' + (autoPlay ? '&autoplay=1' : '') + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + this._containerWidth + '" height="' + this._containerHeight + '"></embed></object>';
				*/
			}
		}
	}
	
	if (!newHTMLCode.length && !newCSSBackgroundCode.length)
	{
		// Vimeo
		if (buttonObj.href.indexOf("vimeo.com") != -1)
		{
			var vimeoId, vmIDStartOffset;
			
			vmIDStartOffset = buttonObj.href.indexOf(".com/");
			
			if (vmIDStartOffset != -1)
			{
				vmIDStartOffset += 5;
				
				vimeoId = buttonObj.href.substring(vmIDStartOffset, buttonObj.href.length);
				
				newHTMLCode = '<object width="' + this._containerWidth + '" height="' + this._containerHeight + '"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + vimeoId + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1' + (autoPlay ? '&amp;autoplay=1' : '') + '" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=' + vimeoId + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1' + (autoPlay ? '&amp;autoplay=1' : '') + '" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + this._containerWidth + '" height="' + this._containerHeight + '"></embed></object>';	
				
			}
		}
	}
	
	if (!loadFunction)
	{
		this.showNewContent(newCSSBackgroundCode, newHTMLCode, newCaption, transition);
	}
	else
	{
		loadFunction();
	}
}

Gallery.prototype.showNewContent = function(newCSSBackgroundCode, newHTMLCode, newCaption, transition)
{
	var newContentObj, hideContentObj, newCaptionObj=0, hideCaptionObj=0;
	var thisGallery = this;
	var i;
	
	if (this._transitionTimer)
	{
		window.clearInterval(this._transitionTimer);
		this._transitionTimer = 0;
	}

	if (this._activeContentObj == this._contentObj1)
	{
		newContentObj  = this._contentObj2;
		hideContentObj = this._contentObj1;
	}
	else
	{
		newContentObj = this._contentObj1;
		hideContentObj = this._contentObj2;
	}

	newContentObj.style.opacity = "0";
	newContentObj.style.backgroundImage = newCSSBackgroundCode;
	newContentObj.innerHTML = newHTMLCode;
	newContentObj.style.display = "block";
	newContentObj.style.zIndex = 10;
	
	if (newCaption)
	{
		var newCaptionObj;
		
		newCaptionObj = document.createElement('div');
		newCaptionObj.setAttribute("class", "caption");
		newCaptionObj.setAttribute("id", "caption");
		newCaptionObj.innerHTML = newCaption;
		
		newContentObj.appendChild(newCaptionObj);
	}

	newContentObj.style.width = this._containerWidth + "px";
	newContentObj.style.height = this._containerHeight + "px";
	newContentObj.onmouseover = null;
	newContentObj.onmouseout = null;

	hideContentObj.style.zIndex = 0;
	hideContentObj.onmouseover = null;
	hideContentObj.onmouseout = null;
	
	/*
	for (i=0; i<newContentObj.childNodes.length; i++)
	{
		if (newContentObj.childNodes[i].id == "caption")
		{
			newCaptionObj = hideContentObj.childNodes[i];
		}
	}
	*/

	for (i=0; i<hideContentObj.childNodes.length; i++)
	{
		if (hideContentObj.childNodes[i].id == "caption")
		{
			hideCaptionObj = hideContentObj.childNodes[i];
		}
	}
	
	if (newCaptionObj)
	{
		if (this._startWithoutCaption)
		{
			newCaptionObj.style.opacity = "0";
			this._startWithoutCaption = false;
		}

		if (!this._captionIsVisible && !this._alwaysDisplayCaptionOnImageChange)
		{
			newCaptionObj.style.opacity = "0";
		}
		else
		{
			this._captionIsVisible = true;
		}
	}
	else
	{
		this._captionIsVisible = false;
	}

	if (transition)
	{
		this._transitionStartTime = new Date();
		this._transitionTimer = window.setInterval(function()
							   {
							   	var nowTime = new Date();
							   	var elapsedTime, opacityValue, animationEnded = false;
							   	
							   	elapsedTime = nowTime - thisGallery._transitionStartTime;
							   	
							   	opacityValue = elapsedTime / 250;
							   	
							   	if (opacityValue < 1.0)
							   	{
									newContentObj.style.opacity = opacityValue;
							   	}
							   	else
							   	{
									newContentObj.style.opacity = "1";
									
									hideContentObj.style.display = "none";
									hideContentObj.style.backgroundImage = "";
									hideContentObj.innerHTML = "";

									window.clearInterval(thisGallery._transitionTimer);
									thisGallery._transitionTimer = 0;
									
									if (newCaptionObj)
									{
										thisGallery.startCaptionTimer(newCaptionObj, true, thisGallery._captionHideTimeIntervalInMilliseconds);
									}
							   	}
							   }, 5);
	}
	else
	{
		newContentObj.style.opacity = "1";
		
		hideContentObj.style.display = "none";
		hideContentObj.style.backgroundImage = "";
		hideContentObj.innerHTML = "";
		
		if (newCaptionObj)
		{
			this.startCaptionTimer(newCaptionObj, true, thisGallery._captionHideTimeIntervalInMilliseconds);
		}
	}
	
	this._activeContentObj = newContentObj;
}

Gallery.prototype.startCaptionTimer = function(newCaptionObj, fadeOut, fadeOutBeginTime)
{
	var thisGallery = this, comingFromMouseOver = true;
	
	if (!fadeOut)
	{
		if (newCaptionObj.parentNode.onmouseover)
		{
			comingFromMouseOver = true;
		}
	
		newCaptionObj.parentNode.onmouseover = null;
		newCaptionObj.parentNode.onmouseout = null;
	}
	else
	{
		newCaptionObj.parentNode.onmouseover = null;
		newCaptionObj.parentNode.onmouseout = null;
	}

	if (thisGallery._transitionTimer)
	{
		window.clearInterval(thisGallery._transitionTimer);
		thisGallery._transitionTimer = 0;
	}

	if (newCaptionObj)
	{
		this._transitionStartTime = new Date();

		this._transitionTimer = window.setInterval(function()
							   {
								var nowTime = new Date();
								var elapsedTime, opacityValue, animationEnded = false;
									
								elapsedTime = nowTime - thisGallery._transitionStartTime;
								
								if (fadeOut)
								{
									if (parseFloat(newCaptionObj.style.opacity) != 0)
									{
										if (elapsedTime > fadeOutBeginTime)
										{
											opacityValue = 1.0 - ((elapsedTime - fadeOutBeginTime) / 500);
												
											if (opacityValue > 0)
											{
												newCaptionObj.style.opacity = opacityValue;
											}
											else
											{
												animationEnded = true;
											}
										}
									}
									else
									{
										animationEnded = true;
									}
									
									if (animationEnded)
									{
										newCaptionObj.style.opacity = "0";
										
										window.clearInterval(thisGallery._transitionTimer);
										thisGallery._transitionTimer = 0;
										
										newCaptionObj.parentNode.onmouseover = 	function()
															{
																thisGallery.startCaptionTimer(newCaptionObj, false, 0);
															};

										thisGallery._captionIsVisible = false;
									}
								}
								else
								{
									opacityValue = elapsedTime / 200;

									if (parseFloat(newCaptionObj.style.opacity) != 1)
									{
										if (opacityValue < 1.0)
										{
											newCaptionObj.style.opacity = opacityValue;
										}
										else
										{
											animationEnded = true;
										}
									}
									else
									{
										animationEnded = true;
									}
									
									if (animationEnded)
									{
										newCaptionObj.style.opacity = "1";

										window.clearInterval(thisGallery._transitionTimer);
										thisGallery._transitionTimer = 0;
										
										if (!comingFromMouseOver)
										{
											thisGallery.startCaptionTimer(newCaptionObj, true, thisGallery._captionHideTimeIntervalInMilliseconds);
										}
										else
										{
											newCaptionObj.parentNode.onmouseout  = function() { thisGallery.startCaptionTimer(newCaptionObj, true, (thisGallery._captionHideTimeIntervalInMilliseconds / 2.0));  }
										}

										thisGallery._captionIsVisible = true;
									}
								}
							     }, 5);
	}
}

Gallery.prototype.getButtonForAnchor = function (anchorObject)
{
	if (anchorObject.tagName == "A")
	{
		if (anchorObject.href)
		{
			var targetAnchorNameOffset, targetAnchorName;
		
			targetAnchorNameOffset = anchorObject.href.lastIndexOf("#");
			
			if (targetAnchorNameOffset != -1)
			{
				targetAnchorName = anchorObject.href.substring(targetAnchorNameOffset+1, anchorObject.href.length);

				try
				{
					if (this._anchorNameObjectMap[targetAnchorName])
					{
						return (this._anchorNameObjectMap[targetAnchorName]);
					}
				}
				catch(e)
				{
				}
			}
		}
	}
	
	return (0);
}

/*

Gallery.prototype.isMouseOverObject = function(object)
{
	if (object.getAttribute("mouseIsOverObject"))
	{
		return (object.getAttribute("mouseIsOverObject"));
	}

	return (false);
}

Gallery.prototype.handleMouseOverOut = function(object, isMouseOver)
{
	var callbackFunction;

	object.setAttribute("mouseIsOverObject", isMouseOver);

	if (isMouseOver)
	{
		if (callbackFunction = object.getAttribute("executeOnMouseOver"))
		{
			callbackFunction(object);
		}
	}
	else
	{
		if (callbackFunction = object.getAttribute("executeOnMouseOut"))
		{
			callbackFunction(object);
		}
	}
}
*/

