$(function(){
  $('.tool > a').click(function(){ $(this).siblings('ul').toggle(); return false; });
  
  $('#link').click(function(){
    var url = text = '';
    if (url = window.prompt("Enter the URL","")) {
      if (text = window.prompt("Enter the text to be shown","")) {
        var link = '['+text+']('+url+')';
        var text_area = $('#topic_body,#comment_body');
        text_area.replaceSelection(link, true);
      }
    }
    return false;
  });
  
  $('#image').click(function(){
    var url = text = '';
    if (url = window.prompt("Enter the image URL","")) {
      if (text = window.prompt("Describe this image","")) {
        var link = '!['+text+']('+url+')';
        var text_area = $('#topic_body,#comment_body');
        text_area.replaceSelection(link, true);
      }
    }
    return false;
  });
  
  $('#embed-video ul a').click(function(){ 
    var prompts = {
      vimeo: 'Enter the URL of your Vimeo video',
      youtube: 'Enter the URL of your YouTube video'
    }
    
    var service = $(this).attr('class');
    var input = '';
    
    if (input = window.prompt(prompts[service],"")) {
      var text_area = $('#topic_body,#comment_body');
    
      var tag = '';
    
      if (service == 'vimeo') {
        tag = vimeo_tag(input);
      } else if (service == 'youtube') {
        tag = youtube_tag(input);
      }
    
      text_area.replaceSelection(tag, true);
    }
    
    $(this).parent().parent().hide();
    return false;
  });
  
  function vimeo_tag(url) {
    var matches = /http:\/\/vimeo\.com\/([0-9]+)/g.exec(url);
    return '<vimeo:'+matches[1]+'>';
  }

  function youtube_tag(url) {
    var matches = /http:\/\/(www\.)?youtube\.com\/watch\?v=([0-9a-zA-Z]+).*/g.exec(url);
    return '<youtube:'+matches[2]+'>';
  }

  $('.preview').click(function(){
    $.get('preview', {body: $('#topic_body').val()}, function(data){
      $('#preview').empty().append('<h3>Preview</h3>'+data);
    });
    return false;
  });
});
