function share_this(site) {
  var shareURL = "";
  var URL = window.document.location.href;

  if (URL.charAt(URL.length - 1) == "#") {
    URL = URL.substring(0, URL.length-1);
  }

  var titleURL = encodeURIComponent(window.document.title);

  if (site == 'meneame') {
    shareURL = 'http://meneame.net/submit.php?url=' + URL;
  } else if (site == 'delicious') {
    shareURL = 'http://delicious.com/post?title=' + titleURL + '&url=' + URL;
  } else if (site == 'digg') {
    shareURL = 'http://digg.com/submit?phase=2&url=' + URL + '&title=' + titleURL;
  } else if (site == 'facebook') {
    shareURL = 'http://www.facebook.com/sharer.php?u=' + URL;
  } else if (site == 'twitter') {
    shareURL = 'http://twitter.com/home?status=' + titleURL + '+-+' + URL;
  }

  if (shareURL != "") {
    window.open(shareURL);
  }

  return false;
}

function logged_in() {
  return ($('.logged').html() != null);
}

function display_reply_form(comment_id) {
  if (logged_in()) {
    var html ='<br class="vacio" />';
    html += '<form id="comment_reply" action="/comments/' + comment_id + '/reply" method="post">';
    html += '<input type="hidden" value="' + window._token + '" name="authenticity_token" />';
    html += '<div class="title"><b>Escribe aquí tu respuesta al comentario:</b></div>';
    html += '<div class="body bluebox"><textarea name="comment_reply" cols="60" rows="10" class="campos2"></textarea>';
    html += '<br /><input name="Responder" type="submit" value="Responder" class="button" /></div></form>';

    $("#comentario-" + comment_id + " .comment-form").html(html);
    $("#comentario-" + comment_id + " .comment-form").show();
  } else {
    jConfirm("Responder a comentario", "Para poder responder a un comentario debes ser usuario registrado. ¿Deseas registrarte ahora?", function() {
      document.location.href = "/signup";
    });
  }

  return false;
}

function display_status_reply_form(login, status_id) {
  if (logged_in()) {
    var html ='<br class="vacio" />';
    html += '<form id="comment_reply" action="/' + login + '/statuses/' + status_id + '/reply" method="post">';
    html += '<input type="hidden" value="' + window._token + '" name="authenticity_token" />';
    html += '<div class="title"><b>Escribe aquí tu respuesta al mensaje de estado:</b></div>';
    html += '<div class="body bluebox"><textarea name="comment_reply" cols="60" rows="10" class="campos2"></textarea>';
    html += '<br /><input name="Responder" type="submit" value="Responder" class="button" /></div></form>';

    $("#comentario-" + status_id + " .comment-form").html(html);
    $("#comentario-" + status_id + " .comment-form").show();
  } else {
    jConfirm("Responder a mensaje de estado", "Para poder responder a un mensaje de estado debes ser usuario registrado. ¿Deseas registrarte ahora?", function() {
      document.location.href = "/signup";
    });
  }

  return false;
}

function report_abuse(url) {
  jConfirm("Denunciar comentario", "¿Está seguro de querer denunciar este comentario?", function() {
    document.location.href = url;
  });
}

function switch_panel(panel_to_show, panel_to_hide) {
  var li_to_disable = '#li_' + panel_to_hide;
  var li_to_enable  = '#li_' + panel_to_show;
  var div_to_hide   = '#' + panel_to_hide;
  var div_to_show   = '#' + panel_to_show;

  // Pestañas
  var li_to_disable_content = $('#li_' + panel_to_hide).html();
  var li_to_enable_content = $('#li_' + panel_to_show + ' > a').html();

  $(li_to_enable).addClass('current');
  $(li_to_enable).html(li_to_enable_content);

  $(li_to_disable).removeClass('current');
  $(li_to_disable).html('<a href="#" onclick="switch_panel(\'' + panel_to_hide + '\', \'' + panel_to_show + '\'); return false;">' + li_to_disable_content + '</a>');

  // Divs con el contenido
  $(div_to_hide).slideUp("fast");
  $(div_to_show).slideDown("fast");
}

