
/**
 *	Universal function for a genarating popup's
 *
 *	Several examples of usage:
 *	popen('http://www.google.com/');
 *	var wref = popen(null,'_bnr',
 *		{width:468,height:60,scrollbars:'no',status:'no'},
 *		'<body style="margin:0;padding:0;"><img src="http://upload.wikimedia.org/wikipedia/commons/2/26/Kyokpae_banner.png" width="468" height="60" alt="" /><br /></body>'
 *	);
 *
 *	Notice, that browsers have different limitation for minimal with and height values of window.
 *	To fix it in FF you could use method wref.sizeToContent();
 *	Also can use functions wref.resizeTo(), wref.resizeBy(), but in this case calculate of acceptable parametrs
 *	will need search in manual mode. With relative big size's that character problems won't happen.
 *
 *	@author Denis Golovtsov
 *	@param string|null, URL that should be open in popup; if it's null or empty, 'about:blank' will open
 *	@param string|null, name of frame popup window, this can be used as target attribute for tags <FORM> and <A>
 *	@param hash|null, associated array of options for popup window:
 *		options is defined by default:
 *			width = 500, height = 500, scrollbars = yes, status = yes, top, left - calculated for centered
 *		other options:
 *			menubar = no, resizable = no, toolbar = no, directories = no
 *		read more about options here:
 *			http://www.devguru.com/Technologies/ecmascript/quickref/win_open.html
 *	@param string|null, HTML code that can be represent in popup, it uses in pair with 'null' URL
 *	@return window reference, reference to new genarated popup
 */

/**
 *	Associated public array where is stored reference's for all popup's were opened in current session.
 */
var _popens = {};

function popen(url,name,opts,html)
{
	if (!opts) var opts = {};

	opts['width'] = opts['width'] || 500;
	opts['height'] = opts['height'] || 500;

	opts['left'] = opts['left'] || (screen.availWidth - opts['width'])/2;
	opts['top'] = opts['top'] || (screen.availHeight - opts['height'])/2;

	opts['scrollbars'] = opts['scrollbars'] || 'yes';
	opts['status'] = opts['status'] || 'yes';

	url = url || 'about:blank';
	name = name || '_popup';

	var s_opts = '';
	for (var i in opts) s_opts += ( s_opts != '' ? ',' : '' ) + i + '=' + opts[i];

	try
	{
		if (_popens[name] && !_popens[name].closed)
		{
			_popens[name].close();
		}

		var w = window.open(url,name,s_opts);

		if (html)
		{
			w.document.open();
			w.document.write(html);
			w.document.close();
		}

		w.focus();

		_popens[name] = w;

		return w;
	}
	catch(e)
	{
	}
}

/**
 *	Function that provide final cleanup and close all popup's are opened.
 *	You should bind this function to 'unload' event of a main page.
 *
 *	@param void
 *	@return void
 */

function popen_clean()
{
	for (var i in _popens)
	{
		if (!_popens[i].closed) _popens[i].close();
	}
}