
  var current_sbpage = 1;        // сраница с которой начать показ, 1-based.
  var autocycle      = true;     // использовать ли автопрокрутку вначале.
  var ac_timeout     = 5 * 1000; // интервал автопрокрутки в миллисекундах.
  
  var ac_timer = null;
  
  $(document).ready(switchBoxInit);
  
  function switchBoxInit()
  {
    if(typeof(switchBoxItems) == 'undefined')
      return;
    
    if(switchBoxItems.length == 0)
    {
      // если список элементов пуст, прячем весь блок.
      $('.switchBox').html('');
      return;
      
    }
    
    // ограничение на номер начальной страницы,
    // защита от дурака.
    // -----
    
    if(current_sbpage < 1 || current_sbpage > switchBoxItems.length)
      current_sbpage = 1;
      
    // показываем первую страницу.
    switchbox_draw();
    
    // запускаем автопрокрутку.
    startAutoCycle();
    
  }
  
  function startAutoCycle()
  {
    if(autocycle == true)
      ac_timer = setTimeout(doAutoCycle, ac_timeout);
      
  }
  
  function doAutoCycle()
  {
    next_sbpage(true);
    
    if(autocycle == true)
      ac_timer = setTimeout(doAutoCycle, ac_timeout);
    
  }
  
  function switchbox_draw()
  {
    var cat_id = switchBoxItems[current_sbpage - 1];
    
    var text = $('#sbp_' + cat_id).html();
    
    $('#switchbox-text').html(text);
    $('#switchbox-label').html(current_sbpage + ' / ' + switchBoxItems.length);
    
  }
  
  function stopAutoCycle()
  {
    autocycle = false;
    clearTimeout(ac_timer);
    
  }
  
  function next_sbpage(auto)
  {
    if(!auto && autocycle)
      stopAutoCycle();
    
    var next_i = current_sbpage + 1;
    
    if(next_i > switchBoxItems.length)
      next_i = 1;
      
    current_sbpage = next_i;
    
    switchbox_draw();
    
  }
  
  function prev_sbpage(auto)
  {
    if(!auto && autocycle)
      stopAutoCycle();

    var prev_i = current_sbpage - 1;
    
    if(prev_i < 1)
      prev_i = switchBoxItems.length;
      
    current_sbpage = prev_i;
    
    switchbox_draw();
    
  }
  