Date.prototype.getDayName = function(shortName,i) {
   var Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
   if(shortName){
      return Days[this.getDay()].substr(0,3);
   }
   else{
      return Days[this.getDay()];
   }
}

Date.prototype.getMonthName = function(shortName) {
   var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; 
   if (shortName) {
      return months[[this.getMonth()]].substr(0,3);
   } else {
      return months[[this.getMonth()]];
   }
}

String.prototype.linkify_tweet = function() {
	var tweet = this.replace(
		/((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
		function(url){
			var full_url = url;
			if (!full_url.match('^https?:\/\/')) {
				full_url = 'http://' + full_url;
			}
			return '<a href="' + full_url + '">' + url + '</a>';
		}
	);
   tweet = tweet.replace(/(^|\s)@(\w+)/g, "$1@<a href='http://www.twitter.com/$2'>$2</a>");
   return tweet.replace(/(^|\s)#(\w+)/g, "$1#<a href='http://search.twitter.com/search?q=%23$2'>$2</a>");
};

var SPIN = {
	init			: function(){
		this.html = "";
		this.ts = "http://api.twitter.com/1/statuses/user_timeline.json?user_id=116189527&callback=SPIN.tw_User_Timeline_cb";
		
		//Gives an unathorised response		
		//http://api.soundcloud.com/users/SpinSessions/tracks.js?callback=SPIN.soundCloud_cb
		
		this.soundCloudScript = "http://api.soundcloud.com/tracks.json?client_id=03701ba10443d2dcf13aff5c4334cba7&callback=SPIN.soundCloud_cb&q=SpinSessions;//&order=hotness";
		this.lower = 0;
		this.upper = 5;
		this.tweetsHeight = 0;
		getScript(this.ts,this.soundCloudScript);//
	},
	soundCloud_cb			: function(response){
		console.log(response);
		j = 0;
		for(i=0; i< response.length && j<3; i++){
			var scDate = new Date(response[i].created_at);
			var dateAdded = scDate.getDayName(true)+" "+scDate.getMonthName(true)+" "+scDate.getDate()+" "
			dateAdded += scDate.getHours()+":"+scDate.getMinutes()+":"+scDate.getSeconds()+" +0000 "+scDate.getFullYear();
			var dateString = getRelativeDate(dateAdded);
			var desc = response[i].description!=""?' ~'+response[i].description.substring(0,50):"";
			if(response[i].user.username=="SpinSessions"){
				this.html += '<h1>No. '+(i+1)+': '+response[i].title+'<br /><span class="scMixInfo">Added: '+dateString+' '+desc+'</span></h1><p><object height="81" width="100%"><param name="movie" value="http://player.soundcloud.com/player.swf?url='+escape(response[i].permalink_url)+'"></param><param name="allowscriptaccess" value="always"></param><embed allowscriptaccess="always" height="81" src="http://player.soundcloud.com/player.swf?url='+escape(response[i].permalink_url)+'&downloadable='+escape(response[i].downloadable)+'" type="application/x-shockwave-flash" width="100%"></embed></object></p>';
				j++;
			}
		}
		document.getElementById('loadingIconSc').parentNode.removeChild(document.getElementById('loadingIconSc'));
		document.getElementById('soundbytes').innerHTML = this.html;
	},
	tw_User_Timeline_cb		: function(response){
		this.tweets = response;
		getScript("http://search.twitter.com/search.json?q=%40SpinSessions&callback=SPIN.tw_Search_cb");
	},
	tw_Search_cb			: function(response){
	
		for(x in response.results){
			var tw_searchDate = new Date(response.results[x].created_at);
			var dateAdded = tw_searchDate.getDayName(true)+" "+tw_searchDate.getMonthName(true)+" "+tw_searchDate.getDate()+" ";
			dateAdded += tw_searchDate.getHours()+":"+tw_searchDate.getMinutes()+":"+tw_searchDate.getSeconds()+" +0000 "+tw_searchDate.getFullYear();
			response.results[x].created_at = dateAdded;
		}

		this.tweets = this.tweets.concat(response.results);
		this.tweets.sort(this.sortTweets);
		this.renderTweets();
		//console.info(response.results);
	},
	renderTweets			: function(){
		for(i=this.lower; i<this.upper; i++){
			var tweet = this.tweets[i].text.linkify_tweet();
			var relativeDateString = getRelativeDate(this.tweets[i].created_at);
					
			var li = document.createElement("li");
			var bubbleTop = document.createElement("div");
			var bubbleCentre = document.createElement("div");
			var bubbleBottom = document.createElement("div");
			bubbleBottom.onmouseover = function(){this.lastChild.style.display='inline';};
			bubbleBottom.onmouseout = function(){this.lastChild.style.display='none';};
			bubbleTop.setAttribute('class','bubbleTop');
			bubbleCentre.setAttribute('class','bubbleCentre');
			bubbleBottom.setAttribute('class','bubbleBottom');
			
			bubbleCentre.innerHTML = tweet;
			
			var channel = this.tweets[i].source.replace(/&lt;/g, "<").replace(/&quot;/g, "\"").replace(/&gt;/g,">");
			var from = this.tweets[i].from_user?"<a href='http://www.twitter.com/"+this.tweets[i].from_user+"'>"+this.tweets[i].from_user+"</a> ":"";
			var user = this.tweets[i].from_user?this.tweets[i].from_user:this.tweets[i].user.name;
			
			bubbleBottom.innerHTML = from+"<a href='http://twitter.com/"+user+"/status/"+this.tweets[i].id+"'>"+relativeDateString+"</a> via "+channel+" <a target='_blank' style='display:none'  href='http://twitter.com/?status=@SpinSessions%20&in_reply_to_status_id="+this.tweets[i].id+"&in_reply_to=SpinSessions'>reply</a>"; 

			if(i==this.lower){
				if(document.getElementById('loadingIcon')){
					document.getElementById('loadingIcon').parentNode.removeChild(document.getElementById('loadingIcon'));
				}
				document.getElementById('more').style.display="inline";
				document.getElementById('rss').style.display="inline";
			}
			
			if(this.upper==this.tweets.length){document.getElementById('more').innerHTML="no more tweets";}
			
			li.appendChild(bubbleTop);
			li.appendChild(bubbleCentre);
			li.appendChild(bubbleBottom);

			var j=this.upper/5;

			document.getElementById('tweetsList').appendChild(li);//console.info(this.tweetsHeight);
			
			this.tweetsHeight += li.clientHeight;
			if(this.tweetsHeight>(350*j)){
				this.upper--;
				document.getElementById('tweetsList').lastChild.parentNode.removeChild(document.getElementById('tweetsList').lastChild);
			}
		}
	},
	sortTweets		: function(a,b){
		var x = Date.parse(a.created_at);
    	var y = Date.parse(b.created_at);
		return ((x > y) ? -1 : ((x < y) ? 1 : 0));
	},
	clearTweets		: function(){
/*		var tweetsList = document.getElementById('tweetsList');
		if (tweetsList.hasChildNodes() ){
			while (tweetsList.childNodes.length >= 1){
				tweetsList.removeChild(tweetsList.firstChild);
			} 
		}
*/	},
	moreTweets		: function(){
		document.getElementById('more').style.display="none";
		document.getElementById('rss').style.display="none";
		
		var loadingicon = document.createElement('img');
		loadingicon.width = 30;
		loadingicon.height = 30;
		loadingicon.vspace = 10;
		loadingicon.hspace = 10;
		loadingicon.id = "loadingIcon";
		loadingicon.src = "images/loadingIcon.gif";
		document.getElementById('tweetsList').appendChild(loadingicon);
		
		var h = document.getElementById('leftCol').offsetHeight+355;
		document.getElementById('leftCol').style.height=h+"px";
		document.getElementById('centreCol').style.height=h+"px";
		document.getElementById('mainBody').style.height=h+"px";
		
		this.lower = this.upper;
		this.upper = this.upper+6>this.tweets.length?(this.tweets.length):(this.upper+6);
		this.renderTweets();
	}
}



