<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     xoops_pagenavi
 * Version:  1.0
 * Date:     Nov 13, 2005
 * Author:   minahito
 * Purpose:  the place holder for xoops pagenavi.
 * Input:    pagenavi =
 *           total = 
 *           current =
 *           perpage =
 *           url = 
 *           offset =
 * 
 * Examples: {xoops_pagenavi total=20 current=3 url="list.php?start="}
 * -------------------------------------------------------------
 */
function smarty_function_xoops_pagenavi($params, &$smarty)
{
	$ret="";

	if(isset($params['pagenavi'])&&is_object($params['pagenavi'])) {
		$perPage =$params['pagenavi']->getPerpage();
		if ($perPage == 0) {
			return;
		}

		$total=$params['pagenavi']->getTotal();
		$totalPages = ceil($params['pagenavi']->getTotal() / $perPage);
		$url=$params['pagenavi']->getRenderUrl();
		$current=$params['pagenavi']->getStart();
	}
	else {
		$perPage=isset($params['perpage']) ? intval($params['perpage']) : 20;
		if ($perPage == 0) {
			return;
		}

		$total=$params['total'];
		$totalPages = ceil($total / $perPage);
		$url=$params['url'];
		$current=$params['current'];
	}

	$offset=isset($params['offset']) ? intval($params['offset']) : 4;

	if($totalPages==0)
		return;

	//
	// check prev
	//
	$prev=$current-$perPage;
	if($prev>=0) 
		$ret.=@sprintf("<a href='%s%d'>&laquo;</a>",$url,$prev);


	//
	// counting
	//
	$counter=1;
	$currentPage=intval(floor(($current+$perPage)/$perPage));
	while($counter<=$totalPages) {
		if($counter==$currentPage) {
			$ret.=@sprintf("<strong>(%d)</strong> ",$counter);
		}
		elseif(($counter>$currentPage-$offset && $counter<$currentPage+$offset) || $counter==1 || $counter==$totalPages) {
			if($counter==$totalPages && $currentPage<$totalPages-$offset) {
				$ret.="... ";
			}
			$ret .= @sprintf("<a href='%s%d'>%d</a> ",$url,($counter-1)*$perPage,$counter);
			if($counter==1 && $currentPage>1 + $offset) {
				$ret.="... ";
			}
		}
		$counter++;
	}

	//
	// check next
	//
	$next=$current + $perPage;
	if($total>$next)
		$ret.=@sprintf("<a href='%s%d'>&raquo;</a>",$url,$next);


	print $ret;
}

?>
