// ===========================
// Checking Browsers fo WWWG Compatibility
// ===========================

function getBrowser() {

var agt = navigator.userAgent.toLowerCase();
var is_op = (agt.indexOf("opera") != -1);
var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op;
var is_ie5 = (agt.indexOf("msie 5") != -1) && document.all && !is_op;
var is_mac = (agt.indexOf("mac") != -1);
var is_gk = (agt.indexOf("gecko") != -1);
var is_sf = (agt.indexOf("safari") != -1);

if (is_ie && !is_op && !is_mac) {
   if (
	agt.indexOf("palmsource") != -1 ||
	agt.indexOf("regking") != -1 ||
	agt.indexOf("windows ce") != -1 ||
	agt.indexOf("j2me") != -1 ||
	agt.indexOf("avantgo") != -1 ||
	agt.indexOf(" stb") != -1
      ) {
	 return false;
	}

    var v = GetFollowingFloat(agt, "msie ");
    if (v != null)
	return (v >= 5.5);
}

if (is_gk && !is_sf) {

    var v = GetFollowingFloat(agt, "rv:");
    if (v != null)
	return (v >= 1.4);
    else {

	v = GetFollowingFloat(agt, "galeon/");
	if (v != null)
		return (v >= 1.3);
    }
}

if (is_sf) {
 var v = GetFollowingFloat(agt, "applewebkit/");
 if (v != null)
	return (v >= 312);
}

if (is_op) {
 if (agt.indexOf("sony/com1") != -1)
	return false;
 // Could have "Opera 8.0" or "Opera/8.0".
 var v = GetFollowingFloat(agt, "opera ");
 if (v == null)
	v = GetFollowingFloat(agt, "opera/");
 if (v != null)
	return (v >= 8.0);		
 }		 
 return false;
}

function GetFollowingFloat(str, pfx) {
 var i = str.indexOf(pfx);
 if (i != -1) {
	var v = parseFloat(str.substring(i + pfx.length));
	if (!isNaN(v))
		return v;
 }
 return null;
}

var isWWGcompatible = false;
function checkWWGcompatibility(where, id, bid){
 if(getCookie('def_edit') == 'bb'){
	myGetCnt('bb', where, id, bid, true, true);
	$('editors_0').style.display = 'block';
	$('editors_1').style.display = 'block';
	return true;
 }
 else{
  if(getBrowser()){
	$('wwg_onload').style.display = 'block';
	$('editors_0').style.display = 'block';
	$('editors_1').style.display = 'block';
	editor = 'wwg'; // Устанавливаем переменную в значение текущего редактора, чтобы определить, куда вставлять текст
  }
  else {
        myGetCnt('bb', where, id, bid, true, true);
	//предпоследний параметр отвечает за вопрос "Вы уверены что хотите переключиться между закладками"
	//последний параметр отвечает за подгрузку текста сообщения в ббедитор в случае если браузер не совместим с визивигом
	$('editors_0').style.display = 'none';
	$('editors_1').style.display = 'block';
  }
 }
 isWWGcompatible = true;
}

// =======================
// = BBEditor code =
// =======================

var b = 2;
var i = 2;
var u = 2;
var q = 2;
var c = 2;
var url = 2;
var img = 2;
var email = 2;
var user = 2;
var community = 2;
var cut = 2;
var s = 2;
var sup = 2;
var sub =2;

var bold_help = "жирный текст: [b]текст[/b]";
var italic_help = "текст курсивом: [i]текст[/i]";
var underline_help = "подчеркнутый text: [u]текст[/u]";
var quote_help = "цитирование: [quote]текст[/quote]";
var code_help = "отображение кода: [code]код[/code]";
var img_help = "вставка картинки: [img]http://image_url[/img]";
var url_help = "вставка URL: [url]http://url[/url] или [url=http://url]текст[/url]";
var email_help = "встака E-mail: [email=email@url]текст[/email]";
var fontcolor_help = "цвет шрифта: [color=red]текст[/color]";
var fontsize_help = "размер шрифта: [size=50%]текст[/size]";
var user_help = "ссылка на блог:  [user=блог]текст[/user] или [user]блог[/user]";
var community_help = "ссылка на сообщество:  [community=блог]текст[/community] или [community]сообщество[/community]";
var cut_help = "врезка текста: [cut=description]текст[/cut] или [cut]текст[/cut]";
var s_help = "зачеркивание текста: [s]текст[/s]";
var sub_help = "нижний индекс: [sub]текст[/sub]";
var sup_help = "верхний индекс: [sup]текст[/sup]";
var resetConfirmation = "Вы действительно хотите стереть все?";
var emptyContentAlert = "вы забыли создать сообщение";

