// PDI Modal System - Replaces Telerik RadWindowManager
var PDIModal = (function () {
	var modals = {};
	var onCloseCallbacks = {};

	function createOverlay(name) {
		var overlay = document.createElement('div');
		overlay.id = 'pdi-modal-overlay-' + name;
		overlay.className = 'pdi-modal-overlay';
		overlay.onclick = function (e) {
			if (e.target === overlay) close(name);
		};

		var dialog = document.createElement('div');
		dialog.className = 'pdi-modal-dialog';

		var header = document.createElement('div');
		header.className = 'pdi-modal-header';

		var title = document.createElement('span');
		title.className = 'pdi-modal-title';
		title.id = 'pdi-modal-title-' + name;

		var closeBtn = document.createElement('button');
		closeBtn.className = 'pdi-modal-close';
		closeBtn.innerHTML = '&times;';
		closeBtn.onclick = function () { close(name); };

		header.appendChild(title);
		header.appendChild(closeBtn);

		var iframe = document.createElement('iframe');
		iframe.id = 'pdi-modal-iframe-' + name;
		iframe.className = 'pdi-modal-iframe';
		iframe.setAttribute('frameborder', '0');

		dialog.appendChild(header);
		dialog.appendChild(iframe);
		overlay.appendChild(dialog);
		document.body.appendChild(overlay);

		modals[name] = { overlay: overlay, dialog: dialog, iframe: iframe, title: title };
		return modals[name];
	}

	function open(name, url, title, width, height) {
		var m = modals[name] || createOverlay(name);
		m.title.textContent = title || '';
		m.dialog.style.width = width || '600px';
		m.dialog.style.height = height || '400px';
		m.iframe.src = url;
		m.overlay.classList.add('active');
	}

	function close(name) {
		var m = modals[name];
		if (m) {
			m.overlay.classList.remove('active');
			m.iframe.src = 'about:blank';
			if (onCloseCallbacks[name]) {
				onCloseCallbacks[name]();
			}
		}
	}

	function onClose(name, callback) {
		onCloseCallbacks[name] = callback;
	}

	// Allow child iframes to close their parent modal
	function closeFromChild() {
		try {
			var frame = window.frameElement;
			if (frame && frame.id && frame.id.indexOf('pdi-modal-iframe-') === 0) {
				var name = frame.id.replace('pdi-modal-iframe-', '');
				if (window.parent && window.parent.PDIModal) {
					window.parent.PDIModal.close(name);
				}
			}
		} catch (e) { }
	}

	return {
		open: open,
		close: close,
		onClose: onClose,
		closeFromChild: closeFromChild
	};
})();
