function validate_comment_form(){
  if (jQuery.cookie('signed_in') != null){
    return true;
  } else {
    if (jQuery('#comment_you_must_be_over_13:checked').length == 0){
      alert('You must be 13 years of age or older to comment.');
      return false;
    } else if (jQuery('#comment_agree_to_terms:checked').length == 0){
      alert('You must agree to the terms and conditions to comment.');
      return false;
    } else {
      return true;
    }
  }
}

function check_comment_form(){
  if (jQuery.cookie('signed_in') != null){
    jQuery('#comment_signin').hide();
    if (jQuery.cookie('confirmed') != null) {
      jQuery('#comment_form').show();        
    } else {
      jQuery('#comment_confirm').show();
    }
  }

  if (jQuery.cookie('user_name')){
    jQuery('#comment_author_name').val(unescape(jQuery.cookie('user_name')));
  }
  if (jQuery.cookie('user_email')){
    jQuery('#comment_author_email').val(unescape(jQuery.cookie('user_email')));
  }
  if (jQuery.cookie('signed_in')){
    jQuery('.anonymous_comments').hide();
    jQuery('.comment_email').hide();
    jQuery('#comment_author_name').attr('disabled','disabled');
  }
}

function submit_comment(){
  if (validate_comment_form()){
    jQuery.post('/comments.js', jQuery('#new_comment').serialize(), function(data){
      jQuery('#comment_container').html(data);
      check_comment_form();
    })
  }
  return false;
}

jQuery().ready(function(){
  if (jQuery('#comment_container').length > 0){
    var url = '/comments/new.js?' + jQuery('#commentable_type').serialize() + '&' + jQuery('#commentable_id').serialize();
    jQuery('#comment_container').load(url, check_comment_form);
    jQuery('#new_comment').live('submit', submit_comment);
    jQuery('#new_comment button').live('click', submit_comment);
  }
});
