var timedelay=50; //ms
var mrcobj=new Object();
mrcobj.Loader=function(url,onload,onerror,method,params,contentType){
  this.req=null;
  mrcobj.currentLoader=this;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loaddoc(url,method,params,contentType);
}
mrcobj.Loader.prototype.loaddoc=function(url,method,params,contentType){

  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");
    //document.getElementById("mmsg").innerHTML="window.ActiveXObject ="+this.req;
  }

  if (this.req){
  
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        mrcobj.Loader.onReadyState.call(loader);
      } 
      this.req.open(method,url,true);

      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}
//####################################
mrcobj.Loader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
 
  try{ 
  var httpStatus=req.status;
  //document.getElementById("mmsg").innerHTML=" ready=" + ready + ", status=" + httpStatus;
  if (ready==4){
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }else{
      //this.onerror.call(this);
    }
  }
  }
  catch(e){}
}
//####################################
mrcobj.Loader.prototype.defaultError=function(){
  alert("error fetching data!"
    +"\n\nreadyState:"+this.req.readyState
    +"\nstatus: "+this.req.status
    +"\nheaders: "+this.req.getAllResponseHeaders());
}
//#############################################################
function  init(server_app, qtype) {
  //alert("run!");
  setJaxbox();
  if (qtype == 'I') {
    setJaxboxsRET(server_app);
  }
}
//####################################
function  setJaxboxsRET(server_app) {
  var msg="No matches";// message for no matching record
  var fm=document.forms[0];
  for(j=0;j<fm.elements.length;j++){
    var formObj=fm.elements[j];
    if(formObj.type.toLowerCase() == "text" && formObj.name.indexOf("val_") == 0) {
         formObj.obj = SetProperties(formObj,"k",server_app,true,true,true,true,msg,false, 10000);
    }
  }
}
//####################################
function  setJaxbox() {
        var elemSpan = document.createElement("span");
        elemSpan.id = "jaxbox";
        elemSpan.className = "jaxboxclass"; 
        document.body.appendChild(elemSpan);
}


 //####################################
      function SetProperties(xElem,xHidden,xserverCode,
        xignoreCase,xmatchAnywhere,xmatchTextBoxWidth,
        xshowNoMatchMessage,xnoMatchingDataMessage,xuseTimeout, xtheVisibleTime){
          var props={
            elem: xElem,
            hidden: xHidden,
            serverCode: xserverCode,
            regExFlags: ( (xignoreCase) ? "i" : "" ),//case
            regExAny: ( (xmatchAnywhere) ? "" : "^" ),
            matchAnywhere: xmatchAnywhere,
            matchTextBoxWidth: xmatchTextBoxWidth,
            theVisibleTime: xtheVisibleTime,
            showNoMatchMessage: xshowNoMatchMessage,
            noMatchingDataMessage: xnoMatchingDataMessage,
            useTimeout: xuseTimeout
          };
          AddHandler(xElem);
          return props;
      }

 //####################################      
      function AddHandler(objText){
        objText.onkeyup = GiveOptions;
        objText.onblur = function(){
          //alert("this.obj.useTimeout=" + this.obj.useTimeout + "  );
          //if(this.obj.useTimeout)StartTimeout();
          //setTimeout("HideTheBox()",10);
        }
         
      }
 
      var arrOptions = new Array();
      var strLastValue = "";
      var bMadeRequest;
      var theTextBox;
      var objLastActive;
      var currentValueSelected = -1;
      var bNoResults = false;
      var isTiming = false;

//####################################
      function GiveOptions(e){      
        var intKey = -1;
        if(window.event){
          intKey = event.keyCode;
          theTextBox = event.srcElement;
        }
        else{
          intKey = e.which;
          theTextBox = e.target;
        }
        if(theTextBox.obj.useTimeout){
          //if(isTiming)EraseTimeout();
          //StartTimeout();
        }
        if(theTextBox.value.length == 0  ){
          arrOptions = new Array();
          HideTheBox();
          strLastValue = "";
          return false;
        }
        if(objLastActive == theTextBox){
          if(intKey == 13){
            GrabHighlighted();
            theTextBox.blur();
            //document.forms[0].submit();
            return false;
          }   else if(intKey == 38){
            MoveHighlight(-1);
            GrabHighlighted2()
            return false;
          }   else if(intKey == 40){
            MoveHighlight(1);
            GrabHighlighted2()
            return false;
          }  else {
           // var charCode = (e.charCode)?e.charCode : ((e.which) ? e.which : e.keyCode);
            if (intKey == 32) {
              //alert("space!"); 
              return false}
          }
        }
        if(objLastActive != theTextBox  ||
       theTextBox.value.indexOf(strLastValue) != 0 ||
           ( (arrOptions.length==0 || arrOptions.length==15 ) && !bNoResults) ||
           (theTextBox.value.length > strLastValue.length)){
             objLastActive = theTextBox;
             bMadeRequest = true;
             callajax0(theTextBox.value);
           // document.getElementById("mmsg").innerHTML="get data....theTextBox.value="+theTextBox.value;
        }  else if(!bMadeRequest){
          BuildList(theTextBox.value);
          //document.getElementById("mmsg").innerHTML="not get data................";
        }
        strLastValue = theTextBox.value;
      }
 
