window.addEvent('load', function() {
	
	if (!document.getElementById('plany')) { return; }
	
	var imgmap = $('plany'),
		upper = imgmap.getElement('.upper'),
		pietra = $$('.pietro'),
				
		getImgID = function(str) {
			return 'photo' + str.match(/#[a-z]+([0-9]+_[0-9]+)$/)[1];
		},
		
		getPietroID = function(str) {
			return str.match(/#(.+)$/)[1];
		},
		
		getPietroNr = function(str) {
			return str.replace('pietro', '').toInt();
		},
		
		getMaxSize = function(imgSize, width, height) {
			var res = {};
			
			if (imgSize.x <= width && imgSize.y <= height) {
				return imgSize;
			}

			if (imgSize.x - width > imgSize.y - height) {
				res.x = width;
				res.y = Math.ceil((res.x / imgSize.x) * imgSize.y);
			} else {
				res.y = height;
				res.x = Math.ceil((res.y / imgSize.y) * imgSize.x);
			}

			return res;
		},
		
		getCenterPosition = function(dim, width, height) {
			return {
				x: Math.ceil(width / 2 - (dim.x / 2)),
				y: Math.ceil(height / 2 - (dim.y / 2))
			}
		};
	
	
	imgmap.getElements('.top a').each(function(link) {
		
		var id = getPietroID(link.href),
			target = $(id);
		
		link.addEvent('click', function(e) {
			e.stop();
			
			if (!target.hasClass('hide')) {
				return;
			}
			
			target.getParent().getElements('.pietro').addClass('hide');
			target.removeClass('hide');
		});
	});
	
	
	pietra.each(function(pietro) {
		
		var pietroNr = getPietroNr(pietro.id);
		
		pietro.getElements('area').each(function(area) {

			var id = getImgID(area.href),
				photo = $(id),
				mainPhoto = $('photo' + pietroNr + '_0'),
				img = $(id.replace('photo', 'mieszkanie')),
				size = imgmap.getSize(),
				width = size.x - 8,
				height = size.y - 8,
				maxSize = getMaxSize(img.getSize(), width, height),
				position = getCenterPosition(maxSize, width, height);
			
			img.addClass('hide');
			
			area.addEvents({
				'mouseenter': function(e) {
					photo.removeClass('hide');
					mainPhoto.addClass('hide');
				},
				'mouseleave': function(e) {
					photo.addClass('hide');
					mainPhoto.removeClass('hide');
				},
				'click': function(e) {
					e.stop();
					
					img.setStyles({
						'width': maxSize.x,
						'height': maxSize.y,
						'top': position.y,
						'left': position.x
					});
					img.removeClass('hide');
					
					upper.setStyles({
						'width': width,
						'height': height
					});
					upper.removeClass('hidden');
				}
			});
			
		});
	});

	upper.addEvent('click', function(e) {
		this.getElement('img[class!=hide]').addClass('hide');
		this.addClass('hidden');
	});	
	
});
