// Comment form submit
$(function() {
	var div = $('#entry div.entry div.comments');
	if (div.length == 0) { return; }
	
	var entry_id = Number(div.attr('id').substr(9));
	
	var form = $('form.comment');
	if (form.length == 0) { return; }
	
	var submit_form = function(form) {
		var url = services_comment_url.replace('0', entry_id);
		var values = {};
		
		for (i=0; i<form.elements.length; i++) {
			e = form.elements[i];
			if (!e.name) { continue; }
			values[e.name] = e.value;
		}
		
		$.post(url, values, function(data, status) {
			$(form).empty();
			if (data == 'ok') {
				refresh_comments(div, true);
				$(form).remove();
			} else {
				$(form).append(data);
			}
			
		}, 'text');
		return false;
	};
	
	var refresh_comments = function(e, with_thanks) {
		with_thanks = with_thanks || false;
		$.ajax({
			type: 'GET', url: window.location.href,
			cache: false, dataType: 'html',
			success: function(data, status) {
				res = $('#entry div.entry div.comments', data);
				if (with_thanks) {
					add_thanks(e);
				}
				e.replaceWith(res);
			}
		});
	};
	
	var add_thanks = function(e) {
		$('div.comment-thanks').remove();
		var t = $('<div class="comment-thanks">Merci pour votre commentaire.</div>');
		$(e).after(t);
		t.hide().fadeIn(1500);
	};
	
	form.submit(function() {
		submit_form(this);
		return false;
	});
	
	form.prev('h3').wrapInner('<a href="#"></a>');
	$('a', form.prev('h3')).click(function() {
		form.show();
		$(this).parent().remove()
		return false;
		
	});
});
