//preloading images
var gImages = new Array("previous-w-border-over.gif", "next-w-border-over.gif");
if(document.images)
{
	for(var i=0; i<gImages.length; i++)
	{
		eval("var pic" + i + " = preload_gallery_image('" + SHARED_IMAGE_DIR + "mod_photos/" + gImages[i] + "');");
	}
}

function checkSubmit()
{
	var photosForm = $('organize_photosform');
	var checked = false;
	
	for (var i=0; i < photosForm.elements.length; i++)
	{
		if(photosForm.elements[i].type=="checkbox" )
		{
			if (photosForm.elements[i].checked == true)
			{
				checked = true;
				break;
			}
		}
	}
	
	if (!checked)
	{
		$('deleteSubmitButton').disabled = true;
	}
	else
	{
		$('deleteSubmitButton').disabled = false;
	}
}

function preload_gallery_image(path)
{
	var I = new Image();
	I.src = path;
	return I;
}

function swap_image(id, newpath)
{
	var img = document.getElementById(id);
	img.src = newpath;
}


function browseGalleryThumbs(direction)
{
	//check if more photos exist, and have not been loaded
	var endPos = totPhotoCount - 1;
	if((direction == 'prev' && dispStartPos > 0 && shadowStartPos +  browseShadowSize== dispStartPos) 
		|| (direction == 'next' && dispEndPos < endPos && dispEndPos == shadowEndPos - browseShadowSize))
	{
		getMoreThumbs(direction);
	}
	
	//transitioning old pic out (in a pretty manner) and showing appropriate next pic
	if((direction == 'prev' && dispStartPos > 0) || (direction == 'next' && dispEndPos < endPos))
	{
		var removee = "photoThumb" + (direction == 'next' ? dispStartPos : dispEndPos);
		var ritem = $(removee);	
		if(typeof(ritem.setStyle) != "undefined" && ritem.setStyle != null)
		{
			new Effect.Opacity(removee,  {duration:0.4, from: 1.0, to: 0.0})
			setTimeout("showNextThumb('"+direction+"')", 400);
		}
	}
}

function showNextThumb(direction)
{
	//showing next or prev picture if applicable
	var endPos = totPhotoCount - 1;
	if((direction == 'prev' && dispStartPos > 0) || (direction == 'next' && dispEndPos < endPos))
	{
		var addIdPos = (direction == 'next' ? dispEndPos+1 : dispStartPos-1);
		if(typeof(galleryThumbs[addIdPos]) != 'object')
		{
			alert("An error occurred while loading the next picture, please try again.");
		}
		else
		{		
			//removing appropriate pic
			var removePic = "photoThumb" + (direction == 'next' ? dispStartPos : dispEndPos);
			var element = $(removePic);
			var removePicParent = element.parentNode.id;
			element.parentNode.removeChild(element);
			
			//moving rest of pics over a cell
			if(direction == 'next')
			{
				for(var i = 0; i < (browseDispSize-1); i++)
				{
					var oldTd = $('photoThumbTd' + (i + 1)), newTd = $('photoThumbTd' + i);
					if(newTd.childNodes[0])
						newTd.removeChild(newTd.childNodes[0]);
					newTd.appendChild(oldTd.childNodes[0]);
				}
			}
			else
			{
				for(var i = (browseDispSize-1); i > 0; i--)
				{
					var oldTd = $('photoThumbTd' + (i - 1)), newTd = $('photoThumbTd' + i);
					if(newTd.childNodes[0])
						newTd.removeChild(newTd.childNodes[0]);
					newTd.appendChild(oldTd.childNodes[0]);
				}
			}
			/*
			var startPos = direction == 'next' ? 0 : (browseDispSize - 1);
			var increment = direction =='next' ? 1 : -1;
			var endPos = direction == 'next' ? browseDispSize-1 : 0;
			for(var i=startPos, finished=false; !finished; i+=increment)
			{
				var oldTd = $('photoThumbTd' + (i + increment)), newTd = $('photoThumbTd' + i);
				newTd.innerHTML = oldTd.innerHTML;
				finished = direction == 'next' ? (i<endPos) : (i>endPos);
			}
			*/
			
			//adding new pic
			var photoInfo = galleryThumbs[addIdPos];
			var outColor = (curPhotoPos == addIdPos ? "#8FE427" : "#D0D0D0");
			var overColor = (curPhotoPos == addIdPos ? "#8FE427" : "#D6F5AF");

			var thumbnail = document.createElement('img');
			thumbnail.src = photoInfo['filePath'];
			thumbnail.onMouseOver = "$('photoThumb" + addIdPos + "').style.backgroundColor='" + overColor + "'";
			thumbnail.onMouseOut = "$('photoThumb" + addIdPos + "').style.backgroundColor='" + outColor + "'";
			thumbnail.style.border = 0;
			
			var thumbnail_a = document.createElement('a');
			thumbnail_a.href = photoInfo['viewUrl'];
			thumbnail_a.appendChild(thumbnail);
			
			var thumbnail_div = document.createElement('div');
			thumbnail_div.id = "photoThumb" + addIdPos;
			thumbnail_div.style.backgroundColor = outColor;
			thumbnail_div.style.padding = "6px";
			thumbnail_div.appendChild(thumbnail_a);

			var addPicTdId = 'photoThumbTd' + (direction == 'next' ? browseDispSize-1 : 0);

			if($(addPicTdId).childNodes[0])
				$(addPicTdId).removeChild($(addPicTdId).childNodes[0]);
			$(addPicTdId).appendChild(thumbnail_div);
					
			dispStartPos += direction == 'next' ? 1 : -1;
			dispEndPos += direction == 'next' ? 1 : -1;
			
			updateNextPrevButtons();
		}
	}
}

function updateNextPrevButtons()
{
	var hasPrev = dispStartPos > 0 ? true : false;
	var hasNext = dispEndPos < totPhotoCount - 1 ? true : false;

	var prevBtn = $('smallPrevious'), nextBtn = $('smallNext');
	if(hasPrev)
	{
		prevBtn.src = SHARED_IMAGE_DIR + "mod_photos/previous-w-border.gif";
		prevBtn.onmouseover = "swap_image('smallPrevious', '" + SHARED_IMAGE_DIR + "mod_photos/previous-w-border-over.gif')";
		prevBtn.onmouseout = "swap_image('smallPrevious', '" + SHARED_IMAGE_DIR + "mod_photos/previous-w-border.gif')";
		prevBtn.style.cursor = "pointer";
	}
	else
	{
		prevBtn.src = SHARED_IMAGE_DIR + "mod_photos/prev-grayed-out.gif";
		if(document.all)
		{
			prevBtn.onmouseover = prevBtn.onmouseout = "";
		}
		else
		{
			delete(prevBtn.onmouseover);
			delete(prevBtn.onmouseout);
		}
		prevBtn.style.cursor = "";
	}
	
	if(hasNext)
	{
		nextBtn.src = SHARED_IMAGE_DIR + "mod_photos/next-w-border.gif";
		nextBtn.onmouseover = "swap_image('smallNext', '" + SHARED_IMAGE_DIR + "mod_photos/next-w-border-over.gif')";
		nextBtn.onmouseout = "swap_image('smallNext', '" + SHARED_IMAGE_DIR + "mod_photos/next-w-border.gif')";
		nextBtn.style.cursor = "pointer";
	}
	else
	{
		nextBtn.src = SHARED_IMAGE_DIR + "mod_photos/next-grayed-out.gif";
		if(document.all)
		{
			nextBtn.onmouseover = nextBtn.onmouseout = "";
		}
		else
		{
			delete(nextBtn.onmouseover);
			delete(nextBtn.onmouseout);
		}
		nextBtn.style.cursor = "";
	}
}


