var ie4=document.all&&navigator.userAgent.indexOf("Opera")==-1
var ns6=document.getElementById&&!document.all
var ns4=document.layers

var daysBack = new Array(-1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,40,50,60,70,80,90,100,120,140,160,180);
var searchblk_pre = "searchCriteria_";
var sltStatuses;

function init() {
	// main content tab selected by default
	if (document.getElementById("reload").value == 1) {
		location.reload();
	}
	tabClick('searchblock_maincontent_tab');
	
	initArea();
	InitGroupedFields();

	// initialize summary block
	// server side sends list of defined criteria to hidden field 'preselected'
	// then 'Apply' button pressed for each of these elements
	var defined = document.getElementById('preselected').getAttribute('value') ;
	var arrDefined = defined.split(',');
	//w = "javascript:";

	for (var ix in arrDefined) {
		var block = document.getElementById(arrDefined[ix]+'_block');
		if (block == null) continue;
		var anchors = block.getElementsByTagName('a');
		for (var i = 0; i < anchors.length; i++) {
			var anchor = anchors[i];
			if ( anchor.getAttribute('id') == 'applyLnk') {
				//var cmd = anchor.href.substring(w.length);
				//eval(cmd);
				if( anchor.onclick!=null )
					anchor.onclick();
			}
		}

	}
	
	var elem = document.getElementById(searchblk_pre+'lst_advcrit');
	selectCriteria(elem);

	var mfields 
	// With NS ASP.NET produces table for Panel object instead of DIV.
	// So to get the list of div's wee need to drill through
	// <tbody><tr><td>, and then get children
	if (ns4) {	
		mfields = document.getElementById(searchblk_pre+'searchblock_maincontent');
		for( ; mfields != null && mfields.tagName!="TD" && mfields.tagName!="td"; mfields=mfields.firstChild);
		mfields=mfields.childNodes;
	} else {
		mfields = document.getElementById(searchblk_pre+'searchblock_maincontent').childNodes;
	}

	for (i=0; i < mfields.length; i++) {
		if ( mfields[i].nodeName == "#text" ) continue; // skip plain text (NS)
		var fld = mfields[i];
		// some main criteria could be hidden by server side. 
		if ( fld.style.display != 'none' ) {
			fld.style.display = 'block';
		}
		//fld.style.width = '550';
	}
	
	sltStatuses = new StatusList();
	
	tabClick('searchblock_maincontent_tab'); // make main tab visible and aligned
}


function initArea() {
	var sltArea = document.getElementById("area_list").getElementsByTagName("select")[2];
	var sltAreaSelected = document.getElementById("area_list").getElementsByTagName("select")[1];
	var sltCounty = document.getElementById("area_list").getElementsByTagName("select")[0];
	var hdnSelAreas = document.getElementById("area_list_hlt");
	var tmpArr = hdnSelAreas.value.split(",");
	var arrSelAreas = new Object();

	for (j = 0; j < tmpArr.length; j++) {
		if (tmpArr[j] != "") {
			arrSelAreas[tmpArr[j]] = tmpArr[j];
		}
	}

	dftCounty = "";
	for (ar in arrSelAreas) {
		dftCounty = arrAllAreas[ar].county;
		break;
	}

	for (ar in arrSelAreas) {
		var hOpt = new Option(arrAllAreas[ar].text, arrAllAreas[ar].value);
		sltAreaSelected.options[sltAreaSelected.options.length] = hOpt;
		//if( arrAllAreas[ar].parentValue!=null && arrAllAreas[ar].parentValue!='') {
		//	hOpt.text = "&nbsp;&nbsp;&nbsp;&nbsp;" + hOpt.text;
		//}
	}

	var i = 0;
	for (c in arrCounty) {
		sltCounty.options[i] = new Option(c);
		if ( dftCounty == "" ) {
			dftCounty = sltCounty.options[0].text;
		}
		if (c == dftCounty) {
			sltCounty.options[i].selected = true;
		}
		i++;
	}
	
	loadArea(dftCounty);

	/*var elArea = document.getElementById("area_list").getElementsByTagName("select")[2];
	for (i = 0; i < elArea.length; i++) {
		if ( arrSelAreas[ elArea[i].value ] != "" && arrSelAreas[ elArea[i].value ] != null ) {
			elArea[i].selected = true;
		}
	}*/
}

function loadArea(countyname) {

	var hdnSelAreas = document.getElementById("area_list_hlt");
	var arrSelectedValues = hdnSelAreas.value.split(",");
	var elArea = document.getElementById("area_list").getElementsByTagName("select")[2];

	elArea.options.length = 0;
	// in case we have optgroups
	while( elArea.firstChild ) elArea.removeChild(elArea.firstChild);

	// create an associative array of selected area ids (id=>true) to quickly identify selected areas
	var aSelAreaMap = new Array();
	for(i = 0; i < arrSelectedValues.length; i++)
		aSelAreaMap[arrSelectedValues[i]]=true;

	var ix=0;
	for (j = 0; j < arrCounty[countyname].length; j++ )
	{
		// if the area is selected, skip it
		if( aSelAreaMap[arrCounty[countyname][j]]==true ) {
			continue;
		}

		// if the area has a parent and the parent is selected, skip it
		if( arrAllAreas[arrCounty[countyname][j]].parentValue!=null && arrAllAreas[arrCounty[countyname][j]].parentValue!=''
			&& aSelAreaMap[arrAllAreas[arrCounty[countyname][j]].parentValue]==true ) {
			continue;	
		}

		
		elArea.options[ix] = new Option(arrAllAreas[arrCounty[countyname][j]].text,arrAllAreas[arrCounty[countyname][j]].value);
		elArea.options[ix].selected = false;
		
		if( arrAllAreas[arrCounty[countyname][j]].parentValue!=null && arrAllAreas[arrCounty[countyname][j]].parentValue!='') {
			// charcode 160 = &nbsp;
			elArea.options[ix].text = String.fromCharCode(160, 160, 160, 160) + elArea.options[ix].text;
		}	
		ix++;
		
		/*for(i = 0; i < arrSelectedValues.length; i++)
		{
			if( arrCounty[countyname][j] == arrSelectedValues[i] ) 
			{
				//elArea.options[j].selected = true;
				setOptionEnabled(elArea.options[j],false);
				break;
			}	
		}*/
	}
}

