/* Add an embed toolbar item */
jQuery(function () {
    var toolbar = $('.wmd-button-row');
    var helptext = "Linking to a supported media file (YouTube video, flickr photo) will embed the object in your preview.";
    var exampleLink = 'http://www.youtube.com/watch?v=UhXiHJ8vfuk';

    // Append button html
    toolbar.append('<li class="wmd-spacer"></li>');
    toolbar.append('<li class="wmd-embed">Embed</li>');
    $('.wmd-button-row').append('<div class="wmd-embed-help"><p>' + helptext +'</p></div>');
    $('.wmd-embed-help').append('<p><a class="try_embed" href="#">Try it</a></p>');
    $('.wmd-embed-help').hide();

    // Handle the click events
    $('.wmd-embed').click(function() {
        if ($('.wmd-embed-help:visible')) {
           $('.wmd-embed-help').hide();
        }; 
    });
    
    $('.wmd-button-bar').next('textarea').click(function() {
         if ($('.wmd-embed-help:visible')) {
           $('.wmd-embed-help').hide();
        }; 
    });
    
    $('.wmd-embed').click(function() {
        $('.wmd-embed-help').toggle();
    });
    $('.try_embed').click(function() {
        $('.wmd-embed-help').hide();
        var currentTextArea = $(this).parents('.wmd-button-bar').next('textarea').focus();
        var currentValue = currentTextArea.val();
        currentTextArea.text(currentValue += "\n" + exampleLink);
        return false;
    });

});

