/*
 Adam Laiacano
 August, 2011
 
 These functions allow you to pull info from various websites and include it in
 a website made with the skeleton framework: getskeleton.com
 
 Defaut settings for each content source are included in the first section of
 this file.
 
 Example code to put in index.html to include a twitter feed with all of the
 default settings:
 
   <div id="twitter"></div>
   <script> twitter({screen_name:"adamlaiacano"})</script>
 
*/

var tumblr_defaults = {
    // Required additional fields are:
    // blog_name: this is from http://{blog-name}.tumblr.com
    // api_key: see http://www.tumblr.com/docs/en/api/v2#auth for info on getting an API key.
    limit: 5,
    showphotos:true,
    showtext:true,
    showvideos:true,
    showtags:true,
    node_id:"tumblr"
}

var twitter_defaults = {
    //screen_name:"twitter",
    limit:5,
    replies:false,
    links:true,
    date:true,
    node_id: "twitter"
}

var github_defaults = {
    // screen_name: "your account name"
    limit:5,
    showdetails:true,
    node_id:"github"
}


var lastfm_defaults = {
    // screen_name: "your username here"
    // api_key: "your api key here"
    limit:10,
    node_id: "lastfm"
}


function twitter(options){
    var opts = $.extend({}, twitter_defaults, options);
    var cnt = 0;
    
    myregexp = new RegExp("http://[^ ]+", "gi")

    $.ajax({
        type: "GET",
        url: "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+opts.screen_name,
        processData: true,
        data: {},
        dataType: "jsonp",
        success: function(data) {
          var items = [];
        
          $.each(data, function(key,item) {
            if(item.text && cnt < opts.limit && ((item.in_reply_to_user_id==null) || opts.replies)){
                if(opts.links){
                    item.text = item.text.replace(/(http\:\/\/[^ ]+)/gi, '<a href="\$1">\$1</a>');
                    item.text = item.text.replace(/@([a-z0-9]+)/gi, '<a href="http://www.twitter.com/\$1">@\$1</a>');
                    item.text = item.text.replace(/#([a-z0-9]+)/gi, '<a href="http://www.twitter.com/search/%23\$1">#\$1</a>');
                }
                if(opts.date){
                    y = item.created_at.split(" ")
                    time_created = y[0]+", "+y[1]+" "+y[2]
                    
                    item.text += "<br><small><a href='http://www.twitter.com/"+opts.screen_name+"status/"+item.id_str+"'>" + time_created + "</a></small>";
                    time_created = '';
                }
                items.push('<li>'+item.text+'</li>');
                
                cnt++;
            }
          });
        
          $('<ul/>', {
            'class': 'my-new-list',
            html: items.join('')
          }).appendTo('#'+opts.node_id);
        }
    });
}


function github(options){
    var opts = $.extend({}, github_defaults, options);
    var cnt = 0;
    
    $.ajax({
        type: "GET",
        url: "https://github.com/"+opts.screen_name+".json",
        processData: true,
        data: {},
        dataType: "jsonp",
        success: function(data) {
          var items = [];            
          
           $.each(data, function(key,item) {
                
                if(opts.showdetails && cnt < opts.limit){
                    if(item.payload.shas != null && item.repository.description != null){
                        items.push('<li><a href="'+item.repository.url+'">' + item.repository.description +'</a><br>'+item.payload.shas[0][2] + '</li>');
                        cnt++;
                    }
                }
            });
          
          $('<ul/>', {
            'class': 'my-new-list',
            html: items.join('')
          }).appendTo('#'+opts.node_id);
        }
    });
}


/*
 NOTE that this function isn't tested with an API key yet. There's a chance that
 you have to change the value of dataType: "json" to "jsonp" in the .ajax call.
 
 I'll obviously update this once I have an API key.
 
 If you don't have an API key, you can do the following:
 1) go to http://api.tumblr.com/v2/blog/{YOUR BLOG NAME}.tumblr.com/posts?api_key=PyezS3Q4Smivb24d9SzZGYSuhMNPQUhMsVetMC9ksuGPkK1BTt
 2) save that file as "tumblr.json"
 3) call the tumblr function from index.html with the following:
   tumblr({feed_url:'/path/to/tumblr.json', ...other options...})
   
 This will load the local json file instead of the remote file.
*/

function tumblr(options){

    var opts = $.extend({}, tumblr_defaults, options);
    if(opts.feed_url == null){
        opts.feed_url = "http://api.tumblr.com/v2/blog/"+blog_name+".tumblr.com/posts?api_key="+opts.api_key
    }
    var cnt = 0;
    $.ajax({
        type: "GET",
        url: opts.feed_url,
        processData: true,
        data: {},
        dataType: "json",
        success: function(data) {
          var items = [];
          
          $.each(data.response.posts, function(key,item) {
            
            if(item != null && cnt < opts.limit){
                title = '';
                switch(item.type){
                    case "photo":
                        if(opts.showphotos)
                            title = "<img src='"+item.photos[0]['alt_sizes'][3]['url']+"' border=0>";
                        break;
                    case 'video':
                        if(opts.showvideos)
                            title='(video)';
                        break;
                    case 'text':
                        if(opts.showtext)
                            title = item.title;
                        break;
                    default:
                        text = '';
                }
                if(title != "" && title != null){
                    if(opts.showtags){
                        tags=item.tags==null?'':item.tags.join(", ");
                        
                        items.push('<li><a href="'+item.post_url+'">' + title + '</a><br>'+tags+ '</li>');
                        cnt++;
                    }
                    else{
                        items.push('<li><a href="'+item.post_url+'">' + title + '</a></li>');
                        cnt++;
                    }
                }
                
                
            }
          });
        
          $('<ul/>', {
            'class': 'my-new-list',
            html: items.join('')
          }).appendTo('#'+opts.node_id);
          
        }
    });
}


function lastfm(options){
    var opts = $.extend({}, lastfm_defaults, options);
    var cnt = 0;
    
    //base URL
    opts.feed_url = 'http://ws.audioscrobbler.com/2.0/?callback=?',  
    
    
    $.ajax({
        type: "GET",
        url: opts.feed_url,
      
        processData: true,
        data: {
            method:  "user.getrecenttracks",
            format:  "json",
            limit:   opts.limit,
            user:    opts.screen_name,
            api_key: opts.api_key
        },
        dataType: "json",
        success: function(data) {
            var items = [];
            $.each(data.recenttracks.track, function(key,item) {
                if(cnt < opts.limit){
                    items.push('<li>"'+ item.name + '" by ' + item.artist["#text"]+"</li>");
                    cnt++;
                }
            });
            $('<ul/>', {
                'class': 'my-new-list',
                html: items.join('')
            }).appendTo('#'+opts.node_id);
        }
    });
}


function lastfm_onetrack(options){
    var opts = $.extend({}, lastfm_defaults, options);
    var cnt = 0;
    
    //base URL
    opts.feed_url = 'http://ws.audioscrobbler.com/2.0/?callback=?',  
    
    $.ajax({
        type: "GET",
        url: opts.feed_url,
      
        processData: true,
        data: {
            method:  "user.getrecenttracks",
            format:  "json",
            limit:   opts.limit,
            user:    opts.screen_name,
            api_key: opts.api_key
        },
        dataType: "json",
        success: function(data) {
            var track = data.recenttracks.track[0];
            $('<span/>', {
                'class': 'my-new-list',
                html: '"'+ track.name + '" by ' + track.artist["#text"]
            }).appendTo('#'+opts.node_id);
        }
    });
}