var clientPC = navigator.userAgent.toLowerCase();
var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
function tag(v, tagadd, newbut, tagclose, oldbut, name) {
 if (is_ie)
 {
	var comment = document.getElementById("comment");
	theSelection = document.selection.createRange().text; 
	if (theSelection) {
		document.selection.createRange().text = tagadd + theSelection + tagclose;			
		theSelection = '';
	}

	else {
//		open tag		
		if (eval(v)%2 == 0) {
			changeButtonName(name, newbut);
			comment.value = comment.value + tagadd;
		}
//		close tag
		else {
			changeButtonName(name, oldbut);
			comment.value = comment.value + tagclose;
		}
					
		eval(v+"++;");
	}
	comment.focus();
 }
 else {
	var comment = window.document.editform.content;
	var start = comment.selectionStart;
	var end = comment.selectionEnd;	

	if (start == end) {	
		var startStr = comment.value.substring(0, start);
		var endStr = comment.value.substring(start);
		
		if (eval(v)%2 == 0) {
			changeButtonName(name, newbut);
			insertTag(tagadd, startStr, endStr);
			start += tagadd.length;
		}		
		else {
			changeButtonName(name, oldbut);
			insertTag(tagclose, startStr, endStr);
			start += tagclose.length;
		}
		
		comment.selectionStart = start;
		comment.selectionEnd = start;
	    eval(v+"++;");
	}	
	else {
		var startStr = comment.value.substring(0, start);
		var selectedStr = comment.value.substring(start, end);
		var endStr = comment.value.substring(end);		

		tagString(tagadd, tagclose, startStr, selectedStr, endStr);
		
		start += tagadd.length + selectedStr.length + tagclose.length;
		comment.selectionStart = start;
		comment.selectionEnd = start;		
	}
 }
}

function tagString(tagOpen, tagClose, startStr, selectedStr, endStr) {
 window.document.editform.content.value = startStr + tagOpen + selectedStr + tagClose + endStr;
 window.document.editform.content.focus();
}

function changeButtonName(name, buttonName) {
	eval("window.document.editform."+name+".value = buttonName;");
}

function insertTag(tag, startStr, endStr) {
 window.document.editform.content.value = startStr + tag + endStr;
 window.document.editform.content.focus();
}

function font(tagadd, tagclose) {
 if (is_ie) {
	var comment = document.getElementById("comment");	
	theSelection = document.selection.createRange().text; 
	if (theSelection) {
		document.selection.createRange().text = tagadd + theSelection + tagclose;
		theSelection = '';
	}
	else
		comment.value = comment.value + tagadd + tagclose;
	
	comment.focus();
	return;			
 }
 else {
	var comment = window.document.editform.content;
	var start = content.selectionStart;
	var end = content.selectionEnd;		
//	get sliced string 
	var startStr = comment.value.substring(0, start);
	var selectedStr = comment.value.substring(start, end);
	var endStr = comment.value.substring(end);		
//	put tags over selected string		
	tagString(tagadd, tagclose, startStr, selectedStr, endStr);
	
	if (start == end) start += tagadd.length;
	else start += tagadd.length + selectedStr.length + tagclose.length;
	comment.selectionStart = start;
	comment.selectionEnd = start;
 }		
}
function helpline(help) {		
        var helpbox = document.editform.helpbox;
        if (help == undefined) { 
        	helpbox.value = '';
        	return;
        }
        helpbox.value = eval(help + "_help");
}

//Function to confirm reset
function confirm_reset () {
	if(confirm(resetConfirmation)) {
	 var comment = document.getElementById("comment");
	 comment.value = "";
	 comment.innerText = "";
	}
}

//Check form emptyness
function simulateButton(name) {
 var button = eval('document.editform.'+name);
 button.value = name;
 document.editform.submit();
}
function ctrlsub() {
 if((event.ctrlKey) && ((event.keyCode==10)||(event.keyCode==13))) {
  this.form.submit();
 }
}

// =======================
// = WYSIWYG Editor code =
// =======================

function $(id)
{
	return document.getElementById(id);
}

function getCookie(name) {
 var cookie = " " + document.cookie;
 var search = " " + name + "=";
 var setStr = null;
 var offset = 0;
 var end = 0;
 if (cookie.length > 0) {
	offset = cookie.indexOf(search);
	if (offset != -1) {
	 offset += search.length;
	 end = cookie.indexOf(";", offset)
	 if (end == -1) {
		end = cookie.length;
	 }
	 setStr = unescape(cookie.substring(offset, end));
	}
 }
return(setStr);
}

