/* Configuration: */

var tabs = new Array;
var totalTabs;
var tabName;
$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */
	extractLinks();
	/* Counting the tabs */
	totalTabs = tabs.length;
	$('#feedWidget').show();
	
		
	/* Using the live method to bind an event, because the .tabItem does not exist yet: it is created unique for every tab */
	$('.tabItem').live('click', function(event){
		
		//check for empty feeditems
		if ($('#'+$(this).attr('id') + ' .feedSince').length == 0){return true;}
		
		/* Calling the showDropDown function, when the drop down is already shown, will hide it: */
		showDropDown($(this));
		$('.expand').remove();

	}).live('mouseover', function(event){

		//check for empty feeditems
		if ($('#'+$(this).attr('id') + ' .feedSince').length == 0){return false;}
			
		//If dropdown exists return
		if ($('#'+$(this).attr('id') + ' .dropDownList').length){return false;}

		var expand = $('<div>').addClass('expand').text('-utöka-').css({
			'color':'#CCCCCC',
			'font-size' : '15px',
			'text-align' : 'center'
		});
			
		$(this).append(expand);
		
	}).live('mouseout', function(event){
		$('.expand').remove();
	});

	$.each(tabs,function(u){tabQuery(u);});
	
});

function extractLinks(){

	$('#linkList' + ' a').each(function(a,b){
		var feed;
		var link = b.href;
		if (link.match(/blogspot.com/gi) == 'blogspot.com'){feed = (link + 'feeds/posts/default')}
		else if (link.match(/blogg.se/gi) == 'blogg.se'){feed = (link + 'index.rss')}
		else if (link.match(/gladers.net/gi) == 'gladers.net'){feed = ('iloapp.gladers.net/blog/julen?RSS')}
		else if (link.match(/julistan.com/gi) == 'julistan.com'){feed = (link + 'feeds/posts/default')}
		else{feed = null;}
				tabs[a] = {
					'title' : b.innerText,
					'feed' : feed,
					'link' : link,
					"functionRss"	: rss,
					"functionTitle"	: title,
					"feedData" : null
				}	
		});
		//Remove links in html file
		$('#linkList' + ' li').remove();
}

function checkTimeSince(date){
	
	var currentTime = new Date;
	var timeSinceDate = new Date;
	var timeSinceDate = currentTime - date;
	return timeSinceDate;
}

function pluralis(number,word,sing,plur){
	
	if (number < 2){
		return (word + sing);
	}
	return (word + plur);
	
}

function largestDateComponent(date){
	var seconds = date/1000;
	var value = new Array();
	var minutes = seconds/60;
	var hours = minutes/60;
	var days = hours/24;
	var weeks = days/7;
	var months = days/30;
	var years = months/12;
	if (years > 1){value.push('år', years); return value;}
	if (months > 1){value.push(pluralis(months,'månad','','er'), months); return value;}
	if (weeks > 1){value.push(pluralis(weeks,'veck','a','or'), weeks); return value;}
	if (days > 1){value.push(pluralis(days,'dag','','ar'), days); return value;}
	if (hours > 1){value.push(pluralis(hours,'timm','e','ar'), hours); return value;}
	if (minutes > 1){value.push(pluralis(minutes,'minut','','er'), minutes); return value;}
	if (seconds > 1){value.push(pluralis(seconds,'sekund','','er'), seconds); return value;}
	
	
	return 0;
}

