/*
 * 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);
//var loadingHTML = "<img src='/images/loading.gif' />";
var loadingHTML = "";

// prevent javascript error before the content has loaded
var TB_WIDTH = 0;
var TB_HEIGHT = 0;
var TB_doneOnce = 0;

// add smoothbox to href elements that have a class of .smoothbox
function TB_init() {
	$$("a.smoothbox").each(function(el) {
		el.onclick = TB_bind;
	});
	$$("input.smoothbox").each(function(el) {
		el.onclick = 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, true);
	this.onclick = TB_bind;
	return false;
}

function showMessage(caption, message, width, height) {
	var actualWidth = 300;
	var actualHeight = 30;
	if (width) {
		actualWidth = width;
	}
	if (height) {
		actualHeight = height;
	}
	var url = "#TB_text?width=" + actualWidth + "&height=" + actualHeight + "&text=" + message;
	TB_show(caption, url, false, false);
	setTimeout(function () {
		if ($('TB_overlay')) {
			TB_remove();
		}
	}, 3000);
}

function showError(caption, message, width, height) {
	var actualWidth = 300;
	var actualHeight = 30;
	if (width) {
		actualWidth = width;
	}
	if (height) {
		actualHeight = height;
	}
	var url = "#TB_text?width=" + actualWidth + "&height=" + actualHeight + "&text=" + message;
	TB_show(caption, url, false, false);
	return $("TB_ajaxContent");
}

function showBox(caption, id, width, height) {
	var actualWidth = 300;
	var actualHeight = 30;
	if (width) {
		actualWidth = width;
	}
	if (height) {
		actualHeight = height;
	}
	var url = "#TB_inline?width=" + actualWidth + "&height=" + actualHeight + "&inlineId=" + id;
	TB_show(caption, url, false, false);
	return $("TB_ajaxContent");
}

function showBoxRelative(caption, id, relativeId, width, left) {
	var actualWidth = 300;
	if (width) {
		actualWidth = width;
	}
	var url = "#TB_relative?width=" + actualWidth + "&height=auto&inlineId=" + id + "&relativeId=" + relativeId + "&TB_Left=" + left;
	TB_show(caption, url, false, false);
	return $("TB_ajaxContent");
}


function showModalBox(caption, id, width, height) {
	var actualWidth = 300;
	var actualHeight = 30;
	if (width) {
		actualWidth = width;
	}
	if (height) {
		actualHeight = height;
	}
	var url = "#TB_inline?width=" + actualWidth + "&height=" + actualHeight + "&inlineId=" + id;
	TB_show(caption, url, false, true);
	return $("TB_ajaxContent");
}

function showModalBoxAjax(caption, url, width, height, ajaxCallBack) {
	var actualWidth = 300;
	var actualHeight = 30;
	if (width) {
		actualWidth = width;
	}
	if (height) {
		actualHeight = height;
	}
	if (url.test("\\?")) {
		url = url + "&width=" + actualWidth + "&height=" + actualHeight;
	} else {
		url = url + "?width=" + actualWidth + "&height=" + actualHeight;
	}
	TB_show(caption, url, false, true, ajaxCallBack);
}

// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel, isModal, ajaxCallBack) {

	// create iframe, overlay and box if non-existent

	if (!$("TB_overlay")) {
		new Element('iframe').setProperty('id', 'TB_HideSelect').inject(document.body);
		$('TB_HideSelect').setOpacity(0);
		new Element('div').setProperty('id', 'TB_overlay').inject(document.body);
		$('TB_overlay').setOpacity(0);
		TB_overlaySize();
		new Element('div').setProperty('id', 'TB_load').inject(document.body);
		$('TB_load').innerHTML = loadingHTML;
		TB_load_position();

		var tbOverlayTween = new Fx.Tween('TB_overlay', {
			duration: 250
		});
		tbOverlayTween.start('opacity', 0, 0.3);
	}

	if (!$("TB_load")) {
		new Element('div').setProperty('id', 'TB_load').inject(document.body);
		$('TB_load').innerHTML = loadingHTML;
		TB_load_position();
	}

	if (!$("TB_window")) {
		new Element('div').setProperty('id', 'TB_window').inject(document.body);
		$('TB_window').setOpacity(0);
	}

	if (!isModal) {
		$("TB_overlay").onclick = TB_remove;
	}
	window.onscroll = TB_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)) {
		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 = "第 " + (i + 1) + " 张， 共 " + (imageGroup.length) + " 张";
				}
				else {
					// when we found ourself, the current is the next image
					if (foundSelf) {
						next = getInfo(image, "next", "下一张 &gt;");
						// stop searching
						break;
					}
					else {
						// didn't find ourself yet, so this may be the one before ourself
						prev = getInfo(image, "prev", "&lt; 上一张");
					}
				}
			}
		}

		var imgPreloader = new Image();
		imgPreloader.onload = function() {
			imgPreloader.onload = null;

			// 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;

			// TODO empty window content instead
			$("TB_window").innerHTML +=
			"<div id='TB_windowInner'><a href='' id='TB_ImageOff' title='关闭窗口'><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='关闭窗口'>关闭</a></div><div style='clear:both;'></div></div>";

			$("TB_closeWindowButton").onclick = TB_remove;

			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, isModal);
					return false;
				};
			}

			var goPrev = buildClickHandler(prev);
			var goNext = buildClickHandler(next);
			if ($('TB_prev')) {
				$("TB_prev").onclick = goPrev;
			}

			if ($('TB_next')) {
				$("TB_next").onclick = goNext;
			}

			document.onkeydown = function(event) {
				var event = new Event(event);
				switch (event.code) {
					case 27:
						TB_remove();
						break;
					case 190:
						if ($('TB_next')) {
							document.onkeydown = null;
							goNext();
						}
						break;
					case 188:
						if ($('TB_prev')) {
							document.onkeydown = null;
							goPrev();
						}
						break;
				}
			};

			// TODO don't remove loader etc., just hide and show later
			$("TB_ImageOff").onclick = 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) + 30;
		TB_HEIGHT = (params['height'] * 1) + 40;

		//		var ajaxContentW = TB_WIDTH - 30, ajaxContentH = TB_HEIGHT - 45;
		var ajaxContentW = TB_WIDTH, ajaxContentH = TB_HEIGHT - 30;
		var htmlAppend;
		if (url.indexOf('TB_iframe') != -1) {
			var urlNoQuery = url.split('TB_');
			htmlAppend = "<div id='TB_windowInner'><div id='TB_title'>" +
			             "<div id='TB_ajaxWindowTitle'>" + caption + "</div>" +
			             "<div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowA' title='关闭窗口'>关闭</a></div>" +
			             "</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_showWindow()'> </iframe>";
			$("TB_window").innerHTML += htmlAppend;
		} else {
			htmlAppend = "<div id='TB_windowInner'><div id='TB_title'>" +
			             '<a href="#" id="TB_closeWindowA" class="close">关闭</a>' +
			             "<div id='TB_ajaxWindowTitle'>" + caption + "</div>";
			htmlAppend += "</div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div></div>";
			$("TB_window").innerHTML += htmlAppend;
		}

		if ($("TB_closeWindowButton")) {
			$("TB_closeWindowButton").onclick = TB_remove;
		}
		if ($("TB_closeWindowA")) {
			$("TB_closeWindowA").onclick = TB_remove;
		}
		if (url.indexOf('TB_inline') != -1) {
			$("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
			TB_position();
			TB_showWindow();
		} else {
			if (url.indexOf('TB_relative') != -1) {
				//相对定位
				// var relativeObj = $(params['relativeId']);
				$("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
				//				var tbWindowMorph = new Fx.Morph('TB_window', {
				//					duration: 20,
				//					transition: Fx.Transitions.Sine.easeOut
				//				});
				if (params['width'] && params['width'] != 'auto') {
					TB_WIDTH = (params['width'] * 1) + 30;
				} else {
					TB_WIDTH = $('TB_window').getSize().x;
				}
				if (params['height'] && params['height'] != 'auto') {
					TB_HEIGHT = (params['height'] * 1) + 40;
				} else {
					TB_HEIGHT = $('TB_window').getSize().y;
				}
				//				TB_HEIGHT = $('TB_window').getSize().y;
				//				TB_WIDTH = $('TB_window').getSize().x;
				/*
				 tbWindowMorph.set({
				 'width': TB_WIDTH,
				 'left': (relativeObj.getPosition().x - TB_WIDTH + relativeObj.getSize().x - TB_Left),
				 'top': (relativeObj.getSize().y + relativeObj.getPosition().y - TB_top)
				 });
				 setTimeout(function() {
				 window.onresize = null;
				 window.onscroll = null;
				 }, 300);*/
				TB_position();
				TB_showWindow();
			} else {
				if (url.indexOf('TB_text') != -1) {
					$("TB_ajaxContent").innerHTML = "<div class='text_content'>" + params['text'] + "</div>";
					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) {
									TB_remove()
								}
							});
							TB_showWindow();
						}
					} else {
						var handlerFunc = function() {
							TB_position();
							TB_showWindow();
							if (ajaxCallBack) {
								ajaxCallBack.run([], $("TB_ajaxContent"));
							}
						};
						new Request.HTML({
							method: 'post',
							update: $("TB_ajaxContent"),
							onComplete: handlerFunc
						}).post(url);
					}
				}
			}
		}
	}

	window.onresize = function() {
		TB_position();
		TB_load_position();
		TB_overlaySize();
	};

	document.onkeyup = function(event) {
		var event = new Event(event);
		if (event.code == 27) { // close
			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;
		var tbWindowTween = new Fx.Tween('TB_window', {
			duration: 250,
			onComplete: function() {
				if ($('TB_load')) {
					$('TB_load').dispose();
				}
			}
		});
		tbWindowTween.start('opacity', 0, 1);
	}
	else {
		$('TB_window').setStyle('opacity', 1);
		if ($('TB_load')) {
			$('TB_load').dispose();
		}
	}
}

