/*
  TwitterFeed plugin
  (P) PSNet, 2008 - 2011
  http://psnet.lookformp3.net/
*/

var TTwitterFeed = new Class ({

  Options: {
    NavClass: 'block-nav',
    ActiveClass: 'active',
    Content: 'block-content',
  },

  ShowTweets: function (TThisA) {
    var LICurrent = $ (TThisA).getParent ('li');
    var ULBlockNav = LICurrent.getParent ('ul.' + this.Options.NavClass);
    var LIAllList = ULBlockNav.getChildren ('li');

    for (ic = 0; ic < LIAllList.length; ic ++) {
      LIAllList [ic].removeClass (this.Options.ActiveClass);
    }

    LICurrent.addClass (this.Options.ActiveClass);

    var TCurBlockContent = ULBlockNav.getParent ('div').getChildren ('div.' + this.Options.Content) [0].set ('html', '');

    this.LoadingData (TCurBlockContent);
    this.GetTweets (TCurBlockContent);
  },
  
  LoadingData: function (TCurBlockContent) {
    var newDiv = new Element ('div');
    newDiv.setStyle ('text-align', 'center');
    newDiv.set ('html', '<img src="' + DIR_STATIC_SKIN + '/images/loader.gif" alt=" ">');
    newDiv.inject (TCurBlockContent);
  },
  
  GetTweets: function (TCurBlockContent) {
    TThisTwitterObj = this;
    var myTwitterRequest = new Request.JSONP ({
      url: 'http://twitter.com/statuses/user_timeline/' + TwitterFeed_UserName + '.json',
      data: {
        count: TwitterFeed_TweetsCount
      },
      noCache: true,
      onComplete: function (TweetsData) {
        TThisTwitterObj.ParseTwitterAnswerAndShowData (TweetsData, TCurBlockContent);
      }
      }).send ();
  },
  
  ParseTwitterAnswerAndShowData: function (TweetsData, TCurBlockContent) {
    TCurBlockContent.empty ();
    for (ic = 0; ic < TweetsData.length; ic ++) {
      if (TwitterFeed_MakeURLsLive) {
        TweetsData [ic].text = this.MakeAllURLsAlive (TweetsData [ic].text);
      }
      var NewTmpElement = new Element ('div', {
        'html': '<p>' + TweetsData [ic].text + '</p>', 'class': 'OneTweet' + (ic % 2 == 0 ? ' Second' : '')
      }).injectInside (TCurBlockContent);
    }
    // add footer link to twitter after all process
    this.AddTwitterLinks (TCurBlockContent);
  },
  
  AddTwitterLinks: function (TCurBlockContent) {
    var newDiv = new Element ('div');
    newDiv.set ('class', 'TwitterFeedFooterLink');
    newDiv.set ('html', '<a href="http://twitter.com/' + TwitterFeed_UserName + '">' + TwitterFeed_GoToTwitter + '</a>');
    newDiv.inject (TCurBlockContent);
  },
  
  MakeAllURLsAlive: function (TCurTweet) {
    return TCurTweet.replace (/(https?:\/\/\S+)/gi, '<a href="$1">$1</a>')
                     .replace (/(^|\s)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
                     .replace (/(^|\s)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
  }

});

