jQuery(function($) {

  $.fn.textarea = function() {
    
    $(this).each(function(index, element) {
      
      var saveRange, getValue, getSelection, replaceSelection, wrapSelection, insertBeforeSelection, insertAfterSelection, collectFromEachSelectedLine, insertBeforeEachSelectedLine;
      
      var range;
      
      saveRange = function() {
        range = document.selection.createRange();
      };
      
      getValue = function() {
        return element.value;
      };
      
      getSelection = function() {
        if (!!document.selection) {
          return document.selection.createRange().text;
        } else if (!!element.setSelectionRange) {
          return element.value.substring(element.selectionStart, element.selectionEnd);
        } else {
          return false;
        }
      };
      
      replaceSelection= function(text) {
        var scrollTop = element.scrollTop;
        if (!!document.selection){
            element.focus();
            var r = (range) ? range : document.selection.createRange();
            r.text = text;
            r.select();
        } else if (!!element.setSelectionRange){
            var selectionStart = element.selectionStart;
            element.value = element.value.substring(0,selectionStart) + text + element.value.substring(element.selectionEnd);
            element.setSelectionRange(selectionStart + text.length,selectionStart + text.length);
        }
        // this.doOnChange();
        element.focus();
        element.scrollTop = scrollTop;
      };
      
      wrapSelection = function(before, after) {
        after = after || before;
        var sel = getSelection();
        // Remove the wrapping if the selection has the same before/after
        if (sel.indexOf(before) === 0 &&
            sel.lastIndexOf(after) === (sel.length - after.length)) {
            replaceSelection(sel.substring(before.length, sel.length - after.length));
        } else {
          replaceSelection(before + sel + after);
        }
      };
      
      insertBeforeSelection = function(text){
          replaceSelection(text + getSelection());
      };
      
      insertAfterSelection = function(text){
          replaceSelection(getSelection() + text);
      };
      
      insertBeforeEachSelectedLine = function(text, after){
        var lines, result = '';
        
        after = after || '';
        lines = getSelection().split("\n");
        for (var i=0,l=lines.length; i < l; i++) {
          result += (text + lines[i] + "\n");
        }
        
        replaceSelection(result + after);
      };
      
      $(this).bind('quote.textarea', function(event) {
        insertBeforeEachSelectedLine('> ');
      });
      
      $(this).bind('bold.textarea', function(event) {
        wrapSelection('*');
      });
      
      $(this).bind('insertQuote.textarea', function(event, text) {
        replaceSelection(text);
        element.select();
        insertBeforeEachSelectedLine('> ', "\n");
        return false;
      });

      $(this).bind('link.textarea', function(event) {
        var selection = getSelection();
        var response = prompt('Enter Link URL','');
        if(response == null)
            return;
        replaceSelection('[' + (selection == '' ? 'Link Text' : selection) + '](' + (response == '' ? 'http://link_url/' : response) + ')');        
      });
      
      $(this).bind('image.textarea', function(event) {
        var selection = getSelection();
        var response = prompt('Enter Image URL','');
        if(response == null)
            return;            
        replaceSelection('![' + (selection == '' ? 'Alt Text' : selection) + '](' + (response == '' ? 'http://image_url/image.jpg' : response) + ')');        
      });
      
    });
    
  };
  
  $('#post_form textarea').textarea();
  
  $('a.make_quote').click(function(event) {
    var textarea = $(this).closest('#post_form').find('textarea');
    $(textarea).trigger('quote.textarea');
    return false;
  });
  
  $('a.make_bold').click(function(event) {
    var textarea = $(this).closest('#post_form').find('textarea');
    $(textarea).trigger('bold.textarea');
    return false;
  });
  
  $('a.insert_link').click(function(event) {
    var textarea = $(this).closest('#post_form').find('textarea');
    $(textarea).trigger('link.textarea');
    return false;
  });
  
  $('a.insert_image').click(function(event) {
    var textarea = $(this).closest('#post_form').find('textarea');
    $(textarea).trigger('image.textarea');
    return false;
  });
  
  $('a.quote_post').click(function(event) {
    var post, id, textarea;
    
    post = $(this).closest('div.post');
    id =  $(post).attr('id').replace('post_', '');
    textarea = $('textarea#post_body');
    
    
    $.get(document.location.pathname + '/' + id + '/source', function(data, textStatus) {
      $(textarea).trigger('insertQuote.textarea', [data]);
    });
    
    return false;
    
  });
  
});