/**
  Binary search
  1. Array MUST be sorted already
  2. If the array has multiple elements with the same value the first instance
     in the array is returned e.g.
       [1,2,3,3,3,4,5].binarySearch(3);  // returns 2
     This means slightly more loops than other binary searches, but I figure
     it's worth it, as the worst case searchs on a 1 million array is around 20
  3. The return value is the index of the first matching element, OR
     if not found, a negative index of where the element should be - 1 e.g.
       [1,2,3,6,7].binarySearch(5);      // returns -4
       [1,2,3,6,7].binarySearch(0);      // returns -1
     To insert at this point do something like this:
       var array = [1,2,3,6,7];
       var index = array.binarySearch(5);
       if(index < 0)
         array.splice(Math.abs(index)-1, 0, 5); // inserted the number 5
**/
function arrayBinarySearch(arr,item,fCompare,compareContext)
{
  var left = -1,
      right = arr.length,
      mid;

  while(right - left > 1)
  {
    mid = (left + right) >>> 1;
    if(fCompare(arr[mid],item,compareContext) < 0)
      left = mid;
    else
      right = mid;
  }

  if(fCompare(arr[right],item,compareContext)!=0)
    return -(right + 1);

  return right;
}

function getAllSelectedOptions(hSelect) {
	var retVal = new Array();	
	var i;
	while (hSelect.selectedIndex != -1)
    {
        retVal.push(hSelect.options[hSelect.selectedIndex]);
        hSelect.options[hSelect.selectedIndex].selected = false;
    }    
    for( i=0;i<retVal.length;i++ ) {
		retVal[i].selected = true;
    }
	return retVal;
}

function compareAreaOptionOrderIndex(optA,optB,context) {
	if( (optA==null || optA.value==null) && (optB==null || optB.value==null) ) return 0;
	if( (optA==null || optA.value==null) ) return -1;
	if( (optB==null || optB.value==null) ) return 1;

	return arrAllAreas[optA.value].orderIndex - arrAllAreas[optB.value].orderIndex;
}

function addSelectedAreas(critId) {
	// get select element for Areas
	var selArea = document.getElementById("area_list").getElementsByTagName("select")[2];
	// get select element for Counties
	var selCounty = document.getElementById("area_list").getElementsByTagName("select")[0];
	// get select element for Areas selected
	var selAreaSelected = document.getElementById("area_list").getElementsByTagName("select")[1];
	var i,j;
	
	var aSelectedOptions = getAllSelectedOptions(selArea);
	var lastParentId = '';
	for( i=0;i<aSelectedOptions.length; i++) {
		var optVal = aSelectedOptions[i].value;
		if( arrAllAreas[optVal].parentValue!=null && arrAllAreas[optVal].parentValue!='' ) {
			// this is a sub Value
			if(lastParentId != arrAllAreas[optVal].parentValue ) {
				var hOpt = new Option(arrAllAreas[optVal].text, arrAllAreas[optVal].value);
				selAreaSelected.options[selAreaSelected.options.length] = hOpt;				
			}
			var optIndex = arrayBinarySearch(selArea.options,aSelectedOptions[i],compareAreaOptionOrderIndex,null);
			if( optIndex >=0 ) {
				selArea.options[optIndex] = null;
			}
		}
		else {
			// this is a parent value
			lastParentId = optVal; 
			// remove any sub items that are already selected
			for( j=selAreaSelected.options.length-1;j>=0;j-- ) {
				if( arrAllAreas[selAreaSelected.options[j].value].parentValue == lastParentId ) {
					selAreaSelected.options[j]=null;
				}
			}
			var hOpt = new Option(arrAllAreas[optVal].text, arrAllAreas[optVal].value);
			selAreaSelected.options[selAreaSelected.options.length] = hOpt;
			var optIndex = arrayBinarySearch(selArea.options,aSelectedOptions[i],compareAreaOptionOrderIndex,null);
			if( optIndex >=0 ) {		
				selArea.options[optIndex] = null;
				// now remove all child items (they are bumped in index by every assignement)
				while( selArea.options[optIndex] != null && arrAllAreas[selArea.options[optIndex].value].parentValue == lastParentId ) {
					selArea.options[optIndex] = null;
				}
			}
		}			
	}
	selectArea(critId);
}

function removeSelectedAreas(critId) {
	// get select element for Areas
	var selArea = document.getElementById("area_list").getElementsByTagName("select")[2];
	// get select element for Counties
	var selCounty = document.getElementById("area_list").getElementsByTagName("select")[0];
	// get select element for Areas selected
	var selAreaSelected = document.getElementById("area_list").getElementsByTagName("select")[1];
	var i,j;
	
	var aSelectedOptions = getAllSelectedOptions(selAreaSelected);
	var lastParentId = '';
	for( i=0;i<aSelectedOptions.length; i++) {
		var optVal = aSelectedOptions[i].value;	
		
		// if the selected element is in the current county, we need to add it to available list
		if( arrAllAreas[optVal].county==selCounty[selCounty.selectedIndex].text ) {
			var optIndex = arrayBinarySearch(selArea.options,aSelectedOptions[i],compareAreaOptionOrderIndex,null);
			if( optIndex < 0 ) {		
				// need to insert at -optIndex - 1
				var hOpt = new Option(arrAllAreas[optVal].text,arrAllAreas[optVal].value);
				if( arrAllAreas[optVal].parentValue!=null && arrAllAreas[optVal].parentValue!='') {
					hOpt.text = String.fromCharCode(160, 160, 160, 160) + hOpt.text;
				}		
				selArea.options.add(hOpt, -optIndex - 1);
				
				if( arrAllAreas[optVal].childValues!=null && arrAllAreas[optVal].childValues.length>0) {
					// need to also add all sub items
					for(j=0;j<arrAllAreas[optVal].childValues.length;j++) {
						var sChildVal = arrAllAreas[optVal].childValues[j];
						optIndex = arrayBinarySearch(selArea.options,arrAllAreas[sChildVal],compareAreaOptionOrderIndex,null);
						if( optIndex < 0 ) {
							hOpt = new Option(String.fromCharCode(160, 160, 160, 160) + arrAllAreas[sChildVal].text,arrAllAreas[sChildVal].value);
							selArea.options.add(hOpt, -optIndex - 1);
						}
					}
				}			
			}
		}
		// now remove all selected options
		while (selAreaSelected.selectedIndex != -1)
		{
			selAreaSelected.options[selAreaSelected.selectedIndex]=null;
		}
	}
	selectArea(critId);
}

function setSelCritBtnState(idBase,btnType,state) {
	var hBtn = document.getElementById(idBase+'_btn_'+btnType);
	if( hBtn ) {
		if( state ) {
			hBtn.src=hBtn.src.replace('disabled','enabled');
		}
		else {
			hBtn.src=hBtn.src.replace('enabled','disabled');
		}
	}
}

