/**
 * JavaScript to integrate file browsing and selection with the editor.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2014 - 2016 fusionLib. All rights reserved.
 * @link http://clearfusioncms.com
 */

$fl(document).ready(function() {

	function useFile(evt) {
		var url = sessionStorage.getItem('cfFileBrowser.useFile');
		if(url != null) {
			sessionStorage.removeItem('cfFileBrowser.useFile');

			// Set the target
			var inp = parent.top.$('#active-input').val();
			parent.top.$('#' + inp).val(url);

			// Close dialog
			parent.top.$("#md-imageselect").data('simplemodal').hide();
		}

		evt.preventDefault();
		evt.stopPropagation();
		return false;
	}

	$fl('#filebrowserUseFile')
		.css('display', 'block')
		.bind('click', useFile);

	$fl('.treeviewwidget a').bind('click', function(evt) {
		if(evt.target.tagName != 'A' && $fl(evt.target).parent().parent()[0].className != 'container') {
			var url;
			if(evt.target.tagName == 'EM')
				url = $fl(evt.target).parent().parent().attr('href').replace(/^.*#/, '');
			else
				url = $fl(evt.target).parent().attr('href').replace(/^.*#/, '');

			sessionStorage.setItem('cfFileBrowser.useFile', url);
		}
	}).bind('dblclick', useFile);
});