//---- Format text, when user click "ok" in custom prompt box -----

var command = false;
var url = false;
var range = false;

function formatWithWaiting( command, url ){
    if(!url || (url == 'http://')){
	return false;
    }
    else{
	switch ( command ) {
	case 'img':
		if(url && (url != 'http://'))
			insert_html('<img border="0" src="'+url+'" />');
		break;
	case 'a':
		if(url && (url != 'http://')){
			var txt = get_selection();
			if ( txt != '' )
				insert_html('<a border="0" href="'+url+'">' + txt + '</a>');
			else
				insert_html('<a border="0" href="'+url+'">' + url + '</a>');
		}
		break;
	case 'cut':
	   if((window.navigator.appName == 'Opera') || (window.navigator.appName == 'Microsoft Internet Explorer')){
		if(doc.selection)
			var selection = doc.selection.createRange();
		else
			var selection = doc.createRange();

		var text = selection.htmlText;				
		if(!text || text == '')
			alert('Предварительно необходимо выделить текст, который Вы хотите спрятать под "кат"');
		else{
			text = '<a href="http://cut">' + (!url?'Читать':url) + '</a><hr/>' + text + '<hr/><br/>';
			insert_html( text );
		}
	   }
	   else{
		try{
			doc.execCommand( "formatBlock", false, 'fieldset');
		}
		catch(e){}	
		re = new RegExp('</fieldset><fieldset>', 'gi');
		text = doc.body.innerHTML.replace(re, '<br>');
		re = /<fieldset>/;
		text = text.replace(re, '<a href="http://cut">' + url + '</a><fieldset>');
		re = new RegExp('</fieldset>', 'gi');
		text = text.replace(re, '</fieldset><br>');
		doc.open();
		doc.write(text);		
		doc.close();
	   }
		break;
	 case 'video':
	   
	}
	return true;	
    }
}
        
//------- Format text, when user click button ----- 

