function each(object, callback) {
  var name, i = 0, length = object.length;

  if(length === undefined){
    for(name in object)
      if(callback.call(object[name], name, object[name]) === false)
        break;
  }else{
    for(var value = object[0];
      i < length && callback.call(value, i, value) !== false;
			value = object[++i]) {}
  }
  return object;
}
Function.prototype.bind = function() {
  var func = this, args = Array.prototype.slice.call(arguments);
  var obj = args.shift();
  return function() {
    var curArgs = Array.prototype.slice.call(arguments);
    return func.apply(obj, args.concat(curArgs));
  }
}
Function.prototype.extBind = function() {
  var func = this, args = arguments;
  return function() {
    var argsArray = [];
    each(args, function(i, obj) { argsArray[i] = obj; });
    var obj = argsArray.shift(), currArgs = [];
    each(arguments, function(i, obj) { currArgs[i] = obj; });
    return func.apply(obj, currArgs.concat(argsArray));
  }
}

function editorChooseAlbum(id){
	var ajax = new Ajax();
	ajax.post({module:'wysiwyg', act:'getAlbumImages', id:id}, function(data){
		try{
			if(data.status == '1') document.getElementById('addImageItems').innerHTML = data.html;
		}catch(e){}
	});
}

function editorChoosePhoto(id, url) {
  var img = new Image();
  var photoObj = { photoID: id, photoURL: url };
  img.onload = function(){
		photoObj.width = img.width;
    photoObj.height = img.height;
		window[window.editorName].insertPhoto(photoObj);
	}
  img.src = url;
  return false;
}

function editorDeletePhoto(id, e){
	var ajax = new Ajax();
	ajax.post({module:'wysiwyg', act:'delImage', id:id}, function(data){
		try{ if(data.status == '1') jWps(e.parentNode).remove(); }catch(e){}
	});
}

function editorChooseVideo(id, videoHTML){
	if(id > 0){
		var ajax = new Ajax();
		ajax.post({module:'wysiwyg', act:'getVideo', id:id}, function(data){
			window[window.editorName].insertVideo(data.html);
		});
	}else{
		window[window.editorName].insertVideo(videoHTML);
	}
}

function editorChooseSmile(code, src){
	window[window.editorName].insertSmile(code, src);
}

function PopupBoxButton(title, type, func){
	this.button = document.createElement('a');
	this.button.href = 'javascript:;';
	this.button.className = (type == 'blue' ? 'button_blue' : 'button_gray');
	this.button.innerHTML = title;
	
	jWps.event.add(this.button, 'mouseup', func);
}

function PopupBox(caption, body, buttons, width){
	this.caption = (caption && caption != '') ? caption : uiLang.popup_box_loading;
	this.body = (body && body != '') ? body : '<div class="popup_box_loading"></div>';
	
	this.width = (width) ? width : 400;
	
	this.createBoxBack();
	this.createBox();
	this.addButtons(buttons);	
}
PopupBox.prototype = {
	createBoxBack: function(){
		this.box_back = document.createElement('DIV');
		this.box_back.className = 'popup_box_back';
		//this.box_back.style.width = jWps.documentWidth() + 'px';
		//this.box_back.style.height = jWps.documentHeight() + 'px';
	},
	createBox: function(){
		this.box = document.createElement('DIV');
		this.box.className = 'popup_box_container';
		this.box.style.width = this.width + 'px';
		this.box.innerHTML = '<div class="box_title_wrap"><div class="box_x_button"></div><div class="box_title"></div></div><div class="box_body_wrap"><div class="box_body"></div><div class="box_control_wrap"><div class="box_control"></div></div></div>';
		
		this.boxTitleWrap = this.box.firstChild;
		this.boxCloseButton = this.boxTitleWrap.firstChild;
		this.boxButtonX = this.boxTitleWrap.firstChild;
		this.boxCaption = this.boxTitleWrap.lastChild;
		this.boxBodyWrap = this.boxTitleWrap.nextSibling;
		this.boxBody = this.boxBodyWrap.firstChild;
		this.boxControlWrap = this.boxBody.nextSibling;
		this.boxControl = this.boxControlWrap.firstChild;
		
		this.boxButtonX.onmouseup = function(){ this.hide(); }.bind(this);
		this.boxCaption.innerHTML = this.caption;
		if(this.body != '') this.boxBody.innerHTML = this.body;
	},
	addButtons: function(buttons){
		this.buttons = new Object();
		for(var key in buttons){
			this.buttons[key] = new PopupBoxButton(buttons[key].title, buttons[key].type, (typeof buttons[key].func == 'function') ? buttons[key].func : function(){ this.hide(); }.bind(this) );
			this.boxControl.appendChild(this.buttons[key].button);
		}
	},
	delButton: function(name){
		for(var key in this.buttons){
			if(key == name){
				this.buttons[key].button.parentNode.removeChild(this.buttons[key].button);
			}
		}
	},
	setWidth: function(width){
		if(parseInt(width) > 0){
			this.width = width;
			this.box.style.width = width + 'px';
			this.fix();
		}
	},
	setData: function(caption, body){
		if(caption && caption != '') this.boxCaption.innerHTML = caption;
		if(body && body != '') this.boxBody.innerHTML = body;
		this.fix();
	},
	fix: function(){
		this.box_back.style.width = jWps.documentWidth() + 'px';
		this.box_back.style.height = jWps.documentHeight() + 'px';
		
		var clientWidth = jWps.clientWidth();
		var clientHeight = jWps.clientHeight();
		var boxWidth = this.width;
		var boxHeight = this.box.offsetHeight;
		this.left = (clientWidth - boxWidth) / 2;
		this.top = ((clientHeight - boxHeight) / 2) + (document.body.scrollTop || document.documentElement.scrollTop);
		//if(this.top > boxHeight) this.top = this.top - (boxHeight / 2);
		this.box.style.left = this.left + 'px';
		this.box.style.top = this.top + 'px';
	},
	show: function(){
		document.body.appendChild(this.box_back);
		document.body.appendChild(this.box);
		this.fix();
		
		window.onresize = function(){
			this.fix();
		}.bind(this);
	},
	hide: function(){
		document.body.removeChild(this.box_back);
		document.body.removeChild(this.box);
	}
}

function ToolBarButton(editor, buttonObj){
	this.down = false;
	this.disabled = false;
	this.canSelect = true;
	this.mouseup = null;
	
  this.obj = document.createElement('A');
  this.obj.className = 'wysiwyg_button';
  this.obj.setAttribute('href', 'javascript:;');
  this.obj.style.backgroundPosition = buttonObj.x + 'px ' + buttonObj.y + 'px';
	this.obj.title = buttonObj.tooltip;
	
	if(buttonObj.disabled){
		this.disabled = true;
		this.obj.className = 'wysiwyg_button disabled';
	}
	
	jWps.event.add(this.obj, 'mouseup', this.mouseUpEvent.extBind(this));
	jWps.event.add(this.obj, 'mouseover', this.mouseover.extBind(this));
	jWps.event.add(this.obj, 'mouseout', this.mouseout.extBind(this));
}
ToolBarButton.prototype = {
	mouseUpEvent: function(e){ if(this.mouseup && !this.disabled) this.mouseup(); },
	mouseover: function() { if(!this.disabled) this.obj.className = 'wysiwyg_button_over' },
  mouseout: function() { if(!this.disabled && !this.down) this.obj.className = 'wysiwyg_button' },
	select: function(){ if(!this.disabled && this.canSelect){ this.down = true; this.obj.className = 'wysiwyg_button_over' }; },
  unselect: function(){ if(!this.disabled) { this.down = false; this.obj.className = 'wysiwyg_button' }; },
  enable: function(){ this.disabled = false; this.obj.className = 'wysiwyg_button' },
  disable: function(){ this.disabled = true; this.obj.className = 'wysiwyg_button disabled' }
}

