/* для смайлов */
var toggle_flag=1;

var showCloseIcon = '<div style="float: right;"><a onclick="hideDivDialog(); return false;" href="#"><img src="http://otvet.mail.ru/img/close_help.gif" width=7 height=7 border=0></a></div>';

function togglesmile()
{
	if (toggle_flag==1) {
		//gebi('somesmileys').style.display='none';
		gebi('allsmileys').style.display='block';				
		gebi('icotxt').innerHTML='Скрыть смайлы';
		toggle_flag=2;
		} else {
		gebi('allsmileys').style.display='none';	
	//	gebi('somesmileys').style.display='block';
		gebi('icotxt').innerHTML='Все смайлы и жесты';
		toggle_flag=1;
		}
}

function replaceSelectedText(obj,flag,mnemonic)
{
	if (flag==1)
	{	var addpltxt='<smile type="'+mnemonic+'">'; }
	if (flag==2)
	{	var addpltxt='<gesture type="'+mnemonic+'">'; }	
	if (flag==3)
	{	var addpltxt='<animated type="'+mnemonic+'">'; }	
	if (flag==4)
	{	var addpltxt='<advanced type="'+mnemonic+'">'; }	
	if (flag==5)
	{	var addpltxt='<kolobki type="'+mnemonic+'">'; }
	
	if (document.selection) //для IE и Opera
	{
		obj.focus();
		var s = document.selection.createRange(); 
	   	s.text= addpltxt;
		s.select();
		return true;
	}
	else if (typeof(obj.selectionStart)=="number")//Для FF
	{
	 	var start = obj.selectionStart;
	    var end = obj.selectionEnd;	
		
		obj.value = obj.value.substr(0,start)+addpltxt+obj.value.substr(end);
		end = end + addpltxt.length;
	    obj.setSelectionRange(end,end);
		obj.focus();
	   return true;
	}
	return false;
}

/* popup add foto, video */
popup = false;
document.domain='mail.ru';
function add_photo() {
	var subj = escape(document.forms['reply'].elements['subject_text'].value);
	if (popup) popup.close();
	popup = window.open('http://foto.mail.ru/cgi-bin/addphoto?blogs=1&Title=','add_pict','width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left='+(screen.width-660)/2+',top='+(screen.height-660)/2);
	if (popup) popup.focus();
}
function add_video() {
	var subj = escape(document.forms['reply'].elements['subject_text'].value);
	if (popup) popup.close();
	popup = window.open('http://my.video.mail.ru/cgi-bin/addvideo?blogs=1&Title=','add_pict','width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left='+(screen.width-660)/2+',top='+(screen.height-660)/2);
	if (popup) popup.focus();
}

/*  */
var direct = '';
var a = '';
var flag = 0;
function loadXMLDoc(url) {
	req = false;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if (req) {
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send("");
	}
}

function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
            var response = req.responseText;
            var array = new Array();
            array = response.split(';');
            var method = array.shift();
            for (var i=0;i<array.length;i++) {
                array[i] = "'"+ array[i] +"'";
            }
            var argument = array.join(',');
            eval(method + '('+argument+')');
        } else {
            //alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
    }
}

function set_npcur(pcur,ncur) {
    (direct) ? (cur=ncur) : (cur=pcur);
	(direct) ? (al_text="последней") : (al_text="первой");
	if (!cur){
		//a_txt=a.firstChild.cloneNode(true);
		//a.parentNode.replaceChild(a_txt,a);
		alert ("Вы находитесь на странице "+al_text+" записи");
		flag = 1;
	}
	else {
	   var url = PerlVar_JournalDir;
	   url+= (direct) ? ncur : pcur;
	   url+= ".html";
       document.location.href = url;
	}
}

function check_go(d,id) {
	if (flag==1) {
	   flag = 0;
	   direct = d;
	   a = document.getElementById(((d) ? "next_post" : "prev_post"));
	   a_txt=a.firstChild.cloneNode(true);
	   a.parentNode.replaceChild(a_txt,a);
	   var url= PerlVar_ACTION_DIR + "jpreviousnextpostid?user=" + PerlVar_JournalEmail +"&id="+id;
       loadXMLDoc(url);
    }
}
flag = 1;

