/*
 * 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
*/

// on page load call TB.init
$(document).ready(
	function() {
		// pass where to apply thickbox
		TB.init('a.thickbox, area.thickbox, input.thickbox');

		// preload image
		TB.imgLoader = new Image();
		TB.imgLoader.src = TB.pathToImage;
	}
);

function TB () {}

TB.pathToImage = 'images/loadingAnimation.gif';

TB.Width = null;
TB.Height = null;

TB.lastParams = {};
TB.windows = new Array();
TB.windowMetaData = new Array ();
TB.useStack = true;
TB.closeHtml = '<img src="img/close_window15.gif" width="15" height="15" alt="close"/><br/>'; //  'close';
TB.lastOverflow = '';

//add thickbox to href & area elements that have a class of .thickbox
TB.init = function (domChunk) {
	$(domChunk).click(
		function() {
			var t = this.title || this.name || null;
			var a = this.href || this.alt;
			var g = this.rel || false;

			TB.show( {caption: t, url: a, imageGroup: g} );
			this.blur();
			return false;
		}
	);
}

TB.getId = function ($id, $diff) {
	var $length = TB.windows.length;

	if ($diff !== undefined) {
		$length += $diff;
	}

	if ($length == 0) {
		return $id;
	}

	return $id + $length;
}

// function called when the user clicks on a thickbox link
TB.show = function (params) {
	TB.lastParams = params;
//	caption, url, imageGroup, onDataReceived, onAfterShow, postParams

	if (TB.imgLoader === undefined) {
		// loader image is set from $(document).ready(...) and when some slow javascript
		// makes page busy and user clicks on something, that opens window, then there will
		// be an error

		return ;
	}

	try {
		if (TB.useStack) {
			// increment window counter
			if (TB.windows.length == 0) {
				getFrame('head').$FrameResizer.fullScreen();
				$(window).scroll(TB.position);
				TB.lastOverflow = document.body.style.overflow;
				document.body.style.overflow = 'hidden';
			}

			TB.windows[TB.windows.length] = '#' + TB.getId('TB_window', 1);
			TB.windowMetaData[TB.windowMetaData.length] = {};
		}

		if (typeof document.body.style.maxHeight === 'undefined') {
			// if IE6 browser only
			$('body', 'html').css( {height: '100%', width: '100%'} );
			$('html').css('overflow', 'hidden');

			if ($('#TB_overlay').length == 0) {
				// create overlay
				$('body').append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div>");
				$('#TB_overlay').click(TB.remove);
			}

			if (document.getElementById( TB.getId('TB_window') ) === null) {
				// iframe to hide select elements in ie6
				$('body').append("<div id='" + TB.getId('TB_window') + "' class='TB_window'></div>");
			}
		} else {
			// all other browsers
			if ($('#TB_overlay').length == 0) {
				// create overlay
				$('body').append("<div id='TB_overlay'></div>");
				$('#TB_overlay').click(TB.remove);
			}

			if ( $('#' + TB.getId('TB_window') ).length == 0) {
				$('body').append("<div id='" + TB.getId('TB_window') + "' class='TB_window'></div>");
			}
		}

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

		if (params.caption === null) {
			params.caption = '';
		}

		$('body').append("<div id='TB_load'><img src='" + TB.imgLoader.src + "' /></div>"); // add loader to the page
		$('#TB_load').show(); // show loader

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

		var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
		var url_params = {};

		if ( baseURL.toLowerCase().match(urlString) ) {
			TB.processImages(params, urlString);
		} else {
			var queryString = params.url.replace(/^[^\?]+\??/,'');
			url_params = TB.parseQuery(queryString);

			TB.processDialog(params, url_params);
		}

		if (url_params['modal'] != 'true') {
			$(document).bind(
				'keyup',
				function(e){
					if (e.which == 27){
						// close
						TB.remove();
					}
				}
			);
		}
	} catch(e) {
		//nothing here
		alert("An exception occurred in the script.\nError name: " + e.name + ".\nError message: " + e.message);
	}
}

