//$(function(){
google.load("feeds", "1");
var twitFeeds=[20238728, 15353955, 102690477];

//var studentDictionary = ["Courtney Williams", "Christopher Fonseka", "Dan Shen", "Coranda Berry", "Jaimie", "Naser Turabi", "Lakshana Huddar", "Maciej Szukszto", "Jonathan Darley", "Louisa"];
//var studentNames = ["Courtney", "Chris", "Shelley", "Corrie", "Jaimie", "Naser", "Lakshana", "Maciej", "Jonny", "Louisa"];

//var studentDictionary = ["Ewa Graf", "Christopher Fonseka", "Aislinn Hayes", "Coranda Berry", "Jaimie Henry", "Dawn Brooks", "Charlotte Levin", "David Robertson", "Sangjin Lee", "Christopher Richardson", "Nina Hartwich"]; 
var studentDictionary = ["Ali Hussein", "Jun Cao", "Tessa Carver", "Aislinn Hayes", "Ken Wu", "Dawn Brooks", "Bernadeta Dadonaite", "Alex Rozanski", "Christopher Nichols", "Richard Bennett", "Keou Kadji", "Reuben Hill"]; 
var studentNames = ["Ali", "Jun", "Tess", "Aislinn", "Ken", "Dawn", "Bernadeta", "Alex", "Christopher", "Richard", "Keou", "Reuben"];


$.each(twitFeeds, function(i){
$.getJSON('http://twitter.com/statuses/user_timeline/'+twitFeeds[i]+'.json?count=5&callback=?',function(j){
	SortTwitter(j);
	
});

});

$.getJSON('http://gdata.youtube.com/feeds/api/playlists/CFDCD7210FF973E9?alt=json-in-script&format=5&callback=?',function(j){
	showMyVideos(j);
	
});

/*$.getScript('http://www.imperial.ac.uk/imedia/dynamic_addin/imageFader/js/fadingimages.js',function(){
	_int = setInterval(function(){
	 if(typeof(fadingImages) != 'undefined'){
	  fadingImages({feed:'http://api.flickr.com/services/feeds/photos_faves.gne?nsid=23120052@N02&lang=en-us&format=json&',addlinks:true,div:'#AccFlickDiv'});
	  clearInterval(_int);
	 }
	})
});
*/

$.getScript('http://www.imperial.ac.uk/imedia/dynamic_addin/imageFader/js/fadingimages.js',function(){
 if(typeof fadingImages == 'undefined'){
  _int = setInterval(function(){
   if(typeof fadingImages != 'undefined'){
		fadingImages({feed:'http://api.flickr.com/services/feeds/photos_faves.gne?nsid=23120052@N02&lang=en-us&format=json&',addlinks:true,div:'#AccFlickDiv'});
    clearInterval(_int);
   }
  })
 } else {
fadingImages({feed:'http://api.flickr.com/services/feeds/photos_faves.gne?nsid=23120052@N02&lang=en-us&format=json&',addlinks:true,div:'#AccFlickDiv'});
 }
});


//Fix server down error
var CheckFeedErrors = window.setInterval(function (a,b) {
	var divList = ['#AccTubeDiv', '#AccPodCaDiv', '#AccStuBlogsDiv', '#AccTwitDiv'];
	var divListNames = ['YouTube', 'Podcast', 'Student Blogs', 'Twitter'];
	
	for (entr in divList){
  if( $(divList[entr]).html()=="Loading..."){
	   $(divList[entr]).html("The "+divListNames[entr]+" feed server is temporarily unavailable");
	  }
	}
  clearInterval(CheckFeedErrors);
},5000);


    $(function(){
	//google.load("feeds", "1");
	})


	var TubeEntryNumbers = new Array();
	var twitList = new Array();
	var studentBlogList = new Array();
	var podCastList =  new Array();
	var feedListStudents=new Array("http://www2.imperial.ac.uk/blog/studentblogs/chris/feed", "http://www2.imperial.ac.uk/blog/studentblogs/corrie/feed", "http://www2.imperial.ac.uk/blog/studentblogs/courtney/feed", "http://www2.imperial.ac.uk/blogs/studentblogs/jonny/feed", "http://www2.imperial.ac.uk/blog/studentblogs/lakshana/feed", "http://www2.imperial.ac.uk/blog/studentblogs/louisa/", "http://www2.imperial.ac.uk/blog/studentblogs/naser/feed", "http://www2.imperial.ac.uk/blogs/studentblogs/maciej/feed", "http://www2.imperial.ac.uk/blog/studentblogs/shelley/feed", "http://www2.imperial.ac.uk/blogs/studentblogs/jaimie/feed");

			$(function(){
				// Accordion
				$("#accordion").accordion({ header: "h3" });
				$('#accordion').accordion('option', 'autoHeight', true);
				
				});				


