var almsamim = {};
var comm, bbcode;
var isIE, isOpera,isGecko, isWebKit,ua,Editor;

ua = navigator.userAgent;
almsamim.isOpera = isOpera = window['opera'] && opera.buildNumber;
almsamim.isWebKit = isWebKit = /WebKit/.test(ua);
almsamim.isGecko = isGecko = !isWebKit && /Gecko/.test(ua);
almsamim.isIE = isIE = !isWebKit && !isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(navigator.appName);

almsamim.plugins = {};

// dropdown divs of the toolbar
var lang_s = new Array();
var ids = new Array;
ids[5] = 'Colorpalettef';

var smiley_wysiwyg = true;

var smiley_code = new Array();
for (i = 0; i < 700; i++){
    smiley_code[i] = '[e' + (i < 10 ? '0' + i : i) + ']';
}

var smiley_img = new Array();
for (i = 0; i < 700; i++){
    smiley_img[i] = (i < 10 ? '0' + i : i ) + '.gif';
}

var smiley_path = "images/smile/";
var smiley_total = 700;

var doc = null;

var tra = new Array();
var abc2 = new Array();
var translit = false;
var translit_language = true;

tra[String.fromCharCode(97)] = new Array ('ы+','Й+','Ы+','й+','Ы','й','ы','Й','','');
abc2[String.fromCharCode(97)] = new Array ('ыа','Йа','Ыа','йа','Я','я','я','Я','а','a');

tra[String.fromCharCode(98)] = new Array ('','');
abc2[String.fromCharCode(98)] = new Array ('б','b');

tra[String.fromCharCode(118)] = new Array ('','');
abc2[String.fromCharCode(118)] = new Array ('в','v');

tra[String.fromCharCode(103)] = new Array ('','');
abc2[String.fromCharCode(103)] = new Array ('г','g');

tra[String.fromCharCode(100)] = new Array ('','');
abc2[String.fromCharCode(100)] = new Array ('д','d');

tra[String.fromCharCode(101)] = new Array ('Й+','й+','Й','й','','');
abc2[String.fromCharCode(101)] = new Array ('Йе','йе','Э','э','е','e');

tra[String.fromCharCode(111)] = new Array ('ы+','Й+','Ы+','й+','Ы','ы','Й','й','','');
abc2[String.fromCharCode(111)] = new Array ('ыо','Йо','Ыо','йо','Ё','ё','Ё','ё','о','o');

tra[String.fromCharCode(246)] = new Array ('','');
abc2[String.fromCharCode(246)] = new Array ('ё','ц');

tra[String.fromCharCode(104)] = new Array ('сх+','Сх+','з+','Сх','с+','ш+','Ц+','Ш+','С+','сх','ц+','З+','Ш','с','ц','ш','З','С','Ц','з','','');
abc2[String.fromCharCode(104)] = new Array ('схх','Схх','зх','Щ','сх','шх','Цх','Шх','Сх','щ','цх','Зх','Щ','ш','ч','щ','Ж','Ш','Ч','ж','х','h');

tra[String.fromCharCode(122)] = new Array ('','');
abc2[String.fromCharCode(122)] = new Array ('з','z');

tra[String.fromCharCode(105)] = new Array ('','');
abc2[String.fromCharCode(105)] = new Array ('и','i');

tra[String.fromCharCode(106)] = new Array ('','');
abc2[String.fromCharCode(106)] = new Array ('й','j');

tra[String.fromCharCode(107)] = new Array ('','');
abc2[String.fromCharCode(107)] = new Array ('к','k');

tra[String.fromCharCode(108)] = new Array ('','');
abc2[String.fromCharCode(108)] = new Array ('л','l');

tra[String.fromCharCode(109)] = new Array ('','');
abc2[String.fromCharCode(109)] = new Array ('м','m');

tra[String.fromCharCode(110)] = new Array ('','');
abc2[String.fromCharCode(110)] = new Array ('н','n');

tra[String.fromCharCode(112)] = new Array ('','');
abc2[String.fromCharCode(112)] = new Array ('п','p');

tra[String.fromCharCode(114)] = new Array ('','');
abc2[String.fromCharCode(114)] = new Array ('р','r');

tra[String.fromCharCode(115)] = new Array ('','');
abc2[String.fromCharCode(115)] = new Array ('с','s');

tra[String.fromCharCode(116)] = new Array ('','');
abc2[String.fromCharCode(116)] = new Array ('т','t');

tra[String.fromCharCode(117)] = new Array ('ы+','Й+','Ы+','й+','Ы','й','ы','Й','','');
abc2[String.fromCharCode(117)] = new Array ('ыу','Йу','Ыу','йу','Ю','ю','ю','Ю','у','u');

tra[String.fromCharCode(102)] = new Array ('','');
abc2[String.fromCharCode(102)] = new Array ('ф','f');

tra[String.fromCharCode(120)] = new Array ('','');
abc2[String.fromCharCode(120)] = new Array ('х','x');

tra[String.fromCharCode(99)] = new Array ('','');
abc2[String.fromCharCode(99)] = new Array ('ц','c');

tra[String.fromCharCode(119)] = new Array ('','');
abc2[String.fromCharCode(119)] = new Array ('щ','w');

tra[String.fromCharCode(35)] = new Array ('ъ+','ъ','','');
abc2[String.fromCharCode(35)] = new Array ('ъъ','Ъ','ъ','#');

tra[String.fromCharCode(121)] = new Array ('','');
abc2[String.fromCharCode(121)] = new Array ('ы','y');

tra[String.fromCharCode(39)] = new Array ('ь+','ь','','');
abc2[String.fromCharCode(39)] = new Array ('ьь','Ь','ь','\'');

tra[String.fromCharCode(228)] = new Array ('','');
abc2[String.fromCharCode(228)] = new Array ('э','д');

tra[String.fromCharCode(252)] = new Array ('','');
abc2[String.fromCharCode(252)] = new Array ('ю','ь');

tra[String.fromCharCode(65)] = new Array ('Ы+','Й+','Ы','Й','','');
abc2[String.fromCharCode(65)] = new Array ('ЫА','ЙА','Я','Я','А','A');

tra[String.fromCharCode(66)] = new Array ('','');
abc2[String.fromCharCode(66)] = new Array ('Б','B');

tra[String.fromCharCode(86)] = new Array ('','');
abc2[String.fromCharCode(86)] = new Array ('В','V');

tra[String.fromCharCode(71)] = new Array ('','');
abc2[String.fromCharCode(71)] = new Array ('Г','G');

tra[String.fromCharCode(68)] = new Array ('','');
abc2[String.fromCharCode(68)] = new Array ('Д','D');

tra[String.fromCharCode(69)] = new Array ('Й+','Й','','');
abc2[String.fromCharCode(69)] = new Array ('ЙЕ','Э','Е','E');

tra[String.fromCharCode(79)] = new Array ('Ы+','Й+','Ы','Й','','');
abc2[String.fromCharCode(79)] = new Array ('ЫО','ЙО','Ё','Ё','О','O');

tra[String.fromCharCode(214)] = new Array ('','');
abc2[String.fromCharCode(214)] = new Array ('Ё','Ц');

tra[String.fromCharCode(72)] = new Array ('СХ+','Ц+','СХ','С+','З+','Ш+','Ш','Ц','С','З','','');
abc2[String.fromCharCode(72)] = new Array ('СХХ','ЦХ','Щ','СХ','ЗХ','ШХ','Щ','Ч','Ш','Ж','Х','H');

tra[String.fromCharCode(90)] = new Array ('','');
abc2[String.fromCharCode(90)] = new Array ('З','Z');

tra[String.fromCharCode(73)] = new Array ('','');
abc2[String.fromCharCode(73)] = new Array ('И','I');

tra[String.fromCharCode(74)] = new Array ('','');
abc2[String.fromCharCode(74)] = new Array ('Й','J');

tra[String.fromCharCode(75)] = new Array ('','');
abc2[String.fromCharCode(75)] = new Array ('К','K');

tra[String.fromCharCode(76)] = new Array ('','');
abc2[String.fromCharCode(76)] = new Array ('Л','L');

tra[String.fromCharCode(77)] = new Array ('','');
abc2[String.fromCharCode(77)] = new Array ('М','M');

tra[String.fromCharCode(78)] = new Array ('','');
abc2[String.fromCharCode(78)] = new Array ('Н','N');

tra[String.fromCharCode(80)] = new Array ('','');
abc2[String.fromCharCode(80)] = new Array ('П','P');

tra[String.fromCharCode(82)] = new Array ('','');
abc2[String.fromCharCode(82)] = new Array ('Р','R');

