/**
 * @author Owner
 */

$(function() {
	// Declare global variables
	var inProgress = false;
	console.log('welcome to GTI commenting system')
	$('#comments-form').submit(function(e) {
		console.log('preventing auto-submit');
		return false;
	});
	$('#send-btn a').click(function(e) {
		e.preventDefault();
		if (!inProgress) {
			inProgress = true;
			$('#comments-form input, #comments-form textarea').attr('disabled', 'true');
			$('#send-btn a').text('Sending...');
			$('#send-btn a').animate({opacity: 0.7}, 500);
			console.log('submitting form');
			$.get(
				'/lib/post-map-comment.php', {
					country: $('#country').val(),
					name: $('#name').val(),
					email: $('#email').val(),
					affiliation: $('#affiliation').val(),
					body: $('#body').val()
				},
				function(data) {
					if (data === 'OK') {
						$('#name').val('');
						$('#email').val('');
						$('#affiliation').val('');
						$('#body').val('');
						$('#comments-form input, #comments-form textarea').attr('disabled', '');
						$('#send-btn a').text('Post Comment');
						$('#send-btn a').animate({opacity: 1.0}, 500);
						inProgress = false;
						$('<div class="notice" id="notice" style="display: none;">Thank you for submitting your comments.<br />' +
							'Your comments will appear in the area below after being reviewed by GTI.</div>')
							.insertAfter('.section.discussion .right h4')
							.fadeIn(500)
							.animate({opacity: 1.0}, 3000)
							.fadeOut(500, function() {
								$(this).remove();
							});
					}
				}
			);
		}
	});
	$('#all-comments-btn').click(function(e) {
		e.preventDefault();
		console.log('showing all comments');
		$('#indicator').fadeIn(500);
		$(this).remove();
		$.getJSON(
			'/lib/get-map-comments.php', {
				country: $('#country').val()
			},
			function(data) {
				var html = '';
				$.each(data, function(index, item) {
					html +=	'<div class="item">' +
								'<p><strong>' + item.name + '</strong> of <strong>' + item.affiliation + '</strong> at ' + item.posted + '</p>' +
								'<p>' + item.body + '</p>' +
							'</div>';
				});
				$(html).insertAfter('#indicator');
				$('#indicator').remove();
			}
		);
	});
});
