$(document).ready(function() {

	var galleryLoadCounters = [];
	var gallerySlideInfos = [];
	var galleryThumbnailsFormatted = [];
	var galleryWidths = [];

	var shimHeight = 50;

	var lang;
	var dir;

	// resourceStart is the Rages start event for resources that need initialisation 
	$('.resource-container').on('resourceStart', '.gallery', function() {
		
		var $this = $(this);
		var re = /\d+/;
		var id = $this.parent('div.resource').attr('id').match(re)[0];

		// change these to $this.data
		galleryLoadCounters[id] = 0;
		gallerySlideInfos[id] = {};
		galleryThumbnailsFormatted[id] = false;
		galleryWidths[id] = $this.width();

		// if we are in a ui tab and hidden, we'll need to find out how wide the tabs are as the gallery width
		$('#r' + id).parents('.ui-tabs-panel').each(function(i, e) {
			var $that = $(this);
			if($that.hasClass('ui-tabs-hide')) { // tab is hidden...
				galleryWidths[id] = $that.siblings('[class!=ui-tabs-hide]').first().width() // so find active tab width
					- parseInt($that.css('padding-left'), 10)  // ...less padding!
					- parseInt($that.css('padding-right'), 10);  // NB 2nd radix arg gets rid of units (em, px, etc)
			}
		});
		// we may also want to look at the width of our parent container
		// when the gallery becomes visible

		lang = $this.attr('lang');
		dir = $this.attr('dir');

		// these get unbound once they are used, as the cycle plugin then binds these buttons for its own use
		$this.find('.gallerybuttons').on('click.startCycle', '.nextBtn', function() {
			id = $(this).attr('id').substr(9);  // nextBtn_r(\d+)
			appendAllToGalleryIfUnloaded(id, true);
			$('#galleryimages_r' + id).cycle('next');
		});
	
	
		// this only runs initially, as above
		$this.find('.gallerybuttons').on('click.startCycle', '.prevBtn', function() {
			id = $(this).attr('id').substr(9);  // prevBtn_r(\d+)
			appendAllToGalleryIfUnloaded(id, true);
			$('#galleryimages_r' + id).cycle('prev');
		});

		
		$this.find('.gallerybuttons').on('click', '.pauseBtn', function() {
			id = $(this).attr('id').substr(10);  // pauseBtn_r(\d+)
			pauseGallery(id);
		});
	
	
		$this.find('.gallerybuttons').on('click', '.startBtn', function() {
			id = $(this).attr('id').substr(10);  // startBtn_r(\d+)
			appendAllToGalleryIfUnloaded(id, false);
			showSlidesIfHidden(id);
			resumeGallery(id);
		});
	
	
		$this.find('.gallerybuttons').on('click', '.thumbBtn', function() {
	
			id = $(this).attr('id').substr(10);  // thumbBtn_r(\d+)
			appendAllToGalleryIfUnloaded(id, true);  // this starts the cycle plugin as well
	
			if(galleryThumbnailsFormatted[id] == false) {
				formatThumbnails(id);
				galleryThumbnailsFormatted[id] = true;
			}
	
			showThumbnails(id);
		});
	
	
		$this.find('.gallerybuttons').on('click', '.slideBtn', function() {
			id = $(this).attr('id').substr(10);  // slideBtn_r(\d+)
			showSlides(id);
		});
	
	
		$this.find('.thumbnails').on('click', '.thumbnail', function() {
			// this is thumb_ddddd_ddddd
			var thumbid = $(this).attr('id');
			var imgre = /(\d+)_(\d+)$/;
			var matches = thumbid.match(imgre);
			var id = matches[1];
			var index = matches[2];
			startCycle(id, index, true);  // start on the selected slide, but paused
			showSlides(id);
		});
		
		getImageData(id);
	});
	
	
	


	$(".gallery").each(function() {
		$(this).trigger('resourceStart');
	});  // get the ball rolling

		

	function getImageData(id) {
		$.getJSON("/ajax/gallery_ajax.php?q=getImages&resourceid=" + id, function(response) {

			if(response.length == 0) {
				$('#galleryimages_r' + id).html($('#galleryemptymsg_r' + id).html()) // empty message (translated)
				$('#r' + id).css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500); //fade empty gallery in
				return;
			}

			gallerySlideInfos[id] = response;

			getNextImage(id, 0); // starting gallery image

			$('#counter_r' + id + ' #imageIndex_r' + id).html(galleryLoadCounters[id]);
			$('#counter_r' + id + ' #countDivider_r' + id).html(' / ');
			$('#counter_r' + id + ' #imageCount_r' + id).html(gallerySlideInfos[id].length);

		});
	}



	function getNextImage(id, index) {
		var image = gallerySlideInfos[id][index];
		if(image.url == null || image.url == '') {
			image.url = '/images/' + image.imageid + '/4';
		}
		// scale image if it's a fixed size gallery, and get div sizes
		if(image.size != null) { // it's a regular fixed (100, 200, 400, 600) px image
			if(image.height >= image.width) {
				image.width  = Math.ceil(image.size *(image.width / image.height));
				image.height = image.size;
			} else {
				image.height = Math.ceil(image.size *(image.height / image.width));
				image.width = image.size;
			}
		}

		var escCaption = image.caption.replace(/"/g, '&quot');

		$("#thumbnails_r" + id).append(
			'<a class="thumbnail" id="thumb_r' + image.resourceid + '_' + index +'"><img src="/images/' + image.imageid + '/0" alt="' + escCaption + '" class="thumbimg" /></a>'
		);

		var margin = (galleryWidths[id] - image.width) / 2;

		$("#galleryimages_r" + id).append(
			'<div class="image" id="image_r' + image.imageid + '" style="margin-left: ' + margin + 'px; margin-right: ' + margin + 'px; width: ' + image.width + 'px; height: ' + image.height + 'px;">' +
			'<a href="' + image.url + '" id="a_r' + image.imageid + '" target="_blank">' +
			// leave this next commented line here
//			'<img id="' + image.imageid + '" alt="' + image.caption +	'" width="' + image.width +	'px" height="' + image.height + 'px">' +
			'<img src="/images/' + image.imageid + '/' + image.displaysize + '" id="' + image.imageid + '" alt="' +  escCaption  +	'" width="' + image.width +	'px" height="' + image.height + 'px">' +
			'</a><div class="caption" lang="' + lang +'" dir="' + dir + '">' + image.caption + '</div></div>'
		);

		if(index == 0) {
			fadeInAndFormatCarousel(image, id);
		}

		galleryLoadCounters[id] = index + 1;
	}


	// this is setup for the first image only, the rest are handled by cycle
	function fadeInAndFormatCarousel(image, id) {
		$('#gallerycontainer_r' + id).height($('#galleryimages_r' + id + ' .caption').height() + image.height + shimHeight);
		$('#galleryimages_r' + id).show();
		$('#r' + id).css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);  // fade new gallery in
	}


	// this is used by the thumbnail button and the start button, but the start button wants to start the gallery as well TODO do this
	function appendAllToGalleryIfUnloaded(id, pause) {
		if(galleryLoadCounters[id] == gallerySlideInfos[id].length) {
			return true;
		}
		for(var i = galleryLoadCounters[id]; i < gallerySlideInfos[id].length; i ++) {
			getNextImage(id, i);
		}
		startCycle(id, i, pause);
	}







	function formatThumbnails(id) {
		var divWidth = $('#thumbnails_r' + id).width();
		//console.log('divWidth: ' + divWidth);
		var thumbWidth = $('#thumbnails_r' + id + ' a:first').width();
		//console.log('thumbWidth: ' + thumbWidth);
		var numHoriz = Math.floor(divWidth / thumbWidth);
		//console.log('numHoriz: ' + numHoriz);
		var remainder = divWidth - (numHoriz * thumbWidth);
		//console.log('remained: ' + remainder);
		var margin = (remainder / 2) - ((thumbWidth - 100) / 2);  // 100 = thumbimg width
		//console.log('margin: ' + margin);

		$('#thumbnails_r' + id).css({'height': $('#gallerycontainer_r' + id).height() + 'px', 'margin-left': margin, 'margin-right': margin, 'overflow-y': 'auto'});
	}





	function startCycle(id, index, pause) {
		// actually start the cycle plugin

		// unbind the next and prev button handlers if they still have their default bindings
		//$('#gallerybuttons_r' + id + ' .nextBtn').unbind('click');
		//$('#gallerybuttons_r' + id + ' .prevBtn').unbind('click');

		$('#gallerybuttons_r' + id).off('click.startCycle', '.nextBtn');
		$('#gallerybuttons_r' + id).off('click.startCycle', '.prevBtn');

		$('#galleryimages_r' + id).cycle({
		    fx:				'fade',
		    startingSlide:	index,
		    timeout:		3000,
		    containerResize: 0,
		    next:			'#abstract_r' + id + ' .nextBtn',
		    prev:			'#abstract_r' + id + ' .prevBtn',
		    before:			function(currSlideElement, nextSlideElement, options, forwardFlag) {
				showSlidesIfHidden(id);
				// fade out the old slide counter index, and fade in the new one (this matches the slide fade in / out)
				$('#counter_r' + id + ' #imageIndex_r' + id).fadeOut('fast', function() { $(this).html(options.currSlide + 1).fadeIn('fast') });
			},
		    after: function(currSlideElement, nextSlideElement, options, forwardFlag) {

				var oldHeight = $('#gallerycontainer_r' + id).height();
				var newHeight = $(nextSlideElement).height() + $(nextSlideElement).find('.caption').height() + shimHeight;

				// don't resize if the new image has just a bit less height
				if(newHeight > oldHeight || newHeight < (oldHeight - shimHeight)) {
					$('#gallerycontainer_r' + id).animate({height: newHeight + 'px'}, 250);
				}
			}
		});

		if(pause == true) {
			$('#galleryimages_r' + id).cycle('pause');
		}
	}



	function resumeGallery(id) {
		$('#galleryimages_r' + id).cycle('resume');
		$("#startBtn_r" + id).hide();
		$("#pauseBtn_r" + id).show();
	}

	function pauseGallery(id) {
		$('#galleryimages_r' + id).cycle('pause');
		$("#pauseBtn_r" + id).hide();
		$("#startBtn_r" + id).show();
	}

	function showSlidesIfHidden(id) {
		if($("#galleryimages_r" + id).is(':hidden')) {
			showSlides(id);
		}
	}

	function showSlides(id) {
		$("#thumbnails_r" + id).fadeOut('fast', function(){
			$("#galleryimages_r" + id).fadeIn('fast');
		});

		$("#slideBtn_r" + id).hide();
		$("#thumbBtn_r" + id).show();
	}

	function showThumbnails(id) {
		$('#galleryimages_r' + id).cycle('pause');

		$("#galleryimages_r" + id).fadeOut('fast', function(){
			//$('#gallerycontainer_r' + id).css('overflow-y', 'scroll');
			$("#thumbnails_r" + id).fadeIn('fast');
		});

		// TODO could we put the buttons into visibility toggle groups?
		$('#thumbBtn_r' + id).hide();
		$('#slideBtn_r' + id).show();
		$('#pauseBtn_r' + id).hide();
		$('#startBtn_r' + id).show();
	}


});