function reduceString(_whichString, _length){
 _whichString.replace("'", "‘")
	if(_whichString.length > _length){
		var newString = _whichString.substring(0, _length)+"...";
	}
	else
	{
		var newString = _whichString;
	}
 return(newString);
}


function getShortName(_whichName)
{
	var thePos = -1;
	
	for(index=0; index<studentDictionary.length; index++)
	{
		if(studentDictionary[index] == _whichName)	
		{
			thePos = index;
			break;
		}
	}
	if(thePos>-1){
		return(studentNames[thePos]);
	}
	else
	{
		return(_whichName);
	}
}


function getRandomEntries(maxNum)
{
	if(TubeEntryNumbers.length<4){
		var foundDuplicate = false;
		var max = maxNum;
		var num = Math.floor((Math.random() * max));
		
		//check if exists:
		for(i=0; i < TubeEntryNumbers.length; i++)
		{
			if(TubeEntryNumbers[i] == num)
			{
				foundDuplicate = true;
				break;
			}
			else
			{
			continue;
			}
		}
		if(!foundDuplicate){TubeEntryNumbers.push(num)};	
	}
}
function showMyVideos(data) {
  var feed = data.feed;
  var entries = feed.entry || [];
  
  while (TubeEntryNumbers.length < 3){
  	getRandomEntries(entries.length);
  }
  if(TubeEntryNumbers.length == 3){
	  	var tubeWidth = "200px";
		if (navigator.userAgent.indexOf("MSIE 6.0")>-1){
	   tubeWidth="195px";
	  }  
  var html = ['<div style="margin-left:-36px; overflow: hidden;"><div class="link-block" style="width:'+tubeWidth+';">'];
  html.push('<ul class="link-list" style="margin-bottom:-30px; padding-right: 0px;">');
  for (i in TubeEntryNumbers) {
    var entry = entries[TubeEntryNumbers[i]];
    var title = entry.title.$t;
	var thumbnailUrl = entry.media$group.media$thumbnail[0].url;
	var playerUrl =entry.link[0].href;
    html.push('<li class="with-thumbnail" style="margin-bottom:-15px;"><div style="margin-left:-10px;"><h4><a style="line-height:14px; font-size:11px;" href="', playerUrl, '">', reduceString(title, 50), '</a></h4></div><a href="',playerUrl,'"><img src="',thumbnailUrl, '" class="thumbnail" title="', title, '" border="0" width="65" height="48" alt="',title,'" /></a></li>');
  }
  html.push('</ul>');
  html.push('</div></div>');
  if(document.getElementById("AccTubeDiv")){
  document.getElementById("AccTubeDiv").innerHTML = html.join('');
  }
  }
}

