// JavaScript Document

var CMS_Gallery = Class.create();
CMS_Gallery.prototype = {
	activeImg: -1,
	preload: [],
	options: [],
	cache: [],
	boundHandlerMethod: undefined,
	
	initialize : function(id,options) {
		if (typeof(options)=="undefined")	options = {};
		
		this.options = Object.extend({
			loadingImg:		_common_url + 'gfx/gallery_loading.gif',
			closeImg:		_common_url + 'gfx/gallery_close.png',
			closeText:		'Klik for at lukke galleriet',
			overlayOpacity: 0.5,
			imgMargin: 10,
			pageMargin: 30,
			minSize: 200,
			orientation: 	'horizontal',
			
			scroll_back:	false,
			scroll_forward:	false,
			scroll_trigger:	'click',
			scroll_untrigger: false,
			scroll_step:	110,
			scroll_delay:	500
		}, options);
		
		if (this.options.scroll_trigger != "click")
			this.options.scroll_untrigger = (this.options.scroll_trigger == "mousedown") ? "mouseup" : "mouseout";
		
		this.id = id;
		this.anchors = $(id).getElementsBySelector("span > div > a").invoke("observe","click",this.openImg.bind(this));
		this.images = $(id).getElementsBySelector("span > div > a > img");
		
		if (this.options.scroll_back && this.options.scroll_forward)
		{
			$(this.options.scroll_back).observe(this.options.scroll_trigger,this.scrollBackStart.bindAsEventListener(this));
			$(this.options.scroll_forward).observe(this.options.scroll_trigger,this.scrollForwardStart.bindAsEventListener(this));
		}
	},
	
	scrollBackStart : function() {
		this.scrollBack();
		
		if (this.options.scroll_trigger != "click")
		{
			if (typeof(this.scroll_interval)!="undefined")	clearTimeout(this.scroll_interval);
			this.scroll_interval = setInterval(this.scrollBack.bind(this),this.options.scroll_delay);
			
			$(this.options.scroll_back).observe(this.options.scroll_untrigger,(function() {
				clearTimeout(this.scroll_interval);
				delete(this.scroll_interval);
				
				$(this.options.scroll_back).stopObserving(this.options.scroll_untrigger);
			}).bindAsEventListener(this));
		}
	},

	scrollForwardStart : function() {
		this.scrollForward();
		
		if (this.options.scroll_trigger != "click")
		{
			if (typeof(this.scroll_interval)!="undefined")	clearTimeout(this.scroll_interval);
			this.scroll_interval = setInterval(this.scrollForward.bind(this),this.options.scroll_delay);
			
			$(this.options.scroll_forward).observe(this.options.scroll_untrigger,(function() {
				clearTimeout(this.scroll_interval);
				delete(this.scroll_interval);
				
				$(this.options.scroll_forward).stopObserving(this.options.scroll_untrigger);
			}).bindAsEventListener(this));
		}
	},
	
	scrollBack : function(event) {
		if (this.options.orientation == 'horizontal')	$(this.id).scrollLeft = ($(this.id).scrollLeft - this.options.scroll_step) - 0;
		else											$(this.id).scrollTop = ($(this.id).scrollTop - this.options.scroll_step) - 0;
	},

	scrollForward : function(event) {
		if (this.options.orientation == 'horizontal')	$(this.id).scrollLeft = ($(this.id).scrollLeft + this.options.scroll_step) - 0;
		else											$(this.id).scrollTop = ($(this.id).scrollTop + this.options.scroll_step) - 0;
	},
	
	openImg : function(event) {
		this.activeImg = Event.findElement(event,'span').previousSiblings().select(function(el) {return $(el).tagName.toLowerCase() == 'span';}).size();
		
		this.prepare();
		this.loadImg();
	},
	
	prevImg : function(event) {
		event.stop();
		
		if (this.activeImg > 0)
		{
			this.activeImg--;
			
			this.reset();
			this.loadImg();
		}
	},
	
	nextImg : function(event) {
		event.stop();
		
		if (this.images.size()-1 > this.activeImg)
		{
			this.activeImg++;
			
			this.reset();
			this.loadImg();
		}
	},
	
	loadImg : function() {
		setTimeout((function() {
		var activeImg = this.images[this.activeImg];
		var activeA = activeImg.up('a');
		
		
		var title = activeA.readAttribute("title");
		var description = (title != "") ? "<h2>"+title+"</h2>": "";
		description = description + activeA.readAttribute("description");		
		this.description.update(description);
		
		if (typeof(this.cache[this.activeImg]) == "undefined")
		{
			this.cache[this.activeImg] = new Image();
			this.cache[this.activeImg].src = activeA.readAttribute("href");

			var currentImg = this.activeImg;
			this.cache[this.activeImg].onload = (function(){
				if (currentImg == this.activeImg && this.img.src != this.cache[this.activeImg].src)
				{
					this.img.src = this.cache[this.activeImg].src;
					this.showImg(this.cache[this.activeImg].width,this.cache[this.activeImg].height);
				}
			}).bind(this);
		}
//		else 
		if (this.cache[this.activeImg].complete && this.img.src != this.cache[this.activeImg].src)
		{
			this.cache[this.activeImg].onload();
		}
		
							 }).bind(this),50);
	},
	
	showLoading : function() {
		this.img.hide();
		this.description.hide();
		this.closeButton.hide();
		this.prevLink.hide();
		this.nextLink.hide();
		
		this.disableNavigation();
		
		this.imgLoading.show();
	},
	
	showImg : function() {
		var size = this.getSize();
		
		this.img.writeAttribute({'width':size.width+'px','height':size.height+'px'}).setStyle({'width':size.width+'px','height':size.height+'px'});
		
		new Effect.Transform(this.imgWrapper,{
//		this.imgWrapper.setStyle({
			"width" : (size.width + this.options.imgMargin*2) +"px",
			"height" : (size.height + this.options.imgMargin*3 + this.description.getHeight()) +"px"
		},{
			"endEffect" : (function () {
				this.imgLoading.hide();
				this.img.show();
				this.description.show();
				this.closeButton.show();
				
				this.enableNavigation();
			}).bind(this)
		});
		
/*		this.imgLoading.hide();
		this.img.show();
		this.description.show();
		this.closeButton.show();

		this.enableNavigation();*/
	},

	getSize : function() {
		var width  = this.img.getWidth();
		var height = this.img.getHeight();
		this.description.setStyle({'width':width+'px'});
		
		var dimensions = document.viewport.getDimensions();
		var max_width = dimensions.width - 2*this.options.pageMargin - this.options.imgMargin*2;
		var max_height = dimensions.height - 2*this.options.pageMargin - this.options.imgMargin*3 - this.description.getHeight();
		
		if (width > max_width || height > max_height)
		{
			if ( (max_width/max_height) > (width/height) )
			{
				width = (max_height * (width/height)).round();
				this.description.setStyle({'width':width+'px'});
				height = dimensions.height - 2*this.options.pageMargin - this.options.imgMargin*3 - this.description.getHeight();
			}
			else if ( (max_width/max_height) < (width/height) )
			{
				width = max_width;
				this.description.setStyle({'width':width+'px'});
				height = (max_width / (width/height)).round();
			}
		}
		
		return {"width" : width, "height": height};
	},
	
	close : function(event) {
		this.activeImg = -1;
		
		
/*		Effect.Fade(this.wrapper,{
			"endEffect" : (function() {
				this.wrapper.remove();				
				this.reset();
			}).bind(this)
		});*/
		
		if ($(this.wrapper).descendantOf(document.body))
		{
			this.overlay.remove();
			this.wrapper.remove();
		}
		
		this.reset();
	},
	
	prepare : function() {
		if (!this.wrapper)
		{
			this.overlay = new Element("div",{"title":this.options.closeText}).addClassName('PopupOverlay').setStyle({"zIndex": 99 ,'opacity' : this.options.overlayOpacity,'cursor':'pointer'}).observe("click",this.close.bind(this));
			
			this.imgLoading = new Element('img',{'src' : this.options.loadingImg}).addClassName('PopupLoading');
			this.description = new Element("div",{}).addClassName('GalleryDescription').setStyle({"margin" : this.options.imgMargin+"px","marginTop" : "0px"});
			this.img = new Element("img",{}).setStyle({"margin" : this.options.imgMargin+"px"});
			this.closeButton = new Element("img",{"src" : this.options.closeImg,"title":this.options.closeText}).addClassName("PopupClose").observe("click",this.close.bind(this)).show();
			
			this.prevLink = new Element("a",{"href":"javascript:void(0);"}).addClassName("GalleryPrevLink").observe("click",this.prevImg.bind(this));
			this.nextLink = new Element("a",{"href":"javascript:void(0);"}).addClassName("GalleryNextLink").observe("click",this.nextImg.bind(this));
			this.navigation = new Element("div").addClassName("GalleryNavigation").insert(this.prevLink).insert(this.nextLink);
			
			this.imgWrapper = new Element("div").addClassName('PopupContentWrapper').setStyle({"top":this.options.pageMargin+"px"}).insert(this.img).insert(this.description).insert(this.imgLoading).insert(this.navigation).insert(this.closeButton)/*.observe("click",this.close.bind(this))*/;
		
			this.wrapper = new Element("div").setStyle({"zIndex": 100 }).addClassName('PopupWrapper').writeAttribute('popup_type','gallery').writeAttribute('popup_id',this.id).insert(this.imgWrapper);
		}
				
		this.reset();
		
		if (!$(this.wrapper).descendantOf(document.body))
		{
			this.wrapper.hide();
			this.imgWrapper.setStyle({"width": this.options.minSize + "px","height":this.options.minSize + "px"});
			
			$(document.body).insert(this.overlay);
			$(document.body).insert(this.wrapper);
			
			this.wrapper.show();
//			Effect.Appear(this.wrapper);
		}
	},
	
	reset : function() {
		this.showLoading();
		
		this.description.update();
		this.img.writeAttribute({"src":false,"alt":false,"title":false,"width":false,"height":false}).setStyle({"width":"","height":""});
	},
	
	enableNavigation : function() {
		this.navigation.show();
		if (this.activeImg > 0)						this.prevLink.show();
		if (this.activeImg < this.images.size()-1)	this.nextLink.show();
	},

	disableNavigation : function() {
		this.navigation.hide();

	}	
};
