/*-------------------------------------------------------------
 * Collection of useful jquery things common to several sites!
 *
 * Add your own!!
 *-------------------------------------------------------------*/


$(document).ready(function() {
  // This makes a link with the delete_link class send a with DELETE verb
  $('.delete_link').live('click', function(){
    var path = $(this).attr('href');
    var prompt = $(this).attr('rel');
    var redirect = $(this).attr('rev');

    if (confirm(prompt)) {
      $.post(path, {'_method' : 'delete'}, function(ret){
        if (ret == "OK") {
          if (redirect.match(/^#eval__/)) {  
            var run = redirect.replace(/^#eval__/,'');
            eval(run);
          }
          else {
            window.location = redirect;
          }
        } else {
          error_message = ret.replace('ERROR', '').trim();
          alert("Sorry, but I can't delete this object. " + error_message);
        }
      });
    }
    return false;
  });

  // Textile cheatsheet
  $('.textile-help-link').live('click', function() {
    $(this).next('.textile-help').toggle('slow');
  });

  // Placeholder labels
  initPlaceholder();
  
  // Toggle button -- see the comment at toggleBox()
  $('.toggle_button').change(function(){ toggleBox('.toggle_button') });
  toggleBox('.toggle_button');
});



// Labels within fields. Use the the "placeholder" HTML 5 attribute.
function initPlaceholder() {
  if ($.browser.webkit) return false;

  $('input[placeholder]').each(function(index) {
    target = $(this);
    target.addClass('placeholder');
    target.attr('value', target.attr('placeholder'));

    target.focus(function() {
      if ( $(this).val() == $(this).attr('placeholder') ) {
        $(this).removeClass('placeholder');
        $(this).attr('value', '');
      }
    });

    target.blur(function() {
      if ( $.trim($(this).val() ) == '' ) {
        $(this).addClass('placeholder');
        $(this).attr('value', $(this).attr('placeholder') );
      }
    });
  });

  // The form shouldn't send the placeholder text as the value
  // TODO: write back the labels after submit
  $('form').submit(function(){
    $(this).find('input[placeholder]').each(function(index) {
      target = $(this);
      if ((target).val() == (target).attr('placeholder')) {
        target.val('');
      }
    });
  });
}

// Show or hide boxes by changing a checkbox.
// Set the class of the checkbox to ".toggle_button"
// and set the "rel" attribute to the ID of the box.
function toggleBox(button) {
  var box = $(button).attr('rel');
  if ( $(button).is(':checked') ) {
    $(box).slideDown();
  } else {
    $(box).slideUp();
  }
}

