(function()
{
    var UA = navigator.userAgent;
    is_gecko = /gecko/i.test(UA);
    is_opera = /opera/i.test(UA);
    is_mac = /mac_powerpc/i.test(UA);
    is_ie = /msie/i.test(UA) && !is_opera && !is_gecko && !is_mac;
    is_ie5 = is_ie && /msie 5\.[^5]/i.test(UA);
    is_nn4 = document.layers ? true : false;
})();

function Community()
{
}

Community.i18n = function(text, arg1, arg2)
{
    if (typeof Community.I18N != "undefined" && typeof Community.I18N[text] != "undefined")
        text = Community.I18N[text];

    if (arg1)
    {
        text = text.replace(/(\(1\))/g, arg1);

        if (arg2)
            text = text.replace(/(\(2\))/g, arg2);
    }

    return text;
};


Community.CE = function(type, parent, props, style)
{
    var el = null,i;

    if (document.createElementNS)
        el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
    else
        el = document.createElement(type);

    if (parent)
        parent.appendChild(el);

    if (props)
        for (i in props)
            el[i] = props[i];

    if (style)
        for (i in style)
            el.style[i] = style[i];

    return el;
};
function Messages()
{
}

var smilesPath = 'http://medproff.ru/img/smiles/';
var editor = null;

Messages.initEditor=function(formId, textareaId, counterId, limit)
{
    if (!textareaId)
        return;

    editor = new HTMLArea(textareaId);

    editor.registerPlugin("SelectColor","s");
    if (counterId)
        editor.registerPlugin("LengthControl", formId, document.getElementById(counterId), limit);

    var cfg = editor.config;

	cfg.fontsize = {
		"8 pt":  "1",
		"10 pt": "2",
		"12 pt": "3",
		"14 pt": "4"
	};

    cfg.registerButton({
      id        : "my_forecolor",
      tooltip   : HTMLArea.I18N.tooltips.forecolor,
      image     : "http://medproff.ru/js/img/t_color.gif",
      textMode  : false,
      action    : function(editor, id) {
                    editor.plugins["SelectColor"].instance.showDiv("forecolor");
                  }
    });

    cfg.registerButton({
      id        : "my_hilitecolor",
      tooltip   : HTMLArea.I18N.tooltips.hilitecolor,
      image     : "http://medproff.ru/js/img/b_color.gif",
      textMode  : false,
      action    : function(editor, id) {
                    editor.plugins["SelectColor"].instance.showDiv((HTMLArea.is_ie) ? "backcolor" : "hilitecolor");
                  }
    });

    cfg.toolbar = [
        ['fontname', 'space',
         'fontsize', 'space',
		 'cut', 'copy', 'paste'
         ],

        [ 'bold', 'italic', 'underline', 'strikethrough', 'separator',
          'my_forecolor', 'my_hilitecolor', 'separator', 'createlink', 'separator', 
          //'insertorderedlist', 'insertunorderedlist', 'separator',
          'justifyleft', 'justifycenter', 'justifyright', 'separator',
  		  'undo', 'redo'
        ]
    ];




    if (is_ie)
        cfg.pageStyle = 'body { border: 1px solid #9F9F9F; font: 12px Arial,Tahoma,Helvetica,sans-serif; line-height: normal;} p { margin: 0px;}';
    else
        cfg.pageStyle = 'body { font: 12px Arial,Tahoma,Helvetica,sans-serif;}';

    cfg.statusBar=false;
    editor._customUndo=true;

    editor.onGenerate = function() {
      with (editor) {
        var d = HTMLArea.is_ie ? _doc.body : _doc;
        HTMLArea._addEvents(
          d,
          ["paste", "dragdrop", "drop"],
          function (e) {
            var e;
            if (HTMLArea.is_ie)
              e = self.editor._iframe.contentWindow.event;
            else
              e = event;

            if (e.type == "paste") {
              var text = window.clipboardData.getData("Text");
              if (!text)
                  return false;
              window.clipboardData.setData("Text", text);
              return true;
            } else {
              var text = e.dataTransfer.getData("Text");
              if (text)
                _createRange(_getSelection()).text = text;
              return false;
            }
          });
      }
    };

    editor.generate();

    editor._toolbarObjects["fontsize"].element.childNodes[1].selected="selected";
    editor.focusEditor();
    return false;
}


