// init los componentes necesarios para los comentarios
function initComentarios() {

  // agregar comentarios
  $(function() {
      var onClick = function(e) {
          e.preventDefault();
/*
          var options = getOptions('#comentarios-formulario');
*/
          var url = $(this).attr('href');
          // Si la url tiene anchor (#), lo usa para bajar la pagina hasta su posicion
          // Hay que quitarlo (el '#' y todo despues) en la url tambien para que funcione
          var split = url.split('#');
          var scroll_target = false;
          if(split.length > 1) {
              var url = split[0];
              var scroll_target = $('#' + split[1]);
          }
  //        options.url = url;

          // esto realmente deberia ser .ajax, porque no es un formulario
    //      $(this).ajaxSubmit(options);

          if(scroll_target && scroll_target.length > 0) {
              $("html:not(:animated), body:not(:animated)").animate(
                  {scrollTop: scroll_target.offset().top},
                  1000
              );
          }


          return false;
    };
    $('#comentarios').find('.deja-tu-comentario').click(onClick);
    $('div.tira-utilidades').find('.deja-tu-comentario').click(onClick);
  });

  // procesar comentarios
  $(function() {
    $('#envia-comentario').live('submit', function(event) {
      event.preventDefault();

      var options = getOptions('#comentarios-formulario');
      options.beforeSerialize = function(form) {
        encodeToBase64(form);
      };

      options.success = function(response) {
          $('#comentarios-formulario').html(response);
          isLoggedinFacebook();
      };

      $(this).ajaxSubmit(options);

       return false;
      });
  });

  // Active links de abuso
  $(function() {
    $('#comentarios').find('.abuso-link').click(function(e) {

      getForm(e, $(this), 'abuso', 'respuesta');
    });
  });

  // procesar abuso
  $(function() {
      var comentarios = $('#comentarios');
      $('.abuso', comentarios[0]).find('form').live('submit', function(e) {
          processForm(e, $(this), 'abuso');
      });
  });

  // Votar a favor/contra
  $(function() {
    $('.voteBtn').bind('click', function(event) {
      event.preventDefault();
      var self = $(this);
      var href = self.attr('href');

      var options = getOptions(self);
      options.url = href;

      options.success = function(response) {
        self.parent().parent().find('.voteBtn').unbind('click');
        self.removeAttr('href').html(response);
        self.removeClass('cero');
        self.parents('ul').find('a').removeAttr('href');
      };

      $(this).ajaxSubmit(options);

      return false;

    });
  });

  // Active links de responder
  $(function() {
    $('#comentarios').find('.respuesta-link').click(function(e) {

      getForm(e, $(this), 'respuesta', 'abuso');

    });
  });

  // procesar responder
  $(function() {
        var comentarios = $('#comentarios');
        $('.respuesta', comentarios[0]).find('form').live('submit', function(e) {
            processForm(e, $(this), 'respuesta');
        });
  });

  // Limite el numero de caracters en el textfield
  $(function() {
    var scrollTop;
    $('#area_comentario').live('keyup', function(event) {
      if ($(this).val().length > 1000) {
        $(this).val($(this).val().substring(0, 1000));
        $(this).scrollTop(scrollTop); // Para que no salte el scroll
      }
      scrollTop = $(this).scrollTop();
    });
  });

  $(function() {
    $('#comentarios').find('.cite').find('em').click(function(e) {
      e.preventDefault();
      if ($(this).hasClass('abierto')) {
        $(this).removeClass('abierto').parent() // h3
            .parent() // li
            .parent() // em
            .find('.blockquote').slideUp('fast');
      } else {
        $(this).addClass('abierto').parent() // h3
            .parent() // li
            .parent() // em
            .find('.blockquote').slideDown('fast');
      }
    });
  });

}

function processForm(e, me, css) {
  e.preventDefault();

  // ID del comentario
  var id = me.find(':hidden[name="parent_id"]').val();

  divResponse = '#aux-comentario-' + id;

  var options = getOptions(divResponse);

  options.beforeSerialize = function(form) {
    encodeToBase64(form);
  };

  options.success = function(response) {
    var $div = $(divResponse);
    $div.html(response);

    var link = $div.parent().find('.' + css + '-link');

    // activa link para cerrar div
    $div.find('.ocultar').click(function(e) {
      e.preventDefault();
      link.removeClass('abierto');
      $div.slideUp('fast');
    });
  };

  me.ajaxSubmit(options);

  return false;
}

function getForm(e, me, css, closeCss) {
  e.preventDefault();

  var aux_div = me.parent().parent().parent().find('div.aux-comentario');
  var link = me;

  if (me.hasClass('abierto')) {
    me.removeClass('abierto');
    aux_div.slideUp('fast');
  } else {
    me.addClass('abierto');
    me.parent().parent().parent().find('.' + closeCss + '-link')
        .removeClass('abierto');

    // evita repitir la peticion si el formulario ya
    // esta en el div
    if (aux_div.hasClass(css)) {
      aux_div.slideDown('fast');
    } else {
      aux_div.removeClass().hide().addClass('aux-comentario ' + css);

      var options = getOptions(aux_div);

      var url = me.attr('href');
      options.url = url;

      options.success = function(response) {
        aux_div.html(response);
        aux_div.slideDown('fast');
        aux_div.find('.ocultar').click(function(e) {
          e.preventDefault();
          link.removeClass('abierto');
          aux_div.slideUp('fast');
        });
      };

      me.ajaxSubmit(options);
    }
  }
}

function encodeToBase64(form) {
  $(form).find('#comentario').val(
      $.base64Encode($(form).find('#area_comentario').val()));
}

function getOptions(canvasResponse) {

  var options = {
    dataType : 'jsonp',

    success : function(response) {
      $(canvasResponse).html(response);
    }
  };

  return options;
}

function isLoggedinFacebook() {
  var cookie = $.cookie('Proyectoi-Facebook');
  cookie = cookie ? $.parseJSON(cookie) : false;

  if (cookie && cookie.logged) {
    initFacebook();
  }
}

function initFacebook() {
  FB.ensureInit(function() {
    FB.Facebook.get_sessionState().waitUntilReady(function(session) {
      var is_now_logged_into_facebook = session ? true : false;

      if(is_now_logged_into_facebook) {
          FBPostComment($('#area_comentario').attr('value'));
          comentario_emailoptin('recibiremail_confirmacion');
      }
    });
  });
}

function comentario_emailoptin(checkbox_id) {
  if (!FB) {
    return;
  }
  var selector = $('#' + checkbox_id);
  if (!selector[0]) {
    return;
  }
  var label = $('label[for="' + checkbox_id + '"]');

  FB.ensureInit(function() {
    FB.Facebook.apiClient.users_hasAppPermission('email', function(perm) {
      var has_perm = (perm == '1');
      // si ya tiene permiso, no hace nada
        if (!has_perm) {
          // muestra el checkbox para que pueden darse de alta
        addListener();
        selector.show();
        label.show();
        selector.attr('checked', false);
      }
    });
  });

  var addListener = function() {
    selector.bind('click', function(e) {
      // no hace el 'check' hasta que haya selecionado si o no en la
        // ventana de facebook
        e.preventDefault();
        FB.Connect.showPermissionDialog("email", function(perm) {
          if (perm) {
            selector.attr('checked', true);
            selector.attr('disabled', true);
          } else {
            selector.attr('checked', false);
          }
        });
      });
  };
}