tra[String.fromCharCode(83)] = new Array ('','');
abc2[String.fromCharCode(83)] = new Array ('С','S');

tra[String.fromCharCode(84)] = new Array ('','');
abc2[String.fromCharCode(84)] = new Array ('Т','T');

tra[String.fromCharCode(85)] = new Array ('Ы+','Й+','Ы','Й','','');
abc2[String.fromCharCode(85)] = new Array ('ЫУ','ЙУ','Ю','Ю','У','U');

tra[String.fromCharCode(70)] = new Array ('','');
abc2[String.fromCharCode(70)] = new Array ('Ф','F');

tra[String.fromCharCode(88)] = new Array ('','');
abc2[String.fromCharCode(88)] = new Array ('Х','X');

tra[String.fromCharCode(67)] = new Array ('','');
abc2[String.fromCharCode(67)] = new Array ('Ц','C');

tra[String.fromCharCode(87)] = new Array ('','');
abc2[String.fromCharCode(87)] = new Array ('Щ','W');

tra[String.fromCharCode(89)] = new Array ('','');
abc2[String.fromCharCode(89)] = new Array ('Ы','Y');

tra[String.fromCharCode(196)] = new Array ('','');
abc2[String.fromCharCode(196)] = new Array ('Э','Д');

tra[String.fromCharCode(220)] = new Array ('','');
abc2[String.fromCharCode(220)] = new Array ('Ю','Ь');

var smiles = new Array();
smiles[':D'] = ':D';
smiles[';)'] = ';)';
smiles[':)'] = ':)';
smiles[':P'] = ':P';
smiles[':]'] = ':]';
smiles['=)'] = '=)';
smiles[':|'] = ':|';
smiles[':('] = ':(';
smiles[':\\'] = ':\\';
smiles['=0'] = '=0';
smiles[':X'] = [':X'];

/*
* отослать сообщение
*/
function send_message(button_object){

	Editor = document.getElementById('box').contentWindow.document;
	var ceditor = bbcode._HTMLtoBBcode(bbcode._erase(Editor.body.innerHTML));
	
	ceditor = ceditor.replace(/(^\s+)|(\s+$)/g, "");
	
	/* если данных нет */
	if (!$.fn.editor_options.empty_msg && ceditor == ''){
		alert(locale.empty_message[lang]);
		$('#box').get(0).contentWindow.focus();
		return;
	}	

	if ($.fn.editor_options.unbind_btn){
		button_object.onclick = '';
	}

	/* выполнить callback или сделать пост по умолчанию */
	if (typeof $.fn.editor_options.callback == 'function'){
		$.fn.editor_options.callback(ceditor);
	}else{

		var valid = true;
		/* если есть дополнительные поля для post */
		if ($.fn.editor_options.onpost != null && (post_vars = $.fn.editor_options.onpost()) != false){

			/* совместить все в один массив */
			post_vars = $.extend({
					editor_msg: ceditor
			  	}, post_vars);
			  	
		}else if($.fn.editor_options.onpost != null && (post_vars = $.fn.editor_options.onpost()) == false){
		
			/* валидация не прошла */
			valid = false;
		
		}else{
			var post_vars = {
				editor_msg: ceditor
		  	};
		}

		/* выполнить запрос на сервер и выполнить onresult */
		if (valid == true){
			$.post($.fn.editor_options.post_url, post_vars, $.fn.editor_options.onresult);
		}
	}

	return;

}

//-----------------------------------------------------------------------

function cookie_create(name, value, days){

	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}else{
		var expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/";
}
//-----------------------------------------------------------------------


function cookie_read(name){

	var ca = document.cookie.split(';');
	var nameEQ = name + "=";
	for(var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length, c.length);
	}
	return null;
}
//-----------------------------------------------------------------------


function cookie_delete(name){
	cookie_create(name, "", -1);
}
//-----------------------------------------------------------------------


function hideFgColors(obj){

	$('#colors_fg').hide();

}
//-----------------------------------------------------------------------


function skip_smile(txt){
	if (txt.length > 2){
		txt = txt.substr(txt.length - 2);
	}
	if (!smiles[txt]){
		return false;
	}else{
		return true;
	}
}
//-----------------------------------------------------------------------


function translate_letter(keyCode, e)
{
	var txt = String.fromCharCode(keyCode);
	if (txt== '<' || txt == '[') {
		translit_language = false;
	}
	if (txt == '>' || txt == ']') {
		translit_language = true;
	}
	if (!tra[txt]){
		return true;
	}
	
	doc = document.getElementById('box').contentWindow.document;
	
	
	if (navigator.family == 'ie4'){
		keyCode = 0;
		with(doc.selection.createRange()){
			if (text != ''){
				
				doc.selection.clear();
			}
			text = '';
			collapse();
			select();
		}
		cursor_pos_selection = doc.selection.createRange();
		cursor_pos_selection.select();
		cursor_pos_selection.text = '%';
		cursor_pos_selection.moveStart("character", -2);
		pretxt = cursor_pos_selection.text.substring(0, cursor_pos_selection.text.length-1);
		cursor_pos_selection.text = '';
		cursor_pos_selection.collapse();
		result ="";
		if (translit_language && !skip_smile(pretxt+txt)){
        		
        		result = translatesymboltocyrillic(pretxt+txt); 
        		
		}else{
			result = pretxt+txt;
		}
		
		with(doc.selection.createRange()) {
			select();
			text = result;
			collapse();
		}
	}else{

		if (keyCode && keyCode > 33 && (!(e.ctrlKey || e.altKey)))
		{
			if (e.preventDefault){
				e.preventDefault();
			}
			var sel = document.getElementById('box').contentWindow.getSelection();
			var range = sel.getRangeAt(0);
			if (navigator.family != 'opera'){
				sel.removeAllRanges();
				range.deleteContents();
				var container = range.startContainer;
				var pos = range.startOffset;
				range=document.createRange();
			}else{
				var container = range.startContainer;
				var pos = range.startOffset;
			}
			var afterNode;
			if (container.nodeType==3) {
				var textNode = container;
				container = textNode.parentNode;
				var text = textNode.nodeValue;
				var textBefore = text.substr(0,pos);
				var textAfter = text.substr(pos);
				
				if (translit_language && !skip_smile(textBefore + txt)){
					textBefore = translatesymboltocyrillic(textBefore + txt); // to cyrillic
				}else{
					textBefore = textBefore + txt;
				}
				pos = textBefore.length;
				textNode.nodeValue = textBefore+textAfter;
				range.setEnd(textNode, pos);
				range.setStart(textNode, pos);
			}else {
				textNode = container.childNodes[pos];
				if (translit_language && !skip_smile(txt)){
					txt = translatesymboltocyrillic(txt); // to cyrillic
				}
				
				afterNode = document.createTextNode(txt);
				pos = txt.length;
				container.insertBefore(afterNode, textNode);
				range.setEnd(afterNode, pos);
				range.setStart(afterNode, pos);
			}
			sel.addRange(range);
		}
	}
	$('#box').get(0).contentWindow.focus();
	return false;
}
//-----------------------------------------------------------------------


function translatesymboltocyrillic(txt)
{
	var pretxt = txt.substr(0,txt.length-1);
	var last = txt.substr(txt.length-1,1);
	var lat = tra[last];
	var rus = abc2[last];
	if (lat){
		for (var ii=0; ii<lat.length; ii++){
			var pos = pretxt.length>lat[ii].length?(pretxt.length-lat[ii].length):0;
			if (lat[ii]==pretxt.substr(pos,pretxt.length-pos)){
				return pretxt.substr(0,pretxt.length-lat[ii].length)+rus[ii];
			}
		}
	}
	return txt;
}
//-----------------------------------------------------------------------


function shortkey_pressed(e){
	var keynum;
	var keychar;
	var ctrl;

	if (navigator.appName.indexOf("Netscape") == -1){ // IE
		keynum = e.keyCode;
	}else if(e.which){ // Netscape/Firefox/Opera
		keynum = e.which;
	}

	keychar = String.fromCharCode(keynum);

	if ((keynum == 13 && e.ctrlKey) || (keynum == 10 && e.ctrlKey)){
		if (document.getElementById("chat") != null) {
			setTimeout('send_message1();', 10);
		} else {
			setTimeout('send_message("");', 10);
		}
		return false;
	}

	if (translit){
		res = translate_letter(keynum, e);
	}else{
		res = true;
	}
	
	return res;
}
//-----------------------------------------------------------------------


function saveCurrentPos(){

	if (navigator.family == 'ie4' ){
		current_pos = document.getElementById('box').contentWindow.document.selection.createRange();
	}

}
//-----------------------------------------------------------------------


