// global variable
var idField,txtField,txtDiv,lookupDiv,onChangeFunction,dynsearch_highlight_row=-1;
var idArray=new Array(0),nameArray=new Array(0),comboArray=new Array(0);
var isIE6=(navigator.userAgent.toLowerCase().indexOf("msie 6.") != -1);
var isIE=(navigator.userAgent.toLowerCase().indexOf("msie") != -1);
var checkParentHeight=false,parentFrame,initParentHeight=null;
var lastCommaIndex=0,ismultiple=false,isupdatecost=false;

// Ajax function
function _dynamicsearch(event,url,str,txtdiv,lookupdiv,idfield,txtfield,maxlimit,onchangefunc) {
        var http_request = false;
        // _callback_control=htmlcontrol;
        if (window.XMLHttpRequest) {
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/plain');
                // See note below about this line
            }
        } 
        else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            return false;
        }

        // set global variables
        idField=idfield;
        txtField=txtfield;
        txtDiv=txtdiv;
        lookupDiv=lookupdiv;
        if (onchangefunc!=null)
          onChangeFunction=onchangefunc;

        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (event) keycode = event.which;
        else return true;

        if (keycode==38) {  // up arrow
            highlightRow(dynsearch_highlight_row,0);
            if (dynsearch_highlight_row > 0)
                dynsearch_highlight_row--;
            else
                dynsearch_highlight_row=idArray.length;
            setDynamicSearchValue(dynsearch_highlight_row);
            highlightRow(dynsearch_highlight_row,1);
            return;
        }
        else if (keycode==40) {  // down arrow
            highlightRow(dynsearch_highlight_row,0);
            if (dynsearch_highlight_row < idArray.length)
                dynsearch_highlight_row++;
            else
                dynsearch_highlight_row=0;
            setDynamicSearchValue(dynsearch_highlight_row);
            highlightRow(dynsearch_highlight_row,1);
            return;
        }
        else if (keycode==37) {
            toTextBoxEnd(txtField);
        }
        else if (keycode==39) {
            toTextBoxEnd(txtField);
        }
        else if (keycode==9 || keycode==13) {
            clearDynamicSearch(false);
            return;
        }
        else {
            clearDynamicSearch(false);
            dynsearch_highlight_row=0;
        }
        if (maxlimit!=null && maxlimit!='' && maxlimit!=0 && isMaxReached(maxlimit)) {
            txtField.value=txtField.value.substring(0,txtField.value.lastIndexOf(",")+1);
            alert("Maximum number of selections reached.");
            return;
        }
        if (str!='') {
            http_request.onreadystatechange = function() { _formatSearch(http_request); };
            http_request.open('GET', url, true);
            http_request.send(null);
        }
        else {
            clearDynamicSearch(true);
        }
}

