/**
 * JQuery plugin which implements a fronend part of the FCKeditor light box plugin.
 * Its main is adding necessary dom nodes to the start link.
 * 
 * @author Anton Vasilyev <anton.vasilyev@gtmdevelopments.com>
 */
(function($) {
	/**
	 * Main plugin method.
	 * 
	 * @return {void}
	 * @author Anton Vasilyev <anton.vasilyev@gtmdevelopments.com>
	 */
	$.fn.fckLightBox = function() {
		
		// Get all galleries identifiers which are presented on the page. 
		var galleryIds = [];
		for (var i = 0; i < this.length; i++) {
			galleryIds.push($(this[i]).attr('galleryId'))
		}
		
		// New variable which is stored start links. It's necessary for circuits.
		var startLinks = this;
		
		// Ajax query for getting images for all libraries and dom building.
		$.post('/image_library/json.php', {"galleryIds[]": galleryIds}, function(data) {
			for (var i = 0; i < startLinks.length; i++) {
				var startLink = $(startLinks[i]);
				
				// If gallery has images. 
				if(imgs = data[$(startLink).attr('galleryId')]) {
					
					// Container for hiding of images.
					var div = $('<div></div>');
					div.hide();
					
					// Add images into container with agreements of light box format.
					for (var j = 0; j < imgs.length; j++) {
						a = $('<a></a>');
						a.attr('href', '/repository/' + imgs[j]['imgName']);
						a.attr('alt', imgs[j]['imgTitle']);
						a.attr('title', imgs[j]['imgTitle']);
						div.append(a);
					}
					
					startLink.attr('nolightbox', 1).append(div);
					
					var img = $(startLink.children().get(0));
										
					// Start light box plugin for built images.
					$('a', startLink).add(startLink).lightBox();
				} else {
					
					// Show alert if it's empty gallery.
					startLink.click(function () {
						alert('Assigned gallery named "' + $(this).attr('galleryName') + '" is empty.');
						return false;
					});
				}
			}
		}, 'json');
	} 
})(jQuery);