/**
 * @deps jquery, jquery.ui.dialog
 * @author miesjel@rhdl.nl
 */

if (typeof jQuery == 'undefined')
	throw 'Expected jQuery';

if (typeof ws == 'undefined')
	var ws = {};
if (typeof ws.ui == 'undefined')
	ws.ui = {};
if (typeof ws.ui.defaults == 'undefined')
	ws.ui.defaults = {};

ws.ui.defaults.dialog = {
	modal: true,
	resizable: false,
	draggable: false,
	position: 'center',
	width: 550,
	minWidth: 550,
	height: 500,
	autoResize: true,
	overlay: {
		opacity: 0.3,
		backgroundColor: '#fff'
	}
};

/**
 * Returns viewport width and height
 *
 * @return Object
 */
ws.ui.getViewPort = function()
{
	if (typeof window.innerWidth != 'undefined') {
		return {
			width: window.innerWidth,
			height: window.innerHeight
		};
	}

	if (typeof document.documentElement != 'undefined' &&
		typeof document.documentElement.clientWidth != 'undefined' && 
		document.documentElement.clientWidth != 0)
	{
		return {
			width: document.documentElement.clientWidth,
			height: document.documentElement.clientHeight
		};
	}

	return {
		width: document.getElementsByTagName('body')[0].clientWidth,
		height: document.getElementsByTagName('body')[0].clientHeight
	};
};

/**
 * Sets the contents of $dialog to an iframe which loads $url
 *
 * @example       ws.ui.openDialog($('#dialog'), {url: '/', title: 'Title'});
 * @param jQuery  dialog element(s)
 * @param Object  options, `url` or `html`, `title`
 *                jQuery ui.dialog options.
 *                Dialog will not be closed if options.close() explicitly returns `false`.
 */
ws.ui.openDialog = function($dialog, options)
{
	if (typeof jQuery.fn.dialog == 'undefined')
		throw 'Expected jQuery ui.dialog';

	var options = $.extend(ws.ui.defaults.dialog, options);
	var viewport = ws.ui.getViewPort();
	if (options.height > viewport.height)
		options.height = viewport.height;
	options.title = options.title || '&nbsp;';

	if (typeof options.url != 'undefined') {
		options.html = '<iframe src="' + options.url + '" frameborder="0" width="'
			+ options.width + '" height="' + (options.height - 10) + '"></iframe>';
	}

	if (typeof options.close != 'undefined') {
		var close = options.close;
		delete options.close;
	}

	$dialog.show();
	if (typeof options.html != 'undefined')
		$dialog.html(options.html);
	$dialog.dialog(options);

	// Allow options.close() to cancel close
	if (typeof close != 'undefined') {
		$('.ui-dialog-titlebar-close').remove();
		var html = '<a class="ui-dialog-titlebar-close" id="ui-dialog-close" href="javascript:;" unselectable="on" style="-moz-user-select: none;"><span unselectable="on" style="-moz-user-select: none;">X</span></a>';
		$('.ui-dialog-titlebar').append(html);
		$('#ui-dialog-close').click(function()
		{
			if (close() === false)
				return false;
		
			return $dialog.dialog('close');
		});
	}
};