// get results from Ajax
function _formatSearch(req) {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var mstr=req.responseText;
            if (mstr.indexOf('<companies>')>0)
                formatResults(mstr,30);
            else if (mstr.indexOf('<people>')>0)
                formatResults(mstr,40);
            else if (mstr.indexOf('<levelone>')>0)
                formatResults(mstr,23);
            else if (mstr.indexOf('<levelonepeople>')>0)
                formatResults(mstr,2340);
            else if (mstr.indexOf('<timecode>')>0)
                formatResults(mstr,'tc');
            else if (mstr.indexOf('<icdcode>')>0)
                formatResults(mstr,'icd');
            else
                clearDynamicSearch(false);
        }
        else {
                
        }
    }
}
// check max reached
function isMaxReached(max) {
  var numselected=0;
  var txtstr=','+txtField.value+',';
  txtstr=txtstr.replace(/,+/g,",");
  txtstr=txtstr.replace(/^,|,$/g,"");
  if (txtstr.indexOf(",")>-1) {
    var txtarr=txtstr.split(",");
    numselected=txtarr.length-1;
  }
  if (max > numselected)
    return false;
  else
    return true;
}
// initial function called from textbox field
function dyn_companysearch(event,str,txtdiv,lookupdiv,idfield,txtfield,isexternal,appid,catlimit,inframe,ismultiselect,omitpermission,listviewentity) {
  if (inframe) checkParentHeight=true;
  var appidstr='';
  if (appid!=null) appidstr='&appid='+appid;
  if (catlimit==null) catlimit='';
  if (ismultiselect!=null && ismultiselect==1) {
    ismultiple=true;
    if (str.lastIndexOf(",")>-1)
      str=str.substring(str.lastIndexOf(",")+1);
  }
  else 
    ismultiple=false;
  if (omitpermission==null) omitpermission='';
  if(listviewentity==null)listviewentity="";
  var surl="/Ajax/aj_dynamicsearch.jsp?isexternal="+isexternal+appidstr+"&catlimit="+catlimit+"&omitpermission="+omitpermission+"&action=companysearch&cname="+encodeURI(str)+"&listviewentity="+listviewentity;
  _dynamicsearch(event,surl,str,txtdiv,lookupdiv,idfield,txtfield);
}

// initial function called from textbox field
function dyn_peoplesearch(event,str,txtdiv,lookupdiv,idfield,txtfield,isexternal,appid,rolelimit,inframe,ismultiselect,limitobjectid,isresourceonly,maxlimit,typeid,limitcompanyid,listviewentity) {
  if (inframe) checkParentHeight=true;
  var appidstr='',typeidstr='',resstr='';
  if (appid!=null) appidstr='&appid='+appid;
  if (typeid!=null) typeidstr='&typeid='+typeid;
  if (rolelimit==null) rolelimit='';
  if (maxlimit==null) maxlimit='';
  if (limitobjectid==null) limitobjectid='';
  if (limitcompanyid==null) limitcompanyid='';
  if (ismultiselect!=null && ismultiselect==1) {
    ismultiple=true;
    if (str.lastIndexOf(",")>-1)
      str=str.substring(str.lastIndexOf(",")+1).trim();
  }
  else 
    ismultiple=false;
  if (isresourceonly!=null) {
    //isupdatecost=isresourceonly;
    if (isresourceonly)
      resstr='&resourceonly=1';
  }
  if(listviewentity==null)listviewentity="";
  var surl="/Ajax/aj_dynamicsearch.jsp?isexternal="+isexternal+appidstr+typeidstr+resstr+"&userlist=&rolelimit="+rolelimit+"&limitobjectid="+limitobjectid+"&limitcompanyid="+limitcompanyid+"&action=peoplesearch&cname="+encodeURI(str)+"&listviewentity="+listviewentity;
  _dynamicsearch(event,surl,str,txtdiv,lookupdiv,idfield,txtfield,maxlimit);
}

// initial function called from textbox field
function dyn_levelonepeoplesearch(event,str,txtdiv,lookupdiv,idfield,txtfield,appid) {
  var appidstr='';
  if (appid!=null) appidstr='&appid='+appid;
  var surl="/Ajax/aj_scheduling.jsp?"+appidstr+"&action=levelonepeoplesearch&cname="+encodeURI(str);
  _dynamicsearch(event,surl,str,txtdiv,lookupdiv,idfield,txtfield);
}

// initial function called from textbox field
function dyn_levelonesearch(event,str,txtdiv,lookupdiv,idfield,txtfield,appid,appitemid,objcompanyid,concatcname,isutaconnect,inframe,isleveltwo,limitstatusid) {
  var appidstr='';
  if (inframe) checkParentHeight=true;
  if (appid!=null) appidstr='&appid='+appid;
  if (appitemid!=null) appidstr+='&appitemid='+appitemid;
  if (isutaconnect!=null) appidstr+='&isutaconnect='+isutaconnect;
  if (isleveltwo!=null) appidstr+='&isleveltwo='+isleveltwo;
  if (objcompanyid!=null) appidstr+='&objcompanyid='+objcompanyid;
  if (limitstatusid!=null) appidstr+='&limitstatusid='+limitstatusid;
  if (concatcname!=null) appidstr+='&concatcname='+concatcname;
  var surl="/Ajax/aj_dynamicsearch.jsp?"+appidstr+"&action=levelonesearch&sname="+encodeURI(str);
  _dynamicsearch(event,surl,str,txtdiv,lookupdiv,idfield,txtfield);
}


