function buildHeader(uid,nick,mode){
    return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html><head>'+
    '<meta http-equiv="Content-Language" content="ru">'+
    '<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=windows-1251" />'+
    buildTitle(uid,nick,mode)+
    buildStyle()+
    '</head>\n';
}

function buildTitle(uid,nick,mode){
    //nick=strsafe(nick);
    if (uid==0) nick='Система';
    switch (mode){
            case 1:
                    return '<title>для : '+nick+((uid>0)?(' (ID: '+uid+')'):(''))+' исходящее сообщение на MyDreams.ru</title>';
            break;
            case 2:
                    return '<title>от: '+nick+((uid>0)?(' (ID: '+uid+')'):(''))+' входящее сообщение на MyDreams.ru</title>';
            break;
            case 3:
                    return '<title>Входящие сообщения на MyDreams.ru</title>';
            break;

    }
}

function buildStyle(){
        return        '<style type="text/css" media="screen, projection, print">@import url("http://static.mydreams.ru/msg.css");</style>';
}

function buildJS(){
    return '<script type="text/javascript" src="/modules/messaging/include/ajax.js"></script>\n'+
            ' <script type="text/javascript">\n'+
            'if (document.charset) document.charset="windows-1251";\n'+
    'var smiles = new Array("", ":-)",":-(",":-D","8-o",":angel:",":-P",":shy:",":-((","8-x",";-)");\n'+
    'function updmlen(){if (document.forms[\'postingform\'].postcontent.value.length>999)document.forms[\'postingform\'].postcontent.value=document.forms[\'postingform\'].postcontent.value.substr(0, 999);document.getElementById(\'mlength\').value=(999-document.forms[\'postingform\'].postcontent.value.length);return true;}\n'+
    'function ins_smile(num){\n'+
        'if(document.all){\n'+
            'var s_msg = document.all["postcontent"];\n'+
        '}else{\n'+
            'var s_msg = document.getElementById("postcontent");\n'+
            '}\n'+
        's_msg.value=s_msg.value+smiles[num];\n'+
        's_msg.focus();\n'+
    '}\n'+
 'function openWin(page, width, height) {'+
        'if(!width) width=488;'+
        'if(!height) height=270;'+
        'Win=this.open(page, "xtrasml", "toolbar=no,scrollbars=yes,status=yes,height="+height+",width="+width);'+
    '}\n'+
    'function doAdd(cid,act) {'+
    		'if (act=="addToIgn" && !confirm("Вы действительно хотите добавить ID"+cid+"в игнор-лист?")) return false;'+
            'var query2 = cid;'+
            'var req = new Subsys_JsHttpRequest_Js();'+
            'req.onreadystatechange = function() {'+
                'if (req.readyState == 4) {'+
                    'if (req.responseJS) {'+
                                    'if (act=="add_clist") {window.opener.loadCList();}'+
                            'if (req.responseJS.authreq==1){ alert("Ожидайте авторизации пользователя с ID"+query2);}'+
                            'else if (req.responseJS.authreq==3){ alert("Вы не можете добавить пользователя в контакт-лист");}'+
                                'else if (req.responseJS.authreq==2) {alert("Пользователь с ID"+query2+" уже есть в вашем контакт-листе");} else {alert("Пользователь с Id"+query2+" добавлен в "+((act=="addToIgn")?("игнор"):("контакт"))+"-лист");}'+
                    '}'+
                '}'+
            '}\n'+
            'req.open("GET", "/modules/messaging/index.php", true);'+
            'req.send({ op: act, cid: query2 });'+
        '}\n'+
	buildExtraJs();
}
function buildExtraJs(){
    return 'function init_focus(){'+
                    'document.getElementById("postcontent").focus();'+
                            'document.getElementById("postcontent").value=document.getElementById("postcontent").value;'+
    '}\n'+
    'function check(obj){'+
            'regexp = new RegExp("\\\\s", "g");'+
            'str = obj.value.replace(regexp,"");'+
                    'if (str=="" || str.length==0)        {'+
                            'alert("Напишите сообщение");'+
                            'obj.focus();'+
                            'return false;'+
                    '}'+
                    'return true;'+
            '}\n'+
    'function reply (uid,nick,status,gender,lastlogin,mode,msgcontent){'+
                    'if (document.getElementById("replytab")){'+
                            'document.getElementById("msgtabs").style.display="none";'+
                            'if (!msgcontent) { document.getElementById("postcontent").value="";}'+
                            'document.getElementById("replytab").style.display="block";'+
                            'document.getElementById("postcontent").focus();'+
                            'document.getElementById("postcontent").value=document.getElementById("postcontent").value;'+
                            'if(document.getElementById("postcontent").createTextRange) {'+   
						        'var range = document.getElementById("postcontent").createTextRange();'+   
						        'range.move("character", document.getElementById("postcontent").value.length);'+
						        'range.select();'+
						    '}'+
                    '}else{'+
                            'window.opener.buildSendForm(uid,nick,status,gender,lastlogin,msgcontent);'+
                    '}\n'+
            '}\n'+
    '</script>\n';
}
function buildOptions(){
    return '<td class="mesInfo1" valign="top" align="center" nowrap>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/sm1.gif" alt=":-)" title=":-)" onclick="ins_smile(1); updmlen();" style="cursor:pointer"/>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/sm2.gif" alt=":-(" title=":-(" onclick="ins_smile(2); updmlen();" style="cursor:pointer"/>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/sm3.gif" alt=":-D" title=":-D" onclick="ins_smile(3); updmlen();" style="cursor:pointer"/>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/sm4.gif" alt="8-o" title="8-o" onclick="ins_smile(4); updmlen();" style="cursor:pointer"/>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/angel.gif" alt=":angel:" title=":angel:" onclick="ins_smile(5); updmlen();" style="cursor:pointer"/><br />\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/sm6.gif" alt=":-P" title=":-P" onclick="ins_smile(6); updmlen();" style="cursor:pointer"/>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/shy.gif" alt=":shy:" title=":shy:" onclick="ins_smile(7); updmlen();" style="cursor:pointer"/>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/sm8.gif" alt=":-((" title=":-((" onclick="ins_smile(8); updmlen();" style="cursor:pointer"/>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/sm9.gif" alt="8-x" title="8-x" onclick="ins_smile(9); updmlen();" style="cursor:pointer"/>\n'+
                                    '<img src="http://static.mydreams.ru/images/smiles/sm10.gif" alt=";-)" title=";-)" onclick="ins_smile(10); updmlen();" style="cursor:pointer"/>\n'+
                    '</td>\n'+
                    '<td align="center" class="mesInfoDop"><img onclick="openWin(\'/themes/default/extra_smiles.html\',550,250);" src="http://static.mydreams.ru/images/new/mes/ico-plus.gif" style="cursor:pointer;" alt="дополнительные смайлики" /></td>\n';
}

