/*
  TwitterFeed plugin
  (P) PSNet, 2008 - 2011
  http://psnet.lookformp3.net/
*/

var ls = ls || {};

ls.twitterfeed = (function ($) {

  this.ShowTweets = function (ThisLIElement) {
    var ULBlockNav = $ (ThisLIElement).parent ('ul');
    var LIAllList = ULBlockNav.children ('li');

    LIAllList.map (function () {
      $ (this).removeClass (ls.blocks.options.active);
    });

    $ (ThisLIElement).addClass (ls.blocks.options.active);

    var TCurBlockContent = ULBlockNav.parent ('div').children ('div#block_stream_content').empty ();

    this.ShowProgress (TCurBlockContent);
    this.GetTweets (TCurBlockContent);
  }
  
  // ---
  
  this.ShowProgress = function (TCurBlockContent) {
    TCurBlockContent.html ($ ('<div />').css ('text-align', 'center').append ($ ('<img>', {src: ls.blocks.options.loader})));
  }
  
  // ---
  
  this.GetTweets = function (TCurBlockContent) {
    $.ajax ({
      url: 'http://api.twitter.com/1/statuses/user_timeline.json?callback=?&screen_name=' + TwitterFeed_UserName,
      data: { count: TwitterFeed_TweetsCount },
      dataType: 'json',
      success: function (TweetsData) {
        ls.twitterfeed.ParseTwitterAnswerAndShowData (TweetsData, TCurBlockContent);
      }
    });
  }
  
  // ---
  
  this.ParseTwitterAnswerAndShowData = function (TweetsData, TCurBlockContent) {
    TCurBlockContent.empty ();

    TweetsData.map (function (o, ic) {
      if (TwitterFeed_MakeURLsLive) {
        o.text = ls.twitterfeed.MakeAllURLsAlive (o.text);
      }

      TCurBlockContent.append ( $ ('<div />', {
        'html' : '<p>' + o.text + '</p>',
        'class': 'OneTweet' + (ic % 2 == 0 ? ' Second' : '')
      }));
    });
    
    // add footer link to twitter after all process
    this.AddTwitterLinks (TCurBlockContent);
  }
  
  // ---
  
  this.AddTwitterLinks = function (TCurBlockContent) {
    TCurBlockContent.append ($ ('<div />', {
      'html': '<a href="http://twitter.com/' + TwitterFeed_UserName + '">' + TwitterFeed_GoToTwitter + '</a>',
      'class': 'TwitterFeedFooterLink'
    }));
  }
  
  // ---
  
  this.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>');
  }
  
  // ---

	return this;
	
}).call (ls.twitterfeed || {}, jQuery);

