<?php

/**
* IRB_Jumper - Class custom sorting lines
* NOTE: Requires PHP version 5 or later and MySQL version 4 or later
* @package irb_movestring
* @author IT studio IRBIS-team
* @copyright © 2012 IRBIS-team
*/

class IRB_Jumper
{


    public  
$table;
    public  
$id;
    public  
$sorts;    
    private 
$and;
    private 
$where;        

////////////////////////////
//    PUBLIC
///////////////////////////    
/**
* Конструктор 
* @param string $table // Таблица MySQL
* @param string $id    // Первичный ключ
*/    
    
public function __construct($table$sorts 'order'$id 'id')
    {
        
$this->table $table;
        
$this->sorts $sorts
        
$this->id    $id;        
    }

/**
* Инсталлятор 
* @return void
*/
    
public function Installation()
    {      
     
        
mysqlQuery("ALTER TABLE `"$this->table ."` 
                     ADD `"
$this->sorts ."` INT(10) NOT NULL DEFAULT '0'"
                    
) or die(mysql_error());
        
        
$this->resetSort();
        
    }    

/**
* Сброс сортировки
* @return void
*/
    
public function resetSort()
    {
        
        
mysqlQuery("UPDATE `"$this->table ."` 
                     SET    `"
$this->sorts ."` = `"$this->id ."`"
                    
$this->where
                    
);
     
    }
    
/**
* Установка многопользовательского режима 
* @return void
*/
    
public function setMultiple($field$parent)
    {
        
$this->where " WHERE `"$field ."` = ". (int)$parent ;    
        
$this->and   " AND   `"$field ."` = ". (int)$parent ;
    } 
    
/**
* Установка режима модифицируемой таблицы
* @return void
*/
    
public function setModification()
    {
        
mysqlQuery("UPDATE `"$this->table ."`
                      SET  `"
$this->sorts ."` = 
                          (SELECT @i := @i + 1 
                            FROM (SELECT @i := MAX(`"
$this->sorts ."`) 
                                   FROM `"
$this->table ."`
                                   "
$this->where ."
                                 ) AS a
                          )
                      WHERE `"
$this->sorts ."` = 0 
                      "
$this->and
                  
);
    }     
    
/**
* Изменение порядка сортировки
* @param int $id      // идентификатор строки
* @param string $move // Направление 
* @return boolean
*/
    
public function moveString($id$move)
    {
        
$num $this->_getPos($id);
        
        if(
$move === 'up')
        {
            if(
$num 1)
                return 
false
          
            
$data $this->_getSorts($num'<');
            
$swap = !empty($data[$this->sorts]) ? $data[$this->sorts] : 1;
        }
        elseif(
$move === 'down')
        {
            
$data $this->_getSorts($num'>');       
         
            if(empty(
$data[$this->sorts]))
                return 
false;         
         
            
$swap $data[$this->sorts];  
        }
        else
            return 
false
  
        return 
$this->_changeString($num$swap);
    }    

/**
* Джампер 
* @param int $id  // идентификатор строки
* @param string $direct // направление прыжка
* @return boolean
*/
    
public function jumpString($id$direct 'up')
    {
        
$func = ($direct == 'down') ? 'MAX' 'MIN';
        
$end  $this->_getBorder($func);
        
        if(
$direct == 'up')
        {
            
mysqlQuery("UPDATE `"$this->table ."` 
                         SET    `"
$this->sorts ."` = `"$this->sorts ."` + 1"
                        
$this->where
                        
);
             
        }
        else
            ++
$end;
     
        
mysqlQuery("UPDATE `"$this->table ."` 
                     SET    `"
$this->sorts ."` = "$end ."
                     WHERE  `"
$this->id ."` = "abs((int)$id)
                    . 
$this->and
                    
);
     
        return (
mysql_affected_rows() > 0) ? true false;
    }     

/**
* Замена несоседних строк
* @param int $id_start // идентификатор строки "откуда"
* @param int $id_pos   // идентификатор строки "куда"
* @return boolean
*/
    
public function changePos($id_from$id_to)
    {
        
$from $this->_getPos($id_from);        
        
$to   $this->_getPos($id_to);
        
        if(!empty(
$from) && !empty($to))
            return 
$this->_changeString($from$to);
    }

////////////////////////////
//    PRIVATE
///////////////////////////

/**
* Метод определения позиции
* @param string $func    // Минимум или максимум
* @return int
*/
    
private function _getPos($id)
    {
        
$res mysqlQuery("SELECT `"$this->sorts ."` AS `pos`
                            FROM  `"
$this->table ."`
                            WHERE `"
$this->id ."` = "abs((int)$id
                            . 
$this->and
                            
);
        
        return 
mysql_result($res0);
    } 

/**
* Метод определения позиции
* @param int $num     // Номер текущей позиции
* @param string $char // Знак
* @return array
*/
    
private function _getSorts($num$char)
    {
        
$res mysqlQuery("SELECT `"$this->sorts ."` FROM `"$this->table ."`
                            WHERE  `"
$this->sorts ."` "$char ." "$num 
                            
$this->and .
                            
" ORDER BY `"$this->sorts ."` DESC
                            LIMIT 1"
);
     
        return 
mysql_fetch_assoc($res);
    }     
    
/**
* Метод смены номеров сортировки
* @param $start // откуда
* @param $end   // куда
* @return void
*/
    
private function _changeString($start$end)
    {
        
mysqlQuery("UPDATE `"$this->table ."` 
                    SET `"
$this->sorts ."` = CASE `"$this->sorts ."` 
                                                WHEN "
$start ."  THEN "$end .
                                                WHEN "
$end ."    THEN "$start .
                                              END 
                    WHERE `"
$this->sorts ."` IN ("$start .", "$end .")"
                    
$this->and
                    
);      
     
        return  (
mysql_affected_rows() > 0) ? true false;                    
    } 
    
/**
* Метод определения границ 
* @param string $func    // Минимум или максимум
* @return int
*/
    
private function _getBorder($func 'MAX')
    {
        
$res mysqlQuery("SELECT "$func ."(`"$this->sorts ."`) AS `num`
                            FROM `"
$this->table ."`
                            "
$this->where
                            
);
        
        return 
mysql_result($res0);
    }    
}