/*

	Version 0.5.1
	andcuriouser.com

	Based on Thickbox 2.1, (c) Cody Lindley / codylindley.com
	Modifications (c) Aaron Scott Hildebrandt / andcuriouser.com

	File detection routines (getID3) by James Heinrich / jamesheinrich.com
	ActiveX auto-activation by Gero Zahn / gerozahn.de
	Thanks to Mike Alsup / malsup.com for troubleshooting assistance

	Compressed with JS Minifier:
		http://fmarcia.info/jsmin/test.html

	Licensed under the MIT License:
		http://www.opensource.org/licenses/mit-license.php

	If you use this script (or a modification of it), please keep the above copyrights intact, as well as any copyrights in the included files.

*/




// on page load call tb_init
$(document).ready(tb_init);

lastClick = null;

// add thickbox to href elements that have a class of .thickbox
function tb_init(){
	$("a.thickbox").click(function(event){
		event.preventDefault();
		this.blur();
		var caption = this.title || this.name || null;
		var desc_id = this.id || null;
		var desc_html = "";
		if (!desc_id) {
			desc_id = "";
		} else {
			desc_id = desc_id + "_desc";
		}
		if(!caption) {
			caption = " &nbsp;";
		}
		group = this.rel || false;
		tb_show(caption, this.href, group,desc_id);
	});
}

