(function() {
	$(document).ready(function() {
		var $contact_form = $('#plugin-contact-form');
			$contact_form.show();
			$contact_email = $('#sender_email_repeat');
			$contact_email.parent('div').parent('div').parent('div').hide();
			//$('#message').expanding();	
		

			$sender_token = $('#sender_token');
			if($sender_token.length){
				set_token();
			}
		

		function set_token(){
			var url = $contact_form.prop('action');
				var load = "token";	
				var data = {};
				$.ajax({
					url: url + "?load=" + load,
					type: 'POST',
					dataType: 'JSON',
					data: data
				})
				.done(function(data, textStatus, jqXHR) {
					//_log(data);
					$sender_token.val(data.token);
					
				})
				.fail(function(jqXHR, textStatus, errorThrown) {
					//_log(jqXHR.responseText);
					display_general_error('There was a problem submitting the form: ' + textStatus + ' ' + errorThrown);
				});

		}
		function display_general_error(msg) {
			var $error_msg = $('#plugin-contact-form-error');
			if (!$error_msg.length) {
				$error_msg = $('<p id="plugin-contact-form-error" class="plugin-contact-form-error" style="display: none;"></p>');
				$contact_form.prepend($error_msg);
			}
			$error_msg.html(msg);
			$error_msg.fadeIn();
		}

		$contact_form.submit(function() {
			$('.error', this).removeClass('.error');
			$('.plugin-contact-form-error', this).hide();
			var data = $(this).serialize();
			var url = $(this).prop('action');
			var load = $(this).data('load');
			$.ajax({
				url: url + "?load=" + load,
				type: 'POST',
				dataType: 'JSON',
				data: data
			})
			.done(function(data, textStatus, jqXHR) {
				console.log(data);
				if (typeof data.errors != 'undefined') {
					set_token();
					for (key in data.errors) {
						if (key == 'general') {
							display_general_error(data.errors[key]);
							continue;
						}
						var html_id = '#error-' + key + '-' + data.errors[key];
						var $container = $(html_id);
						if (!$container.length) {
							$container = $('<div id="' + html_id.substring(1) + '" class="alert alert-danger plugin-contact-form-error"><button type="button" class="close" data-dismiss="alert">×</button>' + 'Bitte Feld ausfüllen.' + '</div>');
							$('[name=' + key + ']').after($container).addClass('error');
						}
						$container.hide().fadeIn();
					}
				}
				else {
					$contact_form.hide();
					var $success_msg = $('#plugin-contact-form-success');
					if (!$success_msg.length) {
						$success_msg = $('<p id="plugin-contact-form-success" style="display: none;">Nachricht gesendet. Vielen Dank!</p>');
						$contact_form.after($success_msg);
					}
					$success_msg.hide().fadeIn();
				}
			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				//_log(jqXHR.responseText);
				display_general_error('There was a problem submitting the form: ' + textStatus + ' ' + errorThrown);
			});
			return false;
		});

	});

})(jQuery);