jQuery.ajaxSetup({
  'beforeSend': function (xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

function add_expander_handlers() {
  $("span.more a").click(function() {
    $(this).parent().hide();
    $(this).parent().siblings("span.expand").css('display', 'inline');
    return false;
  });
  $("span.expand a").click(function() {
    $(this).parent().hide();
    $(this).parent().siblings("span.more").show();
    return false;
  });
};

function add_need_login_handlers() {
  redirect = function() {
    window.location = "/user_sessions/new"
  };
  $("form.needs_login input").click(redirect);
  $("form.needs_login textarea").click(redirect);
};

/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version 1.0
 *
 * Based on Making Compact Forms More Accessible by Mike Brittain
 * (http://alistapart.com/articles/makingcompactformsmoreaccessible)
 */
$.fn.overlabel = function() {
  this.each(function() {
      var $label = $(this),
      $input = $('#' + $label.attr('for'));

      $label
      .addClass('overlabel')
      .bind('click', function(event) {
        $input.focus();
        });

      $input
      .bind('focus blur', function(event) {
        $label.css('display', (event.type == 'blur' && !$input.val() ? '' : 'none'));
        }).trigger('blur');
      });
};

function handle_navigator() {
  $('form#navigator select').bind("change", function(event){
      url = $(this).val();
      if (url != null) {
        window.location = url;
      }
  });
};

function inline_tag_rules() {
  var backup;
  var tag_id;

  show_tags = function() {
    tag_id = '#' + $(this).attr('id');
    $(tag_id + ' .user_tags_show').slideDown('slow');
    $(tag_id + ' .user_tags_edit').slideUp('slow');
    $(tag_id + ' .user_tags_edit textarea[id=\'tag_list\']').val(backup);
  };

  edit_tags = function() {
    tag_id = '#' + $(this).attr('id');
    $(tag_id + ' .user_tags_edit').slideDown('slow');
    $(tag_id + ' .user_tags_show').slideUp('slow');
    backup = $(tag_id + ' .user_tags_edit textarea[id=\'tag_list\']').val();
  };

  $('.user_tags_show button').bind("click change", edit_tags);
  $('.user_tags_edit a').bind("click change", show_tags);
};

function initialize_inline_tags() {
  $('.user_tags_show button.button').show();
  $('.user_tags_show a.button').remove();
  inline_tag_rules();
};

function initialize_ajax_tags() {
  update_via_js = function () {
    $.post($(this).attr('action'), $(this).serialize(), null, "script");
    return false;
  };

  $('.tag_form').live('submit', update_via_js);
};

$(document).ready(function() {
  initialize_ajax_tags();
  initialize_inline_tags();
  add_expander_handlers();
  $("label.overlabel").overlabel();
  add_need_login_handlers();
  handle_navigator();
});
