/**
 * A FlickrChooser object
 *
 * @param string containerId	the id of the field that encapsulates this FlickrChooser
 * @param string saveCallbackFunction	a callback function (or function name) to utilise when saving the FlickrChooser data
 * @param string closeCallbackFunction	a callback function (or function name) to utilise when closing the FlickrChooser
 *
 */
var FlickrChooser = function( containerId, saveCallbackFunction, closeCallbackFunction )
{
	// Private properties
	var _containerId;
	var _saveCallbackFunction;
	var _closeCallbackFunction;


	/**
	 * Initialisation
	 *
	 * @param string containerId	the id of the field that encapsulates this FlickrChooser
	 * @param string saveCallbackFunction	a callback function (or function name) to utilise when saving the FlickrChooser data
	 * @param string closeCallbackFunction	a callback function (or function name) to utilise when closing the FlickrChooser
	 */
	this.init = function( containerId, saveCallbackFunction, closeCallbackFunction )
	{
		_containerId = containerId;
		_saveCallbackFunction = saveCallbackFunction;
		_closeCallbackFunction = closeCallbackFunction;
	}


	/**
	 * Displays the hover for the FlickrChooser
	 *
	 * @param string defaultKeyword	the default keyword to utilise in the FlickrChooser
	 */
	this.show = function( defaultKeyword )
	{
		var self = this;
		var container = $('#' + _containerId);

		// Load the content of the Flickr chooser
		$(container).load('/flickr/select/', function()
		{
			// Center hover
			if( typeof centerPanel == 'function' )
			{
				centerPanel(container);
			}

			// Input the default keyword
			$('input#keyword').val(defaultKeyword);

			// Ensure the form is never submitted
			$('#flickr').submit( function()
			{
				return false;
			});

			// Bind the 'Search' link to the Search method
			$('#btnSearch').click( function()
			{
				self.search();

				return false;
			});

			// Bind the 'Select image' to save the image if one is selected
			$('#btnSelect').click( function()
			{
				var selectedImage = $('div#imagePreview img');

				if( 0 == selectedImage.length )
				{
					alert('Please select an image');
				}
				else
				{
					// Add loading to parent div
					$(this).parent().addClass('loading');

					// Save the flick image using AJAX
					self.save(selectedImage);
				}

				return false;
			});

			// Ensure the close button closes the hover
			$("#btnClose").click( function()
			{
				self.close();
			});

			// Submit the search
			$('#btnSearch').click();

			// Fade in the container for the form
			$(container).fadeIn(1200);
		});


		return false;
	}


	/**
	 * Searches for an image in flickr
	 */
	this.search = function()
	{
		var self = this;

		if( $('input#keyword').val().length == 0 )
		{
			// No keyword entered, so return
			return false;
		}

		// ... keyword exists, so perform the search.
		$('div#results').html('<div class="loading">Searching...</div>');

		$.get('/flickr/search/', {q: $('input#keyword').val(), source: $('#source').val()}, function(data)
		{
			// Load the data returned from the search
			$('div#results').html(data);

			// If no results were found then show a message indicating this and return.
			if( $('div.scrollable ul.items li').length == 0 )
			{
				// No results found
				self.updatePreview('');

				$('#btnSelect').hide();

				$('div#results').html('<p><strong>No images could be found matching your search criteria.</strong></p>')

				return false;
			}

			// ... results found.

			// Initialise scrollable
			$('div.scrollable').scrollable(
			{
				size: 4,
				activeClass: ''
			}).mousewheel().navigator({naviItem: 'li'});

			$('.navi li').each( function(index)
			{
				$(this).html('<a href="#' + index + '">' + (index+1) + '</a>');
			});

			// Since there are multiple images in one li item, set the class 'active' on an image when it is clicked
			$('div.scrollable ul.items li img').click( function()
			{
				$('div.scrollable ul.items li img').removeClass('active');
				$(this).addClass('active');

				// Update the preview image to be the source specified in the 'preview' attribute
				self.updatePreview($(this).attr('preview'));
			});

			// Make the first image the currently selected one
			var firstImage = $('div.scrollable ul.items li:first img:first');
			firstImage.click();
		});

		return false;
	}


	/**
	 * Closes the container of the FlickrChooser
	 */
	this.close = function()
	{
		// Fade out the container
		var container = $('#' + _containerId);

		$(container).fadeOut(800, function()
		{
			// Issue the callback function if exists
			if( typeof _closeCallbackFunction == 'function' )
			{
				_closeCallbackFunction();
			}
		});
	}


	/**
	 * Save the selected image and issue the callback function. Then close the FlickrChooser.
	 *
	 * @param DOMObject selected	img object of selected flickr image
	 */
	this.save = function( selectedImage )
	{
		// Declare variables
		var self = this;
		var imageUrl = selectedImage.attr('src');

		// Ensure largest image is used from flickr
		imageUrl = imageUrl.replace('_m.jpg', '.jpg');

		// Save the flick image using AJAX
		$.post('/flickr/save/', {name: $('input#keyword').val(), url: imageUrl}, function(data)
		{
			// Issue the save callback function if it exists
			if( typeof _saveCallbackFunction == 'function' )
			{
				_saveCallbackFunction(data);
			}

			// Close the hover/dialog
			self.close();
		}, "json");

		return false;
	}


	/**
	 * Updates the preview area to show the image specified at imageUrl.
	 *
	 * @param string imageUrl
	 */
	this.updatePreview = function( imageUrl )
	{
		// If no url is provided, then remove all content from the preview area
		if( imageUrl.length == 0 )
		{
			$('#imagePreview').empty();

			return;
		}

		// ... an image url exists.
		// Update the preview area to show image loading message
		$('#imagePreview').html('<div class="loading">Loading Preview...</div>');

		// Load the new preview image
		var img = new Image();

		$(img).load( function()
		{
			$(this).hide();

			$('#imagePreview').empty();
			$('#imagePreview').append(this);

			$(this).fadeIn();

			$('#btnSelect').show();
			$('#btnSelect').css('background-position', 'top left');	// this is needed to fix an IE display issue
		}).attr('src', imageUrl);
	}


	// Initialise
	this.init(containerId, saveCallbackFunction, closeCallbackFunction);
}
