$(document).ready(function(){
	$('.popup-example').each(function(){
		$(this).simplebox();
	});
});

var resizeHandler = function(event) {
	var elem = event.data.elem;
	elem.calcWinWidth();
	elem.popup.animate({
		left: elem.winWidth/2 - elem.popup.outerWidth(true)/2
	}, {queue:false, duration: elem.options.duration});
	elem.fader.css({width: elem.winWidth});
}

$.fn.simplebox = function(options) { return new Simplebox(this, options); };

function Simplebox(context, options) { this.init(context, options); };

Simplebox.prototype = {
	options:{},
	init: function (context, options){
		this.options = $.extend({
			duration: 150,
			linkClose: 'a.close, a.btn-close',
			divFader: 'fader',
			faderColor: 'black',
			opacity: 0.80,
			wrapper: '.wrapper',
			linkPopap: '.link-submit'
		}, options || {});
		this.btn = $(context);
		this.select = $(this.options.wrapper).find('select');
		this.initFader();
		this.btnEvent(this, this.btn);
	},
	createPopup: function($this){
		var el = $this.btn.find('> ul > li > a');
		var temp = 	'<div class="popup" id="popup">'+
					'	<div class="hold"><ul class="img">';
		el.each(function(){
			var file = $(this).attr('href');
			var ext = file.substr(file.lastIndexOf('.') + 1).toLowerCase();
			if (ext=="jpg" || ext=="jpeg" || ext=="gif" || ext=="png") {
				temp += '	<li><img src="' + file + '" alt="image" /></li>';
			} else {
				temp += '	<li><embed class="video" src="' + file + '"'
					+ ' autoplay="false" scale="tofit" controller="true" loop="false" pluginspage="http://www.apple.com/quicktime/"/></li>';
			}
		});
		temp += '</ul></div>'+
				'	<div class="title">'+
				'		<a href="#" class="next"><em>next</em><span>Close X</span></a><span>'+el.eq(0).attr('title')+'</span>'+
				'		'+
				'		<a href="#" class="prev">prev</a>'+
				'	</div>'+
				'	<a href="#" class="close">close</a>'+
				'</div>'
		$('body').append($(temp));
		$('div#popup').gallery({
			duration: 250,
			disableBtn: 'hidden',
			listOfSlides: 'div.hold > ul > li'
		});
	},
	btnEvent: function($this, el){
		el.click(function(){
			$this.createPopup($this);
			$this.toPrepare('#popup');
			return false;
		});
	},
	calcWinWidth: function(){
		this.winWidth = $('body').width();
		if ($(this.options.wrapper).width() > this.winWidth) this.winWidth = $(this.options.wrapper).width();
	},
	toPrepare: function(obj){
		this.popup = $(obj);
		this.btnClose = this.popup.find(this.options.linkClose);
		this.submitBtn = this.popup.find(this.options.linkPopap);
		
		if ($.browser.msie) this.select.css({visibility: 'hidden'});
		this.calcWinWidth();
		this.winHeight = $(window).height();
		this.winScroll = $(window).scrollTop();
		
		this.popupTop = this.winScroll + (this.winHeight/2) - this.popup.outerHeight(true)/2;
		if (this.popupTop < 0) this.popupTop = 0;
		this.faderHeight = $(this.options.wrapper).outerHeight();
		if ($(window).height() > this.faderHeight) this.faderHeight = $(window).height();
		
		this.popup.css({
			top: this.popupTop,
			left: this.winWidth/2 - this.popup.outerWidth(true)/2
		}).hide();
		this.fader.css({
			width: this.winWidth,
			height: this.faderHeight
		});
		this.initAnimate(this);
		this.initCloseEvent(this, this.btnClose, true);
		this.initCloseEvent(this, this.submitBtn, false);
		this.initCloseEvent(this, this.fader, true);
	},
	initCloseEvent: function($this, el, flag){
		el.click(function(){
			$this.popup.fadeOut($this.options.duration, function(){
				$this.popup.css({left: '-9999px'}).show();
				if ($.browser.msie) $this.select.css({visibility: 'visible'});
				$this.submitBtn.unbind('click');
				$this.fader.unbind('click');
				$this.btnClose.unbind('click');
				$(window).unbind('resize',resizeHandler);
				if (flag) {
					$this.fader.fadeOut($this.options.duration, function(){
						$this.popup.remove();
					});
				}
				else {
					if ($this.submitBtn.attr('href')) 
						$this.toPrepare($this.submitBtn.attr('href'));
					else 
						$this.toPrepare($this.submitBtn.attr('title'));
				}
			});
			return false;
		});
	},
	initAnimate:function ($this){
		$this.fader.fadeIn($this.options.duration, function(){
			$this.popup.fadeIn($this.options.duration);
		});
		$(window).bind('resize', {elem:$this}, resizeHandler);
		/* $(window).resize(function(){
			$this.calcWinWidth();
			$this.popup.animate({
				left: $this.winWidth/2 - $this.popup.outerWidth(true)/2
			}, {queue:false, duration: $this.options.duration});
			$this.fader.css({width: $this.winWidth});
		}); */
	},
	initFader: function(){
		if ($('div.'+this.options.divFader).length > 0) this.fader = $('div.'+this.options.divFader);
		else{
			this.fader = $('<div class="'+this.options.divFader+'"></div>');
			$('body').append(this.fader);
			this.fader.css({
				position: 'absolute',
				zIndex: 999,
				left:0,
				top:0,
				background: this.options.faderColor,
				opacity: this.options.opacity
			}).hide();
		}
	}
}

