(function( $ ){	
	var methods = {
		init: function(options) {
			var oDefault = 
			{
				nMenuId: 0,
				nCategoryId: 0,
				nOrder: 1,
				nSlideItemWidth: 100,
				nSlideItemHeight: 75,
				nPage: 1,
				bAjaxGet: false,
				bExpandClickedPics: true,
				aSlideContent: [],
				nItemsPerPage: 5,
				sImageRoot: '',
				sBorderColor: '#333333',
				sHighlightColor: 'yellow',
				sFullImageId: '',
				sTagsId: '',
				sRatingsId: '',
				sModifyButtonsId: '',
				bShowComments: false,
				nJumpToId: 0,
				noItems: function(){},
				bRightTitle: false,
				sTransitionIn: 'elastic',
				$selected: ''
			}
			
			options = $.extend(oDefault, options);
			
			return this.each(function(){
				var $this = $(this),
					data = $this.data('sqboxImageSlide');
			
				// If the plugin hasn't been initialized yet
				if(!data){
					$this.data('sqboxImageSlide', options);
					
					$this.sqboxImageSlide('draw');
				}
			});
		},
		draw: function(){
			var $container = $(this),
				data = $(this).data('sqboxImageSlide');
				
			var aItemData = [];
			var nStartPage = 0;
			var nJumpTo = 0;
			var nIdx = 0, nLength = 0;
			
			$container
			.empty()
			.addClass('imageslide-slidecontainer')
			.append('<div class="imageslide-slidenavleft"></div>')
			.append('<div class="imageslide-photoitemcontainer"><table cellpadding="0"  class="imageslide-tablecontainer"><tr></tr></div>');
			
			$('.imageslide-photoitem').live('click', function(){
				$(this).sqboxImageSlide('selectItem');								  
			});
			
			$container
			.append('<div class="imageslide-slidenavright"></div>');

			$container
			.find('.imageslide-slidenavleft')
			.css('background-image',  "url('" + data.sImageRoot + "/buttons/default/previousrecord.gif')")
			.click(function(){
				$(this).sqboxImageSlide('slide', false);			
			});
			
			$container
			.find('.imageslide-slidenavright')
			.css({backgroundImage:  "url('" + data.sImageRoot + "/buttons/default/nextrecord.gif')"})
			.click(function(){
				$(this).sqboxImageSlide('slide', true);			
			});
			
			if(data.bAjaxGet){
				$.ic.ajaxSpinner.show();
				$.ajax({
					type: 'POST',
					url: RATINGS.sWebRoot + '/Includes/ajax/image_slide_ajax.cfm',
					data: {Action: 'get',
						   MenuId: data.nMenuId,
						   CategoryId: data.nCategoryId,
						   Order: data.nOrder,
						   Increment: data.nItemsPerPage,
						   Page: data.nPage},
					success: function($data){
						$data = $($data);
						if($data.find('success').text() == 'true'){
							$data.find('images').children().each(function(nIdx, $o){
								var $frame;
								
								aItemData[nIdx] = {
									sId: $(this).find('imageid').text(),
									sTitle: $(this).find('title').text(),
									sPreviewImage: $(this).find('previewimage').text(),
									sFullImage: $(this).find('fullimage').text(),
									sFileName: $(this).find('filename').text(),
									sCaption: $(this).find('caption').text(),
									sDescription: $(this).find('description').text(),
									sFilesize: $(this).find('filesize').text(),
									sAuthor: $(this).find('author').text(),
									sCopyright: $(this).find('copyright').text(),
									sCopyrightNotice: $(this).find('copyrightnotice').text(),
									sInstructions: $(this).find('instructions').text(),
									sName: $(this).find('name').text(),
									sDateCreated: $(this).find('datecreated').text(),
									sDateTaken: $(this).find('datetaken').text(),
									sEditRights: $(this).find('editrights').text(),
									sDeleteRights: $(this).find('deleterights').text(),
									sGraphicTags: $(this).find('graphictags').text()
								}
	
								$container
								.find('.imageslide-photoitemcontainer tr')
								.append('<td><div class="imageslide-photoitem"></div></td>');
								
								$frame = $container.find('.imageslide-photoitem:eq(' + nIdx + ')');
								
								$frame
								.data('sqboxImageItem', {nIdx: nIdx});
								
								if(nIdx <= data.nItemsPerPage){
									$frame.sqboxImageSlide('loadImage', $frame, $(this).find('previewimage').text());
								}
								
								if(data.nJumpToId == aItemData[nIdx].sId){
									nStartPage = Math.floor(nIdx / data.nItemsPerPage);
									nJumpTo = nIdx;
								}
							});
							
							$.extend($container.data('sqboxImageSlide'), {aSlideContent: aItemData});
							$container.sqboxImageSlide('initializeLoadData', $container, data, nStartPage, nJumpTo);
							
							
						}else{
							$container.sqboxImageSlide('statusUpdate', $data.find('error').text(), true);
						}
						$.ic.ajaxSpinner.hide();
					}
				});
			}else{
				//data is already in data.aSlideContent
				for(var nIdx = 0; nIdx < data.aSlideContent.length; nIdx++){
					var $frame;

					$container
					.find('.imageslide-photoitemcontainer tr')
					.append('<td><div class="imageslide-photoitem"></div></td>');
					
					$frame = $container.find('.imageslide-photoitem:eq(' + nIdx + ')');
					
					if(data.bExpandClickedPics){
						$frame.wrap('<a class="ImageSlideExternal" href="' + data.aSlideContent[nIdx].sFullImage + '" title="' + data.aSlideContent[nIdx].sTitle + '" rel="screenshots"></a>');
						
						if(data.aSlideContent[nIdx].sLink && data.aSlideContent[nIdx].sLink.length > 0){
							$frame.parent().attr('data-link', data.aSlideContent[nIdx].sLink);
						}
						$frame.parent().attr('data-id', data.aSlideContent[nIdx].sId);
					}
					
					$frame
					.data('sqboxImageItem', {nIdx: nIdx});
					
					if(nIdx < data.nItemsPerPage){
						$frame.sqboxImageSlide('loadImage', $frame, data.aSlideContent[nIdx].sPreviewImage);
					}
					
					if(data.nJumpToId == data.aSlideContent[nIdx].sId){
						nStartPage = Math.floor(nIdx / data.nItemsPerPage);
						nJumpTo = nIdx;
					}
				}
				
				if (data.bExpandClickedPics){
					$container
					.find('.ImageSlideExternal')
					.fancybox({
						'transitionIn'		: data.sTransitionIn,
						'transitionOut'		: 'fade',
						overlayShow: true,
						cyclic: true,
						hideOnOverlayClick: false,
						'titlePosition'		: 'over',
						'titleFormat'		: function(title, currentArray, currentIndex, currentOpts){
														
							
							var current = $container.find('.ImageSlideExternal[href="' + currentArray + '"]'); //not happy about this method to determine what the current object is. Couldnt find anything within fancybox that would just return the current object
							var nCurrentSlideID = current.attr('data-id');
							
							var nCurrentSlide = -1;
							var optionsBar = $('#SlideTitle').clone();	
							
							if (typeof $.ic.aryImageProperties != 'undefined'){
								for (i = 0; i < $.ic.aryImageProperties.length; i++){
									if (($.ic.aryImageProperties[i].ID + '') == nCurrentSlideID){
										nCurrentSlide = i;
									}
								}
								
								optionsBar.find('span.SlideImageIndex').html('<a href="' + $.ic.aryImageProperties[nCurrentSlide].LINK + '" style="color: white">' + title + '</a>');
								
								optionsBar.find('table.RatingsContainer').attr('id', 'GraphicsRating');
								RATINGS.setNewRating('GraphicsRating', $.ic.aryImageProperties[nCurrentSlide].MENUID, $.ic.aryImageProperties[nCurrentSlide].CATEGORYID, $.ic.aryImageProperties[nCurrentSlide].ID, false);					
													
								var slideCommentsContainer = optionsBar.find('table.SlideCommentsContainer');
								slideCommentsContainer.find('span.SlideComments').html($.ic.aryImageProperties[nCurrentSlide].NCOMMENTCOUNT);
								slideCommentsContainer.find('img').wrap('<a href="' + $.ic.aryImageProperties[nCurrentSlide].LINK + '&addcomment=1" style="color: white"></a>');
							}
							else {
								optionsBar.find('span.SlideImageIndex').html('<span style="color: white">' + title + '</a>');
							}
																	
							
							return optionsBar.html();	
						},
						onComplete: function(){
							if (data.bRightTitle){
								$('#fancybox-title').width(230);
								$('#fancybox-title').css({
									left: 'auto',
									right: '0px'
								});
								$('#fancybox-title').height($('#fancybox-content').height() + 20);
							}
						}
					})
				}
				
				$container.sqboxImageSlide('initializeLoadData', $container, data, nStartPage, nJumpTo);
			}
			$container.find('*').disableSelection();
		},
		initializeLoadData: function($container, data, nStartPage, nJumpTo){
			//this is in a seperate function because the draw function above may need to call this after an ajax success or right away
			if(data.aSlideContent.length == 0){
				data.noItems();
			}
			
			$container
			.find('.imageslide-photoitem')
			.css({
				 borderColor: data.sBorderColor,
				 width: data.nSlideItemWidth + 'px',
				 height: data.nSlideItemHeight + 'px'
			})
			.show();
			
			$('.imageslide-slidecontainer').css({
				height:	data.nSlideItemHeight + 'px'						
			});
			
			$container.data('sqboxImageSlide').nSlideIdx = 0;
			$container.data('sqboxImageSlide').nSlideInnerWidth = (data.nItemsPerPage * $container.find('.imageslide-photoitem:first').outerWidth()) + (data.nItemsPerPage * 8);
			
			$container
			.css({width: (data.nSlideInnerWidth + (26 * 2)).toString() + 'px'}) //pictures + padding + navigation

			$container
			.find('.imageslide-photoitemcontainer')
			.css({width: data.nSlideInnerWidth.toString() + 'px', position: 'relative', overflow: 'hidden'});
			
			if(nStartPage > 0){
				$container.find('.imageslide-tablecontainer')
				.stop(true, true)
				.css({left: -(data.nSlideInnerWidth * nStartPage)});
				
				data.nSlideIdx = nStartPage;
			}
			
			$container.sqboxImageSlide('configureNav');
			
			nIdx = ((data.nSlideIdx + 1) * data.nItemsPerPage) - data.nItemsPerPage;
			nLength = ((data.nSlideIdx + 1) * data.nItemsPerPage);
			
			//load preview images
			for(nIdx; nIdx < nLength; nIdx++){
				var $frame = $container.find('.imageslide-photoitem:eq(' + nIdx + ')');
				if($frame.find('img').length == 0){
					if(typeof data.aSlideContent[nIdx] != "undefined"){
						$frame.sqboxImageSlide('loadImage', $frame, data.aSlideContent[nIdx].sPreviewImage);
					}
				}
			}
			
			if(data.bAjaxGet){
				//select first or 'jumpto' image
				$container
				.find('.imageslide-photoitem:eq(' + nJumpTo + ')')
				.trigger('click');
			}
		},
		selectItem: function(){
			var globaldata = $(this).closest('.imageslide-slidecontainer').data('sqboxImageSlide');
			var itemdata = $(this).data('sqboxImageItem');
			var oDetails = globaldata.aSlideContent[itemdata.nIdx];
			var $item = $(this);

			$('.imageslide-photoitem')
			.css({borderColor: globaldata.sBorderColor});
			
			$(this)
			.css({borderColor: globaldata.sHighlightColor});
			
			if(globaldata.bExpandClickedPics){
				//this expands the image in the browser
				
			}else{
				//this view is used in the details view of graphics gallery
				if(globaldata.sModifyButtonsId.length > 0){
					$('#' + globaldata.sModifyButtonsId)
					.hide();
					
					if(oDetails.sEditRights == 'true'){
						$('#' + globaldata.sModifyButtonsId)
						.find('.EditButton')
						.unbind('click')
						.click(function(event){
							location.href = 'edit.cfm?MenuID=' + globaldata.nMenuId + '&CategoryID=' + globaldata.nCategoryId + '&ID=' + oDetails.sId + '&edit=true';			
							event.preventDefault();
							event.stopPropagation();
						})
						.show();
					}else{
						$('#' + globaldata.sModifyButtonsId)
						.find('.EditButton')
						.unbind('click')
						.hide();
					}
					
					if(oDetails.sDeleteRights == 'true'){
						$('#' + globaldata.sModifyButtonsId)
						.find('.DeleteButton')
						.unbind('click')
						.click(function(event){
							$item.sqboxImageSlide('removeItem', $item);
							event.preventDefault();
							event.stopPropagation();
						})
						.show();
					}else{
						$('#' + globaldata.sModifyButtonsId)
						.find('.DeleteButton')
						.unbind('click')
						.hide();
					}
					
					if(oDetails.sEditRights != 'true' && oDetails.sDeleteRights != 'true'){
						$('#' + globaldata.sModifyButtonsId).addClass('NoRights');
					}else{
						$('#' + globaldata.sModifyButtonsId).removeClass('NoRights');
					}
				}
				
				$(this)
				.closest('.imageslide-slidecontainer')
				.sqboxImageSlide('loadImage', $('#' + globaldata.sFullImageId), oDetails.sFullImage, globaldata.sModifyButtonsId)
				
				//for link on full image
				$('#' + globaldata.sFullImageId).attr('href', oDetails.sFullImage);
				$('#' + globaldata.sFullImageId).attr('data-itemid', oDetails.sId);

				//set item details data
				oDetails.sTitle.length > 0 ? $('#DataTitle').show().find('.ImageData').html(oDetails.sTitle) : $('#DataTitle').hide();
				oDetails.sFileName.length > 0 ? $('#DataFileName').show().find('.ImageData').html(oDetails.sFileName) : $('#DataFileName').hide();
				oDetails.sCaption.length > 0 ? $('#DataCaption').show().find('.ImageData').html(oDetails.sCaption) : $('#DataCaption').hide();
				oDetails.sDescription.length > 0 ? $('#DataDescription').show().find('.ImageData').html(oDetails.sDescription) : $('#DataDescription').hide();
				oDetails.sFilesize.length > 0 ? $('#DataFileSize').show().find('.ImageData').html(oDetails.sFilesize) : $('#DataFileSize').hide();
				oDetails.sAuthor.length > 0 ? $('#DataAuthor').show().find('.ImageData').html(oDetails.sAuthor) : $('#DataAuthor').hide();
				oDetails.sCopyright.length > 0 ? $('#DataCopyright').show().find('.ImageData').html(oDetails.sCopyright) : $('#DataCopyright').hide();
				oDetails.sCopyrightNotice.length > 0 ? $('#DataCopyrightNotice').show().find('.ImageData').html(oDetails.sCopyrightNotice) : $('#DataCopyrightNotice').hide();
				oDetails.sInstructions.length > 0 ? $('#DataInstructions').show().find('.ImageData').html(oDetails.sInstructions) : $('#DataInstructions').hide();
				oDetails.sName.length > 0 ? $('#DataName').show().find('.ImageData').html(oDetails.sName) : $('#DataName').hide();
				oDetails.sDateCreated.length > 0 ? $('#DataDateCreated').show().find('.ImageData').html(oDetails.sDateCreated) : $('#DataDateCreated').hide();
				oDetails.sDateTaken.length > 0 ? $('#DataDateTaken').show().find('.ImageData').html(oDetails.sDateTaken) : $('#DataDateTaken').hide();
				
				if(globaldata.sTagsId != ''){
					try{// tags might be turned off so this function doesn't always exist
						$.ic.oTagQuickForm.resetTagDisplay(oDetails.sId);
					}catch(err){}
				}
				
				//ratings have been linked to this instance
				if(globaldata.sRatingsId != ''){
					$('#' + globaldata.sRatingsId).hide();
					RATINGS.setNewRating(globaldata.sRatingsId, globaldata.nMenuId, globaldata.nCategoryId, globaldata.aSlideContent[itemdata.nIdx].sId, true);
				}
				if(globaldata.bShowComments){
					COMMENTS.setCurrentItem(globaldata.nMenuId, globaldata.nCategoryId, globaldata.aSlideContent[itemdata.nIdx].sId);
					COMMENTS.loadComments();
				}
			}
		},
		slide: function(bNext){
			var $container,
				data,
				nIdx,
				nLength;
			
			if(typeof $(this).data('sqboxImageSlide') != 'undefined'){
				$container = $(this);
			}else{
				$container = $(this).closest('.imageslide-slidecontainer');
			}	
			
			data = $container.data('sqboxImageSlide');
			
			if((!bNext && data.nSlideIdx > 0) || (bNext && (data.nSlideIdx < (data.aSlideContent.length / data.nItemsPerPage) - 1))){
				if(!bNext && data.nSlideIdx > 0){
					data.nSlideIdx--;
				}else{
					data.nSlideIdx++;
				}

				nIdx = ((data.nSlideIdx + 1) * data.nItemsPerPage) - data.nItemsPerPage;
				nLength = ((data.nSlideIdx + 1) * data.nItemsPerPage);
				
				for(nIdx; nIdx < nLength; nIdx++){
					var $frame = $container.find('.imageslide-photoitem:eq(' + nIdx + ')');
					if($frame.find('img').length == 0){
						if(typeof data.aSlideContent[nIdx] != "undefined"){
							$frame.sqboxImageSlide('loadImage', $frame, data.aSlideContent[nIdx].sPreviewImage, '');
						}
					}
				}
								
				$container.find('.imageslide-tablecontainer')
				.stop(true, true)
				.animate({
					left: bNext ? '-=' + data.nSlideInnerWidth : '+=' + data.nSlideInnerWidth	 
				}, 600, 'easeInOutQuart');
			}
			
			$container.sqboxImageSlide('configureNav');
		},
		configureNav: function(){
			var $container = $(this),
				data = $(this).data('sqboxImageSlide');
			
			$container
			.find('.imageslide-slidenavleft')
			.css({
				backgroundImage: "url('" + data.sImageRoot + "/buttons/default/previousrecord.gif')",
				opacity: '1',
				cursor: 'pointer'
			});
			
			$container
			.find('.imageslide-slidenavright')
			.css({
				backgroundImage: "url('" + data.sImageRoot + "/buttons/default/nextrecord.gif')",
				opacity: '1',
				cursor: 'pointer'
			});
			
			if(data.nSlideIdx == 0){
				$container
				.find('.imageslide-slidenavleft')
				.css({
					backgroundImage: "url('" + data.sImageRoot + "/buttons/default/previousrecord_disabled.gif')",
					opacity: '0.2',
					cursor: 'default'
				});
			}
			
			if(data.nSlideIdx >= ((data.aSlideContent.length / data.nItemsPerPage) - 1)){
				$container
				.find('.imageslide-slidenavright')
				.css({
					backgroundImage: "url('" + data.sImageRoot + "/buttons/default/nextrecord_disabled.gif')",
					opacity: '0.2',
					cursor: 'default'
				});
			}
		},
		loadImage: function($o, src, sHoverButtonsId){
			var img = new Image();
			
			$('#NoImageFound').remove();
			
			$o
			.empty();
			//.addClass('loading');
			
			$(img)
			.load(function(){
				var $this = $(this);
				
				$(this).hide();
				
				$o
				.removeClass('loading')
				.append(this);
				
				//seems to be a confict with the plugin load() and this one so we run it on a time out and clear the bind
				setTimeout(function(){
					$this
					.unbind('load')
					.cjObjectScaler({
						destElem: $this.parent().hasClass('imageslide-photoitem') ? $this.parent() : $this.parent().parent(),
						method: $this.parent().hasClass('imageslide-photoitem') ? "fill" : "fit",
						fade: 100
					});
					
					if(sHoverButtonsId && sHoverButtonsId.length > 0){
						$this
						//.addClass('imageslide-fullimage')
						.parent()
						.unbind('hover');
						
						if(!$('#' + sHoverButtonsId).hasClass('NoRights')){
							$('#' + sHoverButtonsId).show();
						}
					}
				}, 50);
				
			})
			.error(function(){
				if(sHoverButtonsId && sHoverButtonsId.length > 0){
					//image load error. If a full image in graphics gallery details, show text and hover icons
					if($('#NoImageFound').length == 0)
						$o.before('<div class="info" id="NoImageFound" style="margin-top: 30px; width: 100%;font-weight:bold;font-size:15pt" align="center">Image not found</div>');
					if(!$('#' + sHoverButtonsId).hasClass('NoRights')){						
						$('#' + sHoverButtonsId).show();
					}
				}
			})
			.attr('src', src)
			.attr('border', '0');
		},
		removeItem: function($item){
			var $container = $item.closest('.imageslide-slidecontainer');
			var data = $item.closest('.imageslide-slidecontainer').data('sqboxImageSlide');
			var oDetails = data.aSlideContent[$item.data('sqboxImageItem').nIdx];
			
			if(confirm("Are you sure you want to delete this image?")){
				$.ic.ajaxSpinner.show();
				$.ajax({
					type: 'POST',
					url: RATINGS.sWebRoot + '/Includes/ajax/image_slide_ajax.cfm',
					data: {Action: 'delete',
						   MenuId: data.nMenuId,
						   CategoryId: data.nCategoryId,
						   ItemId: oDetails.sId},
					success: function($data){
						$data = $($data);
						if($data.find('success').text() == 'true'){
							if(data.aSlideContent.length > 1){
								if(($item.data('sqboxImageItem').nIdx + 1) != data.aSlideContent.length){
									//jump to next slide if not at end
									data.nJumpToId = data.aSlideContent[$item.data('sqboxImageItem').nIdx + 1].sId;
								}else if($item.data('sqboxImageItem').nIdx != 0){
									//jump to previous slide (deleting from end of slide show)
									data.nJumpToId = data.aSlideContent[$item.data('sqboxImageItem').nIdx - 1].sId;
								}
							}
							
							//redraw the slide (will repopulate via ajax)
							$container.sqboxImageSlide('draw');
						}else{
							$container.sqboxImageSlide('statusUpdate', $data.find('error').text(), true);
						}
						$.ic.ajaxSpinner.hide();
					}
				});
			}
		},
		statusUpdate: function(sMessage, bError){
			alert(sMessage);
		}
	};
		
	$.fn.sqboxImageSlide = function(method){
		if(methods[method]){
			return methods[method].apply(this, Array.prototype.slice.call( arguments, 1 ));
		}else if( typeof method === 'object' || ! method){
			return methods.init.apply(this, arguments);
		}else{
			$.error( 'Method ' +  method + ' does not exist on jQuery.sqboxImageSlide' );
		}
	};
})( jQuery );
