window.addEvent('domready', function(){
	var links = $$('div.col_bio_list > a');
		
	if(document.location.hash) {
		var load_id = document.location.hash.substring(1);
		links.each(function(row, key){
			if(row.get('rel') == load_id) {
				cur_link = key;
			}
		});
	}
	else {
		var cur_link = 0;
		var load_id = links[cur_link].get('rel'); 
	}

	links[cur_link].addClass('active').focus();
	var bio = $('bio_frame');
	var names = $('child_names');
	var media = $('child_media');
	bio.setStyle('opacity', 0);
	var racer;
	var im = new Image();
	
	var fader = new Fx.Tween(bio, {'duration': 220, 'onComplete': function(){ increment_racer(); }});
	
	var increment_racer = function(){
		racer++;
		if (racer == 2){
			bio.getFirst().getFirst().set('src', im.src);
			bio.getLast().set('html', '<p>' + bio.retrieve('bio').replace(/\n\n/g, '</p><p>') + '</p>');
			fader.start('opacity', 1);
		}
	};
	
	var load_bio = new Request.JSON({'url': baseurl + 'children/retrieve/',
		'onRequest': function(){
			racer = 0;
			fader.start('opacity', 0);
		},
		'onComplete': function(resp){
			im.src = baseurl + 'images/children/bio/' + resp.path_image;
			bio.store('bio', resp.bio);
			names.set('text', resp.children);
		
			if ($chk(resp.path_media)) {
				var parts = resp.path_media.split('.');
				var type = 'media';
				if (parts[1] == 'mp3') {
					type = 'audio';
				}
				media.set('href', baseurl + 'children/' + type + '/' + parts[0]);
				media.getChildren()[0].set('src', baseurl + 'images/bio_' + type + '.png');
			}
			else {
				media.set('href', 'javascript:void(0)');
				media.getChildren()[0].set('src', baseurl + 'images/bio_null.png');
			}
			
			im.onload = function(){
				increment_racer();
			};
			
			document.location.href = '#' + resp.id;
		}
		,onFailure: function(){
      			alert("An error has ocurred! Please try again.");
    		}

	});

	links.each(function(el, key){
		el.addEvent('click', function(){
			if ( ! this.hasClass('active')) {
				links[cur_link].removeClass('active');
				cur_link = key; 
				this.addClass('active');
				var id = this.get('rel');
				
				load_bio.send({'data': {'id': id}});
			}
		});
	});
	
	load_bio.send({'data': {'id': load_id}});
	
	$('bio_list').addEvent('keyup', function(e){
		if (e.key == 'up' || e.key == 'left' || e.key == 'down' || e.key == 'right') {
			links[cur_link].removeClass('active');
		
			if (e.key == 'up' || e.key == 'left') {
				cur_link--;
				if (cur_link < 0) {
					cur_link = links.length - 1; 
				}
			}
			else if (e.key == 'down' || e.key == 'right') {
				cur_link++;
				if (cur_link == links.length) {
					cur_link = 0;
				}
			}
		
			links[cur_link].addClass('active').focus();
			load_bio.send({'data': {'id': links[cur_link].get('rel')}});
		}
	});
});