function selectArea(areaid) {
	// get select element for Areas
	var selArea = document.getElementById("area_list").getElementsByTagName("select")[2];
	// get select element for Counties
	var selCounty = document.getElementById("area_list").getElementsByTagName("select")[0];
	// get select element for Areas selected
	var selAreaSelected = document.getElementById("area_list").getElementsByTagName("select")[1];
	
	
	var hdnSelAreas = document.getElementById("area_list_hlt");
	var arrSelectedValues = hdnSelAreas.value.split(",");
	// get selected county
	var county = selCounty[selCounty.selectedIndex].text;
	var strSelectedValues = "";
	// for hidden field value remove all selected areas for current county
	//for (i = 0; i < arrSelectedValues.length; i++) {
	//	if ( arrCountyRev[arrSelectedValues[i]] != county) {
	//		strSelectedValues += strSelectedValues == "" ? arrSelectedValues[i] : ","+arrSelectedValues[i];
	//	}
	//}
	// add all currently selected areas to hidden field value
	for (i = 0; i < selAreaSelected.options.length; i++) {
		//if ( selArea.options[i].selected ) {
			strSelectedValues += strSelectedValues == "" ? selAreaSelected.options[i].value : ","+selAreaSelected.options[i].value;
		//}
	}
	hdnSelAreas.value = strSelectedValues;
	
	setCriterion(areaid, "area");
}

// ------------------------------------
// PURPOSE: This function adds an option from the source listbox to the destination one.
//
// INPUTS: source and destination listboxes
//
// RETURNS: 
// ------------------------------------
function moveselected(src, dest) {

	// GET THE  INDEX OF SELECTED ITEM(FIRST IS 0)
	idx = src.selectedIndex;
   
	while( idx >= 0) { 	//do nothing if no selection

		//check whether it is a newly selected area
		//only add, if it is not listed in the "selected" listbox
		for (i=0; i<dest.options.length; i++ ){	//loop through the already selected areas

			if (src.options[idx].value == dest.options[i].value){
				//if the current item already listed among the selected areas
				//QUIT THE FUNCTION WITHOUT ADDING THE ITEM
				return ;
			}
		}
		//create the new option object
		var objOption = new Option(src.options[idx].text, src.options[idx].value);

		//add the option
		dest.options[dest.length] = objOption;	
		//remove selected option from source
		//var opts = new Array(src.options.length - 1 );
		//for (i=0;i<src.options.length;i++) {
		//	if (i == idx) {
		//		src.options[i] = null;
		//	} 
		//}
		src.options[idx] = null;
		
		idx = src.selectedIndex; // prepare for next iteration
	}
}

/// ------------ Status management -----------------------
function movestatus(src, dest) {
	var ix = src.selectedIndex;
	// select status
	if ( src.selectedIndex != null ) {
		if ( ix < 0 ) return ;
		sltStatuses.add (src.options[ix].value, src.options[ix].text);
		src.options[ix] = null;
		
	// remove from selected
	} else { 
		if (document.getElementById("status_list_hlt").value == "") return;
		var hilited = document.getElementById("status_list_hlt").value.split(",");
		for (var i in hilited) {
			// add option to select box
			var objOption = new Option(statuslist[ hilited[i] ], hilited[i]);
			dest.options[dest.length] = objOption;
			// remove 
			sltStatuses.remove(hilited[i]);
			var ptn = new RegExp(hilited[i]+",?");
			document.getElementById("status_list_hlt").value = document.getElementById("status_list_hlt").value.replace(ptn, "");
		}
		setSelCritBtnState('ListStatus','del',false);
	}
}

function hilite(rowid) {
	var row = document.getElementById(rowid);	
	//var anc = row.getElementsByTagName("a")[0];
	if (ie4) {
		if (row.style.backgroundColor == "") {
			row.style.backgroundColor = "#b2b4bf";
			//anc.style.color = "white";
		} else {
			row.style.backgroundColor = "";
			//anc.style.color = "black";
		}
	} else {
		if ( row.getAttribute("style") != null && row.setAttribute("style") != "") {
			row.setAttribute("style", "");
		} else {
			row.setAttribute("style", "background-color:#b2b4bf");
		}
	}
	var s = "statusrow_";
	var hdnHilit = document.getElementById("status_list_hlt");
	
	var code = rowid.substring(s.length, rowid.length);
	var rex = new RegExp(code+",?", "gi");

	if ( rex.test(hdnHilit.value) ) {	
		hdnHilit.value = hdnHilit.value.replace(rex, "");
	} else {
		if (hdnHilit.value != "") hdnHilit.value += ",";
		hdnHilit.value += code;
	}
	
	setSelCritBtnState('ListStatus','del',(hdnHilit.value != ""));
}


var statuslist = new Object();

function StatusList() {
	this.list = document.getElementById("status_list");
	// add defined statuses to statuslist variable
	var rows  = this.list.rows;
	for (var i = 0; i < rows.length; i++) {
		var code = rows[i].childNodes[0].getElementsByTagName("input")[0].value;
		var name = "";
		if ( ns4 ) {
			name = rows[i].childNodes[0].getElementsByTagName("span")[0].text;
		} else {
			var ac = rows[i].childNodes[0].getElementsByTagName("span")[0];
			name = ac.innerHTML;
		}
		statuslist[code] = name;
	}

}

// add status to statuslist
StatusList.prototype.add = function(statuscode, status) {
	statuslist[statuscode] = status;
	this.refresh();
}

// remove requested status from statuslist
// then clear status table and add all rows from status list
StatusList.prototype.remove = function(statuscode) {
	var obj = new Object();
	for ( var item in statuslist ) {
		if (item != statuscode) {
			obj[item] = statuslist[item];
		}
	}
	statuslist = obj;
	this.refresh();
}

//get text by code value
StatusList.prototype.get = function(statuscode) {
	var tbody = new TableBody( this.list.getElementsByTagName("tbody")[0] );
	var row = document.getElementById("statusrow_"+statuscode);
	var anchor = row.getElementsByTagName("span")[0];
	return anchor.innerHTML;
}

StatusList.prototype.refresh = function() {
	var length = this.list.rows.length;
	var alertStatusFlagsList = new Object();
	// clean old list
	for (i=0; i<length; i++) {
		//if ( this.list.rows[i].getElementsByTagName("th").length > 0 ) continue;
		//if ( i == 0 ) continue; // skip title row
		var scode = this.list.rows[0].getElementsByTagName("td")[0].getElementsByTagName("input")[0].value;
		var aalert = document.getElementById("sentToAgent_"+scode).checked;
		var calert = document.getElementById("sentToClient_"+scode).checked;
		var days = document.getElementById("daysBack_"+scode).value;
		alertStatusFlagsList[scode] = new AlertStatusFlags(scode, aalert, calert, days);
		this.list.deleteRow(0);
	}
	
	// add all curently selected statuses
	for ( var item in statuslist ) {
		this.addStatus(item, statuslist[item], alertStatusFlagsList[item]);
	}
}

