(function($) {
	'use strict';

	var config = window.wppsLocalUserAvatar || {};
	var strings = config.strings || {};

	function initLocalAvatarProfile() {
		if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
			return;
		}

		var $wrap = $('.wpps-local-avatar-wrap');
		if (!$wrap.length) {
			return;
		}

		var $input = $('#wpps-local-avatar-id');
		var $preview = $('.wpps-local-avatar-preview');
		var $remove = $('#wpps-local-avatar-remove');
		var $upload = $('#wpps-local-avatar-upload');
		var $tpl = $('.wpps-local-avatar-default-tpl');

		function setReplaceState() {
			$upload.text(strings.replace || 'Replace');
			$remove.prop('hidden', false);
		}

		function setDefaultState() {
			$upload.text(strings.upload || 'Upload Avatar');
			$remove.prop('hidden', true);
		}

		function openMediaFrame() {
			var frame = wp.media({
				title: strings.selectTitle || 'Select or upload avatar',
				button: { text: strings.useAsAvatar || 'Use as avatar' },
				library: { type: 'image' },
				multiple: false
			});

			frame.on('select', function() {
				var att = frame.state().get('selection').first().toJSON();
				var url = (att.sizes && att.sizes.medium && att.sizes.medium.url) ? att.sizes.medium.url : (att.url || '');

				$input.val(att.id);
				$preview.find('.wpps-local-avatar-default').remove();
				$preview.find('.wpps-local-avatar-img').remove();
				$preview.append(
					$('<img />')
						.attr('src', url)
						.addClass('wpps-local-avatar-img')
				);
				setReplaceState();
			});

			frame.open();
		}

		$upload.off('click.wppsLocalAvatar').on('click.wppsLocalAvatar', function(e) {
			e.preventDefault();
			openMediaFrame();
		});

		$preview.off('click.wppsLocalAvatar').on('click.wppsLocalAvatar', function(e) {
			e.preventDefault();
			openMediaFrame();
		});

		$remove.off('click.wppsLocalAvatar').on('click.wppsLocalAvatar', function(e) {
			e.preventDefault();
			$input.val('');
			$preview.find('.wpps-local-avatar-default').remove();
			$preview.find('.wpps-local-avatar-img').remove();
			if ($tpl.length) {
				$preview.append($('<div class="wpps-local-avatar-default">').append($tpl.contents().clone()));
			}
			setDefaultState();
		});
	}

	$(initLocalAvatarProfile);
})(jQuery);
