/**
 * Based on:
 * SUBMODAL v1.6
 * Used for displaying DHTML only popups instead of using buggy modal windows.
 *
 * By Subimage LLC
 * http://www.subimage.com
 *
 * Contributions by:
 * 	Eric Angel - tab index code
 * 	Scott - hiding/showing selects for IE users
 *	Todd Huss - inserting modal dynamically and anchor classes
 *
 * Up to date code can be found at http://submodal.googlecode.com
 */

// Popup code
var gPopupMask = null;
var gPopupContainer = null;
var gPopFrame = null;
var gReturnFunc;
var gPopupIsShown = false;
//var gDefaultPage = "/loading.html";
var gHideSelects = false;
var gReturnVal = null;

var gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");	

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
	document.onkeypress = keyDownHandler;
}

/**
 * Initializes popup code on load.	
 */
function initPopUp() {
	// Add the HTML to the body
	theBody = document.getElementsByTagName('BODY')[0];
	popmask = document.createElement('div');
	popmask.id = 'popupMask';
	popcont = document.createElement('div');
	popcont.id = 'popupContainer';
	popcont.innerHTML = '' +
		'<div id="popupInner">' +
			'<div id="popupTitleBar">' +
				'<div id="popupTitle">&nbsp;</div>' +
				'<div id="popupControls">' +
					'<input type="button" id="popCloseBox" onclick="hidePopWin(true);" value="close [X]" />' +
				'</div>' +
			'</div>' +
			'<table border="0" cellpadding="0" cellspacing="0">' +
				'<tr>' +
					'<td><div id="popupFrame"></div><div id="arrow" style="cursor:pointer; z-index:205; display:none; position:absolute; height:75px; width:75px;">&nbsp;</div></td>' +
				'</tr>' +
			'</table>' +
			'<div id="popupControlsBottom">' +
				'<table border="0" cellpadding="0" cellspacing="0" width="100%">' +
					'<tr>' +
						'<td width="100%">' +
							'<div title="" id="ImageDesc"></div>' +
						'</td>' +
						'<td>' +
							'<input id="popFullScreenBox" type="button" onclick="handleFullViewClick();" value="fullscreen" />' +
						'</td>' +
					'</tr>' +
				'</table>' +
			'</div>' +
		'</div>' +
		'';
	theBody.appendChild(popmask);
	theBody.appendChild(popcont);
	
	gPopupMask = $("popupMask");
	gPopupContainer = $("popupContainer");
	gPopFrame = $("popupFrame");	
	
	gPopFrame.innerHTML = 'Loading picture...';
	
	// check to see if this is IE version 6 or lower. hide select boxes if so
	// maybe they'll fix this in version 7?
	var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
		gHideSelects = true;
	}
	
	$('popCloseBox').onmouseover = function() { this.style.color = '#FF9C00'; }
	$('popCloseBox').onmouseout = function() { this.style.color = '#dedede'; }

	$('popFullScreenBox').onmouseover = function() { this.style.color = '#FF9C00'; }
	$('popFullScreenBox').onmouseout = function() { this.style.color = '#dedede'; }

}

(Prototype.Browser.IE) ? Event.observe(window, 'load',  initPopUp) : Event.observe(window, 'dom:loaded',  initPopUp);

var loadedPicIndx = null;

function navigateImage(direction) {
	hideArrow();
	var imgIndex = loadedPicIndx;
	(direction == 'next') ? imgIndex += 1 : imgIndex -= 1;
	if(imgIndex == -1) imgIndex = pf.imageData.images.length - 1;
	if(imgIndex == pf.imageData.images.length) imgIndex = 0;
	var nextPic = pf.imageData.images[imgIndex].path.replace('_S.jpg','_M.jpg').replace('small','medium');
	//nextPic = nextPic + '?dt=' + dt.getTime();
	//var d = new Date();
	var picM = null;
	picM = new Image();
	
	picM.onload = function() {
		width = picM.width;
		height = picM.height;
		centerPopWin(width, height);
		var titleBarHeight = parseInt($("popupTitleBar").offsetHeight, 10);
		gPopupContainer.style.width = width + "px";
		gPopupContainer.style.height = (height+titleBarHeight) + "px";
		setMaskSize();
		gPopFrame.style.width = parseInt($("popupTitleBar").offsetWidth, 10) + "px";
		gPopFrame.style.height = (height) + "px";
		gPopFrame.style.backgroundImage = 'url(' + nextPic + ')';
		$('ImageDesc').innerHTML = pf.imageData.images[imgIndex].comment;
	}
	picM.src = nextPic;
	
	loadedPicIndx = imgIndex;
}

