// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

port = null;
function getPort() {
  if (!port) {
    port = chrome.extension.connect();
    port.onMessage.addListener(function(msg, port) {
      updateTextArea(msg);
    });
   }
  return port;
}

//if (window == top) 
{
  findTextAreas();
  window.addEventListener("focus", findTextAreas);
  window.addEventListener("keyup", findTextAreas);  
}

function findTextAreas() {
  var result = null;
  // Find the body text area
  //result = document.getElementsByTagName('textarea');
  result = document.getElementsByName('body');

  if(result && result[0]) {
    getPort().postMessage({text: result[0].value, id: result[0].id});
  }
}

function updateTextArea(msg) {
  if(msg) {
    var element = document.getElementById(msg.id);
    if(element) {
      element.value = msg.text;
      // reupdate
      findTextAreas();
    }
  }
}