function getMoreThumbs(direction)
{	
	var startPos = direction == 'next' ? shadowEndPos + 1 : shadowStartPos - 1;
	
	var rpcclient = new xmlrpc_client('xmlremote', WEB_ADDRESS);
	//rpcclient.debug = true;  
	
	rpcclient.addParam(albumId);
	rpcclient.addParam(startPos);
	rpcclient.addParam(direction);
	rpcclient.call('photos.getMoreThumbs', updateGalleryThumbArr);
}


function updateGalleryThumbArr(ret)
{
	if(ret['error'])
	{
		alert("An error occurred while loading the next picture. Please try again.");
	}
	else
	{
		var direction = ret[0];
		for(var i=1; i<ret.length; i+=3)
		{
			var photoArrKey = parseInt(ret[i]), 
				pid = parseInt(ret[i+1]), 
				viewUrl = (viewPhotoUrlPrefix + "curPhoto," + pid + "/"), 
				filePath = ret[i+2];
			galleryThumbs[photoArrKey] = {'pid':pid, 'viewUrl':viewUrl, 'filePath':filePath};
			
			//updating positions of shadows
			shadowStartPos -= (direction == 'prev' ? 1 : 0);
			shadowEndPos += (direction == 'next' ? 1 : 0);
		}
	}
}

var isEditingTitle = false;
function editPhotoTitle(id)
{
	if(!isEditingTitle)
	{	
		isEditingTitle = true;
		var div = $('galTitleContainer_'+id);
		div.title = "";
		var phototitle = div.innerHTML;
		if (phototitle == '[click here to add/edit a title]')
		{
			phototitle = '';
		}
		div.innerHTML = '<input id="photoTitleChange" type="text" size="40" maxlength="63" value="'+phototitle+'">'
			+ '<input type="hidden" id="photoTitleBackup" value="' + div.innerHTML + '">'
			+ '<input type="button" value="Save" title="Save" onclick="event.cancelBubble=true; savePhotoTitleChange(\'' + id + '\')"> '
			+ '<input type="button" value="Cancel" title="Cancel" onclick="event.cancelBubble=true; cancelPhotoTitleChange(\'' + id + '\')">';
		$('photoTitleChange').focus();
	}
}

var photoTitleBeingEdited = "";
function savePhotoTitleChange(id)
{
	var title = escape(html_special_chars($('photoTitleChange').value));

	photoTitleBeingEdited = id;
	
	var ran_unrounded=Math.random()*1000000000000;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,saveTitle/curPhoto," + id + "/?"+ ran_number;
	new Ajax.Request(url,{method:'post', postBody:'title='+title, onSuccess:handleSavedTitleChange, onFailure:handleFailedAjax});

}

function handleSavedTitleChange(ret)
{
	var response = ret.responseText.evalJSON();
	var success = response.success;
	var message = response.message;
	
	if(!success)
	{
		sendFailMessage(message);
	}
	else
	{
		var div = $('galTitleContainer_'+photoTitleBeingEdited);
		div.title = "Click here to edit";
		if($('photoTitleChange').value)
			div.innerHTML = html_special_chars($('photoTitleChange').value);
		else
			div.innerHTML = "[clcik here to add a title]";
		isEditingTitle = false;
		sendSuccessMessage(message);
	}
}

function handleFailedAjax()
{
	alert("An error occurred while processing your request. Please try refreshing the page to see if that corrects the issue.");
}

function cancelPhotoTitleChange(id)
{
	var div = $('galTitleContainer_'+id), title = $('photoTitleBackup');
	div.title = "Click here to edit";
	div.innerHTML = html_special_chars(title.value);	
	isEditingTitle = false;
}


var isEditingDesc = false;
function editPhotoDesc(id)
{
	if(!isEditingDesc)
	{	
		isEditingDesc = true;
		var div = $('galDescContainer_'+id);
		div.title = "";
		var caption = div.innerHTML;
		if (caption == '[click here to add/edit a caption]')
		{
			caption = '';
		}
		div.innerHTML = '<textarea id="photoDescChange'+id+'" rows="5" cols="75">' + caption + '</textarea>'
			+ '<input type="hidden" id="photoDescBackup" value="' + div.innerHTML + '"><br/>'
			+ '<input type="button" value="Save" title="Save" onclick="event.cancelBubble=true; savePhotoDescChange(\'' + id + '\')"> '
			+ '<input type="button" value="Cancel" title="Cancel" onclick="event.cancelBubble=true; cancelPhotoDescChange(\'' + id + '\')">';
		$('photoDescChange'+id).focus();
	}
}

function savePhotoTitleDescChange(id) {	
	var ran_unrounded=Math.random()*10000000000;
	var ran_number=Math.floor(ran_unrounded);
	
	if($('deletePhoto_'+id).checked) {
		//DELETE FOR BUT NOT THROUGH AJAX
//		http://alt.james.dev.obesityhelp.com/myoh/photos/action,gallery/albumId,55213/curPhoto,334744/?rmPhoto=334744&key=219672275cf17bfe879f3534828ad8b7
		if(confirm('Are you sure you want to delete this photo?  You will lose all other changes on this page')) {
			var url = window.location.protocol+"//"+window.location.host+window.location.pathname;
			url += "?rmPhoto="+id+"&key="+ran_number;
			window.location.href = url;
			return;
		}
		else {
			return;
		}
	}
	var desc = escape(html_special_chars($('photoDescChange_'+id).value));	
	var title = escape(html_special_chars($('photoTitleChange_'+id).value));

	
	var url = BASE_URL + "action,saveTitleDesc/curPhoto," + id + "/?desc=" + desc + "&title=" + title + "&" + ran_number;
	new Ajax.Request(url,{method:'get', onSuccess:handleSavedTitleDescChange, onFailure:handleFailedAjax});
}

function handleSavedTitleDescChange(ret)
{
	responseText = ret.responseText.split('&');
	status = responseText[0];
	response = responseText[1];	
	id = responseText[2];	
	
	if(status == '1') {
		sendSuccessMessage(response);
		$("savecancel_"+id).style.visibility = 'hidden';
		savecancel_amount -= 1; 
		$('photoTitleBackup_'+id).value = $('photoTitleChange_'+id).value;
		$('photoDescBackup_'+id).value = $('photoDescChange_'+id).value;
	}
	else
		sendFailMessage(response);
}

