var last_cid = null;
var b_id,p_id,tt,tc;
var reload  = null;
var ccid,cquote_user,cquote,cmodify;
var content,global_content;
var advanceUser = false;
include("/board/js/discussion_config.js");

function submitTopic(board_id,cparent) {

   cparent = $('cid').value;

   tt=$('topictitle_main').value;

   if(tt.length == 0) tt='(沒有標題)';

   b_id    = board_id;
   p_id    = cparent;

   content = FCKeditorAPI.GetInstance('discussion_main').GetHTML();

   if($('captcha_text'))
      tc = $('captcha_text').value;
   customSave();
}

function checkIsDisplayCaptcha(cid,quote_user,quote,modify)
{
    ccid = cid ;
    cquote_user=quote_user;
    cquote = quote;
    cmodify = modify;
    new Ajax.Request(BOARD_P+'checkLogin.php',
           {method: 'get',
            onSuccess:checkIsDisplayCaptchaCallback });

}
function checkIsDisplayCaptchaCallback(t)
{
        resp = t.responseText;
        if (resp == "true"){
            showReplyForm(ccid,cquote_user,cquote,cmodify);
            Element.hide('captcha_div');}
        else{
            Element.show('captcha_div');
            showReplyForm(ccid,cquote_user,cquote,cmodify);}  
}
function showReplyForm(cid,quote_user,quote,modify) {
   if(!checkLoginAndReturn('javascript:checkIsDisplayCaptcha(\''+cid+'\',\''+quote_user+'\',\''+quote+'\',\''+modify+'\');'))
       return ; 
       
//   if (last_cid) hideReplyForm();
   last_cid = cid;

//   Element.hide('reply_'+cid);
   Element.hide('captcha_msg');

   $('reply_control_'+cid).insertBefore($('replyform_main'), $('reply_'+cid) );

/*
      $("sendmsg_subject").value = 'Re: '+$('message_subject').innerHTML;
      quote = $('message_content').innerHTML;
      for( depth = 0; depth < 2; depth++ ) quote = quote.replace(/<div class=\"quote\" author=\"([a-zA-Z][0-9a-zA-Z]+)\">/i,"[quote user_id=$1]");
      quote = quote.replace(/<\/div>/ig,"[/quote]");
      quote = quote.replace(/<div class=\"quote\"[^>]*>.*?\[\/quote\]/i,"");
      quote = quote.replace(/<span class=\"quote_info\"[^>]*>.*?<\/span>/i,"");
      $('sendmsg_msg').value = '[quote author='+to_id+']'+quote+'[/quote]';
*/
      if (quote =="true" || modify =="true"){//process quote or modify

      quotetext = $('description_'+cid).innerHTML;
      quotetext = quotetext.replace(/<p>(.*)<\/p>/ig,"$1");
      quotetext = quotetext.replace(/<div class=\"??quote_author\"??>.*?<\/div>/gi,"");
      for( depth = 0; depth < 2; depth++ ){
         quotetext = quotetext.replace(/<div class=\"??quote\"?? author=\"??([a-zA-Z][0-9a-zA-Z]+)\"??>/i,"[quote author=$1]");
         quotetext = quotetext.replace(/<\/div>/gi,"[/quote]");
        }
        if (modify =="false"){
          quotetext = quotetext.replace(/<div class=\"??quote\"?? author=\"??([a-zA-Z][0-9a-zA-Z]+)\"??>.*?\[\/quote\]/i,"");          
        }
        else
        {
         quotetext = quotetext.replace(/<div class=\"??quote\"?? author=\"??([a-zA-Z][0-9a-zA-Z]+)\"??>/i,"[quote author=$1]");
         quotetext = quotetext.replace(/<\/div>/i,"[/quote]");
        }

      var i = 0;
      var StartTimes = 0;
      while (i < quotetext.length)
      {
         i =quotetext.indexOf("[quote",i);
            if (i == -1)
            break;
         i += 6;
         StartTimes++;
      }

      
      i = 0;
      var EndTimes = 0; 
      while (i < quotetext.length)
      {
         i = quotetext.indexOf("[/quote]",i);
            if (i == -1)
            break;
         i += 8;
         EndTimes++;
      }

      if (StartTimes > EndTimes)
      {
         for (var i = EndTimes ; StartTimes > i ; i++)
         {
            quotetext += "[/quote]";
         }
      }
      else
      {
         for (var j = EndTimes ; StartTimes < j ; j--)
         {
             quotetext = quotetext.substring(0,i);
             while (i < quotetext.length)
             {
                i = quotetext.indexOf("[/quote]",i);
                if (i == -1)
                    break;
                    i += 8;
             }
         }
        }
      }
      if(modify =="false" && quote =="true"){
        global_content = '[quote author='+quote_user+']'+quotetext+'[/quote]';
        $('reply_title').innerHTML = REPLYING+quote_user;
        $('type').value = 0; // 0 means reply for someone
        $('cid').value = cid;
      }
      else if (modify =="true")
      {  
         reload = true;
         $('reply_title').innerHTML = MODIFYARTICLE;
         global_content = quotetext;
         $('type').value = 1;// 1 means modify
         $('cid').value = cid;
      }
      else
      {
            $('reply_title').innerHTML = (cid == 'newtopic') ?POSTNEWTOPIC:REPLYARTICLE;
            global_content = " ";
            $('type').value = 2;// 2 means reply for article or add New Topic
      }  

   PrepareEditor('discussion_main', 'topictext_main', global_content,300);
   if( cid == 'main' || cid == 'newtopic' )
      Element.addClassName( 'reply_title', 'replyheadingNewTopic' );
   else
      Element.addClassName( 'reply_title', 'replyheading' );

}
function showBoardForm() {
   Element.show('replyform_main');
   var editor = FCKeditorAPI.GetInstance('discussion_main');
   FCKeditorAPI.GetInstance('discussion_main').SetHTML(global_content);
   Element.focusTo('replyform_main');
   editor.Focus();
}
function hideReplyForm() {
   Element.hide('replyform_main');
   Element.removeClassName('reply_title', 'replyheadingNewTopic' );
   Element.removeClassName('reply_title', 'replyheading' );
   // show the current reply link, hide form, clear text
   if ( last_cid == 'main' ) {
      if( !Element.empty('topics') )
         Element.show('reply_'+last_cid);
   } else if( last_cid == 'newtopic' ) {
       Element.show('reply_'+last_cid);
   } else {
      //new Effect.BlindUp('replyform_'+cid);
      if (Element.visible('topic_con_'+last_cid)) Element.show('reply_'+last_cid);
   }
   FCKeditorAPI.GetInstance('discussion_main').SetHTML('');
}

function postTopic(title, message, board_id, cparent, code,type,cid) {
	new Ajax.Request(BOARD_P+'DoPostTopic.php', 
		{ method: 'post',
		  parameters: 'title='+encodeURIComponent(title)+
		              '&message='+encodeURIComponent(message)+
                    '&board_id='+encodeURIComponent(board_id)+
		              '&cparent='+encodeURIComponent(cparent)+
		              '&user_code='+encodeURIComponent(code)+
                    '&type='+encodeURIComponent(type)+
                    '&cid='+encodeURIComponent(cid),
		  onSuccess: postTopicCallback });
}

function postTopicCallback(t) {
	resp = t.responseText;

   try {
     rsobj = eval( '(' + resp + ')' );
   } catch (e) {
     getAlertBox(resp);
     funpDlg.show('alertBox');
     return;
   }
	$('captcha_img').src = PUSH_P+'comment/captcha.php?r='+Math.random();
	$('captcha_text').value = '';
   if (resp.length == 0)
   {
      location.reload();
   }
	if (rsobj.success == 1) 
   {
/*
		hideReplyForm();

      if( last_cid == 'newtopic'||reload) {
         location.reload();
      } else {
		   new Insertion.Bottom('topics', resp);
		   Element.hide('captcha_msg');
      }
*/
      location.reload();
	} 
   else 
   {
		Element.show('captcha_msg');
	}
}

function customSave() {
	
   if (content.length == 0) {
      getAlertBox(MESSAGE_INPUT);
      funpDlg.show('alertBox');
      return;
   }

   if (tc.length == 0 && !advanceUser){
      getAlertBox(CAPTCHA_INPUT);
      funpDlg.show('alertBox');
      return;
   }
   postTopic(tt, content, b_id, p_id,tc,$('type').value,$('cid').value);
}
function deleteTopic(topic_id, thread)
{   
  params = 'topic_id=' + topic_id;
  params += '&thread=' + ( thread==1 ? 1 : 0);
  params += '&user_code=' +$("user_code").value;

  new Ajax.Request( BOARD_P+'DoDelTopic.ajax.php?'+params,
    {
      method: 'get',
      onSuccess:  function(rs)
      {
        resp=rs.responseText;
        try {
          rsobj = eval( '(' + resp + ')' );
        } catch (e) {
          getAlertBox(resp);
          funpDlg.show('alertBox');
          return;
        }
         
        if(rsobj.success == 1)
        {
          location.reload();
        }
        else
        {
  	  $('captcha_img_'+topic_id).src = PUSH_P+'comment/captcha.php?r='+Math.random();
	  $('user_code').value = '';
          Element.show('errcaptcha');
        }
      }  
    }    
  );     
}

function DeletePostTopic(cid,type) {
	new Ajax.Request(BOARD_P+'DeleteTopic.php', 
		 {method: 'get',
		  parameters:'cid='+encodeURIComponent(cid)+
                   '&type='+encodeURIComponent(type),
		  onSuccess: postTopicCallback });
}
/* forums */
function fetchBoard(board_id, mode, page, user, keyword, extra_param)
{
  params = 'board_id=' + board_id;
  params += '&mode=' + mode;         // 0 is tree mode, 1 is listing mode
  params += '&board_page=' + (page ? page : 1);

  script=location.href;
  x=location.href.indexOf("/");
  end=location.href.indexOf("?");
  if(end==-1) end = location.href.length;
  for(;x!=-1;)
  {
    script=script.substring(x+1, end);
    x=script.indexOf("/");
  }
  
  params += '&script=' + script;
  if(extra_param.length>0) params += extra_param;
  
  if( user.length ) params += '&user=' + user;
  if( keyword.length>0 ) params += '&keyword=' + keyword;
  
  if(board_id)
  new Ajax.Request( BOARD_P+'fetchBoard.ajax.php?'+params,
    {
      method: 'get',
      onSuccess:  function(rs)
      {
        resp=rs.responseText;
        try {
          rsobj = eval( '(' + resp + ')' );
        } catch (e) {
          getAlertBox(resp);
          funpDlg.show('alertBox');
          return;
        }
         
        if(rsobj.success == 1)
        {
          Element.update("forums_form", rsobj.output);
        }
      }  
    }    
  );     
}        

function fetchTopicThread(topic_id, page, board_page)
{
  params = 'topic_id=' + topic_id;
  params += '&page=' + (page ? page : 1);
  params += '&board_page=' + (board_page ? board_page : 1);

  new Ajax.Request( BOARD_P+'fetchTopicThread.ajax.php?'+params,
    {
      method: 'get',
      onSuccess:  function(rs)
      {
        resp=rs.responseText;
        try {
          rsobj = eval( '(' + resp + ')' );
        } catch (e) {
          getAlertBox(resp);
          funpDlg.show('alertBox');
          return;
        }
         
        if(rsobj.success == 1)
        {
          Element.update("forums_form", rsobj.output);
        }
      }  
    }    
  );     

}

function view_thread(topic_id, ajax, board_page)
{
  if(ajax)
  {
    new Ajax.Request( BOARD_P+'fetchTopicThread.ajax.php?topic_id='+topic_id+'&page=1&board_page='+board_page,
      {
        method: 'get',
        onSuccess:  function(rs)
        {
          resp=rs.responseText;
          try {
            rsobj = eval( '(' + resp + ')' );
          } catch (e) {
            getAlertBox(resp);
            funpDlg.show('alertBox');
            return;
          }
         
          if(rsobj.success == 1)
          {
            Element.update("forums_form", rsobj.output);
          }
        }  
      }    
    );     
  }
  else
  {
    pos=location.href.indexOf("&topic_id=");

    if( pos == -1)
    {
      location += "&topic_id="+topic_id;
    }
    else
    {
      prefix=location.href.substring(0, pos);
      s=location.href.substring(pos+1, location.href.length);
      x=s.indexOf("&");

      suffix="";
      if(x!=-1) suffix=s.substring(x, s.length);

      location=prefix + suffix + '&topic_id=' + topic_id;
    }
  }
}

function view_topic(topic_id, mode)
{
  new Ajax.Request( BOARD_P+'fetchTopic.ajax.php?topic_id='+topic_id+'&mode='+mode,
    {
      method: 'get',
      onSuccess:  function(rs)
      {
        resp=rs.responseText;
        try {
          rsobj = eval( '(' + resp + ')' );
        } catch (e) {
          getAlertBox(resp);
          funpDlg.show('alertBox');
          return;
        }
         
        if(rsobj.success == 1)
        {
          Element.update("topicview_"+topic_id, rsobj.output);
        }
      }  
    }    
  );     
}

function close_thread(topic_id, page)
{
  if(page==0)
  {
    new Ajax.Request( BOARD_P+'fetchTopic.ajax.php?close=1&topic_id='+topic_id,
      {
        method: 'get',
        onSuccess:  function(rs)
        {
          resp=rs.responseText;
          try {
            rsobj = eval( '(' + resp + ')' );
          } catch (e) {
            getAlertBox(resp);
            funpDlg.show('alertBox');
            return;
          }
         
          if(rsobj.success == 1)
          {
            Element.update("topiclist_"+topic_id, rsobj.output);
          }
        }  
      }    
    );     
  }
  else
  {
    board_id=topic_id;
    fetchBoard(board_id, 0, page, '', ''); 
  }
}

function setTopicOnTop(topic_id, ontop)
{
  params = 'topic_id=' + topic_id;
  params += '&ontop=' + ( $("ontop_control").value==1 ? 0 : 1 );

  new Ajax.Request
  ( BOARD_P+'setTopicOnTop.ajax.php?'+params,
    {
      method: 'get',
      onSuccess:  function(rs)
      {
        resp=rs.responseText;
        try {
          rsobj = eval( '(' + resp + ')' );
        } catch (e) {
          getAlertBox(resp);
          funpDlg.show('alertBox');
          return;
        }
       
        if(rsobj.success == 1)
        {
          msg= '主題已' + (rsobj.ontop == 1 ? '設定' : '取消' )+ '置頂';
//          $('ontop_'+topic_id).checked = rsobj.ontop==1 ? true : false;
          if(rsobj.ontop==1)
          {
            $("ontopBtn").addClassName("ontopBtn");
            $("ontopBtn").addClassName("ontopBtn_pressed");
          }
          else
          {
            $("ontopBtn").removeClassName("ontopBtn_pressed");
            $("ontopBtn").addClassName("ontopBtn");
          }
            
          $("ontop_control").value=rsobj.ontop;
          getAlertBox(msg);
          
          funpDlg.show('alertBox');
        }
      }  
    }    
  );     
}

function setTopicReadOnly(topic_id)
{
  params = 'topic_id=' + topic_id;
  params += '&ro=' + ( $("ro_control").value==1 ? 0 : 1 );

  new Ajax.Request
  ( BOARD_P+'setTopicReadOnly.ajax.php?'+params,
    {
      method: 'get',
      onSuccess:  function(rs)
      {
        resp=rs.responseText;
        try {
          rsobj = eval( '(' + resp + ')' );
        } catch (e) {
          getAlertBox(resp);
          funpDlg.show('alertBox');
          return;
        }
       
        if(rsobj.success == 1)
        {
          msg= '主題已' + (rsobj.ro == 1 ? '設定' : '取消' )+ '唯讀';
//          $('ro_'+topic_id).checked = rsobj.ro==1 ? true : false;
          if(rsobj.ro==1)
          {
            $("roBtn").addClassName("roBtn");
            $("roBtn").addClassName("roBtn_pressed");
          }
          else
          {
            $("roBtn").removeClassName("roBtn_pressed");
            $("roBtn").addClassName("roBtn");
          }
            
          $("ro_control").value=rsobj.ro;
          getAlertBox(msg);
          
          funpDlg.show('alertBox');
          location.reload();
        }
      }  
    }    
  );     
}

function confirmDelete(id, thread)
{
  getConfirmDeleteTopicBox(id, thread);
  funpDlg.show('confirmDeleteTopicBox');
}