function formatText( command, url )
{
	switch ( command ) {
	case 'b':
		doc.execCommand( "bold", false, null );
		break;
	case 'i':
		doc.execCommand( "italic", false, null );
		break;
	case 'u':
		doc.execCommand( "underline", false, null );
		break;
	case 'al':
	   if((window.navigator.appName == 'Opera') || (window.navigator.appName == 'Microsoft Internet Explorer')){
		var selection = doc.selection.createRange();
		var p = doc.createElement('p')
		p.style.textAlign = 'left';
		p.innerHTML = selection.htmlText;
		insert_html(p.outerHTML);
	   }else
		doc.execCommand( "justifyleft", false, null );
		break;
	case 'ar':
	   if((window.navigator.appName == 'Opera') || (window.navigator.appName == 'Microsoft Internet Explorer')){
		var selection = doc.selection.createRange();
		var p = doc.createElement('p')
		p.style.textAlign = 'right';
		p.innerHTML = selection.htmlText;
		insert_html(p.outerHTML);
	   }else
		doc.execCommand( "justifyright", false, null );
		break;
	case 'ac':
	   if((window.navigator.appName == 'Opera') || (window.navigator.appName == 'Microsoft Internet Explorer')){
		var selection = doc.selection.createRange();
		var p = doc.createElement('p')
		p.style.textAlign = 'center';
		p.innerHTML = selection.htmlText;
		insert_html(p.outerHTML);
	   }else
		doc.execCommand( "justifycenter", false, null );
		break;
	case 'aj':
	   if((window.navigator.appName == 'Opera') || (window.navigator.appName == 'Microsoft Internet Explorer')){
		var selection = doc.selection.createRange();
		var p = doc.createElement('p')
		p.style.textAlign = 'justify';
		p.innerHTML = selection.htmlText;
		insert_html(p.outerHTML);
	   }else
		doc.execCommand( "justifyfull", false, null );
		break;
	case 'tab':
		doc.execCommand( "indent", false, null );
		break;
	case 'detab':
		doc.execCommand( "outdent", false, null );
		break;
	case 'una':			
		doc.execCommand( "unlink", false, url );
		break;
	case 'sup':
		doc.execCommand( "superscript", false, null );
		break;
	case 'sub':
		doc.execCommand( "subscript", false, null );
		break;
	case 's':
		doc.execCommand( "strikethrough", false, null );
		break;
	case 'font-size':
		doc.execCommand( "fontsize", false, url );
		$('font-size').selectedIndex = 0;
		break;
	case 'font-family':
		doc.execCommand( "fontname", false, url );
		$('font-type').selectedIndex = 0;
		break;
	case 'font-color':
		doc.execCommand( "forecolor", false, url );
		$('color_select_div').style.display = 'none';
		break;
	case 'background-color':
		doc.execCommand( "backcolor", false, url );
		$('color_select_div').style.display = 'none';
		break;
	break;
	//---------------------------------------------
	case 'blockquote':
	   if((window.navigator.appName == 'Opera') || (window.navigator.appName == 'Microsoft Internet Explorer')){
		var selection = doc.selection.createRange();
		var text = selection.htmlText;
		var quote = doc.createElement('blockquote')

		quote.style.borderLeft = "5px solid #EFEBEE";
		quote.style.paddingLeft = "9px";
		quote.innerHTML = text;		

		insert_html(quote.outerHTML);
	   }
	   else{
		doc.execCommand( "FormatBlock", false, 'blockquote' );
		re = new RegExp('</blockquote>', 'gi');
		text = doc.body.innerHTML.replace(re, '</blockquote><br/>');
		re = new RegExp('<blockquote>', 'gi');
		text = doc.body.innerHTML.replace(re, '<blockquote style="border-left:5px solid #EFEBEE; padding-left:9px;">');
		doc.open();
		doc.write(text);		
		doc.close();
	   }
	   break;
	//---------------------------------------------
	case 'ul':
	   if((window.navigator.appName == 'Opera') || (window.navigator.appName == 'Microsoft Internet Explorer')){
		var selection = doc.selection.createRange();
		var text = selection.htmlText;
		re = new RegExp('<br>', 'gi');
		text = text.replace(re, '<li>');
		text = '<ul><li>' + text + '</ul><br>';
		insert_html(text);
	   }
	   else{
		doc.execCommand( "InsertUnorderedList", false, null );
	   }
	   break;
	//---------------------------------------------
	case 'nl':
	   if((window.navigator.appName == 'Opera') || (window.navigator.appName == 'Microsoft Internet Explorer')){
		var selection = doc.selection.createRange();
		var text = selection.htmlText;
		re = new RegExp('<br>', 'gi');
		text = text.replace(re, '</li><li>');
		text = '<ol><li>' + text + '</ol><br>';
		insert_html(text);
	   }
	   else{
		doc.execCommand( "InsertOrderedList", false, null );
	   }
	   break;
	}
	//---------------------------------------------
}

function insert_html( html ) {
	if (navigator.appName == "Microsoft Internet Explorer"){
	  var range = doc.selection.createRange();
	  try{doc.focus(); range.select();}catch(e){}
	  range.pasteHTML( html );		
	}
	else {
	  doc.execCommand('inserthtml', false, html);
	}	
}

function get_selection()
{
	var txt = '';
	var frame = frames['editorArea'];

	if (window.getSelection) {
		txt = frame.getSelection();
	}
	else if (document.getSelection) {
		txt = frame.document.getSelection();
	}
	else if (document.selection) {
		txt = frame.document.selection.createRange().text;
	}

	return txt;
}

function show_color_select( e, trg )
{
	targetE = trg;
	var div = document.getElementById( 'color_select_div' );
	if ( div.style.display == 'none' ) {
		div.style.display = 'block';
		if(trg == 'background'){
			div.style.left = '20px';
		}
		if ( !e )
			var e = window.event;
		e.cancelBubble = true;
		
	}
	else {
		div.style.display = 'none';
		try { window.event.cancelBubble = true; } catch( e ) {}
	}
}

function addInput(divId, newInputName)
{
	var newInput = document.createElement('input');
	newInput.setAttribute('type', 'text');
	newInput.setAttribute('name', newInputName);
	newInput.setAttribute('style', 'width:250px; margin:2px 0px');
	newInput.className = 'subject';
	theBr = document.createElement('br');
	var d1 = document.getElementById(divId);
	d1.appendChild(theBr);
	d1.appendChild(newInput);
}