function cancelPhotoTitleDescChange(id) {
	$("savecancel_"+id).style.visibility = 'hidden';
	savecancel_amount -= 1; 
	$('photoTitleChange_'+id).value = $('photoTitleBackup_'+id).value;
	$('photoDescChange_'+id).value = $('photoDescBackup_'+id).value;
	$('deletePhoto_'+id).checked = false;
	
}

var photoDescBeingEdited = "";

function savePhotoDescChange(id)
{
	var desc = escape(html_special_chars($('photoDescChange'+id).value));

	photoDescBeingEdited = id;
	
	var ran_unrounded=Math.random()*100000000000;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,saveDesc/curPhoto," + id + "/?"+ ran_number;
	new Ajax.Request(url,{method:'post', postBody:'desc='+desc, onSuccess:handleSavedDescChange, onFailure:handleFailedAjax});

}

function handleSavedDescChange(ret)
{
	var response = ret.responseText.evalJSON();
	var success = response.success;
	var message = response.message;
	
	if(!success)
	{
		sendFailMessage(message);
	}
	else
	{
		var div = $('galDescContainer_'+photoDescBeingEdited);
		div.title = "Click here to edit";
		
		if($('photoDescChange'+photoDescBeingEdited).value)
			div.innerHTML = html_special_chars($('photoDescChange'+photoDescBeingEdited).value);
		else
			div.innerHTML = "[click here to add a caption]";
			
		isEditingDesc = false;
		sendSuccessMessage(message);
	}
}

function cancelPhotoDescChange(id)
{
	var div = $('galDescContainer_'+id), desc = $('photoDescBackup');
	div.title = "Click here to edit";
	div.innerHTML = html_special_chars(desc.value);	
	isEditingDesc = false;
}

/* ADD PHOTO TAG HANDLER */

var isAddingTag = false;
function addPhotoTags(id)
{
	if(!isAddingTag)
	{
		isAddingTag = id;
		if($('addTagDiv').innerHTML == '')
		{
			$('addTagButton').innerHTML = 'Loading..';
			var url = BASE_URL + "action,getPhotoTagInterface/?id="+id+"&actiontype=gallery";
			new Ajax.Request(url,{method:'get', onSuccess:addPhotoTagsHandler, onFailure:handleFailedAjax});
		}
		else
		{
			$('addTagButton').innerHTML = '<strong style="color:red">Done adding tags</strong>';
			$('addTagButton').onclick = function () { doneAddingTags() };
			$('addTagDiv').style.display = 'block';
			
		}
	}
}

function addPhotoTagsHandler(ret) 
{
	$('addTagDiv').innerHTML = ret.responseText;
	previewImageTagInit();
	$('addTagButton').innerHTML = '<strong style="color:red">Done adding tags</strong>';
	$('addTagButton').onclick = function () { doneAddingTags() };
}


function addGalleryTag(el,tag)
{
	if(el) 
	{
		el.addClassName('usedTag');
	}
	var ran_unrounded=Math.random()*1000000;
	var ran_number=Math.floor(ran_unrounded);

	var url = BASE_URL + "action,addNewTag/?"+ran_number;
	new Ajax.Request (url, {
		method: 'post',
		postBody: "photoId="+isAddingTag+"&tag="+tag+"&curUrl="+curUrlPrefix,
		onFailure:handleFailedAjax,
		onSuccess:addGalleryTagHandler
		});
	
}

function addGalleryTagHandler(ret)
{
	var msg = $('noTagsMsg');
	if(typeof(msg) != "undefined" && msg != null)
	{
		msg.parentNode.removeChild(msg);
	}

	retVal = ret.responseText.evalJSON();

	var len = retVal.tags.length;
	var div, img, a, tagRet;
	for(var i = 0; i < len; i++)
	{
		tagRet = retVal.tags[i];
		
		if(tagRet.error)
		{
			continue;
		}
		
		div = document.createElement("div");
		img = document.createElement("img");
		a = document.createElement("a");
		
		img.setAttribute("src", SHARED_IMAGE_DIR + "mod_photos/tag-icon.gif");
		img.style.border = "0px";
		img.style.height = "16px";
		img.style.width = "16px";
		div.appendChild(img);
		div.appendChild(document.createTextNode(" "));
		a.className = "photoGalLink";
		a.setAttribute("href", tagRet.viewUrl);
		a.style.marginRight = "3px";
		a.appendChild(document.createTextNode(tagRet.name));
		div.appendChild(a);
		if(tagRet.delLink.length > 0)
		{
			div.appendChild(document.createTextNode(" "));
			a = document.createElement("a");
			a.className = "smallGraylink";
			a.setAttribute("href", tagRet.delLink);
			a.onclick = confirmTagDelete;
			a.appendChild(document.createTextNode("(delete)"));
			div.appendChild(a);
		}
		$('tagContainer').appendChild(div);
	}
	
	if(!retVal.success)
	{
		alert(retVal.error);
	}
}

function doneAddingTags() 
{
	if(isAddingTag != false)
	{
		$('addTagDiv').style.display = 'none';
		
		$('addTagButton').innerHTML = '+ add a tag';
		var id = isAddingTag;
		$('addTagButton').onclick = function () { addPhotoTags(id) };
		
		isAddingTag = false;
	}
}

function confirmTagDelete()
{
	return confirm("Are you sure you want to remove the tag from this photo? Click OK to continue.");
}

function confirmPersonDelete()
{
	return confirm("Are you sure you want to remove the person from this photo? Click OK to continue.");
}

function confirmPersonApprove()
{
	return confirm("You are confirming that you are in this photo. Click OK to continue.");
}

function savePSecurity(photoId, type)
{
	if(document.photo_settings)
	{
		for(var i = 0; i < 3; i++)
		{
			document.photo_settings.albumPrivacy[i].checked=false;
		}
	}
	
	var ran_unrounded=Math.random()*5;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,savePhotoSecurity/albumId," + albumId + "/?photoId="+photoId+"&type="+type+"&"+ran_number;
	new Ajax.Request(url,{method:'get', onSuccess:finishSavingPSecurity, onFailure:handleFailedAjax});
}

function finishSavingPSecurity(ret)
{
	responseText = ret.responseText.split('&');
	status = responseText[0];
	response = responseText[1];
	
	if(status == '1')
		sendSuccessMessage(response);
	else
		sendFailMessage(response);
}

function saveASecurity(albumId, type)
{	
	var ran_unrounded=Math.random()*1000000;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,saveAlbumSecurity/?"+ran_number;
	new Ajax.Request(url,{method:'post', postBody:'type='+type, onSuccess:finishSavingASecurity, onFailure:handleFailedAjax});
}

function finishSavingASecurity(ret)
{
	var response = ret.responseText.evalJSON();
	var success = response.success;
	var message = response.message;
	var value = response.value;	
	
	if(success && document.photo_settings)
	{
		for(var i = 0; i < document.photo_settings.elements.length; i++)
		{
			var e = document.photo_settings.elements[i];
			if(e.className == "privacyRadioOption" && e.type == "radio" && e.value==value)
				e.checked = true;
		}
	}
	
	if(success == '1')
		sendSuccessMessage(message);
	else
		sendFailMessage(message);
}