function showArrow(event) {
	img_w = parseInt(gPopFrame.style.width);
	img_h = parseInt(gPopFrame.style.height);
	pos_x = event.offsetX ? (event.offsetX) : event.layerX - gPopFrame.offsetLeft;
	//pos_y = event.offsetY ? (event.offsetY) : event.layerY - gPopFrame.offsetTop;				
	arrow_area_w = (img_w / 100) * 25;
	//alert('x:' + pos_x + ' -> y:' + pos_y + ' -> w:' + img_w + ' -> h:' + img_h + ' -> arrow_area_w:' + arrow_area_w);
	if (pos_x <= arrow_area_w) {
		$('arrow').style.backgroundImage = 'url(/images/pfeil_links.png)';
		$('arrow').style.top = (img_h/2)-(75/2) + 'px';
		$('arrow').style.left = 0 + 'px';
		$('arrow').title = 'Show previous image';
		$('arrow').show();
	}
	else if (pos_x >= (img_w - arrow_area_w)) {
		$('arrow').style.backgroundImage = 'url(/images/pfeil_rechts.png)';
		$('arrow').style.top = (img_h/2)-(75/2) + 'px';
		$('arrow').style.left = (img_w-75) + 'px';
		$('arrow').title = 'Show next image';
		$('arrow').show();
	}
	else {
		$('arrow').style.backgroundImage = 'url(/images/pixel.gif)';
		$('arrow').hide();
	}
}

function hideArrow() {
	$('arrow').title = "";
	$('arrow').innerHTML = "&nbsp;";
	$('arrow').style.backgroundImage = 'url(/images/pixel.gif)';
	$('arrow').hide();
}

function addEvents() {
	Event.observe(gPopFrame, "mousemove", function(event) {
		showArrow(event);
	});
	Event.observe(gPopupMask, "mouseover", function(event) {
		hideArrow();
	});
	Event.observe($('arrow'), "click", function(event) {
		imgIsLoaded = false;
		if ($('arrow').style.backgroundImage.indexOf('/images/pfeil_rechts.png') != -1) {
			navigateImage('next');
		}
		else {
			navigateImage('prev');
		}
	});
}

var eventsAdded = false;

 /**
	* @argument width - int in pixels
	* @argument height - int in pixels
	* @argument url - url to display
	* @argument returnFunc - function to call when returning true from the window.
	* @argument showCloseBox - show the close box - default true
	*/
