/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$(document).ready( function () {
  // hide all the form elements
  $('form#post textarea').cleditor({
    width: '640px',
    controls: "bold italic underline strikethrough subscript superscript | font size " +
  "color highlight removeformat | bullets numbering | outdent " +
  "indent | alignleft center alignright justify | link unlink | cut copy paste pastetext | source",
  });

  $('form#post').hide();

  // add a click handler to the formset legend to toggle the form elements
  $('a#post_form_toggle').click(function(){
    $('form#post').slideToggle();
  });

  $('ul.post_tags').each( function() {
    post_id = $(this).parent().attr('id').split('_')[1];
    $(this).append('<li><a id="add_tag_'+post_id+'" class="add_tag">+</a></li>');
  });

  $('a.add_tag').live('click', function(){
    post_id = $(this).attr('id').split('_')[2];
    $('#post_'+post_id+' ul li:last-child').html('<form id="'+$(this).attr('id')+'" class="add_tag" action="'+site_url+'tags/ajax_save/" method="post"><input type="text" length="45" name="tags" /><input type="hidden" name="post_id" value="'+post_id+'" /><input type="submit" value="Save"></form>');
  });

  $('form.add_tag').live('submit', function () {
    event.preventDefault();
    post_id = $(this).attr('id').split('_')[2];

    $.post(site_url+"tags/ajax_save", $(this).serialize(), function (data) {
      $('#post_'+post_id+' ul').html('');
      $.each(data, function (index, tag){
        $('#post_'+post_id+' ul').append('<li><a href="'+site_url+'posts/tag/'+tag+'">'+tag+'</a></li>');
      });
      $('#post_'+post_id+' ul').append('<li><a id="'+$(this).attr('id')+'" class="add_tag">+</a></li>');
    },
    'json');
    return false;
  });

});