//####################################
function callajax0(xStrText){
   var today=new Date();  
   var t0=today.getTime(); tt0=t0;
   setTimeout('callajax1('+t0+')', timedelay);
   //alert("op");
}
var tt0=0;
//####################################
function callajax1(stamp){
  if(stamp == tt0) {
    var params = setParms(theTextBox);
    var loader1 = new mrcobj.Loader(theTextBox.obj.serverCode, BuildChoices,null,"POST",params);
  }
}

//####################################
 function setParms(jbox) {
  var parms="AJAX=Y&AJAXFIELD=" + jbox.name;
  var fm=document.forms[0];
  for(j=0;j<fm.elements.length;j++){
    var formObj=fm.elements[j];
    if(formObj.name.indexOf("rls_") == 0) {
      parms += "&" + formObj.name + "=" + formObj.options[formObj.selectedIndex].value;
    } else if(formObj.type.toLowerCase() == "text" || 
           formObj.type.toLowerCase() == "hidden" || 
           formObj.name.indexOf("btn_") == 0) {
      parms += "&" + formObj.name + "=" + formObj.value;
    }
  }
  //alert("parms=" + parms );
  return parms;
 }

//####################################00000000000000000
 function BuildChoices(){
   if (theTextBox.value.length == 0) return;
   var jaxfield=theTextBox.name;
   var jaxvalue=theTextBox.value;
   var errcode=0;
   //alert(theTextBox.value+'=='+jaxvalue);
   var strText = this.req.responseText;
   if (strText.length==0) return;
   eval(strText);
   if (errcode==1) return;
   var boxvalue=theTextBox.value;
   try{
      if(fieldtype==0){
         boxvalue=boxvalue.replace(/,/gi,'');
         strLastValue=strLastValue.replace(/,/gi,'');
      }
   }catch(e){}
   if (theTextBox.name != jaxfield || boxvalue != jaxvalue) return; 
   BuildList(strLastValue);
   bMadeRequest = false;
}

//####################################
      function BuildList(theText){
        SetElementPosition(theTextBox);
        var theMatches = MakeMatches(theText);
        theMatches = theMatches.join().replace(/\,/gi,"");
        if(theMatches.length > 0){
          document.getElementById("jaxbox").innerHTML = theMatches;
          document.getElementById("OptionsList_0").className="highEl";
          currentValueSelected = 0;
          bNoResults = false;
        }
        else{
          currentValueSelected = -1;
          bNoResults = true;
          if(theTextBox.obj.showNoMatchMessage)
            document.getElementById("jaxbox").innerHTML = "<span class='noMatchData'>" +
              theTextBox.obj.noMatchingDataMessage +"</span>";
          else HideTheBox();
        }
      }

 //####################################
      function SetElementPosition(theTextBoxInt){
        var selectedPosX = 0;
        var selectedPosY = 0;
        var theElement = theTextBoxInt;
        if (!theElement) return;
        var theElemHeight = theElement.offsetHeight;
        var theElemWidth = theElement.offsetWidth;
        while(theElement != null){
          selectedPosX += theElement.offsetLeft;
          selectedPosY += theElement.offsetTop;
          theElement = theElement.offsetParent;
        }
        xPosElement = document.getElementById("jaxbox");
        xPosElement.style.left = selectedPosX;
        if(theTextBoxInt.obj.matchTextBoxWidth)
          xPosElement.style.width = theElemWidth+20;
        xPosElement.style.top = selectedPosY + theElemHeight
        xPosElement.style.display = "block";
        if(theTextBoxInt.obj.useTimeout){
          xPosElement.onmouseout = StartTimeout;
          xPosElement.onmouseover = EraseTimeout;
        }
        else{
          xPosElement.onmouseout = null;
          xPosElement.onmouseover = null;
        }
      }

 //####################################
      var countForId = 0;
      function MakeMatches(xCompareStr){
        countForId = 0;
        var matchArray = new Array();
        var regExp = new RegExp(theTextBox.obj.regExAny + xCompareStr,theTextBox.obj.regExFlags);
        for(i=0;i<arrOptions.length;i++){
          var theMatch = arrOptions[i].match(regExp);
          //var theMatch = arrOptions[i][0].match(regExp);
          if(theMatch){
            matchArray[matchArray.length]= CreateUnderline(arrOptions[i], xCompareStr,i);
          }
        }
        return matchArray;
      }


 //####################################
      var hiStart = "<span class='spanMatchText'>";
      var hiEnd = "</span>";
      var selStart = "<span style='width:100%;display:block;' class='normalEl' onmouseover='SetHighColor(this)'";
      var selEnd ="</span>";