StatusList.prototype.addStatus = function(statuscode, status, alertStatusFlags) {

	var row = new TableRow();
	row.row.setAttribute("id", "statusrow_" + statuscode);
	
	var nameCell = new TableCell();
	var sentToAgentCell = new TableCell();
	var sentToClientCell = new TableCell();
	var daysBackCell = new TableCell();
	
	if ( alertStatusFlags == null ) {
		alertStatusFlags = new AlertStatusFlags(statuscode, true, true, -1);
	}
	
	if ( alertStatusFlags.days == -1 && status.toLowerCase() != "active" ) {
		alertStatusFlags.days = 30;
		if ( status.toLowerCase() == "sold" ) {
			alertStatusFlags.days = 60;
		}
	}
	
	// create cell (td) with status name as link
	nameCell.cssClass("c1");
	sentToAgentCell.cssClass("c2");
	sentToClientCell.cssClass("c3");
	daysBackCell.cssClass("c4");
	
	/*var el = document.createElement("a");
	el.setAttribute("href", "javascript:hilite('"+row.row.getAttribute("id")+"')");
	

	if (ie4) {
		el.className = "sb_statusitem";
	} else {
		el.setAttribute("class", "sb_statusitem");
	}
	
	el.appendChild ( document.createTextNode(status) );
	nameCell.appendChild(el);
	*/
	var el = document.createElement("span");
	el.appendChild ( document.createTextNode(status) );
	nameCell.appendChild(el);
	
	nameCell.cell.onclick=new Function("hilite('"+row.row.getAttribute("id")+"')");
	nameCell.cell.style.cursor = ie4 ? "hand" : "pointer";
	
	el = document.createElement("input");
	el.type="hidden";
	el.value=statuscode;
	nameCell.appendChild(el);
	
	el = document.createElement("input");
	el.name="sentToAgent_"+statuscode;
	el.id="sentToAgent_"+statuscode;
	el.type="checkbox";
	sentToAgentCell.appendChild(el);
	
	el = document.createElement("input");
	el.name="sentToClient_"+statuscode;
	el.id="sentToClient_"+statuscode;
	el.type="checkbox";
	sentToClientCell.appendChild(el);
	
	el = document.createElement("select");
	el.name="daysBack_"+statuscode;
	el.id="daysBack_"+statuscode;
	el.className = "select_el ";
	
	var opt;
	for ( i=0; i<daysBack.length; i++) {
		var v = daysBack[i] == -1 ? "Any" : daysBack[i];
		var isSel = daysBack[i] == alertStatusFlags.days;
		opt = new Option(v, daysBack[i]);
		if (ns6) {
			el.add(opt, null);
		} else {
			el.add(opt);
		}
		el[i].selected = isSel;
	}
	
	daysBackCell.appendChild(el);

	row.addCell( nameCell );
	row.addCell( sentToAgentCell );
	row.addCell( sentToClientCell );
	row.addCell( daysBackCell );
	
	var tbody = new TableBody( this.list.getElementsByTagName("tbody")[0] );
	tbody.addRow(row);
	
	document.getElementById("sentToAgent_"+statuscode).checked = alertStatusFlags.sentToAgent;
	document.getElementById("sentToClient_"+statuscode).checked = alertStatusFlags.sentToClient;
}

function AlertStatusFlags(status, aalert, calert, days) {
	this.status = status;
	this.sentToAgent = aalert;
	this.sentToClient = calert;
	this.days = days;
}

/// ------------ End Status management -----------------------

/// ------------ Manage Search Tab Selection --------------

function tabClick(tabID) {
	hideTab("searchblock_maincontent_tab");
	hideTab("searchblock_advcontent_tab");
	
	showTab(tabID);
}

function hideTab(tabID) {
	var hImg = document.getElementById(tabID);
	if(hImg) {
		hImg.src = hImg.src.replace("_select","_deselect");
		hImg.style.cursor = ie4 ? "hand" : "pointer";
	}	
	var s = tabID.replace(/_tab$/, "");
	document.getElementById(searchblk_pre+s).style.display="none";
}
function showTab(tabID) {
	var hImg = document.getElementById(tabID);
	if(hImg) {
		hImg.src = hImg.src.replace("_deselect","_select");
		hImg.style.cursor = "default";
	}	
	var s = tabID.replace(/_tab$/, "")
	document.getElementById("searchblock_border_left").style.display='none';
	document.getElementById("searchblock_border_right").style.display='none';
	document.getElementById("searchblock_bottom_right_corner").style.display='none';
	document.getElementById("searchblock_sum_opt_corner").style.display='none';
	

	document.getElementById( searchblk_pre+s ).style.display="block";
	
	window.setTimeout("alignTabBorders('"+tabID+"')",10);	
}
function alignTabBorders(tabID) {
	var s = tabID.replace(/_tab$/, "");
	document.getElementById("searchblock_border_left").style.display='';
	document.getElementById("searchblock_border_left").style.height=document.getElementById( searchblk_pre+s ).offsetHeight + "px";
	
	// calculate and apply new vorder image heights
	var rightBorderHeight = (document.getElementById( "searchblock" ).offsetHeight - document.getElementById("searchsum_block").offsetHeight);
	var bottomCornerHeight = 12;
	if( rightBorderHeight<0 ) rightBorderHeight=0;
	if( rightBorderHeight > bottomCornerHeight ) {
		document.getElementById("searchblock_border_right").style.display='';
		document.getElementById("searchblock_border_right").style.height=(rightBorderHeight-bottomCornerHeight) + "px";
		document.getElementById("searchblock_bottom_right_corner").style.display='';
		document.getElementById("searchblock_bottom_right_corner").style.height=bottomCornerHeight +"px";
		document.getElementById("searchblock_sum_opt_corner").style.display='';
	}
	else if( rightBorderHeight > 0 ) {
		document.getElementById("searchblock_bottom_right_corner").style.display='';
		document.getElementById("searchblock_bottom_right_corner").style.height=rightBorderHeight+"px";
		document.getElementById("searchblock_sum_opt_corner").style.display='';
	}
	// else leave it invisible (0px 0px)
}

/// ------------ End Manage Search Tab Selection --------------


/// ------------ Manage Adv Search Criteria -------------------

var lastSelectedCrit = null

function selectCriteria(sel) {
	ix= sel.selectedIndex;
	var critId = sel.options[ix].value;
	var crit = document.getElementById(critId+"_block");
	
	if (lastSelectedCrit != null) {
		lastSelectedCrit.style.display="none";
	}
	crit.style.display = "block";
	lastSelectedCrit = crit;	
}

function setCriterionT(critId, critType) {
	// a workaround for quirks changing text input values INSIDE the onchange/onkeyup event
	window.setTimeout("setCriterion('"+critId+"','"+critType+"')",1);
}

function setCriterion(critId, critType) {
	var crit = new Criterion(critId, critType);
	var val = crit.getValue();
	var critList = new SearchSummary();
	critList.add(crit);
	if (critType!="cbx" && val == "") {
		critList.remove(critId);
	}
	return;
}

function delCriterion(critId) {
	if( critId.indexOf("Status") == -1 && critId !="ST")
	{
		var critList = new SearchSummary();
		var crit = critList.get(critId);
		crit.reset();
		critList.remove(critId);
	}	
}

	/// ------ Criteria Value Accessor Definition -------
	
function Criterion(critId, critType) {
	this.suffix = "_block";
	this.critId = critId;
	this.crit = document.getElementById(this.critId+this.suffix);
	this.type = critType;
	this.hidden = document.createElement("input");
	this.hidden.setAttribute("type", "hidden");
}

