/**
 * Popup focusing code partially taken
 * from the sample by Paul van Iterson
 * http://test.itka.nl/javascript/jspopup.html
 *
 */

function loadPopup( popup_url ) {
	showOverlay();

	var popup_wrapper = $('popup_wrapper');
	if (!popup_wrapper) {
		var p = document.createElement('popup_wrapper');
		p.id = 'popup_wrapper';
		document.body.appendChild(p);
		popup_wrapper = $('popup_wrapper');
	}

	new Ajax.Request( popup_url, {
		method: 'get',
		onSuccess: function (transport) {
			popup_wrapper.innerHTML = transport.responseText;
			popup_wrapper.style.top  = (document.viewport.getScrollOffsets().top + document.viewport.getHeight()/5) + 'px';
			popup_wrapper.style.left = (document.viewport.getWidth()/2 - popup_wrapper.getWidth()/2) + 'px';
			popup_wrapper.appear( { duration: 0.5 });
		}
	} );
}

function closePopup( ) {
	$('popup_wrapper').fade( {duration: 0.4});
	hideOverlay();
}


/* escapeOverlay is needed to be able to stop the event listener.
See the prototype API docs for more information:
http://www.prototypejs.org/api/event
*/
var escapeOverlay = {
	fx: function(e)
	{
		// To make script compatable with both MSIE and Firefox
		var kC  = (window.event) ? event.keyCode : e.keyCode;
		var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE;

		// If keypressed is escape and the new entry field is empty
		if( kC == Esc ) {
			closePopup();
		}
	}
}

// Save in cache (to be able to stopObserving() it), see Prototype API docs for more info:
// http://www.prototypejs.org/api/event
escapeOverlay.bfx = escapeOverlay.fx.bindAsEventListener(escapeOverlay);

// Shows the overlay and starts the ESCAPE event listener
function showOverlay()
{
	var overlay = $('overlay');
	if (!overlay) {
		var o = document.createElement('div');
		o.id = 'overlay';
		document.body.appendChild(o);
		overlay = $('overlay');
	}

	// We want the overlay to be the exact same size as the body of our document...
	// Unfortunately, setting the overlay's height to '100%' doesn't account for
	// margins or padding on the body, so we need to manually sum it up and add it
	// to the height of our overlay.
	var body = $$('body')[0];
	var p = ['padding-top', 'padding-bottom', 'margin-top', 'margin-bottom'];
	overlay.style.height = (body.getHeight() + p.inject(0, function(sum, prop) { var pv = parseInt($(body).getStyle(prop)); return sum + ((isNaN(pv)) ? 0 : pv) ; }) ) + 'px';
	overlay.appear( { duration: 0.6, to: 0.75, from: 0.0 });
	overlay.observe('click', function(event) { closePopup(); } );
	Event.observe(document, 'keypress', escapeOverlay.bfx );
}

// Hides the overlay and stops the ESCAPE event listener
function hideOverlay()
{
	$('overlay').fade( {duration: 0.4});

	Event.stopObserving(document, 'keypress', escapeOverlay.bfx );
}