var AS_gid = 0;
function AS_GetUniqueID()
{
  var uid = new Date().getTime() + "_" + (AS_gid++);
  return uid;
}

var AS_Panel = null;
var AS_Object = null;
var AS_TOID = null;

function AS_Init(obj, url, rst, asData, asSep, asClear)
{
  if ( obj != AS_Object ) {
    if ( AS_Object != null ) {
      AS_Unload();
    }
    AS_Object = obj;
    addEvent(window, "resize", AS_Resize);
    addEvent(obj, "blur", AS_Shutdown);
    addEvent(obj, "beforedeactivate", AS_ShutdownDelay);
    addEvent(obj, "keydown", AS_KeyDown);
    addEvent(obj, "keypress", AS_Keypress);
  }
  if ( url ) {
    obj.setAttribute("asURL", url);
  }
  if ( rst ) {
    obj.setAttribute("asKeepOri", "true");
  }
  if ( asData ) {
    obj.setAttribute("asData", asData);
  }
  if ( asSep ) {
    obj.setAttribute("asSep", asSep);
  }
  if ( asClear && AS_Panel != null ) {
    var helpTable = document.getElementById(AS_Panel.getAttribute("helpTable"));
    if ( helpTable != null ) {
      helpTable.parentNode.removeChild(helpTable);
    }
  }
  Make_Suggest(obj,0);
}

var asFocused = 0;
function AS_PanelFocus()
{
  asFocused = 1;
}

function AS_PanelBlur()
{
  asFocused = 0;
}

function AS_Resize()
{
  if ( AS_Panel != null ) {
    AS_ShowPanel();
  }
}

function AS_ClearTimeout()
{
  if ( AS_TOID != null ) {
    window.clearTimeout(AS_TOID);
    AS_TOID = null;
  }
}

function AS_IsActiveElement(obj)
{
  if ( obj != null ) {
    var e = document.activeElement;
    while ( e != null && e.tagName != 'BODY' ) {
      if ( e == obj ) {
        return true;;
      }
      e = e.parentNode;
    }
  }
  return false;
}

function AS_ShutdownDelay()
{
  if ( AS_Object != null ) {
    AS_TOID = window.setTimeout( 
      function() { 
        AS_TOID = null;
        if ( AS_Object != null ) { 
          dispatchEvent(AS_Panel, "blur"); 
        } 
        //AS_Unload();
      }, 100
    );
  }
}

function AS_Shutdown(evt)
{
  if ( !evt ) evt = window.event;
  var obj = evt.srcElement ? evt.srcElement : evt.target;
  if ( evt.ctrlKey )
    debugger;

  AS_ClearTimeout();
  if ( obj == AS_Panel ) {
    if ( AS_IsActiveElement(AS_Object) )
      return;
  } else {
    if ( AS_IsActiveElement(AS_Panel) )
      return;
  }
    
  AS_HidePanel();
  if ( AS_Object.getAttribute("asKeepOri") == null || AS_Object.getAttribute("asKeepOri") == 'false' )
    AS_SetValue(AS_Object,document.getElementById(AS_Object.getAttribute("firstMatch")),true);
  else if ( AS_Object.getAttribute("valueChanged") ) {
    dispatchEvent(AS_Object, "change");
  }
  if ( obj != AS_Object ) {
    obj = AS_Unload();
    if ( document.getElementById(obj.id) != null )
      dispatchEvent(obj, "blur");
  } else {
    AS_Unload();  
  }
}

function AS_Unload()
{
  if ( AS_Object != null ) {
    var obj = AS_Object;
    AS_Object = null;
    obj.removeAttribute("asAttached");
    obj.removeAttribute("asData");
    obj.removeAttribute("asDIV");
    obj.removeAttribute("firstMatch");
    obj.removeAttribute("valueChanged");
    removeEvent(obj, "beforedeactivate", AS_ShutdownDelay);
    removeEvent(obj, "blur", AS_Shutdown);
    removeEvent(obj, "keydown", AS_KeyDown);
    removeEvent(obj, "keypress", AS_Keypress);
    removeEvent(window, "resize", AS_Resize);
    return obj;
  }
  return null;
}

