/*
 * Smoothbox v20080623 by Boris Popoff (http://gueschla.com)
 * To be used with mootools 1.2
 *
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// on page load call TB_init
window.addEvent('domready', TB_init);

// prevent javascript error before the content has loaded
var TB_WIDTH = 0;
var TB_HEIGHT = 0;
var TB_doneOnce = 0;
var forcedOpen = false;

// add smoothbox to href elements that have a class of .smoothbox
function TB_init() {
	$$('.smoothbox').each(function(el) {
		el.addEvent('click', TB_bind);
	});
}

function TB_bind(event) {
	var event = new Event(event);
	// stop default behaviour
	event.preventDefault();
	// remove click border
	this.blur();
	// get caption: either title or name attribute
	var caption = this.title || this.name || '';
	// get rel attribute for image groups
	var group = this.rel || false;
	// display the box for the elements href
	TB_show(caption, this.href, group);
	//this.addEvent('click', TB_bind); // Why is this added again? This doesn't need to be done because it's already done in TB_init!
	return false;
}

// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel, forceOpen, frameless) {
	if (forceOpen == true || forceOpen == false) {
		forcedOpen = forceOpen;
	} else {
		if (!$('TB_window')) {
			forcedOpen = false;
		}
	}
	TB_objectHide(true);
	// create iframe, overlay and box if non-existent
	
	if (!$('TB_overlay')) {
		new Element('iframe', {'id': 'TB_HideSelect', 'style': 'display: none;'}).inject(document.body);
		$('TB_HideSelect').setOpacity(0);
		new Element('div', {'id': 'TB_overlay', 'style': 'display: none;'}).inject(document.body);
		$('TB_overlay').setOpacity(0);
		TB_overlaySize();
		new Element('div', {'id': 'TB_load', 'style': 'display: none;'}).inject(document.body);
		$('TB_load').set('html', '<img src="' + baseUrl + '/assets/images/smoothbox/loading.gif" />');
		TB_load_position();
		
		$('TB_overlay').set('tween', {
			duration: 400
		});
		$('TB_overlay').tween('opacity', 0, 0.75);
		
	}
	
	if (!$('TB_load')) {
		new Element('div', {'id': 'TB_load'}).inject(document.body);
		$('TB_load').set('html', '<img src="' + baseUrl + '/assets/images/smoothbox/loading.gif" />');
		TB_load_position();
	}
	
	if (!$('TB_window')) {
		new Element('div', {'id': 'TB_window', 'style': 'display: none;'}).inject(document.body);
		$('TB_window').setOpacity(0);
	} else {
		// a second request to smoothbox while a smoothbox is already shown - so display the loading icon
		$('TB_window').empty();
		if ($('TB_load')) {
			$('TB_load').dispose();
			new Element('div', {'id':'TB_load'}).inject(document.body);
			$('TB_load').set('html', '<img src="' + baseUrl + '/assets/images/smoothbox/loading_black.gif" />');
			$('TB_load').setStyle('z-index', 103);
			TB_load_position();
		}
	}
	
	if (forcedOpen != true) {
		$('TB_overlay').addEvent('click', TB_remove);
	}
	window.addEvent('scroll', TB_position);
	
	// check if a query string is involved
	if( url.match(/(.+)\?/) != null ) {
		var baseURL = url.match(/(.+)\?/)[1];
	} else {
		var baseURL = 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)) {
		var dummy = {
			caption: '',
			url: '',
			html: ''
		};
		
		var 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>'
				}
			}
			
			// find the anchors that point to the group
			var imageGroup = [];
			$$('a.smoothbox').each(function(el) {
				if (el.rel == rel) {
					imageGroup[imageGroup.length] = el;
				}
			})
			
			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;
					imageCount = 'Image ' + (i + 1) + ' of ' + (imageGroup.length);
				} 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');
					}
				}
			}
		}
		
		imgPreloader = new Image();
		imgPreloader.addEvent('load', function() {
			//imgPreloader.onload = null;
			imgPreloader.removeEvents('load');
			
			// Resizing large images
			var x = window.getWidth() - 150;
			var y = window.getHeight() - 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;
			TB_position();
			
			// TODO empty window content instead
			var TB_ImageOff = new Element('a', {
				'id': 'TB_ImageOff',
				'title': 'Close'
			});
			var TB_Image = new Element('img', {
				'id': 'TB_Image',
				'src': url,
				'width': imageWidth,
				'height': imageHeight,
				'alt': caption
			});
			var TB_caption = new Element('div', {
				'id': 'TB_caption',
				'html': caption
			});
			var TB_secondline = new Element('div', {
				'id': 'TB_secondline',
				'html': imageCount + prev.html + next.html
			});
			var TB_closeWindow = new Element('div', {
				'id': 'TB_closeWindow'
			});
			var TB_closeWindowButton = new Element('a', {
				'id': 'TB_closeWindowButton',
				'title': 'Close'
			});
			TB_closeWindowButton.adopt(new Element('img', {
				'src': baseUrl + '/assets/images/core/smoothbox_close.gif'
			}));
			$('TB_window').adopt(TB_ImageOff);
			TB_ImageOff.adopt(TB_Image);
			
			$('TB_window').adopt(TB_caption);
			TB_caption.adopt(TB_secondline);
			
			$('TB_window').adopt(TB_closeWindow);
			if (forcedOpen != true) {
				TB_closeWindowButton.addEvent('click', TB_remove);
				TB_closeWindow.adopt(TB_closeWindowButton);
			}
			
			function buildClickHandler(image) {
				return function() {
					$('TB_window').dispose();
					new Element('div').setProperty('id', 'TB_window').inject(document.body);
					
					TB_show(image.caption, image.url, rel);
					return false;
				};
			}
			var goPrev = buildClickHandler(prev);
			var goNext = buildClickHandler(next);
			if ($('TB_prev')) {
				$('TB_prev').addEvent('click', goPrev);
			}
			
			if ($('TB_next')) {
				$('TB_next').addEvent('click', goNext);
			}
			
			document.addEvent('keydown', function(event) {
				var event = new Event(event);
				switch (event.code) {
					case 27:
						if (forcedOpen != true) {
							TB_remove();
						}
						break;
					case 190:
						if ($('TB_next')) {
							document.removeEvents('keydown');
							goNext();
						}
						break;
					case 188:
						if ($('TB_prev')) {
							document.removeEvents('keydown');
							goPrev();
						}
						break;
				}
			});
			
			// TODO don't remove loader etc., just hide and show later
			$('TB_ImageOff').addEvent('click', TB_remove);
			TB_position();
			TB_showWindow();
		});
		imgPreloader.src = url;
		
	} else { //code to show html pages
		var queryString = url.match(/\?(.+)/)[1];
		var params = TB_parseQuery(queryString);
		
		TB_WIDTH = (params['width'] * 1);
		TB_HEIGHT = (params['height'] * 1) + 27;
		TB_position();
		
		var ajaxContentW = TB_WIDTH, ajaxContentH = TB_HEIGHT - 27;

		var TB_title = new Element('div', {
			'id': 'TB_title'
		});
		var TB_ajaxWindowTitle = new Element('div', {
			'id': 'TB_ajaxWindowTitle',
			'html': caption
		});
		var TB_closeAjaxWindow = new Element('div', {
			'id': 'TB_closeAjaxWindow'
		});
		var TB_closeWindowButton = new Element('a', {
			'id': 'TB_closeWindowButton',
			'href': '#'
		});
		TB_closeWindowButton.adopt(new Element('img', {
			'id': 'TB_closeWindowButtonImage',
			'src': baseUrl + '/assets/images/core/smoothbox_close.gif',
			'border': '0'
		}));
		if ($('TB_closeWindowButtonImage')) {
			$('TB_closeWindowButtonImage').setStyle('border', 'none');
		}
		
		if (frameless != true) {
			$('TB_window').adopt(TB_title);
			TB_title.adopt(TB_ajaxWindowTitle);
			TB_title.adopt(TB_closeAjaxWindow);
			if (forcedOpen != true) {
				TB_closeAjaxWindow.adopt(TB_closeWindowButton);
			}
			$('TB_window').setStyles({'background-color': '', 'border': ''});
		} else {
			$('TB_window').setStyles({'background-color': 'transparent', 'border': 'none'});
		}
		if (url.indexOf('TB_iframe') != -1) {
			urlNoQuery = url.split('TB_');
			var TB_iframeContent = new Element('iframe', {
				'id': 'TB_iframeContent',
				'frameborder': 0,
				'hspace': 0,
				'src': urlNoQuery[0],
				'name': 'TB_iframeContent'
			});
			TB_iframeContent.setStyles({
				'width': (ajaxContentW + 29) + 'px',
				'height': (ajaxContentH + 17) + 'px'
			});
			TB_iframeContent.addEvent('load', TB_showWindow);
			$('TB_window').adopt(TB_iframeContent);
		} else {
			var TB_ajaxContent = new Element('div', {
				'id': 'TB_ajaxContent'
			});
			TB_ajaxContent.setStyles({
				'width': ajaxContentW + 'px',
				'height': ajaxContentH + 'px'
			});
			$('TB_window').adopt(TB_ajaxContent);
		}
		if (frameless != true) {
			if (forcedOpen != true) {
				$('TB_closeWindowButton').addEvent('click', TB_remove);
			}
		}
		
		if (url.indexOf('TB_inline') != -1) {
			$('TB_ajaxContent').set('html', $(params['inlineId']).get('html'));
			TB_position();
			TB_showWindow();
		} else if (url.indexOf('TB_iframe') != -1) {
			TB_position();
			if (frames['TB_iframeContent'] == undefined) {//be nice to safari
				$(document).keyup(function(e) {
					var key = e.keyCode;
					if (key == 27) {
						if (forcedOpen != true) {
							TB_remove();
						}
					}
				});
				TB_showWindow();
			}
		} else if (url.indexOf('TB_JSON') != -1) {
			new Request.JSON({
				url: baseURL + '/format/json',
				update: $('TB_ajaxContent'),
				onComplete: function(response){
					if (response) {
						TB_position();
						TB_showWindow();
						if (response.customJS_pre != undefined) {
							eval(response.customJS_pre);
						}
						$('TB_ajaxContent').set('html', response.htmlContent);
						if (response.customJS_post != undefined) {
							eval(response.customJS_post);
						}
					}
				}
			}).post(params);
		} else {
			var handlerFunc = function() {
				TB_position();
				TB_showWindow();
			};

			new Request.HTML({
				method: 'get',
				update: $('TB_ajaxContent'),
				onComplete: handlerFunc
			}).get(url);
		}
	}
	
	window.addEvent('resize', function() {
		TB_position();
		TB_load_position();
		TB_overlaySize();
	});
	
	document.addEvent('keyup', function(event) {
		var event = new Event(event);
		if (event.code == 27) { // close
			if (forcedOpen != true) {
				TB_remove();
			}
		}
	});
	
}

//helper functions below

function TB_showWindow(){
	//$("TB_load").dispose();
	//$("TB_window").setStyles({display:"block",opacity:'0'});
	
	if (TB_doneOnce == 0) {
		TB_doneOnce = 1;
		
		$('TB_window').set('tween', {
			duration: 250,
			onComplete: function(){
				if ($('TB_load')) {
					$('TB_load').dispose();
				}
			}
		});
		$('TB_window').tween('opacity', 0, 1);
		
	} else {
		$('TB_window').setStyle('opacity', 1);
		if ($('TB_load')) {
			$('TB_load').dispose();
		}
	}
}

function TB_objectHide(open) {
	var elements = $A(document.getElementsByTagName('object'));
	elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
	elements.each(function(el){
		if (open) {
		   el.lbBackupStyle = el.style.visibility;
		}
		el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
	});
}

function TB_remove(){
	TB_objectHide(false);
	if ($('TB_load')) {
		$('TB_load').dispose();
	}
	if ($('TB_overlay')) {
		$('TB_overlay').removeEvents('click');
	}
	document.removeEvents('keyup');
	document.removeEvents('keydown');
	
	if ($('TB_imageOff')) { 
		$("TB_imageOff").removeEvents('click');
	}
	if ($('TB_closeWindowButton')) { 
		$("TB_closeWindowButton").removeEvents('click');
	}
	if ($('TB_prev')) {
		$("TB_prev").removeEvents('click');
	}
	if ($('TB_next')) {
		$("TB_next").removeEvents('click');
	}
	
	if ($('TB_window')) {
		$('TB_window').set('tween', {
			duration: 250,
			onComplete: function() {
				$('TB_window').dispose();
			}
		});
		$('TB_window').tween('opacity', 1, 0);
	}
	
	if ($('TB_overlay')) {
		$('TB_overlay').set('tween', {
			duration: 400,
			onComplete: function() {
				$('TB_overlay').dispose();
			}
		});
		$('TB_overlay').tween('opacity', 0.75, 0);
	}
	
	window.removeEvents('scroll');
	window.removeEvents('resize');
	
	if ($('TB_HideSelect')) {
		$('TB_HideSelect').dispose();
	}
	TB_init();
	TB_doneOnce = 0;
	return false;
}

function TB_position(){
	$('TB_window').set('morph', {
		duration: 75
	});
	$('TB_window').morph({
		width: TB_WIDTH + 'px',
		height: TB_HEIGHT + 'px',
		left: (window.getScrollLeft() + (window.getWidth() - TB_WIDTH) / 2) + 'px',
		top: (window.getScrollTop() + (window.getHeight() - TB_HEIGHT) / 2) + 'px',
		display: ''
	});
	//$('TB_window').setStyle('display', '');
}

function TB_overlaySize(){
	// we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
	$('TB_overlay').setStyles({
		'height': '0px',
		'width': '0px'
	});
	$('TB_HideSelect').setStyles({
		'height': '0px',
		'width': '0px'
	});
	$('TB_overlay').setStyles({
		'height': window.getScrollHeight() + 'px',
		'width': window.getScrollWidth() + 'px',
		'display': ''
	});
	$('TB_HideSelect').setStyles({
		'height': window.getScrollHeight() + 'px',
		'width': window.getScrollWidth() + 'px',
		'display': ''
	});
}

function TB_load_position(){
	if ($('TB_load')) {
		$('TB_load').setStyles({
			left: (window.getScrollLeft() + (window.getWidth() - 56) / 2) + 'px',
			top: (window.getScrollTop() + ((window.getHeight() - 20) / 2)) + 'px',
			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;
}
