/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Adapted version by virtual identity AG
*/

var TB_PRELOAD_IMAGE = RESOURCES_PATH + "img/tb-loading-animation.gif";

var tb_layout = {
	htmlAddWidth:        0,
	htmlAddHeight:      53,
	imageAddWidth:       0,
	imageAddHeight:     53,
	iframeAddWidth:      0,
	iframeAddHeight:     0,
	minHeight:   350 - 150,
	minWidth:    965 - 150,
	paddingHorizontal: 150,
	paddingVertical:   150
}

var tb_snippet = {
	iframeHtml:
		'<p id="TB_caption">{$caption}</p><p id="TB_info">{$info}</p>\
		<p id="TB_closeWindow"><a href="#" id="TB_closeWindowButton">{$close}</a></p>\
		<iframe frameborder="0" hspace="0" src="{$src}" id="TB_iframeContent" name="TB_iframeContent{$uniqueId}" onload="tb_showIframe()" style="width: {$width}px; height:{$height}px;" > </iframe>',
	image:
		'<p id="TB_caption">{$caption}</p><p id="TB_info">{$info}</p>\
		<p id="TB_closeWindow"><a href="#" id="TB_closeWindowButton">{$close}</a></p>\
		<a href="#" id="TB_ImageOff" title="{$close}"><img id="TB_Image" src="{$src}" width="{$width}" height="{$height}" alt="{$caption}"/></a>',
	loader:
		'<div id="TB_load"><img src="{$src}" /></div>'
}

var TB_WIDTH, TB_HEIGHT;

