// ContentEditor v0.9 (DRAFT)
// copyright (c) 2002 by taker, http://taker.artstyle.ru
// taker.design@artstyle.ru, ICQ7793748

DEFAULT_WIDTH  = 640;		// ширина и высота блока редактирования по умолчанию
DEFAULT_HEIGHT = 420;		// при инициализации можно переназначить

COLOR_LIGHT  = "#FFFFFF";	// цвета трехмерных объектов
COLOR_DARK	 = "#9D9DA1";
COLOR_NORMAL = "#E0DFE3";

EDITOR_PATH = "/editor/";
IMAGES_PATH = "/img/editor/";

COLORS_LIST = new Array (
		new Color("#000000", "Черный (Black)"),
		new Color("#000080", "Темно-синий (Navy)"),
		new Color("#0000FF", "Синий (Blue)"),
		new Color("#800000", "Коричневый (Maroon)"),
		new Color("#800080", "Пурпурный (Purple)"),
		new Color("#008000", "Зеленый (Green)"),
		new Color("#FF0000", "Красный (Red)"),
		new Color("#008080", "Морской волны (Teal)"),
		new Color("#FF00FF", "Фиолетовый (Magenta)"),
		new Color("#808000", "Оливковый (Olive)"),
		new Color("#808080", "Темно-серый (Gray)"),
		new Color("#00FF00", "Лимонный (Lime)"),
		new Color("#00FFFF", "Аква (Aqua)"),
		new Color("#CCCCCC", "Серый (Silver)"),
		new Color("#FFFF00", "Желтый (Yellow)"),
		new Color("#FFFFFF", "Белый (White)")
	);

// ================== Служебные переменные ==================

BUTTON_OVER = 1;
BUTTON_OUT  = 2;
BUTTON_DOWN = 3;

var objCounter = 0;
var editorCounter = 0;
var allEditors = new Array();

// ================== Управляющие шаблоны ==================

var vertDiv = '<table width="100%" border="0" cellspacing="0" cellpadding="0">' +
		'<tr><td><img src="' + IMAGES_PATH + 'void.gif" alt="" width="1" height="3" border="0"></td></tr>' +
		'<tr><td bgcolor="#9D9DA1"><img src="' + IMAGES_PATH + 'void.gif" alt="" width="1" height="1" border="0"></td></tr>' +
		'<tr><td bgcolor="#FFFFFF"><img src="' + IMAGES_PATH + 'void.gif" alt="" width="1" height="1" border="0"></td></tr>' +
		'<tr><td><img src="' + IMAGES_PATH + 'void.gif" alt="" width="1" height="3" border="0"></td></tr>' +
		'</table>';
		
var horizDiv = '<td><img src="' + IMAGES_PATH + 'div.gif" alt="" width="2" hspace="2" height="24" border="0"></td>';		

function newButton(picture, title, action) {
	var name = "button_" + objCounter++;
	var str = '<td><span id="' + name + 'Border" style="position:relative;width:26;height:25" class="btn" unselectable="on">' +
		'<img id="' + name + '" src="' + IMAGES_PATH + picture + '" border=0 style="position:absolute;top:0;left:0" width=23 height=22 ' +
		'onmouseover="button_over(this)" onmouseout="button_out(this)" ' +
		'onmousedown="button_down(this)" onmouseup="button_out(this)" ' +
		'onselectstart="button_void(this)" ondragstart="button_void(this)" ' +
		'onclick="button_over(this); ' + action + '" title="' + title + '" alt="' + title + '">' +
		'</span></td>';
	return str;
}

function codeViewControl(id) {
	return '<td><table border="0" cellspacing="0" cellpadding="0"><tr><td>' + 
		'<input type="checkbox" name="codeview" value="1" onclick="codeView(\'' + id + '\',this.checked)">' +
		'</td><td class="panel">html-код</td></tr></table></td>';
}

