updating textarea with photos

I have an app that has a textarea for users to create blog posts. I
need to allow them to click on a link/button that spawns a popup upload
photo dialogue. The image_tag for the uploaded photo needs to be placed
in the text area at the current cursor location.

I've got javascript to update the cursor and the popup forms/actions to
upload the photo, but I'm at a loss as to how to knit this together so
that the textarea is updated in place with the photo url.

Thanks for any ideas/suggestions.

##main view

<%= javascript_include_tag ('insertphoto')%>
<%= start_form_tag({:action => 'new'}, :id=>'submit_article') %>

<%= text_area 'article', 'body'%>

<a HREF="javascript:void(0)" onClick="myPopup()">insert image</a>
<%= end_form_tag %>

### image_upload.rhtml
<%= start_form_tag({:action => 'image_upload'}, :multipart => true) %>

    <b>Picture:</b><br />
    <%= file_field_tag "picture" %>

  <p><%= submit_tag "Save" %></p>
<%= end_form_tag %>

insertAtCursor(document.myform.article_body, ‘photo_url’);


    def image_upload
      if request.post?
        @myloc="#{RAILS_ROOT}" + '/public/images/' + "#{Time.now.to_i}"
+ '.jpg'
        File.open(@myloc , "wb") do |f|

### js functions

function myPopup(){
window.open('/writer/image_upload', 'MyPopUp',

function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
sel = document.selection.createRange();
sel.text = myValue;
else if (myField.selectionStart || myField.selectionStart == ‘0′) {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;