var _linkid;
function showComplainForm(_link, post_id, comment_id) {
    _linkid = _link.id;
    showDivDialog(showCloseIcon + '<h1 style="margin-bottom: 10px">Сообщить о спаме?</h1><form action="" onsubmit="sendComplain(\''+post_id+'\', \''+comment_id+'\'); return false;"><input type="submit" id="butForSpam" value="Сообщить" style="font-size: 11px; font-family: tahoma;"/><input type="button" onclick="hideDivDialog()" value="Отмена" style="font-size: 11px; font-family: tahoma; margin-left: 15px"/></form>', _link);
    return false;
}

function showDivDialog(html, basis, _x, _y) {
	var div = gebi("complain_form");
	div.innerHTML = html;
	if (basis) {
		var _top = absPosition(basis).y + ((_y) ? _y : 0);
		var _left = absPosition(basis).x + ((_x) ? _x : 0);
	}
	if (_top) div.style.top = _top;
	if (_left) div.style.left = _left;
	div.style.display = "";
}
function hideDivDialog() {
	gebi("complain_form").style.display = "none";
}

function sendComplain(post_id, comment_id) {
    var div = gebi("complain_form");
    div.innerHTML = showCloseIcon + '<span style="color:#696973;font-family:tahoma;font-size:11px;">Запрос обрабатывается</span>';
    perl_send_complain(post_id, comment_id, 'antispam', complainSended);
    delete div;
	return false;
}

function complainSended(result) {
    var div = gebi("complain_form");
//    if (result) {
        div.innerHTML = showCloseIcon + '<span style="color:#696973;font-family:tahoma;font-size:11px;">Ваша жалоба принята и будет рассмотрена в ближайшее время. Спасибо.</span>';
        gebi(_linkid).style.display='none';
//    } else {
//	div.innerHTML = showCloseIcon + '<span style="color:#696973;font-family:tahoma;font-size:11px;">Произошла ошибка.</span>';
//    }
}

/* Перефокусировка на поле комментария */
function refocus()
{
	var elem1 = document.forms['reply'].elements['Subject'];
	var elem2 = document.forms['reply'].elements['Comment'];
	if (elem1 && elem2) { elem1.focus(); elem2.focus();	elem2.value=elem2.value+''; elem1=0; elem2=0; }
}

function dis_sub_but() {
	var val = document.getElementById("comment_text").value;
	var sub_but = document.getElementById("sub_but");
	if (val != "") {
		sub_but.value = "Идет отправка";
		sub_but.disabled = true;
		return true;
	} else {
		return false;
	}
}

function add_comment(form)
{
    var subject = form.Subject.value;
    var comment = form.Comment.value;
    var re = new RegExp('\\S');
    if (!re.test(subject+'') && !re.test(comment+''))
    {
        alert('Поле Тема не должно быть пустым');
        return false;
    }
    return dis_sub_but();
    //return true;
}

function change_selected_opt(select_fiel)
{
    if(select_fiel.options[1].selected==true) {
	document.getElementById('hides_tr').style.display="";document.getElementById('hides_td').style.display="";
    }
    if(select_fiel.options[0].selected==true) {
	document.getElementById("hides_tr").style.display="none";document.getElementById("hides_td").style.display="none";
    }
}

/* */
function form_dis_sub_but() {
	var sub_but = document.getElementById("sub_but");
	var preview_but = document.getElementById("preview_but");
	sub_but.disabled = true;
	preview_but.disabled = true;
	return true;
}
function form_set_preview()
{
	document.getElementById('form_preview').value=1;
}

/* обработка коментов */

function show_del_comment(obj,id)
{
    if(!has_javascript()) return true;
    close_del_comment();
    var del_div=document.createElement("div");
    del_div.id="del_f";
    del_div.className="del_min";
    del_div.innerHTML="Удалить комментарий?<br><img src=http://img.mail.ru/0.gif width=1 height=5><br>"
	+"<input type=checkbox id=delete_all>&nbsp;&nbsp;с&nbsp;вложенными&nbsp;комментариями<br>"
	+"<img src=http://img.mail.ru/0.gif width=1 height=7><br>"
	+"<input type=button value=\" Да \" onclick=\"del_comment('"+id+"');\">&nbsp;&nbsp;"
	+"<input type=button value=\" Нет \" onclick=\"close_del_comment();\">";
    obj.parentNode.appendChild(del_div);
    return false;
}

