var newImageCaption = new Class({
	Implements: [Options,Events],

	options: {
		imageClass:'',
		captionStyle:{},
		buttonStyle:{}
	},

	initialize: function(options) {
		this.setOptions(options);
		this.imgArray = $$('img.'+this.options.imageClass);
		this.imgArray.store('classInstance',this);
		
		this.elementArray = [];

		this.imgArray.each(function(item,index){
			item.setStyle('position','relative');
			var imageDimensions = {
				width:item.offsetWidth,
				height:item.offsetHeight,
				left:item.offsetLeft,
				top:item.offsetTop
			}
			var imageId = item.id;
			var imageZIndex = $(item).getStyle('z-index').toInt();
			var uniqueId = this.uniqueId();

			var coverElement = new Element('DIV', {
				'styles':{
					'position':'absolute',
					'left':imageDimensions.left,
					'top':imageDimensions.top,
					'width':imageDimensions.width,
					'height':imageDimensions.height,
					'z-index':1000,
					'overflow':'hidden',
					'z-index':imageZIndex+1
				},
				'id':'cover_'+uniqueId
			});

			var captionElement = new Element('DIV', {
				'styles':{
					'position':'absolute',
					'top':-10000,
					'left':0,
					'width':imageDimensions.width
				},
				'html':item.title,
				'id':'caption_'+uniqueId
			});

			captionElement.setStyles(this.options.captionStyle);

			var buttonElement = new Element('DIV', {
				'styles':{
					'position':'absolute',
					'bottom':0,
					'left':0
				},
				'html':'show caption',
				'id':'button_'+uniqueId
			});

			buttonElement.setStyles(this.options.buttonStyle);

			$(buttonElement).addEvent('click', this.showHideCaption.bind(this));

			coverElement.appendChild(captionElement);
			coverElement.appendChild(buttonElement);

			coverElement.store('targetImage',item);
			this.elementArray[this.elementArray.length] = coverElement;
		},this);

		this.elementArray.each(function(item,index){
			var targetImage = item.retrieve('targetImage');

			targetImage.getParent().setStyle('position','relative');
			targetImage.getParent().appendChild(item);
			var targetId = item.id.split("_")[1];
			var targetCaption = $("caption_" + targetId);
			$(targetCaption).setStyle('top',-$(targetCaption).getSize().y.toInt());
			$(targetCaption).store('trueTop',-$(targetCaption).getSize().y.toInt());
		});
	},

	showHideCaption: function(e) {
		var targetId = e.target.id.split("_")[1];
		var targetCurTop = $('caption_' + targetId).getStyle('top').toInt();
		if (targetCurTop == 0) {
			$('caption_' + targetId).morph({'top':$('caption_' + targetId).retrieve('trueTop')});
			$('button_' + targetId).set('html','show caption');
		} else {
			$('caption_' + targetId).morph({'top':0});
			$('button_' + targetId).set('html','hide caption');
		}
	},

	uniqueId: function() {
		return ((new Date()).getTime() + "" + Math.floor(Math.random() * 1000000)).substr(0, 18);
	}
});