if (smiley_wysiwyg)
{
       var smiley_code_bbcode = new Array();
       var smiley_img_bbcode = new Array();

       for(var i = 0; i < smiley_total; i++) {
          smiley_code_bbcode[i] = smiley_code[i];
          smiley_img_bbcode[i] = "[IMG]/" + smiley_path + smiley_img[i] + "[/IMG]";
       }

	function Smiley_HTMLtoBBcode(str) {

		/* FF smile troubles */
		
		while (str.indexOf('.../images/smile') > -1) {
			str = str.replace('.../images/smile','/images/smile');
		}
		
		while (str.indexOf('/..') > -1) {
			str = str.replace('/..','');
		}

		for(var i = 0; i < smiley_total; i++) {
			while (str.indexOf(smiley_img_bbcode[i]) > -1) {
				str = str.replace(smiley_img_bbcode[i], smiley_code_bbcode[i]);
			}
		}
		/* удалить все картинки, которые не смайлы */
		return str.replace(/\[img\](.*?)\[\/img\]/gi,'');
       };

       function Smiley_BBcodetoHTML(str) {
          for(var i = 0; i < smiley_total; i++) {
             while (str.indexOf(smiley_code_bbcode[i]) > -1) {
                str = str.replace(smiley_code_bbcode[i], smiley_img_bbcode[i]);
             }
          }
          return str;
       };
}