function CreateUnderline(xStr,xTextMatch,xVal){
  selMid = "onclick='SetText(" + xVal + ")'" + "id='OptionsList_" + countForId + "' theArrayNumber='"+ xVal +"'>";
  var regExp = new RegExp(theTextBox.obj.regExAny + xTextMatch,theTextBox.obj.regExFlags);
  var aStart = xStr.search(regExp);
  var matchedText = xStr.substring(aStart, aStart + xTextMatch.length);
  countForId++;
  return selStart + selMid + xStr.replace(regExp,hiStart + matchedText + hiEnd) + selEnd;
}

 //####################################
      function MoveHighlight(xDir){
        if(currentValueSelected >= 0){
          newValue = parseInt(currentValueSelected) + parseInt(xDir);
          if(newValue > -1 && newValue < countForId){
            currentValueSelected = newValue;
            SetHighColor (null);
          }
        }
      }
 //####################################
      function SetHighColor(theTextBox){
        if(theTextBox){
          currentValueSelected = theTextBox.id.slice(theTextBox.id.indexOf("_")+1,
          theTextBox.id.length);
        }
        for(i = 0; i < countForId; i++){
          document.getElementById('OptionsList_' + i).className ='normalEl';
        }
        document.getElementById('OptionsList_' + currentValueSelected).className = 'highEl';
      }

 //####################################
function SetText(xVal){
     theTextBox.value = arrOptions[xVal]; //set text value
     document.getElementById("jaxbox").style.display = "none";
     currentValueSelected = -1; //remove the selected index
     document.forms[0].btn_search.focus();
}
//####################################
function GrabHighlighted(){
   if(currentValueSelected >= 0){
     xVal = document.getElementById("OptionsList_" + currentValueSelected).getAttribute("theArrayNumber");
     SetText(xVal);
     HideTheBox();
   }
}
//####################################
function GrabHighlighted2(){
   if(currentValueSelected >= 0){
     xVal = document.getElementById("OptionsList_" + currentValueSelected).getAttribute("theArrayNumber");
     theTextBox.value = arrOptions[xVal]; //set text value
     //SetText(xVal);
     //HideTheBox();
   }
}
 //####################################
      function HideTheBox(){
        document.getElementById("jaxbox").style.display = "none";
        currentValueSelected = -1;
        EraseTimeout();
      }

 //####################################
      function EraseTimeout(){
        clearTimeout(isTiming);
        isTiming = false;
      }
 //####################################
      function StartTimeout(){
     // alert("theTextBox.obj.theVisibleTime=" );
        //isTiming = setTimeout("HideTheBox()",theTextBox.obj.theVisibleTime);
      }
//#######################################################
function setSortImage(names) { // for set grey sort images 
  for (var i=0; i<names.length; i++) {
    var im = names[i];  
    if (document.images[im]) {
      if (im.indexOf("s0") == 0) {
        document.images[im].src =  s0.src ;
      } else {
        document.images[im].src =  s1.src ;
      }
    }
  }
}
//#######################################################
function setDropV(fld, val) { // for set value dropdown field
    var selects = document.getElementsByTagName("select");
    for (var i = 0; i < selects.length; i++) {
       var name0 = "val_" + fld;
       if (selects[i].name == name0) { 
          selects[name0].value=val;  
       }  
    }
}