function toquote(str){
    if (str!=""){
    		
    		var regexp = new RegExp("(^&gt;.*[\n\r]*)","gm");
            str=str.replace(regexp,"");
            regexp2 = new RegExp("\n", "g");
            str=str.replace(regexp2,"\n> ");
            return '> '+str+"\n\n";
    } else {
            return "";
    }
}
function toquote2(str){
    if (str!=""){
            var regexp = new RegExp("\n", "g");
            str=str.replace(regexp,"\\n");
            regexp = new RegExp("\r", "g");
            str=str.replace(regexp,"");
            return str;
    } else {
            return "";
    }
}

function buildBody(uid,nick,status,gender,lastlogin,mode,msgcontent,fontsize,fontcolor,backcolor,msgid,msgtime,attach_nick){
    if (uid>0 && msgcontent) msgcontent=strsafe(rplamp(msgcontent));
    if (uid==0){status=1;gender=3;nick='Система';}
    var hid='';
    var action="/modules/messaging/pmlite.php";
    switch (mode){
            case 4:
                    action="/modules/messaging/complain.php";
                    break;
            case 5:
                    action="/modules/humor/complain.php";
                    break;
    }
    switch (mode){
            case 5:
            case 4:
                    status=1;gender=3;nick='Система';msgcontent="Причина жалобы:\n";
            case 3:
            case 1:
                    //if (uid>0){
                            textarea='<textarea tabindex=1 id="postcontent" name="Post" onkeyup="updmlen();" onkeydown="if(event) if((event.ctrlKey) && ((event.keyCode==10)||(event.keyCode==13)))if(check(document.forms[\'postingform\'].postcontent)){ document.forms[\'postingform\'].submit(); window.opener.mySetCookie(\'boost_refresh\',1);} else { return false;}return true;") >'+((mode!=4 && mode!=5)?(toquote(msgcontent)):(msgcontent))+'</textarea>'
                            submit='<input type="image" name="submit" class=button tabindex="2" src="http://static.mydreams.ru/images/new/mes/mbtn-send.gif" alt="Отправить" onclick="if (!document.getElementById(\'postcontent\').value){alert(\'Напишите сообщение!\'); return false;} window.opener.mySetCookie(\'boost_refresh\',1);" />';
                    //} else {
                            //textarea='';submit='';
                    //}
            break;
            case 2:
                    textarea='<div id="rmsg_'+msgid+'" name="rmsg_'+msgid+'" style="padding:0px 0 0;width:456px;height:150px;color:#000000; background:'+backcolor+'; font-family:Tahoma, Arial, Helvetica, sans-serif; font-size:11px;overflow:auto;text-align:left;">'+to_display(msgcontent,attach_nick)+'</div>'
                    if (uid>0){
                            submit='<input type="image" class=button src="http://static.mydreams.ru/images/new/mes/mbtn-complain.gif" onclick="this.style.display=\'none\';window.opener.buildComplainForm('+uid+','+msgid+',4);" />\n'+
                                    '<input type="image" name="submit" class=button tabindex="2" src="http://static.mydreams.ru/images/new/mes/mbtn-answer.gif" alt="Ответить" onclick="reply('+uid+",'"+rplamp(nick)+"',"+status+','+gender+','+lastlogin+','+mode+",'');\" />\n"+
                                    '<input type="image" name="quote" class=button tabindex="3" src="http://static.mydreams.ru/images/new/mes/mbtn-qoute.gif" alt="Цитата" onclick="reply('+uid+",'"+rplamp(nick)+"',"+status+','+gender+','+lastlogin+','+mode+",'"+rplamp(toquote2(msgcontent))+"');\" />";
                    } else {submit='';}
            break;
            break;

            break;
    }

 return ((mode!=2)?('<form action="'+action+'" accept-charset="windows-1251" method="post" name="coolsus" id="postingform" onsubmit="return check(document.forms[\'postingform\'].postcontent);">'):(''))+
'<div class="messages" '+((mode==3)?('id="replytab" style="display:none;"'):(''))+'>\n'+
    '<div class="mesTop">\n'+
            '<div class="mt01">\n'+
                    '<img src="http://static.mydreams.ru/images/status/status_'+status+'.gif" title="'+(   (status>0)?("сейчас на сайте"):(    "был"+(     (gender==2)?("а"):("")    )+" на сайте " +(new Date(lastlogin*1000).toLocaleString()) ))+'">\n'+
                    '<a onclick="'+((uid>0)?('window.opener.info('+uid+');'):('return false;'))+'" class="'+((gender==2)?('fe'):((gender==3)?('sys'):('')))+'male_nick">'+nick+'</a>\n'+
            '</div>\n'+
            '<div class="mt02">\n'+
                    ((mode!=2)?('<!--<input name="inform" type="checkbox" value="1" /> уведомить о получении-->\n'):("<b>"+(new Date(msgtime*1000).toLocaleString())+"</b>"))+
                    '&nbsp;&nbsp;<img style="cursor:pointer" alt="'+((myGetCookie('msg_snd')=='on')?'выключить звуковые уведомления':'включить звуковые уведомления')+'" title="'+((myGetCookie('msg_snd')=='on')?'выключить звуковые уведомления':'включить звуковые уведомления')+'" src="'+itp_static_url+'/images/new/mes/sound-'+((myGetCookie('msg_snd')=='on')?'on':'off')+'.gif" onclick="var msg_snd=(window.opener.myGetCookie(\'msg_snd\')==\'on\')?1:0; msg_snd=1-msg_snd; window.opener.mySetCookie(\'msg_snd\', msg_snd?\'on\':\'off\'); this.src=\''+itp_static_url+'/images/new/mes/sound-\'+(msg_snd?\'on\':\'off\')+\'.gif\'; this.alt=this.title=(msg_snd?\'выключить звуковые уведомления\':\'включить звуковые уведомления\');" />\n'+
            '</div>\n'+
    '</div>\n'+
 '<div class="mesCont">\n'+
            '<div>\n'+
                 textarea+
         '</div>\n'+
    '</div>\n'+
    '<div class="mesFoot1"></div>\n'+
    '<div class="mesFoot2">\n'+
            '<table>\n'+
                    '<tr>\n'+
            ((mode!=2)?(buildOptions()):('<td class="mesInfo1" valign="top"></td><td class="mesInfoDop"></td>'))+
                            '<td class="mesInfo4" nowrap>\n'+
                                    submit+
                            '</td>\n'+
                    '</tr>\n'+
                    '<tr valign="top">\n'+
                            '<td class="mesInfo3" colspan="2">'+((mode!=2)?('<span>Осталось символов <input type="text" value="999" readonly="readonly" id="mlength" name="mlength"/></span>'):('&nbsp'))+'</td>\n'+
                            '<td class="mesInfo4">\n'+((uid>0 && mode!=4)?(
                                    '<input type="image" tabindex="10" src="http://static.mydreams.ru/images/new/mes/mbtn-history.gif" alt="История" onClick="window.open(\'/modules/messaging/history.php?uid='+uid+'\',\'_blank\',\'height=400, width=640,scrollbars=yes,status=no\'); return false;"/>\n'+
                                    '<input type="image" tabindex="11" src="http://static.mydreams.ru/images/new/mes/mbtn-to-ignore.gif" alt="В игнор" onclick="doAdd('+uid+',\'addToIgn\');return false;"/>\n'+
                                    '<input type="image" tabindex="12" src="http://static.mydreams.ru/images/new/mes/mbtn-to-cont.gif" alt="В контакт" onclick="doAdd('+uid+',\'add_clist\');return false;"/>\n'):(""))+
                            '</td>\n'+
                    '</tr>\n'+
            '</table>\n'+
    '</div>\n'+
    ((mode!=2)?('<input type="hidden" name="op" value="submit" />\n'):(''))+
    '<input type="hidden" name="to_userid" value="'+uid+'">'+
    ((mode==4 || mode==5)?('<input type="hidden" name="msg_id" value="'+lastlogin+'" />\n'):(''))+
    //'<div class="mesBanner"><a href="#"><img src="http://static.mydreams.ru/images/new/mes/mes-banner1.gif" width="468" height="60" alt="Баннерок" /></a></div>\n'+
    '<div class="mesFoot3"></div>\n'+
    '</div>\n'+
    '</form>';
}

