/* Extend jQuery with functions for PUT and DELETE requests. */

function _ajax_request(url, data, callback, type, method) {
  if (jQuery.isFunction(data)) {
    callback = data;
    data = {};
  }
  return jQuery.ajax({type: method, url: url, data: data, success: callback, dataType: type});
}

jQuery.extend({
  put: function(url, data, callback, type) {
    return _ajax_request(url, data, callback, type, 'PUT');
  },
  delete_: function(url, data, callback, type) {
    return _ajax_request(url, data, callback, type, 'DELETE');
  }
});


// Find the index of the first item in the array whose first element matches.
function find_item_index(items, match) {
  for (var idx in items) {
    if (items[idx][0] == match) {
      return parseInt(idx);
    }
  }
}


/* application-specific functionality */

$(function() {

  // Hide JavaScript requirement warnings.
  $('.js-required').hide();

  // Focus form elements.
  $('form .focus').focus();
  $('[autofocus]').focus();

  // Activate tooltips.
  $('#calendar tbody a').tipsy({delayOut: 1750, gravity: 's', html: true, title: function() {
    return $(this).prev('span').html();
  }});
  $('table.games [title]').tipsy({gravity: 's'});
  $('.board .topic a.title').tipsy({delayOut: 1750, gravity: 's', html: true, title: function() {
    return $(this).siblings('.pagelinks').html();
  }});
  $('.board .pagelinks').hide();

  // collapsible forms
  $('.collapsible').each(function() {
    var show = $(this).find('.show').show();
    var hide = $(this).find('.hide');
    var form = $(this).find('.collapsing').hide();

    show.click(function() {
      show.hide();
      hide.show();
      form.slideDown();
    });

    hide.click(function() {
      form.slideUp(function() {
        hide.hide();
        show.show();
      });
    });
  });

  // Browse gallery pictures instantly.
  var gallery_image = $('.gallery-image');
  gallery_image.each(function() {
    var image = gallery_image.find('img');
    var image_path = image.attr('src');
    var delim_pos = image_path.lastIndexOf('/') + 1;
    var image_dir = image_path.substr(0, delim_pos);
    var current_ident = image_path.substr(delim_pos, 12);

    var idents_url = $('a.back').attr('href') + '/images';
    $.getJSON(idents_url, function(images) {
      var current_index = find_item_index(images, current_ident);

      function change_image(step) {
        current_index += step;
        var new_image = images[current_index];

        gallery_image.find('a').hide();
        gallery_image.fadeOut(function() {
          $('.gallery-image-title').text(new_image[1]);
          if (images[current_index - 1] != undefined) {
            gallery_image.find('a.prev').show();
          }
          if (images[current_index + 1] != undefined) {
            gallery_image.find('a.next').show();
          }
          image.attr('src', image_dir + new_image[0] + '.jpg').load(function() {
            gallery_image.fadeIn();
          });
        });
      }

      gallery_image.find('a.prev').click(function() {
        change_image(-1);
        return false;
      });

      gallery_image.find('a.next').click(function() {
        change_image(1);
        return false;
      });
    });
  });

  // Vote for a ballot option.
  $('.ballot-options').show();
  $('.ballot-options a').click(function() {
    $.ajax({
      type: 'POST',
      url: $(this).attr('href'),
      data: {},
      success: function() {
        //location.href = $('a.ballot-result-link').attr('href');
        $('#ballots-votecounted').fadeIn();
        setTimeout("$('#ballots-votecounted').fadeOut()", 3000);
      },
      error: function() {
        $('#ballots-alreadyvoted').fadeIn();
        setTimeout("$('#ballots-alreadyvoted').fadeOut()", 3000);
      },
      dataType: 'text'
    });
    return false;
  });

  // Animate ballot results.
  $('ol.ballot-results li').each(function() {
    var label = $(this).find('strong').hide();
    var bar = $(this).find('.bar');
    var width = parseInt(bar.css('width'));
    bar.css('width', 0).animate({width: width}, 1000, function() {
      label.fadeIn();
    });
  });

  // Add our latest Twitter status updates to the sidebar.
  // Our own news URLs as well as replies are filtered, though.
  var statuses_list = $('#twitter ol').show();
  var twitter_news_regex = /http:\/\/www.btb-royals.de\/news\//;
  $.getJSON('http://twitter.com/statuses/user_timeline/btbroyals.json?count=6&callback=?', function(statuses) {
    $.each(statuses, function(i, status) {
      if (! twitter_news_regex.test(status.text) && (status.text.substr(0, 1) != '@')) {
        status.text = status.text.replace(/((https?|ftp)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
          return '<a href="' + url + '">' + url + '</a>';
        }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
          return reply.charAt(0) + '<a href="http://www.twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
        });
        statuses_list.append('<li>' + status.text + '</li>');
      }
      if (statuses_list.children().length == 3) {
        return false;
      }
    });

    // Hide all tweets, then fade in the first one.
    //statuses_list.find('li').hide().first().fadeIn();

    statuses_list.fadeIn();
  });

});
