var agt = navigator.userAgent.toLowerCase();
var is_opera = agt.indexOf('opera') != -1;
var is_ie = agt.indexOf('msie') != -1 && document.all && !is_opera;
var is_ie5 = agt.indexOf('msie 5') != -1 && document.all;
var is_konq = agt.indexOf('konqueror') != -1;
var is_safari = agt.indexOf('safari') != -1 || is_konq;
var is_camino = agt.indexOf('camino') != -1;
var is_moz = !is_ie && !is_safari && (agt.indexOf('mozilla') != -1 || is_opera);
var is_mac = agt.indexOf('macintosh') != -1;
var is_winxp = agt.indexOf('windows nt 5.1') != -1 || agt.indexOf('windows xp') != -1;
var is_win2k = agt.indexOf('windows nt 5.0')!=-1 || agt.indexOf('windows 2000') != -1;
var is_win = is_winxp || is_win2k;


var HILITE_TIMEOUT = 300;
var NOTIFY_ID = 'notify';
var NOTIFY_DELAY = 2000;
var NOTIFY_HIDE_DELAY = 5000;


function checkCount( form, name ) {
  count = 0;
  var i, e = form.elements;
  for( i = 0; i < e.length; i++ )
    if( e[i].name == name )
      if ( e[i].checked )
        count++;
  return count;
}


function checkAll( form, name, check ) {
  var i, e = form.elements;
  for( i = 0; i < e.length; i++ )
    if( e[i].name == name )
      e[i].checked = check
}


function checkAllByValue( form, value, check ) {
  var i, e = form.elements;
  for( i = 0; i < e.length; i++ )
    if( e[i].value == value)
      e[i].checked = check
}


function selectAll( form, name, check ) {
  var list = form.elements[name];
  for ( var i = 0; i < list.options.length; i++ )
    list.options[i].selected = check;
}


function getSelectedValues(select) {
  var ret = [];
  for (var i = 0; i < select.length; i++) {
    if (select.options[i].selected) {
      ret.push(select.options[i].value);
    }
  }
  return ret;
}


function check_checked(f,name,msg) {
  if ( checkCount(f,name) == 0 ) {
    alert(msg);
    return false;
  }
  else {
    return true;
  }
}

function check_ids(f,name,action) {
  if ( checkCount(f,name) == 0 ) {
    alert('Please check at least one item to ' + action + '.');
    return false;
  }

  if ( confirm( 'Are you sure you want to ' + action + ' checked items?' ) ) {
    return true;
  }
  else {
    return false;
  }
}

function set_form_field_value(hidden,val) {
  var x = document.getElementsByName(hidden);
  for( var i=0; i<x.length; i++ ){
    x[i].value = val;
  }
}


function viewWindow( name, url, w, h ) {
  var win = null;
  // window features: toolbar, location, directories, status, menubar
  //   scrollbars, resizable, width, height
  win = window.open( url, name, 'resizable=yes,scrollbars=yes,width=' + w + ',height=' + h);
  if (win != null) {
    if (win.opener == null) {
      win.opener = self;
    }
//    win.location.href = url;
    win.name = name;
    win.focus();
  }

}

function printWindow( name, url, w, h ) {
  var win = null;

  win = window.open( 'about:blank', '', 'resizable=yes,scrollbars=yes,width=' + w + ',height=' + h);
  if (win != null) {
    if (win.opener == null) {
      win.opener = self;
    }

    with( win.document ) {
      write('<html><head><title>Print Preview</title></head>');
      write('<frameset frameborder="0" border="0" rows="30,*">');
      //write('<frame name="nav_bar" src="about:blank" scrolling="no">');
      write('<frame name="nav_bar" src="/assets/htmled/print_nav.html" scrolling="no">');
      write('<frame name="project" src="' + url + '" scrolling="yes">');
      write('</frameset>');
      write('</html>');
    }

/*
    with( win.nav_bar.document ) {
      write('<html><head><title>Print Preview</title></head>');
      write('<body>');
      write('<div align="right"><a href="javascript:parent.project.focus();parent.project.print();" class="action" title="Print this page">Print&nbsp;<img src="/images/icons/print.gif" border="0" align="absmiddle"></a>&nbsp;|&nbsp;<a href="javascript:parent.close();" class="action" title="Close this window">Close&nbsp;<img src="/images/icons/close.gif" border="0" align="absmiddle"></a></div>');
      write('</body>');
      write('</html>');
    }
*/

    win.name = name;
    win.focus();
  }

}

