/**
 * @author Frederik Krautwald
 */

jQuery.iPageNav = {
	
	_container : null,
	_item : null,
	_prev : null,
	_next : null,
	
	/**
	 * 
	 * @param {Object} contentPrefix
	 */
	getElement : function(contentPrefix)
	{
		$.iPageNav._item = $('#' + contentPrefix + $('body').attr('id'));
	},
	
	/**
	 * 
	 */
	getPrevious : function()
	{
		$.iPageNav._prev = $.iPageNav._item.prev();
		if ($.iPageNav._prev.is('li')) {
			$.iPageNav._prev = $.iPageNav.writeWrappers($.iPageNav._prev);
		}
	},
	
	/**
	 * 
	 */
	getNext : function()
	{
		$.iPageNav._next = $.iPageNav._item.next();
		
		if ($.iPageNav._next.is('li')) {
			$.iPageNav._next = $.iPageNav.writeWrappers($.iPageNav._next);
		}
	},
	
	/**
	 * 
	 * @param {Object} node
	 */
	writeWrappers : function(node)
	{
		var navText = node.children('a').children('span')[0].innerHTML;
		var navUrl = node.children('a')[0].href;
		return ['a', { href:navUrl, className:'pagenav' }, [ navText ]];
	},
	
	/**
	 * 
	 */
	writeLinks : function(id)
	{
		var val = 0;
		if ($.iPageNav._prev.length > 0) val += 2;
		if ($.iPageNav._next.length > 0) val += 1;
		if (val >= 2) {
			$('#' + id).createAppend(
				$.iPageNav._prev[0], $.iPageNav._prev[1], $.iPageNav._prev[2]
			);
		}
		if (val >= 1) {
			$('#' + id).createAppend(
				$.iPageNav._next[0], $.iPageNav._next[1], $.iPageNav._next[2]
			);
		}
		
		$('#' + id).children('a').each(function(i) {
			if ((i == 0 && val < 2) || i == 1) {
				this.className += ' column last next'
			} else {
				this.className += ' column first previous'
			}
		});
	},
	
	/**
	 * 
	 * @param {Object} o 
	 */
	build : function (o)
	{
		if (o.contentPrefix && o.contentId && o.contentTag) {
			return this.each(
				function () {
					$.iPageNav.getElement(o.contentPrefix);
					$.iPageNav.getPrevious();
					$.iPageNav.getNext();
					$.iPageNav.writeLinks(o.containerId);
				}
			)
		}
	}
	
};

jQuery.fn.extend(
	{
		PageNav : jQuery.iPageNav.build
	}
);

$(function () {
	$.getScript('/global/scripts/lib/jquery.superflydom-0.9g.js', function() {
		$().PageNav(
			{
				containerId :	'pagenav',
				contentPrefix :	'sn-',
				contentId :		'subnav',
				contentTag :	'li'
			}
		);
	});
});