function AS_KeyDown(evt)
{
  if ( !evt ) evt = window.event;
  var obj = evt.srcElement ? evt.srcElement : evt.target;
  var ch = evt.keyCode;
  if ( ch == 16 || ch == 17 || ch == 18 ) {
    return;
  }
  if ( ch == 9 ) {
    asFocused = 0;
    return;
  }
  AS_TOID = window.setTimeout(function(){Make_Suggest(obj,ch)},50);
}

function AS_Keypress(evt)
{
  if ( !evt ) evt = window.event;
  var obj = evt.srcElement ? evt.srcElement : evt.target;
}

function AS_XmlLoaded(obj, ch, xmlhttp)
{
  if ( xmlhttp.status == 200 ) {
    var asData = xmlhttp.responseXML;
    if ( asData != null && asData.parseError != null && asData.parseError.errorCode != 0 ) {
      //alert( asData.parseError.reason );
      return;
    }
    var asDIV = AS_GetPanel(obj, asData);
    obj.setAttribute("asDIV", asDIV.id);
    obj.setAttribute("asData", asData);
    Make_Suggest(obj, ch);
  }
}

function AS_GetXmlData(obj,ch)
{
  var asData = obj.getAttribute("asData");
  if ( asData == null ) {
    var xmlhttp = obj.getAttribute("xmlhttp");
    if ( xmlhttp == null ) {
      xmlhttp = getXmlHttp();
      obj.setAttribute("xmlhttp", xmlhttp);
    }
    if ( xmlhttp ) {
      var url = obj.getAttribute("asURL");
      if ( url == null ) {
        //url = document.location.href.replace(/tls\/.*$/,'tls/xml/loadList.xml');
        url = "../../../tls/xml/loadList.xml";
      }
      if ( url != null && url != '' ) {
        xmlhttp.open("POST", url);
        xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4) {
            //alert( xmlhttp.responseText );
            //AS_XmlLoaded(xmlhttp.status, xmlhttp.getAllResponseHeaders(), xmlhttp.responseText);
            AS_XmlLoaded(obj, ch, xmlhttp);
          }
        }
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
        var body = null;
        if ( obj.getAttribute("asClass") != null ) {
          if ( body == null )
            body = "";
          else
            body += "&";
          body += "dao="+obj.getAttribute("asClass");
        }
        if ( obj.getAttribute("asField") != null ) {
          if ( body == null )
            body = "";
          else
            body += "&";
          body += "field="+obj.getAttribute("asField");
        }
        if ( obj.getAttribute("asType") != null ) {
          if ( body == null )
            body = "";
          else
            body += "&";
          body += "asType="+obj.getAttribute("asType");
        }
        xmlhttp.send(body);
      }
    }
  }
  return asData;
}

function AS_SetValue(obj, oTR, flag)
{
  if ( oTR ) {
    var v = obj.value;
    var asSep = obj.getAttribute("asSep");
    if ( asSep == null ) {
      asSep = ',';
    }
    var sepIndex = v.lastIndexOf(asSep);
    if ( sepIndex != -1 ) {
      obj.value = v.substring(0,sepIndex+1) + oTR.cells[0].getAttribute("value");
    } else {
      obj.value = oTR.cells[0].getAttribute("value");
    }
    var linkKey = obj.getAttribute("linkKey");
    if ( linkKey != null ) {
      var lKeys = document.getElementsByName(linkKey);
      for(var k=0; k<lKeys.length; k++) {
        lKeys[k].value = oTR!=null?oTR.cells[0].getAttribute("key"):'';
      }
    }
    if ( flag )
      dispatchEvent(obj, "change");
    obj.setAttribute("valueChanged", "true");
  } else if ( flag ) {
    obj.value = '';
    var linkKey = obj.getAttribute("linkKey");
    if ( linkKey != null ) {
      var lKeys = document.getElementsByName(linkKey);
      for(var k=0; k<lKeys.length; k++) {
        lKeys[k].value = oTR!=null?oTR.cells[0].getAttribute("key"):'';
      }
    }
    dispatchEvent(obj, "change");
    obj.setAttribute("valueChanged", "true");
  }
}