function close_del_comment()
{
    var del=document.getElementById("del_f");
    if (del) {
	del.parentNode.removeChild(del);
    }
    return false;
}

function del_comment(id)
{
    var delete_all=(document.getElementById("delete_all").checked?1:0);
    close_del_comment()
    var url= PerlVar_ACTION_DIR + "jdelcomment?user=" + PerlVar_JournalEmail + "&id=" + PerlVar_Entry_ID+ "&delete="+id+"&all="+delete_all+"&xml=1";
    get_script(url);
    return false;
}

function hide_deleted_comment(id,level)
{
    var element_id="t_"+id;
    var div;
    if(level) {
	div=document.createElement('table');
	div.className="tred";
	div.id=element_id;
	div.cellPadding=0;
	div.cellSpacing=0;
	div.border=0;
	div.width="100%";
	var tbody=document.createElement('tbody');
	var tr=document.createElement('tr');
	div.appendChild(tbody);
	tr.valign="top";
	tbody.appendChild(tr);
	var td=document.createElement('td');
	tr.appendChild(td);
	td.align="right";
	td.innerHTML="<img src=http://img.mail.ru/0.gif width="+level+" height=7><br>"
	    +"<img src=http://img.mail.ru/r/blogs/strelka2.gif width=25 height=15 class=prob>";
	td=document.createElement('td');
	tr.appendChild(td);
	td.width="100%";
	td.innerHTML="<div class=del_div><img src=\"http://img.mail.ru/r/blogs/ico_deleted.png\" class=\"IEpng\" width=16 height=16 align=absmiddle>&nbsp;&nbsp;Комментарий удален</div>";
    } else {
    	div=document.createElement('div');
	div.id=element_id;
	div.className="del_div";
	div.innerHTML="<img src=\"http://img.mail.ru/r/blogs/ico_deleted.png\" class=\"IEpng\" width=16 height=16 align=absmiddle>&nbsp;&nbsp;Комментарий удален";
    }
    var old_div=document.getElementById(element_id);
    if(old_div) old_div.parentNode.replaceChild(div,old_div);
}

function screen_comment(id)
{
    if(!has_javascript()) return true;
    var screen_all=0;
    var url;
    if(document.getElementById("screened_not_readable_"+id)) {
        url= PerlVar_ACTION_DIR + "jscreencomment?user=" + PerlVar_JournalEmail +"&id=" + PerlVar_Entry_ID + "&screen="+id+"&all="+screen_all+"&readable=1&xml=1";
    } else {
	if(document.getElementById("screened_"+id)) {
	    url= PerlVar_ACTION_DIR + "jscreencomment?user=" + PerlVar_JournalEmail + "&id=" + PerlVar_Entry_ID + "&screen="+id+"&all="+screen_all+"&xml=1&restore=1";
	} else {
	    url= PerlVar_ACTION_DIR + "jscreencomment?user=" + PerlVar_JournalEmail	+ "&id=" + PerlVar_Entry_ID + "&screen="+id+"&all="+screen_all+"&xml=1";
	}
    }
    get_script(url);
    return false;
}

function hide_screened_comment(id)
{
    var element_id="screened_"+id;
    var old_element_id="unscreened_"+id;
    var div=document.createElement('div');
    div.id=element_id;
    div.className="hide_com";
    div.innerHTML="Комментарий скрыт";
    var old_div=document.getElementById(old_element_id);
    if(old_div) old_div.parentNode.replaceChild(div,old_div);

    var img=document.getElementById("screen_img_"+id);
    if(img) {
      img.src= !Theme_tmpl ? "http://img.mail.ru/r/blogs/ico_comment_show.png" : "http://img.mail.ru/r/blogs/ico_comment_show_2.png";
      img.alt="Показать комментарий";
      img.title="Показать комментарий";
	  img.className = "IEpng";
    }
    var td=document.getElementById("comment_hide_bg_td1_"+id);
    if(td) {
	td.className="hide_bg";
    }
    var td=document.getElementById("comment_hide_bg_td2_"+id);
    if(td) {
	td.className="hide_bg cont";
    }
}