//============= SUPPORT EMAIL ======================

var support_window;
function email_support() {
  win = window.open( '/ltforms/support?view=basic' + '&referer=' + encodeURIComponent(document.location), 'Support', 'resizable=yes,scrollbars=yes,width=525,height=655');
  if (win != null) {
    if (win.opener == null) { win.opener = self; }
    support_window = win;
    support_window.focus();
  }
}

//============= FORM VERIFICATION ===================

function verifyNotBlank( elem, msg ) {
  if ( isEmpty( elem.value ) ) {
    alert( msg );
    elem.focus();
    return false;
  }
  return true;
}

function isEmpty( s ) {
  return ((s == null) || (s == "") || isWhiteSpace( s ));
}

function isWhiteSpace( s ) {
  for ( var i = 0; i < s.length; i++ ) {
    var c = s.charAt(i);
    if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
  }
  return true;
}

//============= ROW HIGHLIGHTING ===================

function checkAllToggle( form, name, check ) {

  var i, e;

  if( form ){
    e = form.elements;
  }else{
    e = document.getElementsByName( name );
  }

  for( i = 0; i < e.length; i++ )
    if( e[i].name == name ) {
      e[i].checked = check;
      if (check) {
        Highlight(e[i]);
      }
      else {
        Unhighlight(e[i]);
      }
    }
}

function Toggle(e) {
  if (e.checked) {
    Highlight(e);
  }
  else {
    Unhighlight(e);
  }
}

function Highlight(e) {
  var r = findParentNode(e, 'tr');
  HighlightRow(r);
}

function HighlightRow(r) {
  if (r) {
    if (r.className == "tint_on") {
      r.className = "tint_on_chk";
    }
    else if (r.className == "tint_off") {
      r.className = "tint_off_chk";
    }
    else if (r.className == "list_item_tint_on") {
      r.className = "list_item_tint_on_chk";
    }
    else if (r.className == "list_item_tint_off") {
      r.className = "list_item_tint_off_chk";
    }
  }
}


function Unhighlight(e) {
  var r = findParentNode(e, 'tr');
  UnhighlightRow(r);
}

function UnhighlightRow(r) {
  if (r) {
    if (r.className == "tint_on_chk") {
      r.className = "tint_on";
    }
    else if (r.className == "tint_off_chk") {
      r.className = "tint_off";
    }
    else if (r.className == "list_item_tint_on_chk") {
      r.className = "list_item_tint_on";
    }
    else if (r.className == "list_item_tint_off_chk") {
      r.className = "list_item_tint_off";
    }
  }
}


//============= UnitedStreaming Link ===================

// define a javascript function for handling submission of the hidden form
function view_ustreaming(urlDestination, formName) {

  var form;
  if( formName ){
    form = document.getElementById(formName);
  }else{
    form = document.ustreaming;
  }

  if ( form ) {
    // default the urlDestination argument if it has not been passed
    urlDestination = urlDestination == void 0 ? '' : urlDestination;

    // update the urlDesintation form field with the value passed to this function
    form.urlDestination.value = urlDestination;

    // submit the hidden form
    form.submit();
  }
  else {
    alert("You do not have access to unitedstreaming. Contact support@livetext.com.");
  }
}


//============= Cookies ===================

function getCookie(name) {
  var cookie = document.cookie.split("; ");
  for (var i = 0; i < cookie.length; i++) {
    var crumb = cookie[i].split("=");
    if (name == crumb[0])
      return unescape(crumb[1]);
  }
  return null;
}

//============= DHTML tree nodes ===================

function nodeLoad(elemId) {
  parent.document.getElementById(elemId).innerHTML = document.body.innerHTML;
}


function setVisible(elemId, visible) {
  elem = document.getElementById(elemId);
  if (elem) {
    if (visible) {
      elem.style.visibility = 'visible';
      elem.style.display = '';
    }
    else {
      elem.style.visibility = 'hidden';
      elem.style.display = 'none';
    }
  }
}

function setStatus(str) {
  if (str == null) str = '';
  window.status = str;
  return true;
}

