// define console.log so things don't explode without firebug enabled
if (window.console == null) {
  window.console = {
    log: function(){}
  };
}

// http://snook.ca/archives/javascript/testing_for_a_v/
function oc(a) {
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

// TODO refactor!  this is icky.  but, right now, i just want to get everything working!

// add a profile to your list - for the home page (list creation)
function add_profile( name ) {
  name = name.toLowerCase().replace(/[^_a-zA-Z0-9]/g, '');
  var profile_element = $('.twitter_profile.' + name);
  if (profile_element.length > 0) {
    console.log('profile already added: ' + name);
  } else {
    console.log('adding profile: ' + name);
    $.get('/twitter_profile/' + name, function(html){
      $('#profiles').append(html);
      initialize_twitter_profile(name);
      var field = 'input[name="list[names]"]';
      $(field).val( $(field).val() + name + ',' );
    });
  }
}

// if there's a div.twitter_profile.username, 
// this will initialize it with additional twitter info
function initialize_twitter_profile( name ) {
  // if it has an image, it's been processed
  var image_that_is_added_during_initialization = $('.twitter_profile.' + name + ' img');
  if (image_that_is_added_during_initialization.length > 0) {
    console.log('twitter profile already initialized for ' + name);
  } else {

    // get twitter data and, once you have it, initialize 
    // the profile and fill in the timeline
    console.log('requesting http://twitter.com/statuses/user_timeline/' + name + '.json?callback=?');

    // doing this *before* ajax call because we need to be able to remove names that aren't 
    // valid (no callback!)
    var element = $('.twitter_profile.' + name);
    var name_span = element.find('span.name');
    var remove_link = $('<a href="#" rel="' + name + '" class="remove">remove</a>');
    remove_link.click(function(){
      name = $(this).attr('rel');
      console.log('removing ' + name + ' from list');
      $('.' + name).remove();

      // remove from the actual hidden field where we track the names
      var names_field = $('#names_field input[name="list[names]"]');
      names_field.val( names_field.val().replace(name + ',', '') );
    });
    name_span.append(remove_link);

    // old - calls twitter
    // $.getJSON('http://twitter.com/users/show/' + name + '.json?callback=?', function(data) {

    // new - calls server-side so we don't eat up people's API calls, which is not nice to do!
    $.getJSON('/twitter_profile/' + name + '.json?callback=?', function(data) {

      console.log('data:');
      console.log(data);

      var user = data;
      console.log('got tweets for ' + user.screen_name);
      console.log(user);
    
      console.log('looking for user profile element: "' + '.twitter_profile.' + user.screen_name.toLowerCase() + '"');

      var element = $('.twitter_profile.' + user.screen_name.toLowerCase());
      console.log('twitter user profile element: ');
      console.log(element);
      var image_link = $('<a href="http://twitter.com/' + user.screen_name + '" title="' + user.name + '"></a>')
      image_link.append('<img src="' + user.profile_image_url + '" />');
      element.prepend(image_link)
      element.append('<span class="description">' + user.description + '</span>')

      var name_span_link = element.find('span.name>a.name');
      name_span_link.text(user.name); // update name to show twitter display name
      name_span_link.attr('title', user.name);

      /* // DISABLING TIMELINE
      var list     = $('#list');
      var timeline = $('ul.timeline');
      if (timeline.length == 0) {
        console.log('initializing timeline');
        list.append('<h3 class="timeline">Timeline</h3>');
        list.append('<ul class="timeline"></ul>');
        timeline = $('ul.timeline');
      }

      for(var i in data){
        var tweet = data[i];
        timeline.append('<li>' + tweet.user.screen_name + ': ' + tweet.text + '</li>');
      }
      */

    });
  }
}

$(function(){

    $('#name_field>input').focus(function(){
      if ($(this).val() == 'Name your follow list') $(this).val('');
    });
    $('#name_field>input').blur(function(){
      if ($(this).val() == '') $(this).val('Name your follow list');
    });

    $('input[name="list[names]"]').focus(function(){
      if ($(this).val() == 'List profiles (comma separated)') $(this).val('');
    });
    $('input[name="list[names]"]').blur(function(){
      if ($(this).val() == '') $(this).val('List profiles (comma separated)');
    });

    $('input[name="list[names]"]').hide().val('');

    // add new fields to homepage
    $('#names_field>input').before("<input type='text' id='profile_to_add' name='profile_to_add' value='Add profile to list' />");
    $('#profile_to_add').after("<input type='button' class='button' id='add_profile_button' name='add_profile_button' value='Add' />");
    $('#add_profile_button').after("<div id='profiles'></div>");

    $('#profile_to_add').focus(function(){
      if ($(this).val() == 'Add profile to list') $(this).val('');
    });
    $('#profile_to_add').blur(function(){
      if ($(this).val() == '') $(this).val('Add profile to list');
    });

    $('#profile_to_add').keydown(function(event){
      if (event.keyCode == 13) {
        var username = $('#profile_to_add').val();
        add_profile( username );
        $('#profile_to_add').val('');
        return false;
      }
    });

    $('#add_profile_button').click(function(){
      var username = $('#profile_to_add').val();
      add_profile( username );
      $('#profile_to_add').val('');
    });

    $('form#list').submit(function(){
      console.log('captured form submission');
      var list_name  = $('input[name="list[name]"]').val();
      var list_names = $('input[name="list[names]"]').val();
      console.log('creating list with name: ' + list_name + ' names: ' + list_names);
      
      var button = $('#submit_field>input[type=submit]');
      button.val('... creating list ...');
      button.attr("disabled", true);  // button.removeAttr("disabled"); 

      $.post('/', { 'list[name]': list_name, 'list[names]': list_names }, function(list){
        if (list == null) {
          alert('there was a problem creating your list');
        } else {
          // alert('list created at http://' + window.location.host + '/' + list.slug);
          button.val('Created!');
          var sharing_info = $('<div id="sharing_info"></div>');
          button.after(sharing_info);
          sharing_info.load('/sharing_info/' + list.slug);
        }
      }, 'json');

      return false;
    });

    $('.twitter_profile').each( function(i, profile) {
      var element   = $(profile);
      var classes   = element.attr('class').split(' ');

      if ('nojs' in oc($($('.twitter_profile')[0]).attr('class').split(' '))){
        // this twitter_profile is marked with nojs, meaning ... do nothing!
      } else {
        var name_span = element.find('span.name');
        var name      = name_span.text().toLowerCase();
        var image     = element.find('>img')

        var image_that_is_added_during_initialization = $('.twitter_profile.' + name + ' img');
        if (image_that_is_added_during_initialization.length > 0) {
          console.log('profile already intitialized for: ' + name);
        } else {
          console.log('initializing profile for: ' + name);
          element.addClass(name.toLowerCase());
          initialize_twitter_profile(name);
        }
      }
    });
  
});