// initial function called from textbox field
function dyn_timecodesearch(event,str,txtdiv,lookupdiv,idfield,txtfield,idtag,txttag,onchangefunc) {
  var paramstr='';
  if (idtag!=null) paramstr+='&idtag='+idtag;
  if (txttag!=null) paramstr+='&txttag='+txttag;
  var surl="/Ajax/aj_dynamicsearch.jsp?"+paramstr+"&action=timecodesearch&sname="+str;
  _dynamicsearch(event,surl,str,txtdiv,lookupdiv,idfield,txtfield,'',onchangefunc);
}

// initial function called from textbox field
function dyn_idccodesearch(event,str,txtdiv,lookupdiv,idfield,txtfield) {
  var surl="/Ajax/aj_dynamicsearch.jsp?action=idccodesearch&sname="+str;
  _dynamicsearch(event,surl,str,txtdiv,lookupdiv,idfield,txtfield,'');
}

// initial function called from textbox field
function dyn_branchsearch(event,str,txtdiv,lookupdiv,idfield,txtfield,appid) {//this is only used for branch ajax on L1, since it is always internal with listviewentity=3, so no need to parse parameter here
  var appidstr='';
  if (appid!=null) appidstr='&appid='+appid;
  var surl="/Ajax/aj_dynamicsearch.jsp?action=branchsearch"+appidstr+"&cname="+encodeURI(str);
  _dynamicsearch(event,surl,str,txtdiv,lookupdiv,idfield,txtfield);
}