function AS_Click(evt)
{
  if ( !evt ) evt = window.event;
  var oTD = evt.srcElement ? evt.srcElement : evt.target;
  var oTR = oTD.parentNode;
  var oDIV = oTR.parentNode;
  while( oDIV != null && oDIV.tagName != 'DIV' )
    oDIV = oDIV.parentNode;
  var obj = document.getElementById(oDIV.getAttribute("srcElement"));
  if ( obj != null ) {
    AS_HidePanel(obj);
    AS_SetValue(obj, oTR, true);
    dispatchEvent(obj, "blur");
  }
}

function AS_Select(obj, helpTable, oTR, l)
{
  obj.setAttribute("firstMatch", oTR.id);
  oTR.bgColor = "highlight";
  oTR.style.color = "white";
  oTR.scrollIntoView();
  AS_SetValue(obj,oTR, false);
  if ( obj.setSelectionRange ) {
    if ( l != null ) {
      obj.setSelectionRange(l, obj.value.length)
    } else {
      obj.setSelectionRange(obj.value.length, obj.value.length)
    }
  } else {
    var r = obj.createTextRange();
    if ( l != null ) {
      r.moveStart("character", l);
      r.moveEnd("character", obj.value.length);
    } else {
      r.moveStart("character", obj.value.length);
      r.collapse();
    }
    r.select();
  }
  //oTR.scrollIntoView();
}

var chAry = new Array(8,35,36,37,39,45,46,46,91);
function AS_Match(obj,ch)
{
  //AS_SetValue(obj,null);
  var asDIV = AS_Panel; //obj.getAttribute("asDIV");
  if ( asDIV != null ) {
    //asDIV = document.getElementById(asDIV);
    var helpTable = document.getElementById(asDIV.getAttribute("helpTable"));
    if ( helpTable != null ) {
      var firstMatch = null;
      if ( ch == 40 || ch == 38 ) {
        var oTR = null;
        firstMatch = document.getElementById(obj.getAttribute("firstMatch"));
        if ( firstMatch != null ) {
          firstMatch.bgColor = '';
          firstMatch.style.color = '';
          oTR = (ch==40)?firstMatch.nextSibling:firstMatch.previousSibling;
        } else {
          oTR = (ch==40)?helpTable.rows[0]:helpTable.rows[helpTable.rows.length-1];
        }
        while( oTR != null && oTR.style.display == 'none' ) {
          oTR = (ch==40)?oTR.nextSibling:oTR.previousSibling;
        }
        if ( oTR != null ) {
          AS_Select(obj, helpTable, oTR);
        } else {
          obj.removeAttribute("firstMatch");
        }
        return;
      }
      obj.removeAttribute("firstMatch");
      var asSep = obj.getAttribute("asSep");
      if ( asSep == null ) {
        asSep = ',';
      }
      var curVal = obj.value;
      curVal = curVal.substring(curVal.lastIndexOf(asSep)+1);
      var rep = new RegExp(curVal.toUpperCase().replace(/([\.\?\$\^\(\)])/g,'\\$1').replace(/\*/g,'.*'));
      for(var i=0; i<helpTable.rows.length; i++) {
        var oTR = helpTable.rows[i];
        oTR.bgColor = '';
        oTR.style.color = '';
        oTR.style.display = '';
        if ( curVal.length > 0 ) {
          var oTD = oTR.cells[0];
          var val = oTD.getAttribute("value");
          if ( val.toUpperCase().match(rep) ) {
            if ( firstMatch == null ) {
              firstMatch = oTR;
            }
          } else {
            oTR.style.display = 'none';
          }
        }
      }
      obj.setAttribute("matchValue", curVal.id);
      for(var j=0; j<chAry.length; j++) {
        if ( ch == chAry[j] )
          return;
      }
      if ( firstMatch && false ) {
        if ( ch == 0 )
          AS_Select(obj, helpTable, firstMatch, 0);
        else
          AS_Select(obj, helpTable, firstMatch, curVal.length);
      }
    }
  }
}

