var isOnFirst = true;

(function($, undefined) {
  $.fn.imagesLoaded = function( callback ) {
    var $this = this,
        $images = $this.find('img').add( $this.filter('img') ),
        len = $images.length,
        blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

    function triggerCallback() {
      callback.call( $this, $images );
    }

    function imgLoaded( event ) {
	  if( !event ) { return; }
      if ( --len <= 0 && event.target.src !== blank ){
        setTimeout( triggerCallback );
        $images.unbind( 'load error', imgLoaded );
      }
    }

    if ( !len ) {
      triggerCallback();
    }

    $images.bind( 'load error',  imgLoaded ).each( function() {
      if (this.complete || this.complete === undefined){
        var src = this.src;
        this.src = blank;
        this.src = src;
      }
    });

    return $this;
  };
})(jQuery);

$(document).ready(function() {
	$('.rotatingGallery').each(function() {
		eGalleryPrepGallery($(this));
	}).click(function() {
		var url = $(this).find('.current A').attr('href');
		if( url ) { document.location = url; }
		return false;
	}).hover(	
		function() { $(this).addClass('pointer'); },
		function() { $(this).removeClass('pointer'); }
	);

	$(window).bind('resize',function() {
		$('.rotatingGallery').each(function() {
			resizeImages($(this));
		});
	});
});


function eGalleryPrepGallery($gallery) {
	var $startImg = $gallery.find('.first div img');
	$startImg.imagesLoaded(function() {
		resizeImage($(this));
		kickThingsOff($gallery);
	});
}

/*
$(document).ready(function() {
	$(window).bind('resize',function() {
		$('.rotatingGallery').each(function() {
			resizeImages($(this));
		});
	});
	$('.rotatingGallery').each(function() {
		var $gallery = $(this);
		var $img = $gallery.find('.first DIV IMG');
		if( $img.get(0).complete ) {
			// is already cached, won't fire load event
			kickThingsOff($gallery);
		} else { 
			$img.bind('load',function() { kickThingsOff($(this).closest('.rotatingGallery')); } );
		}
	}).click(function() {
		var url = $(this).find('.current A').attr('href');
		if( url ) { document.location = url; }
		return false;
	}).hover(	
		function() { $(this).addClass('pointer'); },
		function() { $(this).removeClass('pointer'); }
	);
});


$('.eWidget[data-class="GalleryWidget"][data-init="0"]').each(function() {
	var $widget = $(this);
	if( $widget.data('init') ) { return; }
	$gallery = $widget.find('.rotatingGallery');
	eLog($gallery);
	kickThingsOff($gallery.find('.rotatingGallery'));
	$gallery.find('.first div img').bind('load', function() { resizeImages($gallery); });
});
*/
$(window).load(function() {
	resizeImages($(this));
	isOnFirst = false;
});

	function kickThingsOff($gallery) {
		$gallery.data('firstwidth', $gallery.width());
		window.setTimeout(function() { rapidResizeGallery($gallery); }, 100);

		//showSlide($gallery.find('.rotatingBox'));
		// Start the slideshow now that the first one's loaded
		nextSlide($gallery);
	}

	// The loading images in other columns could screw this up for the 
	// first image. Keep rapid firing.
	function rapidResizeGallery($gallery) {
		if( !isOnFirst ) return; 
		var w = $gallery.width();
		if( w != $gallery.data('firstwidth')) {
			$gallery.data('firstwidth', w);
			resizeImages($gallery);
		}
		window.setTimeout(function() { rapidResizeGallery($gallery); }, 100);
	}

	function nextSlide($gallery) {
		if( $gallery.data('timeout') ) { clearTimeout($gallery.data('timeout')); }

		var $curr = $gallery.find('.current');
		var $next = $curr.eq(0).next();
		if( !$next.size() ) {
			$next = $curr.siblings().eq(0); // wrap
		}
		var success = true;
		if( $next.size() ) { success = showSlide($next); }

		// Prep the next queued slide...
		if( success && $gallery.data('overflow') ) {
			var photo = $gallery.data('overflow').pop(); // I heart jQuery.
			if( photo ) { 
				var $newSlide = $('<div style="z-Index: -1;" class="rotatingBox fauxHidden"><div class="cycleMine"><img src="' + photo['url'] + '"><span class="highlight2"><a href="/mod/gallery/view-photo.php?photo_id=' + photo['photo_id'] + '"></a>' + photo['name'] + '</span></div></div>');
				$newSlide.css({opacity: 0}).appendTo($gallery);
			}
		}

		$gallery.data('timeout', window.setTimeout(function() {
			nextSlide($gallery);
		}, $gallery.data('secs')*1000));
	}

	function showSlide($slide) {
		// make sure it's there
		if( !resizeImage($slide.find('img')) ) { return false; } // Not ready

		$slide.siblings().css('z-Index',1).not('.current').css({opacity: 0});
		$slide.siblings().filter('.current').removeClass('current').animate({opacity: 0}, 1500);
		$slide.css('z-Index',2).addClass('current').animate({opacity: 1}, 1500);
		$slide.removeClass('fauxHidden');
		return true;
	}

	function dbg(msg) {
		eLog(msg);
	}

	function resizeImages($gallery) {
		$gallery.find('img').each(function() {
			resizeImage($(this));
		});
	}
	function resizeImage($img) {
		var $gallery = $img.closest('.rotatingGallery');
		var divW = $gallery.width(); // 20100130 - Too wide for first hit
		var divH = $gallery.height();

		// If narrow, shrink the height
		var maxH = Math.round(divW / $gallery.data('ratio'));
		if( maxH > 340 ) { maxH = 340; }
		//dbg(maxH + ' / ' + divH);
		if( divH != maxH ) {
			//dbg("Rdz from " + divH + ' to ' + maxH);
			$gallery.height(maxH);
			divH = maxH;
		}

		var w = $img.width();
		var h = $img.height();
		if( w == 0 || h == 0 ) {
			return; }

		// Start by making it as wide as the box
		var newW = divW;
		var newH = h*(newW/w);

		// If it's too tall, scale back
		if( newH > maxH ) {
			newW = newW * maxH/newH;
			newH = maxH;
		}
		$img.width(newW);
		$img.height(newH);
		$img.parent().find('p').width(newW);
		var marginLeft = (divW-newW)/2;

	//dbg("RSZ: " + divW + 'x' + divH + ', ' + $img.attr('src') + ", " + $gallery.attr('id'));

		$img.closest('.rotatingBox')
			.css('margin-left', '' + marginLeft + 'px')
			.css('border', '1px solid black')
			.removeClass('fauxHidden')
			.find('span').css({opacity: .7});
		return true;
	}


