//create closure
(function($) {

	// plugin definition	
	$.fn.mediaexplorer_imagegallery = function(options) {
		
		// build main options before element iteration
		var opts = $.extend({}, $.fn.mediaexplorer_imagegallery.defaults, options);		
		
		// iterate over each matched element
		return this.each(function() {
				
			var self = this;
			var jData=opts.jData;
		
			//handle click on media item
			var onImageItemClick = function(e){				
				e.preventDefault();
				e.stopPropagation();
				
				$eventElement=$(e.target);				
				
				var h=$eventElement.attr('href');
				var image_no=$.getURLParameter(h,'image_no');								
				var imageNode=$(jData.find("image_item")[image_no-1]);
				
				writeImage(image_no,imageNode);			
			}
			//write a single image
			var writeImage=function(image_no,imageNode){ 	
				var title=$(imageNode.find("title")[0]).text();
				var author=$(imageNode.find("author")[0]).text();
				var location=$(imageNode.find("location")[0]).text();
				var image_url=$(imageNode.find("image")[0]).text();
				var image_lightbox_url=$(imageNode.find("lightbox_image")[0]).text();
				var image_no=image_no;
				
				var i='<img src="' +image_url +'" alt="' +title +'" width="' +opts.imageWidth +'" height="' +opts.imageHeight +'" />';
					
				var info="";
				info+=author.length>0?author:"";
				if(location.length){
					if(info.length){
						info+=" , ";
					}
					info+=location;
				}				
				
				//write image	
				$(self).find('.image-container').html(i);
				

				if((!(typeof setNewLineOnFullStop=="undefined")) && setNewLineOnFullStop){
					var newTitle = title.replace('.','.<br />');
					$('.me-info .title').html(newTitle);
					
					if($('.me-info .info').length<=0){
						glow.dom.get('.me-info .main').append(glow.dom.create('<p class="info"></p>'));
					}
				}
				else{
					$('.me-info .title').html(title);
				}

				var authorloc = '';
				if(location.length){
					authorloc+=location;
					authorloc+=" , ";
				}
				authorloc += (author.length>0?"Image by ":"") + author;
				$('.me-info .info').html(authorloc);
				
				//update lightbox link
				$(self).find('.controls UL.extra LI.lightbox').remove();
				var c=image_lightbox_url.length>0 ? '' : 'disabled';
				
				if(image_lightbox_url.length>0){
					$(self).find('.controls UL.extra').append('<li class="lightbox ' +c +'"><a href="' +image_lightbox_url +'?lightbox_url=' +image_lightbox_url +'">' +opts.lightboxLabel +'</a></li>');				
					$(self).find('.controls UL.extra LI.lightbox A').bind('click',doLightbox);
				}
				
				$(self).find('.controls UL.image_no LI.selected').removeClass(opts.selectedClass);								
				var image_nos=$(self).find('.controls UL.image_no LI');
				$(image_nos[image_no-1]).addClass(opts.selectedClass);

				writeImageControls(image_no);
			}			
			var writeImageControls=function(image_no){ 
				var h="";
				var c;
				var i;
				var link;
				var title;
				var label;			
				 	
				var page=Math.floor((image_no-1)/opts.pageSize)+1;
				var pages=Math.ceil(opts.noOfImages/opts.pageSize);
								
				var start=((page-1)*opts.pageSize)+1
				var stop=start+opts.pageSize-1;
				if(stop>opts.noOfImages) stop=opts.noOfImages;
				
				//More than 2 images? Add a prev and next link
				if(opts.noOfImages>2){
					h+="<li class=\"prev\"><a title=\"" + opts.viewPrev + "\" href=\"#\">" + opts.prev + "</a></li>"
				}
				
				if(opts.noOfImages>1){
					//do individual image links
					for(var i=start; i<=stop;i++){
						c=i==image_no ? ' class="' +opts.selectedClass +'"' : '';
						var link='?type=' +opts.type +'&id=' +opts.id +'&image_no=' +i;
						var title='View Image ' +i +' of ' +opts.noOfImages;				
						var label=String(i);					
						//if(label.length==1) label="0" +label;
						h+="<li " +c +"><a href=\"" +link +"\" title=\"" +title +"\">" +label +"</a></li>";
					}
				}
				
				if(opts.noOfImages>2){
					h+="<li class=\"next\"><a title=\"" + opts.viewNext + "\" href=\"#\">" + opts.next + "</a></li>"
				}
				
				//write html	
				$(self).find('.controls UL.image_no').html(h);							

				//Get Handles on the prev and next
				var hndlPrev = $('UL.image_no LI.prev');
				var hndlNext = $('UL.image_no LI.next');
				
				//Hide the prev if we're on item 1
				(image_no > 1)?hndlPrev.show():hndlPrev.hide();
				
				//Hide the next link if we're on the last item
				(image_no == opts.noOfImages)?hndlNext.hide():hndlNext.show();
				
				//Set the hyperlink values of the prev and next buttons
				var reOffset=new RegExp("\\d+$");
				var iOffset=reOffset.exec($('UL.image_no LI.' + opts.selectedClass + ' a')[0].href);
				
				$('UL.image_no LI.prev a')[0].href=($('UL.image_no LI.' + opts.selectedClass + ' a')[0].href).replace(/\d+$/,(parseInt(iOffset) - 1));
				$('UL.image_no LI.next a')[0].href=($('UL.image_no LI.' + opts.selectedClass + ' a')[0].href).replace(/\d+$/,(parseInt(iOffset) + 1));
				
				
				
				
				//add mouse events
				$(self).find('.controls UL.image_no LI').addClass('js').bind('click',function(e){
					$($(this).find('A')[0]).trigger('click');
				}).hover(function(){
					$(this).addClass('hover');
				},function(){
					$(this).removeClass('hover');
				});			
				$(self).find('.controls UL.image_no LI A').bind('click',onImageItemClick);
				
			}	


			//write a single image
			var doLightbox=function(e){ 								
				e.preventDefault();
				var h=$(this).attr('href');
				var src=$.getURLParameter(h,'lightbox_url');
				var alt=$(this).attr('title');
				var options={overlay: 80};//, close: false, closeTitle: "close image"}
				var html='<img src="' + src +'" alt="' +alt +'" />';					
				$.modal(html,options);				
			}			
				
				
			
			$(this).find('P.info').html('');				
			$(this).find('UL.extra').html('');				
			writeImageControls(1);			
			
			
			
			//trigger first item (should probably take inital image index as parameter, not first image)
			$($(this).find('.controls UL.image_no LI').filter(':not(.prev) , :not(.next)').find('A')[0]).trigger('click');
						
		});
		//end this.each loop

	};
	//end $.fn.mediaexplorer_imagegallery


	function writeImage($target,url,width,height){ 
		var i='<img src="' +url +'" alt="" width="' +width +'" height="' +height +'" />';
		$target.find('.image-container').html(i);
	}

	
	
	// plugin defaults	
	$.fn.mediaexplorer_imagegallery.defaults = {		
		ajaxURL: '',
		lightboxLabel: 'Enlarge Image',
		selectedClass: 'selected',
		type: 'gallery',
		id: '',
		prev: "&#171;",
		next: "&#187;",
		viewPrev: 'View Previous Image',
		viewNext: 'View Next Image',
		pageSize: 10,
		imageNumber: 1,
		noOfImages: 0,
		imageWidth: 512,
		imageHeight: 288
	};
	

// end of closure
})(jQuery);

