
function SPA()
{
}

SPA.ImageEntry = function(p_strID, p_strThumbSrc, p_iThumbWidth, p_iThumbHeight, p_strCaption)
{
	this.strID = p_strID;
	this.strThumbSrc = p_strThumbSrc;
	this.iThumbWidth = p_iThumbWidth;
	this.iThumbHeight = p_iThumbHeight;
	this.strCaption = p_strCaption;
}



SPA.ImageSpreader = function(
	p_strBorderColor,
	p_iBorderSize,
	p_iSpreaderSideLength,
	p_iMinImageSize,
	p_iStartingAngle,
	p_iMaxThumbsToShow
)
{
	var aimg = new Array();
	var span = document.createElement("span");
	span.style.position = "relative";
	this.element = span;
	
	this.AddImage = function(p_img)
	{
		var img = document.createElement("img");
		img.src = p_img.src;
		img.style.width = p_img.style.width;
		img.style.height = p_img.style.height;
		aimg[aimg.length] = img;
	}


	this.Dispose = function()
	{
		for (var i=span.childNodes.length - 1; i >= 0; i--)
		{
			span.removeChild(span.childNodes[i]);
		}
		for (var i=0; i < aimg.length; i++)
		{
			delete(aimg[i]);
		}		
	}
	
	this.LayoutImages = function()
	{
		var iThumbsToShow = Math.min(p_iMaxThumbsToShow, aimg.length);
		var flIconRatio = 1 / Math.pow(iThumbsToShow, (1/1.5));
		var iMaxImageSide = Math.max(p_iMinImageSize, Math.round(Math.sqrt(flIconRatio * Math.pow(p_iSpreaderSideLength,2)))) - (2*p_iBorderSize);
		var iIconSide = iMaxImageSide + (2*p_iBorderSize);
		var flMin = Math.pow(Math.E,0-(Math.pow(iThumbsToShow,2)/200));
		var pi = Math.PI;
		var flRad45 = pi/4;
		var flRad90 = pi/2;
		var flRad180 = pi;
		var flRad360 = pi*2;
		var flHalfCont = p_iSpreaderSideLength / 2;
		var flHalfIcon = iIconSide / 2;
		var flRegion = p_iSpreaderSideLength - iIconSide;
		var flStartRadAngle = ((p_iStartingAngle/180)*pi) % flRad360;
		var flInterval = flRad360 / iThumbsToShow;


		function ScaleImage(p_img)
		{
			var iWidth = p_img.style.pixelWidth;
			var iHeight = p_img.style.pixelHeight;
			var flScale = Math.min(1, Math.min((iMaxImageSide / iWidth), (iMaxImageSide / iHeight)));
			p_img.style.width = Math.round(iWidth * flScale);
			p_img.style.height = Math.round(iHeight * flScale);
		}

		function PlaceImage(p_img, p_iX, p_iY)
		{
			ScaleImage(p_img);
			p_img.style.position = "absolute";
			p_img.style.borderWidth = p_iBorderSize;
			p_img.style.borderColor = p_strBorderColor;
			p_img.style.borderStyle = "solid";

			var iLeft = p_iX - flHalfIcon + ((iIconSide - p_img.style.pixelWidth)*((flRegion == 0) ? .5 : (flRegion+(2*p_iX))/(2*flRegion)));
			var iTop = p_iY + flHalfIcon - ((iIconSide - p_img.style.pixelHeight)*((flRegion == 0) ? .5 : (flRegion-(2*p_iY))/(2*flRegion)));

			// convert cartesion coordiantes to DHTML coordinates
			iLeft += flHalfCont - p_iBorderSize;
			iTop = Math.abs(iTop - flHalfCont) - p_iBorderSize;

			p_img.style.top = iTop;
			p_img.style.left = iLeft;
			
			span.appendChild(p_img);
		}


		function PlaceImageAtAngle(p_img, p_flAngle)
		{
			var iYMult = (p_flAngle >= pi) ? -1 : 1;
			var iXMult = (((p_flAngle + flRad90) % flRad360) >= pi) ? -1 : 1;
			var flTemp = Math.abs(flRad90-(p_flAngle % flRad180));
			var fInv = flTemp < flRad45;
			p_flAngle = flRad45 - Math.abs(flTemp - flRad45);

			var flX = (flRegion / 2);
			var flY = flX * Math.tan(p_flAngle);

			var flD = ((flMin-1) * Math.random()) + 1;
			PlaceImage(p_img, (fInv ? flY : flX) * flD * iXMult, (fInv ? flX : flY) * flD * iYMult);
		}

		span.style.width = span.style.height = p_iSpreaderSideLength;
		for (var i=0; i < iThumbsToShow; i++)
		{
			PlaceImageAtAngle(aimg[i], (flStartRadAngle + (i*flInterval)) % flRad360);
		}

	}

}







SPA.Point = function(p_iX, p_iY)
{
	this.x = this.left = p_iX;
	this.y = this.top = p_iY;
}

SPA.FindOffsetInParentElement = function(p_element, p_ancestorElement)
{
	var iTop = 0;
	var iLeft = 0;
	var strLeft = "";
	while ((p_element != p_ancestorElement) && (p_ancestorElement.contains(p_element)))
	{
		iTop += p_element.offsetTop;
		iLeft += p_element.offsetLeft;
		strLeft += iLeft + " ";
		p_element = p_element.offsetParent;
	}
	return(new SPA.Point(iLeft, iTop));
}



