/**@license setplus: a lightweight HTML editor
 * @author  Levente Hunyadi
 * @version 0.2.0
 * @remarks Copyright (C) 2010-2011 Levente Hunyadi
 * @remarks Licensed under GNU/GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html
 * @see     http://hunyadi.info.hu/projects/setplus
 **/

/*
* setplus: a lightweight HTML editor
* Copyright 2010-2011 Levente Hunyadi
*
* setplus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* setplus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with setplus.  If not, see <http://www.gnu.org/licenses/>.
*/

setplus.WordProcessorDialog = new Class({
	'Extends': setplus.EditorDialog,

	'initialize': function () {
		var self = this;
		self.parent();

		self._title.adopt(
			new Element('span', {
				'class': 'setplus-wordprocessor-title'
			})
		);

		var wordeditor;
		self._content.adopt(
			wordeditor = new setplus.HTMLEditor(),
			new Element('button', {
				'type': 'button',
				'html': 'OK',
				'events': {
					'click': self.invoke.bind(self, function (editor) {
						// insert HTML
						editor.pastehtml(wordeditor.getHTML()
							.replace(/<!--\[if gte mso \d+\]>[\s\S]*?<!\[endif\]-->/g, '')  // remove Word XML manifest
							.replace(/class="([^"]*)"/g, function (unused, text) {
								text = text.replace(/\bMsoNormal\w*/g, '').clean();
								return text ? 'class="' + text + '"' : '';
							})
							.replace(/style="([^"]*)"/g, function (unused, text) {
								var styles = text.match(/[-\w]+\s*:\s*(?:[^&;]+|&quot;.*?&quot;|&(?!quot)(?:#(?:\d+|x[\da-fA-F]+)|[\da-zA-Z]+);)+;?/g).filter(function (rule) {
									return !/^(mso-|tab-stops|page-break-(before|after))/.test(rule);  // remove proprietary style instructions, e.g. mso-margin-top-alt:auto
								})
								return styles.length ? 'style="' + styles.join('') + '"' : '';
							})
						);

						// close pop-up window
						self.hide();
					})
				}
			})
		);

		wordeditor.prepare();
		self._editor = wordeditor;
	},

	'assign': function () {
		this._editor.clear();
	}
});