/*
 * MODIFIED VERSION OF:
 * ^^^^^^^^^^^^^^^^^^^^
 * 
 * Thickbox 2.1 - jQuery plugin for displaying content in a box above the page
 * 
 * Copyright (c) 2006, 2007 Cody Lindley (http://www.codylindley.com)
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */
var TB_WIDTH;


$(document).ready( function() {
	// add thickbox to href elements that have a class of .thickbox
	$("a.thickbox, area.thickbox").click(function(event){
		// remove click border
		$(this).blur();
		
		// display the box for the elements href
		TB_show($(this));
		
		return false;
	});
});

// called when the user clicks on a thickbox link
function TB_show(linkNode) {
	var url = 		linkNode.attr("href");
	var caption =	linkNode.attr("title") || linkNode.attr("name") || linkNode.children("span.caption").text() || "";
	var rel = 		linkNode.attr("rel") || false;
	
	var prevLink = null;
	var nextLink = null;
	var countGroupLinks = 0;
	var imageCount = '';		// text that shows which image of how many pictures is shown (e.g. "1 / 23")
	
		
	// create iframe, overlay and box if non-existent
	if ( !$("#TB_HideSelect").length ) {
		$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
		$("#TB_overlay").click(TB_remove);
	}
	// TODO replace or check if event is already assigned
	//$(window).scroll(TB_position);
	
	// TODO replace
	TB_overlaySize();
	
	// TODO create loader only once, hide and show on demand
	$("body").append("<div id='TB_load'><img src='/_library/img/thickbox/loading.gif' /></div>");
	TB_load_position();
	
	// check if a query string is involved
	var baseURL = url.match(/(.+)?/)[1] || url;

	// regex to check if a href refers to an image
	var imageURL = /\.(jpe?g|png|gif|bmp)/gi;

	// check for images
	if ( baseURL.match(imageURL) ) {
		// if an image group is given
		if ( rel ) {
			// get the previous and next image
			countGroupLinks = $("a[@rel='" + rel + "']", linkNode.parent().parent()).length;
			var passedSelf = false;
			
			if(countGroupLinks > 0) {
				$("a[@rel='" + rel + "']", linkNode.parent().parent()).each( function(i) {
					if($(this).attr("href") != linkNode.attr("href")) {
						if(!passedSelf) {
							prevLink = $(this);
						} else if(passedSelf && nextLink == null) {
							nextLink = $(this);
						}
					} else {
						passedSelf = true;
						imageCount = (i+1) + ' / ' + countGroupLinks;
					}
				});
			}
		}
		
		imgPreloader = new Image();
		imgPreloader.onload = function() {
			imgPreloader.onload = null;

			// Resizing large images
			var pagesize = TB_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			// TODO don't use globals
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			
			// TODO empty window content instead
			//$("#TB_window").append("<a href='' id='TB_ImageOff' title='Schliessen'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + imageCount + prev.html + next.html + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Schliessen'>schliessen</a></div>");
			$("#TB_window").append("<img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' />" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'><a href='#' id='TB_closeWindowButton' title='Schliessen'>schliessen</a>" + imageCount + "&nbsp;</div></div>");
			
			// $("#TB_caption").width(imageWidth - 90);
			
			// add paging
			$("#TB_window").append('<div id="hoverNav" style="height:' + (imageHeight + 18) + 'px;"></div>'); 
			
			$("#TB_closeWindowButton").click(TB_remove);
			
			function buildClickHandler(linkNode) {
				return function() {
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					var url = 		linkNode.attr("href");
					var caption = 	linkNode.attr("title") || $(this).attr("name") || "";
					var rel = 		linkNode.attr("rel") || false;
					TB_show(linkNode, caption, url, rel);
					return false;
				};
			}
			var goPrev = buildClickHandler(prevLink);
			var goNext = buildClickHandler(nextLink);
			
			if ( prevLink != null ) {
				$("#hoverNav").append('<a href="#" id="TB_prev"></a>');
				$("#TB_prev").click(goPrev);
			}
			
			if ( nextLink != null) {		
				$("#hoverNav").append('<a href="#" id="TB_next"></a>');
				$("#TB_next").click(goNext);
			}
			
			// TODO use jQuery, maybe with event fix plugin, or just get the necessary parts of it
			document.onkeydown = function(e) {
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				switch(keycode) {
				// ESC
				case 27:
					TB_remove();
					break;
				// x
				case 88:
					TB_remove();
					break;
				case 190:
					if( next.html ) {
						document.onkeydown = null;
						goNext();
					}
					break;
				case 188:
					if( prev.html ) {
						document.onkeydown = null;
						goPrev();
					}
					break;
				}
			}
			
			// TODO don't remove loader etc., just hide and show later
			
			$("#TB_load").remove();
			$("#TB_ImageOff").click(TB_remove);
			
			// for safari using css instead of show
			// TODO is that necessary? can't test safari
			$("#TB_window").css({display:"block"});
			
			TB_position();
			TB_overlaySize();
			
			
		}
		imgPreloader.src = url;
		
	} else { //code to show html pages
		
		var queryString = url.match(/\?(.+)/)[1];
		var params = TB_parseQuery( queryString );
		
		TB_WIDTH = (params['width']*1) + 30;
		TB_HEIGHT = (params['height']*1) + 40;

		var ajaxContentW = TB_WIDTH - 30,
			ajaxContentH = TB_HEIGHT - 45;
		
		if(url.indexOf('TB_iframe') != -1){				
			urlNoQuery = url.split('TB_');		
			$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Schliessen'>schliessen</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' onload='TB_showIframe()'> </iframe>");
		} else {
			$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>schliessen</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
		}
				
		$("#TB_closeWindowButton").click(TB_remove);
		
			if(url.indexOf('TB_inline') != -1){	
				$("#TB_ajaxContent").html($('#' + params['inlineId']).html());
				TB_position();
				$("#TB_load").remove();
				$("#TB_window").css({display:"block"}); 
			}else if(url.indexOf('TB_iframe') != -1){
				TB_position();
				if(frames['TB_iframeContent'] == undefined){//be nice to safari
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"});
					$(document).keyup( function(e){ var key = e.keyCode; if(key == 27){TB_remove()} });
				}
			}else{
				$("#TB_ajaxContent").load(url, function(){
					TB_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				});
			}
		
	}
	
	$(window).resize(TB_position);
	$(window).resize(TB_overlaySize);
	
	document.onkeyup = function(e){ 	
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}
		 // close window
		if(keycode == 27 || keycode == 88){ // close
			TB_remove();
		}
	}
		
}