// format companies from results
function formatResults(rstr,type) {
    var typename='',pframe='',pframe2='';
    if (type==30) {
      typename="companies";
      pframe="company_frame";
      pframe2="company2_frame";
    }
    else if (type==40) {
      typename="people";
      pframe="contact_frame";
      pframe2="contact2_frame";
    }
    else if (type==23) {
      typename="levelone";
      pframe="uta_frame";
      pframe2="uta_frame2";
    }
    else if (type==2340)
      typename="levelonepeople";
    else if (type=='tc')
      typename="timecode";
    else if (type=='icd')
      typename="icdcode";

    var cstr=rstr.substring(rstr.indexOf('<'+typename+'>')+typename.length+2,rstr.indexOf('</'+typename+'>'));
    var rowsarr=cstr.split("<row>");
    var info,cname;
    var htmlstr='';
    if (type==30) {
		if(rstr.indexOf('<listviewheaderText>')>-1){
			var listviewheadertextArray=rstr.substring(rstr.indexOf('<listviewheaderText>')+20,rstr.indexOf('</listviewheaderText>')).split("<listviewheader>");
			htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:500px">\n<tr>';
			for(i=0;i<listviewheadertextArray.length;i++)htmlstr+='<td style="font-weight:bold;border-bottom:1px #000000 solid">'+listviewheadertextArray[i]+'</td>';
			htmlstr+="</tr>\n";
		}else{
			var citylabel=rstr.substring(rstr.indexOf('<citylabel>')+11,rstr.indexOf('</citylabel>'));
			var addresslabel=rstr.substring(rstr.indexOf('<addresslabel>')+14,rstr.indexOf('</addresslabel>'));
			var namelabel=rstr.substring(rstr.indexOf('<namelabel>')+11,rstr.indexOf('</namelabel>'));
			htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:500px">\n<tr><td style="font-weight:bold;border-bottom:1px #000000 solid">'+namelabel+'</td><td style="font-weight:bold;border-bottom:1px #000000 solid">'+addresslabel+'</td><td style="font-weight:bold;border-bottom:1px #000000 solid">'+citylabel+'</td></tr>\n';
		}
    }
    else if (type==40) { 
		if(rstr.indexOf('<listviewheaderText>')>-1){
			var listviewheadertextArray=rstr.substring(rstr.indexOf('<listviewheaderText>')+20,rstr.indexOf('</listviewheaderText>')).split("<listviewheader>");
			htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:500px">\n<tr>';
			for(i=0;i<listviewheadertextArray.length;i++)htmlstr+='<td style="font-weight:bold;border-bottom:1px #000000 solid">'+listviewheadertextArray[i]+'</td>';
			htmlstr+="</tr>\n";
		}else{
			var emaillabel=rstr.substring(rstr.indexOf('<emaillabel>')+12,rstr.indexOf('</emaillabel>'));
			var titlelabel=rstr.substring(rstr.indexOf('<titlelabel>')+12,rstr.indexOf('</titlelabel>'));
			htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:500px">\n<tr><td style="font-weight:bold;border-bottom:1px #000000 solid">Name</td><td style="font-weight:bold;border-bottom:1px #000000 solid">Company</td><td style="font-weight:bold;border-bottom:1px #000000 solid">'+titlelabel+'</td><td style="font-weight:bold;border-bottom:1px #000000 solid">'+emaillabel+'</td></tr>\n';
		}
    }
    else if (type==23){
        var headerText="Name";
		if(rstr.indexOf('<listviewheaderText>')>-1){
			var listviewheadertextArray=rstr.substring(rstr.indexOf('<listviewheaderText>')+20,rstr.indexOf('</listviewheaderText>')).split("<listviewheader>");
			htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:300px">\n<tr><td style="font-weight:bold;border-bottom:1px #000000 solid">'+headerText+'</td>';
			for(i=0;i<listviewheadertextArray.length;i++)htmlstr+='<td style="font-weight:bold;border-bottom:1px #000000 solid">'+listviewheadertextArray[i]+'</td>';
			htmlstr+="</tr>\n";
		}else{
			if(rstr.indexOf("<headerText>")>-1)headerText=rstr.substring(rstr.indexOf('<headerText>')+12,rstr.indexOf('</headerText>'));
			htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:300px">\n<tr><td style="font-weight:bold;border-bottom:1px #000000 solid">'+headerText+'</td></tr>\n';
		}
    }
    else if (type==2340) {
        var phonelabel=rstr.substring(rstr.indexOf('<phonelabel>')+12,rstr.indexOf('</phonelabel>'));
        var addrlabel=rstr.substring(rstr.indexOf('<addrlabel>')+11,rstr.indexOf('</addrlabel>'));
        htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:500px">\n<tr><td style="font-weight:bold;border-bottom:1px #000000 solid">Name</td><td style="font-weight:bold;border-bottom:1px #000000 solid">'+addrlabel+'</td><td style="font-weight:bold;border-bottom:1px #000000 solid">'+phonelabel+'</td></tr>\n';
    }
    else if (type=='tc')
        htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:300px">\n<tr><td style="font-weight:bold;border-bottom:1px #000000 solid">Code</td></tr>\n';
    else if (type=='icd')
        htmlstr+='<table cellspacing=0 cellpadding=1 style="border:1px solid #000000;width:300px">\n<tr><td style="font-weight:bold;border-bottom:1px #000000 solid">Code</td><td style="font-weight:bold;border-bottom:1px #000000 solid">Description</td></tr>\n';
    for (i=0; i < rowsarr.length; i++) {
        info=rowsarr[i].split("<col>");
        if (info.length>=4) {
            cname=info[0].replace(/\'/g,'\\\'');
            if (type==30) {
				htmlstr+='<tr id="dynsearchtr_'+eval(i+1)+'" onclick="setDynamicSearchValue(dynsearch_highlight_row)" onmouseover="highlightRow(dynsearch_highlight_row,0);dynsearch_highlight_row='+eval(i+1)+';highlightRow('+eval(i+1)+',1);" style="cursor:hand;cursor:pointer">';
				for(j=0;j<info.length;j++){
					if(rstr.indexOf('<listviewheaderText>')>-1&&j<1||j==1)continue;
					htmlstr+='<td style="border-bottom:1px #DFDFDF dashed" >'+highlightString(info[j],txtField.value)+'</td>';
				}
				htmlstr+='</tr>\n';
            }
            else if (type==40) {
              htmlstr+='<tr id="dynsearchtr_'+eval(i+1)+'" onclick="setDynamicSearchValue(dynsearch_highlight_row)" onmouseover="highlightRow(dynsearch_highlight_row,0);dynsearch_highlight_row='+eval(i+1)+';highlightRow('+eval(i+1)+',1);" style="cursor:hand;cursor:pointer">';
			  for(j=0;j<info.length;j++){
					if(rstr.indexOf('<listviewheaderText>')>-1&&j<1||j==1)continue;
					htmlstr+='<td style="border-bottom:1px #DFDFDF dashed" >'+highlightString(info[j],txtField.value)+'</td>';
				}
            }
            else if (type==23){
				htmlstr+='<tr id="dynsearchtr_'+eval(i+1)+'" onclick="setDynamicSearchValue(dynsearch_highlight_row)" onmouseover="highlightRow(dynsearch_highlight_row,0);dynsearch_highlight_row='+eval(i+1)+';highlightRow('+eval(i+1)+',1);" style="cursor:hand;cursor:pointer">';
				for(j=0;j<info.length-3;j++)if(j!=1)htmlstr+='<td style="border-bottom:1px #DFDFDF dashed" >'+highlightString(info[j],txtField.value)+'</td>';
              htmlstr+='</tr>\n';
            }
            else if (type==2340) {
              htmlstr+='<tr id="dynsearchtr_'+eval(i+1)+'" onclick="setDynamicSearchValue(dynsearch_highlight_row)" onmouseover="highlightRow(dynsearch_highlight_row,0);dynsearch_highlight_row='+eval(i+1)+';highlightRow('+eval(i+1)+',1);" style="cursor:hand;cursor:pointer"><td style="border-bottom:1px #DFDFDF dashed" >'+highlightString(info[0],txtField.value)+'</td>';
              htmlstr+='<td style="border-bottom:1px #DFDFDF dashed" >'+info[2]+'&nbsp;</td><td style="border-bottom:1px #DFDFDF dashed">'+info[3]+'&nbsp;</td></tr>\n';
            }
            else if (type=='tc') {
              htmlstr+='<tr id="dynsearchtr_'+eval(i+1)+'" onclick="setDynamicSearchValue(dynsearch_highlight_row)" onmouseover="highlightRow(dynsearch_highlight_row,0);dynsearch_highlight_row='+eval(i+1)+';highlightRow('+eval(i+1)+',1);" style="cursor:hand;cursor:pointer"><td style="border-bottom:1px #DFDFDF dashed" >'+highlightString(info[0],txtField.value)+'</td>';
              htmlstr+='</tr>\n';
            }
            else if (type=='icd') {
              htmlstr+='<tr id="dynsearchtr_'+eval(i+1)+'" onclick="setDynamicSearchValue(dynsearch_highlight_row)" onmouseover="highlightRow(dynsearch_highlight_row,0);dynsearch_highlight_row='+eval(i+1)+';highlightRow('+eval(i+1)+',1);" style="cursor:hand;cursor:pointer"><td style="border-bottom:1px #DFDFDF dashed" >'+highlightString(info[0],txtField.value)+'</td>';
              htmlstr+='<td style="border-bottom:1px #DFDFDF dashed" >'+highlightString(info[3],txtField.value)+'</td></tr>\n';
            }
            idArray[i]=info[1];
            nameArray[i]=info[0];
        }
    }
    htmlstr+='\n';
//alert(htmlstr);
    if (isIE)
        txtDiv.style.top=20;
    else    
        txtDiv.style.top=lookupDiv.clientHeight;
    lookupDiv.style.zIndex=200;
    txtDiv.style.zIndex=199;
    if (txtField.value.length>0) {
        if (checkParentHeight && !initParentHeight && pframe!='') {
            if (self.name==null || self.name==pframe) {
                parentFrame=parent.document.getElementById(pframe);
                initParentHeight=document.body.scrollHeight;
            }
            else if (pframe2!='' && self.name==pframe2) {
                parentFrame=parent.document.getElementById(pframe2);
                initParentHeight=document.body.scrollHeight;
            }
        }
        txtDiv.innerHTML=htmlstr;
        txtDiv.style.display="block";
        if (isIE)
            lookupDiv.style.height=parseInt(txtDiv.clientHeight)+parseInt(txtDiv.style.top);
        if (isIE6)
          hideComboBoxes();
    }
    if (checkParentHeight && parentFrame)
        setParentHeight(true);
}