SPA.ThumbnailPanel = function(
	p_iMaxImageSize,
	p_iSurroundWidth, p_strSurroundColor,
	p_iBorderWidth, p_strBorderColor,
	p_iHighlightWidth, p_strHighlightColor,
	p_strDropSrc, p_iDropWidth, p_iDropHeight,
	p_strTransPixelSrc,
	p_iMargin,
	p_iStartingTabIndex,
	p_strEmptyCaptionText,
	p_fncOnSelectionChanged,
	p_iMaxPhotoCaptionLength
	)
{
	function PanelClickHandler()
	{
		if (!event.ctrlKey && !event.shiftKey)
		{
			DeselectAll();
		}
	}
	
	function PanelKeyPressHandler()
	{
		if (blnIsCaptionEditing)
		{
			return;
		}
		var blnCancel = false;
		switch(event.keyCode)
		{
			case 27: // Esc
				DeselectAll();
				blnCancel = true;
				break;
			case 37: // left
				ThumbnailDragDropHandler(FindFirstSelected(), false, true);
				blnCancel = true;
				break;
			case 39: // right
				ThumbnailDragDropHandler(FindLastSelected(), true, true);
				blnCancel = true;
				break;
			case 46: // delete
				SPA_DeletePhotos();
				break;
		}
		if (blnCancel)
		{
			event.cancelBubble = true;
			event.returnValue = false;
		}
	}


	function FindFirstSelected()
	{
		var objLastThumbnail = null;
		var objThumbnail = null;
		for (var i=0; i < spanPanel.childNodes.length; i++)
		{
			objThumbnail = spanPanel.childNodes[i].objContainer;
			if (objThumbnail.GetSelected())
			{
				return(objLastThumbnail);
			}
			objLastThumbnail = objThumbnail;
		}
		return(null);
	}


	function FindLastSelected()
	{
		var objLastThumbnail = null;
		var objThumbnail = null;
		for (var i=spanPanel.childNodes.length-1; i >= 0; i--)
		{
			objThumbnail = spanPanel.childNodes[i].objContainer;
			if (objThumbnail.GetSelected())
			{
				return(objLastThumbnail);
			}
			objLastThumbnail = objThumbnail;
		}
		return(null);
	}


	var spanElement = document.createElement("span");

	var spanPanel = document.createElement("ol");
	spanPanel.style.position = "relative";	
	spanPanel.style.height = "100%";
	//spanPanel.style.overflow = "auto";
	spanPanel.style.paddingLeft = p_iMargin + p_iHighlightWidth;
	spanPanel.style.paddingRight = p_iMargin + p_iHighlightWidth;
	spanPanel.style.cursor = "default";
	//spanPanel.onclick = PanelClickHandler;
	Spa.Dom.Event.Set(spanPanel, "onclick", PanelClickHandler);
	Spa.Dom.Event.Set(spanPanel, "onkeydown", PanelKeyPressHandler);

	spanElement.appendChild(spanPanel);

	var ht_id_thumb = new Array();

	//this.element = spanPanel;
	this.element = spanElement;
	



	var objThumbRangeStart = null;
	var blnCtrl = false;
	var blnShift = false;
	var blnSelected = false;
	function ThumbnailMouseDownHandler(p_objThumbnail)
	{
		blnCtrl = event.ctrlKey;
		blnShift = event.shiftKey;
		blnSelected = p_objThumbnail.GetSelected();

		if (!blnCtrl && (!(!blnShift && blnSelected)))
		{
			DeselectAll();
		}
		
		if (!blnCtrl && !blnShift && !blnSelected)
		{
			p_objThumbnail.SetSelected(true);
		}
		
		if (blnShift && (!(blnCtrl && blnSelected)))
		{
			SelectRange(objThumbRangeStart, p_objThumbnail);
		}
		
		if (!blnCtrl && !blnShift)
		{
			objThumbRangeStart = p_objThumbnail;
		}
	}

	function ThumbnailClickHandler(p_objThumbnail, p_blnIsImageRegion)
	{
		event.cancelBubble = true;

		if (p_blnIsImageRegion)
		{
			if (!blnShift)
			{
				objThumbRangeStart = p_objThumbnail;
				if (blnCtrl)
				{
					p_objThumbnail.SetSelected(!blnSelected);
				}
				else if (blnSelected)
				{
					DeselectAll(p_objThumbnail);
					p_objThumbnail.SetSelected(true);
				}
			}
		}
	}

	function DeselectAll(p_objThumbnail)
	{
		var objThumbnail;
		for (var i=0; i < spanPanel.childNodes.length; i++)
		{
			objThumbnail = spanPanel.childNodes[i].objContainer;
			if (objThumbnail != p_objThumbnail)
			{
				objThumbnail.SetSelected(false);
			}
		}
	}

	function SelectRange(p_objThumbnailStart, p_objThumbnailFinish)
	{
		p_objThumbnailStart = p_objThumbnailStart ? p_objThumbnailStart : p_objThumbnailFinish;
		var objThumbnail;
		var blnInRange = false;
		for (var i=0; i < spanPanel.childNodes.length; i++)
		{
			objThumbnail = spanPanel.childNodes[i].objContainer;
			if (!blnInRange)
			{
				if (objThumbnail == p_objThumbnailFinish)
				{
					var temp = p_objThumbnailFinish;
					p_objThumbnailFinish = p_objThumbnailStart;
					p_objThumbnailStart = temp;
					blnInRange = true;
				}
				else if (objThumbnail == p_objThumbnailStart)
				{
					blnInRange = true;
				}
			}
			if (blnInRange)
			{
				objThumbnail.SetSelected(blnInRange);
			}
			if (objThumbnail == p_objThumbnailFinish)
			{
				blnInRange = false;
			}
		}
	}


	var objThumbDragging = null;
	var objDragImageRefPoint;
	var objDragImageMaxPoint;
	var objDraggingRegion;
	var iDraggingRegionSize = 100;
	function ThumbnailDragStartHandler(p_objThumbnail)
	{
		event.dataTransfer.effectAllowed = "move";
		objThumbDragging = p_objThumbnail;
		p_objThumbnail.SetSelected(true);
		objThumbRangeStart = p_objThumbnail;
		
		objDraggingRegion = new SPA.ImageSpreader(
			"#FFFFFF",
			1,
			iDraggingRegionSize,
			20,
			129,
			50
		);

		for (var i=0; i < spanPanel.childNodes.length; i++)
		{
			objThumbnail = spanPanel.childNodes[i].objContainer;
			if (objThumbnail.GetSelected())
			{
				objDraggingRegion.AddImage(objThumbnail.GetImageElement());
			}
		}
		
		objDraggingRegion.LayoutImages();
		
		objDraggingRegion.element.style.position = "absolute";
		objDraggingRegion.element.style.zIndex = 3;
		objDraggingRegion.element.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=65)";

		var objStartingPoint = SPA.FindOffsetInParentElement(event.srcElement, spanPanel);
		objDragImageRefPoint = new SPA.Point(
			objStartingPoint.left - Math.floor(iDraggingRegionSize / 2),
			objStartingPoint.top + 30
			);
		objDragImageMaxPoint = new SPA.Point(
			Math.max(spanPanel.clientWidth, spanPanel.scrollWidth) - iDraggingRegionSize,
			Math.max(spanPanel.clientHeight, spanPanel.scrollHeight) //- iDraggingRegionSize
		);
		
		ThumbnailDraggingHandler();
		spanPanel.appendChild(objDraggingRegion.element);	
	}

	function ThumbnailDraggingHandler(p_objThumbnail)
	{
		objDraggingRegion.element.style.left = Math.max(0, Math.min(objDragImageMaxPoint.left, objDragImageRefPoint.left + event.offsetX));
		objDraggingRegion.element.style.top = Math.max(0, Math.min(objDragImageMaxPoint.top, objDragImageRefPoint.top + event.offsetY));
	}

	function ThumbnailDragEndHandler(p_objThumbnail)
	{
		if (objThumbDragging)
		{
			objThumbDragging = null;
			spanPanel.removeChild(objDraggingRegion.element);
			objDraggingRegion.Dispose();
			spa_isAlbumModified=true;
		}
	}




	function ThumbnailDragEnterHandler(p_objThumbnail, p_blnIsRight)
	{
		if (objThumbDragging)
		{
			event.dataTransfer.dropEffect = "move";
			p_objThumbnail.SetInsertionPointVisibility(true, p_blnIsRight);
			event.returnValue = false;
		}
	}

	function ThumbnailDragOverHandler(p_objThumbnail, p_blnIsRight)
	{
		event.dataTransfer.dropEffect = "move";
		event.returnValue = false;
	}

	function ThumbnailDragLeaveHandler(p_objThumbnail, p_blnIsRight)
	{
		p_objThumbnail.SetInsertionPointVisibility(false, p_blnIsRight);
	}

	function ThumbnailDragDropHandler(p_objThumbnail, p_blnIsRight, p_blnScrollIntoView)
	{
		if (!p_objThumbnail)
		{
			return;
		}
		ThumbnailDragEndHandler(p_objThumbnail);
		ThumbnailDragLeaveHandler(p_objThumbnail, p_blnIsRight);

		var objThumbnail;
		var objThumbnailTarget = null;
		var iDropTargetLocation = -1;
		var aobjThumbSources = new Array();
		for (var i=0; i < spanPanel.childNodes.length; i++)
		{
			objThumbnail = spanPanel.childNodes[i].objContainer;
			if (p_objThumbnail == objThumbnail)
			{
				iDropTargetLocation = 0;
			}
			else if (iDropTargetLocation == 0)
			{
				iDropTargetLocation = 1;
			}
			if (objThumbnail.GetSelected())
			{
				aobjThumbSources[aobjThumbSources.length] = objThumbnail;
			}
			else
			{
				if (p_blnIsRight && (iDropTargetLocation <= 0))
				{
					objThumbnailTarget = objThumbnail;
				}
				else if (!p_blnIsRight && (iDropTargetLocation >= 0) && !objThumbnailTarget)
				{
					objThumbnailTarget = objThumbnail;
				}
			}
		}

		if (objThumbnailTarget)
		{
			var elementTarget = objThumbnailTarget.element;
			for (var i=0; i < aobjThumbSources.length; i++)
			{
				spanPanel.removeChild(aobjThumbSources[i].element);
				elementTarget.insertAdjacentElement(p_blnIsRight ? "afterEnd" : "beforeBegin", aobjThumbSources[i].element);
				if (p_blnScrollIntoView)
				{
					p_blnScrollIntoView = false;
					aobjThumbSources[i].element.focus();
				}
				elementTarget = p_blnIsRight ? aobjThumbSources[i].element : elementTarget;
			}
		}

	}


	var iPreEditScrollHeight;
	var objThumbEditing = null;
	var blnIsCaptionEditing = false;
	function ThumbnailCaptionStartEditHandler(p_objThumbnail, p_iHeightNeeded)
	{
		blnIsCaptionEditing = true;
		objThumbEditing = p_objThumbnail;
		objThumbEditing.element.style.zIndex = 2;
		iPreEditScrollHeight = spanPanel.scrollTop;
		var objThumbLocation = SPA.FindOffsetInParentElement(p_objThumbnail.element, spanPanel);
		var iTopNeeded = objThumbLocation.top + p_iHeightNeeded - spanPanel.clientHeight;
		if (iTopNeeded > iPreEditScrollHeight)
		{
			//spanPanel.scrollTop = Math.max(iPreEditScrollHeight, Math.min(iTopNeeded, objThumbLocation.top));
		}
	}

	function ThumbnailCaptionStopEditHandler()
	{
		blnIsCaptionEditing = false;
		objThumbEditing.element.style.zIndex = 1;
		//spanPanel.scrollTop = iPreEditScrollHeight;
		objThumbEditing = null;
	}


	this.GetCount = function()
	{
		return(spanPanel.childNodes.length);
	}


	this.GetThumbnailByIndex = function(p_iIndex)
	{
		var elementThumb = spanPanel.childNodes(p_iIndex);
		if (elementThumb)
		{
			return(elementThumb.objContainer);
		}
		else
		{
			return(null);
		}
	}


	this.GetThumbnailByID = function(p_id)
	{
		return(ht_id_thumb[p_id]);
	}


	this.RemoveThumbnail = function(p_id)
	{
		var objThumb = ht_id_thumb[p_id];
		if (objThumb)
		{
			if (objThumbRangeStart == objThumb)
			{
				if (spanPanel.childNodes.length > 0)
				{
					objThumbRangeStart = spanPanel.childNodes(0).objContainer;
				}
			}
			
			// the thumb is being removed, so remove it
			if (objThumb.GetSelected())
			{
				p_fncOnSelectionChanged(objThumb, false);
			}
			
			spanPanel.removeChild(ht_id_thumb[p_id].element);
			delete(ht_id_thumb[p_id]);
		}
	}



	this.AddThumbnail = function(p_id, p_strSrc, p_iWidth, p_iHeight, p_strCaption)
	{
		if (this.GetThumbnailByID(p_id))
		{
			return;
		}
		var objThumbnail = new SPA.Thumbnail(
			p_id,
			p_iMaxImageSize,
			p_iSurroundWidth, p_strSurroundColor,
			p_iBorderWidth, p_strBorderColor,
			p_iHighlightWidth, p_strHighlightColor,
			p_strDropSrc, p_iDropWidth, p_iDropHeight,
			p_strTransPixelSrc,
			p_iMargin,
			p_iStartingTabIndex,
			p_strEmptyCaptionText,
			p_strSrc, p_iWidth, p_iHeight, p_strCaption,
			p_iMaxPhotoCaptionLength,
			ThumbnailClickHandler, ThumbnailMouseDownHandler,
			ThumbnailDragStartHandler, ThumbnailDraggingHandler, ThumbnailDragEndHandler, 
			ThumbnailDragEnterHandler, ThumbnailDragOverHandler, ThumbnailDragLeaveHandler, ThumbnailDragDropHandler,
			ThumbnailCaptionStartEditHandler, ThumbnailCaptionStopEditHandler,
			p_fncOnSelectionChanged
			);
		Spa.Memory.CircularReference.Create(objThumbnail.element, "objContainer", objThumbnail);
		//objThumbnail.element.objContainer = objThumbnail;
		spanPanel.appendChild(objThumbnail.element);
		
		if (objThumbRangeStart == null)
		{
			objThumbRangeStart = objThumbnail;
		}
		
		ht_id_thumb[objThumbnail.id] = objThumbnail;
	}
}