function saveACommentSecurity(albumId, type)
{	
	var ran_unrounded=Math.random()*100000000;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,saveAlbumCommentSecurity/?"+ran_number;
	new Ajax.Request(url,{method:'post', postBody:'type='+type, onSuccess:finishSavingACommentSecurity, onFailure:handleFailedAjax});
}

function finishSavingACommentSecurity(ret)
{
	var response = ret.responseText.evalJSON();
	var success = response.success;
	var message = response.message;
	
	if(success == '1')
		sendSuccessMessage(message);
	else
		sendFailMessage(message);
}


////////

function savePAdultContent(photoId, isAdultContent)
{
	
	if(document.photo_settings)
	{
		for(var i = 0; i < 2; i++)
		{
			document.photo_settings.adultContent[i].checked=false;
		}
	}

	
	var ran_unrounded=Math.random()*5;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,savePhotoAdultContent/albumId," + albumId + "/?photoId="+photoId+"&isAdultContent="+isAdultContent+"&"+ran_number;
	new Ajax.Request(url,{method:'get', onSuccess:finishSavingPAdultContent, onFailure:handleFailedAjax});
}

function finishSavingPAdultContent(ret)
{
	responseText = ret.responseText.split('&');
	status = responseText[0];
	response = responseText[1];
	
	if(status == '1')
		sendSuccessMessage(response);
	else
		sendFailMessage(response);
}

function saveAAdultContent(albumId, isAdultContent)
{
	var ran_unrounded=Math.random()*1000000;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,saveAlbumAdultContent/?"+ran_number;
	new Ajax.Request(url,{method:'post', postBody:"isAdultContent="+isAdultContent, onSuccess:finishSavingAAdultContent, onFailure:handleFailedAjax});
}

function finishSavingAAdultContent(ret)
{
	/*
	ret:
		[0] bool return code
		[1] adultContent level saved
		[2] return message
	*/
	var response = ret.responseText.evalJSON();
	var success = response.success;
	var message = response.message;
	var value = response.value;	
	

	if(success && document.photo_settings)
	{
		for(var i = 0; i < document.photo_settings.elements.length; i++)
		{
			var e = document.photo_settings.elements[i];
			if(e.className == "adultContentRadioOption" && e.type == "radio" && e.value==value)
				e.checked = true;
		}
	}
	
	if(success == '1')
		sendSuccessMessage(message);
	else
		sendFailMessage(message);
}
///////



function loadAddAlbumForm()
{
	$('addAlbumBox').hide();
	$('addAlbumBoxForm').show();
}

function cancelAddAlbum() 
{
	$('addAlbumBox').show();
	$('addAlbumBoxForm').hide();
}


var isEditingAlbumTitle = false;
function editAlbumTitle(id)
{
	if(!isEditingAlbumTitle)
	{	
		isEditingAlbumTitle = true;
		var div = $('albumTitleContainer' + id);
		div.title = "";
		var style = {};

		
		div.innerHTML = '<input id="albumTitleChange" type="text" size="20" maxlength="63" value="' + div.innerHTML + '">'
			+ '<input type="hidden" id="albumTitleBackup" value="' + div.innerHTML + '">'
			+ '<input type="button" value="Save" title="Save" onclick="event.cancelBubble=true; saveAlbumTitleChange(\'' + id + '\')"> '
			+ '<input type="button" value="Cancel" title="Cancel" onclick="event.cancelBubble=true; cancelAlbumTitleChange(\'' + id + '\')">';


	}
}

var boxBeingEdited = "";
function saveAlbumTitleChange(id)
{
	var title = escape(html_special_chars($('albumTitleChange').value));	
	if(!title)
	{
		alert("The title of the album appears to be blank. Please try again.");
	}
	else
	{
		var ran_unrounded=Math.random()*10000000000;
		var ran_number=Math.floor(ran_unrounded);
		
		boxBeingEdited = id;
		
		var url = BASE_URL + "action,saveAlbumTitle/albumId," + id + "/?"+ran_number;
		new Ajax.Request(url,{method:'post', postBody:"title=" + title, onSuccess:handleSavedAlbumTitleChange, onFailure:handleFailedAjax});
	}
}

function handleSavedAlbumTitleChange(ret)
{
	responseText = ret.responseText.split('&');
	status = responseText[0];
	response = responseText[1];
	
	if(status == '1') {
		sendSuccessMessage(response);
		var div = $('albumTitleContainer' + boxBeingEdited);
		Position.relativize(div);

		var style = {};
		style.border = "";
		style.padding = "";
		style.display = "";
		style.background = "";
		
		div.setStyle(style);
		
		div.title = "Click here to edit";
		div.className='albumTitleContainer';
		div.innerHTML = html_special_chars($('albumTitleChange').value);
		$('albumHeaderTitle').innerHTML = div.innerHTML;
		isEditingAlbumTitle = false;
	}
	else
		sendFailMessage(response);
}

function cancelAlbumTitleChange(id)
{
	var div = $('albumTitleContainer' + id), title = $('albumTitleBackup');
	Position.relativize(div);
	var style = {};
	style.border = "";
	style.padding = "";
	style.display = "";
	style.background = "";

	div.setStyle(style);
	
	div.title = "Click here to edit";
	div.className='albumTitleContainer';
	div.innerHTML = html_special_chars(title.value);	
	isEditingAlbumTitle = false;
}

var isEditingAlbumPassword = false;
function editAlbumPassword(id)
{
	if(!isEditingAlbumPassword)
	{	
		isEditingAlbumPassword = true;
		var div = $('albumPassword');
		div.title = "";
		div.innerHTML = '<input id="albumPasswordChange" type="text" size="20" maxlength="63" value="' + div.innerHTML + '">'
			+ '<input type="hidden" id="albumPasswordBackup" value="' + div.innerHTML + '">'
			+ '<input type="button" value="Save" title="Save" onclick="event.cancelBubble=true; saveAlbumPasswordChange(\'' + id + '\')"> '
			+ '<input type="button" value="Cancel" title="Cancel" onclick="event.cancelBubble=true; cancelAlbumPasswordChange(\'' + id + '\')">';
	}
}

function saveAlbumPasswordChange(id)
{
	var password = escape(html_special_chars($('albumPasswordChange').value));	
	var ran_unrounded=Math.random()*1000000000;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,saveAlbumPassword/?"+ ran_number;
	new Ajax.Request(url,{method:'post', postBody:'password='+password,onSuccess:handleSavedAlbumPasswordChange, onFailure:handleFailedAjax});

}

function handleSavedAlbumPasswordChange(ret)
{
	var response = ret.responseText.evalJSON();
	
	var success = response.success;
	var message = response.message;
	
	
	if(success) {
		sendSuccessMessage(message);
		var div = $('albumPassword');
		div.title = "Click here to edit";
		div.className='albumPasswordContainer';
		div.innerHTML = html_special_chars($('albumPasswordChange').value);
		var span = $('albumPasswordSend');
		if(div.innerHTML == '') { 
			span.style.display = 'none';
			div.innerHTML = '[Click to set password]';
		}
		else span.style.display = '';
		isEditingAlbumPassword = false;
	}
	else
		sendFailMessage(message);
}