Criterion.prototype.getDisplayName = function() {
	var nameId = this.critId + "_visname";
	var elm = document.getElementById(nameId);
	var txtDispName = elm.firstChild.nodeValue;
	// check existance and formatting for display (append ": " to end if doesn't have one)
	if( txtDispName == null )
		txtDispName = "Unknown";
	if( txtDispName.substr(txtDispName.length - 2) != ": " )
		txtDispName += ": ";
	return txtDispName;
}

Criterion.prototype.getHiddenField = function() {
	var inpId = this.critId;
	this.hidden.name=inpId + "_hidden";
	this.hidden.id=inpId + "_hidden";
	this.hidden.value=this.getValue();
	return this.hidden;
}

Criterion.prototype.getValue = function() {
	var obj = this[this.type + "GetValue"]();
	return obj;
}

Criterion.prototype.cbxGetValue = function() {
	var inpId = this.critId;
	var cbx = document.getElementById(inpId);
	return cbx.checked;
}

Criterion.prototype.dateGetValue = function() {
	var inpId = this.critId;
	if (document.SearchForm[inpId+"_dttype"][0].checked) {
		var inpLeftId = this.critId+"_left";
		var inpRightId = this.critId+"_right";
		var left = document.getElementById(inpLeftId);
		var right = document.getElementById(inpRightId);
		return left.value + "-" + right.value;
	} 
	if (document.SearchForm[inpId+"_dttype"][1].checked) {
		var inpUnits = this.critId+"_units";
		var inpUnitsBack = this.critId+"_unitsback";
		var numunits = document.getElementById(inpUnitsBack);
		var ix = document.SearchForm[inpUnits].selectedIndex;
		var r = "";
		if (ix != -1) {
			r = "NOW-" + numunits.value + document.SearchForm[inpUnits][ix].value;
		}
		return r;
	}
}

Criterion.prototype.numGetValue = function() {
	var inpId = this.critId;
	var elem = document.getElementById(inpId);
	
	// OT:10/25/04 fix common input mistakes
	var sOrigVal = elem.value;
	//alert('orig:'+sOrigVal);
	var sFixedVal = sOrigVal.replace(/[^\d\,\.\+\-\ ]/g,'');
	var m = null;
	// numbers entered using thousands separator (comma)
	sFixedVal = sFixedVal.replace(/\,000/g,"000");
	while(null != (m = (" "+sFixedVal+" ").match(/[^\d](\d{1,3}(,\d{3})+)[^\d]/) ) ) {
   		sFixedVal = sFixedVal.substr(0,m.index) + m[1].replace(/[,]/g,'') + sFixedVal.substr(m.index + m[1].length);
	}
	if( sFixedVal!=sOrigVal )
		elem.value=sFixedVal;

	//alert('fixed:'+sFixedVal);
	return elem.value;
}

Criterion.prototype.txtGetValue = function() {
	var inpId = this.critId;
	var elem = document.getElementById(inpId);
	return elem.value;
}

Criterion.prototype.sltGetValue = function() {
	var inpId = this.critId;
	var str = "";
	var elem = document.getElementById(inpId + "_rbNot");
	var isNotLogic = (elem!=null && elem.checked);
	str += isNotLogic ? "NOT: " : "";
	elem = document.getElementById(inpId);
	for (i=0; i<elem.options.length; i++) {
		if ( str != "" && str != "NOT: ") {
			str += ",";
		}
		str += elem.options[i].value;
	}
	return str;
}

Criterion.prototype.stsGetValue = function() {
	//var inpId = this.critId + "_list";
	// GG: hardcode status select id
	var inpId = "status_list";
	var elem = document.getElementById( inpId.toLowerCase() );
	var rows  = elem.rows;
	var str = "";
	for (var i = 0; i < rows.length; i++) {
		if ( str != "") {
			str += ",";
		}
		var obj = rows[i].childNodes[0].getElementsByTagName("input")[0];
		if ( obj != null ) str += obj.value;
	}
	return str;
}

Criterion.prototype.groupLkpGetValue = function() {
	var inpId = this.critId;
	var str = "";
	var elem = document.getElementById(inpId + "_rbNot");
	var isNotLogic = (elem!=null && elem.checked);
	str += isNotLogic ? "NOT: " : "";
	elem = document.getElementById(inpId + "_selected");
	for (i=0; i<elem.options.length; i++) {
		if ( str != "" && str != "NOT: ") {
			str += ",";
		}
		str += elem.options[i].value;
	}
	return str;
}

Criterion.prototype.areaGetValue = function() {
	var inpId = this.critId;
	var str = "";
//-- not in checkbox is removed
//	var elem = document.getElementById(inpId + "_notin");
//	str += elem.checked ? "NOT: " : "";

	var hdnSelAreas = document.getElementById("area_list_hlt");
	str += hdnSelAreas.value;

	return str;
}

Criterion.prototype.getDisplayValue = function() {
	var obj = this[this.type + "GetDisplayValue"]();
	return obj;
}

Criterion.prototype.cbxGetDisplayValue = function() {
	var s = this.cbxGetValue() ? "Yes" : "No"
	return s;
}

Criterion.prototype.dateGetDisplayValue = function() {
	var s = this.dateGetValue();
	return s;
}

Criterion.prototype.numGetDisplayValue = function() {
	var s = this.numGetValue();
	return s;
}

Criterion.prototype.txtGetDisplayValue = function() {
	var s = this.txtGetValue();
	return s;
}

Criterion.prototype.sltGetDisplayValue = function() {
	var inpId = this.critId;
	var elem = document.getElementById(inpId + "_rbNot");
	var isNotLogic = (elem!=null && elem.checked);
	var str = "";
	str += isNotLogic ? "NOT: " : "";
	elem = document.getElementById(inpId);
	for (i=0; i<elem.options.length; i++) {
		if ( str != "" && str != "NOT: ") {
			str += ", ";
		}
		str += elem.options[i].text;
	}
	return str;
}

Criterion.prototype.groupLkpGetDisplayValue = function() {
	var inpId = this.critId;
	var elem = document.getElementById(inpId + "_rbNot");
	var isNotLogic = (elem!=null && elem.checked);
	var str = "";
	str += isNotLogic ? "NOT: " : "";
	elem = document.getElementById(inpId + "_selected");
	for (i=0; i<elem.options.length; i++) {
		if ( str != "" && str != "NOT: ") {
			str += ", ";
		}
		str += elem.options[i].text;
	}
	return str;
}

