var InlineGallery = Class.create();

InlineGallery.prototype = {
	gallery_id_prefix : 'inline_gallery_',
//	gallery_container_class : 'inline_gallery_container',

	loader_class : 'inline_gallery_loader',
	thumbnail_class : 'inline_gallery_thumbnail',
	thumbnail_current_class : 'inline_gallery_thumbnail_current',
	thumbnail_link_suffix : '_link',

	fullimage_class : 'inline_gallery_current_image',
	fullimage_title_class : 'inline_gallery_current_image_title',
	fullimage_content_class : 'inline_gallery_current_image_content',

	fullimage_cache : new Array(),
	thumbnails : new Array(),
	current_index: -1,

	// Flags - Keep this in sync with singlelargeimagegallery.js. TODO: Add common code
	flagWrap: 4,

	HideEnquiryForm : function() {
		contents = this.holder.getElementsByClassName('inline_gallery_enquire_content')[0];
		contents.style.display="none";
	},

/*
  This function handles the clicking on a thumbnail. Its job is to place the main image into the main div in the viewer.
*/
	handleClick: function(index) {

		for (var i = 0; i < this.thumbnails.length; i++) {
			if ( this.thumbnails[i].link != null ) {
				this.thumbnails[i].link.removeClassName(this.thumbnail_current_class);
			}
		}

		this.HideEnquiryForm();

		var img = this.thumbnails[index];
		img.link.addClassName(this.thumbnail_current_class);

		// TODO: do more thorough checking (ie is array/Image, certain attributes exist)
		if (this.fullimage_cache[index] != undefined) {
			// send this to the large image loader
			this.loadLargeImage(img);
		} else {
			//this.fullimage.src = '';
			//this.fullimage.style.background = "transparent url(" + this.loaderUrl + ") no-repeat scroll center center";
			this.prefetchImage(img, true);
		}


		// Show the contents with the main image etc. By removing the class inline_gallery_grid_container it becomes visible
		if (this.holder.hasClassName('inline_gallery_grid_container')) {
			this.holder.removeClassName('inline_gallery_grid_container');
			//window.parent.scrollTo(window.parent.scrollX,0);
			window.scrollTo(window.scrollX,0);
		}

		// Set the slider to the right position to centre the selected thumbnail
		var element = $('inline_gallery_thumb_holder_'+this.gallery_id);
		var dist = ((img.parentNode.parentNode.offsetLeft - (element.offsetWidth/2)) + (img.offsetWidth/2)) / (element.scrollWidth - element.offsetWidth);
		this.scroller.setValue(dist);

		// Show or hide the enquiry option depending on what's required, but only if it exists anyway
		if ( this.holder.getElementsByClassName("inline_gallery_enquire_message")[0] ) {
			if ( this.HideEnquiry(img) ) {
				this.holder.getElementsByClassName("inline_gallery_enquire_message")[0].style.display = "none";
			} else {
				this.holder.getElementsByClassName("inline_gallery_enquire_message")[0].style.display = "block";
			}
		}

	},


// Returns whether we should hide the enquiry link
	HideEnquiry: function(img) {
		if ( !this.enquiryData.showLinkByDefault ) {
			return RawDescription(img).indexOf("[enquiry]") == -1;

		} else {
			return RawDescription(img).indexOf("[noenquiry]") != -1;
		}
	},

	// does what it says on the box
	initialize: function(gallery_id, flags, galleryEffects, enquiryData) {
		this.galleryEffects = galleryEffects;
		this.gallery_id = gallery_id;
		this.container = $(this.gallery_id_prefix+gallery_id);
		this.scroller = eval('igScroller'+this.gallery_id);
		this.holder = $('inline_gallery_'+this.gallery_id);
		this.enquiryData = enquiryData;
		this.flags = flags;

		var gridLinks = this.holder.getElementsByClassName('inline_gallery_link_view_grid');
		for (var i = 0; i < gridLinks.length; i++) {
			var gridLink = gridLinks[i];
			gridLink.gallery = this;
			// Hide the main image and strip bars by adding an inline_gallery_grid_container class which hides it.
			gridLink.onclick = function() {
				this.gallery.holder.addClassName('inline_gallery_grid_container');
				this.gallery.scroller.setValue(0);
				this.gallery.loadLargeImage(false);

				// Hide any enquiry form
				contents = this.gallery.holder.getElementsByClassName('inline_gallery_enquire_content')[0];
				contents.style.display="none";

				return false;
			}
		}

		var enquireLinks = this.holder.getElementsByClassName('inline_gallery_enquire_message');
		for (var i = 0; i < enquireLinks.length; i++) {
			var enquireLink = enquireLinks[i];
			enquireLink.gallery = this;
			enquireLink.onclick = function() {

				var caption = this.gallery.holder.getElementsByClassName("inline_gallery_current_image_title")[0].innerHTML;
				var description = this.gallery.holder.getElementsByClassName("inline_gallery_current_image_content")[0].innerHTML;

				var message = ReplaceInfo(this.gallery.enquiryData.message, caption, description, document.location.href)

				document.getElementById(this.gallery.enquiryData.id).value = message;

				contents = this.gallery.holder.getElementsByClassName('inline_gallery_enquire_content')[0];
				contents.style.display="block";
				return false;
			}
		}

		// get all the parts of the full image display
		this.fullimage = document.getElementsByClassName(this.fullimage_class, this.container)[0];
		this.fullimage_title = document.getElementsByClassName(this.fullimage_title_class, this.container)[0];
		this.fullimage_content = document.getElementsByClassName(this.fullimage_content_class, this.container)[0];

		this.thumbnails =  document.getElementsByClassName(this.thumbnail_class, this.container);

		// if we use prototype's .each() here, the 'this' keyword points to the thumbnail instead of the gallery
		// which is just a nuisance
		for (var i = 0; i < this.thumbnails.length; i++) {
			var img = this.thumbnails[i];
			// this assumes we're using the wordpress default thumbnail naming/placing settings
			img.full_url = img.parentNode.href; //img.src.replace('.thumbnail', '');
			img.inline_gallery_index = i;
			img.inline_gallery = this;

			// this is so we can remove HTML tags from the mouseover
			img.img_title = img.title;
			img.title = img.title.replace(/<(?:.|\s)*?>/g, "");

			// if the image has an ID, use it to try find the associated link
			img.link = null;
			if (img.id) {
				var link_id = img.id + this.thumbnail_link_suffix;
				img.link = $(link_id);
			}
			// otherwise, try find an ancestor link
			if (img.link == null) {
				var ancestors = img.ancestors();
				for (var a = 0; a < ancestors.length; a++) {
					ancestor = ancestors[a];
					if (ancestor.tagName == 'A' || ancestor.tagName == 'a') {
						img.link = ancestor;
						// TODO: check this
						break;
					}
				}
			}

			// don't bother if the image uses a lightbox
			if (img.hasClassName('lightbox') || img.rel == 'lightbox') {
				return;
			}

			// assign the onclick event
			if (img.link != null) {
				img.link.inline_gallery_index = i;
				img.link.inline_gallery = this;
				if ( document.getElementById('inline_gallery_link_view_grid_id') == null ) {
					this.handleClick(Number(0));
				}
				Event.observe(img.link, 'click', function(event) { 'InlineGallery'+this.inline_gallery.thumbnailClicked(event, this.inline_gallery_index); }.bindAsEventListener(img.link), true);
			}

		}
		this.fullimage.inline_gallery = this;
		// Add event for main image click
		Event.observe(this.fullimage, 'mouseup', function(event) { 'InlineGallery'+this.inline_gallery.mainImageClicked(event); }.bindAsEventListener(this.fullimage), true);
	},

	thumbnailCount: function()
	{
		return this.thumbnails.length;
	},

	atLastImage: function()
	{
		return this.current_index == this.thumbnailCount() - 1;
	},

	mainImageClicked: function(event)
	{
		Event.stop(event);

		var nextIndex = this.current_index;
		if ( this.atLastImage() ) {
			if ( this.wrapNavigation() ) {
				nextIndex = 0;
			}
		} else {
			nextIndex++;
		}
		this.handleClick(nextIndex);
	},

	// make the magic happen when a thumbnail is clicked
	thumbnailClicked: function(event, index) {
		Event.stop(event);
		this.handleClick(index);
	},

	prefetchImage: function(img, display) {
		var gal = this;

		var loader = document.getElementsByClassName(this.loader_class, this.container)[0];
		if ( loader != null ) {
			loader.style.display = "block";
		}

		imageObject = new Image();
		imageObject.onload = function() {
			this.imagepreloaded = true;
			gal.fullimage_cache[img.inline_gallery_index] = this;

			if (display) {
				gal.loadLargeImage(img);
			} else {
				if ( loader != null ) {
					loader.style.display = "none";
				}
			}
		}
		if ( this.galleryEffects == 0 ) {
			loader.style.display = "none";
		}
		imageObject.src = img.full_url;
	},

/* Loads an image into the large image div
  @param img The image to load, or false if you want to clear it.
*/

	loadLargeImage: function(img) {

		var fullimage = this.fullimage;
		var fullimage_title = this.fullimage_title;
		var fullimage_content = this.fullimage_content;
		var loader = document.getElementsByClassName(this.loader_class, this.container)[0];

		if (img == false) {
			fullimage.src = 'spacer.gif';
			fullimage_title.innerHTML = '';
			fullimage_content.innerHTML = '';
			this.current_index = -1;
			return;
		}

		var changeDuration = 0.5 * this.galleryEffects;

		if ( this.galleryEffects == 1 ) {
			if ( loader != null ) {
					loader.style.display = "none";
			}
			new Effect.Opacity(fullimage, {
					duration: changeDuration,
					transition:Effect.Transitions.linear,
					from: 1.0,
					to: 0.01,
					afterFinish:function(effect) {
						fullimage.style.display = 'none';
//						fullimage.style.height="auto";
						fullimage.src = img.full_url;
						fullimage.style.display = 'block';
						new Effect.Appear(fullimage, {
							duration: changeDuration
							});
					}
			});

			new Effect.Opacity(fullimage_title, {
					duration: changeDuration,
					transition:Effect.Transitions.linear,
					from: 1.0,
					to: 0.01,
					afterFinish:function(effect) {
						fullimage_title.innerHTML = Title(img);
						new Effect.Appear(fullimage_title, {duration: changeDuration});
					}
			});

			new Effect.Opacity(fullimage_content, {
					duration: changeDuration,
					transition:Effect.Transitions.linear,
					from: 1.0,
					to: 0.01,
					afterFinish:function(effect) {
						fullimage_content.innerHTML = Description(img);
						new Effect.Appear(fullimage_content, {duration: changeDuration});
					}
			});
		} else {
			if ( loader != null ) {
				loader.style.display = "none";
			}
			fullimage.src = img.full_url;
			fullimage_title.innerHTML = Title(img);
			fullimage_content.innerHTML = Description(img);
		}

		this.current_index = img.inline_gallery_index;
	},

	wrapNavigation: function()
	{
		return this.flags & this.flagWrap;
	}
};

	function Index(img)
	{
		return img.inline_gallery_index;
	}

	function Title(img)
	{
		return img.img_title;
	}

	// Returns the raw description as it was entred in the media editor
	function RawDescription(img)
	{
		return img.alt;
	}

	// returns the converted description
	function Description(img)
	{
		description = img.alt.replace("[noenquiry]","");
		description = description.replace("[enquiry]","");
		return description;
	}

	  function ReplaceInfo(message, caption, description)
	  {
		message = message.replace('[caption]', caption);
		message = message.replace('[description]', description);

		return message;
	  }
