$(document).ready(function(){
  $social_buttons = $('#navbar .btn:not(#btn_blog)');
  /*
  // Semaforo per richieste AJAX,
  $social_buttons.data('ajaxActive', 0);
  //Fired when an AJAX request starts
  $('body').ajaxStart(function() { 
    val = $social_buttons.data('ajaxActive'); 
    $social_buttons.data('ajaxActive', val + 1); 
  });
  //Fired when an AJAX request completes
  $('body').ajaxComplete(function() {
    val = $social_buttons.data('ajaxActive'); 
    $social_buttons.data('ajaxActive', val - 1); 
  });
*/
  $social_buttons.click(function(e){
    // Stop operations immediately if there is at least one AJAX call in progress.
  /*  if ($(this).data('ajaxActive')) {
      return false;
    }*/
    // Attiva o disattiva lo stato del bottone, disattiva ogni altro bottone.
    $(this).toggleClass('btn_active');
    var is_active = $(this).hasClass('btn_active');
    $social_buttons.removeClass('btn_active');
    if (is_active) {
      $(this).addClass('btn_active');
    }
    else {
      $(this).removeClass('btn_active');
      // Disattivo ogni stato riferito all'hash.
      e.preventDefault();
      hash_set('');
    }
    
    //elimino i cookie legati a facebook
    $.cookies.del('fb_comment_data_post_id');
    $.cookies.del('fb_comment_data_hash');
    $.cookies.del('fb_post_index');
    
    
    /**
     * Estrae dall'href del link il network su cui lavorare.
     * Il link contiene un URL completo, non la sola ancora, per cui bisogna splittare e poppare
     * e non fare semplicemente un replace('#', '').
     */
    var type = $(this).attr('href').split('#').pop();
    
    // Se il bottone e' attivo, carichiamo un network specifico, altrimenti carichiamo la versione mista.
    var type_to_load = is_active ? type : null;
    $('.wrapper').hide(); // Nascondi tutti
    var wrappers_to_show = is_active ? '.single.' + type + '-wrapper' : '.mixed';
    $els_shown = $(wrappers_to_show + '.wrapper').show();
    // Se abbiamo gia' caricato dei dati, non serve ricaricarli.
    if (!$els_shown.length) {
      load_slots(type_to_load);
    }
  });
  /**
   * Salva in un cookie i dati sul post che si sta commentando per poter riaprire lo slot relativo.
   * 
   * Questo handler viene eseguito dopo quello contenuto in interface.js, per cui lo slot
   * e' gia' esteso con classe 'less' o chiuso con class 'more' e senza classe 'less'.
   */
  $('.more, .less', $('.facebook-wrapper')).live('click', function(event){
    var fb_post_id = $(this).parents('.wrapper').attr('id');
    var data = $(this).hasClass('less') ? { 'fb_post_id': fb_post_id, 'hash': hash_pieces(0)} : null;
    if ($(this).hasClass('less')) {
      $.cookies.set('fb_comment_data_post_id', '' + fb_post_id);
      $.cookies.set('fb_comment_data_hash', hash_pieces(0));
//      memorizzo l'id dell'elemento che deve aprirsi (devo sapere se si trova nella prima o ennesima pagina)
      $.cookies.set('fb_post_index', '' + $('.facebook-wrapper').index( $(this).parents('.wrapper') ) );
    }
  });
  
  $('#more_entries').live('click', function(event){
    event.preventDefault();
    var hash = hash_pieces(0);
    load_slots(hash, true);
  });
  
  // Ad ogni cambiamento di hash, verifichiamo se mostrare o meno il paginatore.
  $(window).bind( 'hashchange', show_or_hide_paginator);

  // CODICE ESEGUITO AL LOAD
  var post_id = $.cookies.get('fb_comment_data_post_id');
  var cookie_hash = $.cookies.get('fb_comment_data_hash');
  var index_post = $.cookies.get('fb_post_index');
  if (post_id) {
    hash_set(cookie_hash + '/' + post_id + '/' + index_post);
    $.cookies.del('fb_comment_data_post_id');
    $.cookies.del('fb_comment_data_hash');
    $.cookies.del('fb_post_index');
  }
  
  setTimeout ( "checkiframe()", 700);
  
  var hash = hash_pieces(0);
  $('<a href="#" id="more_entries">more...</a>').hide().appendTo('#page');
  // Al load carica gli slot corretti.
  load_slots(hash);
  show_or_hide_paginator();

  
});