Criterion.prototype.areaGetDisplayValue = function() {
	var inpId = this.critId;
//	var elem = document.getElementById(inpId + "_notin");
	var str = "";
	//str += elem.checked ? "NOT: " : "";
	var hdnSelAreas = document.getElementById("area_list_hlt");
	if( hdnSelAreas && hdnSelAreas.value!=null && hdnSelAreas.value!='' ) {
		var arrSelectedAreas = hdnSelAreas.value.split(",");
		for (i=0; i<arrSelectedAreas.length; i++) {
			
			var opts = arrCounty[ arrAllAreas[arrSelectedAreas[i]].county ];
			for (j=0; j<opts.length; j++) {
				if ( arrSelectedAreas[i] == arrAllAreas[opts[j]].value) {
					if ( str != "" && str != "NOT: ") {
						str += ", ";
					}
					str += arrAllAreas[opts[j]].text; 
				}
			}
			
		}
	}
	return str;
}



Criterion.prototype.stsGetDisplayValue = function() {
	var inpId = this.critId;
	// GG: hardcode status select id
	//var elem = document.getElementById(inpId.toLowerCase() + "_list");
	var elem = document.getElementById("status_list");
	var rows  = elem.rows;
	var str = "";

	for (var i = 0; i < rows.length; i++) {
		if ( str != "") {
			str += ", ";
		}
		if ( ns4 ) {
			if ( rows[i].childNodes[0].getElementsByTagName("span").length == 0 ) continue;
			str += rows[i].childNodes[0].getElementsByTagName("span")[0].text;
		} else {
			var obj = rows[i].childNodes[0].getElementsByTagName("span")[0];
			if ( obj != null ) str += obj.innerHTML;
		}
	}
	return str;
}

Criterion.prototype.reset = function() {
	this[this.type+"Reset"]();
}

Criterion.prototype.cbxReset = function() {
	var inpId = this.critId;
	var cbx = document.getElementById(inpId);
	cbx.checked = false;
}

Criterion.prototype.numReset = function() {
	var inpId = this.critId;
	var elem = document.getElementById(inpId);
	elem.value = "";
}

Criterion.prototype.dateReset = function() {
	//var inpUnits = this.critId+"_units";
	var left = document.getElementById(this.critId+"_left");
	var right = document.getElementById(this.critId+"_right");
	var uback = document.getElementById(this.critId+"_unitsback");
	left.value = "";
	right.value = "";
	uback.value = "";
}

Criterion.prototype.txtReset = function() {
	var inpId = this.critId;
	var elem = document.getElementById(inpId);
	elem.value = "";
}

Criterion.prototype.sltReset = function() {
	var inpId = this.critId;
	var elem = document.getElementById(inpId);
	while (elem.options.length >0) {
		elem.selectedIndex = 0;
		moveselected(document.getElementById(inpId), document.getElementById(inpId + "_from") );
	}
}

Criterion.prototype.areaReset = function() {
	var inpId = this.critId;
	var elem = document.getElementById(inpId);
	var i;
	
	var selAreasSelected = document.getElementById("area_list").getElementsByTagName("select")[1];
	for( i=0;i<selAreasSelected.options.length;i++ ) {
		selAreasSelected.options[i].selected = true;
	}
	removeSelectedAreas();
	selAreasSelected.onchange();	
}

Criterion.prototype.stsReset = function()
{
	// not in clientOrganizer
}

Criterion.prototype.groupLkpReset = function()
{
	var inpId = this.critId;
	elem = document.getElementById(inpId + "_selected");
	var i;
	for(i=0;i<elem.options.length;i++) {
		elem.options[i].selected = true;
	}
	deselectGroupValues(inpId);
}

	
	/// ------ End Criteria Value Accessor Definition -------
	
// ------------ End Manage Adv Search Criteria -------------------


// ------------ Manage Search Criteria Summary -------------------

var list = new Object();

function SearchSummary() {
	this.displayId = "critsum";
	this.hiddenId = "searchsum_hdn";
	this.display = document.getElementById(this.displayId);
	this.hidden = document.getElementById(this.hiddenId);
}

SearchSummary.prototype.get = function(critId) {
	return list[critId];
}

SearchSummary.prototype.add = function(crit) {
	list[crit.critId] = crit;
	this.refresh();
}

SearchSummary.prototype.remove = function(critId) {
	var obj = new Object();
	for ( var item in list ) {
		if (item != critId) {
			obj[item] = list[item];
		}
	}
	list = obj;
	this.refresh();
}

SearchSummary.prototype.refresh = function() {
	var length = this.display.rows.length;
	for (i=0; i<length; i++) {
		this.display.deleteRow(0);
	}
	
	while ( this.hidden.hasChildNodes() ) {
		this.hidden.removeChild( this.hidden.firstChild );
	}

	for ( var item in list ) {
		this.addCriteriaItem(list[item]);
	}
}

SearchSummary.prototype.addCriteriaItem = function(item) {
	var tbody = new TableBody( this.display.getElementsByTagName("tbody")[0] );
	var row = new TableRow();
	row.cssClass("criteria_row");
	
	var cell1 = new TableCell();
	var anc = document.createElement("a");
	anc.setAttribute("href", "javascript:delCriterion('"+item.critId+"')");

	if (ie4) {
		anc.className = "criteria_item_del";
	} else {
		anc.setAttribute("class", "criteria_item_del");
	}
	
	anc.setAttribute("title", "Remove criteria");
	
	if( item.critId.indexOf("Status") == -1 && item.critId !="ST")
	{
		var delimage = document.createElement("img");
		delimage.setAttribute("src", "../../images/SearchForm/trash.gif");
		delimage.setAttribute("border","0");
		anc.appendChild( delimage );
		cell1.appendChild(anc);
	}
	
	cell1.cssClass("criteria_item_del");
	var cell2 = new TableCell();
	cell2.text (item.getDisplayName() + item.getDisplayValue());
	cell2.cssClass("criteria_item");
	
	row.addCell(cell1);
	row.addCell(cell2);
	
	tbody.addRow(row);
	
	this.hidden.appendChild(item.getHiddenField());
}


	// -------------- List of defined items based on table -------------

function TableBody(tbody) {
	this.tbody = tbody;
}

TableBody.prototype.addRow = function(row) {
	this.tbody.appendChild(row.row);
}

function TableRow() {
	this.row = document.createElement("tr");
}

TableRow.prototype.addCell = function(cell) {
	this.row.appendChild(cell.cell);
}

TableRow.prototype.cssClass = function(str) {
	if (ns6) {
		if (!str ) return this.row.getAttribute("class");
		this.row.setAttribute("class", str);
	} 
	if (ie4) {
		if (!str ) return this.row.style.className;
		this.row.className = str;
	}
}

function TableCell() {
	this.cell = document.createElement("td");
}

TableCell.prototype.cssClass = function(str) {
	if (ns6) {
		if (!str ) return this.cell.getAttribute("class");
		this.cell.setAttribute("class", str);
	} 
	if (ie4) {
		if (!str ) return this.cell.style.className;
		this.cell.className = str;
	}
}

TableCell.prototype.setAttribute = function(name,val) {
	this.cell.setAttribute(name,val);
}