function showPopWin(url, width, height, returnFunc, showCloseBox, title, type, imgIndex) {
	loadedPicIndx = imgIndex;
	gPopFrame.style.backgroundImage = 'url(/images/pixel.gif)';
	gPopFrame.innerHTML = '';
	switch(type) {
		case "image":
			$('popFullScreenBox').show();
			var picM = null;
			picM = new Image();
			
			picM.onload = function() {
				width = picM.width;
				height = picM.height;
				var d = new Date();
				// show or hide the window close widget
				if (showCloseBox == null || showCloseBox == true) {
					$("popCloseBox").style.display = "block";
				} else {
					$("popCloseBox").style.display = "none";
				}
				$('ImageDesc').innerHTML = title;
				gPopupIsShown = true;
				disableTabIndexes();
				gPopupMask.style.display = "block";
				gPopupContainer.style.display = "block";
				// calculate where to place the window on screen
				centerPopWin(width, height);
				var titleBarHeight = parseInt($("popupTitleBar").offsetHeight, 10);
				gPopupContainer.style.width = width + "px";
				gPopupContainer.style.height = (height+titleBarHeight) + "px";
				setMaskSize();
				// need to set the width of the iframe to the title bar width because of the dropshadow
				// some oddness was occuring and causing the frame to poke outside the border in IE6
				gPopFrame.style.width = parseInt($("popupTitleBar").offsetWidth, 10) + "px";
				gPopFrame.style.height = (height) + "px";
				// browser cache hack
				url = url + '?dt=' + d.getTime();
				// set the url
				//gPopFrame.src = url;
				gPopFrame.style.backgroundRepeat = 'no-repeat';
				gPopFrame.style.backgroundPosition = '50% 50%';
				gPopFrame.style.backgroundImage = 'url(' + url + ')';
				gReturnFunc = returnFunc;
				// for IE
				if (gHideSelects == true) {
					hideSelectBoxes();
				}
				$("popupFrame").innerHTML = '';
				
				if(!eventsAdded) {
					addEvents();
					eventsAdded = true;
				}
				
			}
			picM.src = url;
		break;
		case "video":
			$('popFullScreenBox').hide();
			width = 1024;
			height = 576;
			var d = new Date();
			// show or hide the window close widget
			if (showCloseBox == null || showCloseBox == true) {
				$("popCloseBox").style.display = "block";
			} else {
				$("popCloseBox").style.display = "none";
			}
			$('ImageDesc').innerHTML = title;
			gPopupIsShown = true;
			disableTabIndexes();
			gPopupMask.style.display = "block";
			gPopupContainer.style.display = "block";
			// calculate where to place the window on screen
			centerPopWin(width, height);
			var titleBarHeight = parseInt($("popupTitleBar").offsetHeight, 10);
			gPopupContainer.style.width = width + "px";
			gPopupContainer.style.height = (height+titleBarHeight) + "px";
			setMaskSize();
			// need to set the width of the iframe to the title bar width because of the dropshadow
			// some oddness was occuring and causing the frame to poke outside the border in IE6
			gPopFrame.style.width = parseInt($("popupTitleBar").offsetWidth, 10) + "px";
			gPopFrame.style.height = (height) + "px";
			// browser cache hack
			url = url + '?dt=' + d.getTime();
			// set the url
			//gPopFrame.src = url;
			//gPopFrame.style.backgroundRepeat = 'no-repeat';
			//gPopFrame.style.backgroundPosition = '50% 50%';
			//gPopFrame.style.backgroundImage = 'url(' + url + ')';
			gPopFrame.innerHTML = embedQuicktime(url, '1024', '576', 'bgcolor', '#f0f0f0', 'scale', 'tofit', 'controller', 'true');
			gReturnFunc = returnFunc;
			// for IE
			if (gHideSelects == true) {
				hideSelectBoxes();
			}
			//$("popupFrame").innerHTML = '';
		break;
	}
}

function handleFullViewClick() {
		var picL = null;
		picL = new Image();	
		
		$('imgFullDiv').style.color = '#FFFFFF';
		//$('imgFullDiv').style.backgroundImage = '';
		$('imgFullDiv').style.backgroundImage = 'url(/images/pixel.gif)';
		$('imgFullDiv').show();

		if (!picL.complete) {
			$('imgFullDiv').innerHTML = 'Loading full image...';
		}

		picL.onload = (function(){
			hidePopWin(true);
			$('imgFullDiv').innerHTML = '';
			$('imgFullDiv').style.backgroundImage = 'url(' + picL.src + ')';
			$('imgFullDiv').show();
        });
		
		picL.src = gPopFrame.style.backgroundImage.replace('url(','').replace(')','').replace('medium','large').replace('_M.jpg','_L.jpg').replace('http://localhost/', '').replace('"', '');
}

//
var gi = 0;
function centerPopWin(width, height) {
	if (gPopupIsShown == true) {
		if (width == null || isNaN(width)) {
			width = gPopupContainer.offsetWidth;
		}
		if (height == null) {
			height = gPopupContainer.offsetHeight;
		}
		
		//var theBody = document.documentElement;
		var theBody = document.getElementsByTagName("BODY")[0];
		//theBody.style.overflow = "hidden";
		var scTop = parseInt(document.viewport.getScrollOffsets().top,10);
		var scLeft = parseInt(theBody.scrollLeft,10);
		
		setMaskSize();
		
		//window.status = gPopupMask.style.top + " " + gPopupMask.style.left + " " + gi++;
		
		var titleBarHeight = parseInt($("popupTitleBar").offsetHeight, 10);

		var fullWidth = getViewportWidth();
		var fullHeight = getViewportHeight();
		
		gPopupContainer.style.top = (scTop + ((fullHeight - (height + titleBarHeight)) / 2)) + "px";
		gPopupContainer.style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
		//alert(fullWidth + " " + width + " " + gPopupContainer.style.left);
	}
}
Event.observe(window, 'resize',  centerPopWin);
Event.observe(window, 'scroll',  centerPopWin);

