function forumPost(form) {
  if ($('newTopic_title')) {
    if (trim($('newTopic_title').value).length<2) {
      alert("Введите, пожалуйста, название для новой темы");
      $('newTopic_title').focus();
      return false;
    }
    if (trim($('forumCaptcha_scode').value).length<4) {
      alert("Введите, пожалуйста, код, указанный на картинке");
      $('forumCaptcha_scode').focus();
      return false;
    }
  }
  if (trim($('msgText').value)=="") {
    alert("Введите, пожалуйста, текст сообщения");
    $('msgText').focus();
    return false;
  }
  if ($('subscribeBox')) {
    setCookie('t4noautosub', $('subscribeBox').checked?'':'Y', null, null, '/');
  }
  if (!Browser.Features.xhr) return true;
  if ($('forumLogin').style.display=='none') { // make sure browser didn't put stored values here
    form.elements['t4user'].value='';
    form.elements['t4password'].value='';
  }
  forumPostReq.send($(form).toQueryString()+'&mode=ajax');
  return false;
  //return callServer("POST", '/t4/ForumPost', form2post(form)+'&mode=ajax', 'application/x-www-form-urlencoded;charset=windows-1251', forumPosted, form);
}

function forumPostSuccess(responseText, responseXML) {
  var ok=responseXML.documentElement;
  var msgId=parseInt(ok.getAttribute('msgId'));
  var edited=ok.getAttribute('edited');
  var forumId=ok.getAttribute('forumId');
  var lastMsgAnchor=$('forumLastMsg');

  forumMsgReset();
  reloadCaptcha();
  $('msgText').value='';

  if (typeof(forumMessages)!='undefined' && lastMsgAnchor && msgId && !edited) { // display message without refresh
    lastMsgAnchor.innerHTML='';
    var div=new Element('div', {'class':'msgEntry', id:'msg'+msgId, 'html':getInnerText(ok).stripScripts(true)});
    div.injectBefore(lastMsgAnchor);
    var mySlider=new Fx.Slide(div, {duration: 500}).hide();
    mySlider.slideIn();
    forumGotoMsg(msgId);
    return false;
  }
  // else reload page
  if (confirm("Сообщение "+(edited?"сохранено":"отправлено")+". Обновить страницу?")) {
    if ((window.location.pathname.substring(0,13)=="/t4/ForumPost" || window.location.pathname.substring(0,10)=="/t4/forum/") && forumId) {
      window.location='/t4/forum/'+encodeURIComponentWin1251(forumId)+'?goto='+msgId+'&rnd='+Math.round(Math.random()*1000000)+'#msg'+msgId;
    }
    else {
      window.location.reload(true);
    }
  }
}

function forumPostFailure(reqXHR) {
  var httpStatus=reqXHR.status;
  var errCode=0;
  try { errCode=parseInt(reqXHR.responseXML.documentElement.getAttribute("code")); }
  catch (e) {}
  if (httpStatus==409 && errCode==300) {
    alert("Введите, пожалуйста, имя и пароль");
    $('forumLogin').style.display="";
    $('forumLogin_userName').focus();
  }
  else if (httpStatus==409 && errCode==100) {
    alert("Введите, пожалуйста, код, указанный на картинке");
    $('forumCaptcha').style.display="";
    reloadCaptcha(true);
  }
  else if (httpStatus==409 && errCode==200) {
    alert("Введите, пожалуйста, текст сообщения");
    $('msgText').focus();
  }
  else if (httpStatus==409 && errCode==401) {
    alert("Введите, пожалуйста, название для новой темы");
    $('newTopic_title').focus();
  }
  else {
    alert("Отправить сообщение не удалось:\n"+reqXHR.statusText+"\n"+getInnerText(reqXHR.responseXML.documentElement));
  }
}

var forumPostReq=new Request({method:'post', url:'/t4/ForumPost', link:'cancel', encoding:'windows-1251', onSuccess:forumPostSuccess, onFailure:forumPostFailure});
//forumPostReq.addEvent('success', forumPostSuccess);
//forumPostReq.addEvent('failure', forumPostFailure);

function showLogin() {
  $('forumLogin').style.display="";
  $('forumLogin_userName').focus();
}

function reloadCaptcha(setFocus) {
  $('forumCaptcha_img').src="/t4/Captcha?skey="+$('forumCaptcha_skey').value+"&rnd="+Math.round(Math.random()*1000000);
  $('forumCaptcha_scode').value="";
  if (setFocus) $('forumCaptcha_scode').focus();
}

function forumGotoMsg(msgId) {
  var msg=forumMessages[''+msgId];
  if (msg) {
    window.location.hash='#msg'+msgId;
    return false;
  }
  return true;
}

function forumMsgClear() {
  forumMsgReset();
  msgArea=$('msgText');
  msgArea.value='';
  msgArea.focus();
}

function forumMsgReset() {
  var toolbar=$('wikiEditorToolbar').retrieve('ys.WikiEditorToolbar');
  if (toolbar) toolbar.hideOverlay();
  $('forumPostForm').elements['inReplyTo'].value='';
  $('forumPostForm').elements['editMsgId'].value='';
  $('msgTextTitle').innerHTML='Новое сообщение:';
}

