function teammy_comments(page_id) {
  window.teammy_page_id = page_id;

  $ = jQuery;

  $('.pagination a').live('click', function() {
    scroll_to_comments_list();
    xd_comments( this.href + '&site=' + document.domain.replace(/www\./, '') );
    return false;
  });

  document.write('<link rel="stylesheet" type="text/css" href="http://teammy.com/stylesheets/client.css"/>');
  document.write('<scr' + 'ipt type="text/javascript" src="http://teammy.com/javascripts/insert_text_cursor.js"></scr' + 'ipt>');
  document.write('<scr' + 'ipt type="text/javascript" src="http://teammy.com/javascripts/rails.js"></scr' + 'ipt>');

  wait_for_document(page_id);

  $.receiveMessage(function(e){
    var obj = $.parseJSON(e.data);
    if (obj.comments_list) 
      $('#teammy-comments-list').html(obj.comments_list)
    if (obj.new_comment)
      $('#new_comment').html(obj.new_comment)
    if (obj.post_comment_result)
      $('#post_comment_result').html(obj.new_comment)
    if (obj.anchor)
      document.location.href = document.location.href.replace(/\#.*$/, '') + '#' + obj.anchor;
  })
  
}	

function wait_for_document(page_id) {
  if ($.browser.msie){
    $(function(){ load_comments(page_id) });
  } else {
    load_comments(page_id);
  }

}

function load_comments(page_id) {
  $('#comments').html('<div id="teammy_comments" style="display: none"></div>');
  xd_comments( 'http://teammy.com/comments/' + page_id + "?site=" + document.domain.replace(/www\./, '') );
}

function xd_comments(remote_url) {
  $.getJSON(remote_url + "&callback=?");
}

function scroll_to_comments_list() {
  var currentHref = window.location.href;
  window.location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#commentslist";
}

function scroll_to_comments_form() {
  var currentHref = window.location.href;
  window.location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#addcomments";
}

function load_captcha(){
  if (window.captcha_disabled) {
    jQuery('#teammy_comments').css('display', 'block');  
    return false;
  }
  if (window.Recaptcha){
    window.create_recaptcha();
    window.setTimeout(wait_for_recaptcha_area, 2000);
  } else {
    window.setTimeout(load_captcha, 100);
  }
}

function wait_for_recaptcha_area(){
  if (jQuery('#recaptcha_area').size() > 0){
    jQuery('#teammy_comments').css('display', 'block');  
  } else {
    create_recaptcha();
    window.setTimeout(function(){
      window.console.log ('recreate');
      wait_for_recaptcha_area();
    }, 2000);
  }
}