function SortTwitter(data) {
   
  var tempList = new Array(4);
  //create 2-dim-Array
  for (i=0; i <4; i++){
  tempList[i] = new Array(5);
	}
  //extract latest two, put in array:
  for (a=0; a<3; a++){
    var entry = data[a];
    var message = entry.text;
	var name =  entry.user.screen_name;
	var date =  entry.created_at;
	var url = entry.id;
	
	//convert date to correct format:
	var date_temp=date.split("+");
	date = date_temp[0].substr(0,10) +" "+ date_temp[1].substr(5,10);

	tempList[a][0] = Date.parse(date);
	tempList[a][1] = date;
	tempList[a][2] = message;
	tempList[a][3] = name;
	tempList[a][4] = "http://www.twitter.com/"+name;
	
	twitList.push(tempList[a]);	

  }
}

function getFeedItunes(_url, _amount, _whichElement){
    var URL = _url;
    var ht = [];
	ht = ['<ul class="link-list" style="margin-left:-30px; width:187px; padding-right:0px;">'];
    var dispLink = 'http://www2.imperial.ac.uk/imedia/videos/view/';
    var amount = _amount;
    var counter = 0;
    
    $.getJSON(URL + '?jsonCallBack=?', function(j){
        $(j).each(function(i){
        
            $(j).each(function(a){
                 $(this['Content']).each(function(b){                
                    if (counter < amount) 
					{                    
                       // ht.push('<li class="with-thumbnail"><a target="_self" href="' + dispLink + this.id + '/' + this.slug + '">' + this.title + '<img width="60" height="45" alt="' + this.title + '" src="' + imgSrc + this.id + '/small" class="thumbnail" /></a></li>');
                        
						ht.push ('<li style="font-size:12px; line-height:14px; margin-bottom:6px;"><a href="'+dispLink + this.id + '/' + this.slug + '" title="'+this.title+'">'+reduceString(this.title, 80)+'</a></li>');
						counter += 1;
                    }
                });
            });
        });
		ht.push('</ul>');        
        $(_whichElement).html(ht.join(''));        
    });
}

function collectFeeds(whichFeed, whichArray, _howLong){
var feed = new google.feeds.Feed(whichFeed);

if(_howLong){
	var thelength = _howLong;
}else
{
	thelength = 8;
}

feed.setNumEntries(thelength);
var entryHolder = new Array(thelength);
	//prep 2-Dim-array;
  for (i=0; i < entryHolder.length; i++){
  	entryHolder[i] = new Array(5);
  }
	
feed.load(function(result) {
  if (!result.error) {  
    for (var i = 0; i < thelength; i++) {
		
			if(entryHolder[i]!==undefined)
			{
		  var entry = result.feed.entries[i];
		  
		  if(entry!==undefined){
		  
		  if (whichArray==studentBlogList){
			var attributes = ["TimeStamp", "title", "link", "publishedDate", "author"];
		  }
		  else
		  {
			var attributes = ["TimeStamp", "title", "link", "publishedDate"];
		  }	  
		  for (var j = 0; j < attributes.length; j++) {
			//extract "pseudo" TimeStamp
			 // console.log(attributes[j] + ": " + entry[attributes[j]]);
			if(j==0){	
				entryHolder[i][j] = Date.parse(entry[attributes[3]]);
			}
			else
			{			
				entryHolder[i][j] = entry[attributes[j]];		
			}	
		  }
		}
		
		
		}
	
	}
	
	
	
	for (a in entryHolder){
		if(entryHolder[a]){	
		 	whichArray.push(entryHolder[a]);
	 	}
	 }
  }
  
});
}

collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/ali/feed", studentBlogList, 2);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/jun/feed", studentBlogList, 2);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/tess/feed", studentBlogList, 2);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/aislinn/feed", studentBlogList,4);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/dawn/feed", studentBlogList, 4);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/ken/", studentBlogList, 4);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/bernadeta/feed", studentBlogList, 2);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/alex/feed", studentBlogList, 2);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/christopher-n/feed", studentBlogList, 2);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/richard/feed", studentBlogList, 2);
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/keou/feed", studentBlogList, 2); 
collectFeeds("http://www2.imperial.ac.uk/blog/studentblogs/reuben/feed", studentBlogList, 2);