// helper functions below
TB.processImages = function (params, urlString) {
	// 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;

	if (params.imageGroup) {
		// scan images in group to create Prev/Next links
		var TB_TempArray = $('a[rel=' + params.imageGroup + ']').get();
		for (var TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === '')); TB_Counter++) {
			var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
			if (!(TB_TempArray[TB_Counter].href == params.url)) {
				if (TB_FoundURL) {
					TB_NextCaption = TB_TempArray[TB_Counter].title;
					TB_NextURL = TB_TempArray[TB_Counter].href;
					TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
				} else {
					TB_PrevCaption = TB_TempArray[TB_Counter].title;
					TB_PrevURL = TB_TempArray[TB_Counter].href;
					TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
				}
			} else {
				TB_FoundURL = true;
				TB_imageCount = 'Image ' + (TB_Counter + 1) + ' of ' + TB_TempArray.length;
			}
		}
	}

	var imgPreloader = new Image();
	$(imgPreloader).bind(
		'load',
		function() {
			$(this).unbind('load');
			var $image_size = TB.scaleImage.call(TB, this);

			TB.Width = $image_size.width + 30;
			TB.Height = $image_size.height + 60;
			$('#' + TB.getId('TB_window')).append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='" + params.url + "' width='" + $image_size.width + "' height='" + $image_size.height + "' alt='" + params.caption + "'/></a>" + "<div id='" + TB.getId('TB_caption') + "'>" + params.caption + "<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='" + TB.getId('TB_closeWindow') + "'><a href='#' id='" + TB.getId('TB_closeWindowButton') + "' title='Close'>close</a> or Esc Key</div>");
			$('#' + TB.getId('TB_closeWindowButton')).click(TB.remove);

			if (TB_PrevHTML !== '') {
				function goPrev() {
					$('#' + TB.getId('TB_window')).remove();
					$('body').append("<div id='" + TB.getId('TB_window') + "' class='TB_window'></div>");
					TB.show( {caption: TB_PrevCaption, url: TB_PrevURL, imageGroup: params.imageGroup} );
					return false;
				}

				$('#TB_prev').click(goPrev);
			}

			if (TB_NextHTML !== '') {
				function goNext() {
					$('#' + TB.getId('TB_window')).remove();
					$('body').append("<div id='" + TB.getId('TB_window') + "' class='TB_window'></div>");
					TB.show( {caption: TB_NextCaption, url: TB_NextURL, imageGroup: params.imageGroup} );
					return false;
				}

				$('#TB_next').click(goNext);

			}

			$(document).bind(
				'keydown',
				function(e) {
					var keycode = e.which;

					if (keycode == 27) { // close
						TB.remove();
					} else if (keycode == 190) {
						// display previous image
						if (TB_NextHTML != '') {
							$(this).unbind('keydown');
							goNext();
						}
					} else if (keycode == 188) {
						// display next image
						if(TB_PrevHTML != ''){
							$(this).unbind('keydown');
							goPrev();
						}
					}
				}
			);

			// show image after it's loaded
			TB.position();
			$('#TB_load').remove();
			$('#TB_ImageOff').click(TB.remove);
			$('#' + TB.getId('TB_window')).css('display', 'block'); // for safari using css instead of show
		}
	);

	imgPreloader.src = params.url;
}

TB.scaleImage = function ($image) {
	// resizing large images - orginal by Christian Montoya edited by me
	var pagesize = TB.getPageSize();
	var x = pagesize[0] - 150;
	var y = pagesize[1] - 150;

	var imageWidth = $image.width;
	var imageHeight = $image.height;

	if ($image.src !== undefined) {
		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;
			}
		}
	}
	else {
		if (imageWidth > x) {
			imageWidth = x;
		}

		if (imageHeight > y) {
			imageHeight = y;
		}
	}

	return {width: imageWidth, height: imageHeight};
}

