//if klarna object isnt set, set it
if(window.klarna === undefined) var klarna = {};

//create a social object to put functions and results in
klarna.social = {};
klarna.social.combined = [];

klarna.social.getAll = (function(options){
	if(options === undefined){
		var options = {
			twitterquery: '"klarna faktura" OR "klarna mobil" OR "klarna konto" OR from:Klarna OR @Klarna OR #klarna',
			flickrgroup: '1685868@N20',
			lastfmuser: 'sleavely'
		}
	}
    klarna.social.getTwitterSearch(options.twitterquery);
    klarna.social.getFlickrGroup(options.flickrgroup);
    klarna.social.getLastFMUser(options.lastfmuser);
    klarna.social.sortCombinedByTime();
});

klarna.social.getTwitterSearch = (function(twitterquery){
    //@this is a function. Nobody quite knows what it does, but apparently it's awesome! #random
    
    //lets start by making sure that theres a search query
    if(twitterquery === undefined) twitterquery = '"klarna faktura" OR "klarna mobil" OR "klarna konto" OR from:Klarna OR @Klarna OR #klarna';
    //now make it URL friendly
    twitterquery = encodeURIComponent(twitterquery);
    //somewhere to store results
    var twitterresults = [];
    //I'm feeling lucky.
    jQuery.getJSON(
        'https://search.twitter.com/search.json?&q='+ twitterquery +'&rpp=10&callback=?',
        function(data) {
            for (i=0;i<data.results.length;i++){
                //figure out time of tweet
                var foo = new Date(data.results[i].created_at);
                //now convert it into a unix timestamp
                data.results[i].created_timestamp = (foo.getTime()/1000); //javascript returns in microseconds, hence the division
                
                //add data to the social object
                klarna.social.combined[klarna.social.combined.length] = {
                    type: 'twitter',
                    content: data.results[i].text,
                    link: 'http://twitter.com/#!/'+ data.results[i].from_user +'/status/'+ data.results[i].id_str,
                    timestamp: data.results[i].created_timestamp,
                    author: data.results[i].from_user
                };
                //clone it into klarna.social.twitter
                twitterresults[twitterresults.length] = klarna.social.combined[klarna.social.combined.length-1]; // -1 because the length has increased since we added the new entry
            }
            //do the actual cloning that I mentioned three lines up
            klarna.social.twitter = twitterresults;
        }
    );
    return twitterresults;
});

klarna.social.getFlickrGroup = (function(flickgroup){
    //an image says more than a thousand words.
    //unless it's a fractal, in which case the comments in the code that generated it probably says more.
    
	//options set?
	if(flickgroup === undefined) var flickgroup = '1685868@N20';
	flickgroup = encodeURIComponent(flickgroup);
	
    //local copy of everything we send to klarna.social.combined
    var flickrresults = [];
    jQuery.getJSON(
        'https://secure.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos&api_key=3e5443993b3d3845f465e377c31dda12&group_id='+ flickgroup +'&format=json&jsoncallback=?',
        function(data) {
            if(data.stat == "ok"){
				//loop through images
				for (i=0;i<data.photos.photo.length;i++){
					//add data to the social object
					klarna.social.combined[klarna.social.combined.length] = {
						type: 'flickr',
						content: 'http://farm'+ data.photos.photo[i].farm +'.static.flickr.com/'+ data.photos.photo[i].server +'/'+ data.photos.photo[i].id +'_'+ data.photos.photo[i].secret,
						link: 'http://www.flickr.com/photos/'+ data.photos.photo[i].ownername +'/'+ data.photos.photo[i].id +'/in/pool-'+ flickgroup +'/',
						timestamp: data.photos.photo[i].dateadded,
						author: data.photos.photo[i].ownername
					};
					//clone it into klarna.social.flickr
					flickrresults[flickrresults.length] = klarna.social.combined[klarna.social.combined.length-1]; // -1 because the length has increased since we added the new entry
				}
			}
            //do the actual cloning that I mentioned three lines up
            klarna.social.flickr = flickrresults;
        }
    );
    return flickrresults;
});

klarna.social.getLastFMUser = (function(lastfmuser){
	//if tree falls in the forest and nobody is there to hear it, does LastFM still scrobble it?
	
	var localcopy = [];
    var lastfm = new LastFM({
		apiKey    : '307f9e6a9d17d49ee9c10ce864ba3f77'
	});
	
	//we need to play around with time a bit for "now playing"-tracks
	var nowdate = new Date();
	var unixtime = 0;
	
	lastfm.user.getRecentTracks({user: lastfmuser}, {success: function(data) {
		for (i=0;i<data.recenttracks.track.length;i++){
			unixtime = (data.recenttracks.track[i].date ? data.recenttracks.track[i].date.uts : nowdate.getTime()/1000);
			klarna.social.combined[klarna.social.combined.length] = {
				type: 'lastfm',
				content: data.recenttracks.track[i].artist["#text"] +' - '+ data.recenttracks.track[i].name,
				link: 'http://open.spotify.com/search/'+ encodeURIComponent(data.recenttracks.track[i].artist["#text"]) +' '+ encodeURIComponent(data.recenttracks.track[i].name),
				timestamp: unixtime,
				author: data.recenttracks["@attr"].user
			};
			localcopy[localcopy.length] = klarna.social.combined[klarna.social.combined.length];
		}
		klarna.social.lastfm = localcopy;
	}});
});

klarna.social.sortCombinedByTime = (function(){
    klarna.social.combined.sort(function(a, b){
        return a.timestamp - b.timestamp;
    });
});
