﻿(function ($) {

  $.fn.tweet = function (o) {
    var s = {
      username: ["kalou"],              // [string]   required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"]
      list: null,                              //[string]   optional name of list belonging to username
      avatar_size: null,                      // [integer]  height and width of avatar if displayed (48px max)
      count: 2,                               // [integer]  how many tweets to display?
      intro_text: null,                       // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                       // [string]   do you want text AFTER your tweets?
      join_text: null,                       // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "i said,",      // [string]   auto text for non verb: "i said" bullocks
      auto_join_text_ed: "i",                 // [string]   auto text for past tense: "i" surfed
      auto_join_text_ing: "i am",             // [string]   auto tense for present tense: "i was" surfing
      auto_join_text_reply: "i replied to",   // [string]   auto tense for replies: "i replied to" @someone "with"
      auto_join_text_url: "i was looking at", // [string]   auto tense for urls: "i was looking at" http:...
      loading_text: null,                     // [string]   optional loading text, displayed while tweets load
      query: null,                            // [string]   optional search query
      refresh_interval: null                  // [integer]  optional number of seconds after which to reload tweets
    };

    if (o) $.extend(s, o);

    $.fn.extend({
      linkUrl: function () {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function () {
          returning.push(this.replace(regexp, "<a href=\"$1\" target=\"_blank\">$1</a>"));
        });
        return $(returning);
      },
      linkUser: function () {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function () {
          returning.push(this.replace(regexp, "<a href=\"http://twitter.com/$1\" target=\"_blank\">@$1</a>"));
        });
        return $(returning);
      },
      linkHash: function () {
        var returning = [];
        var regexp = /(?:^| )[\#]+([A-Za-z0-9-_]+)/gi;
        this.each(function () {
          returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from=' + s.username.join("%2BOR%2B") + '" target=\"_blank\">#$1</a>'));
        });
        return $(returning);
      }

    });

    function build_url() {
      var proto = ('https:' == document.location.protocol ? 'https:' : 'http:');
      if (s.list) {
        return proto + "//api.twitter.com/1/" + s.username[0] + "/lists/" + s.list + "/statuses.json?per_page=" + s.count + "&callback=?";
      } else if (s.query == null && s.username.length == 1) {
        return proto + '//api.twitter.com/1/statuses/user_timeline.json?screen_name=' + s.username[0] + '&count=' + s.count + '&include_rts=1&callback=?';
      } else {
        var query = (s.query || 'from:' + s.username.join(' OR from:'));
        return proto + '//search.twitter.com/search.json?&q=' + encodeURIComponent(query) + '&rpp=' + s.count + '&callback=?';
      }
    }

    function checkIsIE7() {
      if (document.createElement &&
      document.getElementsByTagName && document.getElementById) {
        var el = document.createElement("script"), head = document.getElementsByTagName("head")[0];
        if (el && head && head.appendChild && head.removeChild) {
          el.type = "text/javascript";
          el.id = "A";
          head.appendChild(el);
          var buggy = !!document.getElementById("a");
          head.removeChild(el);
          el = null;
          return buggy;
        }
      }
      return null;
    }

    return this.each(function (i, widget) {

      var list = $('<table><tr>').appendTo(widget);
      var intro = '<p class="tweet_intro">' + s.intro_text + '</p>';
      var outro = '<p class="tweet_outro">' + s.outro_text + '</p>';
      var loading = $('<p class="loading">' + s.loading_text + '</p>');

      if (typeof (s.username) == "string") {
        s.username = [s.username];
      }

      if (checkIsIE7()) {
        $('table#tableTweet').show();
        $.getJSON(build_url(), function (data) {          
          var tweets = (data.results || data);
          $.each(tweets, function (i, item) {
            var text = '' + $([item.text]).linkUrl().linkUser().linkHash()[0] + '';
            $('td#tweet' + (i + 1)).html(text);
          });
        });
      }
      else {
        if (s.loading_text) $(widget).append(loading);

        $(widget).bind("load", function () {

          $.getJSON(build_url(), function (data) {
            if (s.loading_text) loading.remove();
            if (s.intro_text) list.before(intro);
            list.empty();
            var tweets = (data.results || data);
            $.each(tweets, function (i, item) {

              //var from_user = item.from_user || item.user.screen_name;
              //var profile_image_url = item.profile_image_url || item.user.profile_image_url;
              var text = '' + $([item.text]).linkUrl().linkUser().linkHash()[0] + '';
              // until we create a template option, arrange the items below to alter a tweet's display.
              list.append('<th class="twitter_MSG" >' + text + '</th>');
              if (i < s.count - 1)
                list.append('<th style="width:1px; height:46px; min-width:1px; padding-right:10px;"><div style="background-color:#FFF; width:1px; height:100%; margin-top:5px; down:0px;"></div></th>');
            });
            if (s.outro_text) list.after(outro);
            $(widget).trigger("loaded").trigger((tweets.length == 0 ? "empty" : "full"));
            if (s.refresh_interval) {
              window.setTimeout(function () { $(widget).trigger("load"); }, 1000 * s.refresh_interval);
            };
          });
        }).trigger("load");
      }

    });
  };
})(jQuery);