function buildComplainForm(uid,msg_id,mode){
    sendform=window.open('', '', 'toolbar=no,scrollbars=no,status=yes,height=316,width=502');
    if (sendform.document.charset) sendform.document.charset="windows-1251";
    sendform.document.write(buildHeader(0,0,1)+buildJS()+'<body onload="init_focus();">'+buildBody(uid, 0, 0, 0, msg_id,mode,0,0,0,0,0,0)+'</body></html>');
    sendform.document.close();
}

function buildSendForm(uid,nick,status,gender,lastlogin, msgcontent){
    sendform=window.open('', '', 'toolbar=no,scrollbars=no,status=yes,height=316,width=502');
    if (sendform.document.charset) sendform.document.charset="windows-1251";
    sendform.document.write(buildHeader(uid,nick,1)+buildJS()+'<body onload="init_focus();">'+buildBody(uid, nick, status, gender, lastlogin,1,msgcontent,0,0,0,0,0)+'</body></html>');
    sendform.document.close();
}

var received_msgs=Array();

function receiveMsgs(msgs){
    if (msgs && msgs.length>0){
	playSound('msg_recive.mp3');

            for (j=0;j<msgs.length;j++){
                    if (ArrayIncludes( received_msgs, msgs[j].msg_id)) msgs.splice(j,1);
            }
            if (msgs.length==0) return;
            if (msgs.length>1){
                    scrbar="yes";
                    hsize="520";
                    vsize="346";
            } else {
                    scrbar="no";
                    hsize="502";
                    vsize="316";
            }
            win=window.open('', '', 'toolbar=no,scrollbars='+scrbar+',status=yes,height='+vsize+',width='+hsize);
            var opened=new Array();
            var towrite='';
            if (win){
                    win.focus();
                    if (win.document.charset) win.document.charset="windows-1251";
                    if (msgs[0].from_userid==0){msgs[0].nickname="Система";}
                    for (k=0;k<msgs.length;k++){
                            if (ArrayIncludes( opened, msgs[k].msg_id)) continue;
                            received_msgs[msgs[k].msg_id]=msgs[k].msg_id;
                            opened[k]=msgs[k].msg_id;
                            if (msgs[k].from_userid==0){msgs[k].nickname="Система";}
                            towrite=towrite+buildBody(msgs[k].from_userid, strsafe(rplamp(msgs[k].nickname)), msgs[k].Status, msgs[k].gender, msgs[k].last_login,2,msgs[k].msg_text,msgs[k].fontsize,msgs[k].fontcolor,msgs[k].backcolor,msgs[k].msg_id,msgs[k].msg_time,msgs[k].attach_nick);
                    }
                    win.document.open();
                    win.document.write(buildHeader(msgs[0].from_userid,strsafe(rplamp(msgs[0].nickname)), (msgs.length>1)?(3):(2))+buildJS()+'<body><div id="msgtabs">'+towrite+'</div>'+((msgs.length==1)?(buildBody(msgs[0].from_userid, strsafe(rplamp(msgs[0].nickname)), msgs[0].Status, msgs[0].gender, msgs[0].last_login,3,msgs[0].msg_text,msgs[0].fontsize,msgs[0].fontcolor,msgs[0].backcolor,msgs[0].msg_id,msgs[0].attach_nick)):(''))+'</body></html>');
                    win.document.close();
                    MsgClient.setRead(opened,function (result){
                        return false;
                });
            } else {
                    for (j=0;j<msgs.length;j++){
                            opened[j]=msgs[j].msg_id;
                    }
                    MsgClient.setAltShow(opened,function (result){
                        return false;
                });
            }
    }
}
function ArrayIncludes( arr, element){
	for( var i in arr ) if( arr[i] == element ) return i;
	return false;
}
function addSmile(str){
    var smiles = new Array(":\\-?\\)",":-?\\(\\(+",":\\-?\\(",":\\-?D","8\\-?o",":angel:",":-?P",":shy:","8-?x",";\\-?\\)");
    var smilepics = new Array("sm1.gif","sm8.gif","sm2.gif","sm3.gif","sm4.gif","angel.gif","sm6.gif","shy.gif","sm9.gif","sm10.gif");
    regexp = new RegExp(":([a-z][a-z,0-9]+):", "g");
    str=str.replace(regexp,'<img src="http://static.mydreams.ru/images/smiles/$1\.gif" alt="$1" title="$1">');
    for (i=0;i<smilepics.length;i++){
            var regexp = new RegExp(smiles[i], "g");
            str=str.replace(regexp,'<img src="http://static.mydreams.ru/images/smiles/'+smilepics[i]+'">');
    }
    return str;
}
function makeClickable(str){
    regexp = new RegExp("(\\s|^)([a-z]+?):\/\/([^, \r\n\"\(\)'<>]+)", "g");
    regexp2= new RegExp("(\\s|^)www\\.([a-z0-9\-]+)\\.([^, \r\n\"\(\)'<>]+)","g");
    regexp3= new RegExp("(\\s|^)ftp\\.([a-z0-9\-]+)\\.([^, \r\n\"\(\)'<>]+)","g");
    regexp4= new RegExp("(^|[^]_a-z0-9-=\"'\/:\.])([a-z0-9\-_\.]+?)@([^, \r\n\"\(\)'<>\[\]]+)","g");
    if (/Firefox\/2/i.test(navigator.userAgent)){
            str=str.replace(regexp,"$1<a onclick='window.opener.location=\"$2://$3\"' >$2://$3</a>");
            str=str.replace(regexp2,"$1<a onclick='window.opener.location=\"http://www.$2.$3\"' >www.$2.$3</a>");
            str=str.replace(regexp3,"$1<a onclick='window.opener.location=\"ftp://ftp.$2.$3\"' >ftp.$2.$3</a>");
        } else {
            str=str.replace(regexp,"$1<a href=\"$2://$3\" target=\"_blank\">$2://$3</a>");
            str=str.replace(regexp2,"$1<a href=\"http://www.$2.$3\" target=\"_blank\">www.$2.$3</a>");
            str=str.replace(regexp3,"$1<a href=\"ftp://ftp.$2.$3\" target=\"_blank\">ftp.$2.$3</a>");
        }
    return str;
}
function addNickLinks(str,info){
    if (info && info!=null && typeof(info)!="undefined"){
            for (i=0;i<info.length;i++){
                    regexp = new RegExp("(\\s|^)#"+info[i].uid,"g");
                    str=str.replace(regexp,"$1<a onclick='window.opener.info("+info[i].uid+")' class='"+((info[i].user_gender==2)?("fe"):(""))+"male_nick'>"+strsafe(info[i].nickname)+"</a>");
            }
    }
    return str;
}
function to_display(str,attach_nick){
    str=addNickLinks(str,attach_nick);
    str=makeClickable(str);
    str=nl2br(str);
    str=addSmile(str);
    return str;
}