//create closure
(function($) {

	// plugin definition	
	$.fn.mediaexplorer_selector = function(options) {
		
		// build main options before element iteration
		var opts = $.extend({}, $.fn.mediaexplorer_selector.defaults, options);		
		
		// iterate over each matched element
		return this.each(function() {
			
			var self = this;		
			
			//On the first entry in we'll either have a next button or not - we would never get a prev button as we'd arrive at the first item which makes prev redundant
			//therefore, add a prev button if a next button exists - hide it straight away - as we're on the first item.
			//The href for next will be correct - don't worry about one for prev at moment			
			if($(self).find('UL.' +opts.paginationClass +' LI.next').length!=0){
				$(self).find('UL.' +opts.paginationClass).prepend("<li class=\"prev\"><a href=\"#\" title=\"View Previous Page\">&#171;</a></li>");				
				$(self).find('UL.' +opts.paginationClass +' LI.prev').hide();
			}
			
			//Get a handle on the prev and next buttons
			var hndlPrev = ($(self).find('UL.' +opts.paginationClass +' LI.prev'));
			var hndlNext = ($(self).find('UL.' +opts.paginationClass +' LI.next'));
			
			//indexes of first and last item - i.e. not the prev and next
			var iFirstItem = 1;
			var iLastItem = ($('UL.' +opts.paginationClass + ' LI').length)-2;
			var iItemCount = $('UL.' +opts.paginationClass + ' LI').length;
			
			//Add an index property to each item
			$('UL.' +opts.paginationClass +' LI').each(function(iCount){
				this.myIndex=iCount;
			})

			//Get the index of the currently selected item
			var iSelected=1;
			
			//handle click on media item
			var onSelectEvent = function(e){										
				e.preventDefault();	
				e.stopPropagation();
				$eventElement=$($(e.target).parents('LI').find("A")[0]);
				
				//remove selected class from any selected elements
				$(self).find('UL.' +opts.itemsClass +' LI.' +opts.selectedClass).removeClass(opts.selectedClass);
				
				//add selected class to current element
				$($(e.target).parents('LI')[0]).addClass(opts.selectedClass);
				
				//broadcast event
				$(self).trigger('selectEvent',$eventElement);										
			}


			
			//handle click on pagination item
			var onSelectPageEvent = function(e){										
				e.preventDefault();	
				e.stopPropagation();
				$eventElement=$($(e.target).parents('LI').find("A")[0]);
				
				//Get index of the clicked item
				var itemIndex=$($(e.target).parents('LI')[0])[0].myIndex;
				
				//remove selected class from any selected elements
				$('UL.' +opts.paginationClass +' LI.' + opts.selectedClass).removeClass(opts.selectedClass);
				
				//add selected class to current element - unless it was the prev or next selected - if so we should actually selected the item to the left or right
				if((itemIndex==0) || (itemIndex==iItemCount-1)){
					//If prev then highlight the item to the left of currently selected
					if(itemIndex==0){
						$('UL.' +opts.paginationClass + ' LI:eq(' + (iSelected - 1) + ')').addClass(opts.selectedClass);
						iSelected-=1;
					}
					
					//If next then highlight the item to the right of selected
					if(itemIndex==iItemCount-1){
						$('UL.' +opts.paginationClass + ' LI:eq(' + (iSelected + 1) + ')').addClass(opts.selectedClass);
						iSelected+=1;
					}
					
				}
				else{
					$($(e.target).parents('LI')[0]).addClass(opts.selectedClass);
					iSelected=itemIndex;
				}
				
				//broadcast event
				$(self).trigger('selectPageEvent',$eventElement);											

				var h=$($eventElement).attr('href');
				var set=$.getURLParameter(h,'set');		
				var set_offset=$.getURLParameter(h,'set_offset');	
				var theme_group=$.getURLParameter(h,'theme_group');	
				var theme=$.getURLParameter(h,'theme');	

				if(set==""){
					var cleanHref=h.replace(opts.baseURL,"");					
					var parts=cleanHref.split("/");
					theme_group=parts[0];
					theme=parts[1];
					set=parts[2];
					set_offset=0;					
					if(parts.length==4){
						//theme_group/theme/set/offset/
						set_offset=parts[3];
					}else if(parts.length==6){
						//theme_group/theme/set/type/id/offset
						set_offset=parts[5];
					}
				}				



				data="theme_group=" +theme_group +"&theme=" +theme +"&set=" +set +"&set_offset=" +set_offset;
				
			
		
				//Hide / show the prev / next buttons
				if($('UL.' +opts.paginationClass +' LI.next').length!=0){
					
					//If the selected item is not item 2 (1st is prev) then show prev
					$('UL.' +opts.paginationClass +' LI:eq(' + iFirstItem + ')').hasClass(opts.selectedClass)?hndlPrev.hide():hndlPrev.show();
					
					//If the selected item is not the last item then show next
					$('UL.' +opts.paginationClass +' LI:eq(' + iLastItem + ')').hasClass(opts.selectedClass)?hndlNext.hide():hndlNext.show();
				
				}
				
				//Set the hyperlink values of the prev and next buttons
				var reOffset=new RegExp("\\d+$");
				var iOffset=reOffset.exec($('UL.' +opts.paginationClass +' LI.' + opts.selectedClass + ' a')[0].href);
				
				if($('UL.' +opts.paginationClass +' LI.prev a').length)
					$('UL.' +opts.paginationClass +' LI.prev a')[0].href=($('UL.' +opts.paginationClass +' LI.' + opts.selectedClass + ' a')[0].href).replace(/\d+$/,(parseInt(iOffset) - opts.pageLength));
				if($('UL.' +opts.paginationClass +' LI.next a').length)
					$('UL.' +opts.paginationClass +' LI.next a')[0].href=($('UL.' +opts.paginationClass +' LI.' + opts.selectedClass + ' a')[0].href).replace(/\d+$/,(parseInt(iOffset) + opts.pageLength));
				
				

				//make ajax request and assign error/success handlers 
				//error/success functions required to mantain scope
				$.ajax({
					url: opts.ajaxURL,
					processData: false,
					data: data,
					dataType: "text",
					error: 		function(data){	onPageDataError(data);	},
					success: 	function(data){	onPageDataSuccess(data);	}
				});				
			}			

			var onPageDataError=function(data){
				alert("There was a problem loading the requested page data.");
			}
			var onPageDataSuccess=function(data){				
				$('BODY').append('<div id="__me_temp__">' +data +'</div>');
				var h=$('#__me_temp__ .' +opts.itemsClass +'').html();
				$(self).find('.' +opts.itemsClass +'').html(h);
				$('#__me_temp__').remove();
				
				
				
				applyItemEvents();
				applyLIEvents();
			}
			
			var applyItemEvents=function(){
				$(self).find('UL.' +opts.itemsClass +' LI A').bind('click',onSelectEvent);
			}
			var applyLIEvents=function(){
				//all LI clicks trigger internal link 
				$(self).find('UL LI').bind('click',function(e){
					$($(this).find('A')[0]).trigger('click');
				}).hover(function(){
					$(this).addClass('hover');
				},function(){
					$(this).removeClass('hover');
				});
			}			
			
			

			

			
			
			
			//bind events						
			
			//all link clicks trigger onSelectEvent()
			$(this).find('UL.' +opts.paginationClass +' LI A').bind('click',onSelectPageEvent);
			applyItemEvents();
			applyLIEvents();
			
			// if a set, type and id is defined in the url use that as the default current item
			// get current window url and check to see if an "a" has the same href, in which case, trigger a click event
			var url=window.location.toString();
			var point=url.indexOf('mediaexplorer/?');
			point=point+15; // to accomodate 'mediaexplorer/?'
			var rightPartOfUrl=url.substr(point,url.length-point);
			if(rightPartOfUrl.indexOf('set=')>-1&&rightPartOfUrl.indexOf('type=')>-1&&rightPartOfUrl.indexOf('id=')>-1)
			{
				var itemindex=0;
				var incr=0;
				var aitem = $(this).find('UL.' +opts.itemsClass +' LI.' +opts.selectedClass +' A');
				$('.me-selector li .image a').each(function (i) {
					var hrf=this.href;
					var hrfpoint=hrf.indexOf('mediaexplorer/?');
					hrfpoint=hrfpoint+15; // to accomodate 'mediaexplorer/?'
					var hrfrightPartOfUrl=hrf.substr(hrfpoint,hrf.length-hrfpoint);
					if(hrfrightPartOfUrl==rightPartOfUrl)
					{
						// this is a match ie. the current
						itemindex = incr;
						return;
					}
					incr++;
				});
			}
			// quick sanity check
			if(typeof(itemindex)=="undefined")
				itemindex=0; // ie. the default
			
			//trigger selected/first element (progressive enhancement)			
			var selectedElements=$(this).find('UL.' +opts.itemsClass +' LI.' +opts.selectedClass +' A');
			var selectedElement=(selectedElements.length>0) ? $(selectedElements[0]) : $( $(this).find('UL.' +opts.itemsClass +' LI')[itemindex] );			
			selectedElement.trigger('click');
			
		});
		//end this.each loop

	};
	//end $.fn.mediaexplorer_selector
	
	// plugin defaults	
	$.fn.mediaexplorer_selector.defaults = {		
		ajaxURL: '',
		pageLength: 6,
		itemsClass: 'items',
		paginationClass: 'pagination',
		selectedClass: 'selected'
	};	

// end of closure
})(jQuery);

