$(function(){
	$('a[rel*="boxy"]').click(setBox);
});

var boxy_exit = $('<div class="close">X</div>');
var boxy_overlay = $('<div id="boxy_overlay"></div>').hide();
var boxy_html = $('<div id="boxy_html">Loading...</div>')
var boxy_in = $('<div id="boxy_in"></div>').append(boxy_exit).append(boxy_html);
var boxy_out = $('<div id="boxy_out"></div>').append(boxy_overlay).append(boxy_in);

function setBox()
{
	var href = $(this).attr('href');
	var raw = $(this).attr('rel').split(';');
	
	var options = new BoxOptions();
	
	for(var i=0; i<raw.length; i++){
		if(raw[i].indexOf('=') > 0){
			var temp = raw[i].split('=',2);
			options[temp[0]] = temp[1];
		}
	}
	
	for(var s in options){
		$(boxy_in).css(s,options[s]);
	}
	
	
	$('body').append(boxy_out);
	boxy_overlay.fadeTo('slow',.75);
	$(boxy_out).bind('click', unsetBox);
	$(window).bind('resize', updateBox);
	updateBox();
	
	$.post(href,{ajax:1},function(data){
		boxy_html.animate({height:"hide"},{step:updateBox,complete:function(){
			$(this).html(data).animate({height:"show"},{step:updateBox});
		}});
	});		
	
	return false;
}

function unsetBox(e)
{
	var t = $(e.target);
	if(t.attr('id') == 'boxy_overlay' || t.hasClass('close')){
		boxy_overlay.hide();
		boxy_out.remove();
		boxy_html.html('Loading...');
		$(window).unbind('resize', updateBox);
	}
}

function BoxOptions()
{
	this.width = '500px';
	this.height = 'auto';
	this.overflow = 'hidden';
}

function getTop()
{
	return (boxy_out.height()-boxy_in.innerHeight())/2+'px';
}

function updateBox()
{
	boxy_in.css('overflow','hidden').css('height','auto');
	if(boxy_in.innerHeight() > boxy_out.height()-20-8){
		boxy_in.stop(true);
		var buffer = boxy_in.innerHeight()-boxy_in.height()+20+8;
		boxy_in.height(boxy_out.height()-buffer);
		boxy_in.css('overflow-y','scroll');
	}
	var offset_x = (boxy_out.width()-boxy_in.innerWidth()-8)/2;
	var offset_y = (boxy_out.height()-boxy_in.innerHeight()-8)/2;
	boxy_in.css('top',offset_y+'px').css('left',offset_x+'px');
}