function show_unscreened_comment(id)
{
    var element_id="unscreened_"+id;
    var old_element_id_screened="screened_"+id;
    var old_element_id_not_readable="screened_not_readable_"+id;
    var div=document.createElement('span');
    div.id=element_id;
    var old_div=document.getElementById(old_element_id_screened);
    if(old_div) {
	old_div.parentNode.replaceChild(div,old_div);
    } else {
	var old_div=document.getElementById(old_element_id_not_readable);
	if(old_div) old_div.parentNode.replaceChild(div,old_div);
    }

    var img=document.getElementById("screen_img_"+id);
    if(img) {
      img.src= !Theme_tmpl ? "http://img.mail.ru/r/blogs/ico_comment_hidden.png" : "http://img.mail.ru/r/blogs/ico_comment_hidden_2.png";
      img.alt="Скрыть комментарий";
      img.title="Скрыть комментарий";
	  img.className = "IEpng";
    }
    var td=document.getElementById("comment_hide_bg_td1_"+id);
    if(td) {
	td.className= !Theme_tmpl ? "comment_list_bg" : "comment_bg_color";
    }
    var td=document.getElementById("comment_hide_bg_td2_"+id);
    if(td) {
	td.className= !Theme_tmpl ? "cont comment_list_bg" : "comment_text cont comment_bg_color";
    }
}

function change_comment_make_notcommentable(id)
{
    if(!has_javascript()) return true;
    var make_all=0;
    var url;
    if(document.getElementById("commentable_"+id)) {
	url= PerlVar_ACTION_DIR + "jmakecommentnotcommentable?user=" + PerlVar_JournalEmail +"&id=" + PerlVar_Entry_ID +"&comment="+id+"&all="+make_all+"&xml=1";
    } else {
	url= PerlVar_ACTION_DIR + "jmakecommentnotcommentable?user=" + PerlVar_JournalEmail +"&id=" + PerlVar_Entry_ID + "&comment="+id+"&all="+make_all+"&xml=1&restore=1";
    }
    get_script(url);
    return false;
}

function make_comment_commentable(id)
{
    var element_id="commentable_"+id;
    var old_element_id="notcommentable_"+id;
    var div=document.createElement('p');
    div.id=element_id;
    div.className="gr_sm";
    div.innerHTML="<a id=\"l_"+id+"\" onclick=\"return show_add_comment('"+id+"', 0, '"+PerlVar_back_value+"');\" "
	+"href=\"" + PerlVar_URL + "&replyto="+id+"#comment_"+id+"\" mc=1>Ответить</a> (<a id=\"c_"+id+"\" "
	+"onclick=\"return show_add_comment('"+id+"', 0, '"+PerlVar_back_value+"','yes');\" href=\"" + PerlVar_URL + "&cit=1&replyto="+id+"#comment_"+id+"\" mc=1>с цитатой</a>)";
    var old_div=document.getElementById(old_element_id);
    if(old_div) old_div.parentNode.replaceChild(div,old_div);
    var img=document.getElementById("commentable_img_"+id);
    if(img) {
      img.src= "http://img.mail.ru/r/blogs/ico_lock_2.png";
      img.title = "Запретить комментарии";
      img.alt ="Запретить комментарии";
	  img.className = "IEpng";
    }
}

function make_comment_notcommentable(id)
{
    var element_id="notcommentable_"+id;
    var old_element_id="commentable_"+id;
    var div=document.createElement('p');
    div.id=element_id;
    div.className="gr_sm";
    div.innerHTML = '<img src="http://img.mail.ru/r/blogs/ico_lock.png" class="IEpng" width="16" height="16" border="0" align="absmiddle">&nbsp;Комментарии запрещены';
    var old_div=document.getElementById(old_element_id);
    if(old_div) old_div.parentNode.replaceChild(div,old_div);
    var img=document.getElementById("commentable_img_"+id);
    if(img) {
      img.src= "http://img.mail.ru/r/blogs/ico_unlock_2.png";
      img.title="Разрешить комментарии";
      img.alt="Разрешить комментарии";
	  img.className = "IEpng";
    }
}