//window.onscroll = centerPopWin;

function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 

	return window.undefined; 
}
function getViewportWidth() {
	var offset = 17;
	var width = null;
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
}

/**
 * Sets the size of the popup mask.
 *
 */
function setMaskSize() {
	var theBody = document.getElementsByTagName("BODY")[0];
			
	var fullWidth = getViewportWidth();
	var fullHeight = getViewportHeight();
	
	// Determine what's bigger, scrollHeight or fullHeight / width
	if (fullHeight > theBody.scrollHeight) {
		popHeight = fullHeight;
	} else {
		popHeight = theBody.scrollHeight;
	}
	
	if (fullWidth > theBody.scrollWidth) {
		popWidth = fullWidth;
	} else {
		popWidth = theBody.scrollWidth;
	}
	
	gPopupMask.style.height = popHeight + "px";
	gPopupMask.style.width = popWidth + "px";
}

/**
 * @argument callReturnFunc - bool - determines if we call the return function specified
 * @argument returnVal - anything - return value 
 */
function hidePopWin(callReturnFunc) {
	gPopupIsShown = false;
	var theBody = document.getElementsByTagName("BODY")[0];
	theBody.style.overflow = "";
	restoreTabIndexes();
	if (gPopupMask == null) {
		return;
	}
	gPopupMask.style.display = "none";
	gPopupContainer.style.display = "none";
	if (callReturnFunc == true && gReturnFunc != null) {
		// Set the return code to run in a timeout.
		// Was having issues using with an Ajax.Request();
		gReturnVal = window.frames["popupFrame"].returnVal;
		window.setTimeout('gReturnFunc(gReturnVal);', 1);
	}
	//gPopFrame.src = gDefaultPage;
	// display all select boxes
	if (gHideSelects == true) {
		displaySelectBoxes();
	}
}

/**
 * Sets the popup title based on the title of the html document it contains.
 * Uses a timeout to keep checking until the title is valid.
 */

// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function keyDownHandler(e) {
    if (gPopupIsShown && e.keyCode == 9)  return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
function disableTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
}

// For IE. Restore tab-indexes.
function restoreTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = gTabIndexes[i];
				tagElements[k].tabEnabled = true;
				i++;
			}
		}
	}
}


/**
 * Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
 * IE has a problem with wanted select form tags to always be the topmost z-index or layer
 *
 * Thanks for the code Scott!
 */
function hideSelectBoxes() {
  var x = document.getElementsByTagName("SELECT");

  for (i=0;x && i < x.length; i++) {
    x[i].style.visibility = "hidden";
  }
}

/**
 * Makes all drop down form select boxes on the screen visible so they do not 
 * reappear after the dialog is closed.
 * 
 * IE has a problem with wanting select form tags to always be the 
 * topmost z-index or layer.
 */
function displaySelectBoxes() {
  var x = document.getElementsByTagName("SELECT");

  for (i=0;x && i < x.length; i++){
    x[i].style.visibility = "visible";
  }
}

/**
 * Insert embeded Quicktime movies
 * To embed a panorama just call one of these functions with 
 * additional pairs for additional paramameters f.e:
 * embedQuicktime('pano.mov','640','480','scale','tofit','background','#eeeeee');
*/
function embedQuicktime(sFile, sWidth, sHeight) {
	var tmp = '';
	tmp += '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"';
	tmp += '  codebase="http://www.apple.com/qtactivex/qtplugin.cab"';
	tmp += '  width="' + sWidth + '" height="' + sHeight + '" >';
	tmp += '  <param name="src" value="' + sFile + '">';
	for(i=3;i<arguments.length;i+=2) {
		tmp += '  <param name="' + arguments[i] + '" value="' + arguments[i+1] + '">';
	}
	tmp += '<embed width="' + sWidth + '" height="' + sHeight + '"';
	tmp += '	pluginspage="http://www.apple.com/quicktime/download/"';
	tmp += '	type="video/quicktime"';
	tmp += '	src="' + sFile + '"';
	for(i=3;i<arguments.length;i+=2) {
		tmp += '  ' + arguments[i] + '="' + arguments[i+1] + '"';
	}
	tmp += '	/>';
	tmp += '</object>';
	return tmp;
}
