/*
Copyright nyide.nu 2011
Contact jacob@nyide.nu
*/

// Check jquery...
jQuery.noConflict();

// Set news array
newsSortable = new Array();

var number = false;


// Insert news into array funktion
function InsertNews(date, news){
	newsSortable.push([date,news]);
};


// Parseing Links, Hashtags and users

// Make trim available to strings
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

//Parse urls
String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
		return url = "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>";
		//return url.link(url);
	});
};

// Parse usernames
String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/, function(u) {
		var username = u.replace("@","")
		return url = "<a href=\"http://twitter.com/"+username + "\" target=\"_blank\">" + u + "</a>";
	});
};

//Parse hashtags
String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/, function(t) {
		var tag = t.replace("#","%23")
		return url = "<a href=\"http://search.twitter.com/search?q=" +tag + "\" target=\"_blank\">" + t + "</a>";
		//return t.link("http://search.twitter.com/search?q="+tag);
	});
};

// Export the hole to the table
function Init(){

	// Sort the array by date
	newsSortable.sort(function(a, b) {
		return b[0] - a[0];
	});
	
	// Empty the table	
	jQuery("tbody.flickr_twitter").empty();
	
	jQuery.each(newsSortable, function(index,value){
		
    	if(number != false){
    		if(number <= index){
    			return false;
    		}
    	}		
		
		// Convert date from array to JSdate
		JSdate = new Date (value[0]);
		
		// What is the date now?
		JSdateNow = new Date ();
			
			
		//Format minutes
		minutes = JSdate.getMinutes() + "";
		if (minutes.length == 1){
			minutes = "0" + minutes;
	    }
		    
	    //Format month
	    months = 1+ JSdate.getMonth()
		    
			
		// Format the tweet if it is newer then 4 hours.	
		if( (JSdateNow.getTime() - JSdate.getTime()) < 4*60*60*1000 ) {
			date = JSdate.getDate() + "-" + months + "-" + JSdate.getFullYear() + " - " + JSdate.getHours() + ":" + minutes + "  <span style=\"color:red;\"> * * NY * *</span>";
		}else{
			date = JSdate.getDate() + "-" + months + "-" + JSdate.getFullYear() + " - " + JSdate.getHours() + ":" + minutes;
		}
			
		text = value[1];	
			
			
   		jQuery("<tr/>").appendTo(".flickr_twitter").html("<td class=\"norm\" style=\"margin-bottom:10px;\"><big>" + date + "</big><br>" + text +"</td>");
    });
}

function getTwitter(){
	
	// Define the url with Twitter lists
	url = "http://ds.nyide.nu/socialmedia/get_twitter_list.php?callback=?";
	
	// Lets get the twitter accounts
	jQuery.getJSON(url, function(data){
		
		// How many accounts
		ListCount = data.users.length;
		
		// Run through the accounts
		jQuery.each(data.users, function(index, item){
			//alert(item.screen_name);
			getTwitterAccount(item.screen_name);	
		});

		getTwitterAccount('dansksejlunion');


	});

}