function cancelAlbumPasswordChange(id)
{
	var div = $('albumPassword'), title = $('albumPasswordBackup');
	div.title = "Click here to edit";
	div.className='albumPasswordContainer';
	div.innerHTML = html_special_chars(title.value);	
	isEditingAlbumPassword = false;
}


function updateAlbumOrder(order)
{
	var ran_unrounded=Math.random()*1000000;
	var ran_number=Math.floor(ran_unrounded);
		
	var post = 'order='+order.replace(/&/g,',');
	var url = BASE_URL + "action,updateAlbumOrder/?"+ran_number;
	new Ajax.Request(url,{method:'post', postBody: post, onSuccess:handleUpdatedAlbumOrder, onFailure:handleFailedAjax});

}

function handleUpdatedAlbumOrder(ret)
{
	var response = ret.responseText.evalJSON();
	
	var success = response.success;
	var message = response.message;
	if(success)
		sendSuccessMessage(message);
	else
		sendFailMessage(message);
}

function updatePhotoOrder(order)
{
	var ran_unrounded=Math.random()*5;
	var ran_number=Math.floor(ran_unrounded);

	var url = BASE_URL + "action,updatePhotoOrder/?order="+order.replace(/&/g,',')+"&"+ran_number;
	new Ajax.Request(url,{method:'get', onSuccess:handleUpdatedPhotoOrder, onFailure:handleFailedAjax});

}

function handleUpdatedPhotoOrder(ret)
{
	responseText = ret.responseText.split('&');
	status = responseText[0];
	response = responseText[1];
	
	if(status == '1')
		sendSuccessMessage(response);
	else
		sendFailMessage(response);
}

var settingAlbumThumbnailId = false;
function setAlbumThumbnail(id)
{		
	settingAlbumThumbnailId = id;
	
	var url = BASE_URL + "action,setAlbumThumbnail/id," + settingAlbumThumbnailId;
	new Ajax.Request(url,{method:'get', onSuccess:handleSetAlbumThumbnail, onFailure:handleFailedAjax});

}

function handleSetAlbumThumbnail(ret)
{
	responseText = ret.responseText.split('&');
	status = responseText[0];
	response = responseText[1];
	
	if(status == '1')
		sendSuccessMessage(response);
	else
		sendFailMessage(response);
}

function showButton(dir)
{
	var btn = $('photo-button-'+dir);
	btn.style.visibility ="visible";
}

function hideButton(dir)
{
	var btn = $('photo-button-'+dir);
	btn.style.visibility ="hidden";
}

var rotatedPhotos = new Array();
function rotatePhotoTemp(dir,id) {
	dirty = true;
	var ran_unrounded=Math.random()*100000000;
	var ran_number=Math.floor(ran_unrounded);
	
	if(!rotatedPhotos[id])
		rotatedPhotos[id] = new Array();
		
	var value = parseInt($('rotate_'+id).value);
	value = (value+(dir == 'left' ? -1 : 1))%4;
	if(value < 0)
		value += 4;
		
	$('rotate_'+id).value = value;
	$('rotate_'+id).checked = true;
	var angle = value*90;
	if(!rotatedPhotos[id][angle])
	{
		$('rotating_'+id).style.display = 'block';
		var url = BASE_URL + "action,rotatePhotoTemp/?direction="+angle+"&id="+id+"&"+ran_number;
		new Ajax.Request(url,{method:'get', onSuccess:handleRotatePhotoTemp, onFailure:handleFailedAjax});
	}
	else
	{
		refreshRotatedThumbnail(id, angle);
	}

}

function handleRotatePhotoTemp(ret) {
	var response = ret.responseText.evalJSON();
	
	var success = response.success;
	var message = response.message;
	var id = response.id;
	var direction = response.direction;
	var thumbnailUrl = response.url;
	$('rotating_'+id).style.display = 'none';
	if(success == 1) {
		rotatedPhotos[id][direction] = thumbnailUrl;
		refreshRotatedThumbnail(id, direction);
		rotatingPhotoId = false;
	}
	else {
		sendFailMessage(message);
	}
}

function refreshRotatedThumbnail(id, dir) {
	var thumbnail = $('photo_thumbnail_'+id);
	thumbnail.src = rotatedPhotos[id][dir]+"?"+(new Date()).getTime();
}


//replaces the < > with &lt; &gt;
function html_special_chars(title) {
	title = title.replace(/</g,'&lt;');
	title = title.replace(/>/g,'&gt;');
	return title;
}




var Photo = Class.create();

Photo.prototype = {
	photo : false,
	orgDimensions : false,
	ratio: 2.0,
	spacer: false,
	
	initialize: function(elem){
		var img = $(elem.firstChild.firstChild);
		this.photo = img;
		
		this.orgDimensions = img.getDimensions();
		this.spacer = $(document.createElement('img'));
		this.spacer.writeAttribute('load_src', this.photo.attributes.getNamedItem('load_src').value);
		this.spacer.setStyle({width:this.orgDimensions.width, height:this.orgDimensions.height, display:'none', margin:'1'});

		this.photo.parentNode.appendChild(this.spacer);
				
		Event.observe(elem, 'mouseover', this.expand.bindAsEventListener(this));
		Event.observe(elem, 'mouseout', this.contract.bindAsEventListener(this));
	},
	
	expand: function(e){
		
		//setup and position photo/spacer
		Position.clone(this.photo, this.spacer);
		Position.absolutize(this.photo);
		
		//increase the size of the photo
		var d = {};
		d.width = Math.round(this.orgDimensions.width * this.ratio) + 'px';
		d.height = Math.round(this.orgDimensions.height * this.ratio) + 'px';
		d.zIndex = 5;
		this.photo.addClassName("largeThumbnailPhoto");
		this.photo.setStyle(d);		
		
		//replace in the spacer
		this.spacer.style.display = '';
		this.spacer.src = this.spacer.readAttribute('load_src');		
		
	},
	
	contract: function(e){
		//contract photo
		Position.relativize(this.photo);
		var d = {};
		d.width = this.orgDimensions.width;
		d.height = this.orgDimensions.height;
		d.zIndex = 1;
		this.photo.setStyle(d);
		this.photo.removeClassName("largeThumbnailPhoto");
		this.spacer.style.display = 'none';
	}
}

var photoThumbs;

function initPhotos()
{
	var thumbs = $$('span.photoThumbContainer');

	for(i=0 ; i < thumbs.length; i++ )
	{
		var photo = new Photo(thumbs[i]);
	}
	
	showThumbnailWindow();
	

}

