var base_opacity = 0.5;
var in_effect = false;
window.addEvent("domready",function(){
	var loader = new Element('div').setProperty('id','ajax_loader').setOpacity(0).injectTop('panel-right');
	$$('#panel-left .obscured').each(function(n){
		n.setOpacity(base_opacity);
	})
	$$('#panel-left .clear')[0].setOpacity(0);
	$$('#panel-left .clear')[0].getParent().setStyle('border-color','#fff');
	loader.setStyles({
		'left' : ($('panel-right').getCoordinates().width - loader.getCoordinates().width) / 2,
		'top' : ($('panel-right').getCoordinates().height - loader.getCoordinates().height) / 2
	});
	$$('#panel-left li a').each(function(n){
		var href = n.getProperty('href');
		n.replaceWith(new Element('span').addClass('link').setProperty('rel',href).setHTML(n.innerHTML));
	});

	
	$$('#panel-left li span.link').each(function(n){
		n.addEvent('click',function(ev){
			/*var click_ev = new Event(ev);
			click_ev.preventDefault();*/
			var href = this.getProperty('rel');
			if (!this.getFirst().hasClass('clear') && !in_effect) {
				in_effect = true;
				$$('#panel-right img')[0].setProperty('id','to_remove');
				$$('#panel-left .clear')[0].getParent().setProperty('id','fade_out');
				this.setProperty('id','the_target');
				new Ajax(href, {method: 'get',
					onComplete: function() {
						var text = this.response.text;
						var img = text.match(/<!-- start img -->(.*?src="([\s\S]*?)".*?)<!-- end img -->/);
						if (img[2]) {
							var src = img[2];
							new Asset.image(src,{
								onload: function(){
									swapImage(this);
								}
							});
						}
					}
				}).request();
				$('ajax_loader').effect('opacity',{duration:300}).start(0,0.9);
			}
		});
	});
});

function swapImage(img) {
	img.setOpacity(0).setStyles({
		'position' : 'absolute',
		'left' : 0,
		'top' : 0
	}).injectInside($('panel-right')).setProperty('id','img_target');
	new Fx.Elements($$('#img_target, #the_target span, #panel-left span.clear, #ajax_loader, #the_target, #fade_out'),{
		onComplete: function(){
			if((n = $('img_target')) != null) {
				n.removeProperty('id');
				$('to_remove').remove();
				n.removeProperty('style');
				$$('#panel-left span.clear')[0].removeClass('clear').addClass('obscured');
				$('the_target').getFirst().removeClass('obscured').addClass('clear');
				$('the_target').removeProperty('id');
				$('fade_out').removeProperty('id').setStyle('border-color','');
				(function(){ in_effect = false }).delay(200);
			}
		}
	}).start({
		0: { opacity: [0,1]},
		1: { opacity: [base_opacity,0]},
		2: { opacity: [0,base_opacity]},
		3: { opacity: [0.9,0], duration: 300},
		4: { borderColor : [$('the_target').getStyle('border-color'),'#ffffff']},
		5: { borderColor : [$('fade_out').getStyle('border-color'),'#cccccc']}
	});
}