//helper functions below

function TB_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function TB_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_overlay").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast", function(){ $('#TB_window,#TB_overlay,#TB_HideSelect').remove(); });
	$("#TB_load").remove();
	return false;
}

function TB_position() {
	var pagesize = TB_getPageSize();	
	var arrayPageScroll = TB_getPageScrollTop();
	//var posY = (arrayPageScroll[1] + (pagesize[1]-TB_HEIGHT)/2);
	var offsetNavGlobal = $("#visualHead").offset();	// uses "dimensions.js"
	var posY = arrayPageScroll[1] + offsetNavGlobal.top;
	
	var style = {width: TB_WIDTH, left: (arrayPageScroll[0] + (pagesize[0] - TB_WIDTH)/2), top: posY};
	$("#TB_window").css(style);
}

function TB_overlaySize(){
	var w = $(document).innerWidth();
	
	var hDoc = $(document).innerHeight();
	var hWin = $(window).innerHeight();
	var h = (hDoc > hWin)? hDoc : hWin;
	if(document.documentElement && document.documentElement.offsetHeight) {
		var hDocEl = document.documentElement.offsetHeight;
		h = (hDocEl > h)? hDocEl : h;
	}
	if(document.documentElement && document.documentElement.scrollHeight) {
		var hDocEl = document.documentElement.scrollHeight;
		h = (hDocEl > h)? hDocEl : h;
	}
	
	// check if the image's bottom protrudes over the document body
	if(document.getElementById("TB_window")) {
		var offsetTBwindow = $("#TB_window").offset();	// uses "dimensions.js"
		var bottomTBwindow = offsetTBwindow.top + $("#TB_window").outerHeight();
	}
	
	h = (bottomTBwindow > h)? bottomTBwindow : h;
	
	$("#TB_overlay").css({"height": h, "width": w});
	$("#TB_HideSelect").css({"height": h,"width": w});
}

function TB_load_position() {
	var pagesize = TB_getPageSize();
	var arrayPageScroll = TB_getPageScrollTop();
	
	var offsetNavGlobal = $("#visualHead").offset();	// uses "dimensions.js"
	var posY = arrayPageScroll[1] + offsetNavGlobal.top + $("#visualHead").height()/2;
	
	$("#TB_load")
		.css({left: (arrayPageScroll[0] + (pagesize[0] - 100)/2), top: posY })
		.css({display:"block"});
}

function TB_parseQuery ( query ) {
	// return empty object
	if( !query )
		return {};
	var params = {};
	
	// parse query
	var pairs = query.split(/[;&]/);
	for ( var i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split('=');
		if ( !pair || pair.length != 2 )
			continue;
		// unescape both key and value, replace "+" with spaces in value
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
   }
   return params;
}


function TB_getPageScrollTop() {
	// here we use the jQuery plugin "dimensions"
	var yDoc = $(document).scrollTop();
	var xDoc = $(document).scrollLeft();
	
	var yWin = $(window).scrollTop();
	var xWin = $(window).scrollLeft();
	
	yScrolltop = (yDoc > yWin)? yDoc : yWin;
	xScrollleft = (xDoc > xWin)? xDoc : xWin;
	
	arrayPageScroll = new Array(xScrollleft,yScrolltop) 
	return arrayPageScroll;
}


function TB_getPageSize() {
	// here we use the jQuery plugin "dimensions"
	var w = $(document).innerWidth();
	
	var hDoc = $(document).innerHeight();
	var hWin = $(window).innerHeight();
	var h = (hDoc > hWin)? hDoc : hWin;
	
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
}