TB.processDialog = function (params, url_params) {
	// code to show html

	// window size is global
	var $fake_image = {
		width: (url_params['width'] * 1) || 600, // defaults to 630 if no paramaters were added to URL
		height: (url_params['height'] * 1) || 400 // defaults to 440 if no paramaters were added to URL
	}

	var $image_size = TB.scaleImage.call(TB, $fake_image);

	TB.setWindowMetaData('window_size', $image_size);
	TB.setWindowMetaData('window_maximized', false);

	TB.Width = $image_size.width + 30;
	TB.Height = $image_size.height + 40;

	var ajaxContentW = TB.Width - 30;
	var ajaxContentH = TB.Height - 45;
	var $modal = url_params['modal'] == 'true';

	if (params.url.indexOf('TB_iframe') != -1) {
		// either iframe or ajax window
		urlNoQuery = params.url.split('TB_');
		$('#' + TB.getId('TB_iframeContent')).remove();
		if ($modal) {
			// iframe modal -> don't close when clicking on grayed-out area
			$('#TB_overlay').unbind();
		}

		var $caption_html = "<div id='" + TB.getId('TB_title') + "' class='TB_title'><div id='" + TB.getId('TB_ajaxWindowTitle') + "' class='TB_ajaxWindowTitle'>" + params.caption + "</div><div id='" + TB.getId('TB_closeAjaxWindow') + "' class='TB_closeAjaxWindow'><a href='#' id='" + TB.getId('TB_closeWindowButton') + "' class='TB_closeWindowButton' title='Close'>" + TB.closeHtml + "</a>" + ($modal ? '' : ' or Esc Key') + "</div></div>";
		$('#' + TB.getId('TB_window')).append($caption_html + "<iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='" + TB.getId('TB_iframeContent') + "' name='" + TB.getId('TB_iframeContent' + Math.round(Math.random() * 1000)) + "' onload='TB.showIframe()' class='TB_iframeContent' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;'> </iframe>");
	} else {
		// not an iframe, ajax
		if ($('#' + TB.getId('TB_window')).css('display') != 'block') {
			var $caption_html = "<div id='" + TB.getId('TB_title') + "' class='TB_title'><div id='" + TB.getId('TB_ajaxWindowTitle') + "' class='TB_ajaxWindowTitle'>" + params.caption + "</div><div id='" + TB.getId('TB_closeAjaxWindow') + "' class='TB_closeAjaxWindow'><a href='#' id='" + TB.getId('TB_closeWindowButton') + "' class='TB_closeWindowButton'>" + TB.closeHtml + "</a>" + ($modal ? '' : ' or Esc Key') + "</div></div>";

			if (!$modal) {
				// ajax no modal
				$('#' + TB.getId('TB_window')).append($caption_html + "<div id='" + TB.getId('TB_ajaxContent') + "' class='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div>");
			} else {
				// ajax modal
				$('#TB_overlay').unbind();
				$('#' + TB.getId('TB_window')).append($caption_html + "<div id='" + TB.getId('TB_ajaxContent') + "' class='TB_modal TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>");
			}
		} else {
			// this means the window is already up, we are just loading new content via ajax
			var $ajax_content = $('#' + TB.getId('TB_ajaxContent')).get(0);

			$ajax_content.style.width = ajaxContentW + 'px';
			$ajax_content.style.height = ajaxContentH + 'px';
			$ajax_content.scrollTop = 0;
			$('#' + TB.getId('TB_ajaxWindowTitle')).html(params.caption);
		}
	}

	$('#' + TB.getId('TB_closeWindowButton')).click(TB.remove);

	if (params.url.indexOf('TB_inline') != -1) {
		$('#' + TB.getId('TB_ajaxContent')).html( $('#' + url_params['inlineId']).html() );
		$('#' + TB.getId('TB_window')).unload(
			function () {
				// move elements back when you're finished
				$('#' + url_params['inlineId']).html( $('#' + TB.getId('TB_ajaxContent')).html() );
			}
		);

		TB.position();
		$('#TB_load').remove();
		$('#' + TB.getId('TB_window')).css('display', 'block');
	} else if (params.url.indexOf('TB_iframe') != -1) {
		TB.position();
		if ($.browser.safari) {
			// safari needs help because it will not fire iframe onload
			$('#TB_load').remove();
			$('#' + TB.getId('TB_window')).css('display', 'block');
		}
	} else {
		$.ajaxSetup({cache: false});

		var $content_url = params.url;
		if (params.postParams === undefined) {
			$.get(
				$content_url,
				function ($data) {
					TB.onDataReceived($data, params);
				}
			);
		}
		else {
			$.post(
				$content_url,
				params.postParams,
				function ($data) {
					TB.onDataReceived($data, params);
				}
			);
		}
	}

	TB.updateZIndex(); // update z-index on window open
}

TB.setWindowTitle = function ($title) {
	if (TB.useStack) {
		// remember window titles
		if (TB.windowMetaData.length == 0) {
			// remember title of topmost window too
			TB.windowMetaData[TB.windowMetaData.length] = {window_name: 'main'};
		}

		TB.setWindowMetaData('title', $title);
	}

	$('#' + TB.getId('TB_ajaxWindowTitle') ).html($title);
}