// called when the user clicks on a thickbox link
function tb_show(caption, url, rel,desc_id) {
	
	var desc_html = "";
	var queryString = "";
	var params = "";

	if (document.getElementById(desc_id)) {
		desc_html = document.getElementById(desc_id).innerHTML;
	}

	if (url.indexOf("?") > 0) {
		queryString = url.match(/\?(.+)/)[1];
	}
	params = tb_parseQuery( queryString );

	if ( !$("#tb_overlay").length ) {
		$("body").append("<div id='tb_overlay'></div><div id='tb_window'></div>");
		$("#tb_overlay").css("opacity", 0.8).fadeIn("normal"); 
		if(params.blockclick != 1) {
			$("#tb_overlay").click(tb_remove);
		}
	} // if

	$(window).scroll(tb_position);
	tb_overlaySize();
	
	$("body").append("<div id='tb_load'><img src='/templates/custom/flugtag-2/template_images/loadingAnimation.gif' /></div>");
	tb_load_position();
	$("#tb_load").fadeIn("fast");
	
	// check if a query string is involved
	var baseURL = url.match(/(.+)?/)[1] || url;

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

	var dummy = { caption: "", url: "", html: "", desc:""};

	prev = dummy;
	next = dummy;
	imageCount = "";
		
	// if an image group is given
	if ( rel ) {
		function getInfo(image, id, label) {
			return {
				caption: image.title,
				url: image.href,
				html: "<span id='tb_" + id + "'>&nbsp;&nbsp;<a href='#'>" + label + "</a></span>"
			};
		} // getInfo()
	
		// find the anchors that point to the group
		var imageGroup = $("a[@rel="+rel+"]").get();
		var foundSelf = false;
		// loop through the anchors, looking for ourself, saving information about previous and next image
		for (var i = 0; i < imageGroup.length; i++) {

			var image = imageGroup[i];
			var urlTypeTemp = image.href.match(imageURL);
			// look for ourself
			if ( image.href == url ) {
				foundSelf = true;
				imageNumber = i;
				imageCount = "<strong>" + (imageNumber + 1) + "</strong> of <strong>" + (imageGroup.length) + "</strong>";
			} else {
				// when we found ourself, the current is the next image
				if ( foundSelf ) {
					next = getInfo(image, "next", "Next &gt;");
					// stop searching
					break;
				} else {
					// didn't find ourself yet, so this may be the one before ourself
					prev = getInfo(image, "prev", "&lt; Prev");
				} // if
			} // if
		} // for
	} else {
		imageCount = "&nbsp;";

	} // if

	// check for images
	if ( baseURL.match(imageURL) ) {
		
		url += "?uid=1";
		
		imgPreloader = new Image();
		imgPreloader.onload = function() {
			imgPreloader.onload = null;
			// Resizing large images
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 200;
			var y = pagesize[1] - 100;
			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; 
				} // if
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				} // if
			} // if

			tb_width = imageWidth + 30;
			tb_height = imageHeight + 60;

			var builder = new Array();
			builder.push("<img id='tb_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/>");
			// builder.push("<img src='/images/thickbox/null.gif' alt='To download, right click on the thumbnail in the main gallery' id='cover'/>");
			builder.push("<div id='tb_outsideNav'>");
			if ( rel && next.html) {
				builder.push("<div id='tb_imageNextBkg'><a href='javascript: void(0)' id='tb_imageNext' title='Next item (right arrow key)'></a></div>");
			} // if
			if ( rel && prev.html) {
				builder.push("<div id='tb_imagePrevBkg'><a href='javascript: void(0)' id='tb_imagePrev' title='Previous item (left arrow key)'></a></div>");
			} // if

			if (desc_html) {
				desc_html = "<div id='tb_desc' style='clear:both;'>"+desc_html+"</div>";
			}




			builder.push("<div id='tb_caption'>"+caption+desc_html+"<div id='tb_secondLine'>"+imageCount+"</div></div>");
			
			
			builder.push("<div id='tb_closeWindow'><a href='javascript: void(0)' id='tb_closeWindowButton' title='Close (escape key)'>Close</a></div>");
			builder.push("</div>");
			$("#tb_window").append(builder.join(" "));

			$("#cover").css({width: imageWidth, height: imageHeight});

			if ( prev.html ) {
				$("#tb_imagePrev").click(tb_buildClickHandler(prev, rel));
				$("#tb_imagePrevBkg").css({height: tb_height});
			} // if
			
			if ( next.html ) {		
				$("#tb_imageNext").click(tb_buildClickHandler(next, rel));
				$("#tb_imageNextBkg").css({height: tb_height});
			} // if

			$("#tb_closeWindowButton").click(tb_remove);
			tb_position();
			$("#tb_load").remove();
			tb_fadeInWindow();
			
		} // imgPreloader.onload()
		
		imgPreloader.src = url;
		
	} else if(url.match(/\?(.+)/)) {
	
		
		tb_width = (params.width*1) + 30;
		tb_height = (params.height*1) + 40;
		var ajaxContentW = tb_width - 30;
		var ajaxContentH = tb_height - 45;

		$("#tb_window").append("<iframe frameborder='0' id='tb_ajaxContent' width="+ajaxContentW+" height="+ajaxContentH+" src="+url+"></iframe><div id='tb_captionTarget'></div>");

		tb_position();
		
		var builder = new Array();
		builder.push("<div id='tb_outsideNav'>");
		if ( rel && next.html) {
			builder.push("<div id='tb_imageNextBkg'><a href='javascript: void(0)' id='tb_imageNext' title='Next item (right arrow key)'></a></div>");
		} // if
		if ( rel && prev.html) {
			builder.push("<div id='tb_imagePrevBkg'><a href='javascript: void(0)' id='tb_imagePrev' title='Previous item (left arrow key)'></a></div>");
		} // if
		builder.push("</div>");
		builder.push("<div id='tb_caption'>"+caption+"<div id='tb_secondLine'>"+imageCount+"</div></div>");
		builder.push("<div id='tb_closeWindow'><a href='javascript: void(0)' id='tb_closeWindowButton' title='Close (escape key)'>Close</a></div>");
		$("#tb_captionTarget").append(builder.join(" "));

		if ( prev.html ) {
			$("#tb_imagePrev").click(tb_buildClickHandler(prev, rel));
			$("#tb_imagePrevBkg").css({height: tb_height+10});
		} // if
		if ( next.html ) {		
			$("#tb_imageNext").click(tb_buildClickHandler(next, rel));
			$("#tb_imageNextBkg").css({height: tb_height+10});
		} // if

		$("#tb_closeWindowButton").click(tb_remove);
		$("#tb_load").remove();
		tb_fadeInWindow();

		
	}
	$(window).resize(function() {
		$("#tb_overlay").css({width:"100%",height:"100%"});
		tb_position();
	}); // resize call
} // tb_show();