function emoticon(text, editor) {
    if(editor == 'bb'){
	text = ' ' + text + ' ';
	var txtarea = document.getElementById('bb');
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
    }	
    else{
	switch ( text ) {
		case ':D': text = '<img src="http://static.meta.ua/wwg/icon_biggrin.gif">'; break;
		case ':-D': text = '<img src="http://static.meta.ua/wwg/icon_smile.gif">'; break;
		case ':smile:': text = '<img src="http://static.meta.ua/wwg/smile.gif">'; break;
		case ':(': text = '<img src="http://static.meta.ua/wwg/icon_sad.gif">'; break;
		case ':sad:': text = '<img src="http://static.meta.ua/wwg/sad.gif">'; break;
		case ':o': text = '<img src="http://static.meta.ua/wwg/icon_surprised.gif">'; break;
		case ':shock:': text = '<img src="http://static.meta.ua/wwg/158.gif">'; break;
		case ':?': text = '<img src="http://static.meta.ua/wwg/icon_confused.gif">'; break;
		case '8)': text = '<img src="http://static.meta.ua/wwg/icon_cool.gif">'; break;
		case ':lol:': text = '<img src="http://static.meta.ua/wwg/icon_lol.gif">'; break;
		case ':x': text = '<img src="http://static.meta.ua/wwg/icon_mad.gif">'; break;
		case ':mad:': text = '<img src="http://static.meta.ua/wwg/mad.gif">'; break;
		case ':P': text = '<img src="http://static.meta.ua/wwg/icon_razz.gif">'; break;
		case ':oops:': text = '<img src="http://static.meta.ua/wwg/icon_redface.gif">'; break;
		case ':cry:': text = '<img src="http://static.meta.ua/wwg/icon_cry.gif">'; break;
		case ':evil:': text = '<img src="http://static.meta.ua/wwg/evil.gif">'; break;
		case ':twisted:': text = '<img src="http://static.meta.ua/wwg/icon_twisted.gif">'; break;
		case ':roll:': text = '<img src="http://static.meta.ua/wwg/icon_rolleyes.gif">'; break;
		case ':wink:': text = '<img src="http://static.meta.ua/wwg/wink.gif">'; break;
		case ';)': text = '<img src="http://static.meta.ua/wwg/icon_wink.gif">'; break;
	}
	insert_html( text );

    }	
}                                    

var form = false;
function fillContent(variant){     
     try{
	var frame = frames['editorArea'];
	var newInput = document.createElement('input');
	newInput.setAttribute('type', 'hidden');
	newInput.setAttribute('name', 'wwg');
	newInput.setAttribute('value', 'true');
	var root = document.getElementById('forwwgInp');
	root.appendChild(newInput);
	frameC = frame.document.body.innerHTML;
	try{
		re = newRegExp('http://[^/]+/fnt/');
		frameC = frameC.replace(re, '/fnt/');
		re = newRegExp('&nbsp;');
		frameC = frameC.replace(re, ' ');
	}
	catch(e){}
	var content = document.getElementById('cTxtarea');
	content.value = frameC;
	if(!$('subject') && (content.value.length > 3000)){
		alert('Размер комментария превышает допустимый');
		return false;
	}
        if (content.value == '' || content.value == '<br>') {		
		alert(emptyContentAlert);
		frame.focus();
	return false;
        }
     }
     catch(e){
	txtarea = document.getElementById('bb');
	if(txtarea.value == '' || txtarea.value == '<br>'){
		alert(emptyContentAlert);
		txtarea.focus();
		return false;
	}
     }		
     if(variant){
	     form = document.getElementById('EditForm');
	     form.action = variant;
	     if(getCookie('sauth')){
		form.submit();
	     }
	     else{
		if(getCookie('scook')){
			$('service_iframe').src = "/ajax/login_restorer.php";
		}		
	     }
     }
}

var doc = null;

function loadText(){
	if($("editorArea"))
		doc = $("editorArea").contentWindow.document;
	if($('cTxtarea'))
		var cnt = $('cTxtarea').value;

	doc.open();
	doc.write(cnt);
	doc.close();
	try{
		doc.body.contentEditable = true;
		doc.designMode = "on";
		doc.onkeydown = cursorControl;
	}
	catch(e){}
}

function cursorControl(){
 evnt = window.frames['editorArea'].event;
 if(evnt.keyCode == '13'){
	range = doc.selection.createRange();
	insert_html('<br>');
	range.move('character');
	range.select();
	return false;
 }
}

