/**
*   Плагин jquery.flex_carousel.js
*   Позволяет организовывать карусели фотографий
*   Работает только с элементами одинакового размера !!!
*   Внутри li должен быть только один элемент и его высота и ширина должна быть задана в css!
*   
*   @author Isaev Roman
*   @modufy_date 08.07.09
*   
*   ToDo:
*   - preload images
*   - ajax
*/

jQuery.fn.flex_carousel = function(ops){
 
  // настройки по умолчанию
  var ops = jQuery.extend({
      start_position: 'center', // Текущая позиция (left, right, center)
      count_visible: 5, // Количество видимых элементов
      animate_time: 1000, // время анимации
      r_margin: 0, // растояние между элементами
      circle: false, // цикличиское движение по кругу
      elem_setting: null // массив параметров видимых элементов (размерность массива, должна совпадать с count_visible)
  },ops);
  
  var count = 0; // общее кол-во элементов
  var first_visible = 0; // указатель на 1-й видимый элемент
  
  var elem_width = 0;
  var elem_height = 0;
  var anim_margin = 0;
    
  var anim_process = false; // определяет идет сейчас анимация или нет
  
  var fs_list_container_width = 0;
  var fs_list_container_height = 0;
 
  return this.each(function() 
  {
      preload_plagin(this);      
  });
 
  function preload_plagin(obj)
  {
      if(ops.elem_setting != null) 
        if(ops.elem_setting.length != ops.count_visible) 
        {
            alert('Ошибка! Неверно заданы параметры! \nДлинна массива elem_setting должна совпадать со значеноем count_visible.');
            return false;
        }
      
      // -----------------------------
      var li = jQuery(obj).find('ul:first').children('li');
      
      jQuery(obj).addClass('foto_scroller');
      jQuery(obj).children('ul').wrap('<div id="fs_list_container"></div>'); // оборачиваем список в контейнер
      
      jQuery(li).css('margin-right', ops.r_margin+'px');
      
      // получаем размеры элементов
      var first_li = jQuery(obj).find('ul:first').children('li:first').find('img:first');       
      elem_width = jQuery(first_li).width();
      elem_height = jQuery(first_li).height();
      anim_margin = elem_width + ops.r_margin;
      
      // ------------------------------
      count = jQuery(li).size();
      
      // определяем первый видимый элемент
      switch (ops.start_position)
      {
        case 'left':
          firstVisible = 0;          
          break;
        case 'right':
          first_visible = count - ops.count_visible;
          break;
        case 'center':
          first_visible = Math.round((count - ops.count_visible)/2);
          break;
      }
      
      // ------------------------------
      // устанавливаем параметры видемых элементов
            
      if(ops.elem_setting != null)
      {
          for(var i=0; i<ops.count_visible; i++)
          {
              jQuery(li).eq(i+first_visible).find('img:first')
                  .css('margin-top', ops.elem_setting[i].margin_t + 'px')
                  .css('width', ops.elem_setting[i].width + 'px')
                  .css('height', ops.elem_setting[i].height + 'px');
              
              // определяем размеры контейнера
              fs_list_container_width += ops.elem_setting[i].width + ops.r_margin;
              var temp = elem_height + ops.elem_setting[i].margin_t;
              if(temp > fs_list_container_height) 
                  fs_list_container_height = temp; 
          }
          fs_list_container_width += elem_width + ops.r_margin;
      } else {
          fs_list_container_width = (elem_width + ops.r_margin)*(ops.count_visible + 1);
          fs_list_container_height = elem_height;
      } 

      // ------------------------------
             
      jQuery(obj).find('#fs_list_container')
          .width( fs_list_container_width )
          .height( fs_list_container_height );  
                  
      // ------------------------------
      // делаем элемент видимыми или нет
            
      //var temp = 'count: '+count+'\nfirst_visible: '+first_visible+'\ncount_visible: '+ops.count_visible+'\n';
      for(var i=0; i<count; i++)
      {
          if( (i >=first_visible) && (i< first_visible + ops.count_visible) ){
              jQuery(li).eq(i).show();
              //temp += 'li_'+i+' visible\n';
          } else {
              jQuery(li).eq(i).hide();
              //temp += 'li_'+i+' hide\n';
          }          
      }
      //alert(temp); 
          
      // ------------------------------
      
      if (count <= ops.count_visible)
      {
          ops.circle = false;
      }
      
      // ------------------------------
      
      state_buttons(obj);
      set_events(obj);   
  }
  
  // установка обработчиков событий
  function set_events(obj)
  {
    // Ховер левой стрелки    
    jQuery(obj).find('#fs_prev').hover(
      function () {
        jQuery(this).css('background-position', 'right -67px');
        jQuery(this).css('cursor','pointer');
      }, 
      function () {
        jQuery(this).css('background-position', 'right top');
        jQuery(this).css('cursor','default');
      }
    );   
    
    // Ховер правой стрелки    
    jQuery(obj).find('#fs_next').hover(
      function () {
        jQuery(this).css('background-position', 'left -67px');
        jQuery(this).css('cursor','pointer');
      }, 
      function () {
        jQuery(this).css('background-position', 'left top');
        jQuery(this).css('cursor','default');
      }
    );
     
    // Нажатие на левую стрелку
    jQuery(obj).find('#fs_prev').click(function () 
    { 
        move_prev(obj);
    });
    
    // Нажатие на правую стрелку
    jQuery(obj).find('#fs_next').click(function () 
    { 
        move_next(obj);         
    });
    
  }
  
// -----------------------------------------------------------------------------  
// --- лево (prev)
// ----------------------------------------------------------------------------- 
  
  // Прогручиваное влево
  function move_prev(obj)
  {
      if(!anim_process)
      {
          if( first_visible + ops.count_visible < count )
          {
              anim_prev(obj);
          } 
          else if(ops.circle)
          {
              circle_prev(obj);
          }
      }
  }
  
  // Анимация влево
  function anim_prev(obj)
  {  
      anim_process = true;
      // покажем еще один элемент справа
      var new_show = jQuery(obj).find('ul:first').children('li').eq(first_visible + ops.count_visible).show();
              
      var first_elem = jQuery(obj).find('ul:first').children('li:visible:first');
      jQuery(first_elem).animate({ 
          marginLeft: '-' + anim_margin + 'px'
      }, ops.animate_time, function () {                
          jQuery(first_elem).hide();
          jQuery(first_elem).css('margin-left','0px');
          first_visible++;         
          state_buttons(obj);
          anim_process = false;
      }); 
      
      // добавляем настройки для нового видимого (правого) элемента
      jQuery(new_show).find('img:first')
          .css('width', ops.elem_setting[ops.count_visible-1].width + 'px')
          .css('height', ops.elem_setting[ops.count_visible-1].height + 'px')
          .css('margin-top', ops.elem_setting[ops.count_visible-1].margin_t + 'px');
      
      // изменяем параметры 
      var li = jQuery(obj).find('ul:first').children('li');
      for(var i=0; i<ops.count_visible; i++)
      {
          jQuery(li).eq(i+first_visible+1).find('img:first').animate({ 
              width: ops.elem_setting[i].width + 'px',
              height: ops.elem_setting[i].height + 'px',
              marginTop:  ops.elem_setting[i].margin_t + 'px'
          });                        
      }  
  }
  
  // перемещение первого элемента в конец
  function circle_prev(obj)
  {
      var temp_li = jQuery(obj).find('ul:first').children('li:first').clone();
      jQuery(obj).find('ul:first').append(temp_li);
      jQuery(obj).find('ul:first').children('li:first').remove();
      first_visible--;
      anim_prev(obj);     
  }
  
// -----------------------------------------------------------------------------  
// --- право (next)
// ----------------------------------------------------------------------------- 
   
  // Прогручиваное вправо
  function move_next(obj)
  {
      if(!anim_process)
      {      
          if( first_visible > 0 )
          {
              anim_next(obj);    
          }
          else if(ops.circle)
          {
              circle_next(obj);
          }
      }
  }
  
  // Анимация вправо
  function anim_next(obj)
  {  
      anim_process = true;
      var new_show = jQuery(obj).find('ul:first').children('li').eq(first_visible - 1)
          .css('margin-left','-' + anim_margin + 'px')
          .show();
              
      var first_elem = jQuery(obj).find('ul:first').children('li:visible:first');
      var last_elem = jQuery(obj).find('ul:first').children('li:visible:last');
      jQuery(first_elem).animate({ 
          marginLeft: "0px"
      }, ops.animate_time, function () {                
          jQuery(last_elem).hide();
          first_visible--;         
          state_buttons(obj);
          anim_process = false;
      }); 
      
      // добавляем настройки для нового видимого (левого) элемента
      jQuery(new_show).find('img:first')          
          .css('width', ops.elem_setting[0].width + 'px')
          .css('height', ops.elem_setting[0].height + 'px')
          .css('margin-top', ops.elem_setting[0].margin_t + 'px');
      
      // изменяем параметры 
      var li = jQuery(obj).find('ul:first').children('li');
      for(var i=0; i<ops.count_visible; i++)
      {
          jQuery(li).eq(i+first_visible-1).find('img:first').animate({
              width: ops.elem_setting[i].width + 'px',
              height: ops.elem_setting[i].height + 'px', 
              marginTop: ops.elem_setting[i].margin_t + 'px'
          });              
      }   
  }
  
  // перемещение последнего элемента в начало
  function circle_next(obj)
  {
      var temp_li = jQuery(obj).find('ul:first').children('li:last').clone();
      jQuery(obj).find('ul:first').prepend(temp_li);
      jQuery(obj).find('ul:first').children('li:last').remove();
      first_visible++;
      anim_next(obj);     
  }
  
// -----------------------------------------------------------------------------  
// --- 
// ----------------------------------------------------------------------------- 
   
  // Определяет скрывать кнопки "НАЗАД" и "ВПЕРЕД" или нет
  function state_buttons(obj)
  {
      if(!ops.circle){
          // назад
          if(first_visible + ops.count_visible >= count)
          {
              jQuery(obj).find('#fs_prev').hide();
          } else {
              jQuery(obj).find('#fs_prev').show();
          }  
          
          // впред
          if(first_visible <= 0)
          {  
              jQuery(obj).find('#fs_next').hide();
          } else {
              jQuery(obj).find('#fs_next').show();
          }   
      }
  }
  

};


