jQuery(document).ready(function($) {

	window.Naming = {

		/* constructor */
		init : function() {

			var canRun = $('body').is('#sets') || $('body').is('#set');
			if (canRun) {
				this.attachGeneralNamingHandlers();
			}
			return this;
		},

		/* constants returned from action bean that tell us what to do next */
		nextStepConstants : {
			NAME_REPRESENTATIVE : "NAME_REPRESENTATIVE",
			NAME_GROUP : "NAME_GROUP",
			NOTHING_TO_NAME : "NOTHING_TO_NAME",
			FINISH_BATCHNAMING : "FINISH_BATCHNAMING",
			NAMING_ERROR : "NAMING_ERROR",
			BATCH_NAMING_DISABLED : "BATCH_NAMING_DISABLED"
		},
		namingData : null, /* temporary data related to current naming progress */
		nameWasAdded : false, /* indicating if at least one name was added */
		imageMd5s : null,
		suggestedNameeId : null,
		suggestedNameMessage : 'If the suggested name is correct just click "Save".',
		enterNameMessage : 'Enter a name in the field above &ndash; then click "Save."',
		/*
		 * during the process (ie if the page should be refreshed on close)
		 */
		generalBatchnamingUrl : "/edit/batch",
		skipFaceAction : "/edit/skip-face",
		markAsNotAFaceAction : "/edit/not-a-face",
		autocomplete : null,
		standardAjaxSuccessFunction : function(data) {
			Naming.namingData = data; /* remembering received data */
			Naming.handleNextNamingStep();
			return false;
		},

		startBatchNaming : function() {
			Naming.nameWasAdded = false;
			Naming.startBatchnamingProcessIterationWithUrl(Naming.generalBatchnamingUrl);
		},

		handleNextNamingStep : function() {
			ModalUtils.currentModalObject = Naming;
			var nextStep = Naming.namingData.nextStep;
			if (nextStep == Naming.nextStepConstants.NAME_REPRESENTATIVE)
				return Naming.showRepresentativeFaceForm();
			if (nextStep == Naming.nextStepConstants.NAME_GROUP)
				return Naming.showMatchesPortion();
			if (nextStep == Naming.nextStepConstants.NOTHING_TO_NAME)
				return Naming.showNothingToNameInfo();
			if (nextStep == Naming.nextStepConstants.NAMING_ERROR)
				return Naming.namingError();
			if (nextStep == Naming.nextStepConstants.BATCH_NAMING_DISABLED)
				return Naming.batchNamingDisabled();
			return Naming.finishBatchnaming();
		},

		startBatchnamingProcessIterationWithUrl : function(startUrl) {
			ModalUtils.getAjaxJson(startUrl, Naming.standardAjaxSuccessFunction);
		},

		getModalReplaceIdAttrsAndAttachHandlers : function(modalIdentifier) {
			var modalForm = ModalUtils.retrieveHtmlTemplateById(modalIdentifier);
			ModalUtils.replaceIdAttributes(modalForm);
			Naming.attachModalHandlers(modalForm);
			Bindings.clearNamingModalBindings();
			Bindings.addNamingModalBindings();
			return modalForm;
		},

		showRepresentativeFaceForm : function() {
			var namingData = Naming.namingData;
			var modalForm = Naming.getModalReplaceIdAttrsAndAttachHandlers("modal-who_is_this");

			/* filling form elements with correct values */
			var img = modalForm.find(".photo img");
			var imageSrcPrefix = img.attr("_src");
			img.attr("src", imageSrcPrefix + namingData.actionBean.faceboxUuid);
			if (namingData.actionBean.nameeIdentityId) {
				modalForm.find("[name=nameeIdentityId]").attr("value", namingData.actionBean.nameeIdentityId);
				modalForm.find(".control [_not_a_face=true]").remove();
			}

			modalForm.find("[name=faceboxUuid]").attr("value", namingData.actionBean.faceboxUuid);
			modalForm.find("[name=faceId]").attr("value", namingData.actionBean.faceId);
			modalForm.find("[name=imageMD5]").attr("value", namingData.actionBean.imageMD5);

			if (namingData.actionBean.faceboxId != null) {
				modalForm.find("[name=faceboxId]").attr("value", namingData.actionBean.faceboxId);
			}
			if (namingData.actionBean.imageInstanceId != null) {
				modalForm.find("[name=imageInstanceId]").attr("value", namingData.actionBean.imageInstanceId);
			}

			if (namingData.actionBean.imageOwnerId != null) {
				modalForm.find("[name=imageOwnerId]").attr("value", namingData.actionBean.imageOwnerId);
			}

			modalForm.find("[name=longRun]").attr("value", namingData.actionBean.longRun);

			/* showing "Skip" or "Cancel" button */
			if (namingData.actionBean.longRun) {
				modalForm.find(".control [_long_run=false]").remove();
			} else {
				modalForm.find(".control [_long_run=true]").remove();
			}

			if (modalForm.find(".control.secondary a").length > 1) {
				modalForm.find(".control.secondary a").not(":last").after(" | ");
			}
			ModalUtils.createAndResizeModal(modalForm);

			GeneralUtils.autocomplete = new AutoComplete("#modal-who_is_this input#name-field", "#modal-who_is_this #autocompleter", function(result) {
				if (result) {
					$("#modal-who_is_this #nameeIdentityId").val(result.defaultIdentityId);
				}
			}, 3, function() {
				/* enter pressed: trying to submit name */
				Naming.nameMainFaceAndGetInitialMatches();
				return false;
			}, "#modal-who_is_this");

			if (namingData.actionBean.nameeUserId != null) {
				Naming.suggestedNameeId = namingData.actionBean.nameeUserId;
				var nameeName = namingData.viewName;
				modalForm.find("input[name=name]").attr("value", nameeName);
				modalForm.find("input[name=nameeUserId]").attr("value", namingData.actionBean.nameeUserId);
				$('#unnamed_label').hide();
				$('#name-field').addClass('suggestion');
				$('#modal-who_is_this .message').html(this.suggestedNameMessage);
			} else {
				$('#suggestion_label').hide();
				$('#no-button').css('visibility', 'hidden');
				$('#modal-who_is_this .message').html(Naming.enterNameMessage);
				$('#name-field').focus();
				modalForm.find("input[name=name]").focus();
			}

		},

		nameMainFaceAndGetInitialMatches : function() {

			var modalForm = $("#modal-data #modal-who_is_this");
			if (!ModalUtils.validateNameForInput(modalForm.find("input[name=name]"))) {
				return false;
			}
			var nameAdded = $.trim(modalForm.find("input[name=name]").val()).toLowerCase();

			/*
			 * assign email input with proper value or cleanup email
			 */
			var email = GeneralUtils.autocomplete.getEmail();
			var emailValid = ModalUtils.isEmailValid(email);
			if (!emailValid) {
				GeneralUtils.autocomplete.invalidEmail();
				return false;
			}
			var name = GeneralUtils.autocomplete.getName();
			if (name == null || name == '' || name == 'Unknown Person') {
				GeneralUtils.autocomplete.emptyName();
				return false;
			} else {
				var nameValid = ModalUtils.isNameValid(name);
				if (!nameValid) {
					GeneralUtils.autocomplete.invalidName();
					return false;
				}
			}

			ModalUtils.hideCurrentModalAndShowLoadingProgress();
			ModalUtils.submitModalForm(modalForm, function(data) {

				if (data.error) {
					if (data.error.email) {
						ModalUtils.removeModalLoadingProgress();
						$('#modal-who_is_this').show();
						GeneralUtils.autocomplete.invalidEmail();
						return false;
					}
					if (data.error.name) {
						ModalUtils.removeModalLoadingProgress();
						$('#modal-who_is_this').show();
						GeneralUtils.autocomplete.invalidName();
						return false;
					}
					if (data.error.emptyName) {
						ModalUtils.removeModalLoadingProgress();
						$('#modal-who_is_this').show();
						GeneralUtils.autocomplete.emptyName();
						return false;
					}
				}
				// Stream.updateNameAndFacebox(data.nameeData);
					if (data.nextStep == Naming.nextStepConstants.NAMING_ERROR) {
						Naming.handleNextNamingStep();
					} else {

						Naming.nameWasAdded = true; // remembering that at least
													// one
					GeneralUtils.autocomplete.updateContactListWithNewName(nameAdded);
					ModalUtils.showModalLoadingProgress();
					Naming.namingData = data;
					Naming.handleNextNamingStep();
				}
				return false;
			});
		},

		skipFace : function() {
			var modalForm = $("#modal-data #modal-who_is_this");
			modalForm.attr("action", Naming.skipFaceAction);
			ModalUtils.showModalLoadingProgress();
			ModalUtils.submitModalForm(modalForm, Naming.standardAjaxSuccessFunction);
		},

		markAsNotAFace : function() {
			var modalForm = $("#modal-data #modal-who_is_this");
			modalForm.attr("action", Naming.markAsNotAFaceAction);
			ModalUtils.showModalLoadingProgress();
			ModalUtils.submitModalForm(modalForm, Naming.standardAjaxSuccessFunction);
		},

		showMatchesPortion : function() {
			var namingData = Naming.namingData;
			var modalForm = Naming.getModalReplaceIdAttrsAndAttachHandlers("modal-are_these_also");

			/* filling form elements with correct values */
			modalForm.find("[name=longRun]").attr("value", namingData.actionBean.longRun);
			modalForm.find("[name=faceId]").attr("value", namingData.actionBean.faceId);
			modalForm.find("[name=faceboxId]").attr("value", namingData.actionBean.faceboxId);
			modalForm.find("[name=nameeIdentityId]").attr("value", namingData.actionBean.nameeIdentityId);
			modalForm.find("[name=imageMD5]").attr("value", namingData.actionBean.imageMD5);
			modalForm.find("[name=name]").attr("value", namingData.actionBean.name);
			modalForm.find("[name=imageOwnerId]").attr("value", namingData.actionBean.imageOwnerId);
			modalForm.find("[name=newIdentity]").attr("value", namingData.actionBean.newIdentity);
			modalForm.find("[name=imageMd5s]").attr("value", namingData.actionBean.imageMd5s);
			Naming.imageMd5s = namingData.actionBean.imageMd5s;
			/* placing name on header and in the description */
			var header = modalForm.find("h1");

			var name = namingData.nameeData.screenName;

			if (name.length > 25) {
				name = name.substring(0, 25) + '...';
			}

			header.text(header.text().replace("__NAME__", name));
			var nameSpan = modalForm.find("p.message strong");
			nameSpan.text(nameSpan.text().replace("__NAME__", name));
			/*
			 * creating face template and removing incomplete template from
			 * modalForm
			 */
			var clusterDiv = modalForm.find(".cluster");
			var faceContainerTemplate = clusterDiv.find(".edit_face_container").clone(true);
			var photoLink = faceContainerTemplate.find("a.photo");
			photoLink.attr("title", photoLink.attr("title").replace("__NAME__", name));
			clusterDiv.find(".edit_face_container").remove();
			/*
			 * now iterating over received faces data and creating face
			 * containers from template
			 */
			var matchingFacesArray = namingData.matchingFaces;
			$.each(matchingFacesArray, function() {
				var faceData = this;
				var newFaceContainer = faceContainerTemplate.clone(true);
				newFaceContainer.attr("_face_id", faceData.faceId);
				newFaceContainer.attr("_facebox_id", faceData.faceboxId);
				var img = newFaceContainer.find(".photo img");
				var imageSrcPrefix = img.attr("_src");
				img.attr("src", imageSrcPrefix + faceData.faceUuid);
				clusterDiv.append(newFaceContainer);
			});

			ModalUtils.createAndResizeModal(modalForm);
		},

		submitCorrectMatchesAndFalsePositives : function() {
			var modalForm = $("#modal-data #modal-are_these_also");

			ModalUtils.showModalLoadingProgress();

			/* reading correctMatches and falsePositives data */
			var correctMatches = [];
			var correctFaceboxesMatches = [];
			var falsePositives = [];
			modalForm.find('.edit_face_container').each(function() {
				var faceContainer = $(this);
				var faceId = faceContainer.attr("_face_id");
				var faceboxid = faceContainer.attr("_facebox_id");
				if (faceContainer.find("img.not").length > 0) {
					falsePositives.push(faceId);
				} else {
					correctMatches.push(faceId);
					correctFaceboxesMatches.push(faceboxid);
				}
			});
			var additionalData = {
				correctMatches : correctMatches,
				falsePositives : falsePositives
			};
			/* finally - submitting the form with data */

			ModalUtils.submitModalFormWithAdditionalData(modalForm, function(data) {
				// Stream.addNamesAndFaceboxes(correctFaceboxesMatches,
					// Naming.imageMd5s, data);
					Naming.namingData = data;
					Naming.handleNextNamingStep();
				}, additionalData);
		},

		showNothingToNameInfo : function() {
			var modalForm = Naming.getModalReplaceIdAttrsAndAttachHandlers("modal-nothing_to_name");
			ModalUtils.createAndResizeModal(modalForm);
		},

		finishBatchnaming : function() {
			ModalUtils.deleteModal();
			window.location.reload();
		},

		namingError : function() {
			var modalForm = Naming.getModalReplaceIdAttrsAndAttachHandlers("modal-naming-error");
			modalForm.find("[class=modalErrorTitle]").text(Naming.namingData.modalErrorTitle);
			modalForm.find("[class=modalErrorMessage]").text(Naming.namingData.modalErrorMessage);
			if (Naming.namingData.modalErrorRemarks) {
				modalForm.find(".modalErrorRemarks").text(Naming.namingData.modalErrorRemarks);
			} else {
				modalForm.find(".modalErrorRemarks").remove();
			}
			if (Naming.namingData.modalErrorButtonLabel) {
				if ("proceed" == Naming.namingData.modalErrorButtonLabel) {
					modalForm.find(".button.close").text("Proceed");
				}
			}
			ModalUtils.createAndResizeModal(modalForm);
		},
		batchNamingDisabled : function() {
			var modalForm = Naming.getModalReplaceIdAttrsAndAttachHandlers("batch-naming-disabled");
			ModalUtils.createAndResizeModal(modalForm);
		},
		attachModalHandlers : function(modalForm) {

			/*
			 * attaching "enter" handler (keyup so that it correctly maps in ie
			 * and safari)
			 */
			/*
			 * modalForm.bind("keypress", function(e) { if (e.keyCode == 13)
			 * return false; }); modalForm.bind("keyup", function(e) { var
			 * keyCode = e.keyCode; if (keyCode == 13) {
			 * 
			 * return false; } });
			 */

			/*
			 * covering standard closing handlers, so that page is being
			 * refreshed if a name was added
			 */
			modalForm.find("a.close_modal, .control a.close, .control a.cancel").click(function() {
				Naming.finishBatchnaming();
				window.location.reload();
				return false;
			});

			/*
			 * FIRST WINDOW WITH ONE FACE catching esc key handler on the input
			 * field so that we can only close the autocomplete if pressed
			 */
			modalForm.filter("#modal-who_is_this").find("input#name-field").bind("keypress", function(e) {
				if (e.keyCode == 27) { /* escape */
					if (GeneralUtils.autocomplete && GeneralUtils.autocomplete.isShown()) {
						return false;
					}
				}
			});
			/* focus/blur on name field */
			modalForm.filter("#modal-who_is_this").find("input#name-field").focus(function() {

				if (Naming.suggestedNameeId != null) {
					// clear name when user clicks on input
					Naming.suggestedNameeId = null;
					$('#name-field').attr('value', '');
					$('#no-button').remove();
					$('#unnamed_label').show();
					$('#suggestion_label').hide();
					$('#name-field').removeClass('suggestion');
					$('#name-field').addClass('named');
					$('#modal-who_is_this .message').html(Naming.enterNameMessage);
					$('.reset').css('display', 'block');
					modalForm.find("input[name=nameeUserId]").attr("value", "");
				} else {
					ModalUtils.focusOnInputWithDefaultValue(this, ModalUtils.defaultName);
				}

			}).blur(function() {
				/* autocomplete shown and tab pressed - choosing selected item */

				if (GeneralUtils.autocomplete)
					GeneralUtils.autocomplete.chooseSelectedValue();
			});

			modalForm.filter("#modal-who_is_this").find(".reset").click(function() {

				$('.name-input #name-field').attr('value', '');
				$('#modal-who_is_this').find("[name=email]").attr('value', '');
				$('#modal-who_is_this').find("[name=nameeUserId]").attr('value', '');
				$('#modal-who_is_this').find("[name=nameeIdentityId]").attr('value', '');
				$('#name-field').attr('value', 'Unknown Person');
				$('#name-field').removeClass('focused');
				$('#name-field').removeClass('named');
				$('#autocompleter').hide();
				$('#modal-who_is_this .message').removeClass('not_visible');
				$('#add_email').remove();
				$(this).hide();
				return false;
			});

			/* saving representative face */
			modalForm.filter("#modal-who_is_this").find(".control a.button.save").click(function() {

				Naming.nameMainFaceAndGetInitialMatches();
				return false;
			});
			/* skipping current face */
			modalForm.filter("#modal-who_is_this").find("#no-button").click(function() {

				modalForm.find("input[name=name]").attr("value", "");
				modalForm.find("input[name=nameeUserId]").attr("value", "");
				$('#suggestion_label').hide();

				$('#unnamed_label').show();
				$('#name-field').removeClass('suggestion');
				$('#no-button').css('visibility', 'hidden');
				modalForm.find("input[name=name]").focus();
				$('#modal-who_is_this .message').html(Naming.enterNameMessage);
				return false;
			});

			/* skipping current face */
			modalForm.filter("#modal-who_is_this").find(".control a.notaface").click(function() {
				Naming.markAsNotAFace();
				return false;
			});
			/* skipping current face */
			modalForm.filter("#modal-who_is_this").find(".control a.skip").click(function() {
				Naming.skipFace();
				return false;
			});

			/* NAMING MATCHES */
			modalForm.filter('#modal-are_these_also').find('a.photo').click(function() {
				var photoLink = $(this);
				var imgObject = photoLink.find("img");
				var selectedDiv = photoLink.find(".selected");
				if (imgObject.is(".not")) {
					selectedDiv.fadeOut('fast');
					imgObject.removeClass('not');
				} else {
					imgObject.addClass('not');
					selectedDiv.fadeIn('fast');
				}

				var button = $(this).parent('.photo').parent('.edit_face_container').find('.button');
				if (button.html() == "No") {
					button.html('Undo');
				} else {
					button.html('No');
				}
				button.toggleClass('black').toggleClass('red');
				return false;
			});

			modalForm.filter('#modal-are_these_also').find('.function a.button').click(function(e) {
				// $(this).parent().siblings('.photo').find('.selected').toggle();

					var selectedDiv = $(this).parent().siblings('.photo').find('.selected');

					if ($(this).text() == "No") {
						$(this).html('Undo');
					} else {
						$(this).html('No');
					}
					var imgObject = $(this).parent().siblings('.photo').find('.data');
					if (imgObject.is(".not")) {
						imgObject.removeClass('not');
						selectedDiv.fadeOut('fast');
					} else {
						imgObject.addClass('not');
						selectedDiv.fadeIn('fast');
					}
					$(this).toggleClass('black').toggleClass('red');
					return false;
				});

			/* Select none */
			modalForm.filter('#modal-are_these_also').find('.selectNone').click(function() {
				var modal = $(this).parents(".modal");
				modal.find('.photo .selected').fadeIn('fast');
				modal.find('.photo img').addClass('not');
				modal.find('.function a').removeClass('red').addClass('black');
				modal.find('.function a').html('Undo');
				return false;
			});
			// Select all
		modalForm.filter('#modal-are_these_also').find('.selectAll').click(function() {
			var modal = $(this).parents(".modal");
			modal.find('.photo .selected').fadeOut('fast');
			modal.find('.photo img').removeClass('not');
			return false;
		});
		modalForm.filter('#modal-are_these_also').find('.control a.button.save').click(function() {
			Naming.submitCorrectMatchesAndFalsePositives();
			return false;
		});

		/*
		 * SENDING EMAILS RELATED focus/blur on email field
		 */
	},

	handleKeyPressed : function(keyCode) {
		// handling esc pressed
		if (keyCode == 27) {
			Naming.finishBatchnaming();
			return false;
		}
		return true;
	},

	attachGeneralNamingHandlers : function() {
		// starting naming process with "Name people" link
		$('a.unnamed').click(function() {
			Naming.nameWasAdded = false;
			Naming.startBatchnamingProcessIterationWithUrl(Naming.generalBatchnamingUrl);
			return false;
		});
		// starting naming process with particular face
		$('.photo_wrapper a.name').live('click', function() {
			var faceLinkUrl = $(this).attr("_href");
			Naming.nameWasAdded = false;
			Naming.startBatchnamingProcessIterationWithUrl(faceLinkUrl);
			return false;
		});

	}

	}.init();
	if (window.location.href.indexOf("batchnamer=true") > 0) {
		Naming.startBatchNaming();
	}
});