function adjustTextArea(elem, delta, min, max) {
  if (elem && delta) {
    if (min <= 0) min = 10;
    if (max <= min) max = min + 400;
    h = parseInt(elem.style.height) + delta;
    if (h < min) h = min;
    if (h > max) h = max;
    elem.style.height = h + 'px';
  }
}

function trim(str) {
    while (str.substring(0,1) == ' ')
        str = str.substring(1, str.length);
    while (str.substring(str.length - 1, str.length) == ' ')
        str = str.substring(0, str.length - 1);
   return str;
}


// return true if this is a Windows XP IE 6.0 running Service Pack 2
// source: http://msdn.microsoft.com/security/default.aspx?pull=/library/en-us/dnwxp/html/xpsp2web.asp
function isIeXpSp2()
{
  if (window.navigator.userAgent.indexOf("SV1") != -1) {
    return true;
  }
  else {
    return false;
  }
}


// XML-HTTP

function xmlHttpCreate() {
  var xmlhttp = null;
  if (is_ie) {
    var objectIDs = new Array(
      "Microsoft.XMLHTTP",
      "Msxml2.XMLHTTP",
      "MSXML2.XMLHTTP.3.0",
      "MSXML2.XMLHTTP.4.0"
    );
    var success = false;
    for (i = 0; !success && i < objectIDs.length; i++) {
      try {
        xmlhttp = new ActiveXObject(objectIDs[i]);
        success = true;
      }
      catch (e) {
        xmlhttp = false;
      }
    }
    if (!success)
      alert('You need to enable active scripting and activeX controls.');
  }
  else {
    xmlhttp = new XMLHttpRequest();
    if (!xmlhttp)
      alert('XMLHttpRequest is not supported on this browser.');
  }

  return xmlhttp;
}

function xmlHttpGet(xmlhttp, url, handler) {
  xmlHttpReq(xmlhttp, 'GET', urlMakeUnique(url), null, handler);
}

function xmlHttpPost(xmlhttp, url, data, handler) {
  xmlHttpReq(xmlhttp, 'POST', url, data, handler);
}

function xmlHttpReq(xmlhttp, meth, url, data, handler) {
  //Debug('xmlhttp request: ' + meth + ' ' + url);
  var async = false;
  if (handler) {
    xmlhttp.onreadystatechange = handler;
    async = true;
  }
  xmlhttp.open(meth, url, async);
  if (meth != 'GET') {
    xmlhttp.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
  }
  xmlhttp.send(data);
}


// URL

function urlParam(key, value) {
  return '&' + key + '=' + encodeURIComponent(value);
}

function urlFirstParam(key, value) {
  return '?' + key + '=' + encodeURIComponent(value);
}

function urlAppendParam(url, key, value) {
  if (url.indexOf('?') < 0) {
    return url + urlFirstParam(key, value);
  }
  else {
    return url + urlParam(key, value);
  }
}

function urlMakeUnique(url) {
  if (url.indexOf('?') < 0)
    return url;
  var rand_str = Math.round(Math.random() * 2147483648.0);
  return urlAppendParam(url, '.rnd', rand_str);
}

// DHTML

function byId(win, id) {
  return win.document.getElementById(id);
}

function GetParentWindow(elt) {
  var doc = elt.ownerDocument || elt;
  var win = doc.parentWindow || doc.defaultView;

  // Safari 1.2 workaround:
  //   doc.defaultView (attribute) returns a function
  //   doc.defaultView() (method) returns the window object
  //   The method does not exist in other browsers and later Safari versions
  //   and is not spec compliant.
  if( typeof(win) == 'function' ) {
    win = doc.defaultView();
  }

  return win;
}

function hasClass(elt, cls) {
  if (elt.className == null) return false;
  var classes = elt.className.split(' ');
  for (var i = 0; i < classes.length; i++)
    if (classes[i] == cls) return true;
  return false;
}

function addClass(elt, cls) {
  if (hasClass(elt, cls)) return;
  elt.className += ' ' + cls;
}

function removeClass(elt, cls) {
  if (elt.className == null) return;
  var classes = elt.className.split(' ');
  var result = [];
  for (var i = 0; i < classes.length; i++)
    if (classes[i] != cls)
      result[result.length] = classes[i];
  elt.className = result.join(' ');
}

function hilite(elt) {
  addClass(elt, 'hilite');
  setTimeout(function() { removeClass(elt, 'hilite') }, HILITE_TIMEOUT);
}