function sortByFirstNumber(a, b) {
	
    var x = a.feedData.timeSince;
    var y = b.feedData.timeSince;
	if (x == -1) return 1;
	if (y == -1){return -1}
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

var number = 0;
function createTabList(){
	
	number++;
	
	//Be sure to wait on the response from the server before processing
	if (tabs.length == number){
		$.each(tabs,function(i){
			
			var dateString = tabs[i].feedData.date;
			if (dateString.length > 0){
				var dateObject = dateString.replace(/\-/g,'\/');
				
				//Remove T from mostly blogspot time, but dont remove tuesday or thursday ref.
				if (!(dateObject.match(/Tu/gi)) && !(dateObject.match(/Th/gi))){dateObject = dateObject.replace(/T/,' ');}
				
				var stringEnd = dateObject.indexOf('.');
				var newDateObject = dateObject;
				if (stringEnd > 0){newDateObject = dateObject.substring(0,stringEnd);}
				 var parsedDate = Date.parse(newDateObject);
				//var timeSince = new Array;

				var since = checkTimeSince(parsedDate);

				//Add dates into array as an array.
				tabs[i].feedData.timeSince = since;
			}
			});

		tabs.sort(sortByFirstNumber);
		
		//	create array with numbers...
		$.each(tabs,function(u){
			createTab(tabs[u],u)});
	}

}
function createTab(object,no){
	
	/*Add style and individual class to every tab*/
	var activeTab = $('#feedWidget');
	var offsetTop =  5;
	var newTabObject = $('<div>').addClass('tabItem').attr('id',('tab' + no)).css({

			'top'	: offsetTop,
			'width'	: (activeTab.width() - 10)
	});
	
	var stage = $('#tabList');
	stage.append(newTabObject);
	newTabObject.append(object.feedData.data);
	if (object.feedData.timeSince != -1 ){
		var dateAndDayArray = new Array;
		dateAndDayArray = largestDateComponent(object.feedData.timeSince);
		
		newTabObject.append('<div class="feedSince">'+ Math.floor(dateAndDayArray[1]) + ' ' + dateAndDayArray[0] +' sedan' + '</div>')};
	
}

function tabQuery(key){
	var obj = tabs[key];
	if(!obj) return false;
	
	if (!obj.feed){
		//Create a null feed item to work in the regular code for those without sucks--needs to be fixed
		var o ={'title':new String(''), 'pubDate':new String('')};
		var objectData = obj['functionTitle'](o,obj);
		tabs[key].feedData = objectData;
		createTabList();
		return true;
		}
	
	/* Forming the query: */
	var query = "select * from feed where url='"+obj.feed+"' LIMIT 1";
	
	/* Forming the URL to YQL: */
	var url = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent(query)+"&format=json&callback=?";
	tabName = obj.title;
	
//Catching error when json doesnt process a catch is needed
	  $.getJSON(url,function(data){

		/* item exists in RSS and entry in ATOM feeds: */
		$.each(data.query.results || data.query.results,function(){
		
			try{
				/* Trying to call the user provided function, "this" the rest of the feed data: */
				var objectData = obj['functionTitle'](this,obj);
				tabs[key].feedData = objectData;
				createTabList();
				var fat;
			}
			
			catch(e){
				/* Notifying users if there are any problems with their handler functions: */
				var f_name =obj['functionTitle'].toString().match(/function\s+(\w+)\(/i);
				if(f_name) f_name = f_name[1];
				
				var objectData = '<div>There is a problem with your '+f_name+ ' function</div>';
			//	createTabList(objectData);
				return false;
			}
		});
	});


}

function showContent(key)
{
	var obj = tabs[key];
	
	var stage = $('#tab'+key +' .dropDownList');
		
	if(!obj) return false;
	
	//Check to see if you have already downloaded content	
	if (obj.feedData.feedContent){
		if (obj.feedData.feedContent.length == 3){
			$.each(obj.feedData.feedContent,function(i){stage.append(obj.feedData.feedContent[i]);});
			return true;
		}
	}
	
	//Create loading text 
	var loading = $('<div>').addClass('loading').text('*laddar*').css({
		'color':'#BBBBBB',
		'font-size' : '15px',
		'text-align' : 'center'
	});
	stage.append(loading);
	
	//Create feedcontent array so you dont need to download data more than once
	var feedContent = new Array;
	//Push it into feedData
	obj.feedData = {'feedContent' : feedContent};
	
	/* Forming the query: */
	var query = "select * from feed where url='"+obj.feed+"' LIMIT 3";
	
	/* Forming the URL to YQL: */
	var url = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent(query)+"&format=json&callback=?";
	
	
	
	$.getJSON(url,function(data){
		//Line before content
		/* item exists in RSS and entry in ATOM feeds: */
		$.each(data.query.results.item || data.query.results.entry,function(){
			try{
				
				/* Trying to call the user provided function, "this" the rest of the feed data: */
				var feed = obj['functionRss'](this).addClass('feedBody');
				obj.feedData.feedContent.push(feed);
				stage.append(feed);
				$('.loading').remove();
				
			}
			catch(e){
				/* Notifying users if there are any problems with their handler functions: */
				var f_name =obj['functionRss'].toString().match(/function\s+(\w+)\(/i);
				if(f_name) f_name = f_name[1];
				
				stage.append('<div>There is a problem with your '+f_name+ ' function</div>');
				return false;
			}
		})
	});
}
function showDropDown(obj)
{
	
	if($('#feedWidget .dropDownList').length){
		/* If the drop down is already shown, hide it: */
		var t = $('.dropDownList');
		
			/*If the dropdown clicked, is the one showing reset, then return false. */
		if ($('#'+obj.attr('id') + ' .dropDownList').length){
			$('#'+obj.attr('id') +' .dropDownList').slideUp('fast',function(){ $(this).remove(); });
			return false;
		}
	}
	
	var activeTab = obj;
	var offsetTop = -10;

	/* Creating the drop down div on the fly: */
	var dropDown = $('<div>').addClass('dropDownList').css({

			'top'	: offsetTop,
			'width'	: activeTab.width() - 10
	
	}).hide().appendTo(activeTab);
	
	dropDown.empty();
	//Line  before 
	dropDown.append($('<div>').addClass('line'));
	
	//every object's name is tab+number; extract number
	showContent(obj.attr('id').substr(3));
	
	dropDown.slideDown('fast');
	
}

function twitter(item)
{
	//Possible available functions
	
	/* Formats the tweets, by turning hashtags, mentions an URLS into proper hyperlinks: */
	return $('<div>').html(
			formatString(item.description || item.title)+
			' <a href="'+(item.link || item.origLink)+'" target="_blank">[tweet]</a>'
	);
}

function checkStringForHTMLImage(string){
	// function to search for image tags and sort for images larger than a certain size to avoid trash
	//Make function to a loop that searches for an image thru the whole item. Now it checks for the first object and validates it.
	var tagIndex1 = string.indexOf('<img ');
	if (tagIndex1 == -1) {
		tagIndex1 = string.indexOf('<IMG ');
		if (tagIndex1 == -1) return false;
	}
	var tagIndex2 = string.indexOf('>',tagIndex1);
	
	var imageSizeIndex1 = string.indexOf(' width="',tagIndex1);
	if (imageSizeIndex1 == -1) {
		imageSizeIndex1 = string.indexOf(' WIDTH="',tagIndex1);
	}
	
	//Do not search after last tag
	if (imageSizeIndex1 < tagIndex2 && imageSizeIndex1 != -1){ 
		var imageSizeIndex2 = string.indexOf('" ',imageSizeIndex1 + 8);
		var sizeOfWidth = string.substring(imageSizeIndex1+8,imageSizeIndex2);

		if (Number(sizeOfWidth) < 50) return false;
	};

	var tagIndexsrc = string.indexOf(' src="',tagIndex1);
	if (tagIndexsrc == -1) {
		tagIndexsrc = string.indexOf(' SRC="',tagIndex1);
		if (tagIndexsrc == -1) {return false;}
	}
	
	tagIndex2 = string.indexOf(('"'),tagIndexsrc + 6);;


	return string.substring(tagIndexsrc,tagIndex2+1);
}

function rss(item)
{

	var obj = $('<div>').html((item.description || item.content.content));

	var contentString = obj.text();
	var html = obj.html();
	
	var image = '';
	if (checkStringForHTMLImage(html)) {image = ('<img class="feedBodyImage"' + checkStringForHTMLImage(html) + ' />');}
	

// no content longer than:
	if (contentString.length > 100){
		contentString = contentString.substr(0,100);
	}
	var titleString = '[NO TITLE]';
	//Check if the item contains a string.
	if ((item.title.content || item.title).length > 0){titleString = (item.title.content || item.title); }
	//Return a whole feed with the structure div title, div image, div content, div link to content
	var linkString;
	//measures for the different blogs, 
	if (item.link.length == 5){linkString = item.link[4].href;}
	else if (item.link){linkString = item.link;}
	else {linkString = item.origLink;}
	
	return $('<div>').html(	'<div class="feedBodyTitle">' + formatString(titleString) + '</div>'  + '<div>' + image + '</div>'
	
			+ '<div class="feedText">' + contentString + '...' + '</div>'+ '<div class="feedBodyLink">' + ' <a href="'+ linkString +'" target="_blank">[Gå till]</a>' + '</div>'  /*+ '<div class="feedDate">' + (item.pubDate || item.published) + '</div>' */
			
	);
}

function buzz(item)
{
	//Possible available functions
	return $('<div>').html(
			formatString(item.content[0].content || item.title.content || item.title)+
			' <a href="'+(item.origLink || item.link[0].href || item.link)+'" target="_blank">[read]</a>'
	);
}
function title(item,obj)
{
	var titleString = '';
	var dateString = '';

	//Check if the items contains a string.
	if ((item.title.content || item.title).length > 0){titleString = (item.title.content || item.title); }
	if ((item.pubDate || item.published).length > 0){dateString = (item.pubDate || item.published); }
	/*Wrap info in an array and send it back*/
	return {'data' :$('<div>').html(
		'<div class="feedName">' + obj.title + '</div>' +	'<div class="feedTitle">' + formatString(titleString) + '</div>' + '<div class="feedLink">' + '<a href="' + obj.link + '" target="_blank"> Gå till </a>' +  '</div>'
	), 'date' : dateString,
	'timeSince' : -1};
}
function formatString(str)
{
	str = str.replace(/<[^>]+>/ig,'');
	str=' '+str;
	str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
	str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
	str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
	return str;
}
