$(function() {
	var $form = $('.formValidate'),
		$messageForm = $('.form-message')

	function initForm() {
		$('.mask-cpf').mask('000.000.000-00', { reverse: true })

		$form.each(function(f, form) {
			$(form)
				.parsley()
				.on('form:validated', function() {
					var ok = $form.find('.parsley-error').length === 0

					$(form)
						.find('.input-file')
						.each(function() {
							if ($(this).hasClass('parsley-error')) {
								$(this)
									.parents('.file')
									.addClass('error')
							} else {
								$(this)
									.parents('.file')
									.removeClass('error')
							}
						})

					if (!ok) {
						$messageForm.addClass('--alert')
						removeFormAlert()
					}
				})
				.on('form:submit', function() {
					sendForm(form)
					return false
				})
		})

		dataType()
	}

	function dataType() {
		var $dataTypeButton = $('.js-data-type-button')

		$dataTypeButton.on('click', function() {
			var selectedValue = $(this).data('type-value')

			$dataTypeButton.removeClass('is-selected')
			$(this).addClass('is-selected')
			$('.js-data-type-value').val(selectedValue)
		})
	}

	function sendForm(form) {
		var formData = new FormData(form),
			$formButton = $(form).find('.formSubmit'),
			url = $(form).data('action')

		$formButton
			.text('')
			.attr('disabled', 'disabled')
			.addClass('--loading')

		$.ajax({
			method: 'POST',
			cache: false,
			contentType: false,
			processData: false,
			url: url,
			data: formData,
			success: function(response) {
				$formButton
					.text('Enviar')
					.removeAttr('disabled')
					.removeClass('--loading')
				$(form)[0].reset()
				removeFormAlert()
				$messageForm.text(response.msg).addClass('--alert')
			}
		})
	}

	function removeFormAlert() {
		setTimeout(function() {
			$messageForm.removeClass('--alert')
		}, 5000)
	}

	initForm()
})
