/*
 * jQuery Pop-up Plugin
 * Copyright 2010 Carl Thomé
 * Released under the MIT and GPL licenses.
 */

function popup(obj, trigger, type, msg) {

	//append popup overlay if it doesn't already exist
	if ( jQuery('.overlay').length == 0 ) jQuery('body').append('<div class="overlay"></div>');
	
	//create object if it doesn't exist
	if (obj == '') {
		jQuery('body').append('<div class="popup-object notification '+type+'">'+msg+'</div>');
		var obj = ('.popup-object');
	}
	//hide the popup
	jQuery(obj).hide().addClass('popup').addClass(type);
	
	//move element to body
	if (!( jQuery('form').children(obj) )) jQuery(obj).appendTo('body');

	//add close button to all popups
	jQuery(obj).prepend('<div class="closepopup"></div>');
	
	//position box with offsets - called on creation of box
	function positionbox() {
		//get content dimensions
		var width = jQuery(obj).outerWidth(false);
		var height = jQuery(obj).outerHeight(false);

		//center popup
		var centerX = '-'+ (width / 2) +'px';
		var centerY = '-'+ (height / 2) +'px';
		jQuery(obj).css('margin-top', centerY);
		jQuery(obj).css('margin-left', centerX);
		
		//shrink box and show scrollbar if client viewport is too small for contents
		var windowHeight = jQuery(window).height();
		var windowWidth = jQuery(window).width();
		
		if ( windowHeight < height ) jQuery(obj).addClass('too-short').css('max-height', windowHeight+'px'); 
		else jQuery(obj).removeClass('too-short').css('max-height', 'none');
		
		if ( windowWidth < width ) jQuery(obj).addClass('too-thin').css('max-width', windowWidth+'px');
		else jQuery(obj).removeClass('too-thin').css('max-width', 'none');
	}

	//reposition and resize box if browser changes size
	jQuery(window).resize(function() {
	//	var resizeDelay;
	//	clearTimeout(resizeDelay);
	//	resizeDelay = setTimeout(positionbox, 10);
		positionbox();
	});
	
	//show this popup
	function showbox() {
		hidebox();
		jQuery(obj).fadeIn();
		jQuery('div.overlay').fadeIn();
		positionbox();
	}

	//hide all popups
	function hidebox() {
		jQuery('div.overlay').hide();
		jQuery('.popup').fadeOut();
	}
	
	//if there is no trigger: create popup on load
	if(trigger == '') {
		showbox();
	}

	//if there is a trigger: create popup on trigger-click
	else {
		jQuery(trigger).click(function(){
			showbox();
		});
	}

	//hide popup when the outside or the close-icon is clicked
	jQuery('div.overlay, .closepopup').click(function(){
		hidebox();
	});

	//remove popup on escape-press
	jQuery(document).keyup(function(e) {
		if (e.keyCode == 27) {
			hidebox();
		}
	});	
}