SPA.Thumbnail = function(
	p_id,
	p_iMaxImageSize,
	p_iSurroundWidth, p_strSurroundColor,
	p_iBorderWidth, p_strBorderColor,
	p_iHighlightWidth, p_strHighlightColor,
	p_strDropSrc, p_iDropWidth, p_iDropHeight,
	p_strTransPixelSrc,
	p_iMargin,
	p_iStartingTabIndex,
	p_strEmptyCaptionText,
	p_strSrc, p_iWidth, p_iHeight, p_strCaption,
	p_iMaxPhotoCaptionLength,
	p_fncOnClick, p_fncOnMouseDown,
	p_fncOnDragStart, p_fncOnDragging, p_fncOnDragEnd,
	p_fncOnDragEnter, p_fncOnDragOver, p_fncOnDragLeave, p_fncOnDragDrop,
	p_fncOnCaptionStartEdit, p_fncOnCaptionStopEdit,
	p_fncOnSelectionChanged
	)
{
	this.id = p_id;
	var objThis = this;
	
	var iInnerSpanSize = p_iMaxImageSize + ((p_iSurroundWidth + p_iBorderWidth)* 2);
	var iOuterSpanSize = iInnerSpanSize + (p_iHighlightWidth * 2);
	var iThumbWidth = iOuterSpanSize;
	var blnIsSelected = false;

	var spanThumb = document.createElement("li");
	spanThumb.style.position = "relative";
	spanThumb.style.zIndex = 1;
	spanThumb.style.styleFloat = "left";	
	spanThumb.style.paddingLeft = p_iMargin;
	spanThumb.style.paddingRight = p_iMargin;
	spanThumb.style.marginTop = p_iMargin;
	spanThumb.style.paddingBottom = p_iMargin * 2;
	spanThumb.style.marginBottom = p_iMargin;
	spanThumb.style.width = iThumbWidth;
	spanThumb.style.fontStyle = "normal";
	spanThumb.style.fontVariant = "normal";
	spanThumb.style.fontWeight = "normal";
	spanThumb.strImageSrc = p_strSrc;
	spanThumb.style.cursor = "default";
	this.element = spanThumb;


	// DropRegion section start
	function CreateAndAddDropRegion(p_blnIsRight)
	{
		function Ret(p_fncReturn)
		{
			return(function(){p_fncReturn(objThis, p_blnIsRight);});
		}
	
		var iDropSpanWidth = (p_iMargin + p_iHighlightWidth) * 2;
		var objDropRegion = new SPA.DropRegion(
			iDropSpanWidth, iOuterSpanSize,
			p_strDropSrc, p_iDropWidth, p_iDropHeight,
			p_strTransPixelSrc,
			Ret(p_fncOnDragEnter), Ret(p_fncOnDragOver), Ret(p_fncOnDragLeave), Ret(p_fncOnDragDrop)
			);

		objDropRegion.element.style.position = "absolute";
		objDropRegion.element.style.left = p_iMargin + (p_blnIsRight ? iThumbWidth - p_iHighlightWidth : p_iHighlightWidth - iDropSpanWidth);
		objDropRegion.element.style.top = 0;
		objDropRegion.element.style.zIndex = 4;

		spanThumb.appendChild(objDropRegion.element);
		return(objDropRegion);
	}		

	var objLeftDropRegion = CreateAndAddDropRegion(false);
	var objRightDropRegion = CreateAndAddDropRegion(true);

	this.SetInsertionPointVisibility = function(p_blnVisible, p_blnIsRight)
	{
		var objDropRegion = p_blnIsRight ? objRightDropRegion : objLeftDropRegion;
		objDropRegion.SetInsertionPointVisibility(p_blnVisible);
	}
	// DropRegion section end


	// ImageRegion section start
	function ImageRegionKeyPressHandler()
	{
		var blnCancel = false;
		switch(event.keyCode)
		{
			case 10: // Enter with Ctrl-key
			case 13: // Enter
			case 32: // Space
				blnCancel = true;
				p_fncOnMouseDown(objThis);
				ImageRegionClickHandler();
				break;
		}
		if (blnCancel)
		{
			event.cancelBubble = true;
			event.returnValue = false;
		}
	}

	function EventRet(p_fncReturn)
	{
		return(function(){p_fncReturn(objThis);});
	}

	function ImageRegionClickHandler()
	{
		p_fncOnClick(objThis, true);
	}

	this.GetImageElement = function()
	{
		return(objImageRegion.GetImageElement());
	}

	this.SetSelected = function(p_blnIsSelected)
	{
		var blnCurrentSelectionState = this.GetSelected();
		objImageRegion.SetSelected(p_blnIsSelected);
		if (p_blnIsSelected != blnCurrentSelectionState)
		{
			if (p_fncOnSelectionChanged)
			{
				p_fncOnSelectionChanged(this, p_blnIsSelected);
			}
		}
	}

	this.GetSelected = function()
	{
		return(objImageRegion.GetSelected());
	}

	this.GetCaption = function()
	{
		return(objCaption.GetText());
	}

	var objImageRegion = new SPA.ImageRegion(
		p_strSrc, p_iWidth, p_iHeight,
		p_iMaxImageSize,
		p_iSurroundWidth, p_strSurroundColor,
		p_iBorderWidth, p_strBorderColor,
		p_iHighlightWidth, p_strHighlightColor,
		EventRet(p_fncOnDragStart), EventRet(p_fncOnDragging), EventRet(p_fncOnDragEnd),
		ImageRegionClickHandler, EventRet(p_fncOnMouseDown)
		);
	objImageRegion.element.tabIndex = 0;
	Spa.Dom.Event.Set(objImageRegion.element, "onkeypress", ImageRegionKeyPressHandler);



	spanThumb.appendChild(objImageRegion.element);
	// ImageRegion section end



	// caption section start
	var iPreEditScrollHeight;
	var captionElementOffSet = 7;

	this.Focus = function()
	{
		objCaption.Focus();
	}


	this.Blur = function()
	{
		objCaption.Blur();
	}

	function CaptionClickHandler()
	{
		p_fncOnClick(objThis, false);
	}

	function CaptionStartEditHandler(p_objCaption, p_iTextAreaHeight)
	{
		var objEditLocation = SPA.FindOffsetInParentElement(objCaption.element, spanThumb);
		var iHeightNeeded = objEditLocation.top + p_iTextAreaHeight;
		p_fncOnCaptionStartEdit(objThis, iHeightNeeded);
	}

	var objCaption = new SPA.Caption(
		iThumbWidth, p_iStartingTabIndex, p_strCaption, p_strEmptyCaptionText,
		p_iMaxPhotoCaptionLength,
		CaptionStartEditHandler, p_fncOnCaptionStopEdit,
		CaptionClickHandler,p_iHighlightWidth
		);

	objCaption.element.style.top = (p_iMaxImageSize + ((p_iSurroundWidth + p_iBorderWidth)* 2)) + captionElementOffSet;
	objCaption.element.style.marginTop = 1;

	spanThumb.appendChild(objCaption.element);
	// caption section end
}




