/*!
 * jQuery Pager Cycle Plugin (plugin uses the jquery.cycle plugin)
 * Requires: jQuery v1.2.6 or later, jQuery.cycle 2.88 or later
 */

(function($){

  $.fn.cyclepager = function(pager_options) {

      $.fn.cycle.transitions.scrollInDirection = function($cont, $slides, opts) {
        if (opts.currSlide < opts.nextSlide) { // forward -->
          $cont.css('overflow','hidden');
          opts.before.push($.fn.cycle.commonReset);
          var w = $cont.width();
          opts.cssBefore.width = w;
          opts.cssFirst = { left: 0, width: w+'px' };
          opts.cssBefore= { left: w, top: 0, width: w+'px' };
          opts.animIn	  = { left: 0, width: w+'px' };
          opts.animOut  = { left: 0-w, width: w+'px' };
        } else {
          $cont.css('overflow','hidden');
          opts.before.push($.fn.cycle.commonReset);
          var w = $cont.width();
          opts.cssFirst = { left: 0, width: w+'px' };
          opts.cssBefore= { left: -w, top: 0, width: w+'px' };
          opts.animIn	  = { left: 0, width: w+'px' };
          opts.animOut  = { left: w, width: w+'px' };
        }
      };

    var context = this;
    var id = context.attr('id');
    var carousel = context.find(".galleria-carousel");
    var carousel_inner = context.find(".galleria-carousel-inner");
    var image_blocks = context.find(".galleria-thumbnails .galleria-image-block");
    var total_thumbnails = image_blocks.length;
    image_blocks.each(function(){
      var img_src = $(this).find('a.fullsize').attr('href');
      img_width = $(this).find("img.thumbnail").width();
      if (img_width > 0) {
        $(this).css({'width':img_width+"px"});
      }
      if (img_src != undefined) {
        var img_height = parseInt($(this).find('a.fullsize').attr('data_height'));
        if (img_height == 0) { img_height = 800; }
        carousel_inner.append($(this).remove());
        context.find(".galleria-slides").append("<div class='placeholder' style='height:"+img_height+"px'>"+img_src+"</div>");
      } else { // check for fullsize div and append that to slides
        var fullsize = $(this).find('div.fullsize, div.fullsize-ajax');
        if (fullsize.length) {
          context.find(".galleria-slides").append(fullsize.remove());
          carousel_inner.append($(this).remove());
        }
      }
    });


    function load_slide(currSlideElement, nextSlideElement, options, forwardFlag) {
      // load the fullsize image and insert in place of the 'placeholder'
      if ($(nextSlideElement).hasClass('placeholder')) {
        img = new Image();
        img.src = $(nextSlideElement).text();
        $(nextSlideElement).html(img);
        $(nextSlideElement).removeClass('placeholder');
      } else if ($(nextSlideElement).hasClass('fullsize-ajax')) {
        context.find(".fullsize-ajax").empty();
        $(nextSlideElement).load($(nextSlideElement).attr('data-href'));
      }
    }

    function show_slide_info(idx, slideElement) {
      // attach the current slide info to the 'galleria-' tags based on 'js_display'
      var image_block = carousel.find(".galleria-image-block").eq(idx);
      var g_reg = /galleria-[^ ]+/;
      image_block.find(".js_display").each(function(e){
        var image_block_id = g_reg.exec($(this).attr('class'))[0];
        $('#'+id+' .galleriainfo-block .'+image_block_id).html($(this).html());
      });
    }
    var slides = context.find(".galleria-slides").children();
    //show_slide_info(1, slides.eq(1));
    show_slide_info(0, slides.eq(0)); // show the first slide
    load_slide(slides.eq(0), slides.eq(0), {}, true);

    context.find(".galleria-carousel a.fullsize").click(function(e){
      e.preventDefault();
    });

    var image_blocks_width = 0;
    image_blocks.each(function(e){
      margin_w = parseInt($(this).css("margin-left"));
      margin_w += parseInt($(this).css("margin-right"));
      w = this.scrollWidth;
      if (w == 0) { // in case scrollWidth doesn't have any width.
        w = parseInt($(this).css("width")) +
          parseInt($(this).css("margin-right")) +
          parseInt($(this).css("margin-left")) +
          parseInt($(this).css("padding-right")) +
          parseInt($(this).css("padding-left"));
      }
      image_blocks_width += w + margin_w;
    });
    carousel_inner.css({width:image_blocks_width+'px'});

    function move_carousel(x_pos) {
      carousel_width = carousel.width();
      var max_left = carousel_width - image_blocks_width;
      if (Math.abs(x_pos) >= carousel_width) {
        var dif = Math.max(x_pos, max_left);
        carousel_inner.animate({left:dif}, {
            duration: 1000,
            queue: false
        });
      } else {
        carousel_inner.animate({left:x_pos}, {
            duration: 1000,
            queue: false
        });
      }
    }
    var build_pager = function(idx, slide) {
      //return '#galleria-carousel div.galleria-image-block:eq('+idx+')';
      return '#'+id+' .galleria-carousel div.galleria-image-block:eq('+idx+')';
    };

    function updateActivePagerLink(pager, currSlide) {
      // attach a counter, move the carousel, and add the active pager link
      var slide_number = currSlide+1;

      var image_block = $(pager).find(".galleria-image-block").eq(currSlide);
      //var carousel_inner = $(pager).find("#galleria-carousel-inner");

      context.find(".galleria-counter .curr_slide").html(slide_number);
      context.find(".galleria-counter .total_slides").html(total_thumbnails);

      $(pager).find(".galleria-image-block").each(function() {
        $(this).removeClass('activeSlide');
      });
      $(pager).find(".galleria-image-block").eq(currSlide).addClass('activeSlide');

      var image_block_x = image_block.width() * currSlide;
      var image_block_x = image_block.offset().left - image_block.parent().offset().left;
      var carousel_width = $(pager).width();
      var min_carousel_width = carousel_width * 0.5;
      var max_left = carousel_width - image_blocks_width;
      if (carousel_width < image_blocks_width) {
        if (image_block_x > min_carousel_width) {
          var dif = Math.max((min_carousel_width - image_block_x), max_left);
          carousel_inner.animate({left:dif}, {
              duration: 1000,
              queue: false
          });
        } else {
          carousel_inner.animate({left:0}, {
              duration: 1000,
              queue: false
          });
        }
      }
    }


    dimensions = {width:500,
                  height:500,
                  thumbnail_width:100,
                  thumbnail_height:100};

    var settings = {
      timeout: 0,
      fx: 'scrollInDirection',
      dimensions: dimensions,
      before: load_slide,
      pager: '#'+id+' .galleria-carousel',
      pagerAnchorBuilder: build_pager,
      onPagerEvent: show_slide_info,
      onPrevNextEvent: function(isNext, idx, slideElement) {
        show_slide_info(idx, slideElement);
      },
      next: '#'+id+' .galleria-slides-flipper-right',
      prev: '#'+id+' .galleria-slides-flipper-left',
      requeueOnImageNotLoaded: true,
      containerResize: false,
      updateActivePagerLink: updateActivePagerLink
    };
    if (pager_options) {
      $.extend(settings, pager_options);
    }

    // only show flippers when hovering
    $('#'+id+' .galleria').hover(function(){
      $(settings.next+', '+settings.prev).show();
    }, function() {
      $(settings.next+', '+settings.prev).hide();
    });

    // set dimensions here
    var d = settings.dimensions;
    $('#'+id+' .galleria').css({'width':d.width+'px'});
    $('#'+id+' .galleria-slides-block, #'+id+' .galleria-slides').css({'width':d.width+'px', 'height':d.height+'px'});
    // flipper_widths = $("#galleria-slides-flipper-left").width() + $("#galleria-slides-flipper-right").width();
    slides.eq(0).css({width:d.width+'px'}); // set initial slide width
    flipper_widths = 0;
    $('#'+id+' .galleria-carousel-block').css({'width':(d.width+flipper_widths)+'px', 'height':d.thumbnail_height+'px'});
    $('#'+id+' .galleria-carousel .galleria-image-block').css({'height':d.thumbnail_height+'px'});
    $('#'+id+' .galleria-carousel').css({'height':d.thumbnail_height+'px'});

    if (carousel.width() > image_blocks_width) {
      $('#'+id+' .galleria-carousel-flipper-right, #'+id+' .galleria-carousel-flipper-left').remove();
    } else {
      $('#'+id+' .galleria-carousel-flipper-right').click(function(e){
        x_pos = parseInt(carousel_inner.css('left')) - carousel.width();
        move_carousel(x_pos);
      });
      $('#'+id+' .galleria-carousel-flipper-left').click(function(e){
        x_pos = parseInt(carousel_inner.css('left')) + carousel.width();
        move_carousel(Math.min(x_pos, 0));
      });
    }
    // plugin inside plugin
    $('#'+id+' .galleria-slides').cycle(settings);
  };

})(jQuery); 