/**
  * Verifica la presenza dell'iframe caricato da twitter, in caso di esito positivo attivo il punsante per il Reply
  */
function checkiframe() {
  if( $(".twitter-anywhere-tweet-box:not(.bound)").length > 0 ) {
    $(".twitter-anywhere-tweet-box:not(.bound)").each( function(index, el) {
      $(el).parent().parent().prev().html('<a href="#" class="action reply">Reply</a>');
      $(el).addClass('bound');
    });
  }  
  if ($(".twitter-wrapper").length > $(".bound").length ) {
    setTimeout ( "checkiframe()", 700);
  }
}

/**
 * Carica gli slot relativi ad un network o a ciascun network.
 * @param type     string   uno dei 4 social network o null.
 */
function load_slots(type, pagination) {
  var pagination = pagination?true:false;
 
  switch (type) {
    case 'twitter':
      setTimeout ( "checkiframe()", 700);
      load_slots_single(type);
      break;
    case 'facebook':
    case 'flickr':
    case 'youtube':
      load_slots_single(type, pagination);
      break;
    default:
      setTimeout ( "checkiframe()", 700);
      load_slots_mixed();
      break;
  }
}

/**
 * Predispone ed effettua il caricamento di 4 slot relativi ai diversi tipi di network.
 */
function load_slots_mixed() {
  $.each(['facebook', 'twitter', 'flickr', 'youtube'], function(index, type){
    network_placeholder(type);
  });
  $.each(['facebook', 'twitter', 'flickr', 'youtube'], function(index, type){
    load_network(type, 'mixed');
  });
}

/**
 * Effetua la chiamata AJAX per il caricamento di un network.
 * 
 * @param type     string   uno dei 4 social network
 * @param display  string   una stringa che indica se si sta caricando slot dello stesso network o misti.
 *                          Puo' essere 'single' o 'mixed'.
 * @param callback function una funzione opzionale da eseguire prima della replaceWith. Riceve
 *                          il parametro data contenente la risposta della chiamata AJAX.
 * @param pagination boolean indica se l'azione viene chiamata in seguito ad una paginazione, è quindi necessario
 *                            caricare solamente 4 contenuti 
 */
function load_network(type, display, callback, trialNum, pagination) {
  var pagination = pagination?true:false;
  if ( trialNum == undefined ) {
    trialNum = 1;
	}
  var url = [];
//  url.push('fdsafds'); // Togliere il commento per forzare un errore AJAX.
  url.push(CD.settings['route_' + type]); // url di base
  
//  nel caso in cui il post da "aprire" sia in una pagina seguente alla prima, devo caricare n pagine
  var numToLoad = ( !pagination && hash_pieces(2) ||  hash_pieces(2) > 4) ? ''+( Number(hash_pieces(2))) : 4 ;
  
  var pag = (type=='facebook' && numToLoad > 4) ? (Math.floor(numToLoad/4) + 1) : 1;
  
  url.push((display == 'single') ? 4*pag : '1');
  if (CD.settings.last_shown[type]) {
    url.push(CD.settings.last_shown[type]);
  }
  var $wrapper = $('.placeholder.' + type + '-wrapper');
  var t = new Date();

  $.ajax({
    url: url.join('/') + '?' + t.getTime(),
    timeout: 15000, // 15s
    success: function(data){
      if (callback) {
        callback(data);
      }
      data = $(data).addClass(display);
      $wrapper.removeClass('placeholder').replaceWith(data);
      if (type == 'facebook') { // Re-parse FBML
        FB.XFBML.Host.parseDomTree();
        // Apre il post di FB corretto.
        fb_open_thread(hash_pieces(1));
      }
      if (type == 'twitter') {
        twttr.anywhere(function (T) {
          $twitterWrapper = $('.twitter-wrapper');
          $twitterPlaceholders = $('.shoutbox-placeholder:not(.processed)', $twitterWrapper).addClass('processed');
          $twitterPlaceholders.each(function(index, ph){
            T($(ph)).tweetBox({
              height: 50,
              width: ( ($.browser.msie && $.browser.version=="6.0") ? 300 : 600 ),
//              defaultContent: "RT:" + $('p', $(ph).parents('.wrapper')).text(),
              defaultContent: "@ideeperilfuturo ",
              onTweet: function(plainTweet, htmlTweet) {
                $(ph).replaceWith('<span class="message">Il tuo tweet &egrave; stato salvato correttamente.<span>');
                $.get(CD.settings['route_verify_twitter']);
              }
            });
          });
        });
      }
      show_or_hide_paginator();
    },
    error: function(data) {
      //  in caso di errore rilancio la richiesta
      if (trialNum < 2) {
        load_network(type, display, callback, ++trialNum);
      }//if
      else {
        $('.icon', $wrapper).after('<div class="social_error">Si &egrave; verificato un problema nel caricare i contenuti.</div>');
        $('.social_preloader', $wrapper).attr('src', '/images/social_error.gif');
      }//else
    }
  });
}

