/*

	Winona gallery tool.
	
	@author: Stephen Tomlinson
	@created: 8 September 2009


*/

(function($){
$.fn.exhibition = function(url,options) {
	
	// Default options

	var defaults = {
		next: '.gallery-next',
		prev: '.gallery-prev',
		btBack: '.gallery-back',
		play: '.gallery-play',
		pause: '.gallery-pause',
		pager: '.gallery-scroller',
		paging: '.gallery-paging',
		nextPage: '.gallery-next-page', 
		prevPage: '.gallery-prev-page',
		status: '.gallery-status',
		step: 5,
		description: '.gallery-description',
		credit: '.gallery-credit',
		autoplay: false
	};
	
	// Extend our default options with those provided
	var opts = $.extend(defaults, options);
	
	// Some globals
	var imagecontainer = this;
	var photos;
	var images;

	/* This is the init for the plugin */
	
	return this.each(function() {

		    // Get the photos
			fetchJSON(url);
		
	});
	
	/* Functions */
	
	// Fetch the gallery data
	function fetchJSON(url) {
		$.ajax({
			url: url,
			dataType: 'json',
			success: function(data) {
				buildgallery(data);
			},
			error: function(request,error) {
				if(request) {
					console.log(request);
				}
				if(error) {
					console.log(error);
				}     
			}
		});	
	}
	
	function buildgallery(data) {
		photos = data.album.photos;
		
		// Create the list of images
		createImageLists();
		
		// Initialise jQuery Cycle plugin to handle the core of the gallery
		images.cycle({
			next: opts.next,
			prev: opts.prev,
			before: updateStatus,
			speed: 800,
			nowrap: true
		});
		images.cycle(0);
		
		// If a hash is passed in the URL, change to that photo
		var hash = document.location.toString().split('#')[1];
		if(hash) {
			var cycleto = hash.split("pic")[1];
			images.cycle(parseInt(cycleto));
		}
		
		// Set intial playback state
		if(opts.autoplay == true) {
			playGal();
		} else {
			pauseGal();
		}
	
		// Bind the controls
		$(opts.pause).click(pauseGal);
		$(opts.play).click(playGal);
		
		// Bind the pause and play buttons
		$(opts.nextPage).click(function(){
			changePage('next');
			return false;
		});
		
		$(opts.prevPage).click(function(){
			changePage('prev');
			return false;
		});
		
		// Bind the arrow keys to previous and next actions
		$().keydown(function(e){
			// Left arrow
			if(e.keyCode == 37) {
				images.cycle('prev');
			}
			/// Right arrow
			if(e.keyCode == 39) {
				images.cycle('next');
			}
		});
	
	}
	
	// Create the lists of images
	function createImageLists() {
		$(imagecontainer).append("<ul></ul>");
		images = $(".gallery-image ul");
		$(opts.pager).html("<ul></ul>");
		thumbs = $(opts.pager + " ul");
		for(var i = 0; i < photos.length; i++) {
			var listitem = $('<li><img src="' + photos[i].thumb + '" alt="" /></li>').data('image',i);
			listitem.click(function(event,delta){
				images.cycle($(this).data('image'));
			});
			var item = $('<li><img src="' + photos[i].photo + '" alt="" /></li>')
				.data('credit',photos[i].credit)
				.data('description',photos[i].description);
			images.append(item);
			thumbs.append(listitem);
		}
		$(opts.pager).each(initialiseScroller);	
	}
	
	// Play the gallery
	function playGal() {
		images.cycle('resume');
		$(opts.play).hide();
		$(opts.pause).show();
		return false;
	}
	
	// Pause the gallery
	function pauseGal() {
		images.cycle('pause');
		$(opts.pause).hide();
		$(opts.play).show();
		return false;
	}
	
	// When the image changes, this runs all the neccessary updates
	function updateStatus(currSlideElement, nextSlideElement, options, forwardFlag) {
		// As this is run before the transition the new current slide is still the 'next' slide
		var	current = options.nextSlide;
		$('li',opts.pager).removeClass('current').eq(current).addClass('current');
		$(opts.status).text((current+1) + ' of ' + options.slideCount);
		$(opts.description).html($(nextSlideElement).data('description'));

		if 	($(nextSlideElement).data('credit') == ""){
		$(opts.credit).html($(nextSlideElement).data('credit'));	
		}  else {
		$(opts.credit).html("Credit: " + $(nextSlideElement).data('credit'));	
		}
		changePagebyIndex(opts.pager,current);
	}
	
	/* Scroller functions */
	
	function initialiseScroller() {
	
		var fullwidth = $("li",this).outerWidth('margin');
		var liwidth = $("li",this).outerWidth();
		var difference = fullwidth - liwidth;
		var children = $("ul li",this).length;
		
		if(opts.step != 'auto') {
			var pageitems = opts.step;
		} else {
			var pageitems = parseInt(($(this).width() + difference) / fullwidth);
		}

		var pages = Math.ceil(children / pageitems);
		
		// Set the width of the UL
		//$("ul",this).width(pages * pageitems * fullwidth);
		
		$(this)
			.data('pages',pages)
			.data('step',pageitems);
		
		for(var i = 1; i <= pages; i++) {
			$("ul",opts.paging).append('<li>' + i + '</li>');
		}
		
		
	}
	
	function reportPage(e, elem, container, items, pos) {
		var page = pos / this.step;
		container.data('currentPage',page);
		$('li',opts.paging).removeClass('current').eq(page-1).addClass('current');
	}

	
	function changePagebyIndex(container,index) {
		var step = $(container).data('step');
		var newpage = Math.floor(index/step);
		var location = (step*newpage)+1;
		var li = $('li:nth-child('+location+')',container);
		$(container).scrollTo(li,500,{ axis: 'x' }).dequeue();
		$(container).data('currentPage',newpage);
		$('li',opts.paging).removeClass('current').eq(newpage).addClass('current');
	}
	
	function changePage(page) {
		var step = $(opts.pager).data('step');
		var currentPage = $(opts.pager).data('currentPage');
		var total = $(opts.pager).data('pages');
		if(page == 'next')
			page = currentPage + 1;
		if(page == 'prev') 
			page = currentPage - 1;
		if(page >= 0 && page < total) {
			changePagebyIndex(opts.pager,page*step);
		}	
	}
	
};
})(jQuery);
