function comment_sucess(comment_count) {
  _gaq.push(['_trackEvent','social','comment',document.location.pathname]);
	update_comment_count(comment_count);
	
	location.href="#book_comments_pane";
	// show success message
	$j('#comment-success').show().delay(2000).fadeOut();
	
}
function update_comment_count(size){
  if ($j('#comment-count')){
    $j('#comment-count').text(size);
  }
  if ($j('#comment-count-top')){
    $j('#comment-count-top').text(size);
  }
}

function create_captcha(key, lang) {
	Recaptcha.create(key, "captcha", {lang: lang}); // so that an exception is thrown immediately
													//   if there is no Recaptcha object
	redo = function() {
		if($j('#recaptcha_area').length == 0) {
			Recaptcha.create(key, "captcha", {lang: lang});
			setTimeout(redo, 100);
		}
	}
	setTimeout(redo, 300);
}

var captcha_updated = false
function update_captcha() {
	if (!captcha_updated) {
		$j.ajax({
			url: '/comments/captcha',
			type: 'GET',
			dataType: 'json',
			complete: function() { captcha_updated = true },
			success: function(data, status, request) {
				// include the recaptcha js
				var html_doc = document.getElementsByTagName('head').item(0);
			    var js = document.createElement('script');
			    js.setAttribute('language', 'javascript');
			    js.setAttribute('type', 'text/javascript');
			    js.setAttribute('src', 'http://api.recaptcha.net/js/recaptcha_ajax.js');
			    html_doc.appendChild(js);
			   	
				//  Since ie's script tag doesn't fire a 'load' event, we need to set
				//    a timeout to ensure that the recaptcha lib is loaded before we
				//    use the Recaptcha object
				var trying = true;
				var check = function() {
					try {
						create_captcha(data.key, data.lang);
						trying = false;
					} catch (err) {
						trying = true;
					}
					
					if(trying) {
						setTimeout(check, 100);
					}
				};
				setTimeout(check, 100);
			}
		});
	}
}

$j('#comment-form').live('submit', function(e) {
    var form = $j(this);
    var url = form.attr('action');
    var data = {};
    
    form.find(':input[type!=submit]').each(function() {
        var el = $j(this);
        data[el.attr('name')] = el.val();
    });
    
    $j.ajax({
        url: url,
        type: 'POST',
        data: data,
        success: function(data, status, request) {
			if (request.status == 200) {
            	$j('#comment-input').val('');
			}
			Recaptcha.reload();
        }
    });
    
    e.preventDefault();
});