$.fn.gallery = function(options) { return new Gallery(this.get(0), options); };
	
	function Gallery(context, options) { this.init(context, options); };
	
	Gallery.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				infinite: false,
				duration: 700,
				slideElement: 1,
				autoRotation: false,
				effect: false,
				listOfSlides: 'ul > li',
				switcher: false,
				disableBtn: false,
				nextBtn: 'a.link-next, a.btn-next, a.next',
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',
				circle: true,
				direction: false,
				event: 'click',
				IE: false,
				autoHeight: false
			}, options || {});
			var _el = $(context).find(this.options.listOfSlides);
			if (this.options.effect) this.list = _el;
			else this.list = _el.parent();
			this.switcher = $(context).find(this.options.switcher);
			this.nextBtn = $(context).find(this.options.nextBtn);
			this.prevBtn = $(context).find(this.options.prevBtn);
			this.count = _el.index(_el.filter(':last'));
			
			if (this.options.switcher) this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
			else this.active = _el.index(_el.filter('.active:eq(0)'));
			if (this.active < 0) this.active = 0;
			this.last = this.active;
			
			this.woh = _el.outerWidth(true);
			if (!this.options.direction) this.installDirections(this.list.parent().width());
			else {
				this.woh = _el.outerHeight(true);
				this.installDirections(this.list.parent().height());
			}
			
			if (!this.options.effect) {
				this.rew = this.count - this.wrapHolderW + 1;
				if (!this.options.direction) this.anim = '{marginLeft: -(this.woh * this.active)}';
				else this.anim = '{marginTop: -(this.woh * this.active)}';
				eval('this.list.css('+this.anim+')');
			}
			else {
				this.rew = this.count;
				this.list.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
				this.switcher.removeClass('active').eq(this.active).addClass('active');
				if(this.options.autoHeight) this.list.parent().css({height: this.list.eq(this.active).outerHeight()});
			}
			this.flag = true;
			if (this.options.infinite){
				this.count++;
				this.active += this.count;
				this.list.append(_el.clone());
				this.list.append(_el.clone());
				eval('this.list.css('+this.anim+')');
			}
			
			this.initEvent(this, this.nextBtn, true);
			this.initEvent(this, this.prevBtn, false);
			if (this.options.disableBtn) this.initDisableBtn();
			if (this.options.autoRotation) this.runTimer(this);
			if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
		},
		closeBtn: '',
		initDisableBtn: function(){
			this.prevBtn.removeClass('prev-'+this.options.disableBtn);
			this.nextBtn.removeClass('next-'+this.options.disableBtn);
			if (this.active == 0 || this.count+1 == this.wrapHolderW) this.prevBtn.addClass('prev-'+this.options.disableBtn);
			if (this.active == 0 && this.count+1 == 1 || this.count+1 <= this.wrapHolderW) this.nextBtn.addClass('next-'+this.options.disableBtn);
			if (this.active == this.rew) this.nextBtn.addClass('next-'+this.options.disableBtn);
			if (typeof this.closeBtn != 'string') this.closeBtn.unbind('click');
			this.closeBtn = $('a.next-hidden > span');
			this.closeBtn.unbind('click').click(function(){
				$('#popup a.close').trigger('click');
				return false;
			});
		},
		installDirections: function(temp){
			this.wrapHolderW = Math.ceil(temp / this.woh);
			if (((this.wrapHolderW - 1) * this.woh + this.woh / 2) > temp) this.wrapHolderW--;
		},
		fadeElement: function(){
			if ($.browser.msie && this.options.IE){
				this.list.eq(this.last).css({opacity:0});
				this.list.removeClass('active').eq(this.active).addClass('active').css({opacity:'auto'});
			}
			else{
				this.list.eq(this.last).animate({opacity:0}, {queue:false, duration: this.options.duration});
				this.list.removeClass('active').eq(this.active).addClass('active').animate({
					opacity:1
				}, {queue:false, duration: this.options.duration, complete: function(){
					$(this).css('opacity','auto');
				}});
			}
			if(this.options.autoHeight) this.list.parent().animate({height: this.list.eq(this.active).outerHeight()}, {queue:false, duration: this.options.duration});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function($this){
			if (!$this.options.infinite) eval('$this.list.animate('+$this.anim+', {queue:false, easing:\'easeOutQuad\',duration: $this.options.duration});');
			else eval('$this.list.animate('+$this.anim+', $this.options.duration, \'easeOutQuad\', function(){ $this.flag = true });');
			if ($this.options.switcher) $this.switcher.removeClass('active').eq($this.active / $this.options.slideElement).addClass('active');
			$($this.list).find("embed").each(function() {this.Stop();});
			$($this.list).find("li:eq(" + $this.active + ")").children("embed").each(function() {this.Play();});
		},
		runTimer: function($this){
			if($this._t) clearTimeout($this._t);
			$this._t = setInterval(function(){
				if ($this.options.infinite) $this.flag = false;
				$this.toPrepare($this, true);
			}, this.options.autoRotation);
		},
		initEventSwitcher: function($this, el){
			el.bind($this.options.event, function(){
				$this.active = $this.switcher.index($(this)) * $this.options.slideElement;
				if($this._t) clearTimeout($this._t);
				if ($this.options.disableBtn) $this.initDisableBtn();
				if (!$this.options.effect) $this.scrollElement($this);
				else $this.fadeElement();
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		initEvent: function($this, addEventEl, dir){
			addEventEl.bind($this.options.event, function(){
				if ($this.flag){
					if ($this.options.infinite) $this.flag = false;
					if($this._t) clearTimeout($this._t);
					$this.toPrepare($this, dir);
					if ($this.options.autoRotation) $this.runTimer($this);
				}
				return false;
			});
		},
		toPrepare: function($this, side){
			if (!$this.options.infinite){
				if (($this.active == $this.rew) && $this.options.circle && side) $this.active = -$this.options.slideElement;
				if (($this.active == 0) && $this.options.circle && !side) $this.active = $this.rew + $this.options.slideElement;
				for (var i = 0; i < $this.options.slideElement; i++){
					if (side) { if ($this.active + 1 <= $this.rew) $this.active++; }
					else { if ($this.active - 1 >= 0) $this.active--; }
				};
			}
			else{
				if ($this.active >= $this.count + $this.count && side) $this.active -= $this.count;
				if ($this.active <= $this.count-1 && !side) $this.active += $this.count;
				eval('$this.list.css('+$this.anim+')');
				if (side) $this.active += $this.options.slideElement;
				else $this.active -= $this.options.slideElement;
			}
			if (this.options.disableBtn) this.initDisableBtn();
			if (!$this.options.effect) $this.scrollElement($this);
			else $this.fadeElement();
		},
		stop: function(){
			if (this._t) clearTimeout(this._t);
		},
		play: function(){
			if (this._t) clearTimeout(this._t);
			if (this.options.autoRotation) this.runTimer(this);
		}
	}
