(function()
{
	tinymce.create('tinymce.plugins.ICLinksPlugin', {
		init: function(ed, url)
		{
			this.editor = ed;
			var self = this;

			// Register commands
			ed.addCommand('mceICLink', function()
			{
				var se = ed.selection;

				// No selection and not in link
				var a = ed.dom.getParent(se.getNode(), 'A');
				if ((se.isCollapsed() && !a) || (a && a.name))
					return;

				self.processLink(a);
			});

			// Register buttons
			ed.addButton('link', {
				title: 'advanced.link_desc',
				cmd: 'mceICLink'
			});

			ed.onNodeChange.add(function(ed, cm, n, co)
			{
				//cm.setDisabled('link', co && n.nodeName != 'A');
				//cm.setActive('link', n.nodeName == 'A' && !n.name);
				try {
				if ((n.nodeName == 'A') && (e.ctrlKey))
					ed.execCommand('mceICLink', false, null);
				} catch(err) {}
			});

			ed.onMouseDown.add(function(ed, e)
			{
				if (e.ctrlKey)
				{
					var target = e.target || e.srcElement;
					self.processLink(ed.dom.getParent(target, 'A'));
					tinymce.dom.Event.prevent(e);
				}
			});

			if ((ed.onMouseOver) && (ed.onMouseOver.add))
			{
				ed.onMouseOver.add(function(ed, e)
				{
					if (e.ctrlKey)
					{
						//ed.execCommand('mceICLink', false, null);
						var se = ed.selection;

						// No selection and not in link
						if (se.isCollapsed() && !ed.dom.getParent(se.getNode(), 'A'))
							return;

						var a = ed.dom.getParent(se.getNode(), 'A');
						if (a != null)
						{
							var href = a.href;
							alert(href);
						}
					}

				});
			}
		},

		processLink: function(linkElem)
		{
			var href = linkElem.href;
			if (href.substr(0, 11) == 'javascript:')
			{
				eval(href.substr(11));
			}
			else
			{
				var local = 'http://' + window.location.hostname;
				if (href.substr(0, local.length) == local)
				{
					var idx = href.lastIndexOf('/');
					var idx2 = href.lastIndexOf('#');
					if (idx2 == idx + 1)
					{
						//var bmarkName = href.substr(idx2 + 1);
						var bmarkName = linkElem.getAttribute('href').substr(1);
						var bmark = this.editor.getDoc().getElementById(bmarkName);
						if (bmark)
						{
							bmark.scrollIntoView(true);
							return;
						}
					}
				}

				try
				{
					window.open(href);
				}
				catch (e)
				{
					alert('Link to "' + href + '" cannot be open. Reason: ' + e.message);

				}
			}
		},

		getInfo: function()
		{
			return {
				longname: 'DCConcept IC Links',
				author: 'Petr Langer, DCConcept a.s.',
				authorurl: 'http://www.dcconcept.com',
				infourl: '',
				version: tinymce.majorVersion + "." + tinymce.minorVersion
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('ic_links', tinymce.plugins.ICLinksPlugin);
})();