function TB_remove() {
	$("TB_overlay").onclick = null;
	document.onkeyup = null;
	document.onkeydown = null;

	if ($('TB_imageOff'))
	{
		$("TB_imageOff").onclick = null;
	}
	if ($('TB_closeWindowButton'))
	{
		$("TB_closeWindowButton").onclick = null;
	}
	if ($('TB_closeWindowA'))
	{
		$("TB_closeWindowA").onclick = null;
	}
	if ($('TB_prev')) {
		$("TB_prev").onclick = null;
	}
	if ($('TB_next')) {
		$("TB_next").onclick = null;
	}

	var tbWindowTween = new Fx.Tween('TB_window', {
		duration: 250,
		onComplete: function() {
			$('TB_window').dispose();
		}
	});
	tbWindowTween.start('opacity', 1, 0);

	var tbOverlayTween = new Fx.Tween('TB_overlay', {
		duration: 250,
		onComplete: function() {
			$('TB_overlay').dispose();
		}
	});
	tbOverlayTween.start('opacity', 0.3, 0);

	window.onscroll = null;
	window.onresize = null;

	$('TB_HideSelect').dispose();
	TB_init();
	TB_doneOnce = 0;
	return false;
}

function TB_position() {
	var tbWindowMorph = new Fx.Morph('TB_window', {
		duration: 20,
		transition: Fx.Transitions.Sine.easeOut
	});
	tbWindowMorph.set({
		'width': TB_WIDTH,
		'left': (window.getScrollLeft() + (window.getWidth() - TB_WIDTH) / 2),
		'top': (window.getScrollTop() + (window.getHeight() - TB_HEIGHT) / 2)
	});
}

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'
	});
	$("TB_HideSelect").setStyles({
		"height": window.getScrollHeight() + 'px',
		"width": window.getScrollWidth() + 'px'
	});
}

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;
}

