/*
 * 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 twRetweetThis() {
  var message = $(this).parent().find('input[name=message]').attr('value');
  var textArea = $('div#dialog-retweet textarea:first');
  var cancelButton = $('div#dialog-retweet input[name="dialog-cancel-button"]');
  var submitButton = $('div#dialog-retweet input[name="dialog-submit-button"]');

  submitButton.removeAttr('disabled');
  textArea.removeAttr('disabled');
  textArea.val(message);

  $('div#dialog-retweet div.login-status').css('display', 'none');
  $('div#dialog-retweet').dialog('open');

  var counterDiv = $('div#dialog-retweet .counter');
  textArea.NobleCount('div#dialog-retweet .counter', {
    max_chars: 140,
    on_negative: function(t_obj, char_area, c_settings, char_rem) {
      counterDiv.removeClass('counter-positive').addClass('counter-negative');
      submitButton.attr('disabled', 'true').removeClass('enabled').addClass('disabled');
    },
    on_positive: function(t_obj, char_area, c_settings, char_rem) {
      counterDiv.removeClass('counter-negative').addClass('counter-positive');
      if (char_rem < c_settings.max_chars) {
        submitButton.removeAttr('disabled').removeClass('disabled').addClass('enabled');
      } else {
        submitButton.attr('disabled', 'true').removeClass('enabled').addClass('disabled');
      }
    }
  });

  textArea.focus();
  return false;
}

function twInitRetweetDialog() {
  var cancelButton = $('div#dialog-retweet input[name="dialog-cancel-button"]');
  var submitButton = $('div#dialog-retweet input[name="dialog-submit-button"]');

  var textArea = $('div#dialog-retweet textarea:first');

  // enable clicks on retweet-dialog form
  cancelButton.click(function() {
    $('div#dialog-retweet').dialog('close');
    textArea.val('');
  });
  submitButton.click(function() {
    var message = textArea.val();
    textArea.attr('disabled', 'true');
    submitButton.attr('disabled', 'true');
    $('div#dialog-retweet div.login-status').css('display', 'block');
    $.ajax({
      url: TWROOT + 'tweet',
      type: 'POST',
      data: {message: message, type: 'ajax'},
      dataType: 'json',
      cache: false,
      async: true,
      success: function(jsonData) {
        if (jsonData != null && jsonData['redirect']) {
          window.location = jsonData['redirect'];
          return;
        } else {
          $('div#dialog-retweet').dialog('close');
        }
        textArea.val('');
        $('div#dialog-retweet div.login-status').css('display', 'none');
      },
      error: function(req, status, err) {
        console.log(err);
        $('div#dialog-retweet').dialog('close');
      }
    });
    //    $('div#dialog-retweet form:first').trigger('submit');
  });

  $('div#dialog-retweet').dialog({
    autoOpen: false,
    width: '550px',
    modal: true,
    resizable: false
  });
}

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.effect('highlight', {color: '#ff6666'}, 3000);
          listEntry.find('img').error(twFixBrokenImage);
          listEntry.find('span.retweet-message a').click(twRetweetThis);
        }
      }
    }
  });
}

$(document).ready(function() {
  $("a[href^='http:']:not([href*='" + window.location.host + "'][target='_blank'])").live('click', function() {
    $(this).attr('target', '_blank');
  });


  $('#activesearch').autocomplete({
    source: TWROOT + 'api/autocomplete',
    minLength: 2,
    select: function(event, ui) {
      $('#appendix form:first').trigger('submit');
    }
  });
  $('div.user-image img').error(twFixBrokenImage);
  $('span.retweet-message a').click(twRetweetThis);
  twInitRetweetDialog();

  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");
    });
  }
});