function moveBy(elt, dx, dy) {
  if (dx)
    elt.style.left = getAbsX(elt) + dx + 'px';
  if (dy)
    elt.style.top = getAbsY(elt) + dy + 'px';
}

function moveTo(elt, x, y) {
  if (x != null) elt.style.left = x + 'px';
  if (y != null) elt.style.top = y + 'px';
}

function moveIntoView(elt) {
  moveBy(elt, -getOffscrX(elt), -getOffscrY(elt));
}

function getOffscrX(elt) {
  var x = getAbsX(elt);
  var xView = getViewScrollLeft();
  var dxView = getViewWidth();
  var dx = 0;
  if (x + elt.offsetWidth > xView + dxView)
    dx = (x + elt.offsetWidth) - (xView + dxView);
  if (x < xView + dx)
    dx = x - xView;
  return dx;
}

function getOffscrY(elt) {
  var y = getAbsY(elt);
  var yView = getViewScrollTop();
  var dyView = getViewHeight();
  var dy = 0;
  if (y + elt.offsetHeight > yView + dyView)
    dy = (y + elt.offsetHeight) - (yView + dyView);
  if (y < yView + dy)
    dy = y - yView;
  return dy;
}

function getAbsX(elt) { return (elt.x) ? elt.x : getAbsPos(elt, 'offsetLeft'); }
function getAbsY(elt) { return (elt.y) ? elt.y : getAbsPos(elt, 'offsetTop'); }
function getAbsPos(elt, which) {
  var iPos = 0;
  while (elt != null) {
    iPos += elt[which];
    elt = elt.offsetParent;
  }
  return iPos;
}

var amp_re_ = /&/g;
var lt_re_ = /</g;
var gt_re_ = />/g;
function HtmlEscape(str) {
  if (str) {
    return str.replace(amp_re_, "&amp;").replace(lt_re_, "&lt;").replace(gt_re_, "&gt;");
  }
}

var quote_re_ = /\"/g;
function QuoteEscape(str) {
  if (str) {
    return HtmlEscape(str).replace(quote_re_, "&quot;");
  }
}

function hideElement(elt) {
  if (elt) {
    elt.style.visibility = 'hidden';
    elt.style.display = 'none';
  }
}

function showElement(elt) {
  if (elt) {
    elt.style.visibility = 'visible';
    elt.style.display = '';
  }
}

function isVisible(elt) {
  return elt ? elt.style.display == '' : null;
}

function toggleVisibility(elt) {
  isVisible(elt) ? hideElement(elt) : showElement(elt);
}

function ShowHideTableRows(table_id,on_class,off_class){
    var tr = document.getElementById(table_id).getElementsByTagName('tr');

    for (i=0;i<tr.length;i++){
       if (on_class && tr[i].className == on_class)
         tr[i].style.display = '';
       else if (off_class && tr[i].className == off_class)
         tr[i].style.display = 'none';
    }
    return false;
}

function findParentNode(elt, tagname, classname) {
  if (elt) {
    var parent;
    var lcname = tagname.toLowerCase();
    while (parent = elt.parentNode) {
      if (parent.tagName.toLowerCase() == lcname) {
        if (classname) {
          if (hasClass(parent, classname)) {
            return parent;
          }
        }
        else {
          return parent;
        }
      }
      if (elt == parent) {
        return null;
      }
      elt = parent;
    }
  }
  return null;
}

function listEnableOptions(list, array) {
  if (list) {
    for (var i = 0; i < list.length; i++) {
      var o = list.options[i];
      if (arrayIndexOf(array, o.value) >= 0) {
        o.className = '';
        o.disabled = false;
      }
    }
  }
}

function listDisableOptions(list, array) {
  if (list) {
    for (var i = 0; i < list.length; i++) {
      var o = list.options[i];
      if (arrayIndexOf(array, o.value) >= 0) {
        o.className = 'disabled';
        o.disabled = true;
      }
    }
  }
}

function arrayUnique(a, sorted) {
  var tmp = [];
  if (a)
    for (var i = 0; i < a.length; i++)
      if (arrayIndexOf(tmp, a[i], sorted) < 0)
        tmp[tmp.length] = a[i];
  return tmp;
}

function arrayTrim(a) {
  var tmp = [];
  if (a)
    for (var i = 0; i < a.length; i++) {
      var str = trim(a[i]);
      if (str != '')
        tmp[tmp.length] = str;
    }
  return tmp;
}

