window.onload = function() {  
    $(function() {
        /*
        Инициализация fancybox для каждого элемента cloud-zoom
         */
        $("#content .cloud-zoom").fancybox({
          'transitionIn'  :  'elastic',
          'transitionOut'  :  'none',
          'speedIn'    :  600,
          'speedOut'    :  200,
          'overlayShow'  :  true,
          'overlayColor'  :  '#000',
          'cyclic'    :  true,
          'easingIn'    :  'easeInOutExpo'
        });

        /*
        Так как плагин cloud zoom выводит элемент div 
        поверх каждого изображения для перехвата перемещений курсора мыши, 
        функция плагина fancybox для события click должна быть изменена.
        Здесь мы переключаем событие click, коорое ожидается плагином 
        fancybox, когда нажимается кнопка мыши на элементе div mousetrap.
        Нам известно, что div mousetrap вставляется после тега <a>,
        которые должен получить событие click:
         */
        $("#content .mousetrap").live('click',function(){
          $(this).prev().trigger('click');
        });

        /*
        Элемент content;
        каждый пункт списка / группа с несколькими изображениями
         */
        var $content  = $('#content'),
        $thumb_list = $content.find('.thumb > ul');
        /*
        Нужно установить ширину каждого ul (сумма ширины элементов потомков);
        также нужно определить обработчик события click для парвой и левой стрелок
        для каждого пункта.
         */
        $thumb_list.each(function(){
          var $this_list  = $(this),
          total_w    = 0,
          loaded    = 0,
          //Предварительная загрузка изображений
          $images    = $this_list.find('img'),
          total_images= $images.length;
          $images.each(function(){
            var $img  = $(this);
            $('<img/>').load(function(){
              ++loaded;
              if (loaded == total_images){
                $this_list.data('current',0).children().each(function(){
                  total_w  += $(this).width();
                });
                $this_list.css('width', total_w + 'px');

                //События next / prev 

                $this_list.parent()
                .siblings('.next')
                .bind('click',function(e){
                  var current = $this_list.data('current');
                  if(current == $this_list.children().length -1) return false;
                  var  next  = ++current,
                  ml    = -next * $this_list.children(':first').width();

                  $this_list.data('current',next)
                  .stop()
                  .animate({
                    'marginLeft'  : ml + 'px'
                  },400);
                  e.preventDefault();
                })
                .end()
                .siblings('.prev')
                .bind('click',function(e){
                  var current = $this_list.data('current');
                  if(current == 0) return false;
                  var  prev  = --current,
                  ml    = -prev * $this_list.children(':first').width();

                  $this_list.data('current',prev)
                  .stop()
                  .animate({
                    'marginLeft'  : ml + 'px'
                  },400);
                  e.preventDefault();
                });
              }
            }).attr('src',$img.attr('src'));
          });
        });
      });
}
