// Inline page stuff
function initInlineDisplayMode() {
	if(!hasInlineContent($('#content'))) {
		return;
	}
	// Group each consecutive inline page inside a container
	var containerNum = 0;
	var inlineData = [];
	var inlinePages = $('#content').children('.inlinepage');
	for(i in inlinePages.toArray()) {
		var inlinePage = $(inlinePages.get(i));
		if(inlineData[containerNum] == null) {
			inlineData[containerNum] = [];
			inlineData[containerNum]['content'] = [];
			if(inlinePage.prev().size() == 0) {
				// First consecutive inline page is the first element
				// in the page content prepend the container at
				// the top of the page content
				inlineData[containerNum]['object'] = inlinePage.parent();
				inlineData[containerNum]['method'] = 'prepend';
			} else {
				// First consecutive inline page is succeeding an element
				// in the page content, add the container after
				// the preceeding element
				inlineData[containerNum]['object'] = inlinePage.prev();
				inlineData[containerNum]['method'] = 'after';
			}
		}
		inlineData[containerNum]['content'].push(inlinePage);
		if(inlinePage.next().attr('class') != 'inlinepage'
				|| inlinePage == inlinePages.last()) {
			// Found the last consecutive inline page
			containerNum++;
		}
	}
	// Create containers for the consecutive inline pages
	// and move the pages there
	for(i in inlineData) {
		var containerId = 'inlinecontainer' + i;
		var containerHtml = '<div id="' + containerId + '" />';
		eval('inlineData[i]["object"].' + inlineData[i]['method'] + '(containerHtml)');
		var container = $('#' + containerId);
		$.each(inlineData[i]['content'], function(i, e) {
			container.append(e);
		});
		addInlineDisplayButtons(container);
		if(isFeedReaderPage()) {
			editInlineContent(container);
		}
	}
}

var INLINE_DISPLAY_MODE = { 'ALL': 'all', 'FIT': 'fit', 'SINGLE': 'single' };

// Buttons that can be used to switch the inline content display mode
function addInlineDisplayButtons(container) {
	var inlineDisplayModeSelection = $('<div class="inlinedisplaymodeselection"/>');
	if(isFeedReaderPage()) {
		container.before(inlineDisplayModeSelection);
	} else {
		container.children('.inlinepage').first().before(inlineDisplayModeSelection);
	}
	var containerIndex = container.parent().find('.inlinedisplaymodeselection').size() - 1;
	if(inlineDisplayMode(containerIndex) == null) {
		inlineDisplayMode(containerIndex, INLINE_DISPLAY_MODE.ALL);
	}
	inlineDisplayModeSelection.append('<b>Postings display mode:</b>');
	inlineDisplayModeSelection.append('<input type="radio" name="inlinedisplaymode' + containerIndex + '" id="inlinedisplaymodeall' + containerIndex + '" class="inlinedisplaymodeall" /><label for="inlinedisplaymodeall' + containerIndex + '" title="Big page of postings">all</label>');
	inlineDisplayModeSelection.append('<input type="radio" name="inlinedisplaymode' + containerIndex + '" id="inlinedisplaymodefit' + containerIndex + '" class="inlinedisplaymodefit" /><label for="inlinedisplaymodefit' + containerIndex + '" title="Fit postings in the browser window">fit</label>');
	inlineDisplayModeSelection.append('<input type="radio" name="inlinedisplaymode' + containerIndex + '" id="inlinedisplaymodesingle' + containerIndex + '" class="inlinedisplaymodesingle" /><label for="inlinedisplaymodesingle' + containerIndex + '" title="Display one posting at a time">single</label>');
	switchInlineDisplayMode(container, containerIndex, inlineDisplayMode(containerIndex));
	inlineDisplayModeSelection.find('input').change(function() {
			var newMode = $(this).attr('class').replace('inlinedisplaymode', '');
			switchInlineDisplayMode(container, containerIndex, newMode);
		});
	$(window).resize(function() {
		if(inlineDisplayMode(containerIndex) == INLINE_DISPLAY_MODE.FIT) {
			setInlineContentHeight(container);
		}});
	// Don't allow fit inline display mode if more than one
	// group of inline content on the page
	if(containerIndex > 1) {
		container.parent().find('.inlinedisplaymodefit').next().remove();
		container.parent().find('.inlinedisplaymodefit').remove();
	}
	// Keypress handler for navigating postings in 'single' mode
	$(window).keypress(function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		switch(code) {
			case 37:
				$('.inlinenavigationleftlink').first().click();
				break;
			case 39:
				$('.inlinenavigationrightlink').first().click();
				break;
		}
	});
}

