var newTitle=document.title;
var arrayStatusBar=new Array();
var class_name_save="undefined";
var iscode=false;
var selectedObj=null;
var move=null;
var tagTD=null;
var cellWidth=0;
var cellHeight=0;
var tagTR=null;
var differX=0;
var differY=0;
var tagTABLE=null;
var trIndex=0;
var allWidth=0;
var allCol=0;
var fullTR=0;
var imgWindow=null;
var childWindow=null;

function Send(){
if(iscode)return;
var message="Отправить на сервер?";
if (!confirm(message))return false;

var htm_code=document.createElement('INPUT');
htm_code.type="hidden";
htm_code.name="htm_code";
htm_code.value=document.getElementById('editor').innerHTML;
document.getElementById("form_save").appendChild(htm_code);


var title_save=document.createElement('INPUT');
title_save.type="hidden";
title_save.name="title";
title_save.value=document.title;
document.getElementById("form_save").appendChild(title_save);

document.getElementById("form_save").submit();

}

function CheckKeyCode(){
if(window.event.keyCode==13||window.event.keyCode==8||window.event.keyCode==37||window.event.keyCode==38||window.event.keyCode==39||window.event.keyCode==40||window.event.keyCode==45||window.event.keyCode==46)InitObj();
}
function NewWindow(path){
if(iscode)return;
path=path+".htm";
childWindow = window.open(path, "", "scrollbars,width=700");
}
function CloseWin(){
if(imgWindow)imgWindow.close();
if(childWindow)childWindow.close();
}
function SetTitle(){
if(iscode)return;
var t=window.prompt("Введите новый заголовок документа",document.title);
if(t)newTitle=t;
document.title=newTitle;
}
function Parser(html){
var lev=/</g;
	html=html.replace(lev, "&lt;");
var prav=/>/g;
	html=html.replace(prav, "&gt;");
var alltags = /(&lt;[\w\/]+[ ]*[\w\=\"\'\.\/\;\: \)\(-]*&gt;)/gi;
	html = html.replace(alltags,"<span class=alltags>$1</span>");
var imgtag = /<span class=alltags>(&lt;IMG[ ]*[\w\=\"\'\.\/\;\: \)\(-]*&gt;)<\/span>/gi;
	html = html.replace(imgtag,"<span class=imgtag>$1</span>");
var formtag = /<span class=alltags>(&lt;[\/]*(form|input){1}[ ]*[\w\=\"\'\.\/\;\: \)\(-]*&gt;)<\/span>/gi;
	html = html.replace(formtag,"<br><span class=formtag>$1</span>");
var tabletag = /<span class=alltags>(&lt;[\/]*(table|tbody|th|tr|td){1}([ ]*[\w\=\"\'\.\/\;\:\)\(-]*){0,}&gt;)<\/span>/gi;
	html = html.replace(tabletag,"<span class=tabletag>$1</span>");
var atag = /<span class=alltags>(&lt;\/a&gt;){1}<\/span>/gi;
	html = html.replace(atag,"<span class=atag>$1</span>");
var atag = /<span class=alltags>(&lt;a [\W _\w\=\"\'\.\/\;\:\)\(-]+&gt;){1,}<\/span>/gi;
	html = html.replace(atag,"<span class=atag>$1</span>");
var attribute = /=("[ \w\'\.\/\;\:\)\(-]+"|'[ \w\"\.\/\;\:\)\(-]+')/gi;
	html = html.replace(attribute,"=<span class=attribute>$1</span>");
var comment = /(&lt;\!--[\W _\w\=\"\'\.\/\;\:\)\(-]*--&gt;)/gi;
	html = html.replace(comment,"<span class=comment>$1</span>");
var perenos=/(&lt;(\!--|img|table|tr|th|td|p|a|br))/gi;
	html=html.replace(perenos, "<br>$1");
return html;
}
function Code() {
if (!iscode){//режим кода
	var html = document.getElementById('editor').innerHTML;
	html=Parser(html);
	document.getElementById('editor').innerHTML=html;
	document.getElementById('editor').className="edit";
	document.getElementById('PanelTools_1').className="disable";
	document.getElementById('PanelTools_2').className="disable";
	document.getElementById('PanelTools_3').className="disable";
	document.getElementById('PanelTools_4').className="disable";
	document.getElementById('selectCss').disabled=true;
	document.getElementById('FontSize').disabled=true;
	document.getElementById('FontName').disabled=true;
	document.getElementById('BackColor').disabled=true;
	document.getElementById('ForeColor').disabled=true;
	iscode=true;
	RemoveStatusBar();
	HideArrows();
}else{
	editor.innerHTML=editor.innerText;
	selectedObj=null;
	iscode=false;
	document.getElementById('editor').className="main";
	document.getElementById('PanelTools_1').removeAttribute('className');
	document.getElementById('PanelTools_2').removeAttribute('className');
	document.getElementById('PanelTools_3').removeAttribute('className');
	document.getElementById('PanelTools_4').removeAttribute('className');
	document.getElementById('selectCss').disabled=false;
	document.getElementById('FontSize').disabled=false;
	document.getElementById('FontName').disabled=false;
	document.getElementById('BackColor').disabled=false;
	document.getElementById('ForeColor').disabled=false;
	document.getElementById('editor').blur();
}
}

function Modal(what){
if (iscode)return;
var url, atr;
   switch(what){
   case "table":
      url = "dlg/table.htm";
      atr = "status:no;dialogWidth:322px;dialogHeight:220px;help:no";
      Insert(window.showModalDialog(url,window,atr));
      break;
   case "char":
      url = "dlg/char.htm";
      atr = "status:no;dialogWidth:305px;dialogHeight:270px;help:no";
      Insert(window.showModalDialog(url,window,atr));
      break;
   case "img":
        url = "dlg/image.php";
		if (imgWindow)imgWindow.close();
		imgWindow=window.open(url,"","height=530, width=550");
		return;
   case "link":// возвратит объект(массив - Array(url,target))
      url = "dlg/link.htm";
      atr = "status:no;dialogWidth:390px;dialogHeight:150px;help:no";
	  Insert(window.showModalDialog(url,window,atr));
	  break;
   }
//return window.showModalDialog(url,window,atr);
}

function Insert(el){
if (!el) return;
editor.focus();
if (document.selection.type=="Control") {
	if (typeof(el)=='object'){// если el-array(url,target)-значит это ссылка
		if(selectedObj.nodeName=='IMG'){
			alert("В демоверсии изображение нельзя сделать ссылкой");
			return;
		}
	el='<a href="http:\/\/'+el[0]+'" target="'+el[1]+'">'+el[0]+'</a>';
	}
selectedObj.insertAdjacentHTML("afterEnd",el);
}else{
	var sel = document.selection.createRange();
	if (typeof(el)=='object'){
		el=(sel.text)?'<a href="http:\/\/'+el[0]+'" target="'+el[1]+'">'+sel.text+'</a>':'<a href="http:\/\/'+el[0]+'" target="'+el[1]+'">'+el[0]+'</a>';
	}
	sel.pasteHTML(el);
}
	HideArrows();
}
function ChangeMarginP(action){
if (iscode||!selectedObj)return;
if (selectedObj.nodeName!='P')return;
	var marginValue =(selectedObj.style.marginTop)?parseInt(selectedObj.style.marginTop):16;
	if(action=="incr"){
		selectedObj.style.marginTop=marginValue+4;
		selectedObj.style.marginBottom=marginValue+4;
	}else{
		if(marginValue-4<0)return;
		selectedObj.style.marginTop=marginValue-4;
		selectedObj.style.marginBottom=marginValue-4;
	}
}

function InitObj(){
if (iscode)return;
HideArrows();
var sel=document.selection.createRange();
selectedObj=(document.selection.type!="Control")?sel.parentElement():window.event.srcElement;
SetInterface();
StatusBar();
if(window.event.button)SetTable();
}
function UnsetObj(){
if(iscode)return;
selectedObj=null;
HideArrows();
RemoveStatusBar();
UnsetInterface();
}
function RemoveStatusBar() {
while(document.getElementById("statusBar").firstChild)document.getElementById("statusBar").removeChild(document.getElementById("statusBar").firstChild);
arrayStatusBar.length=0;
}
function GetCSS(el) {
if (!el||iscode||selectedObj.id=="editor")return;
if(el.className){
document.getElementById('selectCss').options[0].text=el.className;
document.getElementById('selectCss').disabled=false;
}
}
function StatusBar() {
if (!selectedObj||iscode)return;
RemoveStatusBar();
var el=selectedObj;
var first=false;
while(el.id!="editor"){
	var nameEl="";
	switch(el.nodeName){

		case "BODY":
			selectedObj=null;
			RemoveStatusBar();
			return;
		case "P":
			nameEl="абзац";
			break;
		case "TD":
			nameEl="ячейка";
			break;
		case "TABLE":
			nameEl="таблица";
			break;
		case "A":
			nameEl="ссылка";
			break;
		case "IMG":
			nameEl="картинка";
			break;
		case "UL":
			nameEl="список";
			break;
		case "UL":
			nameEl="список";
			break;
		case "LI":
			nameEl="элемент списка";
			break;
		case "BLOCKQUOTE":
			nameEl="отступ";
			break;
	}
	if(nameEl){
		var objAlign="";
		var objClass="";
		if(el.style.align)objAlign=el.style.align;
		if(el.align)objAlign=el.align;
		if(objAlign){
			objAlign=objAlign.toLowerCase();
			switch(objAlign){
				case"left":
					objAlign=" влево";
					break;
				case"right":
					objAlign=" вправо";
					break;
				case"center":
					objAlign=" по центру";
					break;
				case"justify":
					objAlign=" по ширине";
					break;
				}
		objAlign="<span class='alignobj'>"+objAlign+"</span>";
		}
		nameEl="> "+nameEl;
		var newlink=document.createElement("A");
		if(!first)document.getElementById('selectCss').options[0].text="Выберите стиль";
		if(el.className){
			objClass="<span class='classcss'> "+el.className+"</span>";
			if (!first)document.getElementById('selectCss').options[0].text=el.className;
		}
		first=true;
		nameEl=nameEl+objAlign+objClass;
		newlink.innerHTML=nameEl;
		arrayStatusBar.unshift(el);
		(document.getElementById("statusBar").firstChild)?document.getElementById("statusBar").insertBefore(newlink,document.getElementById("statusBar").firstChild):document.getElementById("statusBar").appendChild(newlink);
	var nameEl="";
	}
el=el.parentNode;
}

}
function UnSelectStatusBar() {
var el=document.getElementById('statusBar');
if(el.firstChild)for(i=0; i<el.childNodes.length;i++)el.childNodes[i].removeAttribute('className');
}
function MakeSelection() {
if(!selectedObj)return;
UnSelectStatusBar();
el = window.event.srcElement;
if(el.nodeName=="TD")return;
if(el.nodeName=="SPAN")el=el.parentNode;
el.className="press";
for(i=0;i<arrayStatusBar.length;i++)if(document.getElementById('statusBar').childNodes[i].className=="press")selectedObj=arrayStatusBar[i];
var range = document.body.createTextRange();
range.moveToElementText(selectedObj);
range.select();
if(selectedObj.nodeName!="IMG"){
	GetCSS(selectedObj);
	document.getElementById('selectCss').disabled=false;
	}
HideArrows();
}
function SetMove(){
document.getElementById("rArrow").style.visibility = 'hidden';
document.getElementById("dArrow").style.visibility = 'hidden';
move = event.srcElement.parentElement;
differX=event.clientX;
differY=event.clientY;
}
function UnsetInterface(){
var Buttons=new Array("Cut","Copy","Paste","Undo","Redo","SelAll","RemForm",
      "Link","Unlink","Img","Char","InsTable","Bord","AdRows",
      "RemRows","AddCols","RemCols","AddCSpan","RemCSpan","AddRSpan",
      "RemRSpan","JustifyLeft","JustifyCenter","JustifyRight","JustifyFull",
      "Rem_Align","Bold","Italic","Underline","Strikethrough","Indent",

      "Outdent","Superscript","Subscript","InsUlist","InsOlist");
for (i in Buttons)eval("document.getElementById('"+Buttons[i]+"').removeAttribute('className')");
HideLayers();
document.getElementById('ForeColor').style.backgroundColor="white";
document.getElementById('BackColor').style.backgroundColor="white";
document.getElementById('selectCss').options[0].text="Нет объекта";
document.getElementById('FontSize').options[0].selected=true;
document.getElementById('FontSize').options[0].text="";
document.getElementById('FontName').options[0].selected=true;
document.getElementById('FontName').options[0].text="";
}
function mousemove(){
if (move) {
	if (move.id=="rArrow"){
	ResizeCol();
	}
	else if  (move.id=="dArrow"){
	ResizeRow();
	}
return false;
}
}
function Style(what){
if (iscode||!document.selection.createRange().text)return;
if (document.selection.type=="Text"){
	document.execCommand(what,false,null);
	class_name_save="imgpress";
}
}
function Align(what){
if (iscode||!selectedObj)return;
if ((what=="JustifyFull" && selectedObj.tagName=="TD")||(what=="JustifyCenter" && selectedObj.tagName=="IMG")||(what=="JustifyFull" && selectedObj.tagName=="IMG") || (what=="JustifyFull" && selectedObj.tagName=="TABLE"))return;
if(selectedObj.align)selectedObj.removeAttribute('align');
if(selectedObj.style.align)selectedObj.style.removeAttribute('align');
if(what=="Remove"){
	StatusBar();
	HideArrows();
	return;
}
if (selectedObj.tagName=="TABLE"||selectedObj.tagName=="TD"||(selectedObj.tagName=="DIV" && selectedObj.id!="editor")||selectedObj.tagName=="P"||selectedObj.tagName=="IMG"){
	(what=="JustifyFull")?selectedObj.align="justify":selectedObj.align = what.substring(7,20);
	SetInterface();
	selectedObj.focus();
}else{
	document.execCommand(what);
	SetInterface();
	selectedObj.focus();
}
StatusBar();
HideArrows();
}
function Hover(on) {
var el=event.srcElement;
if(iscode&&el.id!="Code"||el.className=="imgspacer")return;
if (el && el.nodeName == "IMG"&&el.id!="img_css_style") {
switch(on){
	case "over":
		if(el.id=="Send"){
			el.className = "imghoverbig";
		}else{
			class_name_save=el.className;
        	el.className = "imghover";
        }
        break;
	case "down":
        (el.id=="Send")?el.className = "imgpressbig":el.className = "imgpress";
		break;
	case "up":
		editor.focus();
default:
	if(el.id=="Send"){
		el.className="send";
	}
	else (class_name_save=="undefined")?el.removeAttribute('className'):el.className=class_name_save;
}
}
}
function DoCommand(what,usrInt,vVal) {
if(iscode)return;
document.getElementById('editor').focus();
if(selectedObj){//Отлавливаем глюк с IMG и ссылкой
	if(selectedObj.nodeName=="IMG"&&what=="Cut"){
		var mylink=selectedObj.parentNode;
		if(mylink.nodeName=="A"&&mylink.childNodes.length==1){
			var parentMylink=mylink.parentNode;
			for(i in parentMylink.childNodes){
				if (parentMylink.childNodes[i]==mylink){
					document.execCommand(what,usrInt,vVal);
					if(mylink)parentMylink.removeChild(parentMylink.childNodes[i]);//Удаляем пустую ссылку
					InitObj();
					return;
				}
			}
		}
	}
}
document.execCommand(what,usrInt,vVal);
InitObj();
}
function SetInterface() {
if (iscode || !selectedObj)return;
document.getElementById('editor').focus();
UnsetInterface();
GetCSS(selectedObj);
var txt_attrib  =  new Array('JustifyLeft','JustifyCenter','JustifyRight','JustifyFull','Superscript','Subscript','Bold','Italic','Underline','Strikethrough','FontSize','FontName','ForeColor','BackColor');var control_attrib=new Array('left','center','right');
if(document.selection.type=="Control"){
	for(i in control_attrib){
		if (selectedObj.getAttribute('align')==control_attrib[i]){
			eval('document.all.'+txt_attrib[i]+'.className="imgpress"');
			class_name_save="imgpress";
		}
	}
}else{
	document.selection.createRange();
	for(i in txt_attrib){
		if(document.queryCommandValue(txt_attrib[i])){
		var el=eval('document.getElementById("'+txt_attrib[i]+'")');
			if (el.nodeName=="IMG"){
			el.className="imgpress";
			class_name_save="imgpress";
			}
			if (el.nodeName=="SELECT"){
				if(el.id=="ForeColor"||el.id=="BackColor"){
					el.style.backgroundColor=ConvertColor(document.queryCommandValue(txt_attrib[i]));
				}else{
					el.options[0].text=document.queryCommandValue(txt_attrib[i]);
					el.options[0].selected=true;
				}
			}
		}
	}
}
}
function DoCss(el,key){
if (iscode||!selectedObj)return;
document.getElementById('selectCss').disabled=false;
if(!key){
alert("В демоверсии нельзя убрать стиль CSS");
}else{
	if (selectedObj.id!="editor") selectedObj.className=el.className;
	StatusBar();
	selectedObj.focus();
}
document.getElementById("layer_css_style").style.visibility = 'hidden';
GetCSS(selectedObj);
}
function  ColorIndicator(){
var el=window.event.srcElement;
if(el.title)document.getElementById('colorTopRight').style.backgroundColor=el.title;
}
function hex(d) {
	return (d < 16) ? ("0" + d.toString(16)) : d.toString(16);
}
function ConvertColor(v){
if (v[0] == "#") return v;
if (typeof v == "number") {
	var r = v & 0xFF;
	var g = (v >> 8) & 0xFF;
	var b = (v >> 16) & 0xFF;
	return "#" + hex(r) + hex(g) + hex(b);
}
return "#FFFFFF";
}
function SetBackColor(){
if (iscode)return;
var el=window.event.srcElement;
var color="";
var what=WhoCallColor();
if(el.nodeName=="TD"&&el.title){
	color=el.title.substring(1,7);
	if(what!="td"){//фон в тексте
alert("В демоверсии эта опция отключена");

	}else{
		if(tagTD){
			if (tagTD.bgColor)tagTD.bgColor=color;
			else tagTD.style.backgroundColor=color;
		}
	}
}
document.getElementById('layer_color').style.visibility="hidden";
BackColor.disabled=false;
ForeColor.disabled=false;
}
function WhoCallColor(){
var c="";
	if(document.getElementById('BackColor').disabled==true)c="BackColor";
	else if(document.getElementById('ForeColor').disabled==true)c="ForeColor";
	else c="td";
return c;
}
function RemoveBackColor(){
alert("В демо версии эта опция отключена")
}
function ShowLayerColor(){
if (iscode)return;
document.getElementById('layer_color').style.visibility="visible";
document.getElementById("layer_css_style").style.visibility = 'hidden';
var el=window.event.srcElement;
if (el.nodeName!="IMG")window.event.srcElement.disabled=true;
}
function HideLayers(){
document.getElementById('layer_color').style.visibility="hidden";
document.getElementById("layer_css_style").style.visibility = 'hidden';
if(!iscode){
	document.getElementById('BackColor').disabled=false;
	document.getElementById('ForeColor').disabled=false;
	document.getElementById('selectCss').disabled=false;
}
}
function ShowLayerCss(){
if (iscode||!selectedObj||selectedObj.id=="editor")return;
document.getElementById('layer_color').style.visibility="hidden";
if (selectedObj.nodeName=="TD"||selectedObj.tagName=="P"||selectedObj.tagName=="DIV"||selectedObj.tagName=="SPAN"||selectedObj.tagName=="BLOCKQUOTE"||selectedObj.tagName=="A"||selectedObj.tagName=="OL"||selectedObj.tagName=="UL"||selectedObj.tagName=="LI"){
	document.getElementById('selectCss').disabled=true;
	document.getElementById("layer_css_style").style.visibility = 'visible';
	}
editor.focus();
}
function setwidth(){
document.getElementById('editor').style.width=document.body.clientWidth-10;
document.getElementById('editor').style.height=document.body.clientHeight-93;
}