SPA.DropRegion = function(
	p_iWidth, p_iHeight,
	p_strInsertionSrc, p_iInsertionWidth, p_iInsertionHeight,
	p_strTransPixelSrc,
	p_fncOnDragEnter, p_fncOnDragOver, p_fncOnDragLeave, p_fncOnDragDrop
	)
{
	var objThis = this;
	
	this.SetInsertionPointVisibility = function(p_blnVisible)
	{
		imgInsertionPoint.style.display = p_blnVisible ? "inline" : "none";
	}
	
	var spanDrop = document.createElement("span");
	spanDrop.style.position = "relative";
	spanDrop.style.width = p_iWidth;
	spanDrop.style.height = p_iHeight;
	
	var imgDropTarget = document.createElement("img");
	imgDropTarget.style.position = "absolute";
	imgDropTarget.style.top = 0;
	imgDropTarget.style.left = 0;
	imgDropTarget.src = p_strTransPixelSrc;
	imgDropTarget.style.width = p_iWidth;
	imgDropTarget.style.height = p_iHeight;
	Spa.Dom.Event.Set(imgDropTarget, "ondragenter", p_fncOnDragEnter);
	Spa.Dom.Event.Set(imgDropTarget, "ondragover", p_fncOnDragOver);
	Spa.Dom.Event.Set(imgDropTarget, "ondragleave", p_fncOnDragLeave);
	Spa.Dom.Event.Set(imgDropTarget, "ondrop", p_fncOnDragDrop);
	//imgDropTarget.ondragenter = p_fncOnDragEnter;
	//imgDropTarget.ondragover = p_fncOnDragOver;
	//imgDropTarget.ondragleave = p_fncOnDragLeave;
	//imgDropTarget.ondrop = p_fncOnDragDrop;

	var imgInsertionPoint = document.createElement("img");
	imgInsertionPoint.src = p_strInsertionSrc;
	imgInsertionPoint.style.position = "absolute";
	imgInsertionPoint.style.top = Math.floor((p_iHeight - p_iInsertionHeight) / 2);
	imgInsertionPoint.style.left = Math.floor((p_iWidth - p_iInsertionWidth) / 2);
	imgInsertionPoint.style.width = p_iInsertionWidth;
	imgInsertionPoint.style.height = p_iInsertionHeight;
	imgInsertionPoint.style.display = "none";

	spanDrop.appendChild(imgInsertionPoint);
	spanDrop.appendChild(imgDropTarget);
	
	this.element = spanDrop;
}




