var pbox_width = 264;
var pbox_height = 189;
var pbox_hide_delay = 1000;
var pbox_hide_timer = false;
var pbox_current = false;

function pbox_hide(pbox_id) {
	el = $(pbox_id);
	
	if(el) {
		el.get('tween', {property: 'opacity', duration: 100}).start(0).chain(function() {
			el.destroy();
		});
	}
}

function pbox_hide_delayed(pbox_id) {	
	pbox_hide_timer = pbox_hide.delay(pbox_hide_delay, false, pbox_id);
}

function pbox_hide_cancel() {
	if(pbox_hide_timer != false) {
		$clear(pbox_hide_timer);
		pbox_hide_timer = false;
	}
}

function pbox_show() {
	/*
	 * If re-hovering the same image, do nothing.
	 */

	check = this.retrieve('pbox_id');
	if(check && $defined($(check))) {
		pbox_hide_cancel();
		return;
	} else if(pbox_current != false && $defined($(pbox_current))) {
		pbox_hide(pbox_current);
	}

	position = this.getPosition();
	
	pbox_id = 'pbox_dyn_' + uniqid();
	pbox = new Element('div', {
		'id': pbox_id,
		'styles': {
			'width': pbox_width + 'px',
			'height': pbox_height + 'px',
			'zIndex': '100',
			'position': 'absolute',
			'top': position.y + this.getSize().y / 2 - pbox_height / 2 - 12,
			'left': position.x - 300 + 8
		},
		'events': {
			'mouseenter': function() {
				pbox_hide_cancel();
			},
			'mouseleave': function() {
				pbox_hide_delayed(this.getProperty('id'));
			}
		}
	});
			
	var req = new Request.HTML({
		url: '/profile_box_v.php',
		update: pbox_id
	}).get({'id': this.getProperty('rel')});
	
	pbox.fade('hide');
			
	$('test').grab(pbox);
	
	pbox.set('tween', {duration: 100});
	pbox.fade('in');
			
	this.store('pbox_id', pbox_id);
	pbox_current = pbox_id;
}

window.addEvent('domready', function() {
	$$('.profile_box_trigger').each(function(imgEl) {
		imgEl.addEvent('mouseenter', pbox_show);
		
		imgEl.addEvent('mouseleave', function() {
			pbox_hide_delayed(this.retrieve('pbox_id'));
		});
	});
});