/*document.createRange().__proto__.surroundContents = function(parent) {
var frag = this.extractContents();
if (frag != null)
parent.appendChild(frag);
this.insertNode(parent);
this.selectNode(parent);
}
*/


function include(destination) {
	var e = document.createElement('script');
	e.setAttribute('type', 'text/javascript');
	e.setAttribute('src', destination + '.js');
	document.getElementsByTagName('head')[0].appendChild(e);
	return e;
}

include('/plugins/editor/wysiwyg/inheritance');
include('/plugins/editor/wysiwyg/Plugin.class');

//include('/plugins/editor/wysiwyg/Pencil.class');

function RichTextEditor(options) {

	$this = this;

	this.options = {
		width: '100%',
		height: 200,
		plugins: [
			'common/bold',
			'common/italic',
			'common/underline',
			'common/strikethrough',
			'common/link',
			'common/unlink',
			'common/html',

			'cms/list',
			'cms/field'
		]
	};

	for (var k in options) {
		eval('this.options.' + k + ' = options.' + k);
	}

	this.apply = function (selector) {

		this.areas = $(selector);

		this.areas.each(function (i, a) {

			// Hide the original textarea
			this.subject = $(a);
			if (!this.subject.length) {
				return false;
			}
			this.subject.css('display', 'none');

			// Wrapper
			this.wrapper = $('<div class="PE_wrapper">');
			this.wrapper.attr('rel', id = this.subject.attr('id'));
			this.crumbs = $('<div class="PE_crumbs">');
			this.wrapper.append(this.crumbs);
			this.wrapper.append($('<div class="clear">'));
			this.subject.after(this.wrapper);

			// Create iframe
			this.iframe = $('<iframe class="PE_iframe" rel="' + id + '">').css({
				height: $this.options.height
			});
			this.wrapper.prepend(this.iframe);

			// Prepare iframe
			this.window = this.iframe[0].contentWindow;
			this.document = this.iframe.contents();
			this.document.find('body').addClass('PE_canvas').html(this.subject.val()).attr('contenteditable', true);
			this.document.click(function () {
				path = '';
				pointer = this.getSelection().getRangeAt(0).commonAncestorContainer;
				while (pointer.parentElement && pointer.parentElement.tagName != 'BODY') {
					path = '<span>&gt;</span><a href="javascript: void(0)" onclick="sel = $(\'iframe[rel=' + id + ']\')[0].contentWindow.getSelection(); sel.setBaseAndExtent(pointer.parentElement, 0, pointer.parentElement, 1)">' + pointer.parentElement.tagName + '</a>' + path;
					pointer = pointer.parentElement;
				}
				//this.find('crumbs').html(path);
			});

			doc = this.document;
			this.window.select = function (selector) {
				return selector.match(/^cms:/) ? $(this.document.getElementsByTagName(selector)) : doc.find(selector);
			};


			// Toolbar
			var toolbar = $('<div class="PE_toolbar">');
			$($this.options.plugins).each(function (i, plugin) {
				name = plugin.match(/\/(.*)/)[1].toString();
				Name = name.charAt(0).toUpperCase() + name.substr(1);
				script = include('/plugins/editor/wysiwyg/plugins/' + plugin + '/' + name);
				toolbar.append(
					$('<span class="tool" rel="' + Name + '">')
					/*.html('&nbsp;')
					.addClass('button')
					.attr({ href: 'javascript: void(0)', rel: Name, onClick: Name + '.executeOn("' + id + '")' })
					.css('background-image', 'url(/plugins/editor/wysiwyg/plugins/' + plugin + '/' + name + '.png)')*/
				);
			});
			this.wrapper.prepend(toolbar);
		});

		$('iframe.PE_iframe').closest('form').submit(function () {
			$this.updateAll();
			return true;
		});
	};

	this.updateAll = function () {
		$('div.PE_wrapper').each(function (i, rte) {
			var body = $(rte).find('iframe.PE_iframe').contents().find('body');
			$(rte).prev().html(body.html());
		});
	}
	/*this.api = {
		wrap: function(css) {
			var selection = getSelText('');

			var range = $('iframe').contents()[0].createRange();
			range.setStart(selection.anchorNode, selection.anchorOffset);
			range.setEnd(selection.focusNode, selection.focusOffset);

			if(range) {
				var wrapper = $('iframe').contents()[0].createElement('span');
				$(wrapper).css(css);
				range.surroundContents(wrapper);
				range.selectNode(wrapper);
			}
		}
	}*/

}

function getSelText(selector) {
	var txt = '';
	if (typeof(selector) == 'undefined') {
		var Window = window;
		var Document = document;
	} else {
		var Window = $('iframe' + selector)[0].contentWindow;
		var Document = $('iframe' + selector).contents();
	}
	if (window.getSelection) {
		txt = Window.getSelection();
	} else if (Document.getSelection) {
		txt = Document.getSelection();
	} else if (Document.selection) {
		txt = Document.selection.createRange().text;
	} else return;
	return txt;
}

/* Loading content via ajax */
$.fn.fetch = function (url, callback, text) {
	var url = '/editor/' + url;
	var target = $(this);
	$.get(url, null, function (response) {
			if (typeof(callback) != 'undefined') response = callback(response);
			target.html(response);
		}
	);
	return target;
};

/* Get cms tags */
$cms = function (selector) {
	return $(document.getElementsByTagName('cms:' + selector));
};

var RTE = new RichTextEditor({height: 420});
$(document).ready(function () {
	RTE.apply('textarea.richtexteditor');
});
