document.observe('dom:loaded', function() {
	new ViewerMenu();
	new ImageViewer();
});

var ImageViewer = Class.create({
	images: {},
	limitWidth: null,
	iamgeViewer: null,
	viewerContentArea : null,
	titleBar: null,
	initialize: function() {
		var content = $('SectionView').down('.content');
		this.limitWidth = content.getWidth() - 50;
		content.select('img').each( this.init.bind(this) );
		this.imageViewer = new Element('div',{id: 'idgImageViewer'});
		this.viewerContentArea = new Element('div',{className: 'content'});
		this.titleBar = new Element('div',{className: 'titleBar'});
		this.imageViewer.insert(this.titleBar);
		this.imageViewer.insert(this.viewerContentArea);
		this.imageViewer.setStyle({'display':'none'});
		$('container').insert(this.imageViewer);
	},
	init: function ( unit, i ) {
			if ( unit.getWidth() > this.limitWidth ) {
				this.images['resized'+i] = {'width' : unit.getWidth(), 'height' : unit.getHeight(), 'src': unit.src };
				unit.addClassName('resized');
				unit.id = 'resized' + i;
				unit.observe('click', this.onImgClick.bind(this));
			}
	},
	onImgClick: function ( ev ) {
		var el = ev.element();
		var id = el.id;
		var image = new Element('img',{
			'width': this.images[id].width,
			'height' : this.images[id].height,
			'src' : this.images[id].src
		}).observe('click',this.removeViewer.bind(this));

		this.titleBar.innerHTML = el.alt;
		this.viewerContentArea.update(image);
		this.imageViewer.show();
		this.imageViewer.setStyle({'top': el.cumulativeScrollOffset().top + 100 + 'px', 'marginLeft': - parseInt(this.images[id].width/2) + 'px' }) ;
	},
	removeViewer: function (ev) {
		this.imageViewer.hide();
	}
});

var ViewerMenu = Class.create({
	content: null,
	fontSize: null,
	initialize: function() {
		this.content = $('SectionView').down('.content');
		this.fontSize = parseInt(this.content.getStyle('font-size').substr(0,2));

		$$('.viewerMenu .toBig').invoke('observe','click',this.onToBigClick.bind(this));
		$$('.viewerMenu .toSmall').invoke('observe','click',this.onToSmallClick.bind(this));
		$$('.viewerMenu .toPrint').invoke('observe','click',this.onToPrintClick.bind(this));
		$$('.viewerMenu .toMail').invoke('observe','click',this.onToMailClick.bind(this));
		$('mailSender').down('.btnCancel').observe('click',this.onToMailClick.bind(this));
	},
	onToBigClick: function() {
		this.fontSize += 1;
		this.content.setStyle({fontSize: this.fontSize + 'px'});
	},
	onToSmallClick: function() {
		this.fontSize -= 1;
		this.content.setStyle({fontSize: this.fontSize + 'px'});
	},
	onToPrintClick: function() {
		var idx = $F('idx');
		var printView = window.open('/main/popup/printView?idx='+idx,'_blank','width=800, height=600, top=0, left=0, directory=no, channelmode=no, location=no, menubar=no, titlebar=no, toolbar=no, scrollbars=yes');
	},
	onToMailClick: function() {
		var title = $('SectionView').down('h1').innerHTML;
		$('mailSender').down('h3').innerHTML = title;
		$('mailSender').toggle();
	}
});
