var activeLightboxPhotoIds = new Hash();
var fallbackLightboxId;
var lightboxContentsPopulated = false;
var lockChangeLightboxDialog = false;

var isSubscribed = false;
var lightboxAlertLimit = 10;

var loadingHTML = 'loading';

function internalVoid() {
}

function setPointer() {
}

function _debug(message) {
	return;
}

function $t(translationId, english, substitutions) {
	if (document.language == 'en' && !substitutions) {
		return english;
	} else {
		var translation;
		if (document.language == 'en') 
			translation = english;
		else {
			translation = document.translations[translationId];
			if (!translation) {
				translation = english;
			}
		}
		$H(substitutions).keys().each( function(substitutionKey) {
			var subRegex = new RegExp(substitutionKey, 'g');
			translation = translation.replace(subRegex, substitutions[substitutionKey]);
		} );
		return translation;
	}
}

function setLightboxPreviewSize(size, addPhotoId, refreshLightboxId, showRenameDialog) {

	if (size == 'closed') {
		$('lightbox-preview-container').hide();
		lightboxPreviewSize = 'minimized';
		new Ajax.Request('/lightbox/set_preview_size.html', { 
			parameters: { size: 'closed' }
		} );
		return;
	}

	if (lightboxPreviewSize == 'minimized' && size == 'preview') {
		lightboxPreviewSize = size;
		if (!lightboxContentsPopulated) {
			refreshLightboxContents(activeLightboxId, false, addPhotoId);
		}
	}

	$('lightbox-preview-container').show();

	if (size != 'full') {
		new Ajax.Request('/lightbox/set_preview_size.html', { 
			parameters: { size: size }
		} );
	}

	var conf = $H(lightboxElementsConf[size]);

	$('lightbox-preview-container').style.height = conf.get('preview_container_height') + "px";
	$('lightbox-contents-table').style.height = conf.get('contents_table_height') + "px";

	$H(lightboxElementsConf[size]['child_visibility']).each( function(pair) {
		if (pair.value) {
			$(pair.key).show();
		} else {
			$(pair.key).hide();
		}
	} );

	lightboxPreviewSize = size;

	if (refreshLightboxId) {
		refreshLightboxContents(refreshLightboxId, showRenameDialog);
	}

}

function updateLightboxNameDisplay(newName) {
	if (!newName) {
		newName = $('lightbox-new-name-input').value;
	}

	$('rename-message').innerHTML = '';
	
	newName = newName.replace(/^\s+/, '');
	newName = newName.replace(/\s+/g, ' ');

	$('lightbox-new-name-input').value = newName;

	$('lightbox-title').innerHTML = newName;
}

function resetLightboxNameDisplay() {
	$('lightbox-title').style.color = '#383838';
	$('lightbox-title').innerHTML = lightboxTitle;
}

function showLightboxDialog(action) {
	hideLightboxDialogs();

	$(action + '-lightbox-link').className = 'selected-lightbox-link';
	$(action + '-lightbox-dialog').show();
	$(action + '-lightbox-dialog').style.zIndex = parseInt(new Date().getTime()/1000); 	// to appease IE6
	$('lightbox-input-bar').show();

	if (action == 'rename') {
		$('lightbox-title').style.color = '#a0a0a0';
		$('lightbox-new-name-input').focus();

	} else {
		$('lightbox-title').style.color = '#383838';
	}

	if (action == 'share') {
		$('share-lightbox-input').focus();

	} else if (action == 'send') {
		$('send-lightbox-input').focus();
	}
}

function hideLightboxDialogs() {
	$('lightbox-input-bar').hide();
	new Array('send', 'share', 'rename', 'delete', 'alert').each( 
		function(action) {
			$(action + '-lightbox-dialog').hide();
			$(action + '-lightbox-link').className = 'inactive-lightbox-link';
		}
	);
}