//on page load call tb_init
$(document).ready(function(){
	tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
	imgLoader = new Image(); // preload image
	imgLoader.src = TB_PRELOAD_IMAGE;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function() {
		var caption = this.title || this.name || null;
		var url = this.href || this.alt;
		var imageGroup = this.rel || false;
		tb_show(caption, url, imageGroup);
		this.blur();
		return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	var layerController = LayerController.getInstance();
	layerController.closeCurrentLayer();

	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = tb_parseQuery(queryString);

	try {
		if (Info.browser.isIEpre7) {
			if (document.getElementById("TB_HideSelect") === null) { // iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		} else {
			if (document.getElementById("TB_overlay") === null) {
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}

		if (tb_detectMacXFF()) {
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack"); //use png overlay so hide flash
		} else {
			$("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity
		}

		caption = params["caption"] || caption || "";
		$("body").append(template(tb_snippet.loader, {src: imgLoader.src})); //add loader to the page
		$("#TB_load").show(); //show loader

		if (url.indexOf("?")!==-1) { //ff there is a query string involved
			var baseURL = url.substr(0, url.indexOf("?"));
		} else {
			var baseURL = url;
		}

		if (baseURL.toLowerCase().match(/\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/)) { // code to show images

			var TB_PrevCaption = "";
			var TB_PrevURL     = "";
			var TB_PrevHTML    = "";
			var TB_NextCaption = "";
			var TB_NextURL     = "";
			var TB_NextHTML    = "";
			var TB_imageCount  = "";
			var TB_FoundURL    = false;

			/* not in use yet
			if (imageGroup) {
				var TB_TempArray = $("a[@rel=" + imageGroup + "]").get();
				for (var i = 0; (i < TB_TempArray.length) && (TB_NextHTML === ""); ++i) {
					if (TB_TempArray[i].href != url) {
						if (TB_FoundURL) {
							TB_NextCaption = TB_TempArray[i].title;
							TB_NextURL     = TB_TempArray[i].href;
							TB_NextHTML    = template(tb_snippet.next, _.thickbox.next);
						} else {
							TB_PrevCaption = TB_TempArray[i].title;
							TB_PrevURL     = TB_TempArray[i].href;
							TB_PrevHTML    = template(tb_snippet.prev, _.thickbox.prev);
						}
					} else {
						TB_FoundURL = true;
						TB_imageCount = template(tb_snippet.imageCount(_.thickbox.image, i + 1, _.thickbox.of, TB_TempArray.length));
					}
				}
			}
			*/

			imgPreloader = new Image();
			imgPreloader.onload = function() {
				imgPreloader.onload = null;

				// Resizing large images - orginal by Christian Montoya edited by me.
				var pagesize = tb_getPageSize();
				var x = Math.max(pagesize[0] - tb_layout.paddingHorizontal, tb_layout.minWidth);
				var y = Math.max(pagesize[1] - tb_layout.paddingVertical,   tb_layout.minHeight);
				var imageWidth  = imgPreloader.width;
				var imageHeight = imgPreloader.height;
				if (imageWidth > x) {
					imageHeight = Math.round(imageHeight * x / imageWidth);
					imageWidth = x;
					if (imageHeight > y) {
						imageWidth = Math.round(imageWidth * y / imageHeight);
						imageHeight = y;
					}
				} else if (imageHeight > y) {
					imageWidth = Math.round(imageWidth * y / imageHeight);
					imageHeight = y;
					if (imageWidth > x) {
						imageHeight = Math.round(imageHeight * x / imageWidth);
						imageWidth = x;
					}
				}
				// End Resizing

				TB_WIDTH  = imageWidth  + tb_layout.htmlAddWidth;
				TB_HEIGHT = imageHeight + tb_layout.htmlAddHeight;

				var code = template(tb_snippet.image, {
					caption: caption,
					close: _.thickbox.close,
					height: imageHeight,
					info: TB_imageCount + TB_PrevHTML + TB_NextHTML,
					src: url,
					width: imageWidth
				});

				$("#TB_window").append(code);

				$("#TB_closeWindowButton").click(tb_remove);

				if (TB_PrevHTML !== "") {
					function goPrev() {
						if ($(document).unbind("click",goPrev)) {
							$(document).unbind("click",goPrev);
						}
						$("#TB_window").remove();
						$("body").append("<div id='TB_window'></div>");
						tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
						return false;
					}
					$("#TB_prev").click(goPrev);
				}

				if (!(TB_NextHTML === "")) {
					function goNext(){
						$("#TB_window").remove();
						$("body").append("<div id='TB_window'></div>");
						tb_show(TB_NextCaption, TB_NextURL, imageGroup);
						return false;
					}
					$("#TB_next").click(goNext);

				}

				document.onkeydown = function(e){
					keycode = (e) ? e.which : event.keyCode;

					if(keycode == 27) { // close
						tb_remove();
					} else if (keycode == 190 && TB_NextHTML != "") { // display previous image
						document.onkeydown = "";
						goNext();
					} else if (keycode == 188 && TB_PrevHTML != "") { // display next image
						document.onkeydown = "";
						goPrev();
					}
				};

				tb_position();
				$("#TB_load").remove();
				$("#TB_ImageOff").click(tb_remove);
				$("#TB_window").css("display", "block"); //for safari using css instead of show
			};

			imgPreloader.src = url;

		} else { // code to show html

			var info = params["info"] || "";

			TB_WIDTH      = parseInt(params['width']) + tb_layout.htmlAddWidth;
			TB_HEIGHT     = parseInt(params['height']) + tb_layout.htmlAddHeight;
			IFRAME_WIDTH  = parseInt(params['width']) + tb_layout.iframeAddWidth;
			IFRAME_HEIGHT = parseInt(params['height']) + tb_layout.iframeAddHeight;

			urlNoQuery = url.split('TB_');
			$("#TB_iframeContent").remove();
			if (params["modal"] != "true") { //iframe no modal

				var code = template(tb_snippet.iframeHtml, {
					caption: caption,
					close: _.thickbox.close,
					height: IFRAME_HEIGHT,
					id: Math.round(Math.random()*1000),
					info: info,
					src: urlNoQuery[0],
					width: IFRAME_WIDTH
				});

				$("#TB_window").append(code);
			}

			$("#TB_closeWindowButton").click(tb_remove);

			tb_position();
			if($.browser.safari){ //safari needs help because it will not fire iframe onload
				$("#TB_load").remove();
				$("#TB_window").css("display", "block");
			}
		}

		if(!params['modal']){
			document.onkeyup = function(e) {
				keycode = (e) ? e.which : event.keyCode;
				if (keycode == 27){ // close
					tb_remove();
				}
			};
		}

	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css("display", "block");
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
	$("#TB_window").css({marginLeft: '-' + Math.round(TB_WIDTH / 2) + 'px', width: TB_WIDTH + 'px', height: TB_HEIGHT + 'px'});
	if (!Info.browser.isIEpre7) {
		$("#TB_window").css({marginTop: '-' + Math.round(TB_HEIGHT / 2) + 'px'});
	}
	tb_appendShadow();
}

function tb_appendShadow() {
	if (tb_detectMacXFF()) {
		return;
	}
	var shadow = {
		TB_topLeft: {
		},
		TB_left: {
			height: (TB_HEIGHT - 17) + "px"
		},
		TB_topRight: {
			left: TB_WIDTH + "px",
			right: "auto"
		},
		TB_right: {
			height: (TB_HEIGHT - 17) + "px",
			left: TB_WIDTH + "px",
			right: "auto"
		},
		TB_bottomLeft: {
			bottom: "auto",
			top: TB_HEIGHT + "px"
		},
		TB_bottom: {
			bottom: "auto",
			top: TB_HEIGHT + "px",
			width: (TB_WIDTH - 8) + "px"
		},
		TB_bottomRight: {
			bottom: "auto",
			left: (TB_WIDTH - 4) + "px",
			right: "auto",
			top: TB_HEIGHT + "px"
		}
	}

	for(id in shadow) {
		$('<div id="' + id + '"></div>').css(shadow[id]).appendTo("#TB_window");
	}
}

function tb_parseQuery(query) {
	var params = {};
	if (query) {
		var pairs = query.split(/[;&]/);
		for (var i = 0, l = pairs.length; i < l ; ++i) {
			var keyVal = pairs[i].split('=');
			if (!keyVal || keyVal.length != 2) {
				continue;
			}
			var key = unescape(keyVal[0]);
			var val = unescape(keyVal[1]);
			// val = val.replace(/\+/g, ' ');
			params[key] = val;
		}
	}
	return params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
	return [w, h];
}

function tb_detectMacXFF() {
	var userAgent = navigator.userAgent.toLowerCase();
	if (/firefox[\/\s](\d+\.\d+)/.test(userAgent)) {
		var ffversion = new Number(RegExp.$1);
		if (ffversion < 3 && userAgent.indexOf('mac') != -1) {
			return true;
		}
	}
}

function template(s, params) {
	for(var key in params) {
		var reg = new RegExp("\\{\\$" + key + "\\}", "g")
		s = s.replace(reg, params[key]);
	}
	return s;
}
