<?php

function paging($query,$totalRow=0,$page=0,$pagemode="postback",$callback="search")
{
	$length=GRIDLENGTH;
	$pagelimit=PAGELENGTH;
	if($page==0) { $currpage=CURRENTPAGE; } else { $currpage=$page; }
	
	if(URI!="") { $pagename=PAGENAME."?".URI."&"; } else { 	$pagename=PAGENAME."?"; }
	
	$pagehtml="";
	
	if($totalRow==0)
	{
		$qry=$query;
		//if(stripos($qry,"*")) { $qry=str_replace("*","count(*)",$qry); }
		//else
		//{
			$tmpselectidx=stripos($qry,"select")+6;
			$tmpfromidx=stripos($qry,"from");
			$tmpqry = substr($qry,$tmpselectidx,$tmpfromidx-$tmpselectidx);
			$qry=str_replace($tmpqry," count(*) ",$qry);
		//}
		
		$firstidx = stripos($qry,"order by");
		if($firstidx=="") { $firstidx = stripos($qry,"limit "); }
		$qry = substr($qry,0,$firstidx);
		
		$rsc=mysql_query($qry);
		$dt=mysql_fetch_row($rsc);
			
		$totalRow = $dt[0];
	}
	$totalpage = ceil($totalRow/$length);
	
	$rangefirst=floor(($currpage-1)/$pagelimit)*$pagelimit;
	$rangelast=ceil($currpage/$pagelimit)*$pagelimit;
	
	$next = $rangelast+1;
	$last = $rangefirst;
	if($next>$totalpage) { $next=1; }
	if($last<1) { $last=$totalpage; }
	
	// Setup First and Last
	if($totalpage>$pagelimit)
	{
		if($pagemode=="postback")
		{	
			$firsthtml.="<a href=\"{$pagename}currpage=1\">First</a>";
			$firsthtml.="&nbsp;&nbsp;<a href=\"{$pagename}currpage=$last\"><<</a>&nbsp;&nbsp;";
			
			$lasthtml.="&nbsp;&nbsp;<a href=\"{$pagename}currpage=$next\">>></a>";
			$lasthtml.="&nbsp;&nbsp;<a href=\"{$pagename}currpage=$totalpage\">Last</a>";		
		}
		else if($pagemode=="ajax")
		{	
			$firsthtml.="<a href=\"javascript:void()\" onclick=\"$callback('1')\">First</a>";
			$firsthtml.="&nbsp;&nbsp;<a href=\"javascript:void()\" onclick=\"$callback('$last')\"><<</a>&nbsp;&nbsp;";
			
			$lasthtml.="&nbsp;&nbsp;<a href=\"javascript:void()\" onclick=\"$callback('$next')\"> >></a>";
			$lasthtml.="&nbsp;&nbsp;<a href=\"javascript:void()\" onclick=\"$callback('$totalpage')\">Last</a>";		
		}
	}
					
	// Setup start and limit
	$start=$rangelast-$pagelimit+1;
	$pagelimit=$rangelast;

	for($i=$start;$i<=$totalpage;$i++)
	{
		if($i>$pagelimit) { break; }
		if($currpage==$i) { $plable = "<font color=\"#FF0000\"><b>$i</b></font>"; } else { $plable = "$i"; }
		if($pagehtml!="")
		{
			if($pagemode=="postback") { $pagehtml.=" | <a href=\"{$pagename}currpage=$i\">$plable</a>"; }
			else if($pagemode=="ajax") { $pagehtml.=" | <a href=\"javascript:void()\" onclick=\"$callback('$i')\">$plable</a>"; }
		}
		else
		{
			if($pagemode=="postback") { $pagehtml.="<a href=\"{$pagename}currpage=$i\">$plable</a>"; }
			else if($pagemode=="ajax") { $pagehtml.="<a href=\"javascript:void()\" onclick=\"$callback('$i')\">$plable</a>"; }			
		}
	}		
	return $firsthtml.$pagehtml.$lasthtml;
}

?>