var php_path = '/livebbs/';

var AjahBBS = Class.create();
AjahBBS.prototype = {
  initialize: function(){
    this.Effecting = false;
    this.currentStart = '';
    Element.hide('new-thread');
    this.hashChecker = new GSHashChecker( 500, this.onChangeHash.bind( this ) );
  },

  loadData: function( aStartNo )
  {
    AjahBBS.setStatus( 'ロード中' );
    var startNo = '';
    if( aStartNo )
    {
      if( aStartNo == 'c' && this.currentStart != '' )
      {
        startNo = this.currentStart;
      }
      else
      {
        startNo = aStartNo;
      }
    }
    var query = 'start_no=' + startNo;
    this.currentStart = startNo;
    this.hashChecker.setHash( startNo );
    var ajax = new Ajax.Request( php_path + 'threads.php', {method: 'get', parameters: query, onComplete: this.updateData.bind( this ), requestHeaders: ['If-Modified-Since','01 Jan 1970 00:00:00 GMT'] } );
  },
  
  updateData: function( req )
  {
    AjahBBS.clearStatus();
    window.scroll(0, 0);
    $( 'bbs-data' ).innerHTML = req.responseText;
  },
  
  onChangeHash: function( aHash )
  {
    this.loadData( aHash );
  },

  switchCommentForm: function( threadId )
  {
    if( this.Effecting == true )
    {
      return;
    }
    this.Effecting = true;
    if( $( 'reply-content-' + threadId ).innerHTML == '' )
    {
      this.loadingFormThreadId = threadId;
      AjahBBS.setStatus( 'ロード中' );
      var query = 'threadid=' + threadId;
      var ajax = new Ajax.Request( php_path + 'comment_form.php', { method: 'get', parameters: query, requestHeaders: ['If-Modified-Since','01 Jan 1970 00:00:00 GMT'], onComplete: this.onLoadCommentForm.bind( this ) } );
    }
    else if( Element.visible( 'reply-' + threadId ) == false )
    {
      this.openCommentForm( threadId );
    }
    else
    {
      this.closeCommentForm( threadId );
    }
  },

  onLoadCommentForm: function( req )
  {
    AjahBBS.clearStatus();
    $( 'reply-content-' + this.loadingFormThreadId ).innerHTML = req.responseText;
    this.openCommentForm( this.loadingFormThreadId );
  },

  openCommentForm: function( threadId )
  {
    $( 'link-reply-thread-' + threadId ).innerHTML = '[コメント欄を閉じる]';
    Effect.SlideDown( 'reply-' + threadId, { duration: 0.4, afterFinish: this.onFinishEffect.bind( this ) } );
  },

  closeCommentForm: function( threadId )
  {
    Effect.SlideUp( 'reply-' + threadId, { duration: 0.4, afterFinish: this.onFinishEffect.bind( this ) } );
    $( 'link-reply-thread-' + threadId ).innerHTML = '[このスレッドにコメント]';
  },

  onFinishEffect: function(){
    this.Effecting = false;
  },
  
  switchNewThread: function()
  {
    if( this.Effecting == true )
    {
      return;
    }

    this.Effecting = true;
    if( $( 'new-thread' ).innerHTML == '' )
    {
      new Ajax.Request( php_path + 'comment_form.php', { method: 'get', parameters: 'threadid=n', onComplete: this.onGetNewThreadForm.bind( this ) } );
    }
    else
    {
      if( Element.visible( 'new-thread' ) )
      {
        $('link-form-visible').innerHTML = '[新しい書き込み]';
        Effect.SlideUp( 'new-thread', { duration: 0.4, afterFinish: this.onSwitchNewThread.bind( this ) } );
      }
      else
      {
        AjahBBS.clearFormError('n');
        $('link-form-visible').innerHTML = '[書き込み欄を閉じる]';
        Effect.SlideDown( 'new-thread', { duration: 0.4, afterFinish: this.onSwitchNewThread.bind( this ) } );
      }
    }
  },
  
  onGetNewThreadForm: function( req )
  {
    $( 'new-thread' ).innerHTML = req.responseText;
    this.Effecting = false;
    this.switchNewThread();
  },

  onSwitchNewThread: function()
  {
    this.Effecting = false;
  }
  
};