TableCell.prototype.text = function(str) {
	if (!str) {
		var s = "";
		for (n in this.cell.childNodes() ) {
			s += n.nodeValue;
		}
		return s;
	}
	while (this.cell.hasChildNodes()) {
		this.cell.removeChild();
	}
	this.cell.appendChild ( document.createTextNode( str ) );
}

TableCell.prototype.appendChild = function(element) {
	this.cell.appendChild(element);
}
	// -------------- List of defined items based on table -------------

// ------------ End Manage Search Criteria Summary ---------------


// ------------------------ Submit Search ------------------------

function callSubmit() {
	var node = document.getElementById(searchblk_pre+"advcrit");
	var s = "";

	if( node && node.parentNode )
	{
	var pnt_node = node.parentNode;
	pnt_node.removeChild(node);
	}
	if (ns6) {
		var hdn = document.createElement("input");
		hdn.name=searchblk_pre.replace(/_/g,":") + "btnSubmit";
		hdn.type="hidden";
		hdn.value="";
		//var f = document.getElementById("SearchForm");
		//f.appendChild(hdn);
		document.getElementById("reload").value=1;
		//document.SearchForm.submit();
		document.getElementById( searchblk_pre + "btnSubmit").click();
	} else {
		//document.getElementById( (searchblk_pre + "btnSubmit").replace(/_/, ':') ).click();
		document.getElementById("reload").value=1;
		document.getElementById( searchblk_pre + "btnSubmit").click();
	}
}

// --------------------- End Submit Search -----------------------

function callPreview()
{
document.getElementById( searchblk_pre + "btnPreview").click();
}
//--------- GroupedLookups

var aGroupedLookupFields = []; // fieldID => GroupedLookupData
function InitGroupedFields() {
	var fieldId
	for( fieldId in aGroupedLookupFields) {
		var groupData = aGroupedLookupFields[fieldId];
		
		var sltSelect = document.getElementById(fieldId+"_select");
		var sltSelected = document.getElementById(fieldId+"_selected");
		var sltGroups = document.getElementById(fieldId+"_group");
		
		var hdnSelected = document.getElementById(fieldId+"_list_hlt");
		var tmpArr = hdnSelected.value.split(",");
		var arrSelected = new Object();

		for (j = 0; j < tmpArr.length; j++) {
			if (tmpArr[j] != "") {
				arrSelected[tmpArr[j]] = true;
			}
		}

		var dftGroup = null;
		for (ar in arrSelected) {
			dftGroup = groupData.groupByValue[ar];
			break;
		}

		for (ar in arrSelected) {
			var lv = groupData.FindLookupValue(ar);
			if(lv) {
				var hOpt = new Option(lv.label, lv.value);
				sltSelected.options[sltSelected.options.length] = hOpt;
			}
		}

		var i = 0;
		for (g in groupData.groups) {
			if( groupData.hasSeparatorGroups == false ) {
				sltGroups.options[i] = new Option(groupData.groups[g].name,groupData.groups[g].number);
			}
			else {
				if( groupData.groups[g].isSeparator == true ) {
					sltGroups.options[i] = new Option(groupData.groups[g].name,groupData.groups[g].number);
					sltGroups.options[i].className='groupOptionSeparator';
				}
				else {
					sltGroups.options[i] = new Option(String.fromCharCode(160, 160, 160, 160) + groupData.groups[g].name,groupData.groups[g].number);
				}
			}
			if ( dftGroup == null && groupData.groups[g].isSeparator==false ) {
				dftGroup = g;
			}
			if (g == dftGroup) {
				sltGroups.options[i].selected = true;
			}
			i++;
		}
		
		loadGroup(fieldId,dftGroup);
		
	}
}
function validateGroupSelection(fieldId) {
	var sltGroups = document.getElementById(fieldId+"_group");
		
	if(sltGroups.options[sltGroups.selectedIndex].className=='groupOptionSeparator') {
		alert("You have selected an invalid item.\n\nPlease select one of the sub-items to proceed.");
		var groupData = aGroupedLookupFields[fieldId];
		var sltSelect = document.getElementById(fieldId+"_select");
		// find the last group and select it.
		if(sltSelect.options.length>0) {
			var optVal = sltSelect.options[0].value;
			var lkpVal = groupData.FindLookupValue(optVal);
			var i;
			for(i=0;i<sltGroups.options.length;i++) {
				if( sltGroups.options[i].value==lkpVal.groupNumber )
					sltGroups.selectedIndex = i;
			}
		}
		return false;
	}
	return true;
}
function loadGroup(fieldId,group) {
	var hdnSelected = document.getElementById(fieldId+"_list_hlt");
	var arrSelected = hdnSelected.value.split(",");
	var elSelect = document.getElementById(fieldId+"_select");
	var groupData = aGroupedLookupFields[fieldId];

	elSelect.options.length = 0;
	
	// in case we have optgroups
	while( elSelect.firstChild ) elSelect.removeChild(elSelect.firstChild);

	// create an associative array of selected area ids (id=>true) to quickly identify selected areas
	var aSelMap = new Array();
	for(i = 0; i < arrSelected.length; i++)
		aSelMap[arrSelected[i]]=true;

	var ix=0;
	for (j = 0; j < groupData.groups[group].values.length; j++ )
	{
		var lv = groupData.groups[group].values[j];
		// if the area is selected, skip it
		if( aSelMap[lv.value]==true ) {
			continue;
		}

		// if the area has a parent and the parent is selected, skip it
		//if( arrAllAreas[groupData.groups[group][j]].parentValue!=null && arrAllAreas[arrCounty[countyname][j]].parentValue!=''
		//	&& aSelAreaMap[arrAllAreas[arrCounty[countyname][j]].parentValue]==true ) {
		//	continue;	
		//}

		
		elSelect.options[ix] = new Option(lv.label,lv.value);
		elSelect.options[ix].selected = false;
		
		//if( arrAllAreas[arrCounty[countyname][j]].parentValue!=null && arrAllAreas[arrCounty[countyname][j]].parentValue!='') {
		//	// charcode 160 = &nbsp;
		//	elArea.options[ix].text = String.fromCharCode(160, 160, 160, 160) + elArea.options[ix].text;
		//}	
		ix++;		
	}
}

