<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

$callback = $this->getRequest()->request('callback', 'string', '');
$callback = preg_replace('#[^a-z0-9.]#i', '', $callback);

ob_start();

if ($callback) {
	?>
jQuery(function($) {
	$('#sly-wrapper').delegate('a[href="#"]', 'click', function() {
		var self     = $(this);
		var filename = self.data('filename');
		var title    = self.data('title');
		var link     = 'data/mediapool/' + filename;
		var callback = '<?php echo $callback ?>' in window.opener ? window.opener['<?php echo $callback ?>'] : null;
		var close    = true;
		var fullName = '';

		if (title.length === 0) {
			fullName = filename;
		}
		else {
			fullName = title;
		}

		// execute callback (media widget, WYMeditor, ...)
		if (callback !== null) {
			close = callback(filename, fullName, title, link, window);
		}

		// close the popup
		if (close) window.close();
		return false;
	});
});
	<?php
}
?>
function openPage(src) {
	window.opener.location.href = src;
	self.close();
}
<?php
$javascript = ob_get_clean();
sly_Core::getLayout()->addJavaScript($javascript);
