var $lb_cur_win = "";
function lb_createWindow($id, $title, $source, $width, $height) {
	if ($lb_cur_win != "") lb_closeWindow($lb_cur_win);
	$lb_cur_win = $id;
	$overlay = jQuery("<div id=\"overlay_"+$id+"\" class=\"lb_overlay\" />").css({display: 'none', opacity: 0.6});
	$modal = jQuery("<div id=\"window_"+$id+"\" class=\"lb_window\" />");
	//$width += 40;
	//$height += 40;
    $width = jQuery("#"+$id).width() + 40;
    $height = jQuery("#"+$id).height() + 40;
	$margin_left = - Math.floor($width/2);
	$margin_top = - Math.floor($height/2);
	$modal.css({
		left: '50%',
		top: '50%',
		width: $width,
		height: $height,
		marginLeft: $margin_left,
		marginTop: $margin_top,
		display: 'none',
		borderWidth: 0
	});
	$shadow = $modal.clone().attr("id", "shadow1_"+$id).css({marginLeft: $margin_left - 4,	marginTop: $margin_top - 4,borderWidth: '4px', opacity: .8, zIndex: 1002});
	$shadow2 = $modal.clone().attr("id", "shadow2_"+$id).css({marginLeft: $margin_left - 10, marginTop: $margin_top - 10, borderWidth: '10px', opacity: .4, zIndex: 1001});
	
	$close = jQuery("<a class=\"lb_close\">&nbsp;</a>").click( function() {
		lb_closeWindow($id);
	});
	$content = $source.clone(true).css({display: 'block'});
	$modal.append("<h1 class=\"lb_header\">"+$title+"</h1>");
	$modal.append($close);
	$modal.append(jQuery("<div class=\"lb_content\"></div>").append($content));
	// overlay
	$overlay.appendTo('body').fadeIn(200);
	// shadow
	$shadow2.appendTo('body').fadeIn(100);
	$shadow.appendTo('body').fadeIn(100);
	// modal window
	$modal.appendTo('body').fadeIn(300);
}

function lb_closeWindow($id) {
	$("#shadow1_"+$id).remove();
	$("#shadow2_"+$id).remove();
	$("#window_"+$id).fadeOut(300, function() {
		$(this).remove();
		$("#overlay_"+$id).fadeOut(200, function() {
			$(this).remove();
		})
	})
	$lb_cur_win = "";
}

jQuery(document).ready( function() {
	$lb_cur_win = "";
	jQuery(".lightbox").each(function(i) {
		jQuery(this).click( function() {
			$source = jQuery(this).attr("href");
			$boxid = /([a-z, 0-9, _, -]+)/.exec($source)[1];
			$title = jQuery(this).attr("title");
			$width = parseInt(jQuery(this).attr("width"));
			$height = parseInt(jQuery(this).attr("height"));
			lb_createWindow( $boxid, $title, jQuery($source), $width, $height );
            return false;
		});
	});
});
