// JavaScript Document

var CMS_Gallery = Class.create();
CMS_Gallery.prototype = {
	activeImg: -1,
	preload: [],
	options: [],
	cache: [],
	images: [],
	boundHandlerMethod: undefined,
	
	initialize : function(id,options) {
		if (!$(id))	return false;
		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: 300,
			orientation: 	'horizontal',
			
			autoOpen: false,
			
			scroll_back:	false,
			scroll_forward:	false,
			scroll_trigger:	'click',
			scroll_untrigger: false,
			scroll_step:	110,
			scroll_delay:	500,
			
			scroll_wheel: 0,
			autoscroll: false,
			
			circularFlow: false
			
		}, options);
		
		if (this.options.scroll_wheel>0 )
		{
			if (this.options.scroll_wheel > $(id).childElements().size())
				this.options.scroll_wheel = 0;
			else
			{
				var span = 	$(id).down();
				$(id).insert({'bottom' : ' '}).insert({'bottom' : span.clone(true)});
				for (i=1; i<this.options.scroll_wheel; i++)
				{
					span = span.next();
					$(id).insert({'bottom' : ' '}).insert({'bottom' : span.clone(true)});
				}
			}
		}
		
		
		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 = this.options.images;
		this.numOfImages = $H(this.options.images).size();
		
		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));
		}
		
		if (this.options.autoOpen!==false)
			this.openImgBySortOrder(this.options.autoOpen);
			
		if (this.options.autoscroll!==false)
			this.autoscroll();
	},
	
	autoscroll : function() {
		this.scrollForward(1);
	
		if (typeof(this.scroll_interval)!="undefined")	clearTimeout(this.scroll_interval);
		this.scroll_interval = setInterval(this.scrollForward.bind(this,1),this.options.scroll_delay);
	},
	
	scrollBackStart : function() {
		this.scrollBack(this.options.scroll_step);
		
		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_step),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(this.options.scroll_step);
		
		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_step),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(scroll_step) {
		if (this.options.orientation == 'horizontal')
		{
			if (this.options.scroll_wheel>0 && $(this.id).scrollLeft-scroll_step-0 < 0)
				$(this.id).scrollLeft = $(this.id).scrollWidth - $(this.id).getWidth() + ($(this.id).scrollLeft-scroll_step-0);
			else
				$(this.id).scrollLeft = ($(this.id).scrollLeft - scroll_step) - 0;
		}
		else
		{
			if (this.options.scroll_wheel>0 && $(this.id).scrollTop -scroll_step-0 < 0)
				 $(this.id).scrollTop = $(this.id).scrollHeight - $(this.id).getHeight() + ($(this.id).scrollTop-scroll_step-0);
			else
				$(this.id).scrollTop = ($(this.id).scrollTop - scroll_step) - 0;
		}
	},

	scrollForward : function(scroll_step) {
		if (this.options.orientation == 'horizontal')
		{
			if (this.options.scroll_wheel>0 && $(this.id).scrollLeft+scroll_step-0 > $(this.id).scrollWidth - $(this.id).getWidth())
				$(this.id).scrollLeft = 0 - ($(this.id).scrollWidth - $(this.id).getWidth()) + ($(this.id).scrollLeft+scroll_step-0);
			else
				$(this.id).scrollLeft = ($(this.id).scrollLeft + scroll_step) - 0;
		}
		else
		{
			if (this.options.scroll_wheel>0 && $(this.id).scrollTop+scroll_step-0 > $(this.id).scrollHeight - $(this.id).getHeight())
				$(this.id).scrollTop = 0 - ($(this.id).scrollHeight - $(this.id).getHeight()) + ($(this.id).scrollTop+scroll_stepp-0);
			else
				$(this.id).scrollTop = ($(this.id).scrollTop + scroll_step) - 0;
		}
	},
	
	openImg : function(event) {
		if (typeof(this.scroll_interval)!="undefined")	{clearTimeout(this.scroll_interval); delete(this.scroll_interval);}
		
		
		this.activeImg = Event.findElement(event,'a').readAttribute('sort_order');
		
		this.prepare();
		this.loadImg();
	},
	
	openImgBySortOrder : function(sort_order) {
		if (typeof(this.scroll_interval)!="undefined")	{clearTimeout(this.scroll_interval); delete(this.scroll_interval);}
		
		this.activeImg = sort_order;
		
		this.prepare();
		this.loadImg();
	},
	
	prevImg : function(event) {
		event.stop();
		
		if (this.activeImg > 0)
			this.activeImg--;
		else if (this.options.circularFlow!==false)
			this.activeImg = this.numOfImages -1;
		else
			return false;
	
		this.reset();
		this.loadImg();
	},
	
	nextImg : function(event) {
		event.stop();
		
		if (this.numOfImages-1 > this.activeImg)
			this.activeImg++;
		else if (this.options.circularFlow!==false)
			this.activeImg=0;
		else
			return false;
		
		this.reset();
		this.loadImg();
	},
	
	loadImg : function() {
		setTimeout((function() {
			var activeImg = this.images[this.activeImg];
			
			var description = ((activeImg.title != "") ? "<h2>"+activeImg.title+"</h2>": "") + activeImg.description;
			this.description.update(description);
			this.buttons.update(activeImg.buttons);
			
			if (typeof(this.cache[this.activeImg]) == "undefined")
			{
				this.cache[this.activeImg] = new Image();
				this.cache[this.activeImg].src = activeImg.src;
	
				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.buttons.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'});
		this.navigation.setStyle({'height': (size.height+this.options.imgMargin) + 'px'});

		new Effect.Transform(this.imgWrapper,{
//		this.imgWrapper.setStyle({
			"width" : (Math.max(size.width,this.options.minSize) + this.options.imgMargin*2) +"px",
			"height" : (size.height + this.options.imgMargin*3 + this.description.getHeight()) +"px"
		},{
			"endEffect" : (function () {
				this.imgLoading.hide();
				if (size.width < this.options.minSize)
					this.img.setStyle({"marginLeft" : ((this.options.minSize-size.width)/2+this.options.imgMargin)+"px", "marginRight" : ((this.options.minSize-size.width)/2+this.options.imgMargin)+"px"});
				else
					this.img.setStyle({"marginLeft" : this.options.imgMargin+"px", "marginRight" : this.options.imgMargin+"px"});
				
				this.img.show();
				this.description.show();
				this.buttons.show();
				this.closeButton.show();
				
				this.enableNavigation();
			}).bind(this)
		});
		
/*		this.imgLoading.hide();
		this.img.show();
		this.description.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':Math.max(this.options.minSize,width)+'px'});

		var dimensions = document.viewport.getDimensions();
		var max_width = dimensions.width - 2*this.options.pageMargin - this.options.imgMargin*2;
		var max_height = Math.max(300,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':Math.max(this.options.minSize,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':Math.max(this.options.minSize,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.buttons = new Element("div",{}).addClassName("GalleryPopupButtons").setStyle({"margin" : this.options.imgMargin+"px"});
			
			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.buttons).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.buttons.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.options.circularFlow)						this.prevLink.show();
		if (this.activeImg < this.numOfImages-1 || this.options.circularFlow)	this.nextLink.show();
	},

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

	}	
};

JEFF = Event;