function ToolBar(editor, mode, params){
	this.editor = editor;
	
	this.obj = document.createElement('DIV');
	this.obj.className = 'wysiwyg_toolbar';
	
	// Beta version
	this.obj_beta = document.createElement('DIV');
	this.obj_beta.className = 'beta';
	this.obj_beta.title = uiLang.wysiwyg_beta;
	this.obj_beta.onclick = function(){
		this.popupBox = new PopupBox(uiLang.wysiwyg_beta, '<table class="table-info wysiwyg_beta"><tr><td class="l">'+uiLang.wysiwyg_beta_support+'</td><td></i><i class="safari" title="Apple Safari"></i><i class="chrome" title="Google Chrome"></i><i class="ie" title="Internet Explorer"></td></tr><tr><td class="l">'+uiLang.wysiwyg_beta_unsupport+'</td><td><i class="ipad" title="iPad/iPhone"></i><i class="opera" title="Opera"></i><i class="firefox" title="FireFox"></i></td></tr></table><br />'+uiLang.wysiwyg_beta_more, {Close: {title:uiLang.close}});
		this.popupBox.show();
	}.bind(this);
	this.obj.appendChild(this.obj_beta);
	
	
	if(mode == 'simple'){
    if(params && params.simpleToolBar) {
      this.toolbarButtons = params.simpleToolBar;
    }else{
      this.toolbarButtons = 'bold,italic,underline,strike,sub,sup,left,center,right,marker_list,numeric_list,h1,h2,h3,link,unlink';
    }
  }else{
    if(params && params.extendedToolBar){
      this.toolbarButtons = params.extendedToolBar;
    }else{
      this.toolbarButtons = 'bold,italic,gray,underline,strike,sub,sup,left,center,right,marker_list,numeric_list,outdent,indent,h1,h2,h3,image,link,unlink,break,';
      this.toolbarButtons += 'table,table_delete,insert_row_before,insert_row_after,insert_col_before,insert_col_after,delete_row,delete_col,col_width,citate,character,video,audio';
      this.toolbarButtons += ',time,signature,category,hider,wiki';
    }
  }
	var toolbarButtonsArray = this.toolbarButtons.split(',');
	this.buttons = {
		bold: { x: 0, y: 0, tooltip: uiLang.wysiwyg_tooltip_bold },
		italic: { x: -20, y: 0, tooltip: uiLang.wysiwyg_tooltip_italic },
		underline: { x: -40, y: 0, tooltip: uiLang.wysiwyg_tooltip_underline },
		strike: { x: -60, y: 0, tooltip: uiLang.wysiwyg_tooltip_strike },
		sub: { x: -80, y: 0, tooltip: uiLang.wysiwyg_tooltip_sub },
		sup: { x: -100, y: 0, tooltip: uiLang.wysiwyg_tooltip_sup },
		left: { x: -120, y: 0, tooltip: uiLang.wysiwyg_tooltip_left },
		center: { x: -140, y: 0, tooltip: uiLang.wysiwyg_tooltip_center },
		right: { x: -40, y: -40, tooltip: uiLang.wysiwyg_tooltip_right },
		justify: { x: -240, y: -40, tooltip: uiLang.wysiwyg_tooltip_justify },
		marker_list: { x: -160, y: 0, tooltip: uiLang.wysiwyg_tooltip_marker_list },
		numeric_list: { x: -180, y: 0, tooltip: uiLang.wysiwyg_tooltip_numeric_list },
		h1: { x: -240, y: 0, tooltip: uiLang.wysiwyg_tooltip_h1 }, 
		h2: { x: -260, y: 0, tooltip: uiLang.wysiwyg_tooltip_h2 },
		h3: { x: -280, y: 0, tooltip: uiLang.wysiwyg_tooltip_h3 },
		wiki: { x: -140, y: -40, tooltip: uiLang.wysiwyg_tooltip_wiki },
		link: { x: -160, y: -20, tooltip: uiLang.wysiwyg_tooltip_link },
    unlink: { x: -180, y: -20, tooltip: uiLang.wysiwyg_tooltip_unlink, canSelect: false, disabled: false },
		image: { x: -240, y: -20, tooltip: uiLang.wysiwyg_tooltip_image },
    video: { x: -260, y: -20, tooltip: uiLang.wysiwyg_tooltip_video },
		color1: { x: -180, y: -40, tooltip: uiLang.wysiwyg_tooltip_color1 },
		color2: { x: -200, y: -40, tooltip: uiLang.wysiwyg_tooltip_color2 },
		color3: { x: -220, y: -40, tooltip: uiLang.wysiwyg_tooltip_color3 },
		block1: { x: -240, y: -40, tooltip: uiLang.wysiwyg_tooltip_block1 },
		block2: { x: -260, y: -40, tooltip: uiLang.wysiwyg_tooltip_block2 },
		smile: { x: -280, y: -40, tooltip: uiLang.wysiwyg_tooltip_smile }
	};
	
	var buttonName = null;
  for(var i=0; i<toolbarButtonsArray.length; i++){
    buttonName = toolbarButtonsArray[i];
    this.addButton(buttonName);
  }
}
ToolBar.prototype = {
	addButton: function(buttonName){
		this[buttonName] = new ToolBarButton(this.editor, this.buttons[buttonName]);
    this.obj.appendChild(this[buttonName].obj);
	},
	addAction: function(buttonName, func){
		if(this[buttonName] != undefined) this[buttonName].mouseup = func;
	}
}