var vOriented = false;
var actContainer = 0;
function typeVerticalText(){
   if(window.navigator.appName == 'Microsoft Internet Explorer'){
	if(vOriented){
		vOriented = false;
		$('font-type').style.display = 'inline';
		var oncAttr = doc.createAttribute('onchange');
		oncAttr.value = "formatText('font-size', this.value);";
		$('font-size').setAttributeNode(oncAttr);
		doc.onkeydown = null;
	}
	else{
		actContainer++;				
		vOriented = true;
		$('font-type').style.display = 'none';
		$('font-size').removeAttribute('onchange');
		doc.onkeydown = vSymbol;
		var tbl = '<table id="vText'+actContainer+'" border="0"><tr><td valign="bottom" align="right"></td></table>'

		insert_html(tbl);

		range = doc.selection.createRange();
		tbl = doc.getElementById('vText'+actContainer);
		td = tbl.getElementsByTagName('td').item(0);	
		range.moveToElementText(td);
		range.select();
	}
	return true;
   }
   else
   {
	alert('Эта функция доступна только в браузере InternetExplorer');
   }	
}


function vSymbol(){
 evnt = window.frames['editorArea'].event;
 fsize = $('font-size').value;
 fsize = parseInt(fsize);
 switch(fsize){
	case 1: fs='17'; break;
	case 3: fs='20'; break;
	case 6: fs='27'; break;
	case 8: fs=false; break;
	default: fs = '20'; 
 }
 size = fs?'width='+(evnt.shiftKey?(parseInt(fs)+5):fs):'';
 switch (evnt.keyCode){
	case 70: s='a'; break;
	case 188: s='b'; break;
	case 68: s='v'; break;
	case 85: s='g'; break;
	case 76: s='d'; break;
	case 84: s='e'; break;
	case 192: s='yo'; break; //ё
	case 186: s='j'; break;
	case 80: s='z'; break;
	case 66: s='i'; break;
	case 81: s='ii'; break;
	case 82: s='k'; break;
	case 75: s='l'; break;
	case 86: s='m'; break;
	case 89: s='n'; break;
	case 74: s='o'; break;
	case 71: s='p'; break;
	case 72: s='r'; break;
	case 67: s='s'; break;
	case 78: s='t'; break;
	case 69: s='u'; break;
	case 65: s='f'; break;
	case 219: s='h'; break;
	case 87: s='ts'; break;
	case 88: s='ch'; break;
	case 73: s='sh'; break;
	case 79: s='sh2'; break;
	case 77: s='mz'; break;
	case 221: s='tz'; break;
	case 83: s='iii'; break;
	case 222: s='ee'; break;
	case 190: s='iu'; break;
	case 90: s='ia'; break;
	case 32: s='space'; break;
	case 55: 
		if(evnt.shiftKey){
			s = 'q';
		}
		break;
	case 191:
		s='point';
		break;
	case 49:
		if(evnt.shiftKey){
			s = 'voskl';
		}
		break;
	case 46:
		s = false; 
		doc.execCommand( "delete", false, null );
		break;
	case 8: //backspace
		s = false;
		doc.execCommand( "delete", false, null );
		doc.execCommand( "delete", false, null );
		range = doc.selection.createRange();
		range.move('character', 1);
		range.select();
		break;
	case 39: //курсор вправо
		s = false;
		range = doc.selection.createRange();
		range.move('character', -2);
		range.select();
		break;
	case 37: //курсор влево
		s = false;
		range = doc.selection.createRange();
		range.move('character', 2);
		range.select();
		break;
	case 13: //Перевод строки
		s = false;
		var tbl = doc.getElementById('vText'+actContainer);
		var tds = tbl.getElementsByTagName('td');		
		actTd = tds.item(tds.length-1);
		var symbols = actTd.getElementsByTagName('img');
		var lastChar = symbols.item(symbols.length - 1);
		range = doc.selection.createRange();
		range.moveToElementText(lastChar);
		range.select();

		insert_html('~lt~/td~gt~~lt~td valign="bottom"~gt~');

		var re = new RegExp('~lt~', 'gi');
		text = doc.body.innerHTML.replace(re, '<');
		re = new RegExp('~gt~', 'gi');			
		doc.body.innerHTML = text.replace(re, '>');

		tbl = doc.getElementById('vText'+actContainer);			
		tds = tbl.getElementsByTagName('td');		
		lastTd = tds.item(tds.length-1);
		range.moveToElementText(lastTd);
		range.select();

		break;
 };
 if(s){		
	range = doc.selection.createRange();
	var symbol = '<img src=/fnt/'+s+'.gif ' + size + '><br>';
	var iCount = 0;

	insert_html(symbol);

	range.move('character', iCount);
	range.select();
 }
 s = false;

 return false;
}