SPA.ImageRegion = function(
	p_strSrc, p_iWidth, p_iHeight,
	p_iMaxImageSize,
	p_iSurroundWidth, p_strSurroundColor,
	p_iBorderWidth, p_strBorderColor,
	p_iHighlightWidth, p_strHighlightColor,
	p_fncOnDragStart, p_fncOnDragging, p_fncOnDragEnd,
	p_fncOnClick, p_fncOnMouseDown
	)
{
	var objThis = this;
	var blnIsSelected = false;

	this.GetImageElement = function()
	{
		return(imgThumb);
	}

	this.SetSelected = function(p_blnIsSelected)
	{
		blnIsSelected = p_blnIsSelected;
		spanInnerImage.style.borderColor = blnIsSelected ? p_strHighlightColor : p_strBorderColor;		
	}

	this.GetSelected = function()
	{
		return(blnIsSelected);
	}
	
	
	var iInnerSpanSize = p_iMaxImageSize + ((p_iSurroundWidth + p_iBorderWidth)* 2);
	var iOuterSpanSize = iInnerSpanSize + (p_iHighlightWidth * 2);

	var spanOuterImage = document.createElement("span");
	spanOuterImage.style.position = "relative";
	spanOuterImage.style.width = iOuterSpanSize;
	spanOuterImage.style.height = iOuterSpanSize;

	var spanInnerImage = document.createElement("span");
	var iSpanInnerImageOffset = Math.floor((iOuterSpanSize - iInnerSpanSize) / 2 - p_iBorderWidth);
	spanInnerImage.style.position = "relative";
	spanInnerImage.style.display = "block";
	spanInnerImage.style.styleFloat = "left";
	spanInnerImage.style.left = iSpanInnerImageOffset;
	spanInnerImage.style.top = iSpanInnerImageOffset;
	spanInnerImage.style.width = iInnerSpanSize;
	spanInnerImage.style.height = iInnerSpanSize;
	spanInnerImage.style.backgroundColor = p_strSurroundColor;
	spanInnerImage.style.border = p_iBorderWidth + " solid " + p_strBorderColor;
	spanInnerImage.style.cursor = "hand";
	//spanInnerImage.onclick = p_fncOnClick;
	//spanInnerImage.onmousedown = p_fncOnMouseDown;
	Spa.Dom.Event.Set(spanInnerImage, "onclick", p_fncOnClick);
	Spa.Dom.Event.Set(spanInnerImage, "onmousedown", p_fncOnMouseDown);
	spanOuterImage.appendChild(spanInnerImage);

	var flScale = Math.min(1, Math.min((p_iMaxImageSize / p_iWidth), (p_iMaxImageSize / p_iHeight)));
	var imgThumb = document.createElement("img");
	imgThumb.style.position = "relative";
	imgThumb.src = p_strSrc;
	imgThumb.style.width = Math.round(p_iWidth * flScale);
	imgThumb.style.height = Math.round(p_iHeight * flScale);
	imgThumb.style.left = Math.floor((iInnerSpanSize - imgThumb.style.pixelWidth) / 2);
	imgThumb.style.top = Math.floor((iInnerSpanSize - imgThumb.style.pixelHeight) / 2);
	spanInnerImage.appendChild(imgThumb);

	//spanOuterImage.ondragstart = p_fncOnDragStart;
	//spanOuterImage.ondragend = p_fncOnDragEnd;
	//spanOuterImage.ondrag = p_fncOnDragging;
	Spa.Dom.Event.Set(spanOuterImage, "ondragstart", p_fncOnDragStart);
	Spa.Dom.Event.Set(spanOuterImage, "ondragend", p_fncOnDragEnd);
	Spa.Dom.Event.Set(spanOuterImage, "ondrag", p_fncOnDragging);

	this.element = spanOuterImage;
}
	


