// JavaScript Document
var ImageViewer = Class.create(Abstract, {
	initialize: function(controls, images){
		this.controls = controls;
		this.images = images;
		
		if(this.controls.size() > 0){ // make sure there are items on the page that need our script
			this.controls.invoke('observe', 'click', this.click.bind(this));
			this.build();
		}
	},
	
	click: function(e){
		Event.stop(e);
		
		element = Event.findElement(e, 'a');
		
		this.moveTo(element, element.readAttribute('href'));
		
		if(element.hasClassName('imageview')){
			this.show()
			}
	},
	
	build: function(){
		var element = Builder.node('div', { id:'imageViewer' }, [
										Builder.node('div', {id: 'iv_canvas'})							 
									]);
		element = $(element);
		
		this.images.each(function(elm, index){
			element.insert({bottom: 
				Builder.node('a', {
					className: 'iv_control', 
					href: this.controls[index].readAttribute('href'),
					style: 'background-image:url(' + elm.first().readAttribute('src') + ');'
				},
				'img' + index)			   
			});	  
		}, this);
		
		element.childElements().invoke('observe', 'click', this.click.bind(this));
		
		element.hide();
		
		document.body.insert({bottom: element});
	},
	
	moveTo: function(element, href){
		
		$('iv_canvas').update(
				Builder.node('img', {src: href, id: 'iv_image'})				  
			);
		$('iv_image').hide();
		$('iv_image').appear();
		
	},
	
	show: function(){
		Lightview.show({
			href: '#imageViewer',
				options: {
					topclose: true,
					autosize:true,
					viewport:true
				}
		});
	}
});

document.observe('lightview:loaded', function() {
  var imageviewer = new ImageViewer($$('a.imageview'), $$('a.imageview').invoke('childElements'));
});