function showThumbnailWindow() 
{
	var thumbs = $$('img.photoThumbs');
	//dynamically set this depending if we are in photos, groups, or myoh
	var photosPerRow = $('photosPerRow').innerHTML;
	var curPhotoIndex = 0;
	
	//TODO find better formulation for the curPhotoIndex
	for(i=0 ; i < thumbs.length; i++ )
	{
		if(thumbs[i].hasClassName('currentPhoto'))
			curPhotoIndex = i;	
	}
	
	//Calculates thumbnail view window
	var windowStart = 0;
	var windowEnd = thumbs.length-1;
	if(curPhotoIndex == windowStart)
		windowEnd = photosPerRow - 1;
	else if(curPhotoIndex == windowEnd) 			
		windowStart = curPhotoIndex - (photosPerRow - 1);
	else 
	{
		windowStart = curPhotoIndex - (photosPerRow/2 - 1);
		windowEnd = curPhotoIndex + (photosPerRow/2 );
		if(windowStart < 0)
		{
			windowStart = 0;
			windowEnd = photosPerRow - 1;
		}
		if(windowEnd > thumbs.length - 1) 
		{
			windowEnd = thumbs.length - 1;
			windowStart = windowEnd - photosPerRow + 1;
		}
	}
	
	// Loads in the images	
	for(i=0 ; i < thumbs.length; i++ )
	{
		if(i >= windowStart && i <= windowEnd )
		{
			if(!thumbs[i].src)
				thumbs[i].src = thumbs[i].readAttribute('load_src');
			thumbs[i].style.display = 'inline';		
		}
		else
			if(thumbs[i].style.display != 'none')
				thumbs[i].style.display = 'none';		
	}	
}

function showAllThumbnails() 
{
	var thumbs = $$('img.photoThumbs');		
	for(i=0 ; i < thumbs.length; i++ )
	{
		if(!thumbs[i].src)
			thumbs[i].src = thumbs[i].readAttribute('load_src');
		thumbs[i].style.display = 'inline';
	}
}


function sendSuccessMessage(msg) {
	sendMessage(msg, 'green');
}

function sendFailMessage(msg) {
	sendMessage(msg, 'red');
}

function sendMessage(msg,color) {
	var mb = createMessageBox();
	mb.initialize();
	mb.setHeight(document.messageBoxHeight);
	mb.setColor(color);
	mb.message(msg);
	
	document.messageBoxNum = mb.id;
	document.messageBoxes['mb_'+mb.id] = mb;		
}

var previous_order;
var thumbnail_drop = false;
var save_toggle = false;
var album_id;
var saveTimeout;

function init_scripts() {
		
		album_id = $('album_id').value;
		 Sortable.create('photo_list',{	tag:'li',
			 							constraint:false,
			 							overlap:'horizontal',
			 							containment: ['photo_list'], 
			 							dropOnEmpty: true,
			 							onHoverInstant: true,
			 							onUpdate: function(container) {
			 								previous_order = previous_order.replace(/photo_list\[\]=/g, '');
			 								var ordering = previous_order.split('&');
			 								
			 								//get the id of the image that is being moved around
			 								if(thumbnail_drop) {
			 									var moved_item, next_item, div_id;
				 								for(var i = 0; i < ordering.length; i++) {
				 									div_id = container.childNodes[i] ? container.childNodes[i].id.replace('photoId_','') : false;
				 									if(!div_id || div_id != ordering[i]) {
				 										if(div_id == ordering[i+1] || !div_id) {
				 											moved_item = $('photoId_'+ordering[i]);
		 													next_item = $('photoId_'+ordering[i+1]);
				 											break;
				 										}
				 										else {
				 											for(var j = i; j < ordering.length; j++) {
				 												if(ordering[j]==div_id)
				 													break;
				 											}
				 											moved_item = $('photoId_'+div_id);
				 											next_item = $('photoId_'+ordering[j+1]);
				 											break;
				 											
				 										}
				 									}
				 								}
				 								
				 								// reorder thumbnails to correct ordering
				 								if(moved_item) {
				 									//replace in list
													moved_item = moved_item.remove();
		 											if(next_item != null)
														this.element.insertBefore(moved_item, next_item);
													else
														this.element.appendChild(moved_item);
				 									
				 								}
				 								
				 								//unflag thumbnail drop
				 								thumbnail_drop = false;
			 								}
			 								previous_order = Sortable.serialize('photo_list');
			 								clearTimeout(saveTimeout);
			 								saveTimeout = setTimeout("saveAlbumOrdering(album_id,previous_order)",3500);
			 							}

			 								
			 							}
			 						);
			 						
		previous_order = Sortable.serialize('photo_list');

	}
	
	function toggleSave() {
		if(!save_toggle) {
			$('save').show();
			new Effect.Highlight($('save'));
			save_toggle = true;	
		}
	}

	function toggle_org_checkboxes(check) 
	{
		var link = $('checkbox_toggle');		
		var photosForm = $('organize_photosform');
		for(var i = 0; i < photosForm.elements.length; i++)
		{
			if(check)
			{
				if(photosForm.elements[i].type=="checkbox" )
				{
					photosForm.elements[i].checked = true;
				}
				link.innerHTML = "[unselect all]";
				link.href = "javascript:toggle_org_checkboxes(false)";
			}
			else 
			{
				if(photosForm.elements[i].type=="checkbox" )
				{
					photosForm.elements[i].checked = false;
				}
				link.innerHTML = "[select all]";
				link.href = "javascript:toggle_org_checkboxes(true)";
			}
		}
		
		checkSubmit(); // enable/disable the delete button
	}
	
	function valDeletePhotos()
	{
		var photosForm = $('organize_photosform');
		var checked = false;
		
		for (var i=0; i < photosForm.elements.length; i++)
		{
			if(photosForm.elements[i].type=="checkbox" )
			{
				if (photosForm.elements[i].checked == true)
				{
					checked = true;
					break;
				}
			}
		}
		
		if (!checked)
		{
			alert('You have not selected any photos to be deleted.');
			return false;
		}
		else
		{
			return confirm('Are you sure you want to delete the photo(s) that you have selected?');
		}
	}
	
	function save_album_change(id) {	
		//find out if we are chucking the thumbnail
		var photoAlbumId = $('album_thumbnail').childNodes.length == 3 ? $('album_thumbnail').childNodes[1].id : $('album_thumbnail').childNodes[0].id;
		var thumbnailInTheTrash = false;
		var trash = $('trash');
		for (var i = 0; i < trash.childNodes.length; i++) {
			var child = trash.childNodes[i].id;
			if(photoAlbumId.match(child)) {
				 thumbnailInTheTrash = true;
				 break;
			}
		}
		
		if(thumbnailInTheTrash)
			alert("Your thumbnail is in the trash, please remove it from the trash or change your thumbnail before continuing");
		else {				
			if( !Sortable.serialize('trash') || Sortable.serialize('trash') && confirm('Are you sure you want to delete the photos in the trash?'))
				saveAlbumOrdering(id, Sortable.serialize('photo_list'));	
		}
	}
	
	function cancel_album_change() {
		window.location.reload(false);
		
		$('save').hide();
		$('canceling').show();
		
		new Effect.Highlight($('canceling'));
		save_toggle = false;
	}

	function saveAlbumOrdering(id, order_list)
	{
		var ran_unrounded=Math.random()*5;
		var ran_number=Math.floor(ran_unrounded);
		
		var url = BASE_URL + "action,updatePhotoOrder/albumId," + id + "/?photo_order=" + order_list.replace(/&/g,',') + "&" + ran_number;
		new Ajax.Request(url,{method:'get', onSuccess:handleSavedAlbumOrdering, onFailure:handleFailedAjax});
		
	}
		