function arrayIndexOf(a, val, sorted) {
  if (a)
    for (var i = 0; i < a.length; i++)
      if (a[i] == val) return i;
  return -1;
}

function getViewWidth() {
  if (window.innerWidth) return window.innerWidth;
  if (document.documentElement && document.documentElement.offsetWidth)
    return document.documentElement.offsetWidth;
  if (document.body && document.body.clientWidth)
    return document.body.clientWidth;
  return 0;
}

function getViewHeight() {
  if (window.innerHeight) return window.innerHeight;
  if (document.documentElement && document.documentElement.offsetHeight)
    return document.documentElement.offsetHeight;
  if (document.body && document.body.clientHeight)
    return document.body.clientHeight;
  return 0;
}

function getViewScrollTop() {
  if (document.documentElement && document.documentElement.scrollTop)
    return document.documentElement.scrollTop;
  if (document.body) return document.body.scrollTop;
  if (window.pageYOffset) return window.pageYOffset;
  return 0;
}

function getViewScrollLeft() {
  if (document.documentElement && document.documentElement.scrollLeft)
    return document.documentElement.scrollLeft;
  if (document.body) return document.body.scrollLeft;
  if (window.pageXOffset) return window.pageXOffset;
  return 0;
}

function setViewScrollTop(y) {
  if (document.documentElement && document.documentElement.scrollTop)
    document.documentElement.scrollTop = y;
  if (document.body) document.body.scrollTop = y;
  if (window.scrollY) window.scrollY = y;
}

function cancelEvent(evt) {
  evt = evt || window.event;
  evt.cancelBubble = true;
  if (evt.stopPropagation) evt.stopPropagation();
}

function Dump(obj) {
  return jsonEncode(obj);
}

function ShowDump(obj) {
  win = window.open('about:blank', '', 'resizable=yes,scrollbars=yes');
  win.document.write(Dump(obj));
  win.document.close();
}

function jsQuote(str) {
  return "'" + str.replace("'", "\\'") + "'";
}

function jsonEncode(obj) {
  if (obj == null) return 'null';
  try {
    if (typeof(obj) == 'number') return obj;
    if (typeof(obj) == 'boolean') return obj;
    if (typeof(obj) == 'string') return jsQuote(obj);
    if (typeof(obj) == 'object') {
      var items = [];
      for (i in obj)
        items[items.length] = jsQuote(i) + ':' + jsonEncode(obj[i]);
      return '{' + items.join(', ') + '} ';
    }
    return typeof(obj);
  }
  catch (ex) {
    return '[EX:' + ex + ']';
  }
}

function kvEncode(obj, root) {
  if (obj == null) return '';
  try {
    if (typeof(obj) == 'object') {
      var items = [];
      for (i in obj)
        items[items.length] = kvEncode(obj[i], (root ? root + '.' : '') + encodeURIComponent(i));
      return items.join('&');
    }
    var s = (root ? root : 'v') + '=';
    if (typeof(obj) == 'string') return s + encodeURIComponent(obj);
    if (typeof(obj) == 'boolean') return s + obj;
    if (typeof(obj) == 'number') return s + obj;
    return s + typeof(obj);
  }
  catch (ex) {
    return 'EX:' + ex + ']';
  }
}

var spc_re_ = /\s+/g;
var beg_spc_re_ = /^ /;
var end_spc_re_ = / $/;
function CollapseWhitespace(str) {
  return str.replace(spc_re_, " ").replace(beg_spc_re_, "").replace(end_spc_re_, "");
}

function IsEmpty(str) {
  return CollapseWhitespace(str) == "";
}

// windows

function GetWindowWidth(win) {
  return is_ie ? win.document.body.clientWidth : win.innerWidth;
}

function GetWindowHeight(win) {
  return is_ie ? win.document.body.clientHeight : win.innerHeight;
}

function GetAvailScreenWidth() {
  return screen.availWidth;
}

function GetAvailScreenHeight() {
  return screen.availHeight;
}

function GetNiceWindowHeight(win) {
  return Math.floor(0.88 * GetAvailScreenHeight());
}

function GetCenteringLeft(width) {
  return Math.floor((screen.availWidth - width) / 2);
}

function GetCenteringTop(height){
  return Math.floor((screen.availHeight - height) / 2);
}