SPA.Caption = function(
	p_iWidth, p_iTabIndex, p_strText, p_strEmptyText,
	p_iMaxPhotoCaptionLength,
	p_fncOnStartEdit, p_fncOnStopEdit,
	p_fncOnClick, p_iHighlightWidth

)
{
	var objThis = this;
	this.strText = NormalizeActualText(p_strText);

	function StartEditMode()
	{
		spanLabel.style.visibility = "hidden";
		textArea.style.display = "block";
		textArea.focus();
		textArea.select();
		//p_fncOnStartEdit(objThis, textArea.clientHeight);
	}

	function StopEditMode()
	{
		objThis.strText = textArea.value;
		textArea.value = objThis.strText = NormalizeActualText(objThis.strText);
		
		var strDisplayText = objThis.strText ? objThis.strText : p_strEmptyText;
		strDisplayText = NormalizeDisplayText(strDisplayText);
		center.innerText = strDisplayText;
		textArea.style.display = "none";
		spanLabel.style.visibility = "visible";
		//p_fncOnStopEdit();
	}

	function NormalizeActualText(p_strText)
	{
		if (SPA.Caption.reWhiteSpace.test(objThis.strText))
		{
			// only whitesapce
			return("");
		}
		else
		{
			return(p_strText);
		}
	}

	function NormalizeDisplayText(p_strText)
	{
		var iFirstNewLine = p_strText.indexOf("\n");
		var iFirstCarriageReturn = p_strText.indexOf("\r\n");
		var iMin = Math.min(iFirstNewLine, iFirstCarriageReturn);
		var iMax = Math.max(iFirstNewLine, iFirstCarriageReturn);
		if (iMax != -1)
		{
			var iIndex = (iMin == -1) ? iMax : iMin;
			return(p_strText.substring(0, iIndex) + "...");
		}
		else
		{
			return(p_strText);
		}
	}

	function TextAreaKeyDownHandler()
	{
		switch(event.keyCode)
		{
			case 13: // V
				// If the user hits enter, then editing stops
				textArea.blur();
				break;
		}
	}


	function TextAreaKeyPressHandler()
	{
		// do not allow the key pressif it will make the caption
		// too long
		if (textArea.value.length >= p_iMaxPhotoCaptionLength)
		{
			event.returnValue = false;
		}
		spa_isAlbumModified = true;
	}
	
	
	function PasteHandler()
	{
		var strPreviousValue = textArea.value;
		function RevertPaste()
		{
			if (textArea.value.length >= p_iMaxPhotoCaptionLength)
			{
				textArea.value = strPreviousValue;				
			}
			else
			{
			    spa_isAlbumModified = true;
			}
		}
		window.setTimeout(RevertPaste, 1);
	}

	

	this.Focus = function()
	{
		spanLabel.focus();
	}


	this.Blur = function()
	{
		textArea.blur();
	}


	this.GetText = function()
	{
		return(objThis.strText);
	}


	function HeightMetricResizeHandler()
	{
		spanLabel.style.height = spanHeightMetric.clientHeight;
	}

	var spanCaption = document.createElement("span");
	spanCaption.style.position = "absolute";
	spanCaption.style.left = p_iHighlightWidth;
	spanCaption.style.width = p_iWidth;
	spanCaption.style.paddingBottom = 2;
	//spanCaption.onclick = p_fncOnClick;
	Spa.Dom.Event.Set(spanCaption, "onclick", p_fncOnClick);

	var spanLabel = document.createElement("span");
	spanLabel.style.position = "relative";
	spanLabel.style.display = "block";
	spanLabel.style.width = p_iWidth - 8;
	spanLabel.style.left = 4;
	spanLabel.style.top = 1;
	spanLabel.style.overflow = "hidden";
	spanLabel.style.textOverflow = "ellipsis";
	spanLabel.tabIndex = p_iTabIndex;
	//spanLabel.onfocus = StartEditMode;
	Spa.Dom.Event.Set(spanLabel, "onfocus", StartEditMode);
	spanLabel.style.fontStyle = "normal";
	spanLabel.style.fontVariant = "normal";
	spanLabel.style.fontWeight = "normal";
	//spanLabel.style.fontSize = "smaller";
	//spanLabel.style.fontFamily = "Arial";
	spanLabel.style.cursor = "text";

	var center = document.createElement("center");
	center.style.textOverflow = "ellipsis";
	center.innerText = NormalizeDisplayText(this.strText ? this.strText : p_strEmptyText);

	var nobr = document.createElement("nobr");
	nobr.appendChild(center);
	
	spanLabel.appendChild(nobr);

	spanCaption.appendChild(spanLabel);

	var spanHeightMetric = document.createElement("span");
	spanHeightMetric.style.position = "absolute";
	spanHeightMetric.style.visibility = "hidden";
	spanHeightMetric.style.width = spanLabel.style.pixelWidth;
	spanHeightMetric.style.left = spanLabel.style.pixelLeft;
	spanHeightMetric.innerHTML = "&nbsp;";
	//spanHeightMetric.onresize = HeightMetricResizeHandler;
	Spa.Dom.Event.Set(spanHeightMetric, "onresize", HeightMetricResizeHandler);
	spanCaption.appendChild(spanHeightMetric);

	
	var textArea = document.createElement("textarea");
	textArea.style.position = "absolute";	
	textArea.style.marginBottom = 20;
	textArea.style.width = p_iWidth;    
	textArea.style.left = 0;
	textArea.style.top = 1;	
	textArea.tabIndex = p_iTabIndex;
	textArea.style.border = "1 solid #000000";
	textArea.style.padding = "0 3 0 3";
	textArea.style.display = "none";
	textArea.style.overflow = "hidden";
	textArea.style.fontStyle = "normal";
	textArea.style.fontVariant = "normal";
	textArea.style.fontWeight = "normal";
	textArea.style.fontSize = "100%";
	textArea.style.wordWrap = "break-word";
	//textArea.style.fontFamily = "Arial";
	textArea.value = this.strText;
	//textArea.onblur = StopEditMode;
	//textArea.onkeydown = TextAreaKeyDownHandler;
	Spa.Dom.Event.Set(textArea, "onblur", StopEditMode);
	Spa.Dom.Event.Set(textArea, "onkeydown", TextAreaKeyDownHandler);
	Spa.Dom.Event.Set(textArea, "onkeypress", TextAreaKeyPressHandler);
	Spa.Dom.Event.Set(textArea, "onpaste", PasteHandler);
	
	spanCaption.appendChild(textArea);
	
	this.element = spanCaption;
	this.fncOnStartEdit = null;
	this.fncOnStopEdit = null;
}
SPA.Caption.reWhiteSpace = /^\s*$/;


var spa_objPanel;

var spa_objImageEntries = new Array();

var spa_strOriginalPhotoSequence;

var spa_iThumbsSelected = 0;