function selectGroupValues(fieldId) {
	var groupData = aGroupedLookupFields[fieldId];
	
	var sltSelect = document.getElementById(fieldId+"_select");
	var sltSelected = document.getElementById(fieldId+"_selected");
	var sltGroups = document.getElementById(fieldId+"_group");
	
	var hdnSelected = document.getElementById(fieldId+"_list_hlt");
		
	var i,j;
	
	var aSelectedOptions = getAllSelectedOptions(sltSelect);
	var lastParentId = '';
	for( i=0;i<aSelectedOptions.length; i++) {
		var optVal = aSelectedOptions[i].value;
		/*if( arrAllAreas[optVal].parentValue!=null && arrAllAreas[optVal].parentValue!='' ) {
			// this is a sub Value
			if(lastParentId != arrAllAreas[optVal].parentValue ) {
				var hOpt = new Option(arrAllAreas[optVal].text, arrAllAreas[optVal].value);
				selAreaSelected.options[selAreaSelected.options.length] = hOpt;				
			}
			var optIndex = arrayBinarySearch(selArea.options,aSelectedOptions[i],compareAreaOptionOrderIndex,null);
			if( optIndex >=0 ) {
				selArea.options[optIndex] = null;
			}
		}
		else {*/
			// this is a parent value
			//lastParentId = optVal; 
			// remove any sub items that are already selected
			/*for( j=selAreaSelected.options.length-1;j>=0;j-- ) {
				if( arrAllAreas[selAreaSelected.options[j].value].parentValue == lastParentId ) {
					selAreaSelected.options[j]=null;
				}
			}*/
			var lkpVal = groupData.FindLookupValue(optVal);
			var hOpt = new Option(lkpVal.label, lkpVal.value);
			sltSelected.options[sltSelected.options.length] = hOpt;
			var optIndex = arrayBinarySearch(sltSelect.options,aSelectedOptions[i],compareGroupOptionValueIndex,groupData);
			if( optIndex >=0 ) {		
				sltSelect.options[optIndex] = null;
				// now remove all child items (they are bumped in index by every assignement)
				//while( selArea.options[optIndex] != null && arrAllAreas[selArea.options[optIndex].value].parentValue == lastParentId ) {
				//	selArea.options[optIndex] = null;
				//}
			}
		//}			
	}
	applyGroupValueSelection(fieldId);
}

function deselectGroupValues(fieldId) {
	var groupData = aGroupedLookupFields[fieldId];
	
	var sltSelect = document.getElementById(fieldId+"_select");
	var sltSelected = document.getElementById(fieldId+"_selected");
	var sltGroups = document.getElementById(fieldId+"_group");
	
	var hdnSelected = document.getElementById(fieldId+"_list_hlt");
		
	var i,j;
	
	var aSelectedOptions = getAllSelectedOptions(sltSelected);
	var lastParentId = '';
	for( i=0;i<aSelectedOptions.length; i++) {
		var optVal = aSelectedOptions[i].value;	
		var lkpVal = groupData.FindLookupValue(optVal);
		
		// if the selected element is in the current county, we need to add it to available list
		if( lkpVal.groupNumber==sltGroups[sltGroups.selectedIndex].value ) {
			var optIndex = arrayBinarySearch(sltSelect.options,aSelectedOptions[i],compareGroupOptionValueIndex,groupData);
			if( optIndex < 0 ) {		
				// need to insert at -optIndex - 1
				var hOpt = new Option(lkpVal.label,lkpVal.value);
				//if( arrAllAreas[optVal].parentValue!=null && arrAllAreas[optVal].parentValue!='') {
				//	hOpt.text = String.fromCharCode(160, 160, 160, 160) + hOpt.text;
				//}		
				sltSelect.options.add(hOpt, -optIndex - 1);
				
				//if( arrAllAreas[optVal].childValues!=null && arrAllAreas[optVal].childValues.length>0) {
				//	// need to also add all sub items
				//	for(j=0;j<arrAllAreas[optVal].childValues.length;j++) {
				//		var sChildVal = arrAllAreas[optVal].childValues[j];
				//		optIndex = arrayBinarySearch(selArea.options,arrAllAreas[sChildVal],compareGroupOptionValueIndex,groupData);
				//		if( optIndex < 0 ) {
				//			hOpt = new Option(String.fromCharCode(160, 160, 160, 160) + arrAllAreas[sChildVal].text,arrAllAreas[sChildVal].value);
				//			selArea.options.add(hOpt, -optIndex - 1);
				//		}
				//	}
				//}			
			}
		}
		// now remove all selected options
		while (sltSelected.selectedIndex != -1)
		{
			sltSelected.options[sltSelected.selectedIndex]=null;
		}
	}
	applyGroupValueSelection(fieldId);
}

function applyGroupValueSelection(fieldId) {
	var groupData = aGroupedLookupFields[fieldId];
	
	var sltSelect = document.getElementById(fieldId+"_select");
	var sltSelected = document.getElementById(fieldId+"_selected");
	var sltGroups = document.getElementById(fieldId+"_group");
	
	var hdnSelected = document.getElementById(fieldId+"_list_hlt");
	
	var arrSelectedValues = hdnSelected.value.split(",");
	// get selected county
	var groupNumber = sltGroups[sltGroups.selectedIndex].value;
	
	var strSelectedValues = "";

	// add all currently selected areas to hidden field value
	for (i = 0; i < sltSelected.options.length; i++) {
		strSelectedValues += strSelectedValues == "" ? sltSelected.options[i].value : ","+sltSelected.options[i].value;
	}
	hdnSelected.value = strSelectedValues;
	
	setCriterion(fieldId, "groupLkp");
}

function GroupedLookupData(aGroupData) {
	var ig;
	this.groups = [];
	this.groupByValue = [];
	this.hasSeparatorGroups=false;
	for(ig=0;ig<aGroupData.length;ig++) {
		this.groups[aGroupData[ig][0]] = new GroupedLookupGroup(this,aGroupData[ig][0],aGroupData[ig][1]);				
	}
}
GroupedLookupData.prototype.FindLookupValue = function(val) {
	if( this.groupByValue[val]!=null )  {
		var g = this.groups[this.groupByValue[val]];
		if(g) {
			return g.values[g.valueIndex[val]];
		}
	}
	return null;
};

function compareGroupOptionValueIndex(optA,optB,groupData) {
	if( (optA==null || optA.value==null) && (optB==null || optB.value==null) ) return 0;
	if( (optA==null || optA.value==null) ) return -1;
	if( (optB==null || optB.value==null) ) return 1;

	var lvA = groupData.FindLookupValue(optA.value);
	var lvB = groupData.FindLookupValue(optB.value);
	return (lvA.groupNumber*1000 + lvA.index) - (lvB.groupNumber*1000 + lvB.index);
}

function GroupedLookupGroup(hGLD,iGroupNumber,aGroupData) {
	this.number=iGroupNumber;
	this.name=aGroupData[0];
	this.isSeparator=(aGroupData[1]==1?true:false);
	if( this.isSeparator==true ) 
		hGLD.hasSeparatorGroups=true;
	this.values=[];
	this.valueIndex = []; // value => index in values[] 
	var iv;
	for(iv=0;iv<aGroupData[2].length;iv++) {
		this.values[iv]=new GroupedLookupValue(hGLD,this.number,iv,aGroupData[2][iv]);
		this.valueIndex[this.values[iv].value]=iv;
	}
}
function GroupedLookupValue(hGLD,iGroupNumber,iValIndex,aValData) {
	this.groupNumber=iGroupNumber;
	this.index = iValIndex;
	this.label = aValData[0];
	this.value = aValData[1];
	hGLD.groupByValue[this.value]=this.groupNumber;
}