function get_script (url) {
    if(this.callId) {
	this.callId += 1;
    } else {
	this.callId = 1;
    }
    var newScript = document.createElement("SCRIPT");
    newScript.type = "text/javascript";
    newScript.src  = url + "&callid=" + String(this.callId)+"&rand="+Math.random();
    if(this.oldScript) {
	document.body.replaceChild(newScript,this.oldScript);
    } else {
	document.body.appendChild(newScript);
    }
    this.oldScript = newScript;
}

var protect_key=PerlVar_ProKey;
var t = new Date;
var protect_key_expire = t.getTime()+PerlVar_ProKeyExpire*1000;
var timetimer;
var timetimer2;

function set_protect_key(key)
{
	clearTimeout(timetimer);
	clearTimeout(timetimer2);
	var profield = document.getElementById('protect_key');
	if(profield) { profield.value=key; }
	var cform = document.forms['reply'];
	cform.submit();
}


function retrive_protect_key()
{
	if(protect_key=='') {
		perl_get_post_protect_key(PerlVar_Entry_ID,set_protect_key);
		timetimer2=setTimeout(retrive_protect_key,3000);
	}
}

function submit_comment()
{
	var t = new Date;
	if(t.getTime()<protect_key_expire) { return true; }
	if(!dis_sub_but()) { return false; }	
	protect_key='';
	retrive_protect_key();
	timetimer=setTimeout("set_protect_key(0)",5000);
	return false;
}

function comments_subscribe_callback(remove)
{
	if(remove<0) return;
	var link = document.getElementById('commsubscr1');
	var link2 = document.getElementById('commsubscr2');
	if(link && link2) {
		if(remove) {
			PerlVar_comments_subscribed = 0;
			link.innerHTML='<img src="http://img.mail.ru/r/blogs/ico_subscribe_2.png" class=IEpng width=16 height=16 border=0 align=absmiddle>';
			link2.innerHTML='Подписаться на комментарии';
			link.href=PerlVar_ACTION_DIR + 'jcommentssubscribe?user=' + PerlVar_JournalEmail + '&id=' +PerlVar_Entry_ID+ '&' + PerlVar_back;
			link2.href=PerlVar_ACTION_DIR + 'jcommentssubscribe?user=' + PerlVar_JournalEmail + '&id=' +PerlVar_Entry_ID+ '&' + PerlVar_back;
			link.onclick=function() { return comments_subscribe(0,PerlVar_Entry_ID); };
			link2.onclick=function() { return comments_subscribe(0,PerlVar_Entry_ID); };
		}
		else {
			PerlVar_comments_subscribed = 1;
			link.innerHTML='<img src="http://img.mail.ru/r/blogs/ico_unsubscribe.png" class=IEpng width=16 height=16 border=0 align=absmiddle>';
			link2.innerHTML='Отписаться от комментариев';
			link.href=PerlVar_ACTION_DIR + 'jcommentssubscribe?user=' + PerlVar_JournalEmail + '&remove=1&id=' +PerlVar_Entry_ID+ '&' + PerlVar_back;
			link2.href=PerlVar_ACTION_DIR + 'jcommentssubscribe?user=' + PerlVar_JournalEmail + '&remove=1&id=' + PerlVar_Entry_ID+ '&' + PerlVar_back;
			link.onclick=function() { return comments_subscribe(1,PerlVar_Entry_ID); };
			link2.onclick=function() { return comments_subscribe(1,PerlVar_Entry_ID); };
		}
	}
}

function comments_subscribe(remove,entryid)
{
	var link = document.getElementById('commsubscr1');
	var link2 = document.getElementById('commsubscr2');
	if(link && link2) {
		link2.innerHTML='Выполняется...';
		link.onclick=function() { return false; };
		link2.onclick=function() { return false; };
	}
	perl_posts_comments_subscribe(0,remove,entryid,comments_subscribe_callback);
	return false;
}
