$(document).ready(function() {
  var small_fav = false;
  var message_status_interval = 0;

  function clearStatusMessage() {
    $('#status_message').hide('slow');
  }

  $('.favourite_button').hover(function(event) { // in - We want to show the opposite image to the current one
    ($(this).attr('data-small')=='small') ? small_fav=true : small_fav=false;
    (small_fav == true) ? small_extra="_small" : small_extra="";
    ($(this).attr('data-status')=='on') ? favourite_status='off' : favourite_status='on';
    $(this).attr('src', '/action/images/buttons/fone-me.com/favourite_'+favourite_status+small_extra+'.png');
  }, function(event) { // out - Once they hover out we want to show the current status of their favouritation
    (small_fav == true) ? small_extra="_small" : small_extra="";
    $(this).attr('src', '/action/images/buttons/fone-me.com/favourite_'+$(this).attr('data-status')+small_extra+'.png');
  });

  $('.favourite_button').click(function(event) {
    clearTimeout(message_status_interval);
    event.preventDefault(); // If javascript isn't enabled then this won't get called (duh) and the href below will work instead. Look at that planning!
    ($(this).attr('data-status')=='on') ? favourite_status='off' : favourite_status='on';
    $(this).attr('data-status', favourite_status);
    (small_fav == true) ? small_extra="_small" : small_extra="";
    $(this).attr('src', '/action/images/buttons/fone-me.com/favourite_'+favourite_status+small_extra+'.png');
    
    var babenumber = $(this).attr('data-babenumber');

    $.get("/xmlrpc/xmlrpc_favourite_operator", { operator: babenumber, xmlrpc: "1", status: favourite_status },
      function(data){
	//woo - We're not going to check the response. We'll assume it worked.
      }
    );

    if(favourite_status == 'on') {
      message = "Added " + $(this).attr('data-nick') + " as a favourite";
    } else {
      message = "Removed " + $(this).attr('data-nick') + " as a favourite";
    }

    $('#status_message').hide();
    if($('#status_message').length == 0) { // Only add the status_message div once, then re-use it after that.
      //$('#topbar_submenu').html('').prepend('<div style="text-align:left";width:95%;font-weight:bold;color: #ddd;" id="status_message">'+message+'</div>');
      $('#topbar_submenu').prepend('<div style="text-align:left;float:left;margin-left:5px;margin-right:35px;";font-weight:bold;color: #ddd;" id="status_message">'+message+'</div>');
    } else {
      $('#status_message').html(message);
    }
    $('#status_message').show();

    if(small_fav && $(this).attr('data-parent-hide') != 0 && $(this).attr('data-parent-hide') != '0') {
      $(this).parent().hide();
    }

    message_status_interval = setTimeout(clearStatusMessage, 2400);
  });
});
