/*!
 * http://cmc3.cn/e
 * E-mail:59194618@qq.com
 *cbox  Copyright 2010, caii 蔡美纯
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function($) {
	var $overlay, $cbox, $content, $topBorder, $related, $window, $loaded, $loadingOverlay, $loadingGraphic, $title, $current, $next, $prev, $close, loadedHeight, loadedWidth, maxWidth, maxHeight, element, index, settings,$pre, open, cmcbox = 'cmcbox',doc=$(document),
	hover = 'hover',
	prev, next, init, load, position, dimensions, close, cbox_open = 'cbox_open',
	cbox_load = 'cbox_load',
	cbox_complete = 'cbox_complete',
	cbox_close = 'cbox_close',
	cbox_closed = 'cbox_closed',
	defaults = {
		speed: 800,
		initialWidth: "400",
		initialHeight: "400",
		photo: true,
		rel: false,
		opacity: 0.9,
		preloading: true,
		current: "图像 {current} / {total}",
		previous: "previous",
		next: "next",
		close: "close",
		open: 1,
		overlayClose: true
	};
	function cbox_key(e) {
		if (e.keyCode === 37) {
			e.preventDefault();
			$prev.click()
		} else if (e.keyCode === 39) {
			e.preventDefault();
			$next.click()
		}
	}
	function setSize(size, dim) {
		dim = dim === 'x' ? document.documentElement.clientWidth: document.documentElement.clientHeight;
		return parseInt(size, 10)
	}
	$.fn.cmcbox = function(options, custom_callback) {
		if (!this.length) return this;
		this.each(function() {
			var data = $(this).data(cmcbox) ? $.extend({},
			$(this).data(cmcbox), options) : $.extend({},
			defaults, options);
			$(this).data(cmcbox, data).addClass("cboxelement")
		});
		$(this).unbind("click.cmcbox").bind("click.cmcbox",
		function(e) {
			element = this;
			settings = $(element).data(cmcbox);
			if (settings.overlayClose === true) {
				$overlay.css({
					height: doc.height(),
					width: $window.width()
				})
			}
			
			element.blur();
			var rel = settings.rel || element.rel;
			$related = $('.cboxelement').filter(function() {
				var relRelated = $(this).data(cmcbox).rel || this.rel;
				return (relRelated === rel)
			});
			index = $related.index(element);
			if (index < 0) {
				$related = $related.add(element);
				index = $related.length - 1
			}
			if (!open) {
				$overlay.css({
					"opacity": settings.opacity
				}).show();
				open = true;
				vv = setSize(settings.initialWidth, 'x');
				position(vv, setSize(settings.initialHeight, 'y'), 0)
			}
			rev = this.rev;
			load();
			e.preventDefault()
		});
		if (options && options.open) {
			$(this).triggerHandler('click.cmcbox')
		}
		return this
	};
	function $div(id) {
			return $('<div id="cbox' + id + '"/>')
	}
	init = function() {
		$window = $(window);
		$cbox = $('<div id="cmcbox"/>');
		$overlay = $div("Overlay").hide();
		$content = $div("Content").append($loaded = $div("LoadedContent").css({
			width: 0,
			height: 0
		}), $loadingOverlay = $div("LoadingOverlay"), $loadingGraphic = $div("LoadingGraphic"), $title = $div("Title"), $current = $div("Current"), $next = $div("Next"), $prev = $div("Previous"), $close = $div("Close"));
		$('body').prepend($overlay, $cbox.append($content));
		if ($.browser.msie && $.browser.version < 7) {
			$overlay.css('position', 'absolute')
		}
		$content.children().addClass(hover).mouseover(function() {
			$(this).addClass(hover)
		}).mouseout(function() {
			$(this).removeClass(hover)
		}).hide();
		loadedHeight = $loaded.outerHeight(true);
		loadedWidth = $loaded.outerWidth(true);
		$cbox.hide();
		
		$next.click(next);
		$prev.click(prev);
		$close.click(close);
		$content.children().removeClass(hover)
	};
	position = function(mWidth, mHeight, speed, loadedCallback, aa) {
		var winHeight = document.documentElement.clientHeight,
		posTop = winHeight / 2 - mHeight / 2,
		posLeft = document.documentElement.clientWidth / 2 - mWidth / 2,
		animate_speed;
		if (mHeight > winHeight) {
			posTop -= (mHeight - winHeight)
		}
		if (posTop < 0) {
			posTop = 0
		}
		if (posLeft < 0) {
			posLeft = 0
		}
		posTop += $window.scrollTop();
		posLeft += $window.scrollLeft();
		animate_speed = speed;
		function modalDimensions(that) {
			$content[0].style.width = that.style.width;
			$loadingGraphic[0].style.height = $loadingOverlay[0].style.height = $content[0].style.height = that.style.height
		}
		
		$cbox.css('display','block').animate({
			height: mHeight,
			width: mWidth,
			top: posTop,
			left: posLeft
		},
		{
			duration: animate_speed,
			complete: function() {
				
				modalDimensions(this);
				loadedCallback && loadedCallback()
			},
			step: function() {
				modalDimensions(this)
			}
		})
	};
	dimensions = function(object) {
		if (!open) {
			return
		}
		$window.unbind('resize.cbox_resize');
		var width, height, topMargin, prev, prevSrc, next, nextSrc, photo, speed = settings.speed;
		$loaded = $(object);
		function getWidth() {
			width = $loaded.width();
			return $loaded.width()
		}
		function getHeight() {
			height = $loaded.height();
			return $loaded.height()
		}
		$loaded.hide().appendTo('body').attr({
			id: 'cboxLoadedContent'
		}).css({
			width: getWidth()
		}).css({
			height: getHeight()
		}).prependTo($content);
		if ($.browser.msie && $.browser.version < 7) {
			$('select:not(#cmcbox select)').filter(function() {
				return $(this).css('visibility') !== 'hidden'
			}).css({
				'visibility': 'hidden'
			}).one(cbox_close,
			function() {
				$(this).css({
					'visibility': 'inherit'
				})
			})
		}
		function setPosition(s) {
			var mWidth = width,
			mHeight = height + loadedHeight;
			position(mWidth, mHeight, s,
			function() {
				if (!open) {
					return
				}
				$content.children().show();
				$loadingOverlay.hide();
				$loadingGraphic.hide();
				if ($related.length > 1) {
					$current.html(settings.current.replace(/\{current\}/, index + 1).replace(/\{total\}/, $related.length));
					$next.html(settings.next);
					$prev.html(settings.previous);
					doc.unbind('keydown', cbox_key).bind('keydown', cbox_key)
				} else {
					$current.hide();
					$next.hide();
					$prev.hide()
				}
				$title.html(settings.title || element.title);
				$window.bind('resize.cbox_resize',
				function() {
					position(mWidth, mHeight, 0)
				})
			})
		}
		setPosition(speed);
		if (settings.preloading && $related.length > 1) {
			prev = index > 0 ? $related[index - 1] : $related[$related.length - 1];
			next = index < $related.length - 1 ? $related[index + 1] : $related[0];
			nextSrc = $(next).data(cmcbox).href || next.href;
			prevSrc = $(prev).data(cmcbox).href || prev.href;
			$pre&&$pre.remove();
			$pre=$div('pre');
			$pre.css('display','none').appendTo($('body'));
			$('<img />').attr('src', nextSrc).appendTo($pre);
			$('<img />').attr('src', prevSrc).appendTo($pre);
		}
	};
	
	load = function() {
		var height, width, href, loadingElement;
		element = $related[index];
		settings = $(element).data(cmcbox);
		height = false;
		width = false;
		href = settings.href || element.href;
		$loaded.find('img').fadeTo(300, 0.1, kk);
		function kk() {
			delete load.yes;
			$loaded.remove();
			$loadingOverlay.show();
			$loadingGraphic.show();
			$close.show();
			maxHeight = height;
			maxWidth = width;
			loadingElement = new Image();
			loadingElement.onload = function() {
				loadingElement.onload = null;
				var t=$(this).css({
					display: "block",
					opacity: 0.1
				}).attr('id', 'cboxPhoto')
				dimensions($("<div />").append(t));
				setTimeout(function(){t.fadeTo(150, 1)},800);
				if ($related.length > 1) {
					$(this).css({
						cursor: 'pointer'
					}).click(next)
				}
				if ($.browser.msie && $.browser.version == 7) {
					this.style.msInterpolationMode = 'bicubic'
				}
			};
			loadingElement.src = href
		};
		load.yes && kk()
	};
	load.yes = 1;
	next = function() {
		index = index < $related.length - 1 ? index + 1 : 0;
		load();
	};
	prev = function() {
		index = index > 0 ? index - 1 : $related.length - 1;
		load();
	};
	close = function() {
		open = same = rev = null;
		doc.unbind('keydown', cbox_key).unbind("keydown.cbox_close");
		$window.unbind('resize.cbox_resize resize.cboxie6 scroll.cboxie6');
		$cbox.stop(true, false).removeClass().slideUp(460,
		function() {
			$overlay.css({
				cursor: 'auto'
			}).fadeOut();
			$loaded.remove();
			$cbox.css({
				'opacity': 1
			})
		})
	};
	$(init);
})(jQuery);