// TWITTER FUNKTION
function getTwitterAccount(username){
	//Define the url
	url = "http://ds.nyide.nu/socialmedia/get_twitter.php?username=" + username + "&callback=?";

	//Lets get the twitters
	jQuery.getJSON(url,function(data){
		
		// How many Tweets
		TwitterCount = data.length;
		
		jQuery.each(data, function(index, item){
	
			//Gets the date
			JSdate = new Date(item.created_at.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC"));
			date = JSdate.getDate() + "-" + JSdate.getMonth() + "-" + JSdate.getFullYear() + " - " + JSdate.getHours() + ":" + JSdate.getMinutes();
	
			// Javascript timestamp
			JStime = JSdate.getTime();
			
			text = '<img src="/graphics/appSejlere/sejlerprofil/twitter.png" style="float:right; margin-left:5px;"><img style="float:left; margin-right:4px;" src ="' + item.user.profile_image_url_https + '" \><span class="norm twitter"><a href="http://twitter.com/#!/' + username + '" target="_blank">' + item.user.name + '</a>' + ': ' + item.text.parseURL().parseUsername().parseHashtag() + '<br/></span><div class="norm" style="text-align:right;"><a href="http://twitter.com/intent/tweet?in_reply_to=' + item.id + '" target="_blank">reply</a> - <a href="http://twitter.com/intent/retweet?tweet_id=' + item.id + '" target="_blank">retweet</a></div>';
			
			//Insert the news in the array
			InsertNews(JStime, text);
			
			// If last tweet, then run init
			if(TwitterCount == index+1){
				Init();
			}
			
			
		});
	});
};



// FACEBOOK FUNKTION
function getFacebook(){
	// Jonas Hoegh
	getFacebookPage(108392612577214,'page');
	
	// 470-pigerne
	getFacebookPage(131724620252970,'page');
	
	// Sejlerlandsholdet
	getFacebookPage(105848992618,'page');
	
	//Warrer og Hansen
	//getFacebookPage(134810349913596,'page');
	
	//470-drengene
	getFacebookPage(175817189104153,'page');
	
	// Lærke
	getFacebookPage(202992983064214,'page');
	
	//Kruger og Thorsel	
	//getFacebookPage(100516583393,'page');
	
	// Anne-Marie Rindom
	getFacebookPage(300553103297391,'page');
}

function getFacebookPage(username,type){
	// Define the url
	url = "http://ds.nyide.nu/socialmedia/get_facebook.php?username=" + username + "&type=" + type + "&callback=?";
	
	// Lets get the Facebook posts
	jQuery.getJSON(url,function(data){
		
		// How many posts
		FacebookCount = data.entries.length;
		
		jQuery.each(data.entries, function(index,item){
		
			//Gets the date
			JSdate = new Date(item.published.replace(/^(\d{4})(-)(\d{2})(-)(\d{2})(T)(\d{2}\:\d{2}\:\d{2})(\+\d{2}\:\d{2})/, "$1/$3/$5 $7"));
			date = JSdate.getDate() + "-" + JSdate.getMonth() + "-" + JSdate.getFullYear() + " - " + JSdate.getHours() + ":" + JSdate.getMinutes();
	
			// Javascript timestamp
			JStime = JSdate.getTime();
			
			text = '<img src="/graphics/appSejlere/sejlerprofil/facebook.png" style="float:right; margin-left:5px;"><span class="norm facebook"><a href="' + item.alternate + '" style="text-align:left;" target="_blank">' + item.author.name + ':</a> <br>' + item.content + '<br/></span>';
			
			//Insert the news in the array
			InsertNews(JStime, text);
			
			// If last tweet, then run init
			if(FacebookCount == index+1){
				Init();
			}			
		
		});
	
	});

}


// FLICKR FUNKTION
function getFlickr(width){

	//Lets get the overall photos		
	jQuery.getJSON("http://ds.nyide.nu/socialmedia/get_flickr.php?number=" + number + "&callback=?",function(data){
		// How many images
		ImageCount = data.photos.photo.length;
		
		//Run through each photo
		jQuery.each(data.photos.photo, function(index, item){
			
			// Lets get some details about the single photo
			jQuery.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=bbe25ccd49fbbfd9a45e5edf77c0504b&photo_id=" + item.id + " &secret=" + item.secret + "&format=json&jsoncallback=?",function(data){
				
				// Make a working image src
				src = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + ".jpg";
				
				// Insert the news in the array
				InsertNews(data.photo.dateuploaded*1000, "<img src=\"/graphics/appSejlere/sejlerprofil/flickr.png\" style=\"float:right; margin-left:5px;\"><span class=\"norm flickr\"><img width=\"" + width + "\" src=\" " + src + " \">"+data.photo.description._content+"</span>");
				// If the last image, then run init
				if(ImageCount == index+1){
					Init();				
				}
			
			})
					
		})
	
	})
}

