window.addEvent('domready', function(){

	var t = $$("a[rel=external]");
	t.each(function(lnk, nr){
		lnk.set({'target':'_blank'}).addClass('external');									
	});	

	if($chk($('recent_project_wrapper'))){		
		rpa = new Rp_animation();		
	}
	
	if($chk($('sub_nav'))){
		$$('#sub_nav li a').each(function(el, x) {  
			var fx = new Fx.Morph(el,{ duration:300, link:'cancel' });
			if(!el.getParent().hasClass('sel')){
				el.addEvents({
					'mouseenter': function() {
						fx.start({ 'padding-right': '40px' }); 
					},
					'mouseleave': function() { 
						fx.start({ 'padding-right': '15px' }); 											
					}
				});
			}
		}); 		
	}
									 
});

var Rp_animation = new Class({					 

	Implements: [Events, Options],
	
	options:{},

	initialize: function(){
		this.current_project = 1;
		this.project_timer;		
				
		var lnk = $('m_index').get('href');
		var request = new Request.JSON({
			url: lnk + "?action=ajax_get_recent",			
			onComplete: function(rJSON, response) {					
				var json = $H(JSON.decode(response, true));
				if(json["projects"].length>1){
					var lnk_lbl = $('recent_project_wrapper').getElement('p').getElement('a').get('html');
					json["projects"].each(function(el){
						var tmp = new Element('div', {'class':'recent_project'}).setStyle('opacity', 0).adopt(
													new Element('h3', {html:el["title"]}),
													new Element('div', {'class':'img_border'}).adopt(
														new Element('img', {width:282, h:218, src:el["src"], alt:el["title"]}),
														new Element('p').adopt(
															new Element('a', {href:el["url"], title:el["title"], html:lnk_lbl})					   
														)																								   
													)
						);
						$('recent_project_wrapper').grab(tmp);												
					});
					
					this.projects = $$('div[class=recent_project]');
					var header = $("recent_project_wrapper").getPrevious().adopt(
																			 new Element('span', {id: 'rp_counter', html: '[1/' + this.projects.length + ']'}),
 																			 new Element('img', {src: '/ajax_loader.gif', width:16,  height:16, alt:'Loading...'})
																			 );					
				}
			}.bind(this)
		}).post();
				
		this.project_timer = this.get_next.delay(4000, this);
		$('recent_project_wrapper').addEvents({
			mouseenter: function(){this.project_timer = $clear(this.project_timer);}.bind(this),
			mouseleave: function(){this.project_timer = this.get_next.delay(4000, this);}.bind(this)
		});
	},
	
	get_next: function(){		
		var previous = this.projects[this.current_project-1];
		previous.fade('out').retrieve('tween').chain(function(){
			this.current_project++;
			if(this.current_project > this.projects.length){ this.current_project = 1; }	
			$("rp_counter").set('html', '[' + this.current_project + '/' + this.projects.length + ']');
			this.projects[this.current_project-1].fade('in').retrieve('tween').chain(function(){			
				this.project_timer = this.get_next.delay(4000, this);
			}.bind(this));
		}.bind(this));
	}
});