function handleSavedAlbumOrdering(ret)
{
	var response = ret.responseText.evalJSON();
	var success = response.success;
	var message = response.message;
	
	if(success) {
		sendSuccessMessage(message);
//		$('save').hide();
//		$('saving').hide();
//		if($('trash').childNodes.length) {
//			while($('trash').childNodes.length) {
//				if($('trash').firstChild) {
//					$('trash').removeChild($('trash').firstChild);
//				}
//			}
//			$('trash').style.height = '60px';
//		}
//		save_toggle = false;
	}
	else {
		sendFailMessage(message);
	}

}
		
IGNORE_UNLOAD = false;
UNLOAD_MSG = 'You have unsaved changes on this page!';
var dirty = false;
function editAlbumPhotosDoBeforeUnload() 
{
	if(dirty) 
	{
	   if(IGNORE_UNLOAD) return; // Let the page unload
	
	   if(window.event)
	      window.event.returnValue = UNLOAD_MSG; // IE
	   else
	      return UNLOAD_MSG; // FX
	}
}

function editAlbumPhotosDirtyDeleted(formname) 
{
	var form = $(formname);
	for(var i = 0; i < form.elements.length; i++)
		if(form.elements[i].name.match(".*delete.*"))
			if(form.elements[i].checked == true)
				return true;
	return false;
}


/* Used for photo friends */

function searchPhotoFriends(filter)
{
	friends.each(function(friend, i) { 
										if (!friend[1].match(filter)) 
										{ 
											$(friend[0]).style.display="none"; 
										}
										else 
										{
											$(friend[0]).style.display="block"; 
										}
									
								});
}

var friends = new Array();
function initSearchPhotoFriends() 
{
	//maybe get a better way to get the list
	if(friends.length == 0)
	{
		if($('photo_friends_list'))
		{
			var children = $('photo_friends_list').childNodes
			for(index in children) {
				var child = $(children[index]);
				if(child.tagName == "SPAN") {
					friends.push(new Array(child.id, child.readAttribute('name')));
				}
			}
		}
	}
}

/* Used for multiple file uploads */
var tagFormId = false;
var tagPhotoId = false;
var tagTagId = false;
function addNewTag(id, tag, form_id)
{
	tagFormId = form_id;
	var ran_unrounded=Math.random()*1000000;
	var ran_number=Math.floor(ran_unrounded);
	var url = BASE_URL + "action,addNewTag/?"+ran_number;
	new Ajax.Request(url,{method:'post', postBody:"photoId="+id+"&tag="+tag, onSuccess:handleAddNewTag, onFailure:handleFailedAjax});
}

var customTagElem = false;
function addCustomNewTag(id, elem)
{
	var tag = $(elem+"_custom").value;
	var ran_unrounded=Math.random()*1000000;
	var ran_number=Math.floor(ran_unrounded);
	
	customTagElem = elem;
	
	var url = BASE_URL + "action,addNewTag/?"+ran_number;
	new Ajax.Request(url,{method:'post', postBody:"photoId="+id+"&tag="+tag, onSuccess:handleAddNewTag, onFailure:handleFailedAjax});
}


function handleAddNewTag(ret)
{
	var response = ret.responseText.evalJSON();
	if(response.success)
	{
		sendSuccessMessage('Tag added successfully');
		if(customTagElem)
		{
			addCustomTags(customTagElem);
			customTagElem = false;
		}
		
		tags = response.tags;
		tags.each( function(obj)
			{
				
				str = '$("' + obj.name + '_added_tag").onclick = function() { removeTag(this);removeNewTag(' + obj.id + ', ' + obj.tagId + '); };';
				
				eval(str);
		
			}
		);
		
		adjustPhotoPageSize();
		
		//change the state of the selected item. set tags to true.. this one is used in
		//the multiple file handler
		if(Object.isFunction(tagSuccess))
			tagSuccess();
	}
	else
	{
		
		sendFailMessage(response.error);	
	}
}

function removeNewTag(id, tagId)
{
	var ran_unrounded=Math.random()*1000000;
	var ran_number=Math.floor(ran_unrounded);
	
	var url = BASE_URL + "action,removeNewTag/?"+ran_number;
	new Ajax.Request(url,{method:'post', postBody:"photoId="+id+"&tagId="+tagId, onFailure:handleFailedAjax});
}

function adjustPhotoPageSize()
{
	var imagePreviewContainer = $('uploadPhotoTags').up('div.imagePreviewContainer');
	var imagePreviewDims = getElementAbsolutePos(imagePreviewContainer);
	var photoContainerDims = getElementAbsolutePos($('photosOuterWrap'));
	var photoContainerBottom = photoContainerDims.y + $('photosOuterWrap').getHeight();
	var imageContainerBottom = imagePreviewDims.y + imagePreviewContainer.getHeight();
	if(photoContainerBottom < imageContainerBottom)
	{
		var newHeight = $('photosOuterWrap').getHeight() + (imageContainerBottom - photoContainerBottom);
		$('photosOuterWrap').setStyle({height: newHeight + 'px'});
	}
}

if (window.location.href.match('organizeAlbum')) 
{
	var bin, binOffset, binParent,moving = false, upperLimit, lowerLimit, movingDelay, movingEffect;
	Event.observe(window, 'load', function() 
	{
		bin = $('organizeBin');
		
		binOffset = Position.cumulativeOffset(bin);
	
		Event.observe(window, 'scroll', floatingOrganize);
		Event.observe(window, 'resize', floatingOrganize);
	});
	
	Event.observe(window, 'unload', function() 
	{
		saveAlbumOrdering(album_id,Sortable.serialize('photo_list'));
		clearTimeout(saveTimeout);
	});
	
	function doneMoving()
	{
		moving = false;
	}
	
	function cancelMoving() 
	{
		if(movingDelay)
		{
			movingEffect.cancel();
			movingEffect = false;
		}
			
	}
	
	function organizeAlbumDoMove(position)
	{
		movingDelay = false;
		movingEffect = new Effect.Move(bin, {	y:position, 
												mode: 'absolute', 
												delay:0,
												beforeUpdate: cancelMoving,
												afterFinish: doneMoving
												});
	}
	
	function floatingOrganize() 
	{
		var s;
		// scrolling offset calculation via www.quirksmode.org
		if (self.pageYOffset)
		{
			s = self.pageYOffset;
		}
		else if (document.documentElement && document.documentElement.scrollTop) 
		{
			s = document.documentElement.scrollTop;
		}
		else if (document.body) 
		{
			s = document.body.scrollTop;
		}
		var viewportwidth;
		var viewportheight;
		
		if (typeof window.innerWidth != 'undefined')
		{
		   viewportwidth = window.innerWidth,
		   viewportheight = window.innerHeight
		}
		else if (typeof document.documentElement != 'undefined'
		  && typeof document.documentElement.clientWidth !=
		  'undefined' && document.documentElement.clientWidth != 0)
		{
		    viewportwidth = document.documentElement.clientWidth,
		    viewportheight = document.documentElement.clientHeight
		}
		else
		{
		    viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		    viewportheight = document.getElementsByTagName('body')[0].clientHeight
		}

		var binDims = bin.getDimensions();
		upperLimit = binOffset[1];
		binParent = $(bin.parentNode);
		binParentOffset = Position.cumulativeOffset(binParent);
		binParentDim = binParent.getDimensions();
		
		lowerLimit = binParentOffset[1] + binParentDim.height;
		
		
		var shouldMoveDown = s > upperLimit, 
			shouldMoveUp = (s + binDims.height) < viewportheight,
			canMoveDown =  (s + binDims.height) < lowerLimit,
			canMoveUp = s > upperLimit,
			atBottom = (s + binDims.height) >= lowerLimit;
		

//		console.log(atBottom+" "+canMoveDown+" "+shouldMoveDown+" "+s+" "+viewportheight+" "+lowerLimit+" "+upperLimit+" "+binDims.height);
		
		
		if (canMoveDown && shouldMoveDown) 
		{	
			var topOffset = s - binOffset[1];
			if(movingDelay) clearTimeout(movingDelay);
			movingDelay = setTimeout('organizeAlbumDoMove('+topOffset+')',1000);
			bin.style.position = 'relative';
		}
		else if(atBottom && shouldMoveDown)
		{
			var topOffset = binParentDim.height - binDims.height;
			if(movingDelay) clearTimeout(movingDelay);
			movingDelay = setTimeout('organizeAlbumDoMove('+topOffset+')',1000)
			bin.style.position = 'relative';
		}
		else 
		{
			if(movingDelay) clearTimeout(movingDelay);
			movingDelay = setTimeout('organizeAlbumDoMove('+0+')',1000)
			bin.style.position = 'relative';
		}
	}
	
}