Messages.changeTextArea=function(form,ev,limit)
{
    ev||(ev=window.event);
    if(ev && ev.keyCode == 13 && (ev.altKey || ev.ctrlKey))
    {
      form.submit();
      return false;
    }

    var msg = form.msg;
    if (msg.value.length > limit)
      msg.value = msg.value.substring(0,limit);

    document.getElementById("fm_len").innerHTML = limit - msg.value.length;
    return false;
}

// ----------------------
// SMILES FUNCTIONALITY

Messages.changeSmiles=function(tagName)
{
    var i,t,tags=document.getElementsByTagName(tagName);
    for(i=0;i<tags.length;i++)
    {
        t=tags[i];
        if(t.className=='msg-area')
        {
            t.innerHTML=OneSmile.smilize(t.innerHTML, smilesPath);
        }
    }
}

Messages.insertSmilesToInput=function(input, abreviation, src)
{
    if(editor && editor._editMode == "wysiwyg")
    {
        editor.focusEditor();
        var sel = editor._getSelection();
        var range = editor._createRange(sel);

		image = editor.getParentElement();
		if (!image || !/^img$/i.test(image.tagName))
        {
            editor.insertHTML('&nbsp;<img src="' + src + '" alt="' + abreviation + '" />');
        }
        else
        {
			image.src = src;
			image.alt = abreviation;
        }

        if (is_ie)
        {
		    range.collapse(false);
		    range.select();
        }
        else
        {
            var n = sel.focusNode.nextSibling;
            if (n.nodeType != 1 && n.nextSibling)
                n = n.nextSibling;

            if (n)
            {
                sel.removeAllRanges();
                range = document.createRange();
                range.selectNode(n.nextSibling);
                range.collapse(true);
                sel.addRange(range);
            }
        }

        editor.updateToolbar();
    }
    else
    {
        if(is_ie)
        {
            if(input.isTextEdit)
            {
                input.focus();
                var sel=document.selection;
                var rng=sel.createRange();
                rng.colapse;
                if((sel.type == "Text" || sel.type == "None") && rng != null)
                {
                    rng.text = abreviation;
                }
            }
            else{
                    input.value += abreviation;
            }
        }
        else
        {
            input.value+=abreviation;
        }

        input.focus();
    }
}

Messages.createSmilesArea=function(parent, input)
{
    if (is_mac)
        return;

	var C=Community,tbody,row,i,str,img,smile,src,firstDiv;
	firstDiv=C.CE("div",parent,{},{position:"relative"});
    tbody=C.CE("tbody",C.CE("table",firstDiv));

	for(i=0;i<52;++i)
	{
        if (i==47)
            continue;

//        if(i%20==0 && i<51)
//            row=C.CE("tr",tbody);

       if(i==5 && i<51)
            row=C.CE("tr",tbody);
       if(i==10 && i<51)
            row=C.CE("tr",tbody);
       if(i==15 && i<51)
            row=C.CE("tr",tbody);
       if(i==20 && i<51)
            row=C.CE("tr",tbody);
       if(i==25 && i<51)
            row=C.CE("tr",tbody);
       if(i==30 && i<51)
            row=C.CE("tr",tbody);
       if(i==35 && i<51)
            row=C.CE("tr",tbody);
       if(i==40 && i<51)
            row=C.CE("tr",tbody);
       if(i==45 && i<51)
            row=C.CE("tr",tbody);

//		if (i==9)
			
        smile=OneSmile.smiles[i];
		img=C.CE("img",C.CE("td",row),{src:smilesPath+smile[0],title:smile[1]},{cursor:"pointer"});
//		if (i==7)
//		img = "<br>";
//		alert (C.CE("img",C.CE("td",row),{src:smilesPath+smile[0],title:smile[1]},{cursor:"pointer"}));
        img.onclick=function()
        {
            Messages.insertSmilesToInput(input,this.title,this.src);
        };

		img.onmousedown=function()
		{
			return false;
		};
	}
}

function OneSmile()
{
}