function sendLightbox(lightboxId, emailAddress) {

	var error = validateEmailAddress(emailAddress);
	if (error) {
		$('send-message').innerHTML = error;
		return;
	}

	new Ajax.Request( '/lightbox/send_email.html', {
		parameters: {
			lightbox_id: lightboxId,
			email_address: emailAddress
		},
		onFailure: function(transport) {
			alert( $t('LB_TECHNICAL_ERROR_SENDING', "Unfortunately, there was a technical error sending this lightbox") );
		},
		onSuccess: function(transport) {
			alert("This lightbox has been sent to email address: " + emailAddress);
			hideLightboxDialogs();
		}
	} );
}

function renameLightbox(lightboxId, newName) {

	newName = newName.replace(/\s+$/, '');

	var error = validateLightboxName(newName);

	if (!lightboxes.get(lightboxId) || (lightboxes.get(lightboxId) && lightboxes.get(lightboxId).title != newName)) {	
		if (error) {
			$('rename-message').innerHTML = error;
			return;
		}
		new Ajax.Request( '/lightbox/rename_lightbox.html', {
			parameters: {
				lightbox_id: lightboxId,
				new_name: newName
			},
			onFailure: function(transport) {
				alert( $t('LB_TECHNICAL_ERROR_RENAMING', "Unfortunately, there was a technical error changing the lightbox name") );
				$('lightbox-title').innerHTML = lightboxes.get(lightboxId).title;
			},
			onSuccess: function(transport) {
				lightboxTitle = newName;
				var lightbox = lightboxes.get(lightboxId);
				if (lightbox) {
					lightbox.title = newName;
				}
				activeLightbox.set('title', newName);
				exportLightboxData();
				refreshLightboxListings();
			}
		} );
	}
	$('lightbox-title').style.color = '#383838';
	hideLightboxDialogs();
}

function shareLightbox(lightboxId, shareUsername) {

	new Ajax.Request( '/lightbox/share_lightbox.html', {
		parameters: {
			lightbox_id: lightboxId,
			share_username: shareUsername,
			title: lightboxes.get(lightboxId).title
		},
		onFailure: function(transport) {
			alert( $t('LB_TECHNICAL_ERROR_SHARING', "Unfortunately, there was a technical error sharing this lightbox") );
		},
		onSuccess: function(transport) {
			var r = eval(transport.responseText);
			if (r.error) {
				$('share-message').innerHTML = r.error;
			} else {
				alert( $t('LB_SHARE_SUCCESS', "This lightbox has been shared with Shutterstock user: __SHARE_USERNAME__", { __SHARE_USERNAME__: shareUsername }) );
				hideLightboxDialogs();
			}
		}
	} );
}

function createLightbox(lightboxName, photoId) {
	
	$('lightbox-count').innerHTML = '0';
	$('lightbox-title').innerHTML = 'untitled';
	$('lightbox-contents-table').innerHTML = loadingHTML;
	$('lightbox-title').style.color = '#a0a0a0';

	new Ajax.Request( '/lightbox/create_lightbox.html', {
		parameters: {
			lightbox_name: lightboxName
		},
		onSuccess: function(transport) {
			var lightboxId = eval(transport.responseText);
			addImageToLightbox(lightboxId, true);
			lightboxes.set(lightboxId, { title: 'untitled', id: lightboxId, last_modified: parseInt(new Date().getTime()/1000) });
			$('show-lightbox-preview-tab').show();
		},

		onFailure: function(transport) {
			alert( $t('LB_TECHNICAL_ERROR_CREATING', "Unfortunately, there was a technical error creating this lightbox") );
		}
	} );
}

function deleteLightbox(lightboxId) {

	if ($H(selectedLightboxPhotos).keys().length) {
		var proceed = confirm( $t('LB_SELECTED_PHOTOS_CONFIRM_DELETE', "You have selected some photos but you've chosen to delete this entire lightbox.  Are you sure that's what you mean to do?") );
		if (!proceed) {
			hideLightboxDialogs();
			return;
		}
	}
	new Ajax.Request( '/lightbox/delete_lightbox.html', {
		parameters: {
			lightbox_id: lightboxId
		},
		onFailure: function(transport) {
			alert( $t('LB_TECHNICAL_ERROR_DELETING', "Unfortunately, there was a technical error deleting this lightbox") );
		},
		onSuccess: function(transport) {
			lightboxes.unset(lightboxId);
			alert( $t('LB_LIGHTBOX_DELETED', "This lightbox has been deleted") );

			var fallbackLightboxId = lightboxes.values().sortBy( function(lightbox) { return lightbox.last_modified } ).reverse()[0].id;

			refreshLightboxListings();
			if (fallbackLightboxId) {
				refreshLightboxContents(fallbackLightboxId);
			} else {
				setLightboxPreviewSize('closed');
				$('show-lightbox-preview-tab').hide();
			}
		}
	} );

}

