/*----------------------------------------------------------------------------

[WebVision Scrolling Gallery]

Project:	    	Core Templates
Version:	    	1.1.3
Primary use:		For use on article pages of WebVision 3.0
Original Author: 	Darren Waddell
Last change:		26/07/10 [See change history]
Last Assigned to:	Qasim Alyas

Change history:
+ 1.1.0
	- Amended element creation
	- Removed animated height
	- Added credit and setCredit method
	- Added target_blank attribute
+ 1.1.1
	- Added support for alternate text for images
+ 1.1.2
	- Fixed an issue where the last thumbnail was dropping down the row - thus
	its hidden and unclickable. This was due to JQuery not being able to 
	calculate the width's properly when borders are present.
+ 1.1.3
	- Fixed a bug where if the source was missing a link on the first caption it would hide the entire source block

-----------------------------------------------------------------------------*/


(function ($) {

	$.fn.extend({
		createGallery: function (options) {
			return this.each(function () {
				var $this = $(this);
				$(window).load(function () {
					$.wvGallery.init($this, $.extend({}, $.fn.createGallery.defaults, options));
				});
			});
		}
	});

	$.fn.createGallery.defaults = {
		url: '/AJAX/Events/gallery_contents.aspx',
		onLoad: null,
		imageList: {},
		images: 'div.showing li',
		thumbsContainer: 'div.thumbs',
		thumbs: 'div.thumbs li',
		thumbFade: 0.7,
		thumbFadeDuration: 200,
		numThumbsShown: 8,
		currentPosition: 0,
		scrollDuration: 500,
		fixHeight: true,
		maxHeight: 0,
		loadingClass: 'ajax_loading',
		loadingOpacity: 0.7
	};

	$.extend({

		wvGallery: {

			_uID: 0,
			settings: [],

			init: function (jQobj, settings) {
				var pointer = this;
				var inst = this._uID;
				// Save settings
				this.settings[inst] = settings;
				// First, get and save the max height, and set up the required padding on the first item
				this.setupFirstPicture(jQobj, this.settings[inst]);
				// Add in the left and right arrows
				this.createScrollButtons(jQobj, inst);
				// Fetch results
				$.getJSON(this.settings[inst].url, function (reply) {
					$.each(reply.images, function (i, image) {
						// create list container
						var list = $('<li></li>');

						// create preview link
						var previewLink = $('<a href=""></a>').appendTo(list);
						// create preview image
						var previewLinkImage = $('<img />').attr({ 'src': image.filename || '', 'alt': image.alttext || '' }).appendTo(previewLink);

						// create preview data container
						var imageDataContainer = $('<div></div>')
								.addClass('previewData').appendTo(list);

						// create image caption
						var imageDataCaption = $('<p></p>')
									.text(image.caption || '').appendTo(imageDataContainer);

						// create source container
						var imageDataSource = $('<span></span>')
									.addClass('credit')
									.text('Source: ').appendTo(imageDataContainer);
						// create source link
						var imageDataLink = $('<a href="#"></a>')
										.attr('target', '_blank')
										.attr('href', image.creditlink || '')
										.text(image.credittext || '').appendTo(imageDataSource);

						// apend list to
						list.appendTo($(pointer.settings[inst].images).parent());
					});
					pointer.calculateScrollDistance(jQobj, pointer, inst);
					// Set the width of the thumb container
					pointer.setThumbContainerWidth(jQobj, pointer.settings[inst]);
					// Position captions
					pointer.positionCaptions(jQobj, pointer.settings[inst]);
					// Set up the thumbnail fading
					pointer.setThumbFade(jQobj, pointer.settings[inst]);
					// Set up show/hide for captions
					pointer.setCaptionFade(jQobj, pointer.settings[inst]);
					// Set up show/hide for credit
					pointer.setCredit(jQobj, pointer.settings[inst]);
					// Set up selection of new image
					pointer.showNewPicture(jQobj, pointer.settings[inst]);
					// Click for next image
					pointer.clickForNextImage(jQobj, pointer.settings[inst]);
					// Hide the loader!
					$(pointer.settings[inst].images).addClass('loaded');
					pointer.settings[inst].loadScreen.fadeOut(1000, function () { $(this).remove(); });
					pointer._uID++;
				});
			},

			setupFirstPicture: function (jQobj, settings) {
				// Set the CSS to include 'zoom: 1' for ie
				$(jQobj).find(settings.images).css('zoom', 1);
				this.createLoader(jQobj, settings);
				settings.loadScreen.animate({
					'height': settings.maxHeight
				}, 1000);
			},

			createLoader: function (jQobj, settings) {
				var pointer = this;
				settings.loadScreen = $('<div></div>').addClass(settings.loadingClass).appendTo(document.body);
				settings.loadScreen.css({
					'top': $(jQobj).find(settings.images).eq(0).offset().top,
					'left': $(jQobj).find(settings.images).eq(0).offset().left,
					'width': $(jQobj).find(settings.images).eq(0).width(),
					'height': $(jQobj).find(settings.images).eq(0).height(),
					'opacity': settings.loadingOpacity
				});
			},

			createScrollButtons: function (jQobj, inst) {
				// Save a reference to this plugin
				var pointer = this;
				var settings = this.settings[inst];
				// Check to see if the number of thumbs is greater than the required thumbs shown
				if ($(jQobj).find(settings.thumbs).length > settings.numThumbsShown) {
					// Create buttons
					settings.previousButton = $('<span class="previousButton">Previous thumbnails</span>');
					settings.nextButton = $('<span class="nextButton">Next thumbnails</span>');
					// Stick them in at the beginning and end of the thumb container
					$(jQobj).find(settings.thumbsContainer).prepend(settings.previousButton).append(settings.nextButton);
					// Add functionality
					settings.previousButton.click(function () {
						pointer.scrollLeft(jQobj, pointer, inst)
					});
					settings.nextButton.click(function () {
						pointer.scrollRight(jQobj, pointer, inst)
					});
				}
			},

			scrollLeft: function (jQobj, pointer, inst) {
				if (pointer.settings[inst].currentPosition < 0) {
					pointer.settings[inst].currentPosition = parseInt($(pointer.settings[inst].thumbs).parent().css('left')) + pointer.settings[inst].scrollDistance;
					// Temporarily remove the click event from the button
					pointer.settings[inst].previousButton.unbind('click');
					// Animate the scrolling...
					$(jQobj).find(pointer.settings[inst].thumbs).parent().animate({
						left: '+=' + pointer.settings[inst].scrollDistance + 'px'
					},
					{
						duration: pointer.settings[inst].scrollDuration,
						complete: function () {
							pointer.settings[inst].previousButton.click(function () { pointer.scrollLeft(jQobj, pointer, inst) });
						}
					});
				}
			},

			scrollRight: function (jQobj, pointer, inst) {
				if (-(pointer.settings[inst].currentPosition - pointer.settings[inst].scrollDistance) < pointer.settings[inst].totalThumbContainerWidth) {
					// Save the new position
					pointer.settings[inst].currentPosition = parseInt($(pointer.settings[inst].thumbs).parent().css('left')) - pointer.settings[inst].scrollDistance;
					// Temporarily remove the click event from the button
					pointer.settings[inst].nextButton.unbind('click');
					// Animate the scrolling...
					$(jQobj).find(pointer.settings[inst].thumbs).parent().animate({
						left: '-=' + pointer.settings[inst].scrollDistance + 'px'
					},
					{
						duration: pointer.settings[inst].scrollDuration,
						complete: function () {
							pointer.settings[inst].nextButton.click(function () { pointer.scrollRight(jQobj, pointer, inst) });
						}
					});
				}
			},

			calculateScrollDistance: function (jQobj, pointer, inst) {
				// Get the width of one of the thumbs
				pointer.settings[inst].thumbWidth = $(jQobj).find(pointer.settings[inst].thumbs).eq(0).width();
				// Add on any margin and padding
				//pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('border-right-width'));
				//pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('border-left-width'));
				pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('margin-left'));
				pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('margin-right'));
				pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('padding-left'));
				pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('padding-right'));
				// Calculate how much to scroll the thumbs
				pointer.settings[inst].scrollDistance = pointer.settings[inst].numThumbsShown * pointer.settings[inst].thumbWidth;
			},

			setThumbContainerWidth: function (jQobj, settings) {
				settings.totalThumbs = $(jQobj).find(settings.thumbs).length;
				settings.totalThumbContainerWidth = settings.totalThumbs * settings.thumbWidth;
				$(jQobj).find(settings.thumbs).parent().css('width', settings.totalThumbContainerWidth + "px");
			},

			setThumbFade: function (jQobj, settings) {
				$(jQobj).find(settings.thumbs).find('img').hover(
					function () {
						$(this).animate(
							{ opacity: settings.thumbFade },
							{ duration: settings.thumbFadeDuration, queue: false });
					},
					function () {
						$(this).animate(
							{ opacity: 1 },
							{ duration: settings.thumbFadeDuration, queue: false });
					}
				);
			},

			showNewPicture: function (jQobj, settings) {
				// Loop through all the thumbs
				$(jQobj).find(settings.thumbs).find('a').click(function () {
					// Calculate which thumbnail was clicked on
					var index = $(this).parents('ul').children().index(this.parentNode);
					// Hide the existing image and show the new one
					$(jQobj).find(settings.images).removeClass('current').css('display', '').eq(index).addClass('current');
					return false;
				});
			},

			positionCaptions: function (jQobj, settings) {
				$(jQobj).find(settings.images).css({
					'position': 'relative',
					'zoom': 1
				}).find('div').css({
					'position': 'absolute',
					'bottom': '0'
				});
			},

			setCaptionFade: function (jQobj, settings) {
				$(jQobj).find(settings.images).find('div').each(function () {
					if ($(this).children('p').text() == '') $(this).children('p').css('display', 'none');
				});
				$(jQobj).find(settings.images).hover(
					function () { $(this).find('div').fadeIn(); },
					function () { $(this).find('div').fadeOut(); }
				);
			},

			setCredit: function (jQobj, settings) {
				$(jQobj).find(settings.images).slice(1).find('span').each(function () {
					if ($(this).children('a').text() == '') $(this).css('display', 'none');
					else if ($(this).children('a').attr('href') == '') $(this).children('a').replaceWith($(this).children('a').text());
				});
			},

			clickForNextImage: function (jQobj, settings) {
				var index, length = $(jQobj).find(settings.images).length - 1;
				$(jQobj).find(settings.images).find('a').click(function () {
					$(jQobj).find(settings.images).each(function (i) {
						if ($(this).is(':visible')) {
							index = i;
						}
					});
					/*If this link is a credit link, go to the page.*/
					if ($(this).parent().attr('class') == 'credit') return;
					if (index >= length) {
						$(jQobj).find(settings.thumbs).eq(0).find('a').click();
					}
					else {
						$(jQobj).find(settings.thumbs).eq(index + 1).find('a').click();
					}
					return false;
				});
			}

		}

	});

	$(function () {
		$('div.gallery').createGallery({
			url: '/AJAX/Events/gallery_contents.aspx?eventCode=' + Config.get('eventcode') + '&companyCode=' + Config.get('companycode'),
			numThumbsShown: 5,
			maxHeight: 350
		});
	});

})(jQuery)