function check_all(id, parentId) {
  $( "#" + parentId + " :checkbox").attr('checked', $('#' + id).is(':checked'));
}

function toggle_chat(canal, nickname) {
  var html = '';

  if ($('#chatbutton').hasClass('active')) {
    $('.chat_container').slideUp('slow');
    $('.chat').html(html);
    $('#chatbutton').html('Entrar al chat');
    $('#chatbutton').removeClass('active');
  } else {
    html = '<iframe width="100%" height="400" src="http://futbol.irc-hispano.es?canal=' + canal + '&nick=';

    if (nickname != null) {
      html += nickname;
    }

    html += '" frameborder="0"></iframe>';

    $('.chat').html(html);
    $('.chat_container').slideDown('slow');
    $('#chatbutton').html('Salir del chat');
    $('#chatbutton').addClass('active');
  }
}

function scroll_to(anchor) {
  var destination = $(anchor).offset().top;
  $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, 1200);
}

function valorizar() {
  jQuery.each($('.ctrl_valorizar'), function(){
    var ident = this.id.split("_"); 
      /* 
      * ident[0] cadena no utilizada
      * ident[1] class
      * ident[2] id
      */
    var key       = ident[1] + "_" + ident[2];
    var disabled  = ' disabled="disabled"';
    var ratecount = $(this).attr('ratecount');
    var rateavg   = Math.round($(this).attr('rateavg'));
    var votos     = this.innerHTML;
    var user_data  = "";
    if(logged_in()){
      disabled='';
      user_data = '<input type="hidden" name="model_id"   value="'+ident[2]+'"/>';
      user_data += '<input type="hidden" name="model_type" value="'+ident[1]+'"/>';
    }
    

    var form= '<form action ="/rateit/'+ident[2]+'" method="POST" name="valoracion_'+key+'">';
    for(var i=1;i<6;i++){
      var cheched="";
      if (i==rateavg){
        cheched=' checked="checked"';
      }
      form +='<input name="usrrate_'+key+'" value="'+i+'" type="radio" class="usrrate_'+key+'"'+cheched+disabled+'/>'     
    }
    form += user_data;
    form += '</form>';
    
    this.innerHTML=form + votos;
    if(logged_in()){
      rateit(key,"true");
    }else{
      rateit(key,"false");
      ratestarmsg(0);
    }
  });
}

function ratestarmsg(code_msg){
  var mensajes=new Array();
  mensajes[0]="Debe estar logueado para votar";
  jQuery.each($('div..star-rating-readonly a'), function(){
    this.title= mensajes[code_msg];
    this.html = mensajes[code_msg];;
  }); 
}

function rateit(key,vota){
  $('.usrrate_'+key).rating({
    required: 'hide'
  });
  if (vota=="true") {
    $('.usrrate_'+key).click(function(){
      var f = $(this).parents('form');
      $.ajaxSetup({
        beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
      });
      $.ajax({
        type: "POST",
        url: f.attr('action'),
        data: f.serialize(),
        dataType: "script"
      });
    });
  }
}

$(document).ready(function () {
  $("#comentarios .pagination a").live("click", function() {
    scroll_to("#comentarios");
    $(".pagination").html('<img src="/images/common/ajax-loader.gif" alt="Cargando..." />');
    $.getScript(this.href);
    return false;
  });
  $('.timeago').timeago();

  $.getScript('/javascripts/jquery.metadata.js');
  $.getScript('/javascripts/star-rating/jquery.rating.js', function() {
    valorizar();
  });
});

function remove_fields(link) {
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest(".fields").hide();
}

function add_fields(link, association, content, model_type) { 
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_"+association+"_image", "g");
  content = content.replace(regexp, new_id+"_image");
  regexp = new RegExp("new_"+association, "g");
  content = content.replace(regexp, new_id);
  $(link).parent().before(content); 
  tinyMCE.execCommand('mceAddControl', false, model_type+'_'+association+'_attributes_'+new_id+'_excerpt');
}