

	document.addEvent('domready', function() {
	
		var flip_closed = $E('div.flip-closed');
		var flip_open = $E('div.flip-open');

		if($defined(flip_closed) && $defined(flip_open)) {
			flip_closed.addEvent('click', function(e) {
				new Event(e).stop();
				flip_open.setOpacity(0).setStyles({'display':'block', 'zIndex': 1000 }).effect('opacity', { duration: 300 }).start(1);
			});	
			
			flip_open.getElement('h3').addEvent('click', function(e) {
				new Event(e).stop();
				flip_open.effect('opacity', { duration: 300 }).start(0).chain(function() { flip_open.setStyle('display','block'); });
			});
			
			// default open if .error class is found
			if(flip_open.getElement('div.error')) {
				flip_open.setStyle('display','block');
			}
		}
		
		// start the carousel :-)
		if($('sbox')) { carousel(); }
		
	});
	
	// carousel
	
	function carousel() {
		var jrequest = new Json.Remote('/js/images.aspx', {
		   	method:'get',
			onComplete: function(images) {
				var images = images.content;			
				var mapped = images.map(function(i) { if(typeof i == "object") return i.src });
				var preload = new Asset.images(mapped, { 
					onComplete: function() { startCarousel(preload, images); }
				});
			}
		}).send();
	}

	function startCarousel(images, json) {
		var interval = 6*1000;
		var key = 0;
		var previmg;
		var periodical;
		var container = $('sbox').setStyles({ position: 'relative', overflow: 'hidden', background: '#333' });
		var txtElement = container.getElement('div.txtlayer-txt');
		var txtLayer = container.getElement('div.txtlayer').setOpacity(0.7);
		
		images.each(function(i, index) { i.setStyles({ position: 'absolute', top: 0, left: 0, 'z-Index': 100+index }) });
		var rotate = function() {		
			// add new item
			var startitem = function() {	
				if($defined(previmg)) previmg.effect('opacity', { duration: 650 }).start(0).chain(function() { this.element.remove(); }); 
				var link = new Element('a', { href: json[key].url }).setText(json[key].title);
				txtElement.empty();
				link.injectInside(txtElement);
				images[key].setOpacity(0).injectTop(container).effect('opacity', { duration: 650 }).start(1);
			}
			
			startitem();
			previmg = images[key];
			key++;
			if(key > images.length-1) key = 0;
		}
		
		rotate();
		periodcial = rotate.periodical(interval);
		
		// mouse actions to prevent animations when we mouse-over
		//container.addEvent('mouseenter', function() { $clear(periodcial); });
		//container.addEvent('mouseleave', function() { rotate.delay(800); periodcial = rotate.periodical(interval); });
	};