OneSmile.smiles=[
    ['01a.gif','O:-)',[/(O|o|0)(:|=)[-]?\)/gi]],
    ['02a.gif','8-)',[/\8-\)/gi]],
    ['03a.gif',':-[',[/(:|=)[-]?\[/gi]],
    ['04a.gif',':-)',[/(:|=)[-]?\)/gi]],
    ['05a.gif','*ROFL*',[/\*(R|r)(O|o)(F|f)(L|l)\*/gi]],	
    ['06a.gif',':-(',[/(:|=)[-]?\(/gi]],
    ['07a.gif',':-O',[/(:|=)[-]?(O|o)/gi]],
    ['08a.gif',':-|',[/(:|=)[-]?[|I]/gi]],
    ['09a.gif',';-)',[/;[-]?\)/gi]],
    ['10a.gif','*KISSED*',[/\*(K|k)(I|i)(S|s)(S|s)(E|e)(D|d)\*/gi]],
    ['11a.gif',':-D',[/(:|=)[-]?(D|d)/gi]],
    ['12a.gif','*DONT*',[/\*(D|d)(O|o)(N|n)(T|t)\*/gi]],
    ['13a.gif',":'(",[/(:|=)(\'|&#39;)\(/gi]],
    ['14a.gif',':-P',[/(:|=)[-]?(P|p)/gi]],
    ['15a.gif','*SAMO*',[/\*(S|s)(A|a)(M|m)(O|o)\*/gi]],
    ['16a.gif',':-\\',[/(:|=)?\\/gi]],
    ['17a.gif','*DANCE*',[/\*(D|d)(A|a)(N|n)(C|c)(E|e)\*/gi]],
    ['18a.gif',']:->',[/\](:|=)[-]?\>/gi]],
    ['19a.gif','*YAHOO*',[/\*(Y|y)(A|a)(H|h)(O|o)(O|o)\*/gi]],
    ['20a.gif','*STOP*',[/\*(S|s)(T|t)(O|o)(P|p)\*/gi]],
    ['21a.gif',':-*',[/(:|=)[-]?\*/gi]],
    ['22a.gif','*ROSE*',[/\*(R|r)(O|o)(S|s)(E|e)\*/gi]],
    ['23a.gif','*GOOD*',[/\*(G|g)(O|o)(O|o)(D|d)\*/gi]],
    ['24a.gif','*DRINK*',[/\*(D|d)(R|r)(I|i)(N|n)(K|k)\*/gi]],
    ['25a.gif','*LOVE*',[/\*(L|l)(O|o)(V|v)(E|e)\*/gi]],
    ['26a.gif','*BOMB*',[/\*(B|b)(O|o)(M|m)(B|b)\*/gi]],
    ['27a.gif','*SOS*',[/\*(S|s)(O|o)(S|s)\*/gi]],
    ['28a.gif','*IMI*',[/\*(I|i)(M|m)(I|i)\*/gi]],
    ['29a.gif','%)',[/%\)/gi]],
    ['30a.gif','*OK*',[/\*(O|o)(K|k)\*/gi]],
    ['31a.gif','*WUP*',[/\*(W|w)(U|u)(P|p)\*/gi]],
    ['32a.gif','*HNI*',[/\*(H|h)(N|n)(I|i)\*/gi]],
    ['33a.gif','*BRAVO*',[/\*(B|b)(R|r)(A|a)(V|v)(O|o)\*/gi]],
    ['34a.gif','*PEN*',[/\*(P|p)(E|e)(N|n)\*/gi]],
    ['35a.gif','*KING*',[/\*(K|k)(I|i)(N|n)(G|g)\*/gi]],
    ['36a.gif','*VISIL*',[/\*(V|v)(I|i)(S|s)(I|i)(L|l)\*/gi]],
    ['37a.gif','*PINK*',[/\*(P|p)(I|i)(N|n)(K|k)\*/gi]],
    ['38a.gif','*KLISMA*',[/\*(K|k)(L|l)(I|i)(S|s)(M|m)(A|a)\*/gi]],
    ['39a.gif','*PRYAT*',[/\*(P|p)(R|r)(Y|y)(A|a)(T|t)\*/gi]],
    ['40a.gif','*DOWN*',[/\*(D|d)(O|o)(W|w)(N|n)\*/gi]]


//    ['02.gif',':-@',[/(:|=)[-]?@/gi]],
//    ['01.gif','^o)',[/\^o\)/gi]],
//    ['03a.gif',':-S',[/(:|=)[-]?(S|s)/gi]],
//    ['07a.gif','*-)',[/\*-\)/gi]],
//    ['10a.gif','8oI',[/8o(I|\|)/gi]],
//    ['26a.gif',':-$',[/(:|=)[-]?\$/gi]],
//    ['27a.gif',':-O',[/(:|=)[-](O|o|0)/gi]],
//    ['28a.gif','|-)',[/\|-\)/gi]],
//    ['41.gif','(ch)',[/\((C|c)(H|h)\)/gi]],
//    ['44a.gif','(lo)',[/\((L|l)(O|o)\)/gi]],
//    ['45a.gif','(sr)',[/\((S|s)(R|r)\)/gi]],
//    ['46a.gif','|-(',[/\|-\(/gi]],
//    ['47a.gif','(H)',[/\((H|h)\)/gi]],
//    ['48a.gif','(hu)',[/\((H|h)(U|u)\)/gi]],
//    ['49a.gif','(tr)',[/\((T|t)(R|r)\)/gi]],
//    ['50a.gif','(md)',[/\((M|m)(D|d)\)/gi]],
//    ['51a.gif','(fr)',[/\((F|f)(R|r)\)/gi]],
//    ['52a.gif','(dt)',[/\((D|d)(T|t)\)/gi]],
//    ['53a.gif','(sc)',[/\((S|s)(C|c)\)/gi]],
//    ['12.gif','(Y)',[/\((Y|y)\)/gi]],
//    ['15.gif','(N)',[/\((N|n)\)/gi]],
//    ['34.gif','(v)',[/\((V|v)\)/gi]],
//    ['16.gif','(L)',[/\((L|l)\)/gi]],
//    ['17.gif','(U)',[/\((U|u)\)/gi]],
//    ['24.gif','(K)',[/\((K|k)\)/gi]],
//    ['23.gif','(F)',[/\((F|f)\)/gi]],
//    ['32.gif','(*)',[/\(\*\)/gi]],
//    ['19.gif','(^)',[/\((\^)\)/gi]],
//    ['21.gif','(G)',[/\((G|g)\)/gi]],
//    ['25.gif','(B)',[/\((B|b)\)/gi]],
//    ['29.gif','(D)',[/\((D|d)\)/gi]],
//    ['22.gif','(C)',[/\((C|c)\)/gi]],
//    ['30.gif','(pi)',[/\(pi\)/gi]],
//    ['33.gif','(pl)',[/\(pl\)/gi]],
//   ['36.gif','(ic)',[/\((I|i)(C|c)\)/gi]],
//    ['37.gif','(dc)',[/\((D|d)(C|c)\)/gi]],
//    ['baks.gif','($)',[/\(\$\)/gi]],
//    ['35.gif','(co)',[/\((C|c)(O|o)\)/gi]],
//    ['38.gif','(so)',[/\((S|s)(O|o)\)/gi]],
//    ['40.gif','(te)',[/\((T|t)(E|e)\)/gi]],
//    ['39.gif','(nt)',[/\((N|n)(T|t)\)/gi]],
//    ['18.gif','(I)',[/\((I|i)\)/gi]],
//    ['20.gif','(E)',[/\((E|e)\)/gi]],
//    ['42.gif','(Z)',[/\((Z|z)\)/gi]],
//    ['43.gif','(X)',[/\((X|x)\)/gi]],
//    ['31.gif','(S)',[/\((S|s)\)/gi]]
];

OneSmile.smilize=function(str,path)
{
	var i,j,v,regs,tag;

	for(i=this.smiles.length-1;i>=0;--i)
	{
		v=this.smiles[i];
		tag='<img align="middle" src="'+path+v[0]+'" />';

        regs=v[2];
		for(j=regs.length;--j>=0;)
			str=str.replace(regs[j],tag);
	}

    str=str.replace(/&nbsp;<img/gi,'\n<img');

	return str;
};
