function insert_upload () {
  var ref = {};
  
  ref.init = function() {
    
    if ($('form#comment-form, form#node-form').length == 0) return;
    
    ref.first = true;
    ref.count();
    ref.register();
    
    if (typeof(ref.insertTextarea) == 'undefined') {
    ref.insertTextarea = $('#edit-body').get(0) || false;
    }
    
    // Keep track of the last active textarea (if not using WYSIWYG).
    $('.node-form textarea:not([name$="[data][title]"])').focus(function(){
        ref.insertSetActive();
      }).blur(function() {
        ref.insertRemoveActive();
        }
      );
    
  }

  ref.count = function() {
    ref.initial_count = $('.insert-upload-wrapper').length;
  }
  

  ref.check_results = function() {

    if (ref.first) {
      ref.add_buttons();
      ref.first = false;
    };

    if($('.insert-upload-wrapper').length > ref.initial_count) {
      ref.add_buttons();
      ref.count();
    }

    clearTimeout(ref.t);

    ref.register();
  }
  
  
  ref.register = function() {
    ref.t = setTimeout('Drupal.insert_upload.check_results()', 250);
  }


  ref.add_buttons = function() {
    $('.insert-upload-wrapper.image').append('<input class="insert-upload" type="submit" onclick="return false;" value="Insert image"/>');
    $('.insert-upload-wrapper.file').append('<input class="insert-upload" type="submit" onclick="return false;" value="Insert link"/>');
    $('.insert-upload').click(function() {
      ref.clickme(this);
    });
  }
  
  ref.clickme = function(element) {
    wrapper = $(element).parent().parent().parent();
    title = wrapper.find('.form-text').attr('value');
    href = wrapper.find('.description small').html().replace('http://' + location.hostname,'');
    attrs_text = wrapper.find('.insert-upload-wrapper').attr('name');
    
    attrs = attrs_text.split('-');
    
    if (attrs[0] == 'image') {
      width = attrs[2];
      height = attrs[3];

      old_width = width;
      old_height = height;

      width = Math.min(400,old_width);
      height = Math.round(width/old_width * old_height);

      ref.content = '<img src="'+href+'" alt="'+title+'" height="'+height+'" width="'+width+'" />';
    } else {
      ref.content = '<a href="'+href+'">'+title+'</a>'
    }
    

    ref.dotheinsert();
  }
  
  ref.insertSetActive = function() {
    ref.insertTextarea = this;
    this.insertHasFocus = true;
  }
  
  ref.insertRemoveActive = function() {
    if (ref.insertTextarea == this) {
      var thisTextarea = this;
      setTimeout(function() {
        thisTextarea.insertHasFocus = false;
      }, 1000);
    }
  }
  
  ref.dotheinsert = function() {
    insertTextarea = ref.insertTextarea;
    content = ref.content;
    
    // Always work in normal text areas that currently have focus.
    if (insertTextarea && insertTextarea.insertHasFocus) {
      ref.insertAtCursor();
    }
    // Direct tinyMCE support.
    else if (typeof(tinyMCE) != 'undefined' && tinyMCE.activeEditor) {
      tinyMCE.activeEditor.execCommand('mceInsertContent', false, content);
    }
    // WYSIWYG support, should work in all editors if available.
    else if (Drupal.wysiwyg && Drupal.wysiwyg.activeId) {
      Drupal.wysiwyg.instances[Drupal.wysiwyg.activeId].insert(content)
    }
    // FCKeditor module support.
    else if (typeof(FCKeditorAPI) != 'undefined' && fckActiveId) {
      FCKeditorAPI.Instances[fckActiveId].InsertHtml(content);
    }
    // Direct FCKeditor support (only body field supported).
    else if (typeof(FCKeditorAPI) != 'undefined' && FCKeditorAPI.Instances['edit-body']) {
      FCKeditorAPI.Instances['edit-body'].InsertHtml(content);
    }
    // Direct CKeditor support (only body field supported).
    else if (typeof(CKEDITOR) != 'undefined' &&  CKEDITOR.instances['edit-body']) {
      CKEDITOR.instances['edit-body'].insertHtml(content);
    }
    else if (insertTextarea) {
      ref.insertAtCursor();
    }
    
  }
  
  
  
  ref.insertAtCursor = function() {
    var editor = ref.insertTextarea;
    var content = ref.content;
    
    // // IE support.
    if (document.selection) {
      editor.focus();
      sel = document.selection.createRange();
      sel.text = content;
    }
    
    // Mozilla/Firefox/Netscape 7+ support.
    else if (editor.selectionStart || editor.selectionStart == '0') {
      var startPos = editor.selectionStart;
      var endPos = editor.selectionEnd;
      editor.value = editor.value.substring(0, startPos)+ content + editor.value.substring(endPos, editor.value.length);
    }
    
    // Fallback, just add to the end of the content.
    else {
      editor.html(editor.html() + ref.content);
    }
  }
  
  
  return ref;
}


$(function(){
  Drupal.insert_upload = new insert_upload();
  Drupal.insert_upload.init(); 
});