/*
 * the orderedList is an ordered list that allows users to add and remove values by just specifying the value itself
 */
var orderedList = {
	queueId:new Array(),
	hashId:new Array(),
	
	/*
	 * Add to the end of the ordered list
	 */
	add: function(id) 
	{
		var index = this.queueId.push(id) - 1;
		this.hashId[id] = index;
	},
	
	/*
	 * Remove specified element from the ordered list
	 */
	remove: function(id)
	{
		this.queueId.splice(this.hashId[id],1);
		this.hashId[id] = false;
		for(var i = 0; i < this.queueId.length; i++)
			this.hashId[this.queueId[i]] = i;
		
	},
	
	/*
	 * Gets the specifed index in the list
	 */
	getIndex: function(id)
	{
		return this.hashId[id];
	},	
	
	/*
	 * Gets the next element in the list after the specified element
	 */
	next: function(id)
	{
		var cur_index = this.hashId[id];
		var next_index = cur_index+1;
		if(this.queueId[next_index])
			return this.queueId[next_index];
		else
			return false;
	},
	
	/*
	 * Gets the previous element in the list after the specified element
	 */
	prev: function(id)
	{
		var cur_index = this.hashId[id];
		var prev_index = cur_index-1;
		if(this.queueId[prev_index])
			return this.queueId[prev_index];
		else
			return false;
	},
	
	/*
		* prints the list
	 */
	print: function()
	{
		var a = '';
		for(var i = 0; i < this.queueId.length; i++)
			a += this.queueId[i]+": "+this.hashId[this.queueId[i]]+", ";
		return a;
	}
};


var imagePreviewer = {
	
	//the currently viewed image
	currentPreviewImage:false,
	currentPreviewFile:false,
	//keeps a list of photos in the image previewer
	photoList: orderedList,
	
	//sends out ajax command to load an id
	loadPreviewImage:function(id, file_id) 
	{
		
		if(id)
		{
			tagBlur();
			var ran_unrounded=Math.random()*100000000;
			var ran_number=Math.floor(ran_unrounded);

			if($('imagePreview_'+this.currentPreviewFile))
			{
				$('imagePreview_'+this.currentPreviewFile).innerHTML = '';
				$('imagePreview_'+this.currentPreviewFile).style.backgroundColor = '';
			}
//				$('photoPreviewImage').innerHTML = "<div class='imagePreviewerLoading'>"+$('photoPreviewImage').innerHTML+"<div class='imagePreviewerLoadingBG'><img class='imagePreviewerImage' src='/shared/images/mod_photos/rotating.gif'/></div></div>";
			
			var url = BASE_URL + "action,getUploadFileData/?"+ran_number;
			new Ajax.Request(url,{method:'post', postBody:"id="+id+"&file_id="+file_id, onSuccess:this.handleLoadPreviewImage, onFailure:handleFailedAjax});

			
		}
	},
	
	/*
	 * This is kinda like a static class since its called by ajax sometimes o_O
	 */
	handleLoadPreviewImage:function(ret) 
	{
		var response = ret.responseText.evalJSON();
		//update buttons
		imagePreviewer.currentPreviewImage = response.id;
		imagePreviewer.currentPreviewFile = response.file_id;
		
		//reload image
		
		$('imagePreview_'+response.file_id).innerHTML = response.content;	
		
		imagePreviewer.updateButtons();
		tagCurrently();
		//initialize tag
		previewImageTagInit(); 
	},	
	
	updateButtons:function() 
	{
		var next_id = this.photoList.next(this.currentPreviewImage);
		var prev_id = this.photoList.prev(this.currentPreviewImage);
		
		var next_text = '<a href="javascript:imagePreviewer.next()">Next</a>';
		var prev_text = '<a href="javascript:imagePreviewer.prev()">Previous</a>';
		
		if(!next_id)
		{
			if($('nextPreviewImage')) 
				$('nextPreviewImage').innerHTML = 'Next';
		}
		else
		{
			if($('nextPreviewImage')) 
				$('nextPreviewImage').innerHTML = next_text;
		}
			
		if(!prev_id)
		{
			if($('prevPreviewImage')) 
				$('prevPreviewImage').innerHTML = 'Previous';
		}
		else
		{	
			if($('prevPreviewImage')) 
				$('prevPreviewImage').innerHTML = prev_text;
		}
		
	},
	
	// removes an id from the image previewer and updates the list as well as the image previewer itself
	remove: function(id) 
	{
		if(id == this.currentPreviewImage)
		{
			var load_id = false;
			if(!(load_id = this.photoList.next(id)) && !(load_id = this.photoList.prev(id)))
				load_id = false;
			if(this.photoList.getIndex(id) !== false)
				this.photoList.remove(id);
			this.loadPreviewImage(load_id);
		}
		else
		{
			if(this.photoList.getIndex(id) !== false)
				this.photoList.remove(id);
			this.updateButtons();
		}
				
	},
	
	next: function() 
	{
		var id = this.photoList.next(this.currentPreviewImage);
		this.loadPreviewImage(id, idFileHash[id]);
	},
	
	prev: function() 
	{
		var id = this.photoList.prev(this.currentPreviewImage);
		this.loadPreviewImage(id, idFileHash[id]);
	},
	
	addToPhotoList: function(id) 
	{
		this.photoList.add(id);
		this.updateButtons();
	}
};