AjahBBS.setStatus = function( aText )
{
    var y = 10;
    if( window.pageYOffset )
    {
        y += window.pageYOffset;
    }
    else if( document.body.scrollTop )
    {
        y += document.body.scrollTop;
    }
    $( 'status' ).style.top = y + 'px';
    $( 'status' ).innerHTML = aText;
    $( 'status' ).style.display = 'block';
}

AjahBBS.clearForm = function( aForm )
{
    Field.clear( aForm.title, aForm.data );
    if( ! aForm.rememberme.checked )
    {
      Field.clear( aForm.name, aForm.mail, aForm.url );
    }
}

AjahBBS.clearFormError = function( aSuffix )
{
    $( 'nameError' + aSuffix ).innerHTML = '';
    $( 'mailError' + aSuffix ).innerHTML = '';
    $( 'urlError' + aSuffix ).innerHTML = '';
    $( 'dataError' + aSuffix ).innerHTML = '';
}

AjahBBS.clearStatus = function()
{
    $( 'status' ).style.display = 'none';
    $( 'status' ).innerHTML = '';
}



var AjahBBSFormPoster = Class.create();
AjahBBSFormPoster.prototype = {
  initialize: function( aAjahBBS, aUrl, aForm, aSuffix )
  {
    this.threadId = aForm.threadid.value;
    $( 'comment-submit-' + this.threadId ).disbled = true;
    $( 'comment-reset-' + this.threadId ).disbled = true;
    
  	this.ajahBBS = aAjahBBS;
    this.form = aForm;
    this.suffix = aSuffix;
    if( this.validate() == true )
    {
      var title = aForm.title.value || 'no title';
      var dataLines = new String( aForm.data.value ).split("\n", 4);
      var limit = Math.min( dataLines.length, 3 );
      var previewData = '';
      for( var i = 0; i < limit; i++ )
      {
        previewData += dataLines[i] + "\n";
      }
      if( dataLines.length > i )
      {
        previewData += '...';
      }
      if( window.confirm( "以下の内容で書き込みを行います。よろしいですか？\n\n" + "名前:" + aForm.name.value + "\n" + "タイトル:" + title + "\n内容:\n" + previewData ) )
      {
        AjahBBS.setStatus('書き込み中');
        var query = Form.serialize( aForm );
        new Ajax.Request( aUrl, { method: 'post', postBody: query, onComplete: this.onComplete.bind( this ) }  );
      }
    }
  },
  
  validate: function()
  {
    AjahBBS.clearFormError( this.suffix );
    var result = true;
    if( this.form.name.value == '' )
    {
        $( 'nameError' + this.suffix ).innerHTML = '名前を入力してください。';
        result = false;
    }

    if( this.form.mail.value != '' )
    {
        var mailStr = new String(this.form.mail.value);
        var mailMatch = mailStr.match(/[a-zA-Z0-9_-]+(@)[a-zA-Z0-9_-]+(\.)[a-zA-Z]+((\.)[a-zA-Z]+)?/);
        if( ! mailMatch  || mailStr.length != mailMatch[0].length )
        {
          $( 'mailError' + this.suffix ).innerHTML = '正しいメールアドレスを入力してください。';
          result = false;
        }
    }

    if( this.form.url.value != '' && this.form.url.value != 'http://' )
    {
      var urlStr = new String(this.form.url.value);
      var urlMatch = urlStr.match(/s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:@&=+$,%#]+/);  // c.f. http://www.din.or.jp/~ohzaki/perl.htm#URI
      if( ! urlMatch || urlStr.length != urlMatch[0].length )
      {
          $( 'urlError' + this.suffix ).innerHTML = '正しい URLを入力してください。'; 
          result = false;
      }
    }

    if( this.form.data.value == '' )
    {
        $( 'dataError' + this.suffix ).innerHTML = '記事を入力してください。';
        result = false;
    }

    return result;  
  },
  
  onComplete: function( req )
  {
    if( req.responseText == 'success writing.' )
    {
      AjahBBS.clearForm( this.form );
      if( this.threadId = 'n' )
      {
        this.ajahBBS.loadData();
      }
      else
      {
        this.ajahBBS.loadData( 'c' );
      }
    }
    else
    {
      alert( req.responseText );
    }
    this.ajahBBS = null;
  }
};

var gAjahBBS;
function main()
{
  gAjahBBS = new AjahBBS();
  gAjahBBS.loadData();
}