function styleSelector(id) {
	return '<td>&nbsp;<select onchange="applyStyle(\'' + id + '\',this)" class="panel">' +
		'<option>Стиль</option>' +
		'<option value="Normal">Обычный текст</option>' +
		'<option value="Heading 1">Заголовок 1 &lt;H1&gt;</option>' +
		'<option value="Heading 2">Заголовок 2 &lt;H2&gt;</option>' +
		'<option value="Heading 3">Заголовок 3 &lt;H3&gt;</option>' +
		'<option value="Heading 4">Заголовок 4 &lt;H4&gt;</option>' +
		'<option value="Heading 5">Заголовок 5 &lt;H5&gt;</option>' +
		'<option value="Heading 6">Заголовок 6 &lt;H6&gt;</option>' +
		'<option value="Address">Адрес &lt;ADDR&gt;</option>' +
		'</select>&nbsp;</td>';
}

function colorSelector(id) {
	var colors_selector = '<td>&nbsp;<select onchange="applyColor(\'' + id + '\',this)" class="panel"><option>Цвет текста&nbsp;&nbsp;</option>';
	for (var i = 0; i < COLORS_LIST.length; i++)
		colors_selector += '<option value="' + COLORS_LIST[i].value + '" style="background-color:' + COLORS_LIST[i].value + '">&nbsp;</option>';
	colors_selector += '</select>&nbsp;</td>';
	return colors_selector;
}

// ================== Интерфейсная часть ==================

function Editor(form, name, width, height) {
	this.id = "_Editor_" + editorCounter++;
	this.name = name;
	this.form = form;
	this.init = EditorInit;
	this.flush = EditorFlush;
	this.content = EditorContent;
	this.button = EditorButton;
	this.width = (width) ? width : DEFAULT_WIDTH;
	this.height = (height) ? height : DEFAULT_HEIGHT;
}

function EditorContent() {
	if (this.visualMode) {
		return eval(this.id + '.document.body.' + ((eval(this.id + '.editorTextMode')) ? 'innerText' : 'innerHTML'));
	} else {
		return document.forms[this.form].elements[this.name].value;
	}
}

function EditorFlush() {
	if (this.visualMode)
		document.forms[this.form].elements[this.name].value = 
			eval(this.id + '.document.body.' + ((eval(this.id + '.editorTextMode')) ? 'innerText' : 'innerHTML'));
}

function EditorButton(picture, title, action) {
	return newButton(picture, title, "formatCommand('" + this.id + "','" + action + "')");
}

function EditorInit(text) {
	this.visualMode = (document.all && (!window.opera)) ? true : false;
	if (text == null) text = '';
	if (this.visualMode) {
		document.writeln(
			'<table width="' + this.width + '" border="0" cellspacing="0" cellpadding="3" bgcolor="' + COLOR_NORMAL + '" unselectable="on"><tr><td>' +
			'<table border="0" cellspacing="0" cellpadding="0"><tr>' +
				styleSelector(this.id) +
				horizDiv +
				colorSelector(this.id) +
				horizDiv +
				codeViewControl(this.id) +
			'</tr></table>' +
				vertDiv +
			'<table border="0" cellspacing="0" cellpadding="0"><tr>' +
				newButton("save.gif", "Сохранить изменения", "dataSave(); document.forms." + this.form + ".submit();") +
				horizDiv +
				newButton("cut.gif", "Вырезать", this.id + ".document.execCommand('Cut')") +
				newButton("copy.gif", "Копировать", this.id + ".document.execCommand('Copy')") +
				newButton("paste.gif", "Вставить", this.id + ".document.execCommand('Paste')") +
//				horizDiv +
//				this.button("undo.gif", "Отменить", "Undo") +
//				this.button("redo.gif", "Вернуть", "Redo") +
				horizDiv +
				this.button("bold.gif", "Полужирный", "Bold") +
				this.button("italic.gif", "Курсив", "Italic") +
				this.button("under.gif", "Подчеркнутый", "Underline") +
				horizDiv +
				this.button("left.gif", "По левому краю", "justifyLeft") +
				this.button("center.gif", "По центру", "justifyCenter") +
				this.button("right.gif", "По правому краю", "justifyRight") +
				this.button("full.gif", "По ширине", "justifyFull") +
//				horizDiv +
//				this.button("numlist.gif", "Нумерация", "insertOrderedList") +
//				this.button("bullist.gif", "Маркеры", "insertUnorderedList") +
//				this.button("unindent.gif", "Уменьшить отступ", "outdent") +
//				this.button("indent.gif", "Увеличить отступ", "indent") +
				horizDiv +
				this.button("link.gif", "Ссылка", "createLink") +
				newButton("image.gif", "Вставить изображение", "openImager('" + this.id + "')") +
			'</tr></table>' +
			'</td></tr></table>\n' +
			'<input type="hidden" name="' + this.name + '" value="">\n' +
			'<iframe name="' + this.id + '" width="' + this.width + '" height="' + this.height + '"></iframe>\n'
		);
		var html = '<style> body, p, td { font-family: Verdana, Arial, sans-serif; font-size: 10pt; } </style><body topmargin=5 leftmargin=5>' + text + '</body>';
		eval(this.id + '.document.open()');
		eval(this.id + '.document.write(html)');
		eval(this.id + '.document.close()');
		eval(this.id + '.document.designMode = "On"');
		eval(this.id + '.editorTextMode = false');
	} else {
		document.writeln('<textarea name="' + this.name + '" cols="60" rows="20" vrap="virtual" style="width:' + this.width + 'px;height:' + this.height + 'px">' + text + '</textarea>');
	}
	allEditors[allEditors.length] = this;
}

