/*
 * Copyright (c) 2009, Matthias L. Jugel and Mikio Braun. All Rights Reserved.
 */

function twFixBrokenImage() {
  var userId = $(this).attr('class').split(' ')[0].substr(1);
  var userName = $(this).attr('alt');
  var userUrl = $(this).attr('src');

  $(this).unbind('error');
  $(this).attr('src', CONTEXT + '/images/missing-profile-image.png');

  $.ajax({
    url: TWROOT + 'api/error',
    type: 'POST',
    dataType: 'json',
    cache: false,
    async: true,
    data: {
      error: 'missingProfileImage',
      id: userId,
      name: userName,
      url: userUrl
    }
  });
}

function twAutoUpdate() {
  $.ajax({
    url: TWROOT + 'api/update',
    type: 'POST',
    data: { 'currentUrl': location.toString() },
    dataType: 'json',
    cache: false,
    async: true,
    success: function(updatedTweetList, status) {
      var currentTweetList = $('ul#tweet-list li.tweet');
      for (var i = 0; i < currentTweetList.length && i < updatedTweetList.length; i++) {
        if (currentTweetList[i].id && currentTweetList[i].id != updatedTweetList[i].id) {
          var listEntry = $(currentTweetList[i]);
          listEntry.attr('id', updatedTweetList[i].id);
          listEntry.html(updatedTweetList[i].content);
          listEntry.find('img').error(twFixBrokenImage);
          listEntry.effect('highlight', {color: '#ff6666'}, 3000);
        }
      }
    }
  });
}

$(document).ready(function() {
  $('#activesearch').autocomplete(TWROOT + 'api/autocomplete', { });
  $('div.user-image img').error(twFixBrokenImage);

  if ($('ul#tweet-list li').length > 0) {
    if (location.pathname == CONTEXT + '/') {
      $(document).everyTime('10s', twAutoUpdate, true);
    } else {
      $(document).everyTime('30s', twAutoUpdate, true);
    }
  }
  if ($('div#iphone-teaser').length > 0) {
    $(document).oneTime('5s', function() {
      $('div#iphone-teaser').fadeIn("slow");
    });
    $(document).oneTime('20s', function() {
      $('div#iphone-teaser').fadeOut("slow");
    });
  }
});