function forumMsgEdit(msg, elm) {
  if (typeof(msg)!='object') msg=forumMessages[''+msg];
  $('forumPostForm').elements['inReplyTo'].value='';
  $('forumPostForm').elements['editMsgId'].value=msg.id;
  $('msgTextTitle').innerHTML='<b>Редактируем сообщение #'+msg.id+':</b> &nbsp;&nbsp;&nbsp;(<a href="#" onclick="forumMsgReset();return false;">Отменить</a>)';
  msgArea=$('msgText');
  msgArea.value='';
  msgArea.focus();
  msgArea.insertAtCursor(msg.msgText, false);
  return false;
}

function makeQuote(msg) {
  if (typeof(msg)!='object') msg=forumMessages[''+msg];
  //return '\n: **'+msg.senderTitle+' '+msg.dateSent+':**\n>\n'+msg.msgText.replace(/^/gm,">")+'\n\n';
  return '\n\n> **'+msg.senderTitle+' '+msg.dateSent+':**\\\\\n'+msg.msgText.replace(/^/gm,">")+'\n\n';
}

function forumMsgQuote(msg, elm) {
  if (typeof(msg)!='object') msg=forumMessages[''+msg];
  msgArea=$('msgText');
  msgArea.focus();
  msgArea.insertAtCursor(makeQuote(msg), false);
  return false;
}

function forumMsgReply(msg, elm) {
  if (typeof(msg)!='object') msg=forumMessages[''+msg];
  $('forumPostForm').elements['inReplyTo'].value=msg.id;
  $('forumPostForm').elements['editMsgId'].value='';
  $('msgTextTitle').innerHTML='<b>Ответ на сообщение #'+msg.id+' от '+escapeHTML(msg.senderTitle)+':</b> &nbsp;&nbsp;&nbsp;(<a href="#" onclick="forumMsgReset();return false;">Отменить</a>)';
  msgArea=$('msgText');
  msgArea.focus();
  msgArea.insertAtCursor(makeQuote(msg), false);
  return false;
}

function forumMsgSenderName(msg, elm) {
  if (typeof(msg)!='object') msg=forumMessages[''+msg];
  msgArea=$('msgText');
  msgArea.focus();
  msgArea.insertAtCursor('**'+msg.senderTitle+'**, ', false);
  return false;
}

function forumMsgComplain(msgId, elm) {
  //callServer("GET", '/t4/ForumComplain?id='+msgId, null, null, forumMsgComplainResponse, elm);
  var forumComplainReq=new Request({method:'get', url:'/t4/ForumComplain', link:'cancel', encoding:'windows-1251', onSuccess:forumMsgComplainResponse.bind(elm), onFailure:forumMsgComplainResponse.bind(elm)});
  forumComplainReq.send('id='+msgId);
  return false;
}

function forumMsgComplainResponse(responseText, responseXML) {
  // this = elm
  this.title=getInnerText(responseXML.documentElement);
  this.style.textDecoration='line-through';
}

function forumMsgComplainAll() {
  if (typeof(forumMessages)=='undefined') return;
  var list='', cnt=0;
  for (var msgId in forumMessages) {
    if (list!='') list+=',';
    list+=msgId;
    cnt++;
  }
  if (confirm("Пожаловаться на все сообщения ("+cnt+") данной страницы?\n["+list+"]")) {
    var forumComplainReq=new Request({method:'get', url:'/t4/ForumComplain', link:'cancel', encoding:'windows-1251'});
    forumComplainReq.send('id='+list);
  }
  return false;
}

function forumVote(elm, msgId, senderId) {
  var forumVoteReq=new Request({method:'get', url:'/t4/vote', link:'cancel', encoding:'windows-1251', onSuccess:forumMsgVoteResponse.bind(elm), onFailure:forumMsgVoteResponse.bind(elm)});
  forumVoteReq.send('item=fmsg'+senderId+'_'+msgId+'&vote=1');
  return false;
}

function forumMsgVoteResponse(responseText, responseXML) {
  // this = elm
  var elm=$(this);
  elm.title=responseXML?'Спасибо за ваш голос!':'';
  elm.removeClass('fmUserRatingPlus');
  elm.addClass('fmUserRatingPlusA');
}

function forumSubscribe(forumName, elm) {
  var forumSubscribeReq=new Request({method:'get', url:'/t4/Subscribe', link:'cancel', encoding:'windows-1251', onSuccess:forumSubscribeResponse.bind(elm), onFailure:forumSubscribeResponse.bind(elm)});
  forumSubscribeReq.send('tag=forum-topic:'+encodeURIComponentWin1251(forumName)+'&type=forum&mode=ajax');
  return false;
}

function forumUnsubscribe(subId, elm) {
  var forumSubscribeReq=new Request({method:'get', url:'/t4/Subscribe', link:'cancel', encoding:'windows-1251', onSuccess:forumSubscribeResponse.bind(elm), onFailure:forumSubscribeResponse.bind(elm)});
  forumSubscribeReq.send('unsubscribe='+subId+'&mode=ajax');
  return false;
}

function forumSubscribeResponse(responseText, responseXML) {
  // this = elm
  var elm=$(this);
  var newElm=new Element('span', {text:responseXML?getInnerText(responseXML.documentElement):'-',styles:{color:'#666'}});
  //elm.setStyle('color', '#666');
  newElm.replaces(elm);
}