var count=0;
function Make_Suggest(obj, ch)
{
  //window.status = obj.name + "=" + obj.value + "/" + ch + "(" + (count++) + ")" + obj.value.length;
  var asData = AS_GetXmlData(obj, ch);
  if ( asData != null ) {
    var asDIV = AS_GetPanel(obj, asData);
    AS_Match(obj,ch);
    AS_ShowPanel(obj);
  }
}

function AS_ShowPanel()
{
  if ( AS_Panel == null || AS_Object == null )
    return;
  var asDIV = AS_Panel; //document.getElementById(srcE.getAttribute("asDIV"));
  var srcE = AS_Object;
  if ( asDIV != null ) {
    var iframe = document.getElementById(asDIV.getAttribute("iframe"));
    asDIV.style.display = '';
    iframe.style.display = '';
    var pos = AS_findXY(srcE, iframe);
    //window.status = asDIV.offsetWidth + ',' + srcE.offsetWidth;
    var helpTable = document.getElementById(asDIV.getAttribute("helpTable"));
    var width = srcE.getAttribute("asWidth") != null ? srcE.getAttribute("asWidth") : helpTable.clientWidth+20;
    if ( width < srcE.offsetWidth ) {
      width = srcE.offsetWidth;
    }
    if ( (pos.left + width) > document.body.clientWidth ) {
      pos.left = document.body.clientWidth - width;
    }
    if ( pos.left < 0 ) {
      width += pos.left;
      post.left = 0;
    }
    window.status = width;
    iframe.style.left = pos.left;
    iframe.style.top = pos.top + srcE.offsetHeight + 1;
    iframe.style.width = width;
    iframe.style.height = srcE.getAttribute("asHeight") != null ? srcE.getAttribute("asHeight") : "200px";
    asDIV.style.left = pos.left;
    asDIV.style.top = pos.top + srcE.offsetHeight + 1;
    asDIV.style.width = width;
    asDIV.style.height = srcE.getAttribute("asHeight") != null ? srcE.getAttribute("asHeight") : "200px";
  }
}

function AS_HidePanel()
{
  AS_HideDivPanel(AS_Panel);
}

function AS_HideDivPanel(asDIV)
{
  if ( asDIV != null ) {
    var iframe = document.getElementById(asDIV.getAttribute("iframe"));
    iframe.style.display = 'none';
    asDIV.style.display = 'none';
  }
}

function AS_GetPanel(obj, xmlDoc)
{
  if ( AS_Panel == null ) {
    AS_Panel = AS_CreatePanel(obj);
  }
  var helpTable = document.getElementById(AS_Panel.getAttribute("helpTable"));
  if ( helpTable == null ) {
    helpTable = AS_Panel.appendChild(document.createElement("TABLE"));
    helpTable.id = AS_GetUniqueID();
    AS_Panel.setAttribute("helpTable", helpTable.id);
    AS_FillPanel(xmlDoc);
  }
  return AS_Panel;
}

