// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function addFollow(user) {
  $('followloading').show();
  new Ajax.Request('/api/friendships/create/' + user, {
    onSuccess: function(transport) {
      $('followloading').hide();
      $('followbuttons').replace(transport.responseText);
    },
    onFailure: function(transport) {
      $('followloading').hide();
      $('removebutton').show();
      alert("Sorry, there was an error following this user.  Please try again.");
    }
  });
}

function removeFollow(user) {
  $('removebutton').hide();
  $('followloading').show();
  new Ajax.Request('/api/friendships/destroy/' + user, {
    onSuccess: function(transport) {
      $('followloading').hide();
      $('followbuttons').replace(transport.responseText);
    },
    onFailure: function(transport) {
      $('followloading').hide();
      alert("Sorry, there was an error unfollowing this user.  Please try again.");
    }
  });
}

function focusLogin() {
  if ($('new_user_username')) {
    $('new_user_username').focus();
  }
}

function updateNewPostCount(type) {
  var messagebox = $(type+'_post_status')||$('new_post_message');
  var new_count = 140 - messagebox.value.length; 

  if (new_count >= 30) {
    $(type+'_post_count').style.color = '#999';
  }
  else if (new_count < 30 && new_count >= 10) {
    $(type+'_post_count').style.color = '#c00';
  }
  else if (new_count < 10) {
    $(type+'_post_count').style.color = '#f00';
  }
  
  $(type+'_post_count').update(new_count);
  if(new_count < 0) {
    $(type+'_post_count').addClassName('negative')
  } else {
    $(type+'_post_count').removeClassName('negative')
  }
  
  var shorten_urls = $(type+'_shorten_urls')||$('new_shorten_urls');
  if(/\bhttps?:\/\/\S\S+\b/.test(messagebox.value) ||
     /\bwww\.\S\S+\b/.test(messagebox.value)) {
     shorten_urls.show();
  } else {
    shorten_urls.hide();
  }
}

function shortenUrls(type) {
  var messagebox = $(type+'_post_status')||$('new_post_message');
  var indicator = $(type+'_post_indicator')||$('new_post_indicator');
  
  messagebox.disable();
  indicator.show();
  
  new Ajax.Request('/api/shorten_urls', {
    parameters: { status: messagebox.value },
    onSuccess: function(transport) {
      messagebox.value = transport.responseText;
      messagebox.enable();
      indicator.hide();
      updateNewPostCount(type);
    },
    onFailure: function(transport) {
      messagebox.enable();
      indicator.hide();
    }
  });
}

function postSubmit(type, submit_id) {
  var new_count = 140 - $(type+'_post_status').value.length; 
  
  if(new_count < 0) {
    alert("Please shorten your post to under 140 characters");
    return false;
  } else {
    $(submit_id).disable()
    return true;
  }
}

function changeDMTab(tab) {
  if (tab == 'inbox') {
    $('inboxtab').addClassName('current');
    $('senttab').removeClassName('current');
    $('inbox').show();
    $('sent').hide();
  }
  else if (tab == 'sent') {
    $('senttab').addClassName('current');
    $('inboxtab').removeClassName('current');
    $('sent').show();
    $('inbox').hide();
  }
}

function showReplyForm(post_id, username) {
  $('post_in_reply_to_status_id').value = post_id;
  $('tweet_' + post_id).insert($('reply_post_form'));
  $('reply_post_form').show();
  $('reply_post_status').focus();
  $('reply_post_form')['reply_post_status'].value = '@' + username + ' ';
  updateNewPostCount('reply');
 
  return false;
}

function showRetweetForm(post_id, content) {
  $('post_in_reply_to_status_id').value = '';
  $('tweet_' + post_id).insert($('reply_post_form'));
  $('reply_post_form').show();
  $('reply_post_status').focus();
  $('reply_post_form')['reply_post_status'].value = content;
  updateNewPostCount('reply');
  
  return false;
}

function toggleFavorite(link, post_id) {
  link = $(link);
  if(link.hasClassName('favorite_link')) {
    link.addClassName('loading_link');
    new Ajax.Request('/api/favorites/create/' + post_id, {
      onSuccess: function(transport) {
        link.removeClassName('loading_link');
        link.removeClassName('favorite_link');
        link.addClassName('favorited_link');
      },
      onFailure: function(transport) {
        link.removeClassName('loading_link');
        alert("Sorry, there was an error favoriting this post.  Please try again.");
      }
    });
  } else if(link.hasClassName('favorited_link')) {
    link.addClassName('loading_link');
    new Ajax.Request('/api/favorites/destroy/' + post_id, {
      onSuccess: function(transport) {
        link.removeClassName('loading_link');
        link.removeClassName('favorited_link');
        link.addClassName('favorite_link');
      },
      onFailure: function(transport) {
        link.removeClassName('loading_link');
        alert("Sorry, there was an error un-favoriting this post.  Please try again.");
      }
    });
  }
  
  return false;
}

function showFullConversation(reply_id, post_id) {
  $(post_id).down('.full_conversation_link').addClassName('loading_link');
  new Ajax.Request('/api/status/show/' + reply_id, {
    method: 'get',
    onSuccess: function(transport) {
      $(post_id).down('.full_conversation_link').removeClassName('loading_link');
      $('post_' + reply_id).remove();
      $(post_id).replace(transport.responseText);
      $$('.pending .url').each(function(url) {
        new Ajax.Request('/api/url/' + url.innerHTML, {
          method: 'get',
          onSuccess: function(transport) {
            url.removeClassName('pending').replace(transport.responseText);
          }
        });
      });
      $$('.more_link').invoke('observe', 'click', function(e) {
       protoMenu.show(e);
      });
    },
    onFailure: function(transport) {
      $(post_id).removeClassName('loading_link');
      alert("Sorry, there was an error retrieving this conversation.  Please try again.");
    }
  });
  
  return false;
}

function saveSearch(search_query) {
  $('saved_search_loading').show();
  new Ajax.Request('/api/saved_searches/save', {
    parameters: { query: search_query },
    onSuccess: function(transport) {
      location.reload(true);
    },
    onFailure: function(transport) {
      $('saved_search_loading').hide();
      alert("Sorry, there was an error saving this search.  Please try again.");
    }
  });

  return false;
}

function removeSavedSearch(search_id) {
  $('saved_search_loading').show();
  new Ajax.Request('/api/saved_searches/delete/' + search_id, {
    onSuccess: function(transport) {
      location.reload(true);
    },
    onFailure: function(transport) {
      $('saved_search_loading').hide();
      alert("Sorry, there was an error removing this saved search.  Please try again.");
    }
  });

  return false;
}

function errorMessageByResponse(transport) {
  switch(transport.status) {
    case 400:
      return "This user has protected their updates.";

    case 401:
      response = transport.responseText.evalJSON();
      if(response['error'] == 'Could not authenticate you.')
        return "Unable to authenticate you with Twitter.  Try logging out of Tweetree and logging back in.";
      else
        return "This user has protected their updates.";

    case 403:
      response = transport.responseText.evalJSON();
      if(response['error'])
        return response['error'];
      else
        return "Sorry, there was an error communicating with Twitter.  Please try again.";
    
    case 404:
      return "Sorry, that page doesn't exist!";
    
    case 500:
      return "Sorry, Twitter didn't respond to our request.  Please try again shortly.";
    
    case 502:
      return "Sorry, Twitter didn't respond to our request as they are down for maintenance.";
    
    case 503:
      return "Sorry, Twitter didn\'t respond to our request.  Please try again shortly.";
    
    default:
      return "Sorry, there was an error communicating with Twitter.  Please try again.";
  }
}