function togglePhotoSelection(photoId) {

	if (selectedLightboxPhotos.get(photoId)) {
		selectedLightboxPhotos.unset(photoId);
		$('lightbox-photo-' + photoId).removeClassName('selected-lightbox-photo');
		$('lightbox-photo-checkbox-' + photoId).checked = false;
		
	} else {
		selectedLightboxPhotos.set(photoId, true);
		$('lightbox-photo-' + photoId).addClassName('selected-lightbox-photo');
		$('lightbox-photo-checkbox-' + photoId).checked = true;
	}
}

function refreshLightboxContents(lightboxId, showRenameDialog, addPhotoId, overrideSize) {
	var size = overrideSize ? overrideSize : lightboxPreviewSize;

	new Ajax.Request( '/lightbox/refresh_lightbox.html', {
		method: 'GET',
		parameters: {
			lightbox_id: lightboxId,
			size: size,
			rand: new Date().getTime(),
			language: document.language,
			output_format: 'javascript'
		},
		evalScripts: true,
		onComplete: function(transport) {
			if (showRenameDialog) {
				showLightboxDialog('rename');
			}
			selectedLightboxPhotos.keys().each( function(photoId) {
				selectedLightboxPhotos.unset(photoId);
			} );

			activeLightboxId = lightboxId;
			if (lightboxes.get(lightboxId)) {
				lightboxes.get(lightboxId).last_modified = parseInt(new Date().getTime()/1000);
			}
		
			refreshLightboxListings();
			if (size != 'minimized') {
				lightboxContentsPopulated = true;
			}

			if (addPhotoId) {
				addImageToLightbox(lightboxId, false, addPhotoId);

			} else if (size != 'minimized') {
				exportLightboxData();
			}
		},
		onFailure: function(transport) {
			alert("Unfortunately there was a technical problem loading this lightbox");
		}
	} );
}

function redirectLightboxPage(lightboxId) {
	location.href = '/lightboxes.mhtml?lightbox_id=' + lightboxId;
}

function refreshLightboxListings() {

	if ($('add-image-to-lightbox-listing')) 
		$('add-image-to-lightbox-listing').innerHTML = generateLightboxListing(lightboxes, 'addImageToLightbox');

	if ($('change-lightbox-listing')) {
		var changeLightboxFunction = lightboxPreviewSize == 'full' ? 'redirectLightboxPage' : 'refreshLightboxContents';
		$('change-lightbox-listing').innerHTML = generateLightboxListing(lightboxes, changeLightboxFunction, true);
	}		

	if ($('copy-lightbox-listing'))
		$('copy-lightbox-listing').innerHTML = generateLightboxListing(lightboxes, 'copySelectedPhotos', true);

	if ($('move-lightbox-listing'))
		$('move-lightbox-listing').innerHTML = generateLightboxListing(lightboxes, 'moveSelectedPhotos', true);

	if (lightboxes.keys().length > 1 && lightboxElementsConf[lightboxPreviewSize]['child_visibility']['change-lightbox-arrow']) {
		$('change-lightbox-arrow').show();
	} else {
		$('change-lightbox-arrow').hide();
	}
}