function createTable(align){
	try{
		$('font-type').style.display = 'inline';		
		var oncAttr = doc.createAttribute('onchange');
		oncAttr.value = "formatText('font-size', this.value);";
		$('font-size').setAttributeNode(oncAttr);
		doc.onkeydown = null;
	}catch(e){}

	var width = $('width').value;
	var height = $('height').value;		
	var tableCode = '<table'+	
			(width!=''?' width="'+width+'"':'')+
			(height!=''?' height="'+height+'"':'')+
			(align!=''?' align="'+align+'"':'')+
			' border=1 ' + ($('showBorder').checked ? '' : 'delborder') + ' >';
	var cols = $('cols').value;
	var rows = $('rows').value;
	var tds = '<td>';
	for(i=1; i<cols; i++){
		tds = tds+'</td><td>';
	}
	tds = tds+'</td>';

	var trs = '<tr>'+tds;
	for(i=1; i<rows; i++){
		trs = trs+('</tr><tr>'+tds);
	}
	trs = trs+'</tr>';

	tableCode = tableCode + trs + '</table><br />';

	try{
	 range.select();
	 insert_html(tableCode);
	}catch(e){}	

	myclosePanel('cTblCnt');
	return true;
}
//--------------- Controls of My Custom Windows -------------------------

function show_tbl_painter(){
	if(window.navigator.appName == 'Microsoft Internet Explorer')
		range = doc.selection.createRange();
	$('cTblCnt').style.display = 'block';
	var cTblCnt = $('cTblCnt');
	$('cTblCnt').innerHTML = myPANEL('cTblCnt', cTblCnt.innerHTML,'Вставить таблицу', 250, true);
	Drag.init($("h_cTblCnt"), $("r_cTblCnt"));
}

function myPANEL(razdel,text,subj,width,my)
{
if (!width) width=200;
//text="";
str= "<div style='float:"+((razdel=='main'|| razdel=='myNews')?'left':'right')+";width:"+width+"px; line-height:13px;text-align:left;'>"+
"<div onmousedown='this.style.zIndex=maxZ++;' class=a style='z-index"+(maxZ++)+"' id='"+razdel+"_f'><div id=r_"+razdel+"  class='show_w' style='width:"+width+"px;margin-top:0px; '>"+
"<div id='"+razdel+"_wait' class='box_w'>"+
"<div id='h_"+razdel+"' class=b_h style='cursor:move;margin-top:0px; height:18px;line-height:14px'>"+
"<div class='c_button'><a href='javascript:return false;' onclick='"+(my?'my':'')+"closePanel(\""+razdel+"\");return false;'><img src='http://meta.ua/img/m/close.gif' style='width:14px; height:14px;' border=0 title='Close' alt='Close'></a></div>"+
"<span class='b_hc_w' style='float:left'>"+subj+"</span>"+
"</div>"+
"<div class='b_c' id='"+razdel+"W_cnt' style='padding-top:0px;width:100%; text-align:center; float:left'><br>"+
 text+"<br>"+
"</div></div></div></div></div>";
return str;
}

function myclosePanel(razdel){
	$(razdel).style.display = "none";
	$(razdel).innerHTML =  '<div id="' + razdel + '_b">' + $(razdel + '_b').innerHTML + '</div>';
	return true;
}

function myPrompt(cmd, text, defVal){
	if(window.navigator.appName == 'Microsoft Internet Explorer')
		range = doc.selection.createRange();
	command = cmd;
	var myPCnt = $('myPromptCnt');
	$('myprmptInp').value = defVal;
	myPCnt.style.display = 'block';
	try{
		$('myprmptInp').focus();
	}
	catch(e){
	}
	myPCnt.innerHTML = myPANEL('myPromptCnt', myPCnt.innerHTML, text, 250, true);
	Drag.init($("h_myPromptCnt"), $("r_myPromptCnt"));
}

function videoPrompt(cmd, text, defVal){
	if(window.navigator.appName == 'Microsoft Internet Explorer')
		range = doc.selection.createRange();
	command = cmd;
	var videoPCnt = $('videoPromptCnt');
	$('videoprmptInp').value = defVal;
	videoPCnt.style.display = 'block';
	try{
		$('myprmptInp').focus();
	}
	catch(e){}
	videoPCnt.innerHTML = myPANEL('videoPromptCnt', videoPCnt.innerHTML, text, 250, true);
	Drag.init($("h_videoPromptCnt"), $("r_videoPromptCnt"));
}

