/* 
* developed markup-javascript.com
* jQuery jQueryBox v0.8.3
*/
(function($) {
	$.jQueryBox = {ver: '0.8.3'};
	$.fn.jQueryBox = function(_options){    
		// defaults options
		$.jQueryBox.options = $.extend({
			closeBoxByFader:true,
			overlayColor:'#000',
			overlayOpacity:0.5,
			overlayFadeDuration:300,
			boxFadeDuration:300,
			boxAnimate:300,
			boxScrollDuration:500,
			boxContentFadeDuration: 500,
			boxMinWidth:300,
			boxMinHeight:300,
			boxDesignPadding:'10',
			boxDescription:'div.jqb-description',
			boxInsert:'#jqb-insert',
			boxBtnClose:'a.jqb-close-btn',
			boxBtnNext:'a.jqb-next-btn',
			boxBtnPrev:'a.jqb-prev-btn',
			boxLoadIco:'span.jqb-load-ico',
			boxMarkup:'<div class="jqb-lightbox">\
						<div class="jqb-holder">\
							<div class="jqb-content-holder">\
							<span class="jqb-load-ico"></span>\
								<div id="jqb-insert"></div>\
								<span class="jqb-loader-ico"></span>\
								<a href="#" class="jqb-next-btn">Next</a>\
								<a href="#" class="jqb-prev-btn">Prev</a>\
								<a href="#" class="jqb-close-btn">Close</a>\
								<div class="jqb-description"></div>\
							</div>\
						</div>\
					</div>',
			imageMarkup: '<img class="jqb-image" src="{path}" />',
			imageInlineHTML: '<div class="jqb-inline-content"></div>',
			flashMarkup: '<object width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
			iframeMarkup: '<iframe src ="{url}" width="{width}" height="{height}" frameborder="no"></iframe>',
			quicktimeMarkup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
			wmode: 'opaque' /* Set the flash wmode attribute */,
			callbackShow : function(_box){return true},
			callbackClose : function(_box){return true},
			callbackBeforeClose : function(_box){return true},
			autoplay:true
		},_options);
		
		var _body = $('body'), _box, _overlay, _pageWidth, _pageHeight, _pageHeightView, _pageWidthView, _currentGallery, _toInject, _padding;
		_padding = $.jQueryBox.options.boxDesignPadding.split(' ');
		if (_padding.length == 1) {_padding[1] = _padding[2] = _padding[3] = _padding[0]};
		if (_padding.length == 2) {_padding[3] = _padding[1]; _padding[2] = _padding[0]};
		if (_padding.length == 3) {_padding[3] = _padding[1];}
		$(_padding).each(function(i){_padding[i] = parseInt(this);});
		var	_boxTempWidth = $.jQueryBox.options.boxMinWidth + _padding[1] + _padding[3],
			_boxTempHeight = $.jQueryBox.options.boxMinHeight + _padding[0] + _padding[2];
			
		// size
		_body.div = _body.children('div:first');
		$.jQueryBox.windowSize = function(){
			if (window.innerHeight) {
				_pageHeight = _pageHeightView = window.innerHeight;
				_pageWidth = _pageWidthView = window.innerWidth;
			} else {
				_pageHeight = _pageHeightView = document.documentElement.clientHeight;
				_pageWidth = _pageWidthView = document.documentElement.clientWidth;
			}
			if (_pageHeight < _body.div.outerHeight(true)) _pageHeight = _body.div.outerHeight(true);
			if (_pageWidth < _body.div.outerWidth(true)) _pageWidth = _body.div.outerWidth(true);
			else _pageWidth = '100%';
		};
		
		var _tempY=$(document).scrollTop();
		$.jQueryBox.boxSizePosParam = function(_bWidth, _bHeight){
			$.jQueryBox.windowSize();
			var _x = 0, _y = 0, _wTemp = _boxTempWidth, _hTemp = _boxTempHeight;
			if (_bWidth && _bHeight) {
				_wTemp = _bWidth + _padding[3] + _padding[1];
				_hTemp = _bHeight + _padding[0] + _padding[2];
			}
			_boxTempWidth = _wTemp;
			_boxTempHeight = _hTemp;
			
			if (_pageWidthView > _boxTempWidth) 
				_x = (_pageWidthView - _boxTempWidth) / 2;
			if (_pageHeightView > _boxTempHeight) 
				_y = (_pageHeightView - _boxTempHeight) / 2 + parseInt($(document).scrollTop());
				
			if (_pageHeightView < _boxTempHeight)
				return {left:_x, top:_tempY};
			else {
				_tempY=_y;
				return {left:_x, top:_y}
			}
		};
	
		// overlay
		$.jQueryBox.createOverlay = function(){
			_overlay = $('<div class="jqb-overlay"></div>').hide();
			_overlay.css({
				'backgroundColor':$.jQueryBox.options.overlayColor,
				'opacity':$.jQueryBox.options.overlayOpacity,
				'position':'absolute',
				'top':0,
				'left':0,
				'zIndex':1000
			});
			_body.append(_overlay);
		};
		$.jQueryBox.overlaySize = function(){
			_overlay.css({
				width:_pageWidth,
				height:_pageHeight
			});
		};
		
		// box
		$.jQueryBox.createBox = function(){
			_box = $($.jQueryBox.options.boxMarkup).hide();
			_box.css({
				'position':'absolute',
				'width':$.jQueryBox.options.boxMinWidth,
				'zIndex':1001
			});
			_body.append(_box);
		};
		
		// init sub function
		$.jQueryBox.windowSize();
		$.jQueryBox.createOverlay();
		$.jQueryBox.overlaySize();
		$.jQueryBox.createBox();
		_box.css($.jQueryBox.boxSizePosParam());
		
		// window events
		$(window).resize(function(){
			if (_overlay.is(':visible')) {
				$.jQueryBox.windowSize();
				$.jQueryBox.overlaySize();
				_box.animate($.jQueryBox.boxSizePosParam(), {duration:$.jQueryBox.options.boxScrollDuration, queue:false});
			}
		});
		$(window).scroll(function(){
			if (_overlay.is(':visible')) {
				_box.animate($.jQueryBox.boxSizePosParam(), {duration:$.jQueryBox.options.boxScrollDuration, queue:false});
			}
		});
		
		// other func
		$.jQueryBox.getFileType = function(itemSrc){
			if (itemSrc.match(/youtube\.com\/watch/i)) {
				return 'youtube';
			} else if(itemSrc.indexOf('.mov') != -1){ 
				return 'quicktime';
			} else if (itemSrc.match(/vimeo\.com/i)) {
				return 'vimeo';
			} else if(itemSrc.indexOf('.swf') != -1){
				return 'flash';
			} else if(itemSrc.indexOf('iframe') != -1){
				return 'iframe';
			} else if(itemSrc.indexOf('ajax') != -1){
				return 'ajax';
			} else if(itemSrc.indexOf('#') != -1){
				return 'inline';
			} else{
				return 'image';
			};
		};
		$.jQueryBox.getParam = function(_paramName, _url){
			var _regexS = new RegExp("[\\?&]"+_paramName+"=([^&#]*)");
			var _results = _regexS.exec(_url);
			if( _results == null )
				return "";
			else if (_paramName == 'width' || _paramName == 'height')
				return parseInt(_results[1]);
			else return _results[1];
		};
		$.jQueryBox.remParam = function(_paramName, _url){
			$(_paramName).each(function(i){
				var _regexS = new RegExp("[\\?&]"+_paramName[i]+"=([^&#]*)");
				var _results = _regexS.exec(_url);
				_url = _url.replace(_results[0],'');
			});
			return _url;
		};
		
		// gallery sort
		var _links = $(this).filter('[rel!=""]').clone().addClass('filter'),
			_gallerys = [$(this).not('[rel]')];
		
		while (_links.filter('.filter').length) {
			var _rel = _links.filter('.filter').eq(0).attr('rel');
			_gallerys.push('[rel="'+_rel+'"]');
			_links.filter('[rel="'+_rel+'"]').removeClass('filter');
		}
		for (var i=1; i<_gallerys.length; i++) {
			_gallerys[i] = $(this).filter(_gallerys[i]);
		}
		
		// main elements
		var _boxInsert = $($.jQueryBox.options.boxInsert, _box).css('height',$.jQueryBox.options.boxMinHeight),
			_btnNext = $($.jQueryBox.options.boxBtnNext, _box),
			_btnPrev = $($.jQueryBox.options.boxBtnPrev, _box),
			_btnClose = $($.jQueryBox.options.boxBtnClose, _box).length ? $($.jQueryBox.options.boxBtnClose, _box) : [],
			_loadIco = $($.jQueryBox.options.boxLoadIco, _box),
			_description = $($.jQueryBox.options.boxDescription, _box),
			_current = 0;
		// show
		$.jQueryBox.boxShow = function(_linkHref, _hidePrevNext){
			_loadIco.show();
			_description.hide();
			if (!_hidePrevNext || _hidePrevNext == 1) {_btnPrev.hide(); _btnNext.hide()} else {_btnPrev.show(); _btnNext.show()} 
			_boxInsert.css('opacity',0).empty();
			if($.browser.msie && $.browser.version == 6) $('select').css('visibility','hidden');
			if (_overlay.is(':hidden')) 
				_overlay.fadeIn($.jQueryBox.options.overlayFadeDuration, function(){
					_box.css($.jQueryBox.boxSizePosParam()).fadeIn($.jQueryBox.options.boxFadeDuration, function(){
						_boxInsert.css('opacity','auto');
					});
				});
			var _linkType = $.jQueryBox.getFileType(_linkHref);
			switch(_linkType){
				case 'image':
					var _imgPure = new Image(),
						_imageObj = $($.jQueryBox.options.imageMarkup).attr('src', _linkHref);
						
					_imgPure.onload = function(){
						var _pos = $.jQueryBox.boxSizePosParam(this.width, this.height); 
						$.jQueryBox.animateThis(_pos.left, _pos.top, _boxTempWidth, this.height);
						this.onload = function(){};
					}
					_imgPure.src = _linkHref;
					_boxInsert.append(_imageObj);					
					break;
				case 'iframe':
					var _iframeWidth = $.jQueryBox.getParam('width',_linkHref);
					var _iframeHeight = $.jQueryBox.getParam('height',_linkHref);
					_linkHref = $.jQueryBox.remParam(['width','height','iframe'], _linkHref)
					_toInject = $($.jQueryBox.options.iframeMarkup.replace(/{width}/g,_iframeWidth).replace(/{height}/g,_iframeHeight).replace(/{url}/g,_linkHref));
					_boxInsert.append(_toInject);
					_toInject.bind('load', function(){
						var _pos = $.jQueryBox.boxSizePosParam(_iframeWidth, _iframeHeight);
						$.jQueryBox.animateThis(_pos.left, _pos.top, _boxTempWidth, _iframeHeight);
					});
					break;
				case 'inline':
					var _inlineWidth = $.jQueryBox.getParam('width',_linkHref);
					var _inlineHeight = $.jQueryBox.getParam('height',_linkHref);
					if (_inlineWidth && _inlineHeight) _linkHref = $.jQueryBox.remParam(['width','height'], _linkHref);
					_linkHref = _linkHref.substr(_linkHref.indexOf('#'));
					if (!_inlineWidth && !_inlineHeight) {
						_inlineWidth = $(_linkHref).outerWidth(true);
						_inlineHeight = $(_linkHref).outerHeight(true);
					}
					if ($(_linkHref).length) {
						_toInject = $($.jQueryBox.options.imageInlineHTML).html($(_linkHref).clone(true));
						_boxInsert.append(_toInject);
						var _pos = $.jQueryBox.boxSizePosParam(_inlineWidth, _inlineHeight);
						$.jQueryBox.animateThis(_pos.left, _pos.top, _boxTempWidth, _inlineHeight);
					}
					else _overlay.hide().stop();
					break;
				case 'flash':
					var _flashWidth = $.jQueryBox.getParam('width',_linkHref);
					var _flashHeight = $.jQueryBox.getParam('height',_linkHref);
					var _wMode = $.jQueryBox.getParam('wmode',_linkHref);
					_toInject = $($.jQueryBox.options.flashMarkup.replace(/{width}/g,_flashWidth).replace(/{height}/g,_flashHeight).replace(/{wmode}/g,$.jQueryBox.options.wmode).replace(/{path}/g,_linkHref));
					_boxInsert.append(_toInject);
					var _pos = $.jQueryBox.boxSizePosParam(_flashWidth, _flashHeight);
					$.jQueryBox.animateThis(_pos.left, _pos.top, _boxTempWidth, _flashHeight);
					break;
				case 'vimeo':
					var _flashWidth = $.jQueryBox.getParam('width',_linkHref);
					var _flashHeight = $.jQueryBox.getParam('height',_linkHref);
					var _wMode = $.jQueryBox.getParam('wmode',_linkHref);
					_toInject = $($.jQueryBox.options.flashMarkup.replace(/{width}/g,_flashWidth).replace(/{height}/g,_flashHeight).replace(/{wmode}/g,$.jQueryBox.options.wmode).replace(/{path}/g,'http://vimeo.com/moogaloop.swf?clip_id='+_linkHref.replace('http://www.vimeo.com/','').replace('http://vimeo.com/','')));
					_boxInsert.append(_toInject);
					var _pos = $.jQueryBox.boxSizePosParam(_flashWidth, _flashHeight);
					$.jQueryBox.animateThis(_pos.left, _pos.top, _boxTempWidth, _flashHeight);
					break;
				case 'youtube':
					var _flashWidth = $.jQueryBox.getParam('width',_linkHref),
						_flashHeight = $.jQueryBox.getParam('height',_linkHref);
					var _movie = 'http://www.youtube.com/v/'+$.jQueryBox.getParam('v',_linkHref);
					_linkHref = $.jQueryBox.remParam(['width','height'], _linkHref)
					if($.jQueryBox.options.autoplay) _movie += "&autoplay=1";
					_toInject = $($.jQueryBox.options.flashMarkup.replace(/{width}/g,_flashWidth).replace(/{height}/g,_flashHeight).replace(/{wmode}/g,$.jQueryBox.options.wmode).replace(/{path}/g,_movie));
					_boxInsert.append(_toInject);
					var _pos = $.jQueryBox.boxSizePosParam(_flashWidth, _flashHeight);
					$.jQueryBox.animateThis(_pos.left, _pos.top, _boxTempWidth, _flashHeight);
					break;
				case 'ajax':
					var _ajaxWidth = $.jQueryBox.getParam('width',_linkHref), _pos,
						_ajaxHeight = $.jQueryBox.getParam('height',_linkHref);
					if (_ajaxWidth && _ajaxHeight) {
						_linkHref = $.jQueryBox.remParam(['width','height'], _linkHref);
						_pos = $.jQueryBox.boxSizePosParam(_ajaxWidth, _ajaxHeight);
					}
					$.ajax({
						url:_linkHref,
						type:'POST',
						success:function(_html){
							var _htmlClone = $(_html);
							if (!_ajaxWidth && !_ajaxHeight) {
								_body.append(_htmlClone);
								_ajaxWidth = _htmlClone.outerWidth(true);
								_ajaxHeight = _htmlClone.outerHeight(true);
								_htmlClone.remove();
								_pos = $.jQueryBox.boxSizePosParam(_ajaxWidth, _ajaxHeight);
							}
							_toInject = $($.jQueryBox.options.imageInlineHTML).html(_html);
							_boxInsert.append(_toInject);
							if (!_btnClose.length ) {
								_btnClose = $($.jQueryBox.options.boxBtnClose, _boxInsert);
								_btnClose.click($.jQueryBox.close);
								_btnClose = [];
							}
							$.jQueryBox.animateThis(_pos.left, _pos.top, _boxTempWidth, _ajaxHeight);
						},
						error: function(){alert('ajax error!')}
					});
					break;
				case 'quicktime':
					var _quicktimeWidth = $.jQueryBox.getParam('width',_linkHref),
						_quicktimeHeight = $.jQueryBox.getParam('height',_linkHref);
						_quicktimeHeight += 15;
					_linkHref = $.jQueryBox.remParam(['width','height'], _linkHref);
					_toInject = $($.jQueryBox.options.quicktimeMarkup.replace(/{width}/g,_quicktimeWidth).replace(/{height}/g,_quicktimeHeight).replace(/{wmode}/g,$.jQueryBox.options.wmode).replace(/{path}/g,_linkHref).replace(/{autoplay}/g,$.jQueryBox.options.autoplay));
					var _pos = $.jQueryBox.boxSizePosParam(_quicktimeWidth, _quicktimeHeight);
					_boxInsert.hide().append(_toInject);
					$.jQueryBox.animateThis(_pos.left, _pos.top, _boxTempWidth, _quicktimeHeight);
					break;
			}
		};
		$.jQueryBox.close = function(){
			if ($.jQueryBox.options.callbackBeforeClose(_box)) {
				_box.fadeOut($.jQueryBox.options.boxFadeDuration, function(){
					_boxInsert.empty();
					_overlay.fadeOut($.jQueryBox.options.overlayFadeDuration, function (){
						$.jQueryBox.options.callbackClose(_box);
						if($.browser.msie && $.browser.version == 6) $('select').css('visibility','visible');	
					});
				});
			}
			return false;
		};
		$.jQueryBox.animateThis = function(_leftPos, _topPos, _widthBox, _heightBox){
			_loadIco.hide();
			_box.animate({
				'left':_leftPos,
				'top':_topPos,
				'width':_widthBox
			}, {duration:$.jQueryBox.options.boxAnimate});
			_boxInsert.animate({
				'height':_heightBox
			}, {duration:$.jQueryBox.options.boxAnimate, complete:function(){
				_boxInsert.animate({opacity:1},{duration:$.jQueryBox.options.boxContentFadeDuration, queue:false, complete:function(){
					_boxInsert.css('opacity','auto');	
				}});
				if (_description.text() != '')
					_description.fadeIn($.jQueryBox.options.boxContentFadeDuration);
				$.jQueryBox.options.callbackShow(_box);
			}});
		};
		// event func
		$.jQueryBox.next = function(){
			if (_toInject) _toInject.unbind('load');
			_current++;
			if (_current >= _gallerys[_currentGallery].length) _current = 0;
			_gallerys[_currentGallery].eq(_current).trigger('click');
			return false;
		}
		$.jQueryBox.prev = function(){
			if (_toInject) _toInject.unbind('load');
			_current--;
			if (_current < 0) _current = _gallerys[_currentGallery].length - 1;
			_gallerys[_currentGallery].eq(_current).trigger('click');
			return false;
		}
		
		// add events
		$(_gallerys).each(function(j, _galleryLinks){
			$(_galleryLinks).each(function(_num){
				var _link = $(this);
				_link.click(function(){
					_currentGallery = j;
					_current = _num;
					$.jQueryBox.boxShow(this.href, _galleryLinks.length);
					_description.text($(this).attr('title'));
					return false;
				});
			});
		});
		_btnNext.click($.jQueryBox.next);
		_btnPrev.click($.jQueryBox.prev);
		if (_btnClose.length)
			_btnClose.click($.jQueryBox.close);
			
		if ($.jQueryBox.options.closeBoxByFader)
			_overlay.click(function(e){if (e.target == _overlay.get(0)) $.jQueryBox.close();});
		$(document).keydown(function(e){
			if(_overlay.is(':visible'))
			switch(e.keyCode){
				case 37: $.jQueryBox.next();break;
				case 39: $.jQueryBox.prev();break;
				case 27: $.jQueryBox.close();break;
			};
	    });
	}
})(jQuery);