function Wysiwyg(params){
	this.debug = false;
	
	if(jWps.iphone || jWps.ipad || jWps.ipod || jWps.browser.mozilla || jWps.browser.opera){
		return;
	}
	
	this.trim = jWps.trim;
	this.event = jWps.event;
	this.browser = jWps.browser;
	this.ajax = new Ajax();
	
	this.params = params;
	if(!params.replaceElem) return;
	
	this.window = window;
	this.document = document;
	this.editor = null; // Ссылка на редактор
	this.width  = params.width; // Ширина редактора
	this.height = params.height; // Высота редактора
	this.prefix = Math.round(Math.random() * 100); // Уникальный префикс редактора
	
	this.wikiMode = false;
	this.wikiText = '';
	this.saveHTML = '';
	
	this.createContainer();
  this.createToolbar(params);
  this.createContentEditable();
	this.createContentEditableWiki();
	
	this.ajax.post({'module':'wysiwyg', 'act':'parseWiki', 'editor':params.editorName, 'wikiText':this.replaceElem.value}, function(data){
		window[data.editor].editor.innerHTML = (data.html) ? this.fixQuot(data.html) : '<p>\uFEFF</p>';
		this.initSetupPhoto();
	}.bind(this));
}
Wysiwyg.prototype = {
	createContainer: function(){
		this.replaceElem = this.params.replaceElem;
    //this.contentHTML = this.params.html;
    this.width = this.replaceElem.offsetWidth - 2;
    this.height = this.params.height;
    this.cont = document.createElement('DIV');
    this.cont.className = 'wysiwyg_cont';
    this.cont.style.width = this.width + 'px';
    this.replaceElem.parentNode.insertBefore(this.cont, this.replaceElem);
		if(!this.debug) this.replaceElem.style.display = 'none';
	},
	createToolbar: function(params){
		this.toolbar = new ToolBar(this, 'simple', params);
		this.addButtonsActions();
		this.cont.appendChild(this.toolbar.obj);
	},
	createContentEditable: function(){
		this.editor = document.createElement('DIV');
		this.editor.setAttribute('contentEditable', 'true');
		this.editor.className = 'wysiwyg';
		this.editor.style.width = this.width - 10 + 'px';
    this.editor.style.height = this.height - this.toolbar.obj.offsetHeight - 10 + 'px';
    //this.editor.innerHTML = (this.replaceElem.value != '') ? this.replaceElem.value : '<p>\uFEFF</p>';
		this.cont.appendChild(this.editor);		
		
		this.event.add(this.editor, 'mouseup', function(){
			if(this.browser.msie){
				this.currRangeElem = this.getRangeElem();
				if(this.currRangeElem){
					if(this.currRangeElem.nodeName == 'IMG'){
						this.setupPhoto(this.currRangeElem.id);
					}
				}
			}
			this.getFormat();
		}.bind(this));
		
		this.event.add(this.editor, 'keydown', function(e){
			if(e.keyCode == 13){ // Fix New Line For Video Object
				var cont = this.currRangeElem;
				if(!cont) cont = this.getRangeContainer();
				if(cont){
					if(cont.nodeName != 'P'){
						while(cont.nodeName != 'P' && cont != this.editor){
							cont = cont.parentNode;
						}
					}
					if(cont.nodeName == 'P'){
						var searchObject = false;
						var childs = cont.childNodes;
						for(var i=0; i<childs.length; i++){
							if(childs[i].nodeName == 'OBJECT'){
								searchObject = true;
								break;
							}
						}
						if(searchObject){
							var pNew = this.document.createElement('P');
							pNew.innerHTML = '\uFEFF';
							//if(!this.getRangeOffset(cont).startOffset){
								this.editor.insertBefore(pNew, cont.nextSibling);
							/* }else{
								this.editor.insertBefore(pNew, cont);
							} */
							this.setElemFocus(pNew);
							this.event.cancel(e);
						}
					}
				}
			}
		}.bind(this));
		
		this.event.add(this.editor, 'keyup', function(e){
			if(e.keyCode > 36 && e.keyCode < 41){
				this.getFormat();
			}
			if(e.keyCode == 46){ // Fix: Delete all text
				var html = this.editor.innerHTML;
				if(html == '') this.editor.innerHTML = '<p>\uFEFF</p>';
			}
			
			/* if(e.keyCode == 8 || e.keyCode == 46){ // Fix: Correct  deleting video
				var cont = this.getRangeContainer();
				while(cont.className != 'wikiVideo'){
					cont = cont.parentNode;
					if(cont == this.editor) break;
				}
				if(cont.nodeName == 'DIV' && cont.className == 'wikiVideo'){
					cont.parentNode.removeChild(cont);
					this.event.cancel(e);
				}
			} */
			
			try{
				var fonts = this.editor.getElementsByTagName('FONT');
				for(var i=0; i<fonts.length; i++){
					if(fonts[i].getAttribute('color') == '#ffffff' && fonts[i].firstChild.nodeName != 'SPAN'){
						var span = this.document.createElement('SPAN');
						span.style.backgroundColor = '#379cea';
						span.innerHTML = fonts[i].innerHTML;
						fonts[i].innerHTML = '';
						fonts[i].appendChild(span);
						this.setElemFocus(span);
					}
				}
			}catch(e){}
		}.bind(this));
		
		this.event.add(this.editor, 'paste', function(e){ this.clearPasteText(e); }.bind(this));
	},
	createContentEditableWiki: function(){
		this.wikiEditor = document.createElement('textarea');
		this.wikiEditor.style.width = this.editor.offsetWidth + 'px';
		this.wikiEditor.style.height = this.editor.offsetHeight + 'px';
		this.wikiEditor.style.display = 'none';
		this.cont.appendChild(this.wikiEditor);
	},
	clearPasteText: function(e){
		var saveHtml = this.editor.innerHTML;
		var pasteText = '';
		
		var clipboardData = (e.clipboardData) ? e.clipboardData : window.clipboardData;
		if(clipboardData && clipboardData.getData){			
			if(clipboardData.types){
				pasteText = clipboardData.getData('text/plain');
			}else{
				pasteText = clipboardData.getData('text');
			}
			var pasteTextArr = pasteText.split(/(\r\n|\r|\n)/);
			if(pasteTextArr.length > 1){
				pasteText = '';
				for(var i=0; i<pasteTextArr.length; i++){
					if(pasteTextArr[i] != ''){
						if(i == 0){
							pasteText += pasteTextArr[i]; 
						}else{
							pasteText += '<p>' + pasteTextArr[i] + '</p>';
						}
					}
				}
			}
			this.setRangeText(pasteText, this.getRange());
    }
		this.event.cancel(e);
	},
	addButtonsActions: function(){
		this.toolbar.addAction('bold', this.actDefault.extBind(this, 'bold', 'Bold', false));
		this.toolbar.addAction('italic', this.actDefault.extBind(this, 'italic', 'Italic', false));
		this.toolbar.addAction('underline', this.actDefault.extBind(this, 'underline', 'Underline', false));
		this.toolbar.addAction('strike', this.actDefault.extBind(this, 'strike', 'StrikeThrough', false));
		this.toolbar.addAction('sup', this.actDefault.extBind(this, 'sup', 'Superscript', false));
		this.toolbar.addAction('sub', this.actDefault.extBind(this, 'sub', 'Subscript', false));
		this.toolbar.addAction('marker_list', this.actDefault.extBind(this, 'marker_list', 'InsertUnorderedList', true));
		this.toolbar.addAction('numeric_list', this.actDefault.extBind(this, 'numeric_list', 'InsertOrderedList', true));
		this.toolbar.addAction('left', this.actAlign.bind(this, 'left'));
		this.toolbar.addAction('center', this.actAlign.bind(this, 'center'));
		this.toolbar.addAction('right', this.actAlign.bind(this, 'right'));
		this.toolbar.addAction('justify', this.actAlign.bind(this, 'justify'));
		this.toolbar.addAction('h1', this.actHeader.bind(this, 'h1'));
		this.toolbar.addAction('h2', this.actHeader.bind(this, 'h2'));
		this.toolbar.addAction('h3', this.actHeader.bind(this, 'h3'));
		this.toolbar.addAction('wiki', this.actWiki.bind(this));
		this.toolbar.addAction('link', this.actLink.bind(this, 'link'));
		this.toolbar.addAction('unlink', this.actLink.bind(this, 'unlink'));
		this.toolbar.addAction('image', this.actImage.bind(this, 'unlink'));
		this.toolbar.addAction('video', this.actVideo.bind(this, 'unlink'));
		this.toolbar.addAction('color1', this.actColor.bind(this, 'color1', 'wikiColor1'));
		this.toolbar.addAction('color2', this.actColor.bind(this, 'color2', 'wikiColor2'));
		this.toolbar.addAction('color3', this.actColor.bind(this, 'color3', 'wikiColor3'));
		this.toolbar.addAction('block1', this.actBlock.bind(this, 'wikiBlock1'));
		this.toolbar.addAction('block2', this.actBlock.bind(this, 'wikiBlock1'));
		this.toolbar.addAction('smile', this.actSmile.bind(this));
	},
	actDefault: function(elemName, actName, getFormat){
		if (this.toolbar[elemName].down) this.toolbar[elemName].unselect();
		else this.toolbar[elemName].select();
    this.editor.focus();
    this.document.execCommand(actName, false, true);
		this.editor.focus();
		if(getFormat) this.getFormat();
	},
	actAlign: function(align){
		this.editor.focus();
		var cont = null;
		if(this.browser.msie && this.currRangeElem){ // Fix Align Video
			if(this.currRangeElem.nodeName == 'EMBED'){
				cont = this.currRangeElem.parentNode;
			}else{
				cont = this.currRangeElem;
			}
			if(cont.nodeName == 'OBJECT'){
				cont.parentNode.style.textAlign = align;
				this.getFormat();
				return false;
			}
		}else{
			var node = this.getParent('P');
			if(node){
				if( ((this.testAlign(node, 'center') || this.testAlign(node, 'right')) && align == 'left') ||
				((this.testAlign(node, 'left') || this.testAlign(node, 'right')) && align == 'center') ||
				((this.testAlign(node, 'left') || this.testAlign(node, 'center')) && align == 'right') ){
					if(/^(center|right|left)$/.test(node.align)){
						node.align = align;
						node.style.textAlign = '';
					}else if(/^(center|right|left)$/.test(node.style.textAlign)){
						node.style.textAlign = align;
						node.align = '';
					}
				}
			}
		}
		try{
			var command = {'left':'JustifyLeft', 'center':'JustifyCenter', 'right':'JustifyRight'};
			this.document.execCommand(command[align], false, true);
		}catch(e){}

		
		this.getFormat();
	},
	testAlign: function(node, align){
		if((node.getAttribute('align') == align) || (node.style.textAlign == align)) return true;
		return false;
	},
	actHeader: function(tag){
		this.editor.focus();
		var parent = this.getParent(tag);
		var elem = null;
		if(parent){
			var p = document.createElement('P');
      p.innerHTML = this.getInnerText(parent);
      parent.parentNode.replaceChild(p, parent);
      elem = p;
		}else{
			this.document.execCommand('FormatBlock', false, '<' + tag + '>');
			var parent = this.getParent(tag);
			if(parent){
				var text = this.getInnerText(parent);
				parent.innerHTML = (this.trim(text) != '') ? text : '\uFEFF';
			}
			elem = parent;
		}
		this.setElemFocus(elem);
		this.getFormat();
	},
	actWiki: function(){
		if(!this.toolbar.wiki.down){
			this.disableAll();
			this.toolbar.wiki.enable();
			this.toolbar.wiki.select();
			this.wikiEditor.value = this.htmlToWiki();
			this.editor.style.display = 'none';
			this.wikiEditor.style.display = 'block';
			this.wikiMode = true;
		}else{
			this.resetAll();
			this.wikiMode = false;
			this.wikiText = this.wikiEditor.value;
			this.wikiEditor.style.display = 'none';
			this.editor.style.display = 'block';
			
			this.ajax.post({'module':'wysiwyg', 'act':'parseWiki', 'wikiText':this.wikiText}, function(data){
				try{
					this.editor.innerHTML = this.fixQuot(data.html);
					this.initSetupPhoto();
				}catch(e){}
			}.bind(this));
		}
	},
	actLink: function(mode){
		if(mode == 'unlink'){
			this.editor.focus();
			var linkElem = this.getParent('A');
			this.unLink = function(){
				var linkText = this.document.createTextNode(this.getInnerText(linkElem));
				linkElem.parentNode.replaceChild(linkText, linkElem);
				this.editor.focus();
				this.getFormat();
			}
			if(linkElem != null){
				this.alertBox = new PopupBox(uiLang.warning, '<div class="wysiwyg_link_box_del">' + uiLang.wysiwyg_link_delete + '</div>', {
					Yes: {title:uiLang.yes,type:'blue',func:function(){ this.alertBox.hide(); this.unLink(); }.bind(this)},
					Cancel: {title:uiLang.cancel,type:'grey'}
				}, 350);
				this.alertBox.show();
			}
		}else{
			this.insertLink = function(curLinkElem){
				var elemFocus = null;
				var text = document.getElementById('wysiwyg_link_text').value;
				var href = document.getElementById('wysiwyg_link_href').value;
				
				var protocol = /^(https|http|ftp)/.exec(href);
				if(protocol){
					protocol = protocol[0];
					var reg = new RegExp(protocol + ":\/\/", "g");
					href = href.replace(reg, '');
					href = protocol + '://' + href;
				}
				if(text == '') text = href;
				
				if(href == '' || href == 'http://'){
					var link_box_warning = this.document.getElementById('link_box_warning');
					link_box_warning.innerHTML = uiLang.wysiwyg_link_warning_href;
					link_box_warning.style.display = 'block';
					return;
				}
				if(curLinkElem){
					this.setInnerText(curLinkElem, text);
					curLinkElem.href = href;
					elemFocus = curLinkElem;
				}else{
					var link = this.document.createElement('A');
					this.setInnerText(link, text);
					link.href = href;
					this.rangeDeleteContents(this.currRange);
					this.rangeInsertNode(link, this.currRange);
					elemFocus = link;
				}
				this.alertBox.hide();
				this.setElemFocus(elemFocus);
			}
			
			this.editor.focus();
			var linkText = '';
			var linkHref = '';
			var curLinkElem = this.getParent('A');
			if(curLinkElem){
				linkText = this.getInnerText(curLinkElem);
				linkHref = curLinkElem.href;
			}else{
				this.currRange = this.getRange();
				linkText = this.getRangeText(this.currRange);
			}
			if(linkHref == '') linkHref = 'http://';
			
			var body = '<div class="wysiwyg_link_box"><table><tr><td align="right">'+uiLang.wysiwyg_link_href+':</td><td><input type="text" id="wysiwyg_link_href" value="'+linkHref+'" /></td></tr><tr><td align="right">'+uiLang.wysiwyg_link_text+':</td><td><input type="text" id="wysiwyg_link_text" value="'+linkText+'" /></td></tr></table><div id="link_box_warning"></div></div>';
			this.alertBox = new PopupBox(uiLang.wysiwyg_link_add, body, {
				Add: {title:uiLang.add,type:'blue',func:function(){ this.insertLink(curLinkElem); }.bind(this) },
				Cancel: {title:uiLang.cancel,type:'grey'}
			});
			this.alertBox.show();
			document.getElementById('wysiwyg_link_href').focus();
		}
	},
	actImage: function(){
		this.window.editorName = this.params.editorName;
		this.editor.focus();
    this.currRange = this.getRange();
		
		this.popupBox = new PopupBox(uiLang.wysiwyg_add_image, '<div class="popup_box_loading"></div>', {Close:{title:uiLang.close}}, 578);
		this.popupBox.show();
		
		this.ajax.post({module:'wysiwyg', act:'getImagesForm'}, function(data){
			try{
				this.popupBox.boxBody.innerHTML = data.form;
				this.popupBox.setWidth(data.width);
				this.popupBox.fix();
			}catch(e){}
		}.bind(this));
	},
	insertPhoto: function(photoObj){
		this.popupBox.hide();
		
		if(this.imageID > 0){
			this.imageID++;
		}else{
			this.imageID = 1;
		}
		var imageID = this.imageID;
		
		var img = this.document.createElement('IMG');
		img.src = photoObj.photoURL;
		img.id = 'image' + imageID;
		if(photoObj.width > 300){
			img.width = 300;
			img.height = 300 / (photoObj.width / photoObj.height);
			img.className = 'wiki window';
		}else{
			img.className = 'wiki';
		}
		if(photoObj.photoID > 0){
			img.setAttribute('photosrc', 'photo' + photoObj.photoID);
		}else{
			img.setAttribute('photosrc', photoObj.photoURL);
		}
		
		var cont = this.getRangeContainer(this.currRange);
		if(cont == this.editor){
			var new_p = document.createElement('P');
			new_p.appendChild(img);
			this.editor.insertBefore(new_p, this.editor.lastChild);
		}else{
			while(cont.parentNode != this.editor){ cont = cont.parentNode; }
			if(cont.nodeName == 'P' && (cont.innerHTML == '<br>' || cont.innerHTML == '\uFEFF')){
				cont.innerHTML = '';
				cont.appendChild(img);
			}else if(cont.nodeName == 'P' && cont.getElementsByTagName('IMG').length > 0){
				this.rangeInsertNode(img, this.currRange);
			}else{
				var new_p = document.createElement('P');
				new_p.appendChild(img);
				this.editor.insertBefore(new_p, cont.nextSibling);
			}
		}
		this.event.add(img, 'click', function(e){ if(e.which != 1) return; this.setupPhoto('image' + imageID); }.bind(this));
		
		
		/* if(this.imageID > 0){
			this.imageID++;
		}else{
			this.imageID = 1;
		}
		var imageID = this.imageID;
		
		var img = this.document.createElement('IMG');
		img.src = photoObj.photoURL;
		if(photoObj.width > 300){
			img.width = 300;
			img.height = 300 / (photoObj.width / photoObj.height);
			img.className = 'wiki window';
		}else{
			img.className = 'wiki';
		}
		img.id = 'image' + imageID;
		this.rangeInsertNode(img, this.currRange);
		this.event.add(img, 'click', function(e){ if(e.which != 1) return; this.setupPhoto('image' + imageID); }.bind(this)); */
	},
	setupPhoto: function(imageID, imageElem){
		if(imageElem){
			var url  = this.document.getElementById('wysiwyg_photo_setup_url').value;
			var text = this.document.getElementById('wysiwyg_photo_setup_text').value;
			var link = this.document.getElementById('wysiwyg_photo_setup_link').value;
			var sixeX = this.document.getElementById('wysiwyg_photo_setup_sixeX').value;
			var sixeY = this.document.getElementById('wysiwyg_photo_setup_sixeY').value;
			var border  = this.document.getElementById('wysiwyg_photo_setup_border').checked;
			var addlink = this.document.getElementById('wysiwyg_photo_setup_addlink').checked;
			var f_left = this.document.getElementById('wysiwyg_photo_setup_left').checked;
			var f_right = this.document.getElementById('wysiwyg_photo_setup_right').checked;
			var window = this.document.getElementById('wysiwyg_photo_setup_window').checked;
			
			if(this.trim(url) == '') return;
			
			if(link == ''){
				imageElem.alt = text;
				imageElem.title = text;
				
				var perent = imageElem.parentElement;
				if(perent.tagName == 'A'){
					perent.parentNode.insertBefore(imageElem, perent);
					perent.parentNode.removeChild(perent);
				}
				imageElem.className = (border) ? 'wiki' : 'wiki noborder';
				if(window || addlink) imageElem.className += ' window';
				if(f_left) imageElem.className += ' left';
				if(f_right) imageElem.className += ' right';
			}else{
				var perent = imageElem.parentElement;
				if(perent.tagName != 'A'){
					var linkElem = this.document.createElement('A');
					linkElem.href = (link != '') ? link : url;
					linkElem.alt = (text != '') ? text : '';
					linkElem.title = (text != '') ? text : '';
					imageElem.parentNode.insertBefore(linkElem, imageElem);
					linkElem.appendChild(imageElem);
					if(f_left) linkElem.className = 'left';
					if(f_right) linkElem.className = 'right';
				}else{
					perent.href = (link != '') ? link : url;
					perent.alt = (text != '') ? text : '';
					perent.title = (text != '') ? text : '';
					if(f_left) perent.className = 'left';
					if(f_right) perent.className = 'right';
				}
				imageElem.className = (border) ? 'wiki' : 'wiki noborder';
				
			}
			
			
			if(sixeX > 0 && sixeY > 0){
				imageElem.src = url;
				imageElem.width = sixeX;
				imageElem.height = sixeY;
			}
			
			this.popupBox.hide();
		}else{
			this.photoElem = this.document.getElementById(imageID);
			if(!this.photoElem) return;
			
			var photoURL = this.photoElem.src.replace(/_t/g,'');
			var text = this.photoElem.title;
			var noborder = '';
			if(this.photoElem.className.indexOf('noborder') == -1){
				noborder = 'checked';
			}
			var f_left = '', f_right = '', window = '';
			if(this.photoElem.className.indexOf('left') != -1){
				f_left = 'checked'
			}
			if(this.photoElem.className.indexOf('right') != -1){
				f_right = 'checked'
			}
			if(this.photoElem.className.indexOf('window') != -1){
				window = 'checked';
			}
			
			var nolink = '', link = '';
			var parent = this.photoElem.parentElement;
			if(parent.tagName == 'A'){
				nolink = 'checked';
				text = parent.title;
				link = parent.href
				
				if(parent.className.indexOf('left') != -1){
					f_left = 'checked'
				}
				if(parent.className.indexOf('right') != -1){
					f_right = 'checked'
				}
			}
			
			var width = 0, height = 0;
			if(this.photoElem.width > 0) width = this.photoElem.width;
			if(this.photoElem.height > 0) height = this.photoElem.height;
			
			var bodyPopupBox = '<div class="wysiwyg_photo_setup"><table><tr><td>';
			bodyPopupBox+= '<div class="wysiwyg_photo_setup_left"><table><tr><td valign="top"></td><td><h3>' + uiLang.wysiwyg_settings + '</h3></td></tr>';
			bodyPopupBox+= '<tr><td class="label">' + uiLang.wysiwyg_url + ':</td><td><input type="text" id="wysiwyg_photo_setup_url" value="'+photoURL+'" /></td></tr>';
			bodyPopupBox+= '<tr><td class="label">' + uiLang.wysiwyg_text + ':</td><td><input type="text" id="wysiwyg_photo_setup_text" value="'+text+'" /></td></tr>';
			bodyPopupBox+= '<tr><td class="label">' + uiLang.wysiwyg_link + ':</td><td><input type="text" id="wysiwyg_photo_setup_link" value="'+link+'" /></td></tr>';
			bodyPopupBox+= '<tr><td class="label">' + uiLang.wysiwyg_size + ':</td><td><input type="text" id="wysiwyg_photo_setup_sixeX" value="'+width+'" maxlength="3" /> - <input type="text" id="wysiwyg_photo_setup_sixeY" value="'+height+'" maxlength="3" /> px</td></tr>';
			bodyPopupBox+= '<tr><td class="label"></td><td><br /></td></tr>';
			//bodyPopupBox+= '<tr><td class="label"></td><td><label><input type="checkbox" id="wysiwyg_photo_setup_proportion" checked />' + uiLang.wysiwyg_save_proportion + '</label></td></tr>';
			bodyPopupBox+= '<tr><td class="label"></td><td><label><input type="checkbox" id="wysiwyg_photo_setup_border" ' + noborder + ' />' + uiLang.wysiwyg_show_border + '</label></td></tr>';
			bodyPopupBox+= '<tr><td class="label"></td><td><label><input type="checkbox" id="wysiwyg_photo_setup_window" ' + window + ' />' + uiLang.wysiwyg_on_window + '</label></td></tr>';
			bodyPopupBox+= '<tr><td class="label"></td><td><label><input type="checkbox" id="wysiwyg_photo_setup_addlink" ' + nolink + ' />' + uiLang.wysiwyg_add_link + '</label></td></tr>';
			bodyPopupBox+= '<tr><td class="label"></td><td><label><input type="checkbox" id="wysiwyg_photo_setup_left" ' + f_left + ' />' + uiLang.wysiwyg_image_float_left + '</label></td></tr>';
			bodyPopupBox+= '<tr><td class="label"></td><td><label><input type="checkbox" id="wysiwyg_photo_setup_right" ' + f_right + ' />' + uiLang.wysiwyg_image_float_right + '</label></td></tr>';
			bodyPopupBox+= '</table></div></td><td valign="top">';
			bodyPopupBox+= '<div class="wysiwyg_photo_setup_right"><h3>' + uiLang.wysiwyg_image + '</h3><div class="wysiwyg_photo_setup_photo"><img src="'+ photoURL +'" /></div></div>';
			bodyPopupBox+= '</td></tr></table></div>';
			
			
			this.popupBox = new PopupBox(uiLang.wysiwyg_edit_image, bodyPopupBox, {
				Change: {title:uiLang.change, type:'blue', func: function(e){ this.setupPhoto(imageID, this.photoElem); }.bind(this)},
				Close: {title:uiLang.close, type:'gray'}
			}, 500);
			this.popupBox.show();
			
			var img = new Image();
			img.src = photoURL;			
			var sixeX = this.document.getElementById('wysiwyg_photo_setup_sixeX');
			var sixeY = this.document.getElementById('wysiwyg_photo_setup_sixeY');
			var prop = img.width / img.height;
			this.event.add(sixeX, 'keyup', function(sixeX, sixeY, prop){
				sixeY.value = Math.round(sixeX.value / prop, 0);
			}.bind(this, sixeX, sixeY, prop));
			this.event.add(sixeY, 'keyup', function(sixeX, sixeY, prop){
				sixeX.value = Math.round(sixeY.value * prop, 0);
			}.bind(this, sixeX, sixeY, prop));
			var link_input = this.document.getElementById('wysiwyg_photo_setup_link');
			this.event.add(link_input, 'keyup', function(link_input){
				if(this.trim(link_input.value) != ''){
					this.document.getElementById('wysiwyg_photo_setup_addlink').checked = true;
					this.document.getElementById('wysiwyg_photo_setup_window').checked = false;
				}else{
					this.document.getElementById('wysiwyg_photo_setup_addlink').checked = false;
				}
			}.bind(this, link_input));
			var addlink = this.document.getElementById('wysiwyg_photo_setup_addlink');
			this.event.add(addlink, 'click', function(addlink){
				if(!addlink.checked){
					this.document.getElementById('wysiwyg_photo_setup_link').value = '';
				}
			}.bind(this, addlink));
			
			var f_left = this.document.getElementById('wysiwyg_photo_setup_left');
			var f_right = this.document.getElementById('wysiwyg_photo_setup_right');
			this.event.add(f_left, 'click', function(f_left, f_right){
				if(f_left.checked) f_right.checked = false;
			}.bind(this, f_left, f_right));
			this.event.add(f_right, 'click', function(f_left, f_right){
				if(f_right.checked) f_left.checked = false;
			}.bind(this, f_left, f_right));
			
			var window = this.document.getElementById('wysiwyg_photo_setup_window');
			var addlink = this.document.getElementById('wysiwyg_photo_setup_addlink');
			this.event.add(window, 'click', function(window, addlink){
				if(window.checked){
					addlink.checked = false;
					this.document.getElementById('wysiwyg_photo_setup_link').value = '';
				}
			}.bind(this, window, addlink));
			this.event.add(addlink, 'click', function(window, addlink){
				if(addlink.checked) window.checked = false;
			}.bind(this, window, addlink));
		}
	},
	initSetupPhoto: function(){
		this.imageID = 1;
		var imgs = this.editor.getElementsByTagName('IMG');
		for(var i=0; i<imgs.length; i++){
			if(imgs[i].className.indexOf('wiki') != -1 && imgs[i].className.indexOf('wikiVideo') == -1){
				var imageID = 'image' + this.imageID;
				imgs[i].id = imageID;
				imgs[i].onclick = function(){ return false; };
				this.event.add(imgs[i], 'click', function(e, imageID){  if(e.which != 1) return; this.setupPhoto(imageID); }.extBind(this, imageID));
				
				this.imageID++;
			}
		}
	},
	actVideo: function(){
		this.editor.focus();
		this.currRange = this.getRange();
		this.popupBox = new PopupBox(uiLang.wysiwyg_add_video, '<div class="wysiwyg_video_box"><input type="text" id="wysiwyg_video_code" style="width: 530px;" /><br /><br />' + uiLang.wysiwyg_video_codedesc + '</div><div id="wysiwyg_video_error"></div>', {
			Add: {title:uiLang.add, type:'blue', func: function(){ this.insertVideo(); }.bind(this)},
			Close: {title:uiLang.close, type:'gray'}
		}, 550);
		this.popupBox.show();
		this.document.getElementById('wysiwyg_video_code').focus();
	},
	insertVideo: function(videoHTML){
		var videoCode = this.document.getElementById('wysiwyg_video_code').value;
		var match = null, videoHTML = null;
		if(videoCode != ''){
			if(/(youtube)/.test(videoCode)){
				try{
					match = /^(.*?)(&.*?)?$/.exec(videoCode)[1];
					match = /v=(.*?)$/.exec(videoCode)[1];
					videoHTML = '<object width="600" height="400" videourl="'+videoCode+'"><param name="movie" value="http://www.youtube.com/v/' + match + '?fs=1&amp;hl=ru_RU"></param>\
						<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>\
						<param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/' + match + '?fs=1&amp;hl=ru_RU" wmode="transparent"\
						type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="600" height="400"></embed></object>';
				}catch(error){}
			}else if(/(rutube)/.test(videoCode)){
				try{
					match = /v=([A-z0-9]{32})/.exec(videoCode)[1];
					videoHTML = '\uFEFF<object width="600" height="400" videourl="'+videoCode+'"><param name="movie" value="http://video.rutube.ru/' + match + '"></param>\
						<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>\
						<param name="wmode" value="transparent"></param><embed src="http://video.rutube.ru/' + match + '" wmode="transparent"\
						type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="600" height="400"></embed></object>\uFEFF';
				}catch(error){}
			}else if(/(video\.mail)/.test(videoCode)){
				try{
					if(match = /(mail\/.*).html$/.exec(videoCode)[1]){
						videoHTML = '\uFEFF<object width="600" height="400" videourl="'+videoCode+'" type="application/x-shockwave-flash" data="http://img.mail.ru/r/video2/player_v2.swf?2">\
							<param name="movie" value="http://img.mail.ru/r/video2/player_v2.swf?2" /><param name="flashvars" value="movieSrc=' + match + '" />\
							<param name="devicefont" value="false"/><param name="menu" value="false"/><param name="allowFullScreen" value="true" />\
							<param name="allowScriptAccess" value="always" /><param name="wmode" value="transparent"></param></object>\uFEFF';
					}else if(match = /lvi\/(\d+).html$/.exec(videoCode)[1]){
						videoHTML = '\uFEFF<object width="600" height="400" videourl="'+videoCode+'" type="application/x-shockwave-flash" data="http://img.imgsmail.ru/r/video2/legalvideo/player_v2.swf?1">\
							<param name="movie" value="http://img.imgsmail.ru/r/video2/legalvideo/player_v2.swf?1" /><param name="flashvars" value="movieSrc=' + match + '" />\
							<param name="devicefont" value="false"/><param name="menu" value="false"/><param name="allowFullScreen" value="true" /><param name="scale" value="noscale" />\
							<param name="allowScriptAccess" value="always" /><param name="wmode" value="transparent"></param></object>\uFEFF';
					}
				}catch(error){}
			}
		}
		
		var pElem = null;
		if(videoHTML){
			this.editor.focus();
			var parent = this.getRangeContainer(this.currRange);
			if(parent){
				/* if(parent.nodeName == 'P' && (parent.innerHTML == '<br>' || parent.innerHTML == '\uFEFF')){
					parent.innerHTML = videoHTML;
					pElem = parent;
				}else{
					var prevP = null;
					if(parent != this.editor){
						while(parent != this.editor){
							if(parent.nodeName == 'P'){ prevP = parent; break; };
							parent = parent.parentNode;
						}
					}
					pElem = this.document.createElement('P');
					pElem.innerHTML = videoHTML;
					
					if(prevP){
						this.editor.insertBefore(pElem, prevP.nextSibling);
					}else{
						this.editor.appendChild(pElem);
					}
				} */
				
				pElem = this.document.createElement('P');
				pElem.innerHTML = videoHTML;
				if(parent.nodeName == 'P'){
					this.editor.insertBefore(pElem, parent.nextSibling);
				}else{
					this.editor.appendChild(pElem);
				}
			}else{
				pElem = this.document.createElement('P');
				pElem.innerHTML = videoHTML;
				this.editor.appendChild(pElem);
			}
			if(pElem){
				var pNew = this.document.createElement('P');
				pNew.innerHTML = '\uFEFF';
				this.editor.insertBefore(pNew, pElem.nextSibling);
				this.setElemFocus(pNew);
			}
			
			this.popupBox.hide();
		}else{
			var video_error = this.document.getElementById('wysiwyg_video_error');
			video_error.innerHTML = (videoCode == '') ? uiLang.wysiwyg_video_error1 : uiLang.wysiwyg_video_error2;
			video_error.style.display = 'block';
		}
	},
	actColor: function(button, className){
		this.editor.focus();
		
		var range = this.getRange();
		var text = this.getRangeText(range);
		
		//if(text == '') return;
		
		if(className == 'wikiColor1'){ color = '#5f6ea6'; background = ''; }
		if(className == 'wikiColor2'){ color = '#ffffff'; background = '#379cea'; }
		if(className == 'wikiColor3'){ color = '#f32a82'; background = ''; }
		
		
		if(!this.toolbar[button].down){
			this.toolbar[button].select();
			this.document.execCommand('ForeColor', false, color);
			var font = this.getParent('FONT');
		}else{
			this.toolbar[button].unselect();
			this.document.execCommand('RemoveFormat', false, true);
		}
		
		// Fix background
		this.fixColorBackground();
		if(font) this.setElemFocus(font);
		//this.getFormat();
	},
	actBlock: function(className){
		this.editor.focus();
		
		//var range = this.getRange();
		document.execCommand('FormatBlock', false, '<DIV>');
		var parent = this.getParent('DIV');
		if(parent){
			parent.className = className;
			var text = this.getInnerText(parent);
			parent.innerHTML = (this.trim(text) != '') ? text : '\uFEFF';
		}
		elem = parent;
		
	},
	actSmile: function(){
		this.window.editorName = this.params.editorName;
		this.editor.focus();
		this.currRange = this.getRange();
		
		this.popupBox = new PopupBox(uiLang.wysiwyg_add_smile, '<div class="popup_box_loading"></div>', {Close: {title:uiLang.close}}, 400);
		this.popupBox.show();
		
		this.ajax.post({module:'wysiwyg', act:'getSmile'}, function(data){
			try{ this.popupBox.boxBody.innerHTML = data.form; this.popupBox.fix(); }catch(e){}
		}.bind(this));
	},
	insertSmile: function(code, src){
		var img = this.document.createElement('IMG');
		img.src = src;
		img.setAttribute('smile', code);		
		this.rangeInsertNode(img, this.currRange);
		
		this.popupBox.hide();
	},
	fixColorBackground: function(){
		var html = this.editor.innerHTML;
		this.editor.innerHTML = html.replace(new RegExp("\<\/?span.*?\>", "ig"), "");
			
		var fonts = this.editor.getElementsByTagName('FONT');
		for(var i=0; i<fonts.length; i++){
			if(fonts[i].getAttribute('color') == '#ffffff'){
				fonts[i].innerHTML = '<span style="background-color: #379cea;">' + fonts[i].innerHTML + '</span>';
			}
		}
	},
	fixQuot: function(str){
		return str.replace(/\\\\"/g, '"').replace(/\\"/g, '"').replace(/\\\\'/g, "'").replace(/\\'/g, "'");
	},
	rangeInsertNode: function(node, range){
		this.editor.focus();
    if(range.pasteHTML){
      var div = this.document.createElement('DIV');
      div.appendChild(node);
      range.pasteHTML(div.innerHTML);
    }else{
      range.insertNode(node);
      var space = this.document.createTextNode('\uFEFF');
      if(node.nextSibling){
        node.parentNode.insertBefore(space, node.nextSibling);
      }
    }
	},
	getFormat: function(){
		if(this.wikiMode) return;
		
		var node = this.currRangeElem;
		if(node == undefined) node = this.getRangeContainer();
		if(!node) return;
		var nodeList = new Object();
		var actionList = new Object();
		while(node && node != this.editor){
      if(!nodeList[node.nodeName]){
        nodeList[node.nodeName] = new Object();
        nodeList[node.nodeName].classes = new Object();
        nodeList[node.nodeName].styles = new Array();
        nodeList[node.nodeName].nodes = new Array();
      }
      var className = (node.className == '') ? 'none' : node.className;
      nodeList[node.nodeName].classes[className] = true;
      nodeList[node.nodeName].styles.push(node.style);
      nodeList[node.nodeName].nodes.push(node);
      node = node.parentNode;
    }
		
		var hasProp = function(propArray, propName, propValue, getAttribute) {
      for(var i = 0; i < propArray.length; i++){
        if(propArray[i][propName] == propValue) return true;
        if(getAttribute && (propArray[i].getAttribute(propName) == propValue)) return true;
      }
      return false;
    }
		
		if(nodeList['B'] || nodeList['STRONG']) actionList['bold'] = true;
		if(nodeList['SPAN'] && hasProp(nodeList['SPAN'].styles, 'fontWeight', 'bold')) actionList['bold'] = true;
		if(nodeList['I'] || nodeList['EM']) actionList['italic'] = true;
		if(nodeList['U']) actionList['underline'] = true;
		
		//if (nodeList['SPAN'] && hasProp(nodeList['SPAN'].styles, 'textDecoration', 'underline'))  actionList['underline'] = true;
    //if (nodeList['SPAN'] && hasProp(nodeList['SPAN'].styles, 'textDecoration', 'line-through')) actionList['strike'] = true;
		
		if(nodeList['STRIKE'] || nodeList['S']) actionList['strike'] = true;
		if(nodeList['SUB']) actionList['sub'] = true;
		if(nodeList['SUP']) actionList['sup'] = true;
		
		if(nodeList['H1']) actionList['h1'] = true;
		if(nodeList['H2']) actionList['h2'] = true;
		if(nodeList['H3']) actionList['h3'] = true;
		
		/* if((nodeList['H1']) && (hasProp(nodeList['H1'].nodes, 'align', 'center') || hasProp(nodeList['H1'].styles, 'textAlign', 'center'))) actionList['center'] = true;
		if((nodeList['H1']) && (hasProp(nodeList['H1'].nodes, 'align', 'right') || hasProp(nodeList['H1'].styles, 'textAlign', 'right'))) actionList['right'] = true;
		if((nodeList['H2']) && (hasProp(nodeList['H2'].nodes, 'align', 'center') || hasProp(nodeList['H2'].styles, 'textAlign', 'center'))) actionList['center'] = true;
		if((nodeList['H2']) && (hasProp(nodeList['H2'].nodes, 'align', 'right') || hasProp(nodeList['H2'].styles, 'textAlign', 'right'))) actionList['right'] = true;
		if((nodeList['H3']) && (hasProp(nodeList['H3'].nodes, 'align', 'center') || hasProp(nodeList['H3'].styles, 'textAlign', 'center'))) actionList['center'] = true;
		if((nodeList['H3']) && (hasProp(nodeList['H3'].nodes, 'align', 'right') || hasProp(nodeList['H3'].styles, 'textAlign', 'right'))) actionList['right'] = true; */
		
		if((nodeList['FONT']) && hasProp(nodeList['FONT'].nodes, 'color', '#ffffff')) actionList['color1'] = true;
		if((nodeList['FONT']) && hasProp(nodeList['FONT'].nodes, 'color', '#c10090')) actionList['color2'] = true;
		if((nodeList['FONT']) && hasProp(nodeList['FONT'].nodes, 'color', '#00caec')) actionList['color3'] = true;
		
		
		if(nodeList['UL']) actionList['marker_list'] = true;
		if(nodeList['OL']) actionList['numeric_list'] = true;
		
		if((nodeList['P']) && (hasProp(nodeList['P'].nodes, 'align', 'center') || hasProp(nodeList['P'].styles, 'textAlign', 'center'))) actionList['center'] = true;
		if((nodeList['P']) && (hasProp(nodeList['P'].nodes, 'align', 'right') || hasProp(nodeList['P'].styles, 'textAlign', 'right'))) actionList['right'] = true;
		if((nodeList['P']) && (hasProp(nodeList['P'].nodes, 'align', 'justify') || hasProp(nodeList['P'].styles, 'textAlign', 'justify'))) actionList['justify'] = true;
		if(!actionList['center'] && !actionList['right'] && !actionList['justify']) actionList['left'] = true;
		
		this.resetAll();
		this.selectToolBarButtons(actionList);
		
		if(actionList['h1'] || actionList['h2'] || actionList['h3']){
			this.enableOnly('h1', 'h2', 'h3');
		}
	},
	resetAll: function(){
		for(key in this.toolbar.buttons){
			if(this.toolbar[key]){
        this.toolbar[key].unselect();
				if(this.toolbar[key].disabled){
					this.toolbar[key].enable();
				}
      }
    }
	},
	disableAll: function(){
		for(key in this.toolbar.buttons){
      if(this.toolbar[key]){
        this.toolbar[key].disable();
      }
    }
	},
	selectToolBarButtons: function(buttons){
		for(key in buttons){
      var toolBarButton = this.toolbar[key];
      if(toolBarButton) toolBarButton.select();
    }
	},
	enableToolBar: function(){
    for(var i=0; i<arguments.length; i++){
      if(this.toolbar[arguments[i]]) this.toolbar[arguments[i]].enable();
    }
  },
  disableToolBar: function(){
    for(var i=0; i<arguments.length; i++){
      if(this.toolbar[arguments[i]]) this.toolbar[arguments[i]].unselect();
      if(this.toolbar[arguments[i]]) this.toolbar[arguments[i]].disable();
    }
  },
	enableOnly: function(){
    for(key in this.toolbar.buttons){
      if(this.inArray(key, arguments)){
        if(this.toolbar[key]) this.toolbar[key].enable();
      }else{
        if(this.toolbar[key]) this.toolbar[key].disable();
      }
    }
  },
	getParent: function(){
		var whileStop = false, parent = this.getRangeContainer();
		if(parent){
			while(!whileStop && parent != this.editor){
				for(var i=0; i<arguments.length; i++){
					if(arguments[i].toUpperCase() == parent.nodeName.toUpperCase()){
						whileStop = true; break;
					}
				}
				if(!whileStop) parent = parent.parentNode;
			}
			if(parent == this.editor) parent = null;
		}
		return parent;
	},
	getInnerText: function(elem){
		var text = elem.innerText ? elem.innerText : elem.textContent;
		return text ? text : null;
	},
	setInnerText: function(elem, value) {
    if(elem.innerText != undefined){
      elem.innerText = value;
    }else if(elem.textContent != undefined){
      elem.textContent = value;
    }
  },
	getRange: function(){		
		if(this.browser.msie){
			return this.document.selection.createRange();
		}else if(this.window.getSelection){
			var sel = this.window.getSelection();
			if(sel.rangeCount != 0) return sel.getRangeAt(0);
      else return this.document.createRange();
		}
    return null;
	},
	getRangeElem: function(){
		if(this.browser.msie){
			var range = this.document.selection.createRange();
			return (range.length > 0) ? range.item(0) : null;
		}
		return null;
	},
	getRangeText: function(range){
		return (this.browser.msie) ? range.text : range.toString();
	},
	getRangeOffset: function(elem){
		var startOffset = false, endOffset = false;
    if(this.browser.msie) {
      var rangeCurrent = this.document.selection.createRange();
      var rangeBegin = rangeCurrent.duplicate();
      var rangeEnd = rangeCurrent.duplicate();
      rangeBegin.moveToElementText(elem), rangeEnd.moveToElementText(elem);
      rangeBegin.collapse(true), rangeEnd.collapse(false);
      var newRange = this.document.body.createTextRange();
      newRange.setEndPoint('StartToStart', rangeBegin);
      newRange.setEndPoint('EndToEnd', rangeCurrent);
      startOffset = newRange.text.length;
      newRange.setEndPoint('StartToStart', rangeCurrent);
      newRange.setEndPoint('EndToEnd', rangeEnd);
      endOffset = newRange.text.length;
    } else {
      var rangeCurrent = this.getRange();
      var rangeCopy = rangeCurrent.cloneRange();
      rangeCopy.setStartBefore(rangeCopy.commonAncestorContainer);
      startOffset = rangeCopy.toString().length;
      rangeCopy = rangeCurrent.cloneRange();
      rangeCopy.setEndAfter(rangeCopy.commonAncestorContainer);
      endOffset = rangeCopy.toString().length;
    }
    startOffset = (startOffset == 0) ? true : false;
    endOffset = (endOffset == 0) ? true : false;
    return { startOffset: startOffset, endOffset: endOffset };
	},
	getRangeContainer: function(range){
    if(!range) range = this.getRange();
		if(range != null){
      if(range.commonAncestorContainer){
				/* if(range.commonAncestorContainer.parentElement){
					return range.commonAncestorContainer.parentElement;
				} */
        return range.commonAncestorContainer;
      }else{
        if(range.parentElement){
          return range.parentElement();
        }
      }
    }
    return null;
	},
	setRangeText: function(text, range){
		return (range.pasteHTML) ? range.pasteHTML(text) : this.document.execCommand('InsertHtml', false, text);
	},
	rangeDeleteContents: function(range){
		if(range.pasteHTML){
			this.editor.focus();
			range.pasteHTML('');
		}else{
			range.deleteContents();
		}
	},
	setElemFocus: function(elem, pos){
		if(!elem) return;
		if(pos == undefined) pos = false;
    if(this.window.getSelection){
      var sel = this.window.getSelection();
      var rng = this.document.createRange();
      sel.removeAllRanges();
      rng.selectNodeContents(elem);
      rng.collapse(pos);
      sel.addRange(rng);
    }else{
      var rng = this.document.body.createTextRange();
      if(elem.nodeType != 3){
        try{
          rng.moveToElementText(elem);
          rng.collapse(pos);
          rng.select();
        }catch(error){ }
      }
    }
	},
	htmlToWiki: function(){
		if(this.wikiMode){
			return this.wikiEditor.value;
		}
		
		var html = this.editor.innerHTML;
		html = html.replace(/\r\n|\r|\n/gi, '');
		this.editor.innerHTML = jWps.trim(html);
		this.newLine = '\n';
		this.convertOptions = new Object();
    var c = this.convertOptions;
		c.convertTags = ['B', 'I', 'U', 'S', 'SUB', 'SUP', 'BLOCKQUOTE'];
    c.blockTags = ['P', 'DIV', 'H1', 'H2', 'H3', 'LI', 'BR', 'TABLE'];
    c.alignTagsTest = ['P', 'DIV', 'TH', 'TD'];
    c.headersTags = ['H1', 'H2', 'H3'];
    c.replaceTags = {
      STRIKE: { open: '{s}', close: '{s}' },
      EM: { open: '{i}', close: '{i}' },
      STRONG: { open: '{b}', close: '{b}' },
			H1: { open: '== ', close: ' ==' },
			H2: { open: '=== ', close: ' ===' },
			H3: { open: '==== ', close: ' ====' }
    };
    c.tableTags = {
      TABLE: { open: '{|', close: '|}', noBorder: 'noborder' },
      CAPTION: { open: '|+ ', close: '' },
      COL: { open: '|~', close: '' },
      TR: { open: '|-', close: '' },
      TH: { open: '! ', close: '' },
      TD: { open: '| ', close: '' }
    };
		
		this.wikiText = '';
		
		var lastChild = this.editor.lastChild;
		if(lastChild){
			if(lastChild.nodeName == 'P' && lastChild.innerHTML == '\uFEFF'){
				lastChild.parentNode.removeChild(lastChild);
			}
			this.removeEmptyTags(this.editor);
			this.htmlConvert(this.editor);
		}
		
		while(this.wikiText.substr(this.wikiText.length - 1) == "\n"){
			this.wikiText = this.wikiText.substr(0, this.wikiText.length - 1);
		}
		return this.wikiText;
	},
	removeEmptyTags: function(node){
		var node = node.firstChild;
		while(node){
			if(node.nodeType == 1){
				if(node.childNodes.length > 1){
					this.removeEmptyTags(node);
				}
				
				var text = this.trim(node.innerHTML).replace(/\r\n|\r|\n/gi, '');
				if((text == '' || text == '\uFEFF' || (text == '<br>' && node.nodeName != 'P')) && node.nodeName != 'IMG' && node.nodeName != 'OBJECT'){
					var nextNode = node.nextSibling;
					node.parentNode.removeChild(node);
					node = nextNode;
				}else node = node.nextSibling;
			}else node = node.nextSibling;
		}
	},
	htmlConvert: function(node){
		var c = this.convertOptions;
		if(node.nodeType == 3){ // TextNode
			//if(this.trim(node.nodeValue) == '') return false;
			this.addWikiText(this.replaceSpecialChars(node.nodeValue));
		}else if(node.nodeType == 1){ // Tag
			var viewChilds = true;
			
			var left = this.testAlign(node, 'left');
			var center = this.testAlign(node, 'center');
			var right = this.testAlign(node, 'right');
			var justify = this.testAlign(node, 'justify');
			
			if(node.nodeName == 'P'){
				var searchObject = false;
				var childs = node.childNodes;
				for(var i=0; i<childs.length; i++){
					if(childs[i].nodeName == 'OBJECT'){
						if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
						if(center) this.addWikiText('{c}');
						else if(right) this.addWikiText('{r}');
						this.addWikiText('[[' + childs[i].getAttribute('videourl') + ']]');
						if(center) this.addWikiText('{c}');
						else if(right) this.addWikiText('{r}');
						this.addWikiText(this.newLine);
						searchObject = true;
						break;
					}
				}
				if(searchObject) return false;
			}
			
			// VIDEO
			/* if(node.nodeName == 'IMG' && node.className == 'wikiVideo'){
				this.addWikiText('[[' + node.getAttribute('videourl') + ']]');
				//this.addWikiText(this.newLine);
				return false;
			} */
			if(node.nodeName == 'P'){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
			}
			if(node.nodeName == 'P' && (node.innerHTML == '\uFEFF' || node.innerHTML == '<br>')){
				this.addWikiText(this.newLine);
				return false;
			}
			// TABLE
			if(node.nodeName == 'TABLE'){
				var options = '';
				if(node.className.indexOf('nopadding') != -1) options += 'nopadding;';
				if(node.className.indexOf('nomargin') != -1) options += 'nomargin;';
				if(node.className.indexOf('noborder') != -1) options += 'noborder;';
				if(node.className.indexOf('lighting') != -1) options += 'lighting;';
				if(options != '') options = options.substr(0, options.length - 1);
				
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('{|' + options);
			}else if(node.nodeName == 'TR'){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('|-');
			}else if(node.nodeName == 'TH'){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('! ');
			}else if(node.nodeName == 'TD'){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('| ');
			}
			// END TABLE
			
			// BLOCKS
			if(node.nodeName == 'DIV' && (node.className == 'wikiBlock1' || node.className == 'wikiBlock1')){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('{' +  ((node.className == 'wikiBlock1') ? 'block1' : 'block2') + '}');
			}
			
			// VOTE
			if(node.nodeName == 'DIV' && node.className == 'vote'){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('[' + this.getInnerText(node) + ']');
				return false;
			}
			
			// ALBUM
			if(node.nodeName == 'DIV' && node.className == 'box_album'){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('[[album' + node.getAttribute('albumid') + ']]');
				return false;
			}
			
			// NOWIKI
			if(node.nodeName == 'SPAN' && node.className == 'nowiki'){
				//if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('{nowiki}');
				return false;
			}
			
			if(this.inArray(node.nodeName, c.convertTags)){
				this.addWikiText('{' + node.nodeName.toLowerCase() + '}');
			}
			else if(c.replaceTags[node.nodeName]){
				this.addWikiText(c.replaceTags[node.nodeName].open);
			}
			else if(this.inArray(node.nodeName, c.headersTags)){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
			}
			if(center) this.addWikiText('{c}');
      else if(right) this.addWikiText('{r}');
      else if(justify) this.addWikiText('{j}');
			else if(node.nodeName == 'UL') this.listTag = '* ';
      else if(node.nodeName == 'OL') this.listTag = '# ';
			else if(node.nodeName == 'LI'){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
        this.addWikiText(this.listTag);
			}
			else if(node.nodeName == 'IMG' && node.getAttribute('smile')){ // SMILE
				this.addWikiText(node.getAttribute('smile'));
			}
			else if((node.nodeName == 'A' && node.firstChild.nodeName == 'IMG') || node.nodeName == 'IMG'){
				this.addWikiText(this.getWikiImage(node));
				return false;
			}
			else if(node.nodeName == 'A'){
        this.addWikiText(this.getWikiLink(node));
        return false;
      }else if(node.nodeName == 'FONT' || node.nodeName == 'SPAN'){
				if(node.color == '#5f6ea6') this.addWikiText('{c1}');
				if(node.color == '#ffffff') this.addWikiText('{c2}');
				if(node.color == '#f32a82') this.addWikiText('{c3}');
			}
			
			if(viewChilds){ // Recurse
				for(var i=0; i<node.childNodes.length; i++){
					this.htmlConvert(node.childNodes[i]);
				}
			}			
			
			// TABLE
			if(node.nodeName == 'TABLE'){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
				this.addWikiText('|}');
			}
			// END TABLE
			
			// BLOCKS
			if(node.nodeName == 'DIV' && (node.className == 'wikiBlock1' || node.className == 'wikiBlock1')){
				this.addWikiText('{' +  ((node.className == 'wikiBlock1') ? 'block1' : 'block2') + '}');
			}
			
			// NOWIKI
			if(node.nodeName == 'SPAN' && node.className == 'nowiki'){
				this.addWikiText('{nowiki}');
				return false;
			}
			
			if(node.nodeName == 'FONT' || node.nodeName == 'SPAN'){
				if(node.color == '#5f6ea6') this.addWikiText('{c1}');
				if(node.color == '#ffffff') this.addWikiText('{c2}');
				if(node.color == '#f32a82') this.addWikiText('{c3}');
			}
			if(this.inArray(node.nodeName, c.convertTags)){
				this.addWikiText('{' + node.nodeName.toLowerCase() + '}');
			}
			if(center) this.addWikiText('{c}');
      else if(right) this.addWikiText('{r}');
      else if(justify) this.addWikiText('{j}');
			if(c.replaceTags[node.nodeName]){
				this.addWikiText(c.replaceTags[node.nodeName].close);
			}
			//if(node == node.parentNode.lastChild) return false;
			if(this.inArray(node.nodeName, c.blockTags)){
				if(!this.testNewLine(this.wikiText)) this.addWikiText(this.newLine);
			}
		}
	},
	getWikiLink: function(node){
		var locHost = location.host;
		var linkHost = node.host.substr(0,locHost.length);
		var linkPathname = node.pathname;
		var linkHref = node.href;
		var linkText = this.getInnerText(node);
		var link = '';

		if(locHost == linkHost){
			var match = false; // /^\/?(id|group|event|news|note|wiki)(\d+)/.exec(linkPathname);
			if(match){
				link = '[[' + match[1] + match[2] + ']]';
			}else{
				if(linkHref == linkText) link = '[[' + linkHref + ']]';
				else link = '[[' + linkHref + '|' + linkText + ']]';
			}
		}else{
			if(linkHref == linkText) link = '[[' + linkHref + ']]';
			else link = '[[' + linkHref + '|' + linkText + ']]';
		}
		return link;
	},
	getWikiImage: function(node){
		var imgSrc = '', options = '', text = '', link = '';
		if(node.nodeName == 'A'){
			link = node.href;
			if(node.title != '') text = node.title
			var img = node.firstChild;
			imgSrc = img.src;
			if(img.className.indexOf('noborder') != -1) options = 'noborder;';
			if(link == imgSrc){ options+= 'window;'; link = ''; }
			if(node.className.indexOf('left') != -1) options+= 'left;';
			if(node.className.indexOf('right') != -1) options+= 'right;';
			if(((node.width > 100 || node.height > 100) && /^photo\d+$/.test(imgSrc)) || !/^photo\d+$/.test(imgSrc)){
				options+= img.width + 'x' + img.height + 'px';
			}
		}else{
			imgSrc = node.src;
			if(node.title != '') text = node.title;
			if(node.className.indexOf('noborder') != -1) options = 'noborder;';
			if(node.className.indexOf('window') != -1) options+= 'window;';
			else options+= 'nolink;';
			if(node.className.indexOf('left') != -1) options+= 'left;';
			if(node.className.indexOf('right') != -1) options+= 'right;';
			if(((node.width > 100 || node.height > 100) && /^photo\d+$/.test(imgSrc)) || !/^photo\d+$/.test(imgSrc)){
				options+= node.width + 'x' + node.height + 'px';
			}
		}
		if(options.substr(options.length - 1) == ';') options = options.substr(0, options.length - 1);
		if(options != '') options = '|' + options;
		if(text != '') text = '|' + text;
		if(link != '') link = '|' + link;
		
		return '[[' + imgSrc + options + text + link + ']]';
		//[[src|noborder;nolink;100x70px|Красивое фото|Link]]
	},
	inArray: function(value, array) {
    for(var i=0; i<array.length; i++){
      if(array[i] == value) return true;
    }
    return false;
  },
	testNewLine: function(text){
		if(text.length == 0) return true;
    if(text.substr(text.length - 1) == '\n') return true;
    return false;
	},
	replaceSpecialChars: function(str){
    str = str.replace(/#/g, '&#35;').replace(/\*/g, '&#42;');
    str = str.replace(/</g, '&#60;').replace(/>/g, '&#62;');
    str = str.replace(/\[/g, '&#91;').replace(/]/g, '&#93;');
    str = str.replace(/\{/g, '&#123;').replace(/\}/g, '&#125;');
    str = str.replace(/=/g, '&#61;').replace(/~/g, '&#126;');
    str = str.replace(/\|/g, '&#124;').replace(/!/g, '&#33;');
    return str;
	},
	addWikiText: function(text){
		this.wikiText += text;
		if(this.debug) this.replaceElem.value = this.wikiText;
	}
}