//collectFeeds("http://www.imperial.ac.uk/podcasts/Imperial_College_London-Science_Magazine.xml", podCastList, 15);
//collectFeeds("http://www.imperial.ac.uk/podcasts/Imperial_College_London-Public_Lectures.xml", podCastList, 15);
getFeedItunes("http://www2.imperial.ac.uk/imedia/itunes_collections/view/55.json", 7, '#AccPodCaDiv');

var myInterval = window.setInterval(function (a,b) {
  if(studentBlogList.length >=26) //80 was the original, 40 now new optimum
  {
	  studentBlogList.sort();
	  studentBlogList.reverse();

	  var html_output = '<ul class="link-list" style="margin-left:-30px; width:187px; padding-right:0px;">';
	  html_output +='\n';
	  
	  for(i=0; i<7; i++){ //8 was sthe original
		  html_output += '<li style="font-size:12px; line-height:14px; margin-bottom:6px;"><a href="'+studentBlogList[i][2]+'" title="'+studentBlogList[i][1]+'"><strong>'+getShortName(studentBlogList[i][4])+':&nbsp;</strong>'+reduceString(studentBlogList[i][1], 80)+'</a></li>'+'\n';
	  }
	  html_output+='</ul>';
	  $('#AccStuBlogsDiv').html(html_output);
  }
  
/* if(podCastList.length>15)
  {
  	  podCastList.sort();
	  podCastList.reverse();
	  
	  var html_output_pod = '<ul class="link-list" style="margin-left:-30px; width:187px; padding-right:0px;">';
	  html_output_pod +='\n';	  
	  for(i=0; i<7; i++){
		  html_output_pod += '<li style="font-size:12px; line-height:14px; margin-bottom:6px;"><a href="'+podCastList[i][2]+'" title="'+podCastList[i][1]+'">'+reduceString(podCastList[i][1], 80)+'</a></li>'+'\n';
	  }
	  html_output_pod+='</ul>';
	  $('#AccPodCaDiv').html(html_output_pod);
  }*/
  
   if(twitList.length>3)
  {			
  	  twitList.sort();
	  twitList.reverse(); 	  
	 
	  var lineHeight="14px";
	  
	  //fix for Safari 4, which does not pay attention to line-height
	  var fontSize = 12;
	  
	  if (navigator.userAgent.indexOf("Safari")> -1){
	   fontSize = 11;
	  }
	  if (navigator.userAgent.indexOf("MSIE")>-1 || navigator.userAgent.indexOf("Safari")> -1){
	   lineHeight="12px";
	  }
	 
	  var html_output_twit = '<ul class="link-list" style="margin-left:-30px; margin-bottom:-30px; width:187px; margin-right:0px; padding-right:0px;">';
	  html_output_twit +='\n';	  
	  for(i=0; i<2; i++){
		  html_output_twit += '<li style="font-size:'+fontSize+'px;"><a href="'+twitList[i][4]+'" style="line-height:'+lineHeight+';">'+twitList[i][3]+":<br/>"+cutOffString(twitList[i][2])+'<br/>'+'</a><small>'+twitList[i][1]+'</small></li>'+'\n';
	  }
	  html_output_twit+='</ul>';
	  $('#AccTwitDiv').html(html_output_twit);
  }
  
   if(/*podCastList.length>15 && */studentBlogList.length>=26 && twitList.length>3){
   //alert("Cool"); 	
	//delete podCastList;
	delete studentBlogList;
	delete twitList;
	clearInterval(myInterval);
	}
  
},2000);

function cutOffString(_whcihString){
	// reduces string width so that the whole accordeon is not pushed to the right if string > parent container(IE bug)
	var tempIt = _whcihString.split(" ");
	for (items=0; items<tempIt.length; items++)
	{
		if(tempIt[items].length>30)
		{
			tempIt[items]=tempIt[items].substr(0, 30)+"...";
			}
	}
	return(tempIt.join(" "));	
}









			
