max_length = 70

String.prototype.trim=function(){
	// Trim whitespace
	return this.replace(/^\s*|\s*$/g,'');
}

function sortById(container, item) {
	var max = 0;
	container.children().each(function() {
		id = $(this).attr('id').substr(1)
		if (id > max)
			max = id;
	});
	return (max < item['sort_time']);
}

function renderHeadline(header, time, source, max_length) {
	var pre_length = time.length + source.length;
	if ((pre_length + header.text().length) > max_length) {
		var text_length = max_length-pre_length
		header.text(header.text().substr(0, max_length - pre_length).trim());
		header.append('…')
	}
	header.prepend('<span class="time" title="Publication time (UTC)">' + time + '</span> <span class="source" title="News source">[' + source + ']</span> ');
//	header.prepend('<span class="time" title="Publication time (UTC)">' + time + '</span> ');
	header.wrapInner('<a href="javascript:void(0);"></a>')
	header.find('a').css({cursor:'pointer',whiteSpace:'nowrap'});
}

function activateEntry(entry) {
	$(".active_entry").attr('class', 'entry');
	entry.attr('class', 'entry active_entry');
	$("#display")
		.find('.entries').hide().end()
		.children().replaceWith(entry.clone()).end()
		.find('.summary').show().end()
		.find('h3').text(entry.find('h3').attr('title')).end()
		.find('dl').hide().end()
		.find('.entries').fadeIn('slow').end()
		.click(function() { updateEntries()})
}

function prepEntry(entry) {
	var headline = entry.find('h3');
	var list = entry.find('dl')
	var time = entry.find("dl dd.time");
	var source = entry.find("dl dd.source");
	var summary = entry.find(".summary")
	headline.attr('title', headline.text());
	list.hide();
	summary.hide();
	renderHeadline(headline, time.text(), source.text(), max_length);
	var link = headline.find('a');
	link.click(function(){
		activateEntry($(this).parent('h3').parent('.entry'));
	})
	return entry;
}

function renderEntry(item) {
	var entry = document.createElement("div");
	entry = $('\
		<div class="entry" id="e' + item['sort_time'] +'">\
			<h3>' + '<span class="source" title="News source">' + item['feed_name'] + '</pan>' + item['title'] + '</h3>\
			<dl>\
				<dt>Publication time (UTC)</dt>\
				<dd class="time">' + item['datetime'] +'</dd>\
				<dt>Source</dt>\
				<dd class="source">' + item['feed_name'] + '</dd>\
			</dl>\
			<div class="summary">\
				<h4>News summary</h4>\
				<p>' + item['summary'] + '</p>\
				<p class="buttons">| <a href="/external/url/' + encodeURI(item['link']).substr(7) + '">Read more</a> |</p>\
			</div>\
		</div>');
	entry = prepEntry(entry);
	entry.hide();	
	return entry;
}

function updateContainer(container, input, sort_function, max, render_function) {
	// input: An array of new entries.
	// max: Maximum number of entries in container, "true" means as is, "false" means no max, a number specifies the max.
	// sort_function: The entries may need to be inserted in a certain location depending on some sorting rules.
	// render_function: Each entry may require rendering into HTML/XML.

	count = 0;
	for (var i=input.length-1; i>=0; i--) {
		if (sort_function(container, input[i])) {
			count++;
			var entry = render_function(input[i]);
			container.prepend(entry);
			if (count == 1) active_entry = entry;
		}
	}

	if (count > 0) {
		container.children('.entry').slice(-count).remove();
		container.children('.entry').slice(0, count).fadeIn('slow');
		activeEntry(active_entry)
	}
}

function updateEntries() {
	$.getJSON("/data/get_feeds/int/", function(data) {
		updateContainer($('#headlines'), data, sortById, true, renderEntry);
	});
}


$(function() {
	$("#sec").attr('onclick', 'updateEntries();');
	$("#headlines .entry").each(function(){
		prepEntry($(this));
	});
	$("#headlines").after('<div id="display"><span></span></div>');
});
