/**
 * Gets a random number
 */
function get_random_number(range)
{
	return Math.floor(Math.random() * range);
}


/**
 * Gets a random character
 */
function get_random_char()
{
	var chars = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ';
	return chars.substr( get_random_number(62), 1 );
}


/**
 * Generates the radom id
 */
function random_id(size)
{
	var str = '';

	for(var i = 0; i < size; i++)
	{
		str += get_random_char();
	}

	return str;
}


/**
 * Main processing loop
 */
$(document).ready(function() {
	// replaces [more] and [/more] tags with anchor links
	$('div[id^="section"]').each(function() {
		var more = ' <a class="more" href="#more">More ...</a>';
		var less = ' <a class="less" href="#less">... Less</a>';

		$(this).html($(this).html().replace(/\[more\]/g, more).replace(/\[\/more\]/g, less));
	});

	// moves less anchors up to be just below the section parent
	$('.less').each(function() {
		var selected_parents = $(this).parentsUntil('div[id^="section"]');
		if (selected_parents.size() > 0) {
			$(this).insertBefore(selected_parents.last());
		}
	});

	$('.more').each(function() {
		// generates an id
		var unique_id = random_id(32);

		// moves more anchors up to be just below the section parent
		var selected_parents = $(this).parentsUntil('div[id^="section"]');
		if (selected_parents.size() > 0) {
			$('<span id="begin_' + unique_id + '"></span>').insertAfter(selected_parents.last());
		} else {
			$('<span id="begin_' + unique_id + '"></span>').insertAfter(this);
		}

		// adds the additional attributes to the more anchor
		$(this).attr('id', 'more_' + unique_id);
		$(this).click(function() {
			$('#more_' + unique_id).hide();
			$('#content_' + unique_id).slideDown('fast');
		});

		// selects the content between the more and less anchors and wraps it in a span
		var wrap = '<span class="content_more" id="content_' + unique_id + '" style="display: none;" />';
		$('#begin_' + unique_id).nextUntil('.less').wrapAll(wrap);
		$('#begin_' + unique_id).remove();

		// adds the additional attibutes to the less anchor and moves it inside the span
		var less = $('#content_' + unique_id).next('.less');
		less.attr('id', 'less_' + unique_id);
		less.click(function() {
			$('#content_' + unique_id).slideUp('fast');
			$('#more_' + unique_id).show();
		});
		$(less).appendTo('#content_' + unique_id);
	});
});