function AS_FillPanel(xmlDoc)
{
  var helpTable = document.getElementById(AS_Panel.getAttribute("helpTable"));
  while( helpTable.rows.length > 0 ) 
    helpTable.deleteRow(0);
  var datas = xmlDoc.getElementsByTagName("data")
  for(var i=0; i<datas.length; i++) {
    var child = datas[i];
    var oTR = helpTable.insertRow(-1);
    oTR.id = AS_GetUniqueID();
    var oTD = oTR.insertCell(-1);
    oTD.noWrap = true;
    oTD.innerHTML = child.firstChild.nodeValue;
    oTD.style.cursor = "pointer";
    //oTD.onmouseover = AS_PanelFocus;
    //oTD.onmouseout = AS_PanelBlur;
    oTD.onclick = AS_Click;
    oTD.setAttribute("key", child.getAttribute("id"));
    //var value = srcE.
    oTD.setAttribute("value", child.firstChild.nodeValue);
  }
}

function AS_CreatePanel(srcE)
{
  if ( srcE.id == '' || srcE.id == null ) {
    srcE.id = AS_GetUniqueID();
  }
  var iframe = document.createElement("IFRAME");
  iframe.id = AS_GetUniqueID();
  iframe.style.display = 'none'
  iframe.style.position = "absolute";
  iframe.setAttribute("frameBorder", "0");
  iframe.tabIndex = -1;
  iframe.style.zIndex = 999;
  document.body.appendChild(iframe);
  //srcE.parentNode.insertBefore(iframe, srcE);

  var helpE = document.createElement("DIV")
  helpE.id = AS_GetUniqueID();
  helpE.setAttribute("iframe", iframe.id);
  helpE.setAttribute("srcElement", srcE.id);
  //helpE.style.display = 'none'
  helpE.style.position = "absolute";
  helpE.style.border = "1px solid gray";
  //alert( srcE.getAttribute("asHeight") );
  helpE.style.height = srcE.getAttribute("asHeight") != null ? srcE.getAttribute("asHeight") : "200px";
  helpE.style.overflow = "auto";
  helpE.style.background = 'white';
  //helpE.onblur = AS_Shutdown;
  //helpE.onmouseover = AS_PanelFocus;
  //helpE.onmouseout = AS_PanelBlur;
  helpE.style.zIndex = 999;
  document.body.appendChild(helpE);
  addEvent(helpE, "blur", AS_Shutdown);
  addEvent(helpE, "beforedeactivate", AS_ShutdownDelay);
  //srcE.parentNode.insertBefore(helpE, srcE);

  //var helpTable = helpE.appendChild(document.createElement("TABLE"));
  //helpTable.id = AS_GetUniqueID();
  //helpE.setAttribute("helpTable", helpTable.id);
  //helpTable.width ="100%";
  /*
  var datas = xmlDoc.getElementsByTagName("data")
  for(var i=0; i<datas.length; i++) {
    var child = datas[i];
    var oTR = helpTable.insertRow(-1);
    oTR.id = AS_GetUniqueID();
    var oTD = oTR.insertCell(-1);
    oTD.noWrap = true;
    oTD.innerHTML = child.firstChild.nodeValue;
    oTD.style.cursor = "pointer";
    //oTD.onmouseover = AS_PanelFocus;
    //oTD.onmouseout = AS_PanelBlur;
    oTD.onclick = AS_Click;
    oTD.setAttribute("key", child.getAttribute("id"));
    //var value = srcE.
    oTD.setAttribute("value", child.firstChild.nodeValue);
  }
  */
  //iframe.width = helpE.clientWidth;
  //iframe.height = helpE.clientHeight;
  return helpE;
}

function AS_findXY(obj, me)
{
  var pos = new Object();
  pos.left = 0;
  pos.top = 0;
  var p = obj;
  while( p != null ) {
    if ( me != null && p == me.offsetParent ) {
      return pos;
    }
    pos.left += p.offsetLeft + p.clientLeft;
    pos.top += p.offsetTop + p.clientTop;
    p = p.offsetParent;
  }
  if ( me != null ) {
    p = me.offsetParent;
    while ( p != null ) {
      pos.left -= (p.offsetLeft+p.clientLeft);
      pos.top -= (p.offsetTop+p.clientTop);
      p = p.offsetParent;
    }
  }
  return pos;
}