// adjust parent frames height
function setParentHeight(isincrease) {
    if (isincrease) {
        var intTop=parseInt(txtDiv.style.top);
        if (txtDiv.clientHeight+intTop>initParentHeight)
            parentFrame.height=txtDiv.clientHeight+intTop+10;
    }
    else if (initParentHeight) {
        parentFrame.height=initParentHeight;
    }
}

// finding the combobox position on the page
function comboPosition(ele,axis,pos) {
  var pele=ele.offsetParent;
  if (pele==null)
    return pos;
  if (axis=="x")
      return comboPosition(pele,axis,eval(pos+pele.offsetLeft));
  else
      return comboPosition(pele,axis,eval(pos+pele.offsetTop));
}

// fixing combobox display problems for IE6
function hideComboBoxes() {
    var divTop=comboPosition(txtDiv,"y",txtDiv.offsetTop);
    var divBottom=eval(divTop+txtDiv.offsetHeight);
    var divLeft=comboPosition(txtDiv,"x",txtDiv.offsetLeft);
    var divRight=eval(divLeft+txtDiv.offsetWidth);
    
    var elarr=document.getElementsByTagName("select");
    var etop,ebottom,eleft,eright;
    var lefttopin=false,leftbottomin=false,righttopin=false,rightbottomin=false;
    if (elarr!=null && elarr.length>0) {
      for (var i=0; i < elarr.length; i++) {
        etop=comboPosition(elarr[i],"y",elarr[i].offsetTop);
        ebottom=eval(etop+elarr[i].offsetHeight);
        eleft=comboPosition(elarr[i],"x",elarr[i].offsetLeft);
        eright=eval(eleft+elarr[i].offsetWidth);
        lefttopin=(etop >= divTop && etop <= divBottom && eleft >= divLeft && eleft <= divRight);
        leftbottomin=(ebottom >= divTop && ebottom <= divBottom && eleft >= divLeft && eleft <= divRight);
        righttopin=(etop >= divTop && etop <= divBottom && eright >= divLeft && eright <= divRight);
        rightbottomin=(ebottom >= divTop && ebottom <= divBottom && eright >= divLeft && eright <= divRight);
        if (lefttopin || leftbottomin || righttopin || rightbottomin) {
          comboArray[comboArray.length]=elarr[i];
          elarr[i].style.visibility="hidden";
        }
      }
    }
}

