/*

This is based on Tweet! by seaofclouds. 

The original Tweet! script available from:
http://tweet.seaofclouds.com/

Tweet! is licensed under the MIT:
http://www.opensource.org/licenses/mit-license.php

*/

(function($) {

  $.fn.feedMe = function(o){

    /* Defaults */
    var s = {
      username: 'n_sonic',
      feed: 'twitter',
      count: 1,
      loading_text: 'Loading...'
    };

    /* Overrides the properties found in "s" with those from the passed object "o" */
    if(o) $.extend(s, o);

    /* Configuration of feeds */
    var c = {
      'twitter': {
        niceName: 'Twitter',
        restUrl: 'http://search.twitter.com/search.json?q=from:' + s.username + '&rpp=' + s.count + '&callback=?',
        profileLink: 'http://twitter.com/' + s.username
      },
      'lastfm': {
        niceName: 'Last.fm',
        restUrl: 'http://ws.audioscrobbler.com/2.0/?format=json&method=user.getRecentTracks&api_key=2dbab32783351adb1831e264460125b6&user=' + s.username + '&limit=' + s.count + '&callback=?',
        profileLink: 'http://last.fm/user/' + s.username
      },
      'flickr': {
        niceName: 'Flickr',
        restUrl: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=86cd9a657a02e0e96ffe44f1e51288bf&user_id=60887737@N00&format=json&per_page=' + s.count + '&jsoncallback=?',
        profileLink: 'http://www.flickr.com/photos/' + s.username
      }
    }
        
    /* CSS class names used for HTML output */
    var css = {
      el_list: 'feed_list',
      el_loader: 'feed_loading',
      el_text: 'feed_text',
      el_link: 'feed_link external',
      el_date: 'feed_date',
      el_photo: 'feed_photo',
      el_photo_link: 'feed_photo external'
    }
  
    /* Generation of "how long ago" message */
    function relative_time(time_value) {
      var parsed_date = Date.parse(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      if(delta < 60) {
        return 'less than a minute ago';
      } else if(delta < 120) {
        return 'about a minute ago';
      } else if(delta < (45*60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (90*60)) {
        return 'about an hour ago';
      } else if(delta < (24*60*60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
        return '1 day ago';
      } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
      }
    }

    /* Attach the anonymous function to the passed object */
    return this.each(function(){
    
      /* Appends an element to the object we're attached to */
      var list = $('<ul class="' + css['el_list'] + '">').appendTo(this);
      var loading = $('<span class="' + css['el_loader'] + '">' + s.loading_text + '</span>');

      /* Pick a config object to use */     
      var config = c[s.feed];

      /* DEBUG */
      // console.log("Feed ID: " + s.feed);
      // console.log("REST URL: " + config.restUrl);

      /* Replace the target's content with the loading message */
      if (s.loading_text) $(this).append(loading);
      
      /* Make the AJAX call and pass the parsed JSON to an anonymous function */
      $.getJSON(config.restUrl, function(json){

        /* DEBUG */
        // console.log(json);

        if (s.loading_text) loading.remove();

        if ( s.feed == 'twitter' ) {
        
          var data = json.results;  
          $.each(data, function(i,item){
            
            var listItem = '<li>';
            
            listItem += '<span class="' + css['el_text'] + '">' + item.text.replace(/(\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&#\?\/.=]+)/gi, '<a href="$1">$1</a>').replace(/[\@]+([A-Za-z0-9-_]+)/gi, '<a href="http://twitter.com/$1">@$1</a>').replace(/ [\#]+([A-Za-z0-9-_]+) /gi, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from='+s.username+'">#$1</a> ').replace(/[&lt;]+[3]/gi, "<tt class='heart'>&#x2665;</tt>") + '</span>';
  
            listItem += '<a class="' + css['el_date'] + '" href="http://twitter.com/' + item.from_user + '/statuses/ '+ item.id + '" title="View tweet on twitter">' + relative_time(item.created_at) + '</a></li>';
  
            list.append(listItem);
  
          });
          
        } else if ( s.feed == 'lastfm' ) {
        
          if( "track" in  json.recenttracks){          
		  
			var data = json.recenttracks.track;
			
            $.each(data, function(i,item){            

				var listItem = '<li>';
				listItem += '<span class="' + css['el_text'] + '">' + item.artist['#text'] + ' - ' + item.name + '</span>';
				if ("date" in item) {
					listItem += '<a class="' + css['el_date'] + '" href="' + config.profileLink + '" title="View ' + config.niceName + ' profile">' + relative_time(item.date['#text']) + '</a>';
				}
				
				list.append(listItem);
				
            });            
          }
		  
          
        } else if ( s.feed == 'flickr' ) {
        
          var data = json.photos.photo;
          
          $.each(data, function(i,item){
          
            var listItem = '<li>';
            listItem += '<span class="' + css['el_photo'] + '"><a class="' + css['el_photo_link'] + '" href="http://www.flickr.com/photos/' + item.owner + '/' + item.id + '"><img src="http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_s.jpg" /></a></span>';
            listItem += '</li>';
            list.append(listItem);
            
            //$("<img/>").attr("src", item.media.m).appendTo("#images");
            //if ( i == 4 ) return false;
            
          });
        
        }
        
        $("a.external").click(function(event){
  				newWindow=window.open(this.href,'benjeffreys');
  				if (window.focus) {newWindow.focus()}
  				event.preventDefault();
  			});
 
      });
      
    });

  };
})(jQuery);