function removeSelectedPhotos(lightboxId, forMove) {
	
	var selectedPhotoCount = selectedLightboxPhotos.keys().length;
	if (selectedPhotoCount == 0) {
		alert( $t('LB_SELECT_TO_REMOVE', "Please select some photos to remove") );
		return;
	}

	if (!forMove) {
		var confirmationMessage;
		if (selectedPhotoCount == 1) 
			confirmationMessage = $t('LB_REMOVE_CONFIRM_SINGULAR', "Are you sure you want to remove this photo from this lightbox?");
		else 
			confirmationMessage = $t('LB_REMOVE_CONFIRM_PLURAL', "Are you sure you want to remove these __SELECTED_PHOTO_COUNT__ photos from this lightbox?", { __SELECTED_PHOTO_COUNT__: selectedPhotoCount});

		if (!confirm(confirmationMessage)) {
			return;
		}
	}

	selectedLightboxPhotos.keys().each( function(photoId) {
		$('lightbox-photo-' + photoId).addClassName('semi-transparent');
	} );

	var photoIdsList = selectedLightboxPhotos.keys().join(',');
	new Ajax.Request( '/lightbox/remove_photos_from_lightbox.html', {
		parameters: {
			photo_ids: photoIdsList,
			lightbox_id: lightboxId
		},
		onFailure: function(transport) {
			alert( $t('LB_TECHNICAL_ERROR_REMOVING', "Unfortunately, there was a technical error removing these photos") );
		},
		onSuccess: function(transport) {
			var removalCount = 0;
			selectedLightboxPhotos.keys().each( function(photoId) {
				selectedLightboxPhotos.unset(photoId);
				activeLightboxPhotoIds.unset(photoId);
				$('lightbox-photo-' + photoId).hide();
				removalCount++;
			} );
			activeLightbox.set('count', activeLightbox.get('count') - removalCount);
			exportLightboxData();
			$('lightbox-count').innerHTML = parseInt($('lightbox-count').innerHTML) - removalCount;
		}
	} );
}

function copySelectedPhotos(lightboxId, forMove) {
	
	var selectedPhotoCount = selectedLightboxPhotos.keys().length;
	hideLightboxDropdowns();
	var photoIdsList = selectedLightboxPhotos.keys().join(',');
	new Ajax.Request( '/lightbox/copy_photos_to_lightbox.html', {
		parameters: {
			photo_ids: photoIdsList,
			lightbox_id: lightboxId
		},
		onFailure: function(transport) {
			alert( $t('LB_TECHNICAL_ERROR_COPYING', "Unfortunately, there was a technical error copying these photos") );
		},
		onSuccess: function(transport) {
			if (forMove) {
				removeSelectedPhotos(activeLightboxId, true);
			} else {
				var confirmationMessage;
				if (selectedPhotoCount == 1) 
					confirmationMessage = $t('LB_COPY_SUCCESS_SINGULAR', "That photo has been copied to that lightbox");
				else 
					confirmationMessage = $t('LB_COPY_SUCCESS_PLURAL', "Those __SELECTED_PHOTO_COUNT__ photos have been copied to that lightbox", { __SELECTED_PHOTO_COUNT__: selectedPhotoCount });

				alert(confirmationMessage);

				selectedLightboxPhotos.keys().each( function(photoId) {
					togglePhotoSelection(photoId);
					$('select-' + photoId).style.opacity = 0;
					selectedPhotoCount++;
				} );
			}
		}
	} );
}

function moveSelectedPhotos(lightboxId) {
	copySelectedPhotos(lightboxId, true);
	// copySelectedPhotos will call removeSelectedPhotos
}

function toggleElementVisibility(elementId) {
	if (elementId == 'change-lightbox-dialog') {
		if (lightboxes.keys().length <= 1 || lightboxPreviewSize == 'minimized') 
			return;
	}

	if ($(elementId).visible()) {
		$(elementId).hide();
	} else {
		$(elementId).show();
	}
}

function toggleLightboxLimitAlert() {

	if ( ! isSubscribed && activeLightbox.get('count') >= lightboxAlertLimit ) {
		if ( activeLightbox.get('count') % lightboxAlertLimit == 0 ) {
			showLightboxDialog('alert');
		}
	}

}