TB.parseRedirect = function ($data) {
	var $match_redirect = new RegExp('^#redirect#(.*)').exec($data);
	if ($match_redirect != null) {
		// redirect to external template requested
		return $match_redirect[1];
	}

	return false;
}

TB.onDataReceived = function ($data, $params) {
	if ( $.isFunction($params.onDataReceived) ) {
		$data = $params.onDataReceived($data);
		if ($data === false) {
			// this callback even could prevent redirect action
			// callback requested to stop processing
			return ;
		}
	}

	var $redirect = TB.parseRedirect($data);
	if ($redirect !== false) {
		window.location.href = $redirect;
		return ;
	}

	$('#' + TB.getId('TB_ajaxContent')).html($data);

	TB.position();
	$('#TB_load').remove();
	TB.init('#' + TB.getId('TB_ajaxContent') + ' a.thickbox');
	$('#' + TB.getId('TB_window')).css('display', 'block');

	if ( $.isFunction($params.onAfterShow) ) {
		$params.onAfterShow();
	}
}

TB.showIframe = function () {
	$('#TB_load').remove();
	$('#' + TB.getId('TB_window')).css('display', 'block');

	try {
		if ( $.isFunction(TB.lastParams.onAfterShow) ) {
			TB.lastParams.onAfterShow();
		}
	}
	catch (e) {
		// IE gives "Can't execute code from a freed script" when iframe is closed and parent window is reloaded
		// It's not a big problem, that our method is not called in this case, becase it doesn't do anything in
		// such case either
	}
}

TB.remove = function ($e, $on_close) {
	var $last_window = TB.useStack && TB.windows.length <= 1;

	$('#TB_imageOff').unbind('click');
	$('#' + TB.getId('TB_closeWindowButton')).unbind('click');

	/*$('#' + TB.getId('TB_window')).fadeOut(
		'fast',
		function() {
			TB.onAfterFade($last_window);
		}
	)*/

	$('#' + TB.getId('TB_window')).hide();

	TB.onAfterFade($last_window, $on_close);

	if ($last_window) {
		$('#TB_load').remove();
		if (typeof document.body.style.maxHeight == 'undefined') {
			// if IE 6
			$('body','html').css( {height: 'auto', width: 'auto'} );
			$('html').css('overflow', '');
		}

		$(document).unbind('keydown').unbind('keyup');
		document.body.style.overflow = TB.lastOverflow;
	}

	return false;
}

TB.onAfterFade = function ($last_window, $on_close) {
	if ($last_window) {
		// hide overlays first
		$('#TB_overlay,#TB_HideSelect').remove();
	}

	if ($.isFunction($on_close)) {
		// use close callback, because iframe will be removed later in this method
		$on_close();
	}

	$('#' + TB.getId('TB_window')).unload().remove();

	if (TB.useStack) {
		// tricky window removing to prevent memory leaks
		var n_nesting = TB.windows.length - 1;
		$(TB.windows[n_nesting]).remove();
		TB.windows[n_nesting] = null;
		TB.windows.length = n_nesting;

		// window meta data has one more record at beginning for topmost window
		TB.windowMetaData[n_nesting + 1] = null;
		TB.windowMetaData.length = n_nesting + 1;

		TB.updateZIndex(); // update z-index on window close

		set_window_title(TB.windowMetaData[TB.windowMetaData.length - 1].title);

		if (TB.windows.length == 0) {
			getFrame('head').$FrameResizer.fullScreen(true);
		}
	}
}

