<?php

class walker {
   var $onpage = 20;
   var $visible_pages = 10;
   var $html;
   var $sql;
   var $page;
   var $templ = 'pagewalker.htm';
   var $allcount;
   var $parsed_url;
   var $prefix = 'curpage';
    
   function __construct( $allcount = 0, $onpage = 0 ) {
   	   if ($onpage) {
   	   	    $this->onpage = $onpage;   
   	   }
	   $this->allcount = intval($allcount);
	   $this->page = intval($_GET[$this->prefix]);
   }

   function setPrefix($prefix) {
       $this->prefix = $prefix;
	   $this->page = intval($_GET[$this->prefix]);
   }
   
   function setTempl( $templ ) {
   		$this->templ = $templ;   
   }
   
   function process() {
   	global $R, $url_arr;
   		
   	$tpl = $R->getTpl( $this->templ, 'body' );
   	$tpln = $R->getTpl( $this->templ, 'num' );
   	$tplnc = $R->getTpl( $this->templ, 'num_c' );
   	$tplnf = $R->getTpl( $this->templ, 'num_first' );
   	$tplpp = $R->getTpl( $this->templ, 'page_prev' );
   	$tplpn = $R->getTpl( $this->templ, 'page_next' );

    $this->parsed_url[] = $this->prefix;
   		
	$this->html = "";
	$pages = $this->allcount/$this->onpage;
	
	if ( $this->allcount < $this->onpage ) return false;

	if ( $this->page >= 1 ) {
    	$tt = $R->set('url', $this->getUrl($this->page - 1), $tplpp );
		$tpl = $R->parse('pages', $tt, $tpl );
	}
    
    for($i=max(0, $this->page - 5);$i<min($pages,  $this->page + 5);$i++) {
		if ($i == $this->page) $tt = $tplnc; else $tt = $tpln;
		$tt = $R->set('page_num', $i+1, $tt );
    	$tt = $R->set('url', $this->getUrl( $i ), $tt );
		$tpl = $R->parse('pages', $tt, $tpl );
	}

	if ( $this->page < ($pages-1) ) {
        $tt = $R->set('url', $this->getUrl( $this->page + 1 ), $tplpn );
		$tpl = $R->parse('pages', $tt, $tpl );
	}

    $this->sql = ' LIMIT ' . max(0, intval($this->page)  * $this->onpage ) . ', ' . $this->onpage ;
   	$this->html = $tpl;
   }

   function getHTML() {
  		if (!$this->html) $this->process(); 
  		return $this->html;
   }
   
   function getSQL() {
  		if (!$this->sql) $this->process(); 
        return $this->sql;   
   }

   function getUrl($page_id = 0) {
      $uri  = $_SERVER['REQUEST_URI'];
      $ua = parse_url($uri);
      parse_str($ua['query'], $query);
      if ($page_id > 0 ) {
        $query[$this->prefix] = $page_id;
      } else {
        unset($query[$this->prefix]);
      }
      $pars = http_build_query($query);
      if ($pars) {
           return $ua['path'] . '?' . $pars;   
      } else {
           return $ua['path'];
      }
   }
}

?>