function Color(value, name) {
	this.value = value;
	this.name = name;
}

function showWarning() {
	alert('Данная команда не поддерживается в режиме редактирования HTML-кода.');
}

function dataSave() {
	for (var i = 0; i < allEditors.length; i++)
		allEditors[i].flush();
}

// ================== Программная часть ==================

function formatCommand(id, action, format) {
	var editor = eval(id);
	editor.focus();
	if (editor.editorTextMode) showWarning();
		else if (format == null) editor.document.execCommand(action);
				else editor.document.execCommand(action, "", format);
}

function applyColor(id, select_obj) {
	if (select_obj[select_obj.selectedIndex].value)
		formatCommand(id, "foreColor", select_obj[select_obj.selectedIndex].value);
	select_obj.selectedIndex = 0;
}

function codeView(id, textMode) {
	var editor = eval(id);
	editor.editorTextMode = textMode;
	if (textMode) editor.document.body.innerText = editor.document.body.innerHTML;
		else editor.document.body.innerHTML = editor.document.body.innerText;
	editor.focus();
}

function applyStyle(id, select_obj) {
	if (select_obj[select_obj.selectedIndex].value)
		formatCommand(id, "formatBlock", select_obj[select_obj.selectedIndex].value);
	select_obj.selectedIndex = 0;
}

function newWindow(url, width, height) {
	var myPos = (screen) ? ',left=' + parseInt((screen.width-width)/2) + ',top=' + parseInt((screen.height-height)/2) : '';
	var myWin = window.open(url, 'myWin', 'width=' + width + ',height=' + height + ',menubar=0,location=0,resizable=0,scrollbars=0,toolbar=0' + myPos);
	myWin.focus();
	return myWin;
}

function findElement(tag, range) {
	for (i = 0; i < range.length; i++)
		if (range(i).tagName == tag)
			return range(i);
}

