dB.image = {

	init: function() {
		$("a[href*='i']").each(function() {
			if (this.getAttribute('href').match(/i\d+$/)) {
				$(this).unbind('click').click(dB.image.showImageViewerOverlayWindow);
			}
		});
	},

	getBestInstance: function(width, jqImage) {
		if (jqImage.length > 0) {
			var numInstances = jqImage.find('imageinstance').length;
			if (numInstances > 0) {
				var best = jqImage.find('imageinstance').get(0);
				if (numInstances > 1) {
					for (var ctr = 1; ctr < numInstances; ctr ++) {
						if (parseInt(jqImage.find('imageinstance').get(ctr).getAttribute('width')) >= width) {
							best = jqImage.find('imageinstance').get(ctr);
						}
					}
				}
				return best;
			}
		}
		return null;
	},
	getImage: function(width, caption, jqImage) {
		var best = dB.image.getBestInstance(width, jqImage);
		if (best != null) {
			var w = parseInt(best.getAttribute('width')); var h = parseInt(best.getAttribute('height'));
			if (w > width) {
				h = h * (width / w);
				w = width;
			} // scale image down to requested size if necessary
			if (h > (width * 1.5)) {
				w = (width * w * 1.5) / h;
				h = width * 1.5;
			} // further scaling for tall narrow images
			w = Math.round(w);
			h = Math.round(h);
			return '<img src="' + best.getAttribute('src') + '" alt="' + caption + '" width="' + w + '" height="' + h + '">';
		}
		return null;
	},

	showImageViewerOverlayWindow: function() {
		var match = this.getAttribute('href').match(/(i\d+)$/);
		if (match && match[1]) {
			if (dB.image.imageViewer == null) {
//				$('body, html').css({'height':'100%', 'width':'100%'});
				$('html').css({'overflow':'hidden'});
				$('body').append('<div id="imageViewerOverlay"></div><div id="imageViewerOverlayWindow">Please wait...</div>');
				if ($.browser.msie && $.browser.version < 7) {
					// IE6 issues...
					$('#imageViewerOverlay').css({'position':'absolute', 'height': $(document).height() + 'px', 'width': $(document).width() + 'px'});
					$('#imageViewerOverlayWindow').css({'position':'absolute', 'marginTop': parseInt($(document).scrollTop() - $('#imageViewerOverlayWindow').outerHeight() / 2) + 'px' });
				}
				dB.image.imageViewer = {'currentId':match[1], 'images':new Array()};
				$('#imageViewerOverlay').click(dB.image.removeImageViewerOverlayWindow);
				$(document).bind("keydown", dB.image.imageViewerOverlayWindowKeyboardCapture);
				$(window).bind("resize", function() { dB.image.retargetImageViewerOverlayWindow(0); });
				$.post(dB.indexURL, {'id': dB.image.imageViewer.currentId, 'action': 'getImageViewerXML'}, dB.image.refreshImageViewerOverlayWindow);
				$('#imageViewerOverlayWindow').show();
			}
			return false;
		}
		return true;
	},
	removeImageViewerOverlayWindow: function() {
		$("#imageViewerOverlayWindow").fadeOut("500",function() {
			$('#imageViewerOverlayWindow').find('a').unbind();
			$('#imageViewerOverlay').unbind();
			$(document).unbind("keydown");
			$(window).unbind("resize");
			$('#imageViewerOverlayWindow,#imageViewerOverlay').remove();
//			$('body, html').css({'height':'auto', 'width':'auto'});
			if ($.browser.msie && $.browser.version < 7) {
				// IE6 issues...
				$('html').css({'overflow':''});
			} else if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
				// Chrome issues...
				$('html').css({'overflow':'scroll'});
			} else {
				$('html').css({'overflow':'auto'});
			}
			dB.image.imageViewer = null;
		});
	},
	refreshImageViewerOverlayWindow: function(xml) {
		if ($('imageviewer', xml).length) {
			$('imageviewer image', xml).each(function() {
				var jqInstances = $(this).find('imageinstance');
				if (jqInstances.length > 0) {
					dB.image.imageViewer.images[dB.image.imageViewer.images.length] = {
						'id':this.getAttribute('id'),
						'caption':this.getAttribute('caption'),
						'width':parseInt(jqInstances.get(0).getAttribute('width')),
						'height':parseInt(jqInstances.get(0).getAttribute('height')),
						'filesize':parseInt(jqInstances.get(0).getAttribute('filesize')),
						'src':$(this).find('imageinstance').get(0).getAttribute('src')
					};
				} else {
					dB.image.imageViewer.images[dB.image.imageViewer.images.length] = {
						'id':this.getAttribute('id'),
						'caption':this.getAttribute('caption'),
						'width':500,
						'height':300,
						'filesize':0,
						'src':''
					};
				}
			});
			for (var imgCtr = 0; imgCtr < dB.image.imageViewer.images.length; imgCtr++) {
				if (dB.image.imageViewer.images[imgCtr].id == dB.image.imageViewer.currentId) {
					dB.image.imageViewer.currentImageNum = imgCtr;
				}
			}
			dB.image.retargetImageViewerOverlayWindow(0);
		}
	},
	retargetImageViewerOverlayWindow: function(increment) {
		// shorthand to make code easier to work with
		var iV = dB.image.imageViewer;

		if (iV.images.length > 0) {
			// move forward or back in the image group
			iV.currentImageNum = ((iV.currentImageNum + increment + iV.images.length) % iV.images.length);

			// get viewable size of page
			iV.pageWidth = uF.getPageWidth();
			iV.pageHeight = uF.getPageHeight();

			// figure out size of browser window, and thus max allowable size for image
			iV.maxOverlayWidth = iV.pageWidth - 40;
			iV.maxOverlayHeight = iV.pageHeight - 40;
			iV.maxImageWidth = iV.maxOverlayWidth - 40;
			iV.maxImageHeight = iV.maxOverlayHeight - 80;

			// figure out what the dimensions of the full-size image are
			iV.fullImageWidth = iV.images[iV.currentImageNum].width;
			iV.fullImageHeight = iV.images[iV.currentImageNum].height;
			iV.imageWidth = iV.images[iV.currentImageNum].width;
			iV.imageHeight = iV.images[iV.currentImageNum].height;

			// scale the image to fit the max allowable size
			if (iV.imageWidth > iV.maxImageWidth) {
				iV.imageHeight = iV.imageHeight * (iV.maxImageWidth / iV.imageWidth);
				iV.imageWidth = iV.maxImageWidth;
			}
			if (iV.imageHeight > iV.maxImageHeight) {
				iV.imageWidth = iV.imageWidth * (iV.maxImageHeight / iV.imageHeight);
				iV.imageHeight = iV.maxImageHeight;
			}
			iV.scalingFactor = iV.fullImageWidth / iV.imageWidth;
			iV.imageWidth = Math.round(iV.imageWidth);
			iV.imageHeight = Math.round(iV.imageHeight);

			// size the window with appropriate margin
			iV.width = iV.imageWidth + 40;
			iV.height = iV.imageHeight + 80;

			// figure out the zoom height and width
			if ((iV.fullImageWidth > iV.imageWidth) && (iV.imageWidth < iV.maxImageWidth)) {
				iV.zoomWidth = (iV.fullImageWidth < iV.maxImageWidth) ? iV.fullImageWidth + 40 : iV.maxOverlayWidth;
			} else {
				iV.zoomWidth = iV.width;
			}
			if ((iV.fullImageHeight > iV.imageHeight) && (iV.imageHeight < iV.maxImageHeight)) {
				iV.zoomHeight = (iV.fullImageHeight < iV.maxImageHeight) ? iV.fullImageHeight + 80 : iV.maxOverlayHeight;
			} else {
				iV.zoomHeight = iV.height;
			}

			// setup the output
			var imgTag = '<a id="imageViewerTargetImageWrapper"><img id="imageViewerTargetImage" src="' + iV.images[iV.currentImageNum].src + '" alt="' + iV.images[iV.currentImageNum].caption + '" width="' + iV.imageWidth + '" height="' + iV.imageHeight + '"></a>';
			var controlLinks = '<div id="imageViewerControlLinks">';
			if (iV.images.length > 1) {
				controlLinks += '<a id="retargetImageViewerToPreviousLink">&lt;&lt;</a>';
				controlLinks += (iV.currentImageNum + 1) + '/' + iV.images.length;
				controlLinks += '<a id="retargetImageViewerToNextLink">&gt;&gt;</a>';
			}
			controlLinks += '<div id="imageViewerActionLinks">';
			controlLinks += '<a id="editImageViewerLink">edit</a>';
			controlLinks += '<a id="deleteImageViewerLink">delete</a>';
			controlLinks += '<a id="closeImageViewerLink">close</a>';
			controlLinks += '</div></div>';

			// get rid of old stuff
			$('#imageViewerOverlayWindow').find('a').unbind().end().empty();

			// output the new stuff
			$('#imageViewerOverlayWindow').append(imgTag);
			$('#imageViewerOverlayWindow').append('<div id="imageViewerCaption">' + iV.images[iV.currentImageNum].caption + '</div>')
			$('#imageViewerOverlayWindow').append(controlLinks);

			// adjust size
			$('#imageViewerOverlayWindow').css({'width': iV.width + 'px', 'height': iV.height + 'px'});
			$('#imageViewerCaption, #imageViewerControlLinks').css({'width': parseInt(iV.width - 36) + 'px'});

			// determine size modifiers (basically accounting for border thickness)
			iV.widthModifier = $('#imageViewerOverlayWindow').outerWidth() - iV.width;
			iV.heightModifier = $('#imageViewerOverlayWindow').outerHeight() - iV.height;

			// adjust position
			$('#imageViewerOverlayWindow').css({'marginLeft': parseInt((iV.width + iV.widthModifier) / -2) + 'px'});
			if ($.browser.msie && $.browser.version < 7) {
				// IE6 can't handle fixed overlay window
				$('#imageViewerOverlayWindow').css({'marginTop': parseInt($(document).scrollTop() - ((iV.height + iV.heightModifier) / 2)) + 'px' });
			} else {
				$('#imageViewerOverlayWindow').css({'marginTop': parseInt((iV.height + iV.heightModifier) / -2) + 'px'});
			}

			// setup event listeners
			$('#retargetImageViewerToPreviousLink').click(function() { dB.image.retargetImageViewerOverlayWindow(-1); });
			$('#retargetImageViewerToNextLink').click(function() { dB.image.retargetImageViewerOverlayWindow(1); });
			$('#editImageViewerLink').click(dB.image.modifyCaption);
			$('#deleteImageViewerLink').click(dB.image.confirmDelete);
			$('#closeImageViewerLink').click(dB.image.removeImageViewerOverlayWindow);
			$('#imageViewerTargetImageWrapper').click(dB.image.imageViewerOverlayWindowImageClickCallback);

		}
		return false;
	},
	imageViewerOverlayWindowKeyboardCapture: function(key) {
		switch (key.which) {
			case 27: // esc
				dB.image.removeImageViewerOverlayWindow();
				break;
			case 188: // <
				if (dB.image.imageViewer.images.length > 1)
					dB.image.retargetImageViewerOverlayWindow(-1);
				break;
			case 190: // >
				if (dB.image.imageViewer.images.length > 1)
					dB.image.retargetImageViewerOverlayWindow(1);
				break;
			case 68: // d
				dB.image.confirmDelete();
				break;
			case 69: // e
				dB.image.modifyCaption();
				break;
			default:
		}
	},
	imageViewerOverlayWindowImageClickCallback: function() {
		// shorthand to make code easier to work with
		var iV = dB.image.imageViewer;

		if (this.scrollable) {
			if (this.frozen) {
				var w = iV.width + 'px';
				var h = iV.height + 'px';
				var ml = parseInt((iV.width + iV.widthModifier) / -2) + 'px';
				var mt = parseInt((iV.height + iV.heightModifier) / -2) + 'px';
				if ($.browser.msie && $.browser.version < 7) {
					mt = parseInt($(document).scrollTop() - ((iV.height + iV.heightModifier) / 2)) + 'px';
				}
				$("#imageViewerOverlayWindow").animate({'width':w, 'height':h, 'marginLeft':ml, 'marginTop':mt}, "600",'linear',function(){
					$('#imageViewerTargetImageWrapper').removeClass('scrollable').css('background', '');
				});
				$('#imageViewerCaption, #imageViewerControlLinks').animate({'width': parseInt(iV.width - 36) + 'px'}, "600");
				$(this).animate({'width': iV.imageWidth + 'px','height': iV.imageHeight + 'px'}, "600");
				this.scrollable = false;
				this.frozen = false;
			} else {
				$(this).unbind('mousemove');
				this.frozen = true;
			}
		} else {
			$(this).addClass('scrollable').css('background', 'url(' + $(this).find('img').attr('src') + ')').css('backgroundRepeat','no-repeat');
			var w = iV.zoomWidth + 'px';
			var h = iV.zoomHeight + 'px';
			var ml = parseInt((iV.zoomWidth + iV.widthModifier) / -2) + 'px';
			var mt = parseInt((iV.zoomHeight + iV.heightModifier) / -2) + 'px';
			if ($.browser.msie && $.browser.version < 7) {
				mt = parseInt($(document).scrollTop() - ((iV.zoomHeight + iV.heightModifier) / 2)) + 'px';
			}
			$("#imageViewerOverlayWindow").animate({'width':w, 'height':h, 'marginLeft':ml, 'marginTop':mt}, "600");
			$('#imageViewerCaption, #imageViewerControlLinks').animate({'width': parseInt(iV.zoomWidth - 36) + 'px'}, "600");
			$(this).animate({'width': (iV.zoomWidth - 40) + 'px','height': (iV.zoomHeight - 80) + 'px'}, "600");
      	$(this).mousemove(dB.image.imageViewerOverlayWindowImageScrollCallback);
			this.scrollable = true;
			this.frozen = false;
		}
		return false;

	},
	imageViewerOverlayWindowImageScrollCallback: function(e) {
		// shorthand to make code easier to work with
		var iV = dB.image.imageViewer;

		var mX, mY;
		if (e.pageX && e.pageY) {
			mX = e.pageX;
			mY = e.pageY;
		} else if (e.clientX && e.clientY) {
			mX = e.clientX;
			mY = e.clientY;
		}
		var offset = $(this).offset();
		var xPos = mX - offset.left;
		var yPos = mY - offset.top;
// mX and mY are distances from the top left corner of the page
// xpos and ypos are distances from the top left corner of the imageLinkWrapper
		var img = $(this).find('img');
		var xScale = (iV.zoomWidth - iV.fullImageWidth - 40) / (iV.zoomWidth - 40);
		var yScale = (iV.zoomHeight - iV.fullImageHeight - 80) / (iV.zoomHeight - 80);
		this.style.backgroundPosition = (parseInt(xPos * xScale)) + 'px ' + (parseInt(yPos * yScale)) + 'px';
	},

	modifyCaption: function() {
		dB.overlay.submitCallback = function() {
			var input = $('#captionModificationCaption input').get(0); var caption = input.value ? input.value : '';
			return {'id': dB.image.imageViewer.images[dB.image.imageViewer.currentImageNum].id, 'action': 'modifyCaption', 'value': caption };
		};
		dB.overlay.successCallback = function(xml) {
			dB.image.imageViewer.images[dB.image.imageViewer.currentImageNum].caption = $('caption', xml).text();
			$('#imageViewerCaption').text($('caption', xml).text());

			$('#pageImageGroup_' + dB.page.id).find('a').each(function() {
				var match = this.getAttribute('href').match(/(i\d+)$/);
				if (match && match[1] && (match[1] == dB.image.imageViewer.images[dB.image.imageViewer.currentImageNum].id)) {
					$(this).find('div.tileText').text($('#imageViewerCaption').text());
					if ($(this).find('div.tileText').text().length == 0) {
						$(this).find('div.tileText').addClass('emptyTileText');
					} else {
						$(this).find('div.tileText').removeClass('emptyTileText');
					}
				}
			});
		};
		dB.overlay.removeCallback = function() {
			$(document).unbind("keydown");
			$(document).bind("keydown", dB.image.imageViewerOverlayWindowKeyboardCapture);
		};
		$(document).unbind("keydown");
		var content = '<div class="overlayContent"><div id="captionModificationCaption"><label>image caption:</label><input type="text"></div></div>';
		dB.overlay.showOverlayWindow('Modify Image Caption', content);
		dB.overlay.fixPosition();
		$('#captionModificationCaption input').val(dB.image.imageViewer.images[dB.image.imageViewer.currentImageNum].caption);
		setTimeout("$('#captionModificationCaption input').focus()", 200);
		$(document).bind("keydown", function(key) {
			switch (key.which) {
				case 27: // esc
					dB.overlay.removeOverlayWindow();
					break;
				case 13: // enter
					dB.overlay.submitOverlayWindow();
					break;
				default:
			}
		});
	},
	confirmDelete: function() {
		dB.overlay.submitCallback = function() {
			var checkbox = $('#deleteConfirmationConfirm input').get(0); var confirm = checkbox.checked ? 1 : 0;
			return {'id': dB.image.imageViewer.images[dB.image.imageViewer.currentImageNum].id, 'action': 'deleteImage', 'value': confirm };
		};
		dB.overlay.successCallback = function(xml) {
			$('#pageImageGroup_' + dB.page.id).find('a').each(function() {
				var match = this.getAttribute('href').match(/(i\d+)$/);
				if (match && match[1] && (match[1] == dB.image.imageViewer.images[dB.image.imageViewer.currentImageNum].id)) {
					$(this).parent().remove();
				}
			});
			dB.page.renumberImageGroupTiles();
			dB.image.imageViewer.removeImageViewer = true;
		};
		dB.overlay.removeCallback = function() {
			$(document).unbind("keydown");
			if (dB.image.imageViewer.removeImageViewer) {
				dB.image.removeImageViewerOverlayWindow();
			} else {
				$(document).bind("keydown", dB.image.imageViewerOverlayWindowKeyboardCapture);
			}
		};
		$(document).unbind("keydown");
		var content = '<div class="overlayContent"><div id="deleteConfirmationConfirm"><input type="checkbox" class="checkbox"><label>YES, I really want to do this!</label></div></div>';
		dB.overlay.showOverlayWindow('Confirm Image Delete', content);
		dB.overlay.fixPosition();
		$(document).bind("keydown", function(key) {
			switch (key.which) {
				case 27: // esc
					dB.overlay.removeOverlayWindow();
					break;
				case 13: // enter
					dB.overlay.submitOverlayWindow();
					break;
				case 78: // n
					$('#deleteConfirmationConfirm input').attr('checked','');
					break;
				case 89: // y
					$('#deleteConfirmationConfirm input').attr('checked','checked');
					break;
				default:
			}
		});
	}
};

$(dB.image.init);