function codePrompt(cmd, text){
	if(window.navigator.appName == 'Microsoft Internet Explorer')
		range = doc.selection.createRange();
	command = cmd;
	var codePCnt = $('codePromptCnt');
	codePCnt.style.display = 'block';
	codePCnt.innerHTML = myPANEL('codePromptCnt', codePCnt.innerHTML, text, 250, true);
	Drag.init($("h_codePromptCnt"), $("r_codePromptCnt"));
}

function PromptOk(prefix, handler){
    if(handler){
	eval(handler);
    }else{
	try{
		range.select();
	}catch(e){}
	formatWithWaiting( command, $(prefix + 'prmptInp').value);
    }	
	myclosePanel(prefix + 'PromptCnt');
	return true;
}

function PromptCancel(prefix){
	myclosePanel(prefix + 'PromptCnt');
	return false;
}

function selVpr(){
	var inpts = $('siteSel').getElementsByTagName('input');
	i = 0;
	while(i < inpts.length){
		if(inpts.item(i).checked){
			if(inpts.item(i).value == 'yahoo'){
				$('codeSelH').style.display = 'none';
				$('codeSel').style.display = 'none';
				$('videoprmptInp').style.display = 'none';
				$('videoprmptTxt').style.display = 'block';
			}
			else{
				$('codeSelH').style.display = 'block';
				$('codeSel').style.display = 'block';
				$('codeSel').getElementsByTagName('input')[1].checked = true;
				$('videoprmptInp').style.display = 'block';
				$('videoprmptTxt').style.display = 'none';
			}
		}
		i++;
	}
	
}

function selVInput(){
	var inpts = $('codeSel').getElementsByTagName('input');
	i = 0;
	while(i < inpts.length){
		if(inpts.item(i).checked){
			if(inpts.item(i).value == 'link'){
				$('videoprmptInp').style.display = 'block';
				$('videoprmptTxt').style.display = 'none';
			}
			else{
				$('videoprmptInp').style.display = 'none';
				$('videoprmptTxt').style.display = 'block';
			}
		}
		i++;
	}
}

function insertVideo(){
	var prTypes = document.forms['editform'].prtype;
	i = 0;
	while(i < prTypes.length){
		if(prTypes.item(i).checked)
			var prType = prTypes.item(i).value;
		i++;
	}
	var codeTypes = document.forms['editform'].codetype;
	i = 0;
	while(i < codeTypes.length){
		if(codeTypes.item(i).checked)
			var codeType = codeTypes.item(i).value;
		i++;
	}
	var val = (codeType == 'html'?$('videoprmptTxt').value:$('videoprmptInp').value);
	try{
		range.select();
	}catch(e){}
	if(codeType == 'html'){
		insert_html(val.replace(/(\n|\r|\t)/, ''));
	}
	else{
	    switch(prType){
	      case 'google':
		var regexp = /docid=([-0-9]+)/ig;
		docIds = regexp.exec(val);
		var str = '<embed style="width:400px; height:326px;" id="VideoPlayback" type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docId=' + docIds[1] + '&hl=en" flashvars=""></embed>';
	        break;
	      case 'youtube':
		var regexp = /watch\?v=(\w+)/ig;
		docIds = regexp.exec(val);
		var str = '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/' + docIds[1] + '"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/' + docIds[1] + '" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>';
	        break;
	    }
	    insert_html(str);	      	
	}
}

function insertCode(){
	try{
		doc.focus();
	}
	catch(e){}	
	try{
		range.select();
	}catch(e){}
	var code = $('codeprmptTxt').value;
	insert_html(code);
}

//------------------- ------------------
var tutLoaded = 0;
function viewTutorial(){
	if(tutLoaded == 0){
		loadJS('/js/tutorial.js');
	}
	else{
		playAnimation();
		return;
	}
}

if (typeof(HTMLElement) != "undefined") {
    var _emptyTags = {
       "IMG": true,
       "BR": true,
       "INPUT": true,
       "META": true,
       "LINK": true,
       "PARAM": true,
       "HR": true
    };
    
    HTMLElement.prototype.__defineGetter__("outerHTML", function () {
       var attrs = this.attributes;
       var str = "<" + this.tagName;
       for (var i = 0; i < attrs.length; i++)
          str += " " + attrs[ i ].name + "=\"" + attrs[ i ].value + "\"";
    
       if (_emptyTags[this.tagName])
          return str + ">";
    
       return str + ">" + this.innerHTML + "</" + this.tagName + ">";
    });
    
    HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
       var r = this.ownerDocument.createRange();
       r.setStartBefore(this);
       var df = r.createContextualFragment(sHTML);
       this.parentNode.replaceChild(df, this);
    });
}