function OpenWindow(win, url, name, features) {
  var newwin;
  if (features) {
    newwin = win.open(url, name, features);
  }
  else {
    newwin = win.open(url, name);
  }
  if (!newwin) {
    Debug("Cannot open window. Is there a popup blocker?");
  }
  else {
    if (newwin.opener == null) {
      newwin.opener = win;
    }
    newwin.focus();
  }
  return newwin;
}

function CloseWindow(win) {
  if (win != null && !win.closed) {
    win.close();
    return true;
  }
  return false;
}

function FocusWindow(win) {
  if (win != null && !win.closed) {
    win.focus();
    return true;
  }
  return false;
}

function Popup(win, url, name, width, height, do_center) {
  if (!height) {
    height = Math.floor(GetWindowHeight(win.top) * 0.88);
  }
  if (!width) {
    width = Math.min(GetAvailScreenWidth(), height);
  }
  var features = "resizable=yes,scrollbars=yes," + "width=" + width + ",height=" + height;
  if (do_center) {
    features += ",left=" + GetCenteringLeft(width) + "," + "top=" + GetCenteringTop(height);
  }
//  features += ",status=yes,toolbar=yes,menubar=yes"; //debug
  return OpenWindow(win, url, name, features);
}

// status messages

function ShowError(win, text) {
  ShowMessage(win, text, 'error');
}

function ShowSuccess(win, text) {
  ShowMessage(win, text, 'success');
}

function ShowStatus(win, text) {
  ShowMessage(win, text, 'status', NOTIFY_DELAY);
}

function ShowMessage(win, text, type, delay) {
  var elt = byId(win, NOTIFY_ID);
  if (elt) {
    elt.innerHTML = "<span class='" + type + "'>" + text + '</span>';
    moveTo(elt, 0, 20 + getViewScrollTop()); // position:absolute for FF and IE
//    moveTo(elt, 0, 20);
    var d = GetWindowData(win);
    clearTimeout(d.notify_pending);
    if (delay) {
      d.notify_pending = setTimeout(function() { showElement(elt); }, delay);
    }
    else {
      showElement(elt);
    }
  }
}

function HideMessage(win, delay) {
  var elt = byId(win, NOTIFY_ID);
  if (isVisible(elt)) {
    var d = GetWindowData(win);
    clearTimeout(d.notify_pending);
    if (delay) {
      d.notify_pending = setTimeout(function() { hideElement(elt); }, delay);
    }
    else {
      hideElement(elt);
    }
  }
}

function StatusMessageHandler(win, info) {
  if (info.type == ONCLICK) {
    HideMessage(win, NOTIFY_HIDE_DELAY);
  }
}


var windata = [];
function GetWindowData(win) {
  var data = windata[win.name];
  if (!data) {
    windata[win.name] = data = [];
  }
  return data;
}

function ClearWindowData(win_name) {
  if (windata[win_name]) {
    windata[win_name] = null;
  }
}


// events

var ONCLICK = 1;
var ONMOUSEDOWN = 2;
var ONKEYPRESS = 3;
var ONKEYDOWN = 4;
var ONSCROLL = 5;
var ONMOUSEOVER = 6;
var ONMOUSEOUT = 7;
var ONTOOLTIP = 8;
var ONCMD = 9;
var EventTypeNames = ["null", "onclick", "onmousedown", "onkeypress", "onkeydown", "onscroll", "onmouseover", "onmouseout", "ontooltip", "oncmd"];
function InitEventHandlers(win, handlers, mouse_movement_handlers) {
  GetWindowData(win).event_handlers = handlers;
  GetWindowData(win).mouse_movement_handlers = mouse_movement_handlers;
  win.document.onclick = CreateEventHandler(win, ONCLICK);
//  win.document.onmousedown = CreateEventHandler(win, ONMOUSEDOWN);
//  win.document.onkeydown = CreateEventHandler(win, ONKEYDOWN);
//  win.document.onkeypress = CreateEventHandler(win, ONKEYPRESS);
//  win.document.onmouseover = CreateEventHandler(win, ONMOUSEOVER);
//  win.document.onmouseout = CreateEventHandler(win, ONMOUSEOUT);
//  win.onscroll = CreateEventHandler(win, ONSCROLL);
}

