/**
 * Functions to handle sliding elements and loading pages via ajax
 */

/**
 * Intialize markup intended to support a sliding container
 */
function slideContainerInit(options)
{
	$('.slidePrev,.slideNext')
	.removeClass('slidePrev')
	.removeClass('slideNext')
	.each(function()
	{
		var $this = $(this);

		defaultOptions = {
			// the URL to load new items from via ajax
			slideUrl        : '/ajax/list_more/' + $this.attr('data-channel') + '/?list=channel&videoinfo=false&index=',
			// function to call when the 'next' slide finishes sliding into place
			slideNextFinish : '',
			// function to call when the 'prev' slide finishes sliding into place
			slidePrevFinish : '',
			// whether to ajax load pages when 'next' is clicked at the end of the slide container
			pagesLoad       : true,
			// how many pages have already been loaded into the DOM
			pagesPreloaded  : null,
			// how many pages to show per slide
			pagesPerSlide   : null,
			// whether to apply default styling rules to the slide container
			slideStyle      : true
		};

		// store the default options in the anchor element
		for (option in defaultOptions)
		{
			$this.data(option, defaultOptions[option]);
		}

		// override the default options with the supplied options and store them in the anchor
		for (option in options)
		{
			$this.data(option, options[option]);
		}

		$this.data('container', $this.parent().find('ul'));

		if ($this.data('slideStyle') == true)
		{
			$this.data('container').css({
				'list-style' : 'none',
				position     : 'relative',
				margin       : 0,
				padding      : 0
			})
			.find('li').css({
				'float' : 'left'
			})
			.parent().parent().css({
				position : 'relative',
				overflow : 'hidden'
			});
		}
	})
	.click(function(event)
	{
		event.preventDefault();

		slideContainer($(this));
	});
}

/**
 * Calculate the full width of an element including its padding and margin sizes
 */
function fullWidth(obj)
{
	return parseInt(obj.outerWidth())
		+ parseInt(obj.css('padding-left'))
		+ parseInt(obj.css('padding-right'))
		+ parseInt(obj.css('margin-left'))
		+ parseInt(obj.css('margin-right'));
}

/**
 * Handle loading pages via ajax and sliding new pages into view
 */
function slideContainer($link)
{
	if ($('.slider ul li').length < 6)
		return;

	var $container = $link.data().container,
	direction = $link.attr('data-action'),
	slideUrl = $link.data().slideUrl;

	// use jQuery's data() function to associate the below variables with the container object only

	if (typeof $container.data('currentPage') == 'undefined')
		$container.data('currentPage', 1);
	
	if (typeof $container.data('totalPages') == 'undefined')
	{
		if ($link.data().pagesPreloaded != null)
			$container.data('totalPages', $link.data().pagesPreloaded);
		else
			$container.data('totalPages', 1);
	}

	if (typeof $container.data('originalWidth') == 'undefined')
	{
		if ($link.data().pagesPerSlide != null)
			$container.data('originalWidth', fullWidth($container.children()) * $link.data().pagesPerSlide);
		else
			$container.data('originalWidth', fullWidth($container.children()) * $container.children().length);
	}

	if (typeof $container.data('emptyElementCount') == 'undefined')
		$container.data('emptyElementCount', 0);

	// determine if the last X elements in the slide are empty and clone entries from the beginning of the list
	// to fill in the empty spots
	$container.wrap_data = function($data)
	{
		var $empty = $data.find('.empty');

		$empty.each(function()
		{
			var $this = $(this);
			
			// replace the innerHTML of the empty li with the contents of the emptyElementCount-th element
			// from the beginning of the list
			$this.html($container.find('li').eq($container.data('emptyElementCount')).html());

			$container.data('emptyElementCount', $container.data('emptyElementCount') + 1);
		});
	}
	
	// slides to the previous set of elements
	$container.prev = function()
	{
		$container.data('currentPage', $container.data('currentPage') - 1);

		$container.animate({
				left : ((parseInt($container.data('originalWidth'), 10) * -1) * ($container.data('currentPage') - 1))
			}, function()
			{
				if ($link.data('slidePrevFinish') != '')
					window[$link.data('slidePrevFinish')]();
			});
	};

	// slides to the next set of elements and injects a new set of elements if data is passed into the function
	$container.next = function(data)
	{
		var $data = $(data);

		$container.wrap_data($data);

		if ($data.length > 0)
		{
			$container
			.width($container.data('originalWidth') * ($container.data('currentPage')))
			.append($data.find('li'))
			.animate({
				// move the ul element it's width to the left times the number of slides that have been loaded
				left : ((parseInt($container.data('originalWidth'), 10) * -1) * ($container.data('currentPage') - 1))
			}, function()
			{
				if ($link.data('slideNextFinish') != '')
					window[$link.data('slideNextFinish')]();
			});
		}
		else
		{
			$container.animate({
				left : ((parseInt($container.data('originalWidth'), 10) * -1) * ($container.data('currentPage') - 1))
			});
		}
	};

	// don't slide backwards if we're at the first page
	if (direction == 'prev' && $container.data('currentPage') == 1)
	{
		// return the slide back to its original position incase it was dragged out of position
		$container.animate({
			left : '0px'
		});
	}
	// only ajax load new items if they haven't already been loaded
	else if ($container.data('currentPage') == $container.data('totalPages') && direction == 'next')
	{
		$container.data('currentPage', $container.data('currentPage') + 1);

		if ($link.data().pagesLoad == true)
		{
			$('<div />')
			.load(slideUrl + $container.data('currentPage'), function(data, status)
			{
				if (status == 'success')
				{
					if (direction == 'next')
					{
						// we successfully loaded new items, so increase our total page count
						$container.data('totalPages', $container.data('totalPages') + 1);
						$container.next(data);
					}
				}
			});
		}
	}
	// if the items have already been loaded, just slide them into view
	else if ($container.data('currentPage') < $container.data('totalPages') && direction == 'next')
	{
		$container.data('currentPage', $container.data('currentPage') + 1);
		$container.next();
	}
	else if ($container.data('currentPage') > $container.data('totalPages') && direction == 'next')
	{
		console.log('Pages greater than');
		$container.animate({
			left:((parseInt($container.data('originalWidth'), 10) * -1) * ($container.data('currentPage') - 1))
		});
	}
	else if (direction == 'prev')
	{
		$container.prev();
	}
}