// highlight row on selected item
function highlightRow(row,onoff) {
    var trrow=document.getElementById("dynsearchtr_"+row);
    if (trrow)
        if (onoff==1)
            trrow.style.backgroundColor='yellow';
        else
            trrow.style.backgroundColor='white';
}

// highlight matched string
function highlightString(mstr,hstr) {
  var highlightstr=hstr;
  var lastindex=highlightstr.lastIndexOf(",");
  if (lastindex>-1)
    highlightstr=highlightstr.substring(lastindex+1);
  if (highlightstr!='')
    return doHighlight(mstr,highlightstr,"<span style='font-weight:bold'>","</span>");
  else
    return '';
}

// clear dynamic search div
function clearDynamicSearch(isSetValue) {
    idArray = new Array(0);
    nameArray = new Array(0);
    if (txtDiv) {
        txtDiv.style.display="none";
        txtDiv.innerHTML="";
        if (isSetValue)
            setDynamicSearchValue(0);
        if (checkParentHeight && parentFrame)
            setParentHeight(false);
        if (isIE)
           lookupDiv.style.height="100%";
        lookupDiv.style.zIndex=100;
        txtDiv.style.zIndex=99;
    }
    if (isIE6 && comboArray.length>0) {  // fix IE6 combobox display problem
      for (var i=0; i < comboArray.length; i++)
        comboArray[i].style.visibility="visible";
      comboArray.length=0; //clear combo array
    }
}

