var last_cid = null;
var p_id = -1;
include(PUSH_P+"js/push_config.js");

function showCommentForm() {
   FCKeditorAPI.GetInstance('commenttext_main').Focus();
   FCKeditorAPI.GetInstance('commenttext_main').SetHTML('');
}

function showReplyForm(cid,form_title) {
   if(!isUserLogined && !isVirtualUserLogined){
      checkLogin("javascript:showReplyForm('"+cid+"','"+form_title+"');");
      return;
   }

   // hide last shown form if exists
   if (last_cid) hideReplyForm();
   last_cid = cid;
   Element.hide('reply_'+cid);
   $('reply_'+cid).insert({'before': $('replyform_main')});
   PrepareEditor( 'commenttext_main', 'commenttext_main_container', '' );
   
   $('reply_title').innerHTML = form_title;
   if( cid == 'main' )
      Element.addClassName( 'reply_title', 'replyheadingNewTopic' );
   else
      Element.addClassName( 'reply_title', 'replyheading' );
   Element.show('replyform_main');
   Element.focusTo('replyform_main');
}

function hideReplyForm() {
   Element.hide('replyform_main');
   $('comment_captcha_text').value ='';
   Element.hide('comment_captcha_msg');
   Element.removeClassName('reply_title', 'replyheadingNewTopic' );
   Element.removeClassName('reply_title', 'replyheading' );
   // show the current reply link, hide form, clear text
   if ( last_cid != 'main' ) {
      //new Effect.BlindUp('replyform_'+cid);
      if (Element.visible('commentcon_'+last_cid)) Element.show('reply_'+last_cid);
   } else {
      //new Effect.BlindUp('commentform_main');
      if( !Element.empty('comments') ) Element.show('reply_'+last_cid);
   }
//   Element.update("commenttext_main_container", "" );
}

function PrepareCommentEditor(cid,form_title) {
   PrepareEditor( 'commenttext_main', 'commenttext_main_container', '' );
   Element.show('replyform_main');
   Element.focusTo('replyform_main');
}

var cur_cparent;
var cur_pid;

function postComment(content) {

   if( $('commentSubmitBtn') )
      $('commentSubmitBtn').disabled = true;

   new Ajax.Request(PUSH_P+'comment/DoPostComment.php', 
      { method: 'post',
        parameters: 'pid='+encodeURIComponent(p_id)+
                    '&commenttext='+encodeURIComponent(content)+
                    '&cparent='+encodeURIComponent(last_cid)+
                    '&user_code='+encodeURIComponent($F('comment_captcha_text'))+
                    '&autotrack='+encodeURIComponent($('track_main').checked), 
        onSuccess: postCommentCallback });
   cur_cparent = last_cid;
   cur_pid = p_id;
}

function postComment_by_url(content, id, pw, url_id) {

   if( $('commentSubmitBtn') )
      $('commentSubmitBtn').disabled = true;

   new Ajax.Request(PUSH_P+'comment/DoPostComment.php', 
      { method: 'post',
        parameters: 'username='+encodeURIComponent(id)+'&password='+encodeURIComponent(pw)+'&url_id='+encodeURIComponent(url_id)+'&pid='+encodeURIComponent(p_id)+
                    '&commenttext='+encodeURIComponent(content)+
                    '&cparent='+encodeURIComponent(last_cid)+
                    '&user_code='+encodeURIComponent($F('comment_captcha_text'))+
                    '&autotrack='+encodeURIComponent($('track_main').checked), 
        onSuccess: postCommentCallback });
   cur_cparent = last_cid;
   cur_pid = p_id;
}

function postCommentCallback(t) {

   if( $('commentSubmitBtn') )
      $('commentSubmitBtn').disabled = false;

   $('comment_captcha_img').src = PUSH_P+'comment/captcha.php?r='+Math.random();
   $('comment_captcha_text').value = '';
   
   rsobj = ej(t.responseText); 
   if( $('comment_dialog') ) {   // post in comment dialog
      if( rsobj.res == 'ok' ) {   
         funpDlg.close();
         
         showAlertBox('新增文章討論完成');
         eles = document.getElementsByClassName('uncomment_'+cur_pid);
         for( i=0; i<eles.length; i++){
            eles[i].innerHTML = '1';
            eles[i].setAttribute('href', '/t' + cur_pid);
            eles[i].removeClassName('uncomment_'+cur_pid);
         }
      } else {
         if( rsobj.type == 'block_post' ){
            funpDlg.close();
            showAlertBox( rsobj.block_reason );
         }else if( rsobj.type == 'error_captcha'){   
            Element.show('comment_captcha_msg');
         }
      }
   } else {    // post in comment page
      if( rsobj.res == 'ok' ) {        
         hideReplyForm();
         if (cur_cparent == 'main') {
            $('comments').insert({'bottom': rsobj.html});
            $('commenttext_main').value = '';
            Element.show('reply_main');
         } else {
            $('reply_main').insert({'before':$('replyform_main')});
            Element.update('thread_'+cur_cparent, rsobj.html);
            FCKeditorAPI.GetInstance('commenttext_main').SetHTML('');
         }
         Element.hide('comment_captcha_msg');
         Element.show('comments');
      } else {
         if( rsobj.type == 'block_post' ){
            hideReplyForm();
            showAlertBox( rsobj.block_reason );
         }else if( rsobj.type == 'error_captcha'){   
            Element.show('comment_captcha_msg');
         }
      }  
   }
}