function addImageToLightbox(lightboxId, showRenameDialog, photoIdOverride) {

	// disable dynamic previews until we move our mouse again
	mouseoverEnabled = false;

	var photoId = photoIdOverride ? photoIdOverride : selectedPhotoId;
	if ($('thumb-cell-' + photoId)) {
		$('thumb-cell-' + photoId).style.borderColor = 'white';
		$('thumb-cell-' + photoId).style.backgroundColor = 'white';
	}
	hideLightboxDropdowns();

	if (!showRenameDialog && lightboxId != activeLightboxId) {
		refreshLightboxContents(lightboxId, false, photoId, 'preview');
		return;
	}

	if (lightboxId == activeLightboxId && activeLightboxPhotoIds.get(photoId)) {
		if (lightboxPreviewSize == 'minimized') {
			setLightboxPreviewSize('preview');
		}
		alert( $t('LB_ALREADY_IN_LIGHTBOX', 'That photo is already in this lightbox') );
		return;
	}

	if (lightboxId == activeLightboxId && lightboxContentsPopulated) {
		$('lightbox-contents-table').innerHTML = imageTemplateHTML.replace(/<!-- photo_id -->/g, photoId) + $('lightbox-contents-table').innerHTML;
	}

	new Ajax.Updater('lightbox-thumb-' + photoId, '/lightbox/add_image_to_lightbox.html', {
		parameters: {
			photo_id: photoId,
			lightbox_id: lightboxId
		},
		onSuccess: function(transport) {
			activeLightboxPhotoIds.set(photoId, true);
			if (lightboxId != activeLightboxId) {
				lightboxPreviewSize = 'preview';
				$('lightbox-preview-container').show();
				if (showRenameDialog) {
					setLightboxPreviewSize('preview', false, lightboxId, true);
				}
			} else {
				$('lightbox-count').innerHTML = parseInt($('lightbox-count').innerHTML) + 1;
				if (lightboxPreviewSize == 'minimized') {
					setLightboxPreviewSize('preview');
				}
			}
			activeLightbox.set('count', parseInt(activeLightbox.get('count')) + 1);
			exportLightboxData();

			toggleLightboxLimitAlert(); 
		},
		onFailure: function(transport) {
			alert( $t('LB_TECHNICAL_ERROR_ADDING', "Unfortunately, there was a technical error adding the image to your lightbox") );
		}
	} );
}

function validateLightboxName(name) {

	var errorCode;
	
	if (name.length > 24) {
		errorCode = $t('LB_NAME_TOO_LONG', 'This lightbox name is too long');
	} else if (!name) {
		errorCode = $t('LB_NAME_TOO_SHORT', 'Please enter a name for this lightbox');

	} else if (name.match(/[<>]/)) {
		errorCode = $t('LB_NAME_BAD_CHARS', 'Lightbox names can only contain numbers and letters');

	} else {
		lightboxes.keys().each( function(lightboxId) {
			if (lightboxes.get(lightboxId) && lightboxes.get(lightboxId).title == name) {
				errorCode = $t('LB_NAME_ALREADY_EXISTS', 'You already have a lightbox with this name');
			}
		} );
	}

	return errorCode;
}

function validateEmailAddress(address) {
	var errorCode;
	if (!address.match(/[\w.-]+\@[\w.-]+\.[\w]{2,5}/)) {
		errorCode = $t('LB_INVALID_EMAIL', "This email address does not appear to be a valid one");
	}

	return errorCode;
}

function generateLightboxListing(lightboxes, onclickAction, dontShowActive) {

	var output = '';
	var t = new Template('<div onmouseover="this.style.backgroundColor = \'#f0f4ff\'" onmouseout="this.style.backgroundColor = \'white\'" onclick="mouseoverEnabled = false; ' + onclickAction + '(#{id})" class="lightbox-dialog-link">#{title}</div>');
	lightboxes.values().sortBy( function(lightbox) {
		return lightbox.last_modified;
	} )
	.reverse()
	.each( function(lightbox) {
		if (!(dontShowActive && lightbox.id == activeLightboxId)) {
			output += t.evaluate(lightbox);
		} 
	} );
	return output;
}

