tinymce.PluginManager.add('fileuploader', function(editor, url) {

	editor.settings.file_browser_callback = fileuploader;

	function fileuploader_onMessage(event) {
		if (editor.settings.external_fileuploader_path.toLowerCase().indexOf(event.origin.toLowerCase()) === 0) {
			if (event.data.sender === 'fileuploader') {
				editor.windowManager.getParams().setUrl(event.data.url);
				editor.windowManager.close();

				window.removeEventListener('message', fileuploader_onMessage, false);
			}
		}
	}
	
	function fileuploader(id, value, type, win) {
		
		window.addEventListener('message', fileuploader_onMessage, false);
		
		var qs = "";
		if (typeof id !== "undefined" && typeof win !== "undefined") {
			qs = "?opener=1&type=" + type;
		}
		
		editor.windowManager.open({
			title : 'File uploader',
			url : tinymce.settings.external_fileuploader_path + 'fileuploader.php' + qs,
			width : 840,
			height : 480,
			buttons : [ {
				text : 'Close',
				onclick : 'close'
			} ]
		}, {
			setUrl : function(url) {
				if (!qs.length) {
					return;
				}
				var fieldElm = win.document.getElementById(id);
				fieldElm.value = editor.convertURL(url);
				if ("createEvent" in document) {
					var evt = document.createEvent("HTMLEvents");
					evt.initEvent("change", false, true);
					fieldElm.dispatchEvent(evt);
				} else {
					fieldElm.fireEvent("onchange");
				}
			}
		});
	}

	// Add a button that opens a window
	editor.addButton('fileuploader', {
		title : 'File uploader',
		icon : 'browse',
		onclick : function() {
			// Open window with a specific url
			fileuploader();
		}
	});

	return {
		getMetadata : function() {
			return {
				name : "File uploader plugin",
				url : "https://www.phpjabbers.com"
			};
		}
	};
});