// set selected item
function setDynamicSearchValue(row,nocleartxt) {
    if (idField) {
        if (ismultiple) {
            var idString=idField.value;
            var txtString=txtField.value;

            if (txtString.endsWith(",") && row>0 && row<=idArray.length) { //remove last selection
                idString=idString.substring(0,idString.length-1);
                txtString=txtString.substring(0,txtString.length-1);
                if (idString.lastIndexOf(",")>-1) {
                    idString=idString.substring(0,idString.lastIndexOf(",")+1);
                    txtString=txtString.substring(0,txtString.lastIndexOf(",")+1);
                }
                else {
                    idString='';
                    txtString='';
                }
            }
            else if (!txtString.endsWith(",")) { //remove trailing characters in multi-select
                txtString=txtString.substring(0,txtString.lastIndexOf(",")+1);
                var txtcount=0,idcount=0;
                for (i=0; i < txtString.length; i++)
                    if (txtString.charAt(i)==',')
                        txtcount++;
                for (i=0; i < idString.length; i++)
                    if (idString.charAt(i)==',')
                        idcount++;
                while (idcount>txtcount) {
                    idString=idString.substring(0,idString.length-1);
                    idString=idString.substring(0,idString.lastIndexOf(",")+1);
                    idcount--;
                }
            }
            if (row>0 && row<=idArray.length) {
                idField.value=idString+idArray[eval(row-1)]+",";
                txtField.value=txtString+nameArray[eval(row-1)]+",";
            }
            else {
                idField.value=idString;
                txtField.value=txtString;
            }
        }
        else {
            if (row==0) {
                if (nocleartxt==null || !nocleartxt) {
                    idField.value=0;
                    txtField.value='';
                }
                else 
                    idField.value=0;
            }
            else if (row>0 && row <= idArray.length) {
                idField.value=idArray[eval(row-1)];
                txtField.value=nameArray[eval(row-1)];
            }
        }
        //if (isupdatecost) 
        //    updateUserCost();
        if (onChangeFunction)
            onChangeFunction();
    }
}

function toTextBoxEnd(field) {
    if (field.createTextRange) {
        var r = (field.createTextRange());
        r.moveStart('character', (field.value.length));
        r.collapse();
        r.select();
    }
    else {
        if(field.selectionStart) {
            field.focus();
            field.setSelectionRange(field.value.length, field.value.length);
        }
        else
            field.focus();
    }
}

// Prototype functions for string operations
String.prototype.trim = function(){
return this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")}
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
    highlightEndTag = "</font>";
  }
  
  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  return newText;
}
