$(document).ready(function(){
  var $element = $('.submit-check-isFan');
  FB_RequireFeatures(["Api"], function(){
    /**
     * Al click su un elemento con classe submit-check-isFan verifica che l'utente sia o meno
     * un fan della pagina.
     */
    var api = FB.Facebook.apiClient;
    $element.live('click', function(event){
      event.preventDefault();
      $(this).parent('form').next().hide();
      FB.Connect.requireSession(function(exception){
        FB.Facebook.apiClient.pages_isFan(CD.settings.facebook_page_id, null, function(isFan, exception){
          if (!isFan) {
            $('.submit-check-isFan').parent('form').next().html("Per commentare devi prima cliccare sul pulsante 'Mi piace'!");
            $('.submit-check-isFan').parent('form').next().show();
            //alert("Per commentare devi prima cliccare sul pulsante 'Mi piace'!");
          }
          else {
           if (checkcomment($('.submit-check-isFan').parent('form')))
              $('.submit-check-isFan').parent('form').trigger('submit');
          }
        });
      });
    });
    /**
     * Carica tutti i commenti di un post attraverso una chiamata JS.
     */
    $('.more_comments').live('click', function(event){
      event.preventDefault();
      var post_id = $(this).attr('href').split('#');
      post_id = post_id[1];
      
      var $current = $('form', $(this).parent());
      var $this = $(this);
      
     // alert ($(this).attr('href') + '   ' + post_id);
      
      FB.Connect.requireSession(function(exception){
        FB.Facebook.apiClient.stream_getComments(post_id, function(comments, exception){
          $('.fb_comment:visible',  $current.parent() ).remove();
          $('.fb_comments .more_comments').hide();
          $fb_comment = $('.fb_comment.prototype');
          //console.log ("CURRENT");
          //console.log ($current);

          $.each(comments, function(key, comment){
            $new = $fb_comment.clone();
            $new.removeClass('prototype');
            //console.log($new);
            $new.html($new.html().replace(/FROMID/g, comment.fromid).replace('TEXT', '&nbsp;'+comment.text));
            $new.show();
            $current.before($new);
          });
          $this.hide();
          FB.XFBML.Host.parseDomTree();
        });
      });
    });
  });
});

function checkcomment( form ) {
  f = $(form);
  textarea = $('textarea', f);

  if ( textarea.val() == "" || textarea.val() == "per lasciare un commento, clicca prima su \'mi piace\'" ) {
    textarea.addClass('formerror');
    textarea.focus();
    textarea.blur ( function () { $(this).removeClass('formerror'); $(this).parent('form').next().hide(); } );
    f.next().html("Il testo del commento &egrave; obbligatorio!");
    f.next().show();
    return false;
  }//if

  return true;
}//checkcomment

function likeDislike (action, obj) {
  $('img', $(obj)).show();
  $(obj).load (action);
}//likeDislike


