// Define sections
var ProfileInfo = $('#SideProfileInfo');
var ProfileForm = $('#SideProfileForm');
var PasswordForm = $('#SidePasswordForm');

// Define methods
$(function () {

	// Change the password
	PasswordForm.submit(function (event) {

		// Show preloader, hide message
		PasswordForm.find('img.loader').show();
		PasswordForm.parent().find('.alert').remove();

		// Change password over AJAX
		$.post(
			'/administrators/password',
			PasswordForm.serialize(),
			function (response) {
				eval('var response =' + response);

				// Successful
				if (response.success) {
					location.reload();

					// Error
				} else {

					// Hide the preloader and show the error
					PasswordForm.find('img.loader').hide();
					alert(response.error);
				}
			}
		);

		return event.preventDefault();
	});

	// Define helpers
	var profileWrapper = $('.sb-slidebar');
	var profileForms = profileWrapper.find('form');
	var profileInfo = profileWrapper.find('.profile');

	// AJAX form submit
	ProfileForm.submit(function (event) {

		// Check for uploading file
		if (!$(this).closest('form').data('uploading')) {

			// Show preloader, hide message
			ProfileForm.find('img.loader').show();
			ProfileForm.parent().find('.alert').remove();

			// Change password over AJAX
			$.post(
				'/administrators/profile',
				ProfileForm.serialize(),
				function (response) {
					eval('var response =' + response);

					// Successful
					if (response.success) {
						location.reload();

						// Error
					} else {

						// Hide the preloader and show error
						ProfileForm.find('img.loader').hide();
						alert(response.error);
					}
				}
			);

			// There are files that are being uploaded
		} else {
			alert(Polyglot.sideProfile.error_files_uploading);
		}

		return event.preventDefault();
	});


	/**
	 * Profile upload.
	 */
	$('#PhotoNewFile').fileTransport({

		start: function (event, file, data) {

			// Validate the image
			var imageMime = /^image\/(jpeg|png|gif)/;
			if (!imageMime.test(file.type)) {
				alert(Polyglot.sideProfile.error_file_unsupported);
				return false;
			}
		},

		/**
		 * Invoked when file is successfully uploaded.
		 *
		 * @param {object} event The event that created this action.
		 * @param {object} file The uploaded file.
		 * @param {string} token The secret token for the uploaded file.
		 * @param {object} meta Additional info about the uploaded file.
		 * @param {object} data The data containing additional details.
		 */
		success: function (event, file, token, meta, data) {
			$('#PhotoNewFileLabel img').attr('src', meta.thumbnail + '&w=200&h=200');
			$('#ProfileImageToken').val(token);
		},

		progress: function (event, file, percent, data) {
			console.log(percent);
		},

		error: function (event, id, errorMessage) {
			alert(errorMessage);
		}
	});


	// Handle fancy upload
	$('#-PhotoNewFile').fileupload({
		dataType: 'json',
		dropZone: $('#PhotoNewFileLabel'),

		// When the file is added
		add: function (e, data) {
			var file = data.files[0];

			// Validate the image
			var imageMime = /^image\/(jpeg|png|gif)/;
			if (!imageMime.test(file.type)) {
				alert(Polyglot.sideProfile.error_file_unsupported);
				return;
			}

			// Show the preview
			var reader = new FileReader();
			reader.onload = (function (aImg) {
				return function (e) {
					aImg.src = e.target.result;
				};
			})($('#PhotoNewFileLabel img')[0]);
			reader.readAsDataURL(file);

			// Mark the form as uploading
			var parentForm = $(this).closest('form');
			parentForm.data('uploading', (parentForm.data('uploading') || 0) + 1);

			// Hide all idle elements
			parentForm.find('[data-upload-behaviour=idle]').fadeOut();
			parentForm.find('[data-upload-behaviour=working]').fadeIn();

			// Submit
			data.submit();
		},

		// On success
		done: function (e, data) {
			$('#YourAvatar').val(data.result.filename);
		},

		// On error
		fail: function (e, data) {
			$('#YourAvatar').val('');
			alert(Polyglot.sideProfile.error_file_upload);
		},

		// On completed mark there is no active uploads in progress
		always: function (e, data) {

			// Calculate the number or working uploads
			var uploading = ($(this).closest('form').data('uploading') || 0) - 1;
			$(this).closest('form').data('uploading', uploading);

			// Hide all working elements
			if (uploading <= 0) {
				var parentForm = $(this).closest('form');
				parentForm.find('[data-upload-behaviour=idle]').fadeIn();
				parentForm.find('[data-upload-behaviour=working]').fadeOut();
			}
		},

		// Update progress
		progressall: function (e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			$(this).closest('form').find('span.bar').css('width', progress + '%');
		}
	});

	// Show form
	$('a.profile-edit').click(function () {

		// Hide everything
		ProfileInfo.hide();
		ProfileForm.hide();
		PasswordForm.hide();

		// Show appripriate form
		$($(this).attr('href')).show();

		// Show the password field
		if (PasswordForm.is(':visible')) {
			PasswordForm.find('[data-password]').each(function () {
				$(this).attr('type', 'password');
			});
		}
	});

	// Hide form
	$('a.close-form').click(function () {

		// Hide forms
		ProfileForm.hide();
		PasswordForm.hide();

		// Show profile info
		ProfileInfo.show();
	});

});