function kickComment(cid, amount) {
   if(!checkLoginAndReturn("javascript:kickComment('"+cid+"',"+amount+");"))
        return;
   new Ajax.Request(PUSH_P+'comment/kick.ajax.php', 
      { method: 'post',
        postBody: 'pid='+p_id+'&cid='+cid+'&amount='+amount, 
        onSuccess: kickCommentCallback });
}

function kickCommentCallback(t) {
   resp = t.responseText;
   if (resp != 'fail') {
      rsobj = ej(resp);
      Element.update('score_'+rsobj.cid, rsobj.score);
      Element.removeClassName('minus_'+rsobj.cid, 'buttonPlugin');
      Element.addClassName('minus_'+rsobj.cid, 'buttonPlugin_press');
      $('minus_'+rsobj.cid).removeAttribute('href');
      Element.removeClassName('plus_'+rsobj.cid, 'buttonPlugin');
      Element.addClassName('plus_'+rsobj.cid, 'buttonPlugin_press');
      $('plus_'+rsobj.cid).removeAttribute('href');
   }
}

function toggleComment(cid) {
   if (Element.visible('commentcon_'+cid)) {
      Element.hide('commentcon_'+cid);
      Element.hide('commentScore_'+cid);
      Element.addClassName('commentdesc_'+cid,'collapsed');
      Element.removeClassName('exp_'+cid, 'minusBtn');
      Element.addClassName('exp_'+cid, 'plusBtn');
      if ($('reply_'+cid)) Element.hide('reply_'+cid);
   } else {
      Element.show('commentcon_'+cid);
      Element.show('commentScore_'+cid);
      Element.removeClassName('commentdesc_'+cid,'collapsed');
      if ($('reply_'+cid)) Element.show('reply_'+cid);
      Element.removeClassName('exp_'+cid, 'plusBtn');
      Element.addClassName('exp_'+cid, 'minusBtn');
   }
}

function savecomment() {
   editor = FCKeditorAPI.GetInstance('commenttext_main');
   var content = editor.GetHTML();
   //ta = document.getElementById("commenttext_"+last_cid);
   tc = document.getElementById("comment_captcha_text");
   if (tc.value.length == 0) {
      alert(INPUT_CAPTCHA);
      return;
   }
   if (content.length == 0) {
      alert(INPUT_CONTAIN);
      return;
   }
   postComment(content);
}

function login_and_savecomment(uid) {
   id=pw=0;
   editor = FCKeditorAPI.GetInstance('commenttext_main');
   var content = editor.GetHTML();
   //ta = document.getElementById("commenttext_"+last_cid);
   tc = document.getElementById("comment_captcha_text");
   if(uid < 0) {
     page_id = document.getElementById("page_id");
     page_pw = document.getElementById("page_password");
     if (page_id.value.length == 0) {
        alert('請輸入帳號');
        return;
     }
     id=page_id.value;
     if (page_pw.value.length == 0) {
        alert('請輸入密碼');
        return;
     }
     pw=page_pw.value;
   }
   if (tc.value.length == 0) {
      alert(INPUT_CAPTCHA);
      return;
   }
   if (content.length == 0) {
      alert(INPUT_CONTAIN);
      return;
   }
   postComment_by_url(content, id, pw, url_id);
   Element.show('comments');
}

function showCommentDialog(thispid) {
   last_cid = 'main'; // in order to fit the comment page architecture
   p_id = thispid;
   getCommentDialog();
   PrepareEditor( 'commenttext_main', 'commenttext_main_container', '' );
   funpDlg.show('comment_dialog');
}

function closeCommentDialog() {
//   tinyMCE.execCommand( 'mceRemoveControl', false, 'commenttext_main' );
}

function getCommentDialog(){
   funpDlg.beforeClose = closeCommentDialog;
   pd=$('comment_dialog');
   if(pd) return pd;
head = '        <form id="comment_form" onSubmit="savecomment(); return false;">';
msg =
staticField('內容','<div id="commenttext_main_container" height="150"></div>')+
'<div style="margin-left:130px;text-align:left;">請遵守<a target="_blank" title="文章留言規章" href="http://help.funp.com/doku.php/funp/push/comment/rule">文章留言規章</a></div>'+
staticField('認證碼','<img src="'+PUSH_P+'comment/captcha.php?r='+Math.round(Math.random()*100000)+'" id="comment_captcha_img">')+
staticField('請輸入認證碼','<input type="text" name="user_code" id="comment_captcha_text" class="quarterLength" autocomplete="off"/><span id="comment_captcha_msg" style="margin-left:20px; display:none; color:red">'+INPUT_WRONG_CAPTCHA+'</span>')+
staticField('自動追蹤討論','<input type="checkbox" id="track_main" checked="true"/>')
;
btns =
'                        <input type="submit" class="positive" id="comment_submitBtn" value="送出">'+
'                        <input type="button" class="negtive" id="comment_cancelBtn" onclick="funpDlg.close()" value="取消">';
  new Insertion.Bottom(document.body, getWideDialogBox('comment_dialog',16,msg,btns,head,'</form>') );
  return $('comment_dialog');
}
