var Globals = Globals || {};
Globals.fx = Globals.fx || {};

Slimbox.scanPage = function() {
	
	Globals.popupImages = $$('div.images div.image, div.images-2 div.image, div.images-l div.image, div.template-img, span.template-img');
	
	var exists = false;
	
	Globals.popupImages.each(function(img){
		
		// check if parent with class 'scale_up' exists
		if(img == null || !img){
			Globals.popupImages.erase(img);
			return;
		}
		
		exists = false;
		
		img.getParents().each(function(el){
			if (el.get('tag') == 'a' && el.hasClass('scale_up')) {
				exists = true;
				return;
			}
		});
		
		if (!exists) {
			Globals.popupImages.erase(img);
			return;
		}
		
		var captionEl = null;
		if($chk(img.getChildren('div.template-low')[0]))
			captionEl = img.getChildren('div.template-low')[0];
		else if($chk(img.getChildren('div.template-verylow')[0]))
			captionEl = img.getChildren('div.template-low')[0];
			
		if($chk(captionEl) && captionEl.get('text', '').trim() == '')
			captionEl.destroy();
		
		img.addEvents({
			'mouseenter': function(){
				this.addClass('over');
			},
			'mouseleave': function(){
				this.removeClass('over');
			}
		});
	});
		
	Globals.popupImages.slimbox({overlayOpacity: 0.9, counterText: '({x}/{y})'}, function(img) {
		var captionEl = img.getParent('.scale_up').getChildren('.caption');
		var caption = $chk(captionEl) ? captionEl.get('text', '') : '';
		var imgSrc = img.getElement('img').get('rel').replace(/^popup\(/, '').replace(/\)$/, '');
		return [
			imgSrc,
			caption
		];
	});
};

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

	options: {},
 	
	initialize: function(options){
		this.setOptions(options);
		
		// build the menu
		this.leftCol = $('left-col');
		
		// scroll the menu
		if (!Browser.Engine.trident) {
			this.menu = $('navi_sub');
			window.addEvent('scroll', function(){
				if (window.getScrollTop() - 228 > 0) 
					this.menu.setStyles({
						'position': 'fixed',
						'top': 0
					});
				else {
					this.menu.setStyles({
						'position': 'relative'
					});
					this.menu.removeProperty
				}
			}.bind(this));
		}
	}
});

window.addEvents({	
	'domready': function() {
		Globals.fx.windowScroll =  new Fx.Scroll(window);
		
		Globals.up = $('up');
		
		$$('.editable').each(function(item) {
			item.set('title', '');
			if (item.style.removeAttribute) {
			        item.style.removeAttribute("cursor");
			} else {
			        item.style.removeProperty("cursor");
			}
		});
		Slimbox.scanPage();
		
		// button for scrolling to top
		if (Globals.up) {
			Globals.up.addEvent('click', function(e){
				e.stop();
				Globals.fx.windowScroll.toTop();
			});
		}
		
		new DynamicMenu();
	}
});