function SPA_RunEditor(p_oResources, ctrlDetailsPane, ctrlAddComment, ctrlComments, addButton, delButton)
{
    var objImageEntry;
    
    window.attachEvent("onbeforeunload", albumEditCheck);
    for (var i=0; i < spa_aaImageData.length; i++)
    {
	    objImageEntry = new SPA.ImageEntry(
		    spa_aaImageData[i][0],
		    spa_aaImageData[i][1],
		    spa_aaImageData[i][2],
		    spa_aaImageData[i][3],
		    spa_aaImageData[i][4]
		    );

	    spa_objImageEntries[spa_objImageEntries.length] = objImageEntry;
    }
		
    spa_textAlbumName1.value = spa_textAlbumName2.value = spa_strAlbumTitle;
    spa_textAlbumName1.maxLength = spa_textAlbumName2.maxLength = spa_iMaxAlbumTitleLength;    
    addButton.Enable();	    
    delButton.Disable();
    
    /*
     *  FUNCTION:  albumEditCheck
     *
     *  DESCRIPTION:
     *
     */
    function albumEditCheck()
    {        
        if (spa_isAlbumModified)
        {
            event.returnValue = _gblDirtyString;
        }
    }

	
    function CreateCommentHandler(p_oComment)
    {
        function CommentCreated(p_oComment)
        {
            if (p_oComment)
            {
                ctrlComments.AddComment(p_oComment);
                ctrlAddComment.Clear();
            }
            ctrlAddComment.SetEnabled(true);
        }

        if (oSingleThumbSelected)
        {
            ctrlAddComment.SetEnabled(false);
            Msn.Spaces.Photos.OM.AddImageComment(
                spa_strAlbumID,
                oSingleThumbSelected.id,
                p_oComment,
                p_oResources.properties.strUserDateFormat,
                p_oResources.properties.strUserTimeFormat,
                p_oResources.properties.iTimeZone,
                CommentCreated
                );
        }
    }

    function CreateCommentCancelHandler()
    {
        ctrlAddComment.SetExpanded(false);
    }

    var isAddCommentExpanded = false;
    var isAllCommentsExpanded = false;

    function AddCommentsExpanded(p_blnExpanded)
    {
        if (p_blnExpanded)
        {
            isAddCommentExpanded = true;
            ctrlComments.SetExpanded(true);
        }
        else
        {
            isAddCommentExpanded = false;
            if(!isAllCommentsExpanded)
            {
                DetailsExpansionHandler(false);
                ctrlDetailsPane.HideCloseAll(); 
            }
        }
    }
    
    function ctrlCommentsExpanded(p_blnExpanded)
    {
        if (p_blnExpanded)
        {
            isAllCommentsExpanded = true;		    
        }
        else
        {
            isAllCommentsExpanded = false;
            if(!isAddCommentExpanded)
            {
                DetailsExpansionHandler(false);
                ctrlDetailsPane.HideCloseAll(); 
            }
        }
    }

    
    function RemoveCommentHandler(p_oComment)
    {
        function CommentRemoved(p_blnSuccess)
        {
            if (p_blnSuccess)
            {
                UpdateDetails();
            }
        }

        if (oSingleThumbSelected)
        {
             var dataArray = new SimpleDialogData(null, 
                                                  null, 
                                                  null, 
                                                  null, 
                                                  p_oResources.strings["deleteblogitem.comment.text"]  + "<p>" + Spaces.Utility.GetString(Spaces.Common.Strings,"global_cannotbeundone"), 
                                                  Spaces.Utility.GetString(Spaces.Common.Strings,"global_delete"), 
                                                  Spaces.Utility.GetString(Spaces.Common.Strings,"global_cancel"));
            
            function cb()
            {
                Msn.Spaces.Photos.OM.DeleteImageComment(
                    oSingleThumbSelected.id,
                    p_oComment.strID,
                    CommentRemoved
                    );
            }	        
            Spaces.PopOvers.SimplePopOver(null, 
                                          p_oResources.strings["deleteblogitem.comment.title"], 
                                          dataArray, 
                                          null, 
                                          cb,
                                          event.srcElement);
        }
    }

    if (ctrlAddComment)
    {
        ctrlAddComment.onPublish.attach(CreateCommentHandler);
        ctrlAddComment.onCancel.attach(CreateCommentCancelHandler);
        ctrlAddComment.onExpand.attach(AddCommentsExpanded);
    }
        
    if (ctrlComments)
    {
        ctrlComments.onExpand.attach(ctrlCommentsExpanded);
	    ctrlComments.onRemove.attach(RemoveCommentHandler);
    }


    var oSingleThumbSelected = null;

    function SelectionChanged(p_objThumb, p_blnSelected)
    {
	    oSingleThumbSelected = null;
	    spa_iThumbsSelected += (p_blnSelected ? 1 : -1);
	    if (spa_iThumbsSelected == 0)
	    {		    
		    delButton.Disable();
	    }
	    else if (spa_iThumbsSelected == 1)
	    {		 
		    delButton.Enable();
		    oSingleThumbSelected = GetFirstSelectedThumb();
	    }
		
	    UpdateDetails();
    }
	
	
    function UpdateDetails()
    {
	    if (oSingleThumbSelected)
	    {
		    ctrlDetailsPane.SetEnabled(true);
		    if (ctrlAddComment)
		    {
			    ctrlAddComment.SetEnabled(true);
		    }
		    Msn.Spaces.Photos.OM.GetImageComments(
			    spa_strAlbumID,
			    oSingleThumbSelected.id,
			    p_oResources.properties.strUserDateFormat,
			    p_oResources.properties.strUserTimeFormat,
			    p_oResources.properties.iTimeZone,
			    ctrlComments.SetComments
			    );
	    }
	    else
	    {
		    ctrlDetailsPane.SetEnabled(false);
		    if (ctrlAddComment)
		    {
			    ctrlAddComment.Clear();
			    ctrlAddComment.SetEnabled(false);
		    }
		    ctrlComments.SetComments(Array.Empty);
	    }
    }
	
    var tdThumbnailPanel = document.getElementById("tdThumbnailPanel");
    var tdDetailsPaneCollapsed = document.getElementById("tdDetailsPaneCollapsed");
    var tdDetailsPaneExanded = document.getElementById("tdDetailsPaneExanded");
	
    function DetailsExpansionHandler(p_blnExpanded)
    {
        spa_isAlbumModified = false;
	    if (blnDetailsExpanded == p_blnExpanded)
	    {
		    return;
	    }
	    blnDetailsExpanded = p_blnExpanded;
	    if (p_blnExpanded)
	    {
		    tdDetailsPaneCollapsed.removeChild(ctrlDetailsPane.element);
		    tdDetailsPaneExanded.appendChild(ctrlDetailsPane.element);
		    ctrlDetailsPane.element.style.width ="96%";
		    tdThumbnailPanel.width = "70%";
		    tdDetailsPaneExanded.width = "30%";
	    }
	    else
	    {                       
		    tdDetailsPaneExanded.removeChild(ctrlDetailsPane.element);
		    tdDetailsPaneCollapsed.appendChild(ctrlDetailsPane.element);
		    tdThumbnailPanel.width = "99%";
		    tdDetailsPaneExanded.width = "1%";
	    }
    }
    var blnDetailsExpanded = false;

	
    ctrlDetailsPane.onExpansion.attach(DetailsExpansionHandler);

    spa_objPanel = new SPA.ThumbnailPanel(
	    96,
	    6, "#FFFFFF", 
	    2, "#CCCCCC", 
	    5, "#6699CC",
	    PathUtility.MapPath(PathUtility.MapPathType.Image, PathUtility.MapPathServerType.SpacesWeb, 'Parts/PhotoAlbum', 'ibeam.gif'), 8, 109,
	    PathUtility.MapPath(PathUtility.MapPathType.Image, PathUtility.MapPathServerType.SpacesWeb, 'Parts/PhotoAlbum', '1x1.gif'),
	    9,
	    null,
	    spa_strEnterCaptionText,
	    SelectionChanged,
	    spa_iMaxPhotoCaptionLength
	    );

    spa_objPanel.element.attachEvent("onresize", SetControls2Visibility);
    window.attachEvent("onresize", SetControls2Visibility);

    spa_objPanel.element.style.width = "100%";
    spa_objPanel.element.style.height = "100%";
    document.all.spa_spanThumbnailPanel.appendChild(spa_objPanel.element);

    for (var i=0; i < spa_objImageEntries.length; i++)
    {
	    AddThumbnailToPanel(spa_objImageEntries[i]);
    }
    SetControls2Visibility();

    Spa.Dom.ExecuteWhenLayoutComplete(tblControls2, SetControls2Visibility);
    UpdateDetails();    
}