function tb_fadeInWindow() {
	$("#tb_window").css({display:"block"});
} // tb_fadeInWindow()

function tb_remove() {
	$("#tb_overlay").unbind("click");
	$("#tb_closeWindowButton").unbind("click");
	$('#tb_window').remove();
	$("#tb_overlay").fadeOut("fast",function(){
		$('#tb_overlay').remove();
	});
	$("#tb_load").remove();
	return false;
} // tb_remove()

function tb_position() {
	var pagesize = tb_getPageSize();	
	var arrayPageScroll = tb_getPageScrollTop();
	var style = {width: tb_width, left: (arrayPageScroll[0] + (pagesize[0] - tb_width)/2)-6, top: (arrayPageScroll[1] + (pagesize[1]-tb_height)/2)};
	$("#tb_window").css(style);
} // tb_position()

function tb_overlaySize(){
	if (window.innerHeight && window.scrollMaxY || window.innerWidth && window.scrollMaxX) {
		yScroll = window.innerHeight + window.scrollMaxY;
		xScroll = window.innerWidth + window.scrollMaxX;
		var deff = document.documentElement;
		var wff = (deff&&deff.clientWidth) || document.body.clientWidth || window.innerWidth || self.innerWidth;
		var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
		xScroll -= (window.innerWidth - wff);
		yScroll -= (window.innerHeight - hff);
	} else if (document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth){ // all but Explorer Mac
		yScroll = document.body.scrollHeight;
		xScroll = document.body.scrollWidth;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari 	
		yScroll = document.body.offsetHeight;
		xScroll = document.body.offsetWidth;
	} // if
	$("#tb_overlay").css({"height": yScroll, "width": xScroll});
} // tb_overlaySize()

function tb_load_position() {
	var pagesize = tb_getPageSize();
	var arrayPageScroll = tb_getPageScrollTop();
	$("#tb_load")
		.css({left: (arrayPageScroll[0] + (pagesize[0] - 100)/2), top: (arrayPageScroll[1] + ((pagesize[1]-100)/2)) })
		.css({display:"block"});
} // tb_load_position() 

function tb_parseQuery ( query ) {
	var Params = {};
	if ( ! query ) {return Params;}// return empty object
		var Pairs = query.split(/[;&]/);
	for ( var i = 0; i < Pairs.length; 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_getPageScrollTop(){
	var yScrolltop;
	var xScrollleft;
	if (self.pageYOffset || self.pageXOffset) {
		yScrolltop = self.pageYOffset;
		xScrollleft = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){	 // Explorer 6 Strict
		yScrolltop = document.documentElement.scrollTop;
		xScrollleft = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScrolltop = document.body.scrollTop;
		xScrollleft = document.body.scrollLeft;
	} // if
	arrayPageScroll = new Array(xScrollleft,yScrolltop);
	return arrayPageScroll;
} // tb_getPageScrollTop()

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;
	arrayPageSize = new Array(w,h);
	return arrayPageSize;
} // tb_getPageSize()

function tb_buildClickHandler(image, rel) {
	return function() {
		document.getElementById('tb_window').innerHTML = "";
		$("#tb_window").remove();
		$("body").append("<div id='tb_window'></div>");
		tb_show(image.caption, image.url, rel,image.desc_id);
	};
} // tb_buildClickHandler()

$(document).bind("keydown", function(e) {
	if(window.prev != undefined || window.next != undefined) {
		goPrev = tb_buildClickHandler(prev, group);
		goNext = tb_buildClickHandler(next, group);
		var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if(key == 37 && prev.html) {
			goPrev();
		} else if(key == 39 || key == 32 && next.html) {
			if(next.html.length != 0) {
				goNext();
			} // if
		} else if(key == 27) {
			tb_remove();
		} // if
	}
}); // keydown