TB.position = function () {

	var pagesize = TB.getPageSize();
	var $window = $('#' + TB.getId('TB_window'));

	var $borders = {
		horizontal: $window.outerWidth() - $window.width(),
		vertical: $window.outerHeight() - $window.height()
	};

	var $top = $(window).scrollTop() + Math.round((pagesize[1] - TB.Height - $borders.vertical) / 2);
	var $left = Math.round((pagesize[0] - TB.Width - $borders.horizontal) / 2);

	$window.css(
		{
			width: TB.Width + 'px',
			height: TB.Height + 'px'
		}
	);

	if ($left > 0) {
		// when something large is opened from right, then we got negative left
		// (negative values breaks down "draggable.containment")
		$window.css('left', $left + 'px');
	}

	if ($top > 0) {
		// when Firebug console is opened from bottom, then we got negative top
		// (negative values breaks down "draggable.containment")
		$window.css('top', $top + 'px');
	}

	$window
	.resizable(
		{
			alsoResize: '#' + TB.getId('TB_iframeContent'),
			stop: function(event, ui) {
				if (TB.getWindowMetaData('window_maximized')) {
					return ;
				}

				var $window = $(this);

				var $window_size = {
					width: $window.width() - 30,
					height: $window.height() - 40
				}

				TB.setWindowMetaData('window_size', $window_size);
			}

		}
	)
	.draggable(
		{
			handle: '.TB_title',
			containment: 'window'
		}
	);

	$('#' + TB.getId('TB_title')).dblclick(
		function($e) {
			var $window = $('#' + TB.getId('TB_window'));
			var $maximized = TB.getWindowMetaData('window_maximized');

			var $borders = {
				horizontal: $window.outerWidth() - $window.width(),
				vertical: $window.outerHeight() - $window.height()
			};

			if ($maximized) {
				var $window_size = TB.getWindowMetaData('window_size');
				var $new_width = $window_size.width + 30;
				var $new_height = $window_size.height + 40;

				TB.setWindowMetaData('window_maximized', false);
			}
			else {
				var $new_width = pagesize[0] - $borders.horizontal;
				var $new_height = pagesize[1] - $borders.vertical;

				TB.setWindowMetaData('window_maximized', true);
			}

			var $window_width = $window.width();
			var $window_height = $window.height();

			$window.css(
				{
					width: $new_width + 'px',
					height: $new_height + 'px',
					left: Math.round((pagesize[0] - $new_width - $borders.horizontal) / 2) + 'px',
					top: $(window).scrollTop() + Math.round((pagesize[1] - $new_height - $borders.vertical) / 2) + 'px'
				}
			);

			var $width_diff = $new_width - $window_width;
			var $height_diff = $new_height - $window_height;

			var $iframe = $('#' + TB.getId('TB_iframeContent'));
			$iframe.width( $iframe.width() + $width_diff );
			$iframe.height( $iframe.height() + $height_diff );
		}
	);


	/*$('#' + TB.getId('TB_window')).css( {marginLeft: '-' + parseInt((TB.Width / 2), 10) + 'px', width: TB.Width + 'px'} );

	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) {
		// take away IE6
		$('#' + TB.getId('TB_window')).css( {marginTop: '-' + parseInt((TB.Height / 2), 10) + 'px'} );
	}*/
}

TB.parseQuery = function (query) {
	var Params = {};
	if (!query) {
		// return empty object
		return Params;
	}

	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;
}

TB.getPageSize = function () {
	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];
}

TB.detectMacXFF = function () {
	var userAgent = navigator.userAgent.toLowerCase();

	return userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1;
}

TB.updateZIndex = function () {
	// #TB_overlay - 100
	// .TB_window - 102 [ok]
	// #TB_load - 103 [ok]
	// #TB_HideSelect - 99

	var n_nesting = TB.windows.length - 1;
	var $window_index = 102 + n_nesting + TB.windows.length;

//	alert('nesting ' + n_nesting + ', window index ' + $window_index);

	$(TB.windows[n_nesting]).css('z-index', $window_index); // window position is dependend on it's opening order
	$('#TB_load').css('z-index', $window_index + 1); // progress bar is over window
	$('#TB_overlay').css('z-index', $window_index - 1); // overlay is under window
}

TB.setWindowMetaData = function ($title, $value) {
	TB.windowMetaData[TB.windowMetaData.length - 1][$title] = $value;
}

TB.getWindowMetaData = function ($title) {
	return TB.windowMetaData[TB.windowMetaData.length - 1][$title];
}

TB.findWindow = function ($name, $diff) {
	if (!isset($diff)) {
		$diff = 0;
	}

	for (var $i = TB.windowMetaData.length - 1; $i >= 0; $i--) {
//		alert('comparing [' + TB.windowMetaData[$i].window_name + '] to [' + $name + ']');
		if (TB.windowMetaData[$i].window_name == $name) {
			break;
		}
	}

	var $window_index = $i + $diff;
	if ($i == 0 || $window_index <= 0) {
		// not found or "main" window was requested -> it's not in TB.windows array anyway
		return window;
	}

	return $found_window = $('.TB_iframeContent', TB.windows[$window_index - 1]).get(0).contentWindow;
}