/* Lightbox must be loaded */

var borderSize = 10;
var displayElement;
var caption = '';
var save_position = 0;

var Modalbox = Class.create();

Modalbox.prototype = {

	initialize: function()
	{
		this.updateLinkList();

		// Code inserts html at the bottom of the page that looks similar to this:
		//
		//	<div id="overlay"></div>
		//	<div id="modalbox">
		//		<div id="outerModalContainer">
		//			<div id="modalContainer">
		//				<!-- Here is the content -->
		//			</div>
		//		</div>
		//		<div id="modalDataContainer">
		//			<div id="modalData">
		//				<div id="modalDetails">
		//					<span id="captionModal"></span>
		//				</div>
		//				<div id="bottomNav">
		//					<a href="#" id="bottomNavClose">
		//						<img src="img/lightbox/close.gif">
		//					</a>
		//				</div>
		//			</div>
		//		</div>
		//	</div>


		var objBody = document.getElementsByTagName("body").item(0);

		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		objOverlay.style.display = 'none';
		objOverlay.onclick = function() { myModalbox.end();  }
		objBody.appendChild(objOverlay);

		var objModalbox = document.createElement("div");
		objModalbox.setAttribute('id','modalbox');
		objModalbox.style.display = 'none';
		objModalbox.onclick = function(e) {	// close Modalbox is user clicks shadow overlay
			if (!e) var e = window.event;
			var clickObj = Event.element(e).id;
			if ( clickObj == 'modalbox') {
				myModalbox.end();
			}
		};
		objBody.appendChild(objModalbox);

		var objOuterModalContainer = document.createElement("div");
		objOuterModalContainer.setAttribute('id','outerModalContainer');
		objModalbox.appendChild(objOuterModalContainer);
		Element.setWidth('outerModalContainer', 200);
		Element.setHeight('outerModalContainer', 200);

		var objModalContainer = document.createElement("div");
		objModalContainer.setAttribute('id','modalContainer');
		objOuterModalContainer.appendChild(objModalContainer);

		var objModalDataContainer = document.createElement("div");
		objModalDataContainer.setAttribute('id','modalDataContainer');
		objModalbox.appendChild(objModalDataContainer);

		var objModalData = document.createElement("div");
		objModalData.setAttribute('id','modalData');
		objModalDataContainer.appendChild(objModalData);

		var objModalDetails = document.createElement("div");
		objModalDetails.setAttribute('id','modalDetails');
		objModalData.appendChild(objModalDetails);

		var objCaptionModal = document.createElement("span");
		objCaptionModal.setAttribute('id','captionModal');
		objModalDetails.appendChild(objCaptionModal);

		var objBottomNav = document.createElement("div");
		objBottomNav.setAttribute('id','bottomNav');
		objModalData.appendChild(objBottomNav);

		var objBottomNavCloseLink = document.createElement("a");
		objBottomNavCloseLink.setAttribute('id','bottomNavClose');
		objBottomNavCloseLink.setAttribute('href','#');
		objBottomNavCloseLink.onclick = function() { myModalbox.end(); return false; }
		objBottomNav.appendChild(objBottomNavCloseLink);

		var objBottomNavCloseImage = document.createElement("img");
		objBottomNavCloseImage.setAttribute('src', fileBottomNavCloseImage);
		objBottomNavCloseLink.appendChild(objBottomNavCloseImage);
	},

	updateLinkList: function()
	{
		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');

		// loop through all anchor tags
		for (var i=0; i < anchors.length; i++)
		{
			var anchor = anchors[i];

			var relAttribute = String(anchor.getAttribute('rel'));

			// use the string.match() method to catch 'modalbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('modalbox')))
				anchor.onclick = function () { myModalbox.start(this); return false; }
		}
	},

	start: function(link)
	{	
		hideSelectBoxes();
		hideFlash();

		caption = '';

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setWidth('overlay', arrayPageSize[0]);
		Element.setHeight('overlay', arrayPageSize[1]);

		new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.8 });

		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName(link.tagName);

		if (link.getAttribute('rel') == 'modalbox')
		{
			var url = link.getAttribute('href');
			var urlElements = url.split('#');
			var el = urlElements[1];

			if (link.getAttribute('title') != null)
				caption = link.getAttribute('title');
		}

		// calculate top and left offset for the modalbox
		var arrayPageScroll = getPageScroll();
		var modalboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var modalboxLeft = arrayPageScroll[0];
		
		Element.setTop('modalbox', modalboxTop);
		Element.setLeft('modalbox', modalboxLeft);

		Element.show('modalbox');
		
		this.changeContent(el);
	},

	changeContent: function(el)
	{
		displayElement = "_"+el;

		Element.hide('modalDataContainer');

		if (navigator.appVersion.indexOf("MSIE")!=-1)
		{
			var elOuterHtml = $(el).outerHTML;
			var elHtml = elOuterHtml.replace(el, displayElement);
		}
		else
		{
			var elInnerHtml = document.getElementById(el).innerHTML;
			var elHtml = '<div id="'+displayElement+'" style="'+$(el).getAttribute('style')+'">'+elInnerHtml+'<img src="/clear.gif" id="posGif" width="1" height="1" /></div>';
		}

		// New Element ID
		//var content = elHtml.replace(el, displayElement);

		new Insertion.Top('modalContainer', elHtml);

		// Get height and width from content
		if (navigator.appVersion.indexOf("MSIE")!=-1)
		{
			var width = parseInt($(el).style.width);
			var height = parseInt($(el).style.height);
		}
		else
		{
			var dimensions = $(displayElement).getDimensions();
			var width = dimensions.width;
			var height = dimensions.height;
		}

		myModalbox.resizeModalContainer(width, height);
	},

	resizeModalContainer: function(width, height)
	{
		// get curren width and height
		this.widthCurrent = Element.getWidth('outerModalContainer');
		this.heightCurrent = Element.getHeight('outerModalContainer');

		// get new width and height
		var widthNew = (width  + (borderSize * 2));
		var heightNew = (height  + (borderSize * 2));
		
		// Falls Bilder existieren, soll der Container nach recht erweitert werden
		var images = $(displayElement).childElements();
		
		for (var i = 0; i < images.length; i++)
		{
			if (images[i].hasClassName('images'))
			{
				widthNew += 110;
				break;
			}
			
			// Bilder in zweiter Ebene suchen
			var images_e2 = images[i].childElements();
			for (var j = 0; j < images_e2.length; j++)
			{
				if (images_e2[j].hasClassName('images'))
				{
					widthNew += 110;
					break;
				}
			}
		}
		
		// Breite für Firefox erweitern, da scrollbalken sonst außerhalb angezeigt wird
		if (Prototype.Browser.Gecko) {
			$(displayElement).style.visible = false;
			$(displayElement).style.display = 'block';

			var testOffsetTop = Position.positionedOffset($('posGif'))[1];
			var testOffsetHeight = $(displayElement).getHeight();
			
			$(displayElement).style.display = 'none';
			
			if (testOffsetTop > testOffsetHeight)
			{
				widthNew = widthNew + 16;
			}
		}
		
		
		
		// scalars based on change from old to new
		this.xScale = ( widthNew / this.widthCurrent) * 100;
		this.yScale = ( heightNew / this.heightCurrent) * 100;

		// calculate size difference between new and old content, and resize if necessary
		wDiff = this.widthCurrent - widthNew;
		hDiff = this.heightCurrent - heightNew;

		if(!( hDiff == 0)){ new Effect.Scale('outerModalContainer', this.yScale, {scaleX: false, duration: 0.6, queue: 'front'}); }
		if(!( wDiff == 0)){ new Effect.Scale('outerModalContainer', this.xScale, {scaleY: false, delay: 0.6, duration: 0.6}); }

		// if new and old image are same size and no scaling transition is necessary,
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);}
		}

		Element.setWidth('modalDataContainer', widthNew);
		
		this.showContent();
	},

	showContent: function()
	{
		new Effect.Appear(displayElement, { duration: 0.6, queue: 'end', afterFinish: function(){ myModalbox.updateDetails(); } });
	},

	updateDetails: function()
	{
		this.updateImagesLinkList();
		
		// if caption is not null
		if(caption != ''){
			Element.show('captionModal');
			Element.setInnerHTML('captionModal', caption);
		}

		new Effect.Parallel(
			[ new Effect.SlideDown('modalDataContainer', { sync: true, duration: 0.6, from: 0.0, to: 1.0 }),
			  new Effect.Appear('modalDataContainer', { sync: true, duration: 0.6 }) ],
			{ duration: 0.6, afterFinish: function() {
				// update overlay size and update nav
				var arrayPageSize = getPageSize();
				Element.setHeight('overlay', arrayPageSize[1]);
				}
			}
		);
	},
	
	updateImagesLinkList: function()
	{
		//image_container = $('modalContainer').getElementsByClassName('images')[0];
		image_container = $$('#modalContainer .images')[0];
		var image_anchors = $('modalContainer').getElementsByTagName('A');
		preload_images = new Array();

		for (var i = 0; i < image_anchors.length; i++)
		{
			var anchor = image_anchors[i];

			var relAttribute = String(anchor.getAttribute('rel'));
			
			
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox')))
			{
				anchor.onclick = function () { myModalbox.showImage(this); return false; }
				
				// preload Image
				var pre_img = new Image();
				pre_img.src = anchor.getAttribute('href');
				
				preload_images[preload_images.length] = pre_img;
			}
		}
		
		
		// Buttons zum Scrollen hinzufügen, falls mehr Bilder existieren als angezeigt werden könne
		if (preload_images.length > 4)
		{
			var link_div = document.createElement('DIV');
			link_div.setAttribute('id', 'link_container');
			$('modalContainer').appendChild(link_div);
			
			var link_down = new Image();
			link_down.id = 'linkDown';
			link_down.src = 'typo3conf/ext/easytourist/img/down.jpg';
			link_down.onmouseover = function() { this.src = 'typo3conf/ext/easytourist/img/down_hover.jpg'; }
			link_down.onmouseout = function() { this.src = 'typo3conf/ext/easytourist/img/down.jpg'; }
			link_down.style.cursor = 'pointer';
			link_down.style.margin = '0 10px 0 0';
			link_down.style.display = 'none';
			link_down.onclick = function () { myModalbox.moveTo(image_container, 320); return false; }
			link_div.appendChild(link_down);
			
			var link_up = new Image();
			link_up.id = 'linkUp';
			link_up.src = 'typo3conf/ext/easytourist/img/up.jpg';
			link_up.onmouseover = function() { this.src = 'typo3conf/ext/easytourist/img/up_hover.jpg'; }
			link_up.onmouseout = function() { this.src = 'typo3conf/ext/easytourist/img/up.jpg'; }
			link_up.style.cursor = 'pointer';
			link_up.style.display = 'none';
			link_up.onclick = function () { myModalbox.moveTo(image_container, -320); return false; }
			link_div.appendChild(link_up);
			
			new Effect.Parallel([
			    new Effect.Appear('linkDown', {duration: 0.3}),
			    new Effect.Appear('linkUp', {duration: 0.3})
			], {duration: 0.5});
		}
	},
	
	showImage: function(link)
	{
		var title = link.getAttribute('title');
		var image = resizeImage(link.getAttribute('href'), 370, 420, preload_images);
		image.id = 'bigHotelImage';

		if ($('hotelimg') == null)
		{
			var imageLayer = document.createElement('div');
			imageLayer.setAttribute('id', 'hotelimg')
			imageLayer.setAttribute('class', 'imagelayer');
			imageLayer.style.display = 'none';
			$('modalContainer').appendChild(imageLayer);
			
			$('hotelimg').appendChild(image);
			
			new Effect.BlindRight('hotelimg', {duration: 0.3, scaleContent: false});
		}
		else if ($('hotelimg').style.display == 'none')
		{
			$('hotelimg').remove();
			
			var imageLayer = document.createElement('div');
			imageLayer.setAttribute('id', 'hotelimg')
			imageLayer.setAttribute('class', 'imagelayer');
			imageLayer.style.display = 'none';
			$('modalContainer').appendChild(imageLayer);
			
			$('hotelimg').appendChild(image);
			
			new Effect.BlindRight('hotelimg', {duration: 0.3, scaleContent: false});
		}
		else
		{
			var old_image = $('hotelimg').getElementsByTagName('IMG')[0];
			
			$(old_image).remove();
			
			image.style.display = 'none';
			$('hotelimg').appendChild(image);
		
			new Effect.Appear('bigHotelImage', {duration: 0.3});
		}
		
		if(title != '')
		{
			Element.hide('captionModal');
			Element.setInnerHTML('captionModal', title);
			new Effect.Appear('captionModal', {duration: 0.3});
		}
		else 
		{
			Element.setInnerHTML('captionModal', '');
		}
		
		var link_to_text = document.createElement('IMG');
		link_to_text.setAttribute('id', 'linkToText');
		link_to_text.src = 'typo3conf/ext/easytourist/img/to_text.jpg';
		link_to_text.onmouseover = function() { this.src = 'typo3conf/ext/easytourist/img/to_text_hover.jpg'; }
		link_to_text.onmouseout = function() { this.src = 'typo3conf/ext/easytourist/img/to_text.jpg'; }
		link_to_text.onclick = function() { myModalbox.hideImage(this); new Effect.Appear('linkToText', {duration: 0.3, from: 1, to: 0}); return false; }
		link_to_text.style.cursor = 'pointer';
		link_to_text.style.display = 'none';
		$('modalContainer').appendChild(link_to_text);
		new Effect.Appear('linkToText', {duration: 0.3});
	},
	
	hideImage: function(link)
	{
		if ($('hotelimg') != null)
		{
			new Effect.Appear('hotelimg', {duration: 0.3, from: 1, to: 0, 
				afterFinish: function() { $('hotelimg').style.display = 'none'; } });
		}
		
		Element.setInnerHTML('captionModal', '');
	},
	
	moveTo: function (container, y)
	{
		var last_image = $(image_container).getElementsByTagName('IMG')[preload_images.length-1];
		var last_image_offset = Position.positionedOffset($(last_image))[1];
		
		if ((last_image_offset > (save_position + y)) && ((save_position + y) >= 0))
		{
			save_position = save_position + y;
		
			Position.prepare();
			new Effect.Scroll(container, {x:0, y:save_position});
		}
		
		return false;
	},

	end: function()
	{
		Element.hide('modalbox');
		$(displayElement).remove();
		
		if ($('hotelimg') != null)
			$('hotelimg').remove();
		
		if ($('link_container') != null)
			$('link_container').remove();
		
		save_position = 0;
		
		Element.setInnerHTML('captionModal', '');
		
		new Effect.Fade('overlay', { duration: 0.2 });
		showSelectBoxes();
		showFlash();
	}

}


function initModalbox() { myModalbox = new Modalbox(); }
Event.observe(window, 'load', initModalbox, false);


function resizeImage(src, maxWidth, maxHeight, preload_images)
{
	var image = '';

	for (var i = 0; i < preload_images.length; i++)
	{
		if (src == preload_images[i].src || preload_images[i].src.indexOf(src) > 0)
		{
			image = preload_images[i];
		}
	}
	
	var scale_factor = image.width / image.height;

	if (image.width > maxWidth && image.height > maxHeight)
	{
		image.width = maxWidth;
		image.height = Math.round(image.width / scale_factor);
		
		if (image.height > maxHeight)
		{
			scale_factor = image.height / maxHeight;
			image.height = maxHeight;
			image.width = Math.round(image.width / scale_factor);
		}
	}
	else if (image.width > maxWidth && image.height <= maxHeight)
	{
		image.width = maxWidth;
	}
	else if (image.height > maxHeight && image.width <= maxWidth)
	{
		image.height = maxHeight;
	}
	
	return image;	
}