almsamim.bbcode = bbcode = {

// turning the editor on
Start  : function (){

	Editor = document.getElementById('box').contentWindow.document;


	var iframeContent;
	iframeContent  = '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-gb" xml:lang="en-gb">\n';
	iframeContent += '<head><style type="text/css">body{font-family:Verdana,Arial,Sans-Serif,Tahoma;font-size:11px;background:#fff;color:#000;margin:2px;padding:2px;}p {margin:0;padding:0;min-height: 1em; } *+html p { min-height: auto; }div {margin:0;padding:0;}</style></head><body>';
	//iframeContent += '<head></head><body>';
	var msg_editor_h = document.getElementById("msg_editor_h");
	if (msg_editor_h.value !== ""){
		iframeContent += this._BBcodetoHTML(msg_editor_h.value) ;
	}

	iframeContent += '</body>';
	iframeContent += '</html>';
	Editor.open();
	Editor.write(iframeContent);
	Editor.close();

	if(isIE){
		Editor.body.contentEditable = true;
	}else {
		Editor.designMode = "on";
	}
	
	
	
	/* события */
	
	if (typeof Editor.addEventListener != 'undefined') {
		Editor.addEventListener("keypress", shortkey_pressed, true);
		Editor.addEventListener("onclick", saveCurrentPos, true);

	}else if (typeof Editor.attachEvent != 'undefined') {
		Editor.attachEvent('onkeypress', shortkey_pressed);
		Editor.attachEvent('onclick', saveCurrentPos);

	}

	if(isIE){
		Editor.attachEvent('onmousedown', hideall);
	}else{
		Editor.addEventListener('mousedown', hideall, true);
	}
	/*
	if(isIE){
		Editor.attachEvent('onkeypress', editorEvents);
		Editor.attachEvent('onmousedown', editorEvents);
		Editor.attachEvent('onmousedown', hideall);
		Editor.body.contentEditable = true;
	}else{
		Editor.addEventListener('keypress', editorEvents, true);
		Editor.addEventListener('mousedown', editorEvents, true);
		Editor.addEventListener('mousedown', hideall, true);
		Editor.designMode = "on";
	}
	*/

//		activate_divs();


	if(!isWebKit){
		// disable CSS in Geko ,IE and opera
		try {
			// Try new Gecko method
			Editor.execCommand("styleWithCSS", 0, false);
		} catch (e) {
			// Use old method
			try {Editor.execCommand("useCSS", 0, true);} catch (e) {};
		}
	}


	$('#more_smiles').click(function(e){

		if (!$('#smile_popup_width').is(":hidden")) {
			$('#smile_popup_width').hide();
			$('#box').get(0).contentWindow.focus();
		} else {
			x=e.pageX - 520;
			//y=e.pageY - 390;
			y = e.pageY - $('#smile_popup_width').height() - 30;

			if (x < 0) {
				x = 3;
			}
			if (y < 0) {
				y = 0;
			}

			x = x + 'px';
			y = y + 'px';

			$('#smile_popup_width').css({left:x,top:y,display:''});

		}
		return false;
	});
	//-----------------------------------------------------------------------


	$('.customize_smiles').click(function(e){
		 window_open('/window/profile/custom_smiles.html', 700, 500, 'smiles', true);
	});
	//-----------------------------------------------------------------------

	
	$('#bclose_smiles').click(function(e){

		$('#smile_popup_width').hide();
		$('#box').get(0).contentWindow.focus();

	});
	//-----------------------------------------------------------------------


	$('#colors_btn').click(function(e){

		if (!$('#colors_fg').is(":hidden")) {

			$('#colors_fg').hide();
			$('#box').get(0).contentWindow.focus();

		} else {
			x = e.pageX;
			y = e.pageY;

			if (x < 0){
				x = 3;
			}
			if (y < 0){
				y = 0;
			}

			x = x + 'px';
			y = y + 'px';
			
			$('#colors_fg').css({left:x,top:y,display:''}).show();

		}

	});
	//-----------------------------------------------------------------------


	$('#col_close').click(function(e){

		$('#colors_fg').hide();
		$('#box').get(0).contentWindow.focus();

	});
	
	//-----------------------------------------------------------------------
	
	
	$('#toggle_translit_id').mouseover(function(e){
	
		x = e.pageX + 5;
		y = e.pageY;
		
		if (x < 0){
			x = 3;
		}
		if (y < 0){
			y = 0;
		}
		
		if (x + 370 > $(document).width()) {
			x = $(document).width() - 370;
		}
		
		if (y + 176 > $(document).height()) {
			y = $(document).height() - 176;
		}
		
		x = x + 'px';
		y = y + 'px';
		
		
			
		$('#translit_hint').css({left:x,top:y,display:'',cursor:'pointer'});
		return false;
		
	});
	//-----------------------------------------------------------------------
	
	
	$('#translit_hint').mouseout(function(e){
	
		$('#translit_hint').hide();
	
	});

},
// convert BBcode to HTML code
_BBcodetoHTML : function (a)
{
    function r(re, str) {
            a = a.replace(re, str);
    };
    if (smiley_wysiwyg)   {
          a=Smiley_BBcodetoHTML(a);
    }
    a = a.replace(/\[fg=/gi, "[color=");
    a = a.replace(/\[\/fg\]/gi, "[/color]");
    a = a.replace(/\[a=/gi, "[url=");
    a = a.replace(/\[\/a\]/gi, "[/url]");
    a = a.replace(/\[wbr\]/gi, "<wbr>");


	r(/\n+(\[\/list\])/gi,'[/list]');
	r(/\[list\]\n+/gi,'[list]');
	r(/\[list=1\]\n+/gi,'[list=1]');
	r(/\[list=a\]\n+/gi,'[list=a]');
	r(/\n+\[\/tr\]/gi,'[/tr]');
	r(/\n+\[tr\]/gi,'[tr]');
	r(/\n+\[td\]/gi,'[td]');
	r(/\n+\[\/td\]/gi,'[/td]');
	r(/\n+\[\/table\]/gi,'[/table]');
	r(/\[\/table\]$/gi,"[/table]\n");
	r(/&/g,'&amp;');
	r(/<wbr>/gi,'');
	r(/<br[^>]*>/gi, "");  //mojo
	r(/</g,'&lt;');
	r(/>/g,'&gt;');
	r(/  /g,'&nbsp;&nbsp;');
	r(/\t/g,'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
	r(/\n/g,'<br>');
	r(/\[hr\]/gi,'<hr />');
	r(/\[\/hr]/gi,'');
	r(/\[table\]/gi,'<table style="width: 100%; padding: 0px;border:1px dotted gray;">');
	r(/\[\/table\]/gi,'</table>');
	r(/\[(\/|)tr\]/gi,'<$1tr>');
	r(/\[(\/|)td\]/gi,'<$1td style="font-size: 20px; display:table-cell;padding:1px;vertical-align:inherit;border:1px dotted #CCCCCC;">');
	r(/\[(\/|)indent\]/gi,'<$1blockquote>');
	r(/\[(sub|sup|strike|s|b|i|u|blockquote)\]/gi,'<$1>');
	r(/\[\/(sub|sup|strike|s|b|i|u|blockquote)\]/gi,'</$1>');
	r(/\[font=(.*?)\]/gi,'<font face="$1">');
	r(/\[color=(.*?)\]/gi,'<font color="$1">');
	r(/\[highlight=(.*?)\]/gi,'<span style="background-color:$1">');
	r(/\[\/highlight\]/gi,'</span>');
	r(/\[size=(.*?)\]/gi,'<font size="$1">');
	r(/\[\/(font|color|size)\]/gi,'</font>');
	r(/\[(center|left|right|justify)\]/gi,'<div align="$1">');
	r(/\[\/(center|left|right|justify)\]/gi,'</div>');
	r(/\[url=(.*?)\]/gi,'<a href="$1">');
	r(/\[url\](.*?)\[\/url\]/gi,'<a href="$1">$1[/url]');
	r(/\[\/url\]/gi,'</a>');
	r(/\[img\](.*?)\[\/img\]/gi,'<img src="$1">');
	var b=a.match(/\[(list|list=1|list=a)\]/gi);
	r(/\[list=1\]/gi,'<ol>');
	r(/\[list=a\]/gi,'<ol style="list-style-type: lower-alpha">');
	r(/\[list\]/gi,'<ul>');
	r(/\[\*\]/gi,'<li>');
	r(/<br[^>]*><li>/gi,'<li>');
	r(/<br[^>]*> <li>/gi,'<li>');
	r(/<br[^>]*><\/li>/gi,'</li>');
	r(/\[h([1-6])?\]/gi,"<h$1>");
	r(/\[\/h([1-6])?\]/gi,"</h$1>");
	if(b){for(var i=0;i<b.length;i++){if(b[i].toLowerCase()=="[list]"){r(/\[\/list\]/i,'</ul>');}else if(b[i].toLowerCase()=="[list=1]"||b[i].toLowerCase()=="[list=a]"){r(/\[\/list\]/i,'</ol>');}}}
	if(isOpera){r(/<\/table>/gi,'</tr></table>');r(/<\/tr>/gi,'</td></tr>');}
	if(isOpera||isIE){r(/<li>/gi,'</li><li>');r(/<\/(ol|ul)>/gi,'</li></$1>');}



	return a;
},

// erase white spaces from the text inside the editor
_erase : function (a)
{
	if(typeof a!="string")return a;
	var b=a;
	var c=b.substring(0,1);
	while(c==" ")
	{
		b=b.substring(1,b.length);
		c=b.substring(0,1)
	}
	c=b.substring(b.length-1,b.length);
	while(c==" ")
	{
		b=b.substring(0,b.length-1);
		c=b.substring(b.length-1,b.length)
	}
	while(b.indexOf("  ")!=-1)
	{
		b=b.substring(0,b.indexOf("  "))+b.substring(b.indexOf("  ")+1,b.length)
	}
	return b ;
},

// convert HTML to bb when submit bbcode
_HTMLtoBBcode : function (a) {
    function r(re, str) {
            a = a.replace(re, str);
    };
        if (isIE) {
            r(/<\/li>/gi, "");
            r(/<li>/gi, "[*]");
        }
        r(/<div><\/div>/gi, "");
        r(/<br[^>]*>/gi, "<br>");
        r(/[\n\r]/gi, " ");
        r(/<script>(.*?)<\/script>/gi, "");
        r(/<script.*?>(.*?)<\/script>/gi, "");
	// remove style tag with anything within
        r(/<style>(.*?)<\/style>/gi, "");
        r(/<style.*?>(.*?)<\/style>/gi, "");
	// remove tags <w:> of MS word
        r(/<w:.*?>(.*?)<\/w:.*?>/gi, "");
        r(/<(abbr|acronym|applet|area|base|basefont|bdo|bgSound|big|body|button|caption|center|cite|code|col|colGroup|comment|custom|dd|del|dfn|dir|dl|dt|embed|fieldSet|frame|frameSet|head|html|ins|isIndex|kbd|label|legend|link|listing|map|marquee|menu|meta|noBR|noFrames|noScript|optGroup|option|param|plainText|pre|q|rt|ruby|samp|small|tBody|tFoot|tHead|title|tt|wbr|xml|xmp|th|script|form|input|iframe|object|select|textarea)(.*?)>/gi, "");
        r(/<\/(abbr|acronym|applet|area|base|basefont|bdo|bgSound|big|body|button|caption|center|cite|code|col|colGroup|comment|custom|dd|del|dfn|dir|dl|dt|embed|fieldSet|frame|frameSet|head|html|ins|isIndex|kbd|label|legend|link|listing|map|marquee|menu|meta|noBR|noFrames|noScript|optGroup|option|param|plainText|pre|q|rt|ruby|samp|small|tBody|tFoot|tHead|title|tt|wbr|xml|xmp|th|script|form|iframe|object|select|textarea)(.*?)>/gi, "");
        r(/\xA0/gi, " ");
        r(/<br[^>]*><\/div>/gi, "</div>");
        r(/<br[^>]*>/gi, "\n");
        r(/<hr[^>]*>/gi, "[hr][/hr]");
        r(/<\/hr>/gi, "");
        r(/<(ul|ol)><\/li>/gi, "<$1>");
        r(/  /gi, " ");
        r(/<p([^>]*)>/gi, "<div$1>");
        r(/<\/p([^>]*)>/gi, "</div$1>\n");
        r(/\t/g, "     ");
        r(/\n /g, "\n");
        r(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi, "[url=$1]$2[/url]");
        //r(/<h([1-6])([^>]*)>/gi, "[h$1]");
        //r(/<\/h([1-6])([^>]*)>/gi, "[/h$1]");
        var b = a.split("<");
        var c = new Array;
        var e = 0;
        if (b.length > 1) {
            for (var i = 0; i < b.length; i++) {
                if (i > 0) {
                    b[i] = "<" + b[i];
                }
                var f = b[i];
                if (f.match(/<(div|span|font|strong|b|u|i|em|var|address|img|ol|ul|li|a|strike|s|sub|sup)( ([^>]{1,}.*?)){0,1}( {0,1}){0,1}>/i)) {
                    var g = RegExp.$1;
                    var h = RegExp.$3;

                    if (h.toLowerCase().indexOf("style=") != -1 && h.toLowerCase().indexOf("font-family:") != -1 && h.toLowerCase().indexOf("face=") != -1) {
                        h = h.replace(/face="(.*?)"/gi, "");
                    } else if (h.toLowerCase().indexOf("style=") != -1 &&  h.toLowerCase().indexOf("color:") != -1 && h.toLowerCase().indexOf("color=") != -1) {
                        h = h.replace(/color="(.*?)"/gi, "");
                    }
                    h = h.replace(/(color=|size=|face=|style=)/gi, "|$1");
                    h = h.replace(/('|")/g, "");
                    h = h.replace(/ \|/g, "|");
                    var j = h.split("|");
                    var k = new Array;
                    if (j != null) {
                        for (var z = 0; z < j.length; z++) {
                            var l = j[z].split("=");
                            k[l[0].toLowerCase()] = j[z].replace(l[0].toLowerCase() + "=", "");
                        }
                    }
                    var m = "";
                    var g = g.toLowerCase();
                    if (g == "strike" || g == "s") {
                        if (k['style']) {
                            m = "[s]" + this._process(g, k);
                        } else {
                            m = "[s]";
                        }
                    } else if (g == "sub") {
                        if (k['style']) {
                            m = "[sub]" + this._process(g, k);
                        } else {
                            m = "[sub]";
                        }
                        if (k['style']) {
                        } else if (g == "sup") {
                            m = "[sup]" + this._process(g, k);
                        } else {
                            m = "[sup]";
                        }
                    }else if(g=="blockquote"){
					if(k['style'])
						{
						m = '[blockquote]'+this._process(g,k);
					}
					else
						{
						m='[blockquote]';
					}
				} else if (g == "li") {
                        if (k['style']) {
                            m = "[*]" + this._process(g, k);
                        } else {
                            m = "[*]";
                        }
                    } else if (g == "strong" || g == "b") {
                        if (k['style']) {
                            if (k['style'].toLowerCase().indexOf("font-weight: bold") != -1 ||  k['style'].toLowerCase().indexOf("font-weight: 700") != -1) {
                                m = this._process(g, k);
                            } else {
                                m = "[b]" + this._process(g, k);
                            }
                        } else {
                            m = "[b]";
                        }
                    } else if (g == "em" ||
                        g == "i" || g == "var" || g == "address") {
                        if (k['style']) {
                            if (k['style'].toLowerCase().indexOf("font-style: italic") != -1) {
                                m = this._process(g, k);
                            } else {
                                m = "[i]" + this._process(g, k);
                            }
                        } else {
                            m = "[i]";
                        }
                    } else if (g == "u") {
                        if (k['style']) {
                            if (k['style'].toLowerCase().indexOf("text-decoration: underline") != -1) {
                                m = this._process(g, k);
                            } else {
                                m = "[u]" + this._process(g, k);
                            }
                        } else {
                            m = "[u]";
                        }

                    } else if (g == "font" || g == "h1" || g == "h2" || g == "h3" || g == "h4" || g == "h5" || g == "h6") {
                        if (j.length > 0) {
                            for (var r in k) {
                                if (r == "color") {
                                    m += "[color=" + k.color + "]";
                                } 
                            }
                        }
                    } else if (g == "div" || g == "span") {
                        if (k['style']) {
                            m = this._process(g, k);
                        } else if (k.align) {
                            m = "[" + k.align.toUpperCase() + "]";
                        } else {
                            m = "[ALMSAMIM]";
                        }
                    } else if (g == "img") {
                        if (isWebKit) {
                            f = f.replace(/<img(.*?)src="(.*?)">/gi, "[IMG]$2[/IMG]");

                        } else {
                            f.match(/<img(.*?)src="(.*?)"(.*?)>/gi);
                            var s = RegExp.$2;
                            s = s.replace("./", "");
                            if (s.toLowerCase().substr(0, 7) != "http://") {
                                var t = document.URL;
                                t = t.replace("http://", "");
                                var u = t.split("/");
                                var v = "http://";
                                for (var d = 0; d < u.length; d++) {
                                    if (d < u.length - 1) {
                                        v += u[d] + "/";
                                    }
                                }
                               f = f.replace(/\<img(.*?)src="(.*?)"(.*?)>/gi, "[IMG]" + s + "[/IMG]");
                            } else {
                                f = f.replace(/<img(.*?)src="http:\/\/(.*?)\/(.*?)"(.*?)>/gi, "[IMG]/$3[/IMG]");
                            }
                        }
                   
                    }
                    b[i] = f.replace(/(<([^>]+)>)/, m);
                    if (g != "img") {
                        c[e] = m;
                        e++;
                    }
                } else if (f.match(/<\/(div|span|font|strong|b|u|i|em|var|address|ol|ul|li|a|strike|s|sub|sup)>/i)) {
                    e--;
                    var w = c.pop();
                    if (w != null) {
                        var x = "";
                        var A = w;
                        A = A.replace(/=(.*?)\]/g, "]");
                        A = A.replace(/\]/g, "],");
                        A = A.replace(/\[(.*?)\]/g, "[/$1]");
                        var B = A.split(",");
                        B.reverse();
                        for (var y = 0; y < B.length; y++) {
                            x += B[y];
                        }
                        x = x.replace(/\[\/\*\]/gi, "");
                        b[i] = b[i].replace(/(<([^>]+)>)/, x);
                    } else {
                        b[i] = b[i].replace(/(<([^>]+)>)/, "");
                    }
                }
            }
            var C = b.join("");
        } else {
            var C = a;
        }
		function r2(re, str) {
	            C = C.replace(re, str);
	    };
        r2(/<[^>]*>/g, "");
        r2(/&lt;/g, "<");
        r2(/&gt;/g, ">");
        r2(/&nbsp;/g, " ");
        r2(/&amp;/g, "&");
        r2(/     /g, "\t");
        r2(/\[ALMSAMIM\]/g, "\n");
        r2(/\[ALMSAMIM\]\n+/g, "\n");
        r2(/\[\/ALMSAMIM\]\n+/g, "\n");
        r2(/\[\/ALMSAMIM\]/g, "\n");
        r2(/\[\*\]/gi, "\n[*]");
        r2(/\n\n\[\*\]/gi, "\n[*]");
        r2(/\[color=#.\w*\]\[\/color\]/gi, "");
		r2(/\[HIGHLIGHT=#.\w*\]\[\/HIGHLIGHT\]/gi,"");
        r2(/\[size=\d\]\[\/size\]/gi, "");
        r2(/\[b\]\[\/b\]/gi, "");
        r2(/\[u\]\[\/u\]/gi, "");
        r2(/\[i\]\[\/i\]/gi, "");
        r2(/\[left\]\[\/left\]/gi, "");
        r2(/\[center\]\[\/center\]/gi, "");
        r2(/\[right\]\[\/right\]/gi, "");
        r2(/\[justify\]\[\/justify\]/gi, "");
        r2(/\[blockquote\]\[\/blockquote\]/gi, "");
        r2(/\[url\]\[\/url\]/gi, "");
        r2(/\[s\]\[\/s\]/gi, "");
        r2(/\[sub\]\[\/sub\]/gi, "");
        r2(/\[sup\]\[\/sup\]/gi, "");
        r2(/\[img\]\[\/img\]/gi, "");
        r2(/^\n+/, "");
        r2(/\n+$/, "");

	if (smiley_wysiwyg){
             C=Smiley_HTMLtoBBcode(C);
        }
        C = C.replace(/\[color=/gi, "[fg=");
	C = C.replace(/\[\/color\]/gi, "[/fg]");
	C = C.replace(/\[url=/gi, "[a=");
	C = C.replace(/\[\/url\]/gi, "[/a]");
	C = convert_smiles(C);
	
        return C;
},

// processing HTML code to BBcode
_process : function (a, b) {
	var c="";
	var d=b['style'].split(";");
	for(var j=0;j<d.length;j++){
		if(d[j]!=""&&d[j]!=null){
			var e=d[j].split(":");
			var f=e[0].toLowerCase().replace(/ /g,"");
			f=f.replace(/style=/gi,"");
			try{
			    var g = e[1].replace(/^ +| +$/g,"");
			}catch(err){
			    var g = '';
			}
			if (f=="background-color"){
				if(g.indexOf("#")==-1){
					var h=this._toHex(g);
				} else {
					var h=g ;
				}
//				c+='[highlight='+h+']';
			}
			else if (f == "vertical-align" && g == "sub") {
//                    c += "[sub]";
                } else if (f == "vertical-align" && g == "super") {
//                  c += "[sup]";
                } else if (f == "list-style-type" && g == "lower-alpha") {
//                    c += "[list=a]";
                } else if (f == "text-align") {
                    g = g.toUpperCase();
                    c += "[" + g + "]";
                } else if(f=="margin-left"||f=="margin-right"){
				g=parseInt(g)/40;
				for(var z=0;z<g;z++)
					{
//					c+='[blockquote]';
					}
			}else if (f == "font-weight") {
                    if (g.toUpperCase() == "BOLD" || g.toUpperCase() == "700") {
                        c += "[b]";
                    }
                } else if (f == "font-style") {
                    if (g.toUpperCase() == "ITALIC") {
                        c += "[i]";
                    }

                } else if (f == "text-decoration") {
                    if (g.toUpperCase() == "UNDERLINE") {
                        c += "[u]";
                    } else if (g.toUpperCase() == "LINE-THROUGH") {
//                        c += "[s]";
                    }
                } else if (f == "color") {
					g=g.replace(/^ +| +$/g,"");
                    if (g.indexOf("#") == -1) {
					if (g.match(/rgb\((.*?)\)/gi)){
					var h = this._toHex(g);
					}else{
                       var h = g; }
					   } else {
                        var h = g;
                    }
                    c += "[color=" + h + "]";
                }
            }
        }
        return c;
},
//converting rgb(..) to Hex
_toHex : function (a)
	{
	a=a.replace(/rgb\((.*?)\)/gi,"$1");
	a=a.replace(/ /,"");
	var c=a.split(",");
	var r=parseInt(c[0]).toString(16);
	var g=parseInt(c[1]).toString(16);
	var b=parseInt(c[2]).toString(16);
	if(r.length==1)r="0"+r;
	if(g.length==1)g="0"+g;
	if(b.length==1)b="0"+b;
	return"#"+r+g+b
}
};

// ----------- almsamim command object -----------//
almsamim.comm = comm = {
_viewmode : 1 ,
_focus : function ()
{
var editor = document.getElementById('box');
editor.contentWindow.focus();
},
// the execCommand function
_command : function (command){
	if (this._viewmode == 1){
		this._focus();
		document.getElementById('box').contentWindow.document.queryCommandEnabled(command);
		document.getElementById('box').contentWindow.document.execCommand(command, false, null);
		this._focus();
	}else {
		if (command == 'bold'){
			bbfontstyle('[b]','[/b]');
		}else if (command == 'italic'){
			bbfontstyle('[i]','[/i]');
		}else if (command == 'underline'){
			bbfontstyle('[u]','[/u]');
		}
	}
},

// create URL of selection through prompt
_url : function (prompturl)
{
	if (this._viewmode == 1){

		if (prompturl == 1){

			var szURL = prompt(lang_s[12], "http://");
			var tURL = prompt(lang_s[8], "");
			if(tURL){
			this._HTML(' ',' ','<a href ="'+ szURL +'">'+ tURL +'</a>');
			}
		}else{

			var szURL = prompt(lang_s[12], "http://");
			if ((szURL != null) && (szURL != "")) {
				var Editor = document.getElementById('box').contentWindow.document;
				this._focus();
				Editor.queryCommandEnabled("CreateLink");
				szURL = szURL.replace(/(^\s+)|(\s+$)/g, "");
				Editor.execCommand("CreateLink", false,szURL);
				this._focus();
			  }
		}

	}
},

//alternative to insertHTML with all browsers to insert bbcode OR html
_HTML : function (tag,tagend,a)
	{
	this._focus();
	if (this._viewmode == 1){
	var c;
	var u="";
	var d;
	tagend = tagend.replace("=","");
	if(document.all) {
		d=document.getElementById('box').contentWindow;
		d.focus();
		var f=d.document.selection;
		if(f!=null)
			{
			rng=f.createRange();
			u=rng.htmlText;
		}
	} else if (window.getSelection) {
		d=document.getElementById('box').contentWindow;
		d.focus();
		var f=d.getSelection();
		if(f!=""&&f.rangeCount>0)
			{
			rng=f.getRangeAt(f.rangeCount-1).cloneContents();
			var g=d.document.createElement('div');
			g.appendChild(rng);
			u=g.innerHTML;
		}
	}
	if(a){
	var cc = tag+a+tagend;
	}else if(u){
		if(tag=="[code]"||tag=="[code=php]")
		{
				u=u.replace(/[\n\r]/ig,'');
				u=u.replace(/<(br|p|div|li).*?>/ig,"[BR/]");
				u=u.replace(/<\/(p|div).*?>/ig,"");
				u=u.replace(/(<([^>]+)>)/ig,"");
				u=u.replace(/\[BR\/\]/ig,"<br>");
				var cc = tag+u+tagend;
		}else{
				var cc = tag+u+tagend;
		}
	}else {
		if(tag=="[code]"||tag=="[code=php]"||tag=="[quote]"){
			var cc = tag+tagend;
		}else if(tag =="[video]"){
		var q=prompt("","");
		if(q!=""&&q!=null){
		var cc = tag+q+tagend;
		}else{
		var cc = '';
		}
		}else{
			var cc = tag+tagend;
			}
	}
	if(isIE)
	{
		d=document.getElementById('box').contentWindow;
		d.document.execCommand("removeformat",false,"");
		d.focus();
		rng.pasteHTML(cc);
		d.focus();
	}
	else if(isWebKit)
		{
		c=document.getElementById('box').contentWindow;
		c.focus();
		u=u.replace(/</g,"[OPEN]");
		u=u.replace(/>/g,"[CLOSE]");
		c.document.execCommand('insertHTML',false,cc);
		var e=document.getElementById('box').contentWindow.document.body.innerHTML;
		u=u.replace(/\[OPEN\]/g,'<');
		u=u.replace(/\[CLOSE\]/g,'>');
		u=u.replace(/[\n\r]/ig,'');
		document.getElementById('box').contentWindow.document.body.innerHTML=e;
		c.focus();
	}
	else
		{
		if(cc!=""&&cc!=null){
		c=document.getElementById('box').contentWindow;
		c.focus();
		c.document.execCommand("removeformat",false,"");
		c.document.execCommand('insertHTML',false,cc);
		c.document.execCommand("removeformat",false,"");
		c.focus();
		}
	}
	  	  }else {
		  if(a){
				bbfontstyle(tag + bbcode._HTMLtoBBcode(a),tagend);
}else{
				bbfontstyle(tag ,tagend);
}
}
},

_set : function (s) {
	var Editor = document.getElementById('box').contentWindow.document;
	if (!isGecko)
		return;
	try {
		// Try new Gecko method
		Editor.execCommand("styleWithCSS", 0, s);
		} catch (ex) {
		// Use old
		Editor.execCommand("useCSS", 0, !s);
		}
},
//colour EXECCOMMAND
_colour : function (colour,type) {

	if (this._viewmode == 1){
	    if(isIE && type=="hilitecolor"|| isWebKit && type=="hilitecolor")type="backcolor";
	    var Editor = document.getElementById('box').contentWindow.document;
	    this._focus();
	    if (isGecko || isOpera && type=="hilitecolor") {
		    this._set(true);
	    }
	    Editor.queryCommandEnabled(type);
	    Editor.execCommand(type, false, colour);
	    if (isGecko || isOpera && type=="hilitecolor") {
		this._set(false);
	    }
	    this._focus();
	}else {
	    if(type == "hilitecolor"){
		bbfontstyle('[highlight=' + colour +']','[/highlight]');
	    }else{
		bbfontstyle('[color=' + colour +']','[/color]');
	    }
	}
    }
};


// gettext into textarea html or bbcode
function Gettext(value,bb) {

  	 var text = document.getElementById(value);
	 if (comm._viewmode == 2){
		 var source = document.getElementById('box_text');
		 source.value = source.value.replace(/\$/g, "&39;");
		 text.value = source.value;
		 comm._viewmode = 1; // WYSIWYG
	 }else {
		 Editor = document.getElementById('box').contentWindow.document;
		 var ceditor = bbcode._HTMLtoBBcode(bbcode._erase(Editor.body.innerHTML));
		 ceditor = ceditor.replace(/\$/g, "&39;");
		 text.value = ceditor;
	 }
};


function hideall(){
	$('#translit_hint').hide();
};
//visibility of the color pallette
function toggle_visibility(id,id2)
{
       var e = document.getElementById(id);
       var buttonElement = document.getElementById(id2);
		e.style.left = getOffsetLeft(buttonElement) + 'px';
		e.style.top = (getOffsetTop(buttonElement) + buttonElement.offsetHeight) + 'px';
       if(e.style.display = ''){
		 hideall();
         e.style.display = 'none';
		 }
       else{
	     hideall();
          e.style.display = '';
		  }
};
// adding quote in topic revision
function addquote(post_id, username){
	var message_name = 'message_' + post_id;
	divarea = document.getElementById(message_name).innerHTML;
	comm._HTML('[quote="' + username + '"]','[/quote]',divarea);
};

// add smiley through path as image
function AddSmileyIcon(imagePath, theme){
	// removing dot from URL
	if (comm._viewmode == 1){
		imagePath = imagePath.replace(/.\/images\/smilies/gi,"/images/smilies");
		comm._focus();
		comm._HTML(' ',' ',' <img src="'+ imagePath +'" />');
		comm._focus();
		}else{
		bbfontstyle(' ' + theme,' ');
	}

	document.getElementById('smile_popup_width').style.display = 'none';
};

//Function to hover button icon
function overIcon(iconItem){
	iconItem.className='oover';
};
//Function to moving off button icon
function outIcon(iconItem){
	iconItem.className='button';
};


/**
* Caret Position object
*/
function caretPosition()
{
	var start = null;
	var end = null;
};


/**
* Get the caret position in an textarea
*/
function getCaretPosition(txtarea)
{
	var caretPos = new caretPosition();

	// simple Gecko/Opera way
	if(txtarea.selectionStart || txtarea.selectionStart == 0)
	{
		caretPos.start = txtarea.selectionStart;
		caretPos.end = txtarea.selectionEnd;
	}
	// dirty and slow IE way
	else if(document.selection)
	{

		// get current selection
		var range = document.selection.createRange();

		// a new selection of the whole textarea
		var range_all = document.body.createTextRange();
		range_all.moveToElementText(txtarea);

		// calculate selection start point by moving beginning of range_all to beginning of range
		var sel_start;
		for (sel_start = 0; range_all.compareEndPoints('StartToStart', range) < 0; sel_start++)
		{
			range_all.moveStart('character', 1);
		}

		txtarea.sel_start = sel_start;

		// we ignore the end value for IE, this is already dirty enough and we don't need it
		caretPos.start = txtarea.sel_start;
		caretPos.end = txtarea.sel_start;
	}

	return caretPos;
};

/**
* Apply bbcodes
*/
function bbfontstyle(bbopen, bbclose)
{
	theSelection = false;

	var textarea = document.getElementById('box_text');

	textarea.focus();

  if (isIE)
   {
      // Get text selection
      theSelection = document.selection.createRange().text;
      var sel = document.selection.createRange();

      if (theSelection)
      {
         // Add tags around selection
         document.selection.createRange().text = bbopen + theSelection + bbclose;
         textarea.focus();
         sel.moveStart('character', bbopen.length);
         sel.moveEnd('character', theSelection.length);
         sel.select();
         theSelection = '';
         return;
      }
   }
	else if (textarea.selectionEnd && (textarea.selectionEnd - textarea.selectionStart > 0))
	{
		mozWrap(textarea, bbopen, bbclose);
		textarea.focus();
		theSelection = '';
		return;
	}

	//The new position for the cursor after adding the bbcode
	var caret_pos = getCaretPosition(textarea).start;
	var new_pos = caret_pos + bbopen.length;

	// Open tag
	insert_text(bbopen + bbclose);

	// Center the cursor when we don't have a selection
	// Gecko and proper browsers
	if (!isNaN(textarea.selectionStart))
	{
		textarea.selectionStart = new_pos;
		textarea.selectionEnd = new_pos;
	}
	// IE
	else if (document.selection)
	{
		var range = textarea.createTextRange();
		range.move("character", new_pos);
		range.select();
		storeCaret(textarea);
	}

	textarea.focus();
	return;
};
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	var scrollTop = txtarea.scrollTop;

	if (selEnd == 1 || selEnd == 2)
	{
		selEnd = selLength;
	}

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd);
	var s3 = (txtarea.value).substring(selEnd, selLength);

	txtarea.value = s1 + open + s2 + close + s3;
	txtarea.selectionStart = selStart + open.length;
	txtarea.selectionEnd = selEnd + open.length;
	txtarea.focus();
	txtarea.scrollTop = scrollTop;

	return;
};
function insert_text(text, spaces, popup)
{
	var textarea;

	if (!popup)
	{
		textarea = document.getElementById('box_text');
	}
	else
	{
		textarea = opener.document.getElementById('box_text');
	}
	if (spaces)
	{
		text = ' ' + text + ' ';
	}

	if (!isNaN(textarea.selectionStart))
	{
		var sel_start = textarea.selectionStart;
		var sel_end = textarea.selectionEnd;

		mozWrap(textarea, text, '');
		textarea.selectionStart = sel_start + text.length;
		textarea.selectionEnd = sel_end + text.length;
	}
	else if (textarea.createTextRange && textarea.caretPos)
	{
			textarea.focus();
			storeCaret(textarea);

		var caret_pos = textarea.caretPos;
		caret_pos.text = caret_pos.text.charAt(caret_pos.text.length - 1) == ' ' ? caret_pos.text + text + ' ' : caret_pos.text + text;
	}
	else
	{
		textarea.value = textarea.value + text;
	}
	if (!popup)
	{
		textarea.focus();
	}
};

function storeCaret(textEl)
{
	if (textEl.createTextRange)
	{
		textEl.caretPos = document.selection.createRange().duplicate();
	}
};
//Iframe top offset
function getOffsetTop(elm){
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	while(mOffsetParent){
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	return mOffsetTop;
};

//Iframe left offset
function getOffsetLeft(elm){
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	while(mOffsetParent){
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	return mOffsetLeft;
};
//Run Editor Events
function editorEvents(evt){
	var keyCode = evt.keyCode ? evt.keyCode : evt.charCode;
	var keyCodeChar = String.fromCharCode(keyCode).toLowerCase();

	if (evt.type=='keypress' && evt.ctrlKey && (keyCode==10 || keyCode==13)){
		if (document.getElementById("chat") != null) {
			setTimeout('send_message1();', 10);
		} else {
			setTimeout('send_message("");', 10);
		}
		return false;
	}

	if(isIE){
	//run if enter key is pressed

		if (evt.type=='keypress' && keyCode==13){
			var editor = document.getElementById('box');
			var selectedRange = editor.contentWindow.document.selection.createRange();
			var parentElement = selectedRange.parentElement();
			var tagName = parentElement.tagName;

			while((/^(a|abbr|acronym|b|bdo|big|cite|code|dfn|em|font|i|kbd|label|q|s|samp|select|small|span|strike|strong|sub|sup|textarea|tt|u|var)$/i.test(tagName)) && (tagName!='HTML')){
				parentElement = parentElement.parentElement;
				tagName = parentElement.tagName;
			}

			//Insert <div> instead of <p>
			if (parentElement.tagName == 'P'||parentElement.tagName=='BODY'||parentElement.tagName=='HTML'||parentElement.tagName=='TD'||parentElement.tagName=='THEAD'||parentElement.tagName=='TFOOT'){
				selectedRange.pasteHTML('<div>');
				selectedRange.select();
				return false;
			}
		}

		return true;

	} else {
  		//Keyboard shortcuts
  		if (evt.type=='keypress' && evt.ctrlKey){
  			var kbShortcut;
  			switch (keyCodeChar){
				case 'b': kbShortcut = 'bold'; break;
				case 'i': kbShortcut = 'italic'; break;
				case 'u': kbShortcut = 'underline'; break;
				case 's': kbShortcut = 'strikethrough'; break;
			}
			if (kbShortcut){
				comm._focus();
				document.getElementById('box').contentWindow.document.queryCommandEnabled(kbShortcut);
				document.getElementById('box').contentWindow.document.execCommand(kbShortcut, false, null);
				comm._focus();
				evt.preventDefault();
				evt.stopPropagation();
			}
		}

		return true;
	}
};


var ed_locale = new Object();
ed_locale.add_link = {'ru' : 'Добавить ссылку', 'lv' : 'Pielikt URL'};
ed_locale.block = {'ru' : 'Блокировать', 'lv' : 'Bloķēt'};
ed_locale.trns_ruls = {'ru' : 'Правила транслитерации:', 'lv' : 'Transliterācijas noteikumi:'};
ed_locale.sel_color = {'ru' : 'Выберите цвет шрифта сообщения', 'lv' : 'Teksta krāsa'};
ed_locale.spositive = {'ru' : 'Позитивные', 'lv' : 'Pozitīvie'};
ed_locale.slove = {'ru' : 'Любовь', 'lv' : 'Mīlestība'};
ed_locale.snegative = {'ru' : 'Негативные', 'lv' : 'Negatīvie'};
ed_locale.sdifferent = {'ru' : 'Разные', 'lv' : 'Dažādi'};
ed_locale.snew = {'ru' : 'Новые', 'lv' : 'Jaunas'};
ed_locale.smore = {'ru' : 'Еще', 'lv' : 'Vēl'};
ed_locale.url_txt = {'ru' : 'Введите текст URL:', 'lv' : 'Ievadiet tekstu:'};
ed_locale.url = {'ru' : 'Введите URL:', 'lv' : 'Ievadiet URL:'};
ed_locale.trns_on = {'ru' : 'Транслитератор включён', 'lv' : 'Transliterators ir ieslēgts'};
ed_locale.trns_off = {'ru' : 'Транслитератор отключён', 'lv' : 'Transliterators ir izslēgts'};
ed_locale.custom_sm = {'ru' : 'Заменить смайлики', 'lv' : 'Mainīt smaidiņus'};

function push_smiles(smiles_array, from, to){
	for (i = from; i < to; i++){
		smiles_array.push(i);
	}
	
	return smiles_array;
}

function default_smiles(){
	var smiles_array = new Array();
	smiles_array = push_smiles(smiles_array, 28, 44);
	smiles_array = push_smiles(smiles_array, 57, 72);
	smiles_array = push_smiles(smiles_array, 73, 91);
	smiles_array = push_smiles(smiles_array, 100, 109);
	
	return smiles_array;
}

function more_smiles_new(){
	if (allow_custom_smiles == 1){
		var custom_smiles = cookie_read('__usm');

		if (custom_smiles != null){
			var smiles_array = custom_smiles.split('.');
		} else {
			var smiles_array = default_smiles();
		}
	} else {
		var smiles_array = default_smiles();
	}
	
	var len=smiles_array.length;
	html = '';
	
	if (allow_custom_smiles == 1){
		html += '<div style="clear:both;padding:5px"><a href="#" class="global_a"><span  class="customize_smiles link">' + ed_locale.custom_sm[lang] + '</span> »</a></div>';
	} else {
		html += '<div style="clear:both;padding:5px"><a href="#" onclick="window_open(\'/window/extras/extra/7.html\', 508, 600, \'extra\'); return false;"><span  class="link">' + ed_locale.custom_sm[lang] + '</span> »</a></div>';
	}
	
	for (i = 0; i < len; i++){
		html += ' <table cellspacing="0" cellpadding="0" style="width:76px;height:46px;float:left;border:1px solid;margin:2px;cursor:pointer" class="border_color1" onclick="AddSmileyIcon(\'/images/smile/' + smiles_array[i] + '.gif\',\'' + smiles_array[i] + '\'); return false;"><tr><td align="center"><img src="/images/smile/' + smiles_array[i] + '.gif" alt="" title="" vspace="1" /><\/td><\/tr><\/table>';
	}
	
	if (allow_custom_smiles == 1){
		html += '<div style="clear:both;padding:5px"><a href="#" class="customize_smiles global_a"><span  class="link">' + ed_locale.custom_sm[lang] + '</span> »</a></div>';
	} else {
		html += '<div style="clear:both;padding:5px"><a href="#" onclick="window_open(\'/window/extras/extra/7.html\', 508, 600, \'extra\'); return false;"><span  class="link">' + ed_locale.custom_sm[lang] + '</span> »</a></div>';
	}
	
	return html;
}


function toggle_translit(obj){
	text_obj = document.getElementById('toggle_translit_text');
				
	if (translit){
		cookie_delete('translit');
		obj.src = "/skin/all/wys/inf_chat_translit_off.gif";
		obj.alt = ed_locale.trns_off[lang];	
		obj.title = ed_locale.trns_off[lang];	
	}else{
		obj.src = "/skin/all/wys/inf_chat_translit_on.gif";
		obj.alt = ed_locale.trns_on[lang];	
		obj.title = ed_locale.trns_on[lang];	
		cookie_create('translit', 1);
	}
	translit = !translit;
	$('#box').get(0).contentWindow.focus();

}


/*
*
*/
(function($){

	var css = '<style type="text/css">' +
	'#colors_fg,' +
	'#colors_bg{' +
		'position: absolute;' +
		'background-color: #fff' +
	'}' +
	'.c_color{' +
		'float:left;' +
		'margin:3px;' +
		'border:1px solid #ccc' +
	'}' +
	'.c_color img{' +
		'width: 22px;' +
		'height: 14px;' +
		'border: 1px solid #fff' +
	'}' +
	'.smiles_popup{' +
		'position:absolute;' +
		'background-color: #fff;' +
	'}' +
	'.smiles td{' +
		'border-bottom:1px solid #e6e6e6' +
	'}' +
	'.smiles_popup .head{' +
		'color:#0B5D9C;' +
		'height:23px;' +
		'padding-left:7px' +
	'}' +
	'div.colors-tbl{' +
		'width:205px;' +
		'height:50px;' +
	'}' +
	'#translit_hint{' +
		'position:absolute;' +
		'z-index: 99;' +
	'}' +
	'</style>';


	/*
	* Редактор
	*/
	$.fn.editor = function(options){

		/* значения по умолчанию */
		$.fn.editor_options = options = $.extend({
				buttons: true,
				smilies: true,
				width: '99%',
				height: 253,
				post_url: document.location + '?',
				onresult: null,
				onpost: null,
				callback: false,
				empty_msg: false,
				blocking: false,
				url_btn: true,
				unbind_btn: false,
				editor_msg: ''
			  }, options);

		
		
		if (cookie_read('translit') != null){
			translit = true;
		}else{
			translit = false;
		}
		
		if (translit){
			btn_src = '/skin/all/wys/inf_chat_translit_on.gif';
			btn_title = ed_locale.trns_on[lang];	
		}else{
			btn_src = '/skin/all/wys/inf_chat_translit_off.gif';
			btn_title = ed_locale.trns_off[lang];
		}

		var html = '<div id="message-box">' +
				'<table id="buttons_panel" style="display: ' + (options.buttons ? '' : 'none') + '">' +
					'<tr>' +
						'<td><img src="/skin/all/wys/inf_chat_b.gif" alt="Bold" title="Bold" onclick="comm._command(\'bold\');" onmouseover="this.style.cursor = \'pointer\';"></td>' +
						'<td style="padding-left: 3px;"><img src="/skin/all/wys/inf_chat_i.gif" alt="Italic" title="Italic" onclick="comm._command(\'italic\');" onmouseover="this.style.cursor = \'pointer\';"></td>' +
						'<td style="padding-left: 3px;"><img src="/skin/all/wys/inf_chat_u.gif" alt="Underline" title="Underline" onclick="comm._command(\'underline\');" onmouseover="this.style.cursor = \'pointer\';"></td>' +
						'<td style="padding-left: 10px"><img src="/skin/all/wys/inf_chat_fg.gif" id="colors_btn" alt="ForeColor" title="ForeColor"  onmouseover="this.style.cursor = \'pointer\'; return false;"><br /></td>' +
						'<td style="padding-left: 3px;display: ' + (options.url_btn ? '' : 'none') + '"><img src="/skin/all/wys/inf_chat_url.gif" alt="' + ed_locale.add_link[lang] + '" title="' + ed_locale.add_link[lang] + '" onclick="comm._url(0);" onmouseover="this.style.cursor = \'pointer\';"></td>' +
						'<td style="padding-left: 10px;"><img src="' + btn_src + '" alt="' + btn_title + '" title="' + btn_title + '" onclick="toggle_translit(this); return false;" id="toggle_translit_id"></td>' +
						'<td style="text-align:right;width:100%;display: ' + (options.blocking ? '' : 'none') + '"><a href="#" onclick="window_open(\'/window/messages/block_id/\'+ active_user + \'.html\', 422, 286, \'block\'); return false;" class="color1">' + ed_locale.block[lang] + '</a></td>' +
					'</tr>' +
				'</table>' +
				'<iframe id="box" frameborder="0" scrolling="auto" style="padding:0px; background-color: #fff; border:1px solid #a9b8c2; width: ' + options.width + '; height: ' + options.height + 'px;"></iframe>' +
				'<textarea  id="box_text" style="display: none; width: 100%; height: 249px; background: #fff;" cols="60" rows="10" class="inputbox" tabindex="3" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);"></textarea>' +
				'<textarea  name="msg_editor_h" id="msg_editor_h" rows="15" cols="76" tabindex="3" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" class="inputbox" style="display: none;">'+ options.editor_msg + '</textarea>' +
			'</div>';

		var pop_divs = '<div id="translit_hint" style="display: none;">' +
					'<div class="java_menu">' +
						'<div class="head">' + ed_locale.trns_ruls[lang] + '</div>' +
						'<div class="j_menu" align="center"><img src="/skin/all/translate_rules.gif" alt="" /><br /></div>' +
					'</div>' +
				'</div>' +
				'<div style="display:none;position:absolute;z-index:99;" id="colors_fg">' +
					'<div class="java_menu">' +
						'<div class="close"><img src="/skin/all/close.gif" id="col_close" ></div>' +
						'<div class="head">' + ed_locale.sel_color[lang] + ':</div>' +
						'<div class="j_menu">' +
							'<div class="colors-tbl">';

		var colors = new Array('000000', '808080', 'ff0000', '000080', '8000ff', '00a300');
		for (i in colors){
			pop_divs += '<div class="c_color" style="background-color: #' + colors[i] + '">' +
					'<a href="#" onclick="comm._colour(\'#' + colors[i] + "','forecolor'); hideFgColors('colors_fg'); return false\"><img src=\"/skin/_.gif\" /><br /></a>" +
				'</div>';
		}

				pop_divs +='</div>' +
				'</div>' +
			'</div>' +
		'</div>' +
		'<div style="float:left;display: none; z-index: 99;" id="smile_popup_width" class="smiles_popup">' +
			'<div class="close" align="right"><img src="/skin/all/close.gif" id="bclose_smiles"  alt="" /></div>' +
			'<table cellspacing="0" cellpadding="0" style="width:505px;border:1px solid #DDDDDD">' +
				'<tr>' +
					'<td>' +
						'<table cellspacing="0" cellpadding="0" width="100%"><tr><td>' +
						'<div style="overflow:auto;max-height:370px;">'+
							more_smiles_new() + 
						'</div>'+
						'</td></tr></table>' +
					'</td>' +
				'</tr>' +
			'</table>' +
		'</div>';



		$(this).each(function(){

			var smile_html = '<div style="width:100%; text-align: left; margin: 5px 0 5px 0; display:' + (options.smilies ? '' : 'none') + '">';

			for (i = 1; i < 28; i++){

				if (i == 27){
					smile_html += '&nbsp;<a id="more_smiles" href="#" class="global_a"><span  class="link">' + ed_locale.smore[lang] + '</span> »</a>';
					break;
				}
				if (i < 10){
					i = '0' + i;
				}

				smile_html += '<wbr><img style="float:left" src="/images/smile/' + i + '.gif" vspace="1" hspace="1" onmouseover="this.style.cursor = \'pointer\';" onclick="AddSmileyIcon(\'/images/smile/' + i + '.gif\', \'' + i + '\'); return false;">';
			}

			$(this).html(css + html + smile_html + '</div>');

			$('#box').get(0).contentWindow.focus();
			$('#editor_popups').html(pop_divs);

			lang_s[8] =  ed_locale.url_txt[lang];
			lang_s[12] = ed_locale.url[lang];
			bbcode.Start();
		});
	};
	//----------------------------------------------------------------------
	
	

})(jQuery);

