(function($) {

    $.fn.productpager = function(options) {

        var opts = $.extend({}, $.fn.productpager.defaults, options);

        // empty out the destination element and then render out the product pager with the supplied options
        $(this).empty().append(renderProductPager(options.url, parseInt(options.pagenumber), parseInt(options.pagecount)));     
        
    };

    function renderProductPager(url, currentPage, lastPage) {
	var i = 0;
	var j = 0;

        // setup $pagerproductpager to hold render
        var $productpager = $('<div id="pagelinks"></div>');

	// print Previous page link if there are previous pages
	if (currentPage != 1) {
		var previousPage = currentPage - 1;
		/*
		// print link to first page if more than one previous pages available
		if (previousPage > 3) {
			$productpager.append('<a href="' + url + '&index=0' + '">&laquo; Alkuun</a>');
		}
		*/
		var previousPageNro = previousPage - 1;
		$productpager.append('<a href="' + url + '&index=' + previousPageNro + '">&laquo; Edellinen</a>');
		// print dots if more than one previous pages available
		if (previousPage > 3) {
			$productpager.append('<span class="dots">...</span>');
		}
	}

	// print max 3 previous page numbers as links
	i = currentPage-3;
	while (i < currentPage) {
		if (i > 0) {
			var pageNro = i-1;
			$productpager.append('<a href="' + url + '&index=' + pageNro + '">' + i + '</a>');
		}
		i++;
	}

	// print nothing if there is only one page
	if (lastPage != 1) {
		$productpager.append('<span class="currentPage">' + currentPage+ '</span>');
	}

	// print max 3 next page numbers as links
	i = currentPage+1;
	j = 0;
	while (i <= lastPage && j < 3) {
		var pageNro2 = i-1;
		$productpager.append('<a href="' + url + '&index=' + pageNro2 + '">' + i + '</a>');
		i++;
		j++;
	}

	// print Next page link if there are previous pages
	if (currentPage!= lastPage) {
		var nextPage = currentPage + 1;
		// print dots if more than more than one next page
		if ((lastPage - nextPage) > 3) {
			$productpager.append('<span class="dots">...</span>');
		}
		var nextPageNro = nextPage - 1;
		$productpager.append('<a href="' + url + '&index=' + nextPageNro + '">Seuraava &raquo;</a>');
		/*
		// print link to last page if more than more than one next page
		if ((lastPage - nextPage) > 3) {
			var lastPageNro = lastPage-1;
			$productpager.append('<a href="' + url + '&index=' + lastPageNro + '">Loppuun &raquo;</a>');
		}
		*/
	}

        return $productpager;
    }

})(jQuery);