function SetControls2Visibility()
{
	var pntOffset1 = SPA.FindOffsetInParentElement(tblControls1, document.body);
	var pntOffset2 = SPA.FindOffsetInParentElement(tblControls2, document.body);
	var blnShowControls2 = (pntOffset2.top - pntOffset1.top > document.body.clientHeight);
	tblControls2.style.visibility = blnShowControls2 ? "visible" : "hidden";
}


function AddThumbnailToPanel(p_objThumbData)
{
	spa_objPanel.AddThumbnail(
		p_objThumbData.strID,
		p_objThumbData.strThumbSrc,
		p_objThumbData.iThumbWidth,
		p_objThumbData.iThumbHeight,
		p_objThumbData.strCaption
		);
}

function GetFirstSelectedThumb()
{
	for (var i = spa_objPanel.GetCount() - 1; i >=0; i--)
	{
		var thumbData = spa_objPanel.GetThumbnailByIndex(i);
		if (thumbData.GetSelected())
		{
			return(thumbData);
		}
	}
	return(null);
}


function SPA_DeletePhotos()
{
	if (spa_iThumbsSelected <= 0)
	{
		return;
	}
	function PadButtonText(p_str)
	{
		return("   " + p_str + "   ");
	}
	
	var dataArray = new SimpleDialogData(spa_strRemovePhotosConfirmation, null, null, null, null, Spaces.Utility.GetString(Spaces.Common.Strings,"global_delete"), Spaces.Utility.GetString(Spaces.Common.Strings,"global_cancel"));
			
	function cb()
	{
		for (var i = spa_objPanel.GetCount() - 1; i >=0; i--)
		{
			var thumbData = spa_objPanel.GetThumbnailByIndex(i);
			if (thumbData.GetSelected())
			{
				spa_objPanel.RemoveThumbnail(thumbData.id);
			}
		}
		spa_isAlbumModified=true;
	}

	Spaces.PopOvers.SimplePopOver("Confirmation", spa_strDeleteSelected, dataArray, null, cb);
    //prevent navigation.	
	event.returnValue = false;
}



var spa_blnPhotosAdded = false;
function SPA_AddPhotosFromSPUD(returnObj)
{
	function AddThumbnail(p_objAddedImage)
	{
		// create Image entry and add to spa_objImageEntries
		var objImageEntry = new SPA.ImageEntry(
			p_objAddedImage.GUID,
			p_objAddedImage.ThumbSource,
			p_objAddedImage.ThumbWidth,
			p_objAddedImage.ThumbHeight,
			p_objAddedImage.Caption
			);
		spa_objImageEntries[spa_objImageEntries.length] = objImageEntry;

		// add thumbnail to panel
		AddThumbnailToPanel(objImageEntry);
	}

	if(returnObj)
	{
		if (returnObj.length > 0 )
		{
			for (i=0; i < returnObj.length; i++)
			{
				spa_blnPhotosAdded = true;
				AddThumbnail(returnObj[i]);
			}
		}
	}
}

function SPA_AddPhotos()
{
	
	LoadPhotoUploadcontrol("/SPUD.aspx?albumID=" + spa_strAlbumID + "&flags=0&domain=" + document.domain);
	
}



var strFormData = "";
function SPA_AddHiddenInputToForm(p_form, p_strName, p_strValue)
{
	var hidden = document.createElement("<input type='hidden'>");
	hidden.name = p_strName;
	hidden.value = p_strValue;
	p_form.appendChild(hidden);
	strFormData += p_strName + " : " + p_strValue + "\n";
}


function SPA_Done()
{
	strFormData = "";
	var thumbData;
	
	spa_isAlbumModified = false;
	spa_EditForm.action = spa_strFormActionUrl;

	// add the album ID to the form
	SPA_AddHiddenInputToForm(spa_EditForm, spa_albumIDFieldName, spa_strAlbumID);

	// add the title to the form if it has changed
	if (spa_strAlbumTitle != spa_textAlbumName1.value)
	{
		SPA_AddHiddenInputToForm(spa_EditForm, spa_albumNameFieldName, spa_textAlbumName1.value);
	}

	// build the list of photo handles
	var strPhotoHandles = "";
	var htPhotoHandlesToIndex = new Array();
	for (var i=0; i < spa_objImageEntries.length; i++)
	{
		if (i > 0)
		{
			strPhotoHandles += spa_dataSeparator;
		}
		strPhotoHandles += spa_objImageEntries[i].strID;
		htPhotoHandlesToIndex[spa_objImageEntries[i].strID] = i;
	}
	SPA_AddHiddenInputToForm(spa_EditForm, spa_photoHandlesFieldName, strPhotoHandles);
		
	// add the updated sequence of images
	// the sequence is out-of-sequence if the counts do not match
	var blnOutOfSequence = (spa_objPanel.GetCount() != spa_objImageEntries.length);
	var strPhotosSequence = "";
	for (var i = 0; i < spa_objPanel.GetCount(); i++)
	{
		thumbData = spa_objPanel.GetThumbnailByIndex(i);
		if (i > 0)
		{
			strPhotosSequence += spa_dataSeparator;
		}
		strPhotosSequence += htPhotoHandlesToIndex[thumbData.id];
		if (!blnOutOfSequence)
		{
			blnOutOfSequence = (thumbData.id != spa_objImageEntries[i].strID);
		}
	}
	if (blnOutOfSequence || spa_blnPhotosAdded)
	{
		SPA_AddHiddenInputToForm(spa_EditForm, spa_photosSequenceFieldName, strPhotosSequence);
	}
	
	// add the captions that have changed
	var objImageEntry;
	var strDeletedPhotos = null;
	var blnCaptionsChanged = false;
	for (var i=0; i < spa_objImageEntries.length; i++)
	{
		objImageEntry = spa_objImageEntries[i];
		thumbData = spa_objPanel.GetThumbnailByID(objImageEntry.strID);
		if (thumbData)
		{
			if (thumbData.GetCaption() != objImageEntry.strCaption)
			{
				SPA_AddHiddenInputToForm(spa_EditForm, spa_captionFieldName + htPhotoHandlesToIndex[objImageEntry.strID], thumbData.GetCaption());
				blnCaptionsChanged = true;
			}
		}
		else
		{
			if (strDeletedPhotos == null)
			{
				strDeletedPhotos = "";
			}
			else
			{
				strDeletedPhotos += spa_dataSeparator;
			}
			strDeletedPhotos += htPhotoHandlesToIndex[objImageEntry.strID];
		}
	}
	
	if (blnCaptionsChanged)
	{
		SPA_AddHiddenInputToForm(spa_EditForm, spa_captionFieldName, "1");
	}
	
	// add the deelted photos id there were any
	if (strDeletedPhotos != null)
	{
		SPA_AddHiddenInputToForm(spa_EditForm, spa_deletedPhotosFieldName, strDeletedPhotos);
	}
	
	
	//alert(strFormData);
	spa_EditForm.submit();
}