// Setup inline content displaying according to desired inline content display mode
function switchInlineDisplayMode(container, containerIndex, newMode) {
	switch(newMode) {
		case INLINE_DISPLAY_MODE.ALL:
			// inlinenavigation and postingposition are used in the 'single' mode
			container.find('.inlinenavigation').remove();
			container.find('.postingposition').remove();
			container.css('height', 'auto');
			container.css('max-height', 'none');
			container.css('overflow', 'visible');
			container.find('.inlinepage').css('display', isFeedReaderPage() ? 'inline' : 'block');
			break;
		case INLINE_DISPLAY_MODE.FIT:
			// inlinenavigation and postingposition are used in the 'single' mode
			container.find('.inlinenavigation').remove();
			container.find('.postingposition').remove();
			container.css('overflow', 'auto');
			container.find('.inlinepage').css('display', isFeedReaderPage() ? 'inline' : 'block');
			if(isFeedReaderPage()) {
				container.scrollTop(0);
			}
			setInlineContentHeight(container);
			break;
		case INLINE_DISPLAY_MODE.SINGLE:
			var currentPosting = 1;
			container.css('height', 'auto');
			container.css('max-height', 'none');
			container.css('overflow', 'visible');
			container.find('.inlinepage').css('display', 'none');
			if(!hasInlineContent(container)) {
				break;
			}
			// inlinenavigation contains arrows and titles of
			// previous and next postings that can be used to
			// change the shown feed
			var inlineNavigationHtml = '<div class="inlinenavigation"><span><a class="inlinenavigationleftlink" href="#">&larr; <span class="inlinenavigationlefttitle"/></a></span><span style="float:right;"><a class="inlinenavigationrightlink" href="#"><span class="inlinenavigationrighttitle"/> &rarr;</a></span></div>';
			if(isFeedReaderPage()) {
				container.children('p').first().after(inlineNavigationHtml);
			} else {
				container.find('.inlinedisplaymodeselection').after(inlineNavigationHtml);
			}
			displayInlinePage(container, currentPosting, 0);
			// Show previous posting
			container.find('.inlinenavigationleftlink').click(function() {
				var postings = container.find('.inlinepage');
				if(postings.size() == 0) {
					return false;
				}
				if(currentPosting + 1 <= postings.size()) {
					if(isFeedReaderPage()) {
						markFeedPostingRead(postings.slice(currentPosting - 1, currentPosting));
					}
					displayInlinePage(container, currentPosting, 1);
					currentPosting++;
				}
				return false;
			});
			// Show next posting
			container.find('.inlinenavigationrightlink').click(function() {
				var postings = container.find('.inlinepage');
				if(postings.size() == 0) {
					return false;
				}
				if(currentPosting - 1 >= 1) {
					if(isFeedReaderPage()) {
						markFeedPostingRead(postings.slice(currentPosting - 1, currentPosting));
					}
					displayInlinePage(container, currentPosting, -1);
					currentPosting--;
				}
				return false;
			});
			break;
		default:
			return inlineError(container, 'Invalid inline content display mode: ' + newMode);
	}
	inlineDisplayMode(containerIndex, newMode);
	$('#inlinedisplaymode' + inlineDisplayMode(containerIndex) + containerIndex).attr('checked', 1);
}

// Current inline content display mode stored in a cookie
function inlineDisplayMode(containerIndex, mode) {
	var cookieName = 'inline_display_mode_' + containerIndex;
	if(mode != null && mode.length > 0) {
		$.cookie(cookieName, mode, {expires: 10000});
	}
	return $.cookie(cookieName);
}

// Adjust the height of the feed content in 'fit' mode to match
// the size of the browser window
function setInlineContentHeight(container) {
	var minHeight = 200;
	var heightOffset = isFeedReaderPage() ? 300 : 200;
	var elementsHeight = $('.page')
	var newHeight = $(window).height() - heightOffset;
	var height = newHeight > minHeight ? newHeight : minHeight;
	container.css('max-height', height);
}

// In 'single' mode, show the desired posting on the screen
// and update navigation elements
function displayInlinePage(container, currentPosition, delta) {
	var newPosition = currentPosition + delta;
	var postings = container.find('.inlinepage');
	if(newPosition < 1) {
		return inlineError(container, 'Posting position too small: ' + newPosition);
	}
	if(newPosition > postings.size()) {
		return inlineError(container, 'Posting position too large: ' + newPosition);
	}
	if(newPosition == 1) {
		// Showing the first posting
		container.find('.inlinenavigationrightlink').addClass('inlinenavigationdisabled');
	} else {
		container.find('.inlinenavigationrightlink').removeClass('inlinenavigationdisabled');
	}
	if(newPosition == postings.size()) {
		// Showing the last posting
		container.find('.inlinenavigationleftlink').addClass('inlinenavigationdisabled');
	} else {
		container.find('.inlinenavigationleftlink').removeClass('inlinenavigationdisabled');
	}
	var posting = postings.slice(newPosition - 1, newPosition);
	// Remove the existing position indicator and
	// add it again with the current values
	postings.find('.postingposition').remove();
	posting.find('.inlineheader > .header > a').prepend('<span class="postingposition">[' + newPosition + '/' + postings.size() + '] </span>');
	// Update title of the link leading to previous posting
	if(newPosition > 1) {
		container.find('.inlinenavigationrighttitle').text(posting.prev().find('.inlineheader > .header > a').text());
	} else {
		container.find('.inlinenavigationrighttitle').text('');
	}
	// Update title of the link leading to next posting
	if(newPosition < postings.size()) {
		container.find('.inlinenavigationlefttitle').text(posting.next().find('.inlineheader > .header > a').text());
	} else {
		container.find('.inlinenavigationlefttitle').text('');
	}
	// Hide the preceding posting and show current one
	if(delta > 0) {
		posting.prev().css('display', 'none');
	}
	if(delta < 0) {
		posting.next().css('display', 'none');
	}
	posting.css('display', 'inline');
}

// Show an error message in the inline content display space
function inlineError(container, text) {
	container.children().remove();
	container.append('<span class="error">' + text + '</span>');
	container.scrollTop(0);
	return;
}

function hasInlineContent(container) {
	return container.children('.inlinepage').size() > 0;
}

// Used to detect feedreader support
function isFeedReaderPage() {
	return $('#feedreadercontent').size() > 0 && $('#feedreaderlinks').size();
}

// Inject the code
$(document).ready(function() {
	initInlineDisplayMode();
});

