// Convert proper text to URL-friendly slugs (taken from Django)
function URLify(s, num_chars) {
    removelist = ["a", "an", "as", "at", "before", "but", "by", "for", "from",
                  "is", "in", "into", "like", "of", "off", "on", "onto", "per",
                  "since", "than", "the", "this", "that", "to", "up", "via",
                  "with"];
    r = new RegExp('\\b(' + removelist.join('|') + ')\\b', 'gi');
    s = s.replace(r, '');
    s = s.replace(/[^-\.\+\w\s]/g, '');  // remove unneeded chars
    s = s.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces
    s = s.replace(/[-\s]+/g, '-');   // convert spaces to hyphens
    s = s.toLowerCase();             // convert to lowercase
    return s.substring(0, num_chars);// trim to first num_chars chars
}

// jQuery
$(document).ready(function(){
  // Div toggler
  $('div._toggled').hide();
  $('a._toggle_next').click(function(event){
    $(this).parent().nextAll('div._toggled').slideToggle('fast');
    $(this).blur();
    event.preventDefault();
  });
  // Checkbox toggler
  $('#toggle:checkbox').click(function(){
    $(':checkbox').attr('checked', $(this).attr('checked'));
  });
  // Slugification
  $('#id_slug').change(function(){
    $(this).attr('_changed', true);
  });
  $('#id_title').keyup(function(){
    if (!$('#id_slug').attr('_changed')) {
      $('#id_slug').val(URLify($('#id_title').val(), 100));
    }
  });
  $('._slug_source').keyup(function(){
    if (!$('#id_slug').attr('_changed')) {
      $('#id_slug').val(URLify($(this).val(), 100));
    }
  });
  // Hiding initial data
  $('._hide_initial').focus(function(){
    $(this).css('color', '#000000');
    if (!$(this).attr('_initial')) {
      $(this).attr('_initial', $(this).val());
    }
    if (!$(this).attr('_changed')) {
      $(this).val('');
    }
  });
  $('._hide_initial').blur(function(){
    if ($(this).val() && $(this).val() != $(this).attr('_initial')) {
      $(this).attr('_changed', true);
    } else {
      $(this).removeAttr('_changed');
      $(this).val($(this).attr('_initial'));
      $(this).css('color', '#c0c0c0');
    }
  });
  // Wiki tag insertion
  $('a._insert_tag').live('click', function(event){
    $('#main').find('textarea:first').val($('#main').find('textarea:first').val() + ' ' + $(this).attr('title'));
    event.preventDefault();
  });
  // Editing guide help_text
  $('textarea._markup').after('<span class="help_text">For syntax help, see the <a href="/wiki/editing-guide/" target="_blank">editing guide</a>.</span>');
});