function acceptLightbox(lightboxAccessId, lightboxName) {

	var errorCode = validateLightboxName(lightboxName);
	
	if (errorCode) {
		$('lightbox-share-prompt-' + lightboxAccessId).hide();
		$('lightbox-share-rename-' + lightboxAccessId).show();
	} else {
		new Ajax.Updater('lightboxes-overview-container', '/lightbox/accept_lightbox.html', {
			parameters: { 
				lightbox_access_id: lightboxAccessId,
				title: lightboxName
			},
			onFailure: function() {
				alert( $t('LB_TECHNICAL_ERROR_ACCEPTING', "Unfortunately, there was a technical error accepting this lightbox") );
			}
		} );
	}
}

function denyLightbox(lightboxAccessId) {
	new Ajax.Updater('lightboxes-overview-container', '/lightbox/deny_lightbox.html', {
		parameters: { lightbox_access_id: lightboxAccessId },
		onFailure: function() {
			alert( $t('LB_TECHNICAL_ERROR_DENYING', "Unfortunately, there was a technical error denying this lightbox") );
		}
	} );
}
function hideLightboxDropdowns() {
	$('add-to-lightbox-dialog').hide();
	$('change-lightbox-dialog').hide();
	$('copy-lightbox-dialog').hide();
	$('move-lightbox-dialog').hide();
	dropdownDialogShowing = false;
}

function showCopyDialog() {
	
	hideLightboxDropdowns();
	if (lightboxes.keys().length <= 1) {
		alert( $t('LB_NO_OTHER_LIGHTBOXES_COPY', "You don't have any other lightboxes to copy to") );
		return;
	}

	var selectedPhotoCount = selectedLightboxPhotos.keys().length;
	if (selectedPhotoCount < 1) {
		alert( $t('LB_SELECT_PHOTOS_COPY', "Please select some photos to copy") );
		return;
	} else {
		$('copy-lightbox-dialog').show();
		dropdownDialogShowing = true;
	}
}

function showMoveDialog() {
	
	hideLightboxDropdowns();
	if (lightboxes.keys().length <= 1) {
		alert( $t('LB_NO_OTHER_LIGHTBOXES_MOVE', "You don't have any other lightboxes to move to") );
		return;
	}

	var selectedPhotoCount = selectedLightboxPhotos.keys().length;

	if (selectedPhotoCount < 1) {
		alert( $t('LB_SELECT_PHOTOS_MOVE', "Please select some photos to move") );
		return;
	} else {
		$('move-lightbox-dialog').show();
		dropdownDialogShowing = true;
	}
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) 
			return unescape(c.substring(nameEQ.length, c.length));
	}
	return null;
}

function exportLightboxData() {
	if (activeLightbox) {
		document.cookie = "active_lightbox=" + escape(activeLightbox.toJSON()) + "; path=/";
	} else {
		// pass-through
	}
}

function importLightboxData() {
	new Ajax.Request('/lightbox/import_lightbox_data.html', {
		onSuccess: function(transport) {
			refreshLightboxPreview();
		},
		onComplete: function(transport) {
			refreshLightboxListings();
		}
	} );
}

function setLightboxFreshTime(timestamp) {
	document.cookie = "lightboxes_fresh_time=" + timestamp + "; path=/";
}

function showChangeLightboxDialog() {
	if (lightboxes.keys().length > 1 && lightboxPreviewSize != 'minimized') {
		$('change-lightbox-dialog').show();
	}
}

function restoreLightboxPreview() {
	var lightboxId;
	if (!activeLightboxId) {
		lightboxId = lightboxes.values().sortBy( function(lightbox) { return lightbox.last_modified } ).reverse()[0].id;
	}
	setLightboxPreviewSize('preview', false, lightboxId);
}

function toggleChangeLightboxDialog() {
	if ($('change-lightbox-dialog').visible) {
		if (lockChangeLightboxDialog) {
			lockChangeLightboxDialog = false;
			$('change-lightbox-dialog').hide();
		} else {
			lockChangeLightboxDialog = true;
		}
	} else {
		lockChangeLightboxDialog = true;
	}
}

function hideChangeLightboxDialog() {
	if (lockChangeLightboxDialog) {
		return;
	} else {
		$('change-lightbox-dialog').hide();
		lockChangeLightboxDialog = false;
	}
}

