(function($){

	$.fn.clikPopup = function(options){
	
		options = $.extend({
						animSpeed: 500,
						bgID: 'popupBG',
						imgDspId: 'imageDsp',
						bgOpacity: 0.8,
						//loadingIcon: null,
						zIndex: 100,
						cycle: true,
						loadingIcon: '_graphics/loading.gif',
						//closeIcon:'_graphics/style85/close.gif',
						//nextIcon:'_graphics/style86/next.gif',
						//prevIcon:'_graphics/style86/prev.gif',
						//closeText:'close',
						controlsInside:true,//next and previous controls inside the popup box.
						keyboardCtrl:true,
						nextKey:39,
						prevKey:37,
						closeKey:27,
						minHeight:250 //Same setting is used in the accompanying stylesheet, but required here for IE6.
						},options || {});
		
		var zIndex = options.zIndex;
		var puWidth = null;
		
		var running = false;
		
		//return $('a img',this).each(function(){
		//return $('a[class*="galleryPhotoLink"]',this).each(function(){
		return $(this).each(function(){
			/*var parent;
			if($(this).parent()[0].tagName !== 'A'){
				// Thumbnails are on and parent is a div. Link tag is above that.
				parent = $(this).parent().parent();
			}
			else{
				parent = $(this).parent();
			}*/
			//parent
			
			$(this)
			.unbind('click')
			.click(
			function(e){
				var id = null;
				if(($(this).attr('href')).match('.*photos_id=(.+)$')){
					id = ($(this).attr('href')).match('.*photos_id=(.+)$')[1];
				}
				else if(($(this).attr('href')).match('^photo_(.+).html$')){
					id = ($(this).attr('href')).match('^photo_(.+).html$')[1];
				}
				//showImage($('img',$(this)).attr('id'));
				
				if(id){
					showImage(id);
					return false;
				}
			});
		});
		
		function hideImage(){
			$('h3.imageCaption').slideUp(options.animSpeed);
			//$('div#imageDetails').slideUp(options.animSpeed,function(){
			if($.browser.msie && $.browser.version < 7){$('div#'+options.imgDspId).animate({height:options.minHeight},'fast');}
			$('div#imageDetailsContainer').slideUp(options.animSpeed,function(){
				$('div#image>img').fadeOut(options.animSpeed);
				$('div#'+options.imgDspId).animate({width:puWidth},options.animSpeed).animShowHide(0,-100,options.animSpeed,1);
				$('div#'+options.bgID).animShowHide(0,-100,options.animSpeed,1);
				$('div#mainDsp').animShowHide(0,-100,options.animSpeed,1,removeHtml);
			});
			return false;
		}
		
		function removeHtml(){
			$(options.html).remove();
			$(document).unbind('keydown.clikPopup');
		}
		
		function showImage(id){
			bg = $('div#'+options.bgID);
			if(bg.size() != 0){
				bg.animShowHide(options.bgOpacity,zIndex-10,options.animSpeed);
				$('div#mainDsp').animShowHide(100,zIndex-10,options.animSpeed);
			}
			
			img = $('div#'+options.imgDspId);
			
			if(img.size() == 0){
				addHtml();
				img = $('div#'+options.imgDspId);				
			}
			
			setTopDistance();
			changeImage(id,img);
			return false;
		}
		
		var marginTop;
		
		function setTopDistance(){
			scrollPos = $(window).scrollTop();			 
			if(scrollPos > 0){
				if(!marginTop){
					marginTop = parseInt(img.css('margin-top'));
				}
				//puH = $('div#'+options.imgDspId).height();
				//winH = $(window).height();
				//if(!(puH + marginTop > winH)){
					img.css({'margin-top':marginTop + scrollPos});
				//}
			}
		}
		
		function resetRunning(){
			running = false;
		}
		
		function changeImage(id,imgElement){
			running = true;
			setTimeout(resetRunning,1000); //Unset variable in case image doesn't load.
			if(puWidth == null){
				puWidth = $('div#'+options.imgDspId).width();
			}
			
			$('div#loadingImage').show();			
			$('div#image>img',imgElement).hide();
						
			//if($('div#imageDetails',imgElement).is(':visible')){
			if($('div#imageDetailsContainer',imgElement).is(':visible')){
				$('h3.imageCaption',imgElement).slideUp(options.animSpeed);
				//$('div#imageDetails',imgElement).slideUp(options.animSpeed,function(){				
				if($.browser.msie && $.browser.version < 7){imgElement.animate({height:options.minHeight},'fast');}
				$('div#imageDetailsContainer',imgElement).slideUp(options.animSpeed,function(){
					loadImage(id,imgElement);
				});
			}
			else{
				loadImage(id,imgElement);
			}			
		}
		
		function loadImage(id,imgElement){
			$('div#image>img',imgElement).attr({
				'src':'',
				'alt':''
			});
			
			var imgPreLoad = new Image()
			imgPreLoad.onload = function(){
				
				imgWidth = imgPreLoad.width;
				imgHeight = imgPreLoad.height;
				/*$('div#image>img',imgElement).attr({
					'src':photos[id].src,
					'alt':photos[id].caption
				});*/
				//$('div#image>img',imgElement).fadeIn();
				
				//$(imgElement).animate({width:imgWidth},function(){
				imgPadding = parseInt($('div#image').css('padding-left')) + parseInt($('div#image').css('padding-right'));
				imgBorder = parseInt($('div#image img').css('border-left-width')) || 0 + parseInt($('div#image img').css('border-right-width')) || 0;
				tmpW = (options.detailsWFull?imgWidth+options.detailsWFull:imgWidth)+imgPadding+imgBorder;
				$(imgElement).animate({width:tmpW},options.animSpeed,function(){
					
					$('div#image',imgElement).width(imgWidth);
					$('div#image>img',imgElement)
					.attr({
						'src':photos[id].src,
						'alt':photos[id].caption
					})
					.fadeIn(options.animSpeed,function(){
							if($.browser.msie){
								$('div#image>img').css({'filter':'none'});
								$('div#image>img').parents().css({'filter':'none'});
							}
						}
					);
					
					$('div#loadingImage').hide();
					
					options.detailsW?
						//$('div#imageDetails',imgElement).css({width:options.detailsW}):
						$('div#imageDetailsContainer',imgElement).width(options.detailsW):
						//$('div#imageDetails',imgElement).css({width:imgWidth,'margin-left':options.prevW,'margin-right':options.nextW});
						//$('div#imageDetails',imgElement).css({width:imgWidth});
						$('div#imageDetailsContainer',imgElement).css({
																	width:imgWidth,
																	'margin-left':parseInt($('div#image').css('padding-left')),
																	'margin-right':parseInt($('div#image').css('padding-right'))
																	});
					
					photos[id].caption===''?
						$('h3.imageCaption',imgElement).hide():
						$('h3.imageCaption',imgElement)
							.html(photos[id].caption)
							.show()
							.css({'margin-left':options.prevW,'margin-right':options.nextW});
					$('div#imageDetails',imgElement).html(fnGetImageDetails(id));
					toggleAddToCartConfirm();
					//$('div#imageDetails',imgElement).slideDown(options.animSpeed,function(){running = false;});
					$('div#imageDetailsContainer',imgElement)
						.slideDown(options.animSpeed,function(){
							// Browser detection for IE6 to get the controls to appear at the bottom of the box.
							if($.browser.msie && $.browser.version < 7){imgElement.height(imgElement.height());}
							running = false;
							// Call this function incase the popup window is exceeds the window edges.
							backgroundResize();
						});
					
				});
								
				/*$('div#imageDetails',imgElement).css({width:imgWidth});
				$('div#loadingImage').hide();
									photos[id].caption===''?$('h3.imageCaption',imgElement).hide():$('h3.imageCaption',imgElement).html(photos[id].caption).show();
				$('div#imageDetails',imgElement).html(fnGetImageDetails(id)).slideDown();*/
				imgPreLoad.onload = function(){};
				$('#mainDsp').unbind('click');
			}
			
			imgPreLoad.src = photos[id].src;
			toggleActiveControls(id);
			
			imgElement.animShowHide(100,zIndex,options.animSpeed);
			
			/*if($(imgElement).is(':not(:visible)')){
				imgElement.animShowHide(100,zIndex,options.animSpeed);
			}*/
			
			setEvents(id);
		}
		
		function setEvents(id){
			
			//$(window).scroll(setTopDistance);
			
			//$('#closeButton, #mainDsp, #'+options.bgID)
			$('#closeButton, #'+options.bgID+', #mainDsp')
			.unbind('click')
			.click(function(e){
				hideImage();
				return false;
			});
			
			/* Need to set the image close click event on the background to 
			be turned off when the mouse moves into the image display box. */
			$('#'+options.imgDspId).hover(
				function(e){
					$('#mainDsp').unbind('click');
				},
				function(e){
					if((e.target.type && (e.target.type).indexOf('select') == -1) || !e.target.type){
						$('#mainDsp').click(function(){
							hideImage();
							return false;
						});
					}
				}
			);
			
			/*$('#'+options.imgDspId)
			.unbind('click')
			.click(function(e){
				return false;
			});*/
			
			$('a#nextPU, div#image')
			.unbind()
			.click(function(e){
				e.shiftKey?prev(id):next(id);
				return false;
			});
			
			$('a#prevPU')
			.unbind()
			.click(function(e){
				prev(id);
				return false;
			});
			
			if(options.keyboardCtrl){
				$(document)
				.unbind('keydown.clikPopup')
				.bind('keydown.clikPopup',function(e){
					if(e.keyCode == options.nextKey){
						next(id);
					}
					if(e.keyCode == options.prevKey){
						prev(id);
					}
					if(e.keyCode == options.closeKey){
						hideImage();
					}			
				});
			}			
		}
		
		function addHtml(){
			
			options.html = $(imageHtml()).appendTo($('body'));
			
			$(options.html,'div#mainDsp')
			.css({
				'z-index':zIndex-10,
				left:0,
				top:0,
				position:'absolute',
				width: '100%'
			});
			
			options.html.appendTo($('body'));
			
			/*windowWidth = $(window).width();
			windowHeight = $(window).height();*/			
			docW = $(document).width();
			docH = $(document).height();
			
			$('div#'+options.bgID)
			.css({
				//width:windowWidth,
				//height:windowHeight,
				width:docW,
				height:docH,
				//width:'100%',
				//height:'100%', // IE6 doesn't like 100%...
				'z-index':zIndex-10,
				position:'absolute',
				opacity:0,
				top:0,
				left:0})
			.animate({opacity:options.bgOpacity});

			$('div#loadingImage')
			.css({
				'z-index':zIndex-10,
				'text-align':'center'//,
				//width:'100%'
			});
			
			/* This styling needs to be applied before appending to the page
			$('div#mainDsp')
			.css({
				'z-index':zIndex-10,
				left:0,
				top:0,
				position:'absolute',
				width: '100%'
			});*/
			
			$('h3.imageCaption').hide();
			//$('div#imageDetails').hide();
			$('div#imageDetailsContainer').hide();
			
			$('div#'+options.imgDspId)
			.css({
				//overflow:'hidden',
				'z-index':zIndex//,
				//position:'relative'
			}).hide().fadeIn();
			
			/*if($('div#imageDetails').css('float') != 'none'){
				options.detailsW = $('div#imageDetails').width();
				options.detailsWFull = $('div#imageDetails').csswidth();
			}*/
			if($('div#imageDetailsContainer').css('float') != 'none'){
				options.detailsW = $('div#imageDetailsContainer').width();
				options.detailsWFull = $('div#imageDetailsContainer').outerWidth(1);
			}
			
			//options.prevW = $('#prevPU').width();
			//options.nextW = $('#nextPU').width();
			
			$('#prevPU, #nextPU').css({'z-index':zIndex+10});
			
			$(window)
			.resize(backgroundResize);
		}
		
		function backgroundResize(){
			$('div#'+options.bgID)
			.css({
				width:$(document).width(),
				height:$(document).height()});
		}
		
		function imageHtml(){
			var html = '';
			html += '<div id="'+options.bgID+'"></div>';
			//html += '<div id="loadingImage"><img src="'+options.loadingIcon+'" alt="loading"></div>';
			html += '<div id="mainDsp">';
			//html += '<div><a id="prevPU">&lt;</a><a id="nextPU">&gt;</a></div>';
			//html += '<div id="'+options.imgDspId+'_outer" class="imageDsp">';
			//html += '<a id="prevPU">&lt;</a><a id="nextPU">&gt;</a>';
			imgDsp = '<div id="'+options.imgDspId+'" class="imageDsp">';
			//nav = '<a id="prevPU"><img src="'+options.prevIcon+'" alt="previous"></a><a id="nextPU"><img src="'+options.nextIcon+'" alt="next"></a>';
			nav = '<a id="prevPU">&nbsp;</a><a id="nextPU">&nbsp;</a>';
			if(options.controlsInside){
				html += imgDsp;
				html += nav;
			}
			else{
				html += nav;
				html += imgDsp;
			}
			//html += '<div><a id="prevPU">&lt;</a><a id="nextPU">&gt;</a><div style="clear:both;line-height:1px;">&nbsp;</div></div>';
			html += '<div id="loadingImage">';
			options.loadingIcon?
				html += '<img src="'+options.loadingIcon+'" alt="loading">':
				html += '&nbsp;';	
			html += '</div>';
			html += '<div id="image"><img src="" alt=""></div>';
			html += '<h3 class="imageCaption"></h3>';
			html += '<div id="imageDetailsContainer"><div id="imageDetails"></div></div>';
			//html += '<div id="imageDetails"></div>';
			//html += '<a id="closeButton">'+options.closeTxt+'</a>';
			//html += '<a id="closeButton"><img src="'+options.closeIcon+'" alt="close"></a>';
			html += '<a id="closeButton">&nbsp;</a>';
			html += '<div class="clearing">&nbsp;</div>';
			html += '</div>';
			//html += '</div>';
			html += '</div>';
			return html
		}
		
		/*function centreElement(element){
			y = ($(window).height() - $(element).height())*options.yFrac;
			x = ($(window).width() - $(element).width())*options.xFrac;
			element.animate({top:y,left:x},300,'swing');
		}*/
		
		function next(currId){
			if(!running){
				//running = true;
				galleryPhotoIDList = galleries[photos[currId].galleries_id].photoIDs;
				nextId = getNextId(currId,galleryPhotoIDList);
				if(options.cycle){
					changeImage(nextId,$('div#imageDsp'));
				}
				else if(!options.cycle && ($.inArray(parseInt(nextId),galleryPhotoIDList))>($.inArray(parseInt(currId),galleryPhotoIDList))){
					changeImage(nextId,$('div#imageDsp'));
				}
				//running = false;
			}			
			return false;
		}
		
		function prev(currId){
			if(!running){
				//running = true;
				galleryPhotoIDList = galleries[photos[currId].galleries_id].photoIDs;
				nextId = getNextId(currId,galleryPhotoIDList,1);
				if(options.cycle){
					changeImage(nextId,$('div#imageDsp'));
				}
				else if(!options.cycle && ($.inArray(parseInt(nextId),galleryPhotoIDList))<($.inArray(parseInt(currId),galleryPhotoIDList))){
					changeImage(nextId,$('div#imageDsp'));
				}
				//running = false;
			}
			return false;
		}
		
		function toggleActiveControls(id){
			if(!options.cycle){
				galleryPhotoIDList = galleries[photos[id].galleries_id].photoIDs;
				nextId = parseInt(getNextId(id,galleryPhotoIDList));
				prevId = parseInt(getNextId(id,galleryPhotoIDList,1));
				i = $.inArray(parseInt(id),galleryPhotoIDList);
				$.inArray(nextId,galleryPhotoIDList)<i?$('#nextPU').addClass('deactivated'):$('#nextPU').removeClass('deactivated');
				$.inArray(prevId,galleryPhotoIDList)>i?$('#prevPU').addClass('deactivated'):$('#prevPU').removeClass('deactivated');
			}
		}
	}
	
	$.fn.animShowHide = function(opacity,z,speed,hide,callback){
		if(hide){
			return this.animate(
							{opacity:opacity},
							speed,
							'linear',
							function(){
								$(this).css({'z-index':z});
								if(callback){callback.call();}
							}
							);
		}
		else{
			return this.animate(
							{opacity:opacity},
							speed,
							'linear',
							function(){
								if(callback){callback.call();}
							}
							).css({'z-index':z});
		}
		
	}
	
})(jQuery);