function CreateEventHandler(win, type) {
//  if (is_ie) {
//    alert(32);
//    return win.eval("tmp=function(e){return HandleEvent(window,e," + type + ");}");
//  }
//  else {
    return function (e) {
      return HandleEvent(win, e, type);
    }
  ;
//  }
}

function HandleEvent(win, evt, type) {
  try {
    if (!evt) evt = win.event;
    var keycode = GetKeyCode(evt);
    var src = GetEventTarget(evt);
    var id = "";
    try {
      for (var el = src; el != null; el = el.parentNode) {
        if (id == "" && el.id && el.id.indexOf('_') != 0) {
          id = el.id;
        }
      }
    }
    catch (ex) {
      Debug("Exception: " + ex);
    }
    return DispatchEvent(win, CreateEventInfo(evt, type, src, id, null));
  }
  catch (ex) {
    DumpException(ex, "View: " + win.name + " Event: " + EventTypeNames[type]);
  }
}

function DispatchEvent(win, info) {
  var handlers;
  if (info.type == ONMOUSEOVER || info.type == ONMOUSEOUT) {
    handlers = GetWindowData(win).mouse_movement_handlers;
  }
  else {
    handlers = GetWindowData(win).event_handlers;
    //Debug("Event: " + EventTypeNames[info.type] + " id = " + info.id + " keycode = " + info.keycode);
  }
  for (var i in handlers) {
    var result = handlers[i](win, info);
    if (result == false || result == true) {
      return result;
    }
  }
}

function GetKeyCode(evt) {
  return is_ie ? evt.keyCode : evt.which;
}

function GetEventTarget(evt) {
  var elt = evt.srcElement ? evt.srcElement : evt.target;
  if (is_safari && elt && elt.nodeType == 3) {
    elt = elt.parentNode;
  }
  return elt;
}

function CreateEventInfo(evt, type, src, id, cmd) {
  var u = id.indexOf("_", 1);
  u++;
  return {
    event : evt,
    type : type,
    src : src,
    id : id,
    id_prefix : id.substr(0, u),
    id_n : id.substr(u),
    cmd : cmd
  };
}

function GetItemId(elt, prefix) {
  for (; elt; elt = elt.parentNode) {
    if (elt.id && elt.id.indexOf(prefix) == 0) {
      return elt.id.substring(prefix.length);
    }
  }
  return null;
}

// debug

function Debug(msg) {
  alert(msg);
}

function DumpException(msg) {
  Debug(msg);
}


var LT = {
  createElement : function(doc, tagname, attrs, children) {
    var elt = doc.createElement(tagname);
    for (var i in attrs) elt[i] = attrs[i];
    if (typeof(children) == 'object') {
      for (var i in children) {
        var c = children[i];
        if (typeof(c) == 'object') {
          elt.appendChild(LT.createElement(doc, c[0], c[1], c[2]));
        }
        else {
          elt.appendChild(doc.createTextNode(c));
        }
      }
    }
    return elt;
  }
};


var LT_Event = {

  handler : function(win, callback)
  {
    return is_ie ? function () { callback(win.event); } : callback;
  },

  getKeycode : function(evt)
  {
    return is_ie ? evt.keyCode : evt.which;
  },

  getTarget : function(evt) {
    var elt = evt.srcElement ? evt.srcElement : evt.target;
    if (is_safari && elt && elt.nodeType == 3) {
      elt = elt.parentNode;
    }
    return elt;
  }

};

var WindowManager = {
  offset: function(element) {
    var offset = {}
    //element = $(element)
    offset.top = element.offsetTop
    offset.left = element.offsetLeft
    while (element = element.offsetParent) {
      offset.top += element.offsetTop
      offset.left += element.offsetLeft
    }
    return offset
  },

  size: function(element) {
    var size = {}
    //element = $(element)
    size.width = element.clientWidth
    size.height = element.clientHeight
    if (size.width == 0) size.width = element.scrollWidth
    if (size.height == 0) size.height = element.scrollHeight
    return size
  },

  innerSize: function() {
    var size = {}
    size.width = window.innerWidth ||
                   document.documentElement && document.documentElement.clientWidth ||
                   document.body.clientWidth
    size.height = window.innerHeight ||
                   document.documentElement && document.documentElement.clientHeight ||
                   document.body.clientHeight
    return size
  }
};

function imposeMaxLength(Object, MaxLen){ return (Object.value.length <= MaxLen); }