/**
 * Clona il prototipo di placeholder, lo specializza per un network e lo aggiunge prima
 * del placeholder.
 * 
 * Sostituisce la classe wrapper-prototype e il path dell'immagine ico_prototype.gif con
 * classe e src relativi al network.
 * 
 * @param type string uno dei 4 social network
 */
function network_placeholder(type) {
  $prototype = $('.prototype-wrapper:first');
  $placeholder = $prototype
    .clone()
    .removeClass('prototype-wrapper')
    /* 
     * Aggiunge la classe 'placeholder' per distinguere i placeholder dagli slot 
     * effettivi.
     */ 
    .addClass(type + '-wrapper placeholder');
  $image = $('img.icon', $placeholder);
  $image.attr('src', $image.attr('src').replace('prototype', type));
  $prototype.before($placeholder);
  $placeholder.show();
}

/**
 * Predispone ed effettua il caricamento di 4 slot relativi allo stesso network.
 * 
 * 1. Attiva lo stato attivo sul bottone di un network;
 * 2. Predispone i placeholder;
 * 3. Carica i risultati nei placeholder.
 * 
 * @param type string uno dei 4 social network
 */
function load_slots_single(type, pagination) {
  var pagination = pagination?true:false;

  $('#btn_' + type).addClass('btn_active');

  var numToLoad = ( !pagination && hash_pieces(2) ||  hash_pieces(2) > 4) ? ( Number(hash_pieces(2))) : 4 ;

  var pag = (type=='facebook' && numToLoad > 4) ? (Math.floor(numToLoad/4) + 1) : 1;
  
  for (var i=0; i<(4*pag) ; i++) {
    network_placeholder(type);
  }//for
  
/*  network_placeholder(type);
  network_placeholder(type);
  network_placeholder(type);*/

  load_network(type, 'single', null, null, true);
}

/**
 * Simula un click sul more di un post di facebook cosi' da presentarlo aperto.
 * @param fb_post_id
 */
function fb_open_thread(fb_post_id) {
  if (fb_post_id) {
    $('#' + fb_post_id + ' a.more').click();
  }
}

/**
 * Divide l'hash per / e ritorna l'indice indicato. Per l'indice 0, ritorna 'hp' anziche' ritornare null.
 * @param index 
 * @return string la parte dell'hash selezionata dall'indice.
 */
function hash_pieces(index) {
  var hash_pieces = document.location.hash.replace('#', '').split('/');
  if (index < hash_pieces.length) {
    return (hash_pieces[index]) ? hash_pieces[index] : 'hp';
  }
  return null;
}

function hash_set(hash) {
  document.location.hash = '#' + hash;
}

/**
 * Nasconde o mostra il link per la paginazione in funzione della pagina caricata o della presenza di ulteriori post.
 */
function show_or_hide_paginator() {
  var $more = $("#more_entries");
  var type = hash_pieces(0);
  (type == 'hp' || CD.settings.last_shown[type] == '-1') ? $more.hide() : $more.show();
}

$.fn.listHandlers = function(events) {
  return this.each(function(i){
      var elem = this,
          dEvents = $(this).data('events');
      if (!dEvents) {return;}
      $.each(dEvents, function(name, handler){
          if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
             $.each(handler, function(i,handler){
                 console.info(elem, '\n' + i + ': [' + name + '] : ' + handler );
                 console.info(elem);
                 console.info(handler);
             });
         }
      });
  });
};