function absoluteImagePath(url) { return url.replace(/.*\/img\//,"/img/"); }

function ImagerArguments(id, image) {
	this.windowID = window.self;
	this.editorID = id;
	if (image) {
		this.source = absoluteImagePath(image.src);
		this.title = image.alt;
		this.width = image.width;
		this.height = image.height;
		this.hspace = (image.outerHTML.match(/hspace=/i)) ? image.hspace : '';
		this.vspace = (image.outerHTML.match(/vspace=/i)) ? image.vspace : '';
		this.align = image.align;
	}
}

function openImager(id) {
	var editor = eval(id);
	editor.focus();
	var image = (editor.document.selection.type == "Control") ? findElement("IMG", editor.document.selection.createRange()) : null;
	var arguments = new ImagerArguments(id, image);
	window.showModalDialog(EDITOR_PATH + 'imager', arguments, "dialogWidth: 590px; dialogHeight: 480px; edge: Raised; center: Yes; help: No; resizable: No; status: No;");
}

function isInteger(str) { return str.match(/^\d+$/); }

function insertImage(id, source, title, width, height, hspace, vspace, align) {
	var editor = eval(id);
	var imgTag = '<img src="' + source + 
		'" width="' + width + 
		'" height="' + height + 
		'" alt="' + title + 
		(isInteger(hspace) ? '" hspace="' + hspace : '') +
		(isInteger(vspace) ? '" vspace="' + vspace : '') +
		((align) ? '" align="' + align : '') +
		'" border="0">';
	editor.focus();
	if (editor.document.selection.type == "Control") editor.document.selection.clear();
	var range = editor.document.selection.createRange();
	range.pasteHTML(imgTag);
	range.select();
}

// ================== Манипулирование кнопками ==================

function button_manipulate(button_obj, command) {
	var border_obj = document.all[button_obj.id + "Border"];
	var button_offset = (command == BUTTON_DOWN) ? 1 : 0;
	var color_one = ((command == BUTTON_OVER) ? COLOR_LIGHT : ((command == BUTTON_DOWN) ? COLOR_DARK : COLOR_NORMAL));
	var color_two = ((command == BUTTON_OVER) ? COLOR_DARK : ((command == BUTTON_DOWN) ? COLOR_LIGHT : COLOR_NORMAL));
	border_obj.style.borderTopColor = color_one;
	border_obj.style.borderLeftColor = color_one;
	border_obj.style.borderRightColor = color_two;
	border_obj.style.borderBottomColor = color_two;
	button_obj.style.top = button_offset;
	button_obj.style.left = button_offset;
}

function button_over(button_obj) { button_manipulate(button_obj, BUTTON_OVER); }
function button_out(button_obj) { button_manipulate(button_obj, BUTTON_OUT); }
function button_down(button_obj) { button_manipulate(button_obj, BUTTON_DOWN); }
function button_void(button_obj) { window.event.returnValue = false; }

// ================== Thumbnails control ==================

function openImager(id) {
	var editor = eval(id);
	editor.focus();
	var image = (editor.document.selection.type == "Control") ? findElement("IMG", editor.document.selection.createRange()) : null;
	var arguments = new ImagerArguments(id, image);
	window.showModalDialog(EDITOR_PATH + 'imager', arguments, "dialogWidth: 590px; dialogHeight: 480px; edge: Raised; center: Yes; help: No; resizable: No; status: No;");
}

function parseThumbnails() {
	var text = '';
	for (var i = 0; i < allEditors.length; i++) text += allEditors[i].content();
	var thumblist = text.match(/<img[^>]*>/gi);
	if (thumblist) {
		for (var i = 0; i < thumblist.length; i++) {
			thumblist[i] = thumblist[i].replace(/.*src=\"?([^\s\"]+)\"?\s.*/gi, "$1");
			thumblist[i] = "/img/preview/" + thumblist[i].replace(/^.*\//, "");
		}
	}
	return thumblist;
}

function loadThumbnail(form, img) {
	form.pic.value = (img) ? img : '';
	document.images.thumbnail.src = (img) ? img : IMAGES_PATH + 'void.gif';
}

function chooseThumbnail(form) {
	var args = new Object();
	args.windowID = window.self;
	args.form = form;
	args.thumbnails = parseThumbnails();
	if (args.thumbnails) {
		window.showModalDialog(EDITOR_PATH + 'thumbnails', args, "dialogWidth: 520px; dialogHeight: 200px; edge: Raised; center: Yes; help: No; resizable: No; status: No;");
	} else {
		alert('В редактируемом документе отсутсвуют изображения.');
	}
}


