// Constants/static variables for rendering the contract grid
var lCompanyNameWidth = 0;
var lContractNameWidth = 0;
var lContractBasisNameWidth = 0;
var lRowHeight = 0;
var lHeaderHeight = 0;
var renderRowHeight = 20;
var renderDefaultFieldWidth = 100;
var renderDefaultScrollbarHeightWidth = 17;
var ContextFieldId = 0;
var renderNormalHeaderHeight = 60;
var renderFlippedHeaderHeight = 90;
var renderFlippedRowHeader = 250;
var renderFlippedColumnWidth = 125;
var bDoneEthicalWarning = false;
var lResetScrollLeft = 0;
var lResetScrollTop = 0;
var bInRenderingFlag = false;
var bGotMaxRecords = false;
var gMenuContractId = "";
var gFields;

var MAX_RECORDS = 500;
var FUND_PRODUCT_TYPE = 30;
var MANUAL_FUND_LIST_PRODUCT_BASIS = 30;

var LIPPERSECTORSID = 1;
var IMASECTORSID = 2;
var FINEXSECTORSID = 3;


var strMutualExclusivity = "(This feature is disabled because you have selected another mutually-exclusive feature.)";
var strRightClickTooltip;
if (IsMac()) {
	strRightClickTooltip = "(Ctrl + click for options)";
} else {
	strRightClickTooltip = "(Right-click for options)";
}

var strAddToGridTooltip = "Add this field to the grid\r\n" + strRightClickTooltip;

// Cache the number of sort fields...
var cacheCountOfSortFields = 0;

var activeSectorDiv = "IMASectorFields";

// Marker for quote fields. Can be text of image etc..
var strSelectFieldHTML = "<img src='images/SelectContractButton.gif'  border='0' />"
  


function KE(e) {
	try {
		e.returnValue = false;
	}
	catch (errX) {}
	return null;
}

function HandleContractListResponse(objXML) {
	switch (objXML.status) {
		case 200:
			DisplayContractList(objXML.responseText);
			return true;

		case 281:
			// The response text includes a new, reduced list of contract IDs as
			// a result of new filtering being imposed
			var strIncludeContractList = objXML.responseText;
			ctExcluded = Zval(strIncludeContractList.split("|")[0]);

			// Remove any contracts which aren't included in the new list
			var bHasChanged = false;
			var arrNew = new Array();
			for (var iC = 0; iC < ctContracts; iC++) {
				if (strIncludeContractList.indexOf("|" + arrContracts[iC].ContractId + "|") == -1) {
					// Nope
					bHasChanged = true;
				} else {
					arrNew.push(arrContracts[iC]);
				}
			}
			
			if (bHasChanged) {
				arrContracts = arrNew;
				ctContracts = arrContracts.length;
                lngTotalResults = ctContracts;
				// Redisplay the contract list
				DisplayContractList("");
			} else {
				DisplayContractCount();
			}
			return true;


		case 282:
			var arrBlocks = objXML.responseText.split("~");
			
			// The response text contains a list of contract IDs, as a result
			// of the sort conditions on the list being changed
			var arrNew = new Array();
			var strIncludeContractList = arrBlocks[1];
			var arrIncludeContractList = strIncludeContractList.split("|");
			var ctNew = arrIncludeContractList.length;
			for (var iNew = 0; iNew < ctNew; iNew++) {
				if (arrIncludeContractList[iNew]) {
					for (var iOld = 0; iOld < ctContracts; iOld++) {
						if (arrContracts[iOld].ContractId == arrIncludeContractList[iNew]) {
							arrNew.push(arrContracts[iOld]);
							iOld = ctContracts;
						}
					}
				}
			}

			// Process the new sort fields
			var strSortFields = arrBlocks[0];
			ctSortFields = 0;
			if (!strSortFields) {
				ctSortFields = 0;
				arrSortFields = new Array();
			} else {
				var arrSortF = strSortFields.split("|");
				ctSortFields = arrSortF.length;
				arrSortFields = new Array(ctSortFields);
				for (var iSort = 0; iSort < ctSortFields; iSort++) {
					var arrSortPart = arrSortF[iSort].split(":");
					arrSortFields[iSort] = new SortField(arrSortPart[0], arrSortPart[1]);
				}
			}				
			cacheCountOfSortFields = ctSortFields;

			
			arrContracts = arrNew;
			DisplayContractList("");
			return true;

		case 283:
			// Removing the field indicated by the response text;
			var arrNewFields = new Array();
			var lRemoveField = Zval(objXML.responseText);
			var iRemoveIndex = -1;
			for (var iX = 0; iX < ctFields; iX++) {
				if (arrFields[iX].FieldId != lRemoveField) {
					arrNewFields.push(arrFields[iX]);
				} else {
					iRemoveIndex = iX;
				}
			}

			// Need to modify the data for each contract in the contract block
			if (iRemoveIndex >= 0) {
				for (var iC = 0; iC < ctContracts; iC++) {
					for (iX = iRemoveIndex + 1; iX < ctFields; iX++) {
						arrContracts[iC].DataArray[iX - 1 + 5] = arrContracts[iC].DataArray[iX + 5];
					}
				}
			}
			
			arrFields = arrNewFields;
			ctFields = arrFields.length;
			DisplayContractList("");
			return true;
			
		case 286:
			// The response text contains the data for a new field to be added to the grid
			var arrBlocks = objXML.responseText.split("`");
			var szHeaderBlocks = 2;
			var ctNewContracts = arrBlocks.length - szHeaderBlocks;

			// Process the new field
			var strFieldDef = arrBlocks[1];
			var arrFieldDef = strFieldDef.split("~");

			var objNewFieldDef = new FieldDef(Zval(arrFieldDef[0]),arrFieldDef[1],arrFieldDef[2],arrFieldDef[3],arrFieldDef[4]);
			var lColumnWidth = renderDefaultFieldWidth;
			switch (objNewFieldDef.FieldType) {
				case 3:
				case 4:
					lColumnWidth = 100;
					break;
				case 5:
				case 6:
				case 1003:
				case 5000004:
					lColumnWidth = 200;
					//lRowHeight = 40;
					break;
				case 1:
					lColumnWidth = 150;
					break;
				default:
					lColumnWidth = 75;
					break;

			}
			objNewFieldDef.RenderWidth = lColumnWidth;

			// Add the new field into the array	
			ctFields++;
			arrFields.push(objNewFieldDef);

			var lInsertFieldAt = 4 + ctFields;

			// Need to add the data for each contract into the contract block
			for (var iC = 0; iC < ctNewContracts; iC++) {
				var strContractData = arrBlocks[iC + szHeaderBlocks];
				var arrContractFields = strContractData.split("~");
				var strContractId = arrContractFields[0];

				for (var iOld = 0; iOld < ctContracts; iOld++) {
					if (arrContracts[iOld].ContractId == strContractId) {
						if (lInsertFieldAt > arrContracts[iOld].DataArray.length) {
							arrContracts[iOld].DataArray.push(arrContractFields[1]);
						} else {
							arrContracts[iOld].DataArray[lInsertFieldAt] = arrContractFields[1];
						}
						iOld = ctContracts;
					}
				}
			}

			
			DisplayContractList("");
			return true;

		case 298:
		    // Just reload the page. Used after clearing all filters.
			Goto("FilterContracts.asp?searchid=" + strSearchId);
			return true;

		case 299:
			alert(objXML.responseText);
			// May need to reload...
			Goto("FilterContracts.asp?searchid=" + strSearchId);
			return true;
			
		default:
			return false;
	}
}

function LoadContractList(pageNo) {
    //JohnC Defect 1-1451
    //pageNo is an optional parameter to specify the page of results required
    var strPage = "";
    if(pageNo != undefined) {
        strPage = "&pageno=" + pageNo;
    }

	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl("_SearchContractList.asp?searchid=" + strSearchId + strPage), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, LoadContractList2);
	objXML.send(null);
}

function LoadContractList2(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				switch (objXML.status) {
					case 200:
						DisplayContractList(objXML.responseText);
						break;
					case 299:
						SetFailedCaption();
						alert("An error occurred while trying to load the list of contracts:\r\n\r\n" + objXML.responseText);
						break;							
					default:
						SetFailedCaption();
						alert("Unable to load the list of contracts");
						break;							
				}						
				objXML = null;
				
				// Do a load of the full field list after the contract list,
				// if this hasn't already been done
				if (!bDoneLoadAll) {
					Delay_LoadAllNonFeatureFields();
				}
		}
	}
}

// Used to delay loading of data fields after contract loading has finished.
// If there isn't a delay, then rendering can be affected
var tmrLoadAllNonFeatureFields;
function Delay_LoadAllNonFeatureFields() {
	tmrLoadAllNonFeatureFields = setInterval("LoadAllNonFeatureFields()", 2000);
}

function SetFeatureFilter(f, e) {
	// Get the field ID from the checkbox
	var strFieldId = f.name.substr(1, f.name.length-1);

	// The e (event) parameter is only supplied in relation to feature fields. The
	// rendering code below omits the parameter in relation to sector fields
	if (!e) {
		AddFeatureFilter(strFieldId, 1, f.checked);
	} else {	
		if (e.altKey) {
			// Expand header field
			f.checked = !f.checked;
			ShowHideSubFields(strFieldId);
		} else if (e.ctrlKey && e.shiftKey) {
			FilterClear(strFieldId);
		} else if (e.ctrlKey) {
			FilterNo(strFieldId);	
		} else if (e.shiftKey) {
			FilterDecline(strFieldId);	
		} else {
			AddFeatureFilter(strFieldId, 1, f.checked);
		}
	}
}

function AddFeatureFilter(FieldId, FieldValue, bAdd) {
	// Change the field display state
	
	var fRow = document.getElementById("frow" + FieldId);
	
	//---------------------------------------
	sectorDiv = document.getElementById("SectorFields");
	sectorTables = sectorDiv.getElementsByTagName("table");
	sectorCheckBoxes = sectorDiv.getElementsByTagName("input");	

	var len = sectorCheckBoxes.length;
	var len2 = sectorTables.length;
	
	var i=0;
	for( i=0 ; i<len ; i++) {
		if (sectorCheckBoxes[i].checked==true) {
			sectorTables[i+1].className = "SelectedField";
		}
		else {
			sectorTables[i+1].className = "GF";
		}
	}
	//-----------------------------------------

	if (fRow) {
		fRow.className = (bAdd ? "SelectedField" : "GF");

		// Clear the No and Decline indicators (only applicable to features, not sectors)
		if (document.getElementById("lbl" + FieldId)) {
			document.getElementById("lbl" + FieldId).style.textDecoration = "";
			document.getElementById("lbl" + FieldId).style.color = "";
		}	

		// Set the status
		var objField = document.getElementsByName("f" + FieldId)[0];
		if (objField) objField.checked = bAdd;
	
	}
	

	var objSubFields = document.getElementById("subfields" + FieldId);
	if (objSubFields) {
		if (bAdd) {
			objSubFields.style.display = "";
			objField.scrollIntoView();
		} else {
			// Note that the data layer is responsible for
			// removing these sub fields from the actual filter.
			// However, we need to change the colours, and hide the group. 
			// We also need to remove any disabling which is the result of
			// the fields being part of a group, one of which was previously
			// selected. However, we don't re-enable anything with
			// the permdisable attribute, because this indicates that it's
			// also disabled because e.g. it isn't offered by any contracts
			var arrElem = objSubFields.getElementsByTagName("INPUT");
			var ctElem = arrElem.length;
			for (var iElem = 0; iElem < ctElem; iElem++) {
				arrElem[iElem].checked = false;
				if (Zval(arrElem[iElem].getAttribute("permdisabled"))) {
					// Don't re-enable
				} else {
					arrElem[iElem].disabled = false;
				}

				// Get the name so that we can get the id, in order to
				// get the row to reset the colours...
				var strId = arrElem[iElem].name;
				strId = strId.substr(1, strId.length - 1);
				document.getElementById("frow" + strId).className = "GF";
			}
			objSubFields.style.display = "none";
		}
	} else {
	}

	// See if this field is part of a group
	//MarkD 03/2008 quick fix for defectID 1-1472
	//no longer need to have client data to disable checkboxes for sub-features
	//if (bHasClients) {
		var objAttr = objField.getAttribute("groupid");
		if (objAttr) {
			var lGroup = Zval(objAttr);
			if (lGroup) {
				// See if this field has a parent
				var lParent = Zval(objField.getAttribute("parentfield"));
				if (lParent) {
					// Either need to restrict the others if adding this field,
					// or release the restriction
					var arrElem = document.getElementById("subfields" + lParent).getElementsByTagName("INPUT");
					var ctElem = arrElem.length;
					for (var iElem = 0; iElem < ctElem; iElem++) {
						if (Zval(arrElem[iElem].getAttribute("groupid")) == lGroup && arrElem[iElem].name != "f" + FieldId) {
							if (bAdd) {
								arrElem[iElem].disabled = "yes";
								HandleMutualExclusivityTooltip(arrElem[iElem], true);
							} else {
								arrElem[iElem].disabled = "";
								HandleMutualExclusivityTooltip(arrElem[iElem], false);
							}
						}
					}
				} else {
					var arrElem = document.getElementById("FeatureFields").getElementsByTagName("INPUT");
					var ctElem = arrElem.length;
					for (var iElem = 0; iElem < ctElem; iElem++) {
						if (Zval(arrElem[iElem].getAttribute("groupid")) == lGroup && arrElem[iElem].name != "f" + FieldId) {
							if (bAdd) {
								arrElem[iElem].disabled = "yes";
								HandleMutualExclusivityTooltip(arrElem[iElem], true);
							} else {
								arrElem[iElem].disabled = "";
								HandleMutualExclusivityTooltip(arrElem[iElem], false);
							}
						}
					}
				}
			}
		}
	//}

	if (FieldId == 5000020) {
		if (bAdd) {
			if (!bDoneEthicalWarning) {
				alert("Please note: filtering on ethical funds also removes any sectors which do not contain ethical funds.\nIt also changes the basis of all past performance calculations so that only ethical funds are considered.");
				bDoneEthicalWarning = true;
			}
		}

		// Make sure that the relevant tabs are re-loaded
		bDoneLoadAll = false;
		bLoadedNonFeatureFieldData = false;
		arrTabsLoaded[2] = false;
		arrTabData[2] = "";
		arrTabsLoaded[5] = false;
		arrTabData[5] = "";
		Delay_LoadAllNonFeatureFields();
	}

	// Tell the user that we're reloading...
	SetLoadingCaption();

	// Do the XML communication
	var strUrl = "";
	var objXML = CreateXMLObject();
	if (bAdd) {
		strUrl = "_AddToSearchFilter.asp?searchid=" + strSearchId + "&fieldid=" + FieldId + "&operator=1&value=" + FieldValue;
		if (bGotMaxRecords) strUrl += "&max=1";
		strUrl += "&ptype=" + lProductTypeId;
		//JohnC Defect 1-1451 - add paging flag to url
		if(lProductTypeId == FUND_PRODUCT_TYPE) strUrl += "&paging=1";
		
	} else {
		strUrl = "_RemoveFromSearchFilter.asp?searchid=" + strSearchId + "&fieldid=" + FieldId;
	}
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
	objXML.send(null);
}

function HandleMutualExclusivityTooltip(arrElem, bAdd) {
	var strT = arrElem.title;
	var arrT = strT.split("\r\n");


	var iPresent = -1;
	for (var i = 0; i < arrT.length; i++) {
		if (arrT[i] == strMutualExclusivity) {
			iPresent = i;
			i = arrT.length;
		}
	}

	

	if (bAdd) {
		if (iPresent == -1) {
			strT = arrT.join("\r\n") + "\r\n" + strMutualExclusivity;
		}
		document.getElementById("lbl" + GetFieldIdFromFName(arrElem.name)).className = "GT";
	} else {
		if (iPresent != -1) {
			strT = "";
			for (i = 0; i < arrT.length; i++) {
				if (i != iPresent) {
					strT += (strT ? "\r\n" : "") + arrT[i];
				}
			}
		}
		document.getElementById("lbl" + GetFieldIdFromFName(arrElem.name)).className = "";
	}
	arrElem.title = strT;
}

function GetFieldIdFromFName(strName) {
	return Zval(strName.substr(1));
}

function SetConditionFilterOperator(f) {
	// Get the field ID from the checkbox - extract the "foper" from the beginning
	var strFieldId = f.name.substr(5, f.name.length-5);
	var objF = document.getElementsByName("f" + strFieldId)[0];
	SetConditionFilter(objF, true);
}

function ClearCriteria() {
	if (!confirm("Are you sure that you want to remove all the filtering from this list of contracts?")) return false;
	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl("_ClearSearchCriteria.asp?searchid=" + strSearchId), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
	objXML.send(null);
	
	// TODO - nasty cheat
	//Goto("FilterContracts.asp?searchid=" + strSearchId);
}

function SetConditionFilter(f, bChangeUnlessBlank) {
	// Get the field ID from the checkbox
	var strFieldId = f.name.substr(1, f.name.length-1);

	// The field may either be an INPUT or a SELECT
	var strVal = "";
	if (f.tagName.toLowerCase == "select") {
		strVal = GetComboValue(f);
	} else {
		strVal = f.value;
	} 

	if (!strVal && !f.lastvalue) {
	} else {
		if (strVal != f.lastvalue || (strVal && bChangeUnlessBlank)) {

			strVal = EncodeForUrl(strVal);

			// Change the field display state
			document.getElementById("frow" + strFieldId).className = (strVal ? "SelectedField" : "GF");

			// Tell the user that we're reloading...
			SetLoadingCaption();

			// Do the XML communication
			var strUrl = "";
			var objXML = CreateXMLObject();
			if (strVal) {
				var strOper = GetComboValue(document.getElementsByName("foper" + strFieldId)[0]);
				strUrl = "_AddToSearchFilter.asp?searchid=" + strSearchId + "&fieldid=" + strFieldId + "&operator=" + strOper + "&value=" + strVal;
				if (bGotMaxRecords) strUrl += "&max=1";
				strUrl += "&ptype=" + lProductTypeId;
			} else {
				strUrl = "_RemoveFromSearchFilter.asp?searchid=" + strSearchId + "&fieldid=" + strFieldId;
			}

			f.lastvalue = strVal;
			objXML.open("GET", RefreshableUrl(strUrl), true);
			objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
			objXML.send(null);
		}
	}
}

function OnFilterChange(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				if (HandleContractListResponse(objXML)) {
				
				} else {
					switch (objXML.status) {
						case 298:
							Goto("FilterContracts.asp?searchid=" + strSearchId);
							break;	
					
						case 299:
							SetFailedCaption();
							alert("An error occurred while trying to change the filter on the contract list:\r\n\r\n" + objXML.responseText);
							break;							

						default:
							SetFailedCaption();
							alert("Unable to load the revised list of contracts");
							break;							
					}						
				}
				objXML = null;
		}
	}
}

function SortField(FieldId, Order) {
	this.FieldId = Zval(FieldId);
	this.Order = Zval(Order);
}

function FieldDef(FieldId, FieldName, FieldType, HeaderType, ParentFieldName, DetailFieldId, HasDef) {
	this.FieldId = FieldId;
	this.FieldName = FieldName;
	this.FieldType = Zval(FieldType);
	this.HeaderType = HeaderType;
	this.ParentFieldName = ParentFieldName;
	this.DetailFieldId = DetailFieldId;
	this.HasDef = HasDef;
	this.RenderWidth = 0;
}
function ContractDef(ContractId, ContractName, CompanyName, CompanyId, BasisName, DataArray) {
	this.ContractId = ContractId;
	this.ContractName = ContractName;
	this.CompanyName = CompanyName;
	this.CompanyId = CompanyId;
	this.BasisName = BasisName;

	this.DataArray = DataArray;
}

function IsSortField(arrSortFields, ctSortFields, FieldId) {
	if (!ctSortFields && FieldId == 5000000) return true;
	// See if this is a sort field
	for (var iSort = 0; iSort < ctSortFields; iSort++) {
		if (arrSortFields[iSort].FieldId == FieldId) return true;
	}
	return false;
}


function SetLoadingCaption() {
	document.getElementById("ContractCountCaption").innerHTML = "Loading <img src='" + strPathImg + "/Progress.gif' width='96' height='10' border='0'/>";
}

function SetRenderingCaption() {
	document.getElementById("ContractCountCaption").innerHTML = "Got data. Displaying <img src='" + strPathImg + "/Progress.gif' width='96' height='10' border='0'/>";
}

function SetFailedCaption() {
	document.getElementById("ContractCountCaption").innerHTML = "Failed to re-load list";
}


var lCurrentTab = 1;
function SwitchTab(x) {
	document.getElementById("tabFeatures").className = (x == 1 ? "SelectedTab" : "UnselectedTab");
	document.getElementById("tabSectors").className = (x == 2 ? "SelectedTab" : "UnselectedTab");
	document.getElementById("tabConditions").className = (x == 3 ? "SelectedTab" : "UnselectedTab");
	document.getElementById("tabRanking").className = (x == 4 ? "SelectedTab" : "UnselectedTab");
	document.getElementById("tabPP").className = (x == 5 ? "SelectedTab" : "UnselectedTab");

	document.getElementById("tabNotes").className = ((x == 999999 || bHasNotes) ? "NoteTab" : "UnselectedTab");

	document.getElementById("FeatureFields").style.display = (x == 1 ? "" : "none");
	document.getElementById("SectorFields").style.display = (x == 2 ? "" : "none");
	document.getElementById("ConditionFields").style.display = (x == 3 ? "" : "none");
	document.getElementById("RankingFields").style.display = (x == 4 ? "" : "none");
	document.getElementById("PPFields").style.display = (x == 5 ? "" : "none");

	document.getElementById("NoteContainer").style.display = (x == 999999 ? "" : "none");

	document.getElementById("FieldListContainer").style.backgroundColor = (x == 999999 ? "#FFFFC0" : "");

	// Scroll to top of field container
	document.getElementById("FieldListContainer").scrollTop = 0;
	

	// Work around for bug in IE where it mis-sizes the field list because of 
	// forgetting to take into account the vertical scrollbar
	document.getElementById("FieldListContainer").scrollLeft = 0;
	
	lCurrentTab = x;

	LoadAllNonFeatureFields();
	
	// May need to load some fields, unless we're dealing with the notes tab
	if (x != 999999) {
		if (!arrTabsLoaded[x]) {
			DisplayTabFields(x);
		}
	} else {
		LoadNotes();
	}

	Page_BodyResize();
}
function UpdateSectorTypeForSearch(SectorType) {
	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl("_SetSectorTypeForSearch.asp?searchid=" + strSearchId + "&sectortypeid=" + SectorType), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, UpdateSectorTypeForSearch2);
	objXML.send(null);
}
function SwitchSectorTab(iTab) {
	UpdateSectorTypeForSearch(iTab);	
}
function UpdateSectorTypeForSearch2(objXML) {

	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				switch (objXML.status) {
					case 200:
						SwitchSectorTab2(objXML.responseText);
						break;
					case 299:
						SetFailedCaption();
						alert("An error occurred while trying to load the list of contracts:\r\n\r\n" + objXML.responseText);
						break;							
					default:
						SetFailedCaption();
						alert("Unable to load the list of contracts");
						break;							
				}						
				objXML = null;
		}
	}
}

function SwitchSectorTab2(iTab) {
	lSectorType = iTab;
	//if (lSectorsLoaded != lSectorType && lSectorsLoaded != 3 ) {
		//alert('Need To load other sector page');
	//}
	sectorDiv = document.getElementById('SectorFields');

	sectorCheckBoxes = sectorDiv.getElementsByTagName("input");	

	var len = sectorCheckBoxes.length;
	var i=0;
	var bSectorsChecked = false;
	
	for( i=0 ; i<len ; i++) {
		if (sectorCheckBoxes[i].id=='checkgroup') {
			if (sectorCheckBoxes[i].checked == 1) {
				bSectorsChecked = true;
				i=len;
			}
		}
	}	
	if (!bSectorsChecked) {
		var ppDivName = 'PPFields'
		ppDiv = document.getElementById(ppDivName);
		ppTextBoxes = ppDiv.getElementsByTagName("input");
		len = ppTextBoxes.length;
		for( i=0 ; i<len ; i++) {
			if (ppTextBoxes[i].value!="") {
				bSectorsChecked = true;
				i=len;
			}
		}	
	}
	if (bSectorsChecked) if (!confirm("Switching sector categories will clear all filtering on sectors and past performance \nand remove all sector or past performance fields from the grid. \nAre you sure you wish to continue?")) return;
	
	
	if (iTab == LIPPERSECTORSID) {
		RemoveSectorsAndPP('checkgroup','SectorFields');
	}
	if (iTab == IMASECTORSID ) {
		RemoveSectorsAndPP('checkgroup','SectorFields');
	}	
	if (iTab == FINEXSECTORSID ) {
		RemoveSectorsAndPP('checkgroup','SectorFields');
	}

	document.getElementById("tabIMASectors").className = (iTab == IMASECTORSID  ? "SelectedTab" : "UnselectedTab");
	//document.getElementById("tabLipperSectors").className = (iTab == 1 ? "SelectedTab" : "UnselectedTab");
	document.getElementById("tabFinExSectors").className = (iTab == FINEXSECTORSID  ? "SelectedTab" : "UnselectedTab");
	
	document.getElementById("tabIMAPP").className = (iTab == IMASECTORSID  ? "SelectedTab" : "UnselectedTab");
	//document.getElementById("tabLipperPP").className = (iTab == 1 ? "SelectedTab" : "UnselectedTab");
	document.getElementById("tabFinExPP").className = (iTab == FINEXSECTORSID  ? "SelectedTab" : "UnselectedTab");
	
	document.getElementById("IMASectorFields").style.display = (iTab == IMASECTORSID  ? "" : "none");	
	//document.getElementById("LipperSectorFields").style.display = (iTab == 1 ? "" : "none");
	document.getElementById("FinExSectorFields").style.display = (iTab == FINEXSECTORSID  ? "" : "none");
		
	document.getElementById("IMAPPFields").style.display = (iTab == IMASECTORSID  ? "" : "none");	
	//document.getElementById("LipperPPFields").style.display = (iTab == 1 ? "" : "none");
	document.getElementById("FinExPPFields").style.display = (iTab == FINEXSECTORSID  ? "" : "none");
	
	document.getElementById("SectorMessage2").style.display = "none";
	document.getElementById("PPMessage").style.display = "none";
	document.getElementById("SectorMessage").style.display = "";
	
	if (lCurrentTab == 2) {
	    DisplayTabFields(2);
	}
	if (lCurrentTab == 5) {
	    DisplayTabFields(5);
	}
}
// Caches the id of a field being added across asynchronous calls to the server
// Used in SetDataField2 to scroll across to the new field
var lAddFieldId = 0;

function SetDataField(FieldId, e, bNoKeyHandling) {
	if (!bNoKeyHandling) {
		if (e) {
			if (e.altKey) {
				ShowHideSubFields(FieldId);
				e.cancelBubble = true;
				return false;
			}
			if (e.ctrlKey) {
				e.cancelBubble = true;
			}
		}
	}
	
	var strUrl = "_SetSearchDataFieldList.asp?searchid=" + strSearchId + "&fieldid=" + FieldId;
	if (!bNoKeyHandling) {

		if (e) {
			if (!e.ctrlKey) strUrl += "&add=1";
		} else {
			strUrl += "&add=1";
		}
	}
	
	SetLoadingCaption();
	lAddFieldId = FieldId;
	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, SetDataField2);
	objXML.send(null);
}

function RemoveField(FieldId, e) {
	HideMenus();
	var strUrl = "_SetSearchDataFieldList.asp?searchid=" + strSearchId + "&fieldid=" + FieldId;
	strUrl += "&remove=1";

	SetLoadingCaption();

	lAddFieldId = 0;
	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, SetDataField2);
	objXML.send(null);
}
function SetDataField2(objXML) {
	try {
		if (objXML) {
			switch (objXML.readyState) {
				case 4:
					switch (objXML.status) {
						case 200:
							DisplayContractList(objXML.responseText);

							// Try scrolling to the newly added column
							if (lAddFieldId) {
								var objNewField = document.getElementById("header" + lAddFieldId);
								if (objNewField) {
									var objC = document.getElementById("BodyBlockContainer");
									var l = parseInt(objNewField.style.left);
									if (l > objC.scrollLeft + objC.offsetWidth) {
										objC.scrollLeft = l;
										ScrollBodyBlock();
									}
								}
							}	
							break;

						case 283:
							HandleContractListResponse(objXML);
							break;

						case 286:
							HandleContractListResponse(objXML);
							break;

						case 299:
							SetFailedCaption();
							alert("Unable to display the contents of this field:\r\n\r\n" + objXML.responseText);
							break;

						default:
							SetFailedCaption();
							alert("An error occurred while trying to display the contents of this field.");
							break;
					}
					objXML = null;
					break;
			}
		}
	}
	catch (e) {
		alert("Error: " + e);
	}
}

function SetSortField(FieldId, e, lOrder) {
	if (e) {
		var b = GetMouseButton(e);
		if (b == 2) return true;
	}
	
	// If there are currently no sort fields then pretend that we're currently
	// sorting on company name
	var bAddToSort = false;
	if (FieldId == 5000000 && !cacheCountOfSortFields) {
		FieldId = "5000000:desc";
	} else {
		if (e) {
			bAddToSort = e.ctrlKey;
			if (bAddToSort && !cacheCountOfSortFields) {
				FieldId = "5000000:desc," + FieldId;
			}
		}
	}

	if (lOrder) {
		if (lOrder == 2) {
			FieldId += ":desc";
		} else {
			FieldId += ":asc";
		}
	}

	var strUrl = "_SetSearchSortFieldList.asp?searchid=" + strSearchId + "&fieldid=" + FieldId;
	if (bAddToSort) strUrl += "&add=1";
	
	if (bGotMaxRecords) strUrl += "&max=1";
	//JohnC Defect 1-1451 - Add a parameter to the URL to show that we are paging results
	if(lProductTypeId == FUND_PRODUCT_TYPE) strUrl += "&paging=1";

	SetLoadingCaption();

	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, SetSortField2);
	objXML.send(null);
}
function SetSortField2(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				if (HandleContractListResponse(objXML)) {
								
				} else {
					switch (objXML.status) {
						case 299:
							SetFailedCaption();
							alert("Unable to change the sort order of the list:\r\n\r\n" + objXML.responseText);
							break;
						default:
							SetFailedCaption();
							alert("An error occurred while trying to change the sort order of the list.");
							break;

					}
				}
				objXML = null;
				break;
		}
	}
}

function CheckBrochureAvailability(e) {
	var lContracts = document.getElementById("ctContracts").value;
	if (lContracts == 0) {
		alert("You have filtered out all available contracts. There is no data to display.");
	} else if (lContracts > 50) {
		// Arbitrary limit of 50 due to time and processor cost. Might still be too high in practice.
		alert("The comparison report cannot be generated because there are more than 50 contracts to be included.\r\n\r\nThe resulting web page would be enormous, and almost impossible to read.\r\n\r\nPlease filter down the contracts to a smaller list, and then use this option again.");
	} else {
		if (lContracts > 10) {
			if (!confirm("There are more than 10 contracts to display. Creation/downloading of the report may take a long time, and the report will be difficult to read because of the number of columns.\r\n\r\nAre you sure that you want to continue with this number of records?")) {
				return KE(e);
			}
		}
		Goto("Brochure.asp?searchid=" + strSearchId + "&contracttypeid=" + strContractTypeId);
	}				
	KE(e);
}

function CheckRankingAvailability(e) {
    //alert(""+lSectorType+"");
	var lContracts = document.getElementById("ctContracts").value;
	if (lContracts == 0) {
		alert("You have filtered out all available contracts. There is nothing to rank.");
	} else if (lContracts == 1) {
		alert("There is only one available contract. There is nothing to rank.");
	} else {
		if (bSearchIsReadOnly) {
			if (!bHasRanking) {
				alert("This research does not contain any ranking criteria.");
				KE(e);
			} else {
				Goto("DisplayRanking.asp?searchid=" + strSearchId + "&contracttypeid=" + strContractTypeId);
			}
		} else {
			Goto("RankingSelection.asp?searchid=" + strSearchId + "&contracttypeid=" + strContractTypeId + "&Sectortype=" + lSectorType);
		}
	}
	KE(e);
}

function ExcludeContract(ContractId) {
	var strUrl = "pAskContractExclusion.asp?searchid=" + strSearchId + "&contractid=" + ContractId;
	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: 400px; DialogHeight: 300px");
		if (strRet) {
			var arrPart = strRet.split("|");
			if (arrPart.length == 2) {
				if (arrPart[0] == "reinclude") {
					ReincludeAll();							
				} else {
					DoExcludeContract(arrPart[0], arrPart[1]);
				}
			}
		}
	} else {
		var h = 250;
		var w = 400;
		l = (screen.availWidth - w) / 2;
		t = (screen.availHeight - h) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

// Very, very nasty. Parameters are passed via global variables and a timer from
// DoExcludeContract() to Delay_DoExcludeContract(). The reason is that
// for browsers other than IE, DoExcludeContract() is called from a different
// browser window. Browsers such as Firefox tend to throw their toys out of the
// pram if an XMLHTTP object is created "in the context" of the other browser window,
// which is then closed before the XMLHTTP call completes. Therefore, do the request
// in the context of this main page by diverting everything through the variables and timer.

//var objXMLExclude;
var passExcludeContractId;
var passExcludeContractReason;
var tmrExcludeDelay;

function DoExcludeContract(ContractId, strReason) {
	passExcludeContractId = ContractId;
	passExcludeContractReason = strReason;
	tmrExcludeDelay = setInterval("Delay_DoExcludeContract()", 1);
}
function Delay_DoExcludeContract() {
	clearInterval(tmrExcludeDelay);

	var ContractId = passExcludeContractId;

	var strReason = passExcludeContractReason;
	
	var strPost = "searchid=" + strSearchId + "&contractid=" + ContractId + "&reason=" + EncodeForUrl(strReason);
	var objXMLExclude = CreateXMLObject();
	var bAsync = true;
	objXMLExclude.open("GET", "_ExcludeContract.asp?" + strPost, bAsync);
	objXMLExclude.onreadystatechange = newReadyStateHandler(objXMLExclude, DoExcludeContract2);
	objXMLExclude.send(null);
	if (!bAsync) DoExcludeContract2();
}

function ReincludeAll() {
	var strPost = "searchid=" + strSearchId + "&contractid=reinclude";
	var objXMLExclude = CreateXMLObject();
	objXMLExclude.open("GET", "_ExcludeContract.asp?" + strPost, true);
	objXMLExclude.onreadystatechange = newReadyStateHandler(objXMLExclude, DoExcludeContract2);
	objXMLExclude.send(null);			
}

function DoExcludeContract2(objXMLExclude) {
	if (objXMLExclude) {
		switch (objXMLExclude.readyState) {
			case 4:
				switch (objXMLExclude.status) {
					case 200:
						DisplayContractList(objXMLExclude.responseText);
						break;
					case 281:
						HandleContractListResponse(objXMLExclude);
						break;
					case 299:
						SetFailedCaption();
						alert("Unable to change the contracts excluded from this list:\r\n\r\n" + objXML.responseText);
						break;
					default:
						SetFailedCaption();
						alert("An error occurred while trying to change the list of excluded contracts.");
						break;
				}
				objXMLExclude = null;
				break;
		}
	}
}

var objFieldXML;
var bInLoadAll = false;
var bLoadedNonFeatureFieldData = false;
var bDoneLoadAll = false;
var arrTabsLoaded = new Array(10);
var arrTabData = new Array(10);

function LoadAllNonFeatureFields() {
	clearInterval(tmrLoadAllNonFeatureFields);
	

	if (bDoneLoadAll) return;
	bDoneLoadAll = true;
	

	bInLoadAll = true;
	lFieldsForPage = 99;
	var objFieldXML = CreateXMLObject();
	objFieldXML.open("GET", RefreshableUrl("_ContractFieldData.asp?page=99&searchid=" + strSearchId + "&contracttypeid=" + strContractTypeId), true);
	objFieldXML.onreadystatechange = newReadyStateHandler(objFieldXML, LoadNonFeatureFields2);
	objFieldXML.send(null);
}

function DisplayTabFields(lPage) {
	// Potential for this to be called before the loading of tab data
	// has finished. In this case, we set up a timer
	if (!arrTabData[lPage]) {
		if (bLoadedNonFeatureFieldData) {
			strHtml = "(none)";	
		} else {
			strHtml = "Loading...";	
		}
		arrTabsLoaded[lPage] = 1;
	} else {
		arrTabsLoaded[lPage] = 1;
		strHtml = RenderFieldListAsHtml(arrTabData[lPage]);
	}
	
	switch (lPage) {
		case 2:
			var arrSectorHtml = strHtml.split("{-}");
			document.getElementById("SectorMessage").innerHTML = arrSectorHtml[0];
			//MarkD 05/2008 needs to check the length to get rid of NaN, bless her!
			if (arrSectorHtml.length > 1) {
			    if (lSectorType == LIPPERSECTORSID ) {
			        //alert(""+lSectorsLoaded+"");
				    document.getElementById("LipperSectorFields").innerHTML = arrSectorHtml[1] + arrSectorHtml[3];
				    lSectorsLoaded += lSectorType;
			    } else if (lSectorType == IMASECTORSID ) {
			        //alert(""+lSectorType+"");
				    document.getElementById("IMASectorFields").innerHTML = arrSectorHtml[2] + arrSectorHtml[3];
				    lSectorsLoaded += lSectorType;
			    } else if (lSectorType == FINEXSECTORSID ) {
			        //alert(""+lSectorType+"");
				    document.getElementById("FinExSectorFields").innerHTML = arrSectorHtml[1] + arrSectorHtml[3];
				    lSectorsLoaded += lSectorType;
			    }		    
			}
			break;
		case 3:
			document.getElementById("ConditionFields").innerHTML = strHtml;
			break;
		case 4:
			document.getElementById("RankingFields").innerHTML = strHtml;
			break;
		case 5:
			var arrPPHtml = strHtml.split("{-}");
			if (lSectorType == LIPPERSECTORSID ) {
			    document.getElementById("LipperPPFields").innerHTML = arrPPHtml[0];			
			} else if (lSectorType == IMASECTORSID ) {
			    document.getElementById("IMAPPFields").innerHTML = arrPPHtml[1];
			} else if (lSectorType == FINEXSECTORSID ) {
			    document.getElementById("FinExPPFields").innerHTML = arrPPHtml[0];
			}
			break;
	}
	Page_BodyResize();
}

function LoadNonFeatureFields2(objFieldXML) {
	if (objFieldXML) {
		switch (objFieldXML.readyState) {
			case 4:
				switch (objFieldXML.status) {
					case 200:
						var strData = objFieldXML.responseText;

						// Store the tab data for later rendering
						var arrFieldBlocks = strData.split("{}");
						for (var iTab =2;iTab < 6; iTab++) {
							arrTabData[iTab] = arrFieldBlocks[iTab - 2];
						}
						
						// If we're not the feature tab, then render
						// the current tab now.
						if (lCurrentTab != 1) {
							DisplayTabFields(lCurrentTab);
						}
						bLoadedNonFeatureFieldData = true;
						break;
					default:
						alert("Unable to load the full list of fields for this type of contract.");
						break;
				}
			
				objFieldXML = null;
		}
	}
}


function ToggleAllSectors(buttonid) {
	if (lSectorType==1) {
		SetChecked('checkgroup',buttonid,'LipperSectorFields')
	} else if (lSectorType==2) {
		SetChecked('checkgroup',buttonid,'IMASectorFields')	
	} else if (lSectorType==3) {
		SetChecked('checkgroup',buttonid,'FinExSectorFields')	
	} else {
		//Don't need to do anything as no sectors shown
	}

}

//MarkD 05/10/07 adding functions to handle checking all sectors in one go
//function checks/clears all checkboxes in the collection. changes the text of the button accordingly
//also changes the class of all rows to highlight background
//and hopefully updates the fund list to reflect the revised collection of available funds
//enables/disables the submit button(s) if they are to exist at a later date
//MattM 29/11/2007 changed function to handle divs as injecting a form into a page in IE7 (used by notes) causes an error
function SetChecked(chkName,buttonID,parentElementName) {
	
	var mycount = 0
	var fieldidlist = new Array();
	var button=document.getElementById(buttonID).value;
	
	sectorDiv = document.getElementById(parentElementName);

	sectorCheckBoxes = sectorDiv.getElementsByTagName("input");	
	sectorTables = sectorDiv.getElementsByTagName("table");	
	
	var len = sectorCheckBoxes.length;
	var len2 = sectorTables.length;
	
	var i=0;
		if (button=="Check all sectors") {
			for( i=0 ; i<len ; i++) {
				if (sectorCheckBoxes[i].id==chkName) {
					sectorCheckBoxes[i].checked=1;
					var namevalue = sectorCheckBoxes[i].name.replace(/f/, "");
					
					fieldidlist[mycount] = namevalue ;
					mycount = mycount + 1 ;	
					var j= 0;

					//document.getElementById("frow" + namevalue).className = "SelectedField";
				}
			}
			for( j=0 ; j<len2 ; j++) {
					sectorTables[j].className = "SelectedField";
			}		
			button.value = "Clear all sectors";
			var fids = fieldidlist.toString();
			SetLoadingCaption();
			// Do some XML communication type stuff hopefully
			var FieldValue = "1"
			var strUrl = "";
			var objXML = CreateXMLObject();

			strUrl = "_AddToSearchFilter.asp?aAllSectors=Add&searchid=" + strSearchId + "&fids=" + fids + "&operator=1&value=" + FieldValue;
				if (bGotMaxRecords) strUrl += "&max=1";
				strUrl += "&ptype=" + lProductTypeId;
				 
			objXML.open("GET", RefreshableUrl(strUrl), true);
			objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
			objXML.send(null);
			ShowCounter();
			return "Clear all";
		}
		else {
		for( i=0 ; i<len ; i++) {
			if (sectorCheckBoxes[i].id==chkName) {
				sectorCheckBoxes[i].checked=0;
				var namevalue = sectorCheckBoxes[i].name.replace(/f/, "");			
				
					mycount = mycount + 1 ;	
			}
		}
					var j= 0;
					for( j=0 ; j<len2 ; j++) {					
							sectorTables[j].className = "GF";
					}
			button.value ="Check all sectors";
			SetLoadingCaption();
			// Do some XML communication type stuff hopefully
			var strUrl = "";
			var objXML = CreateXMLObject();

			strUrl = "_RemoveFromSearchFilter.asp?aAllSectors=remove&searchid=" + strSearchId;

			objXML.open("GET", RefreshableUrl(strUrl), true);
			objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
			objXML.send(null);
			ShowCounter();
			return "Check all";
			}
}


function RemoveSectorsAndPP(checkgroupname,SectorDivName) {
	var mycount = 0
	var fieldidlist = new Array();
	//var button=document.getElementById(buttonID).value;
	
	sectorDiv = document.getElementById(SectorDivName);
	sectorTables = sectorDiv.getElementsByTagName("table");
	var len2 = sectorTables.length;

	sectorCheckBoxes = sectorDiv.getElementsByTagName("input");	

	var len = sectorCheckBoxes.length;
	var len2 = sectorTables.length;
	
	var i=0;
	for( i=0 ; i<len ; i++) {
		if (sectorCheckBoxes[i].id==checkgroupname) {
			sectorCheckBoxes[i].checked=0;
			var namevalue = sectorCheckBoxes[i].name.replace(/f/, "");

		}
	}
	var j= 0;
	for( j=0 ; j<len2 ; j++) {
		sectorTables[j].className = "GF";
	}
	var ppDivName = 'PPFields'
	ppDiv = document.getElementById(ppDivName);
	ppFieldNameBoxes = ppDiv.getElementsByTagName("td");	
		
	len = ppFieldNameBoxes.length;
	for( i=0 ; i<len ; i++) {
		if (ppFieldNameBoxes[i].className=="SelectedField") {
			ppFieldNameBoxes[i].className="GF";
			//var namevalue = sectorCheckBoxes[i].name.replace(/frow/, "");
			//document.getElementById("f" + namevalue).className = "GF";
		}
	}
	ppTextBoxes = ppDiv.getElementsByTagName("input");
	len = ppTextBoxes.length;
	for( i=0 ; i<len ; i++) {
		if (ppTextBoxes[i].value!="") {
			ppTextBoxes[i].value="";
			//var namevalue = sectorCheckBoxes[i].name.replace(/frow/, "");
			//document.getElementById("f" + namevalue).className = "GF";
		}
	}	
	
	
	//button.value ="Check all sectors";
	SetLoadingCaption();
	// Do some XML communication type stuff hopefully
	var strUrl = "";
	var objXML = CreateXMLObject();

	strUrl = "_RemoveFromSearchFilter.asp?aAllSectors=remove&aAllPP=remove&searchid=" + strSearchId;

	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
	objXML.send(null);
	ShowCounter();
	return "Check all";
			
}

//MarkD - called onmouseout of each checkbox to update the select all button text accordingly
function ButtonState(){
//var formname = "sSetall"
var chkName = "checkgroup"
var buttonid = "btnCheckAll"

sectorDiv = document.getElementById("SectorFields");
sectorCheckBoxes = sectorDiv.getElementsByTagName("input");
sectorTables = sectorDiv.getElementsByTagName("table");

var len = sectorCheckBoxes.length;
var len2 = sectorTables.length;
var sCount = 0
	for (i=0; i<len; i++) {
		if ((sectorCheckBoxes[i].checked==true)&&(sectorCheckBoxes[i].id==chkName)) {
			sCount=(sCount+1);
			i=len;
		} 
	}
	if (sCount != 0){
		document.getElementById(buttonid).value="Clear all sectors";
		return "Clear all sectors";
		}
		
	else {
		document.getElementById(buttonid).value="Check all sectors";
		return "Check all sectors";
	}
}

//MarkD 10/2007 - function to display/hide the select all sectors button
function Showhide(action) {
	if (lProductTypeId == FUND_PRODUCT_TYPE) {
		document.getElementById("CheckAllButtonContainer").className = action;
		Page_BodyResize();
		ShowCounter();
		ButtonState();
	}
}

//MarkD 10/2007 - function to output total fund/contract count next to check all button
//also makes sure we display the correct text on the button
//to cater for a page refresh which may not catch the ButtonState function
function ShowCounter() {
	var sContracts = Zval(document.getElementById("ctContracts").value);
	var sTotalContracts = document.getElementById("TotalContracts").value;
	var sExcluded = Zval(document.getElementById("ctExcluded").value);
	var sOutput = sTotalContracts - sContracts;
	document.getElementById("ShowCounter").innerHTML = " " + lngTotalResults + " of " + sTotalContracts + " Funds";
	ButtonState();
}

//MarkD 10/2007 - Function to address defectid 1-1375 where it errors if you click the selectall button before the list id loaded.
function EndIsSelectAll() {
	document.getElementById("btnCheckAll").disabled = false;
}



function RenderFieldListAsHtml(strData) {
	if (!strData) return;
	var arrFields = strData.split("|");
	var ctFields = arrFields.length;
	if (!ctFields) return;

	// Get the block type from the first field
	var lBlockType = Zval(arrFields[0].split("`")[4]);

	// Start the HTML

	var objH = new Array();

	// Structure of table is different between sectors and everything else
	if (lBlockType == 2 || lBlockType == 12) {
		// Headers...
		if (lProductTypeId == FUND_PRODUCT_TYPE) {
			if (lBasisId <= 5) {
				objH.push("<div class='GT GB PB5'>Choose the sectors you want to research. Funds will be included if they are in <b>any</b> of the sectors you specify. No funds are included until you pick at least one sector.</div>");
			} else {
				objH.push("<div class='GT GB PB5'>Funds will be included if they are in <b>any</b> of the sectors you specify. If you don't choose any sectors, all funds will be included.</div>");
			}
		} else {
		
		}

		

		// The last item in the sectors list is a special entry for required funds.
		// Therefore decrement the count of fields so that this
		// doesn't get displayed in the main block of sector fields
		//MarkD 10/2007 added clearpixel gif so i could call the ButtonState function
		//after the list had loaded, also calling the function to enable the button
		//it is disabled by default to stop people (NIGEL!!) clicking it before the full list of sectors has loaded
		objH.push("<img src='images/x.gif' onload='ButtonState(),EndIsSelectAll();' style='position:absolute; left:-2px; top:-2px'>");
		
		objH.push("{-}");
		ctFields--;
		
	} else {
		// Need table
		var lWidth = 100;
		// Caters for rendering error in Internet Explorer where it forgets to take into
		// account the scroll bar when there are more conditions than fit in the list
		// without scrolling
		if (whichBrs() == "Internet Explorer") lWidth = 100;
		objH.push("<table border='0' cellpadding='2' cellspacing='0' width='" + lWidth + "%'>");
	}

	var lLastGroup = 0;	
	var bPPShowGroup = false;	
	var lLastBlockType = 0;
	
	for (var iField = 0; iField < ctFields; iField++) {
		var arrInfo = arrFields[iField].split("`");
		var lFieldType = Zval(arrInfo[2]);
		var lPreset = Zval(arrInfo[7]);
		var lFieldId = Zval(arrInfo[0]);
		var lHasDef = Zval(arrInfo[9]);
		var lQuoteField = Zval(arrInfo[11]);
		
		//if (lQuoteField == 1) alert("QuoteField");
		
		var strTitle = "";
		if (lPreset == 2) strTitle = "Fixed preset";

		var bDisabled = false;
		
		// Disable all quote related fields
		if (lQuoteField == 1 && bLockQuoteFields) bDisabled = true;
		
		if (lPreset == 2 || bSearchIsReadOnly) bDisabled = true;
		//if (lLastBlockType != 12 && Zval(arrInfo[4]) == 12) {
		//	objH.push("{-}");
		//}
		lLastBlockType = lBlockType;
		lBlockType = Zval(arrInfo[4]);
		if (lLastBlockType == 5) {
			if (lBlockType == 15) {
				objH.push("</table>");
				objH.push("{-}");
				objH.push("<table>");
			}
		}
		var anid = ""
		var anotherid = ""
		
		
		
		// Lipper Sector fields		
		if (lBlockType == 2) {
			var strRowClass = "GF";
			var bCheckboxSelected = false;
			var strLblStyle = "";
			anid = "frow"
			anotherid = "checkgroup"
			
			if (arrInfo[6]) {
				if (arrInfo[5] == 1000) {
					// Declined
					strRowClass = "SelectedDeclineFiltering";
					strLblStyle = "text-decoration: line-through;";
				} else {
					strRowClass = "SelectedField";
					bCheckboxSelected = true;
				}
			}
			
			//markd - Lipper sectors output
			//objH.push("<div onmousedown='FilterOptionMenu(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' oncontextmenu='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' id='frow" + arrInfo[0] + "' style='font-size: 8pt;' class='" + strRowClass + "'>");
			//objH.push("<tr><td colspan='3'>");
			objH.push("<table width='100%' cellpadding='2' cellspacing='0' border='0' onmousedown='FilterOptionMenu(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' oncontextmenu='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' id='" + anid + "" + arrInfo[0] + "' style='font-size: 8pt;' class='" + strRowClass + "'");
			objH.push("<tr>");			
			objH.push("<td valign='top' width='15' align='left'><input title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " name='f" + arrInfo[0] + "' type='checkbox' id='" + anotherid + "' onclick='SetFeatureFilter(this);'" + (bCheckboxSelected ? "checked='yes'" : "") + "/></td> ");
			objH.push("<td><span id='lbl" + arrInfo[0] + "' class='FieldName' style='"+ strLblStyle  + "'>");
			if (lQuoteField == 1) objH.push(strQuoteMarker);
			objH.push("<a href='#' title='" + arrInfo[1] + "\r\n" + strRightClickTooltip + "' onmousedown='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' oncontextmenu='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' onclick='SetDataField(" + arrInfo[0] + ", event);return KE(event);'>");
			objH.push(arrInfo[1]);
			objH.push("</a>");
			objH.push("</span>");
			objH.push("</td></tr></table>");
			//objH.push("</td></tr>");
			//objH.push("</div>");
			
		// IMA Sector fields		
		} else if (lBlockType == 12) {
			var strRowClass = "GF";
			var bCheckboxSelected = false;
			var strLblStyle = "";
			anotherid = "checkgroup"
			if  (lLastBlockType != 12 || iField == 0)  {
				objH.push("{-}");
			}
			if (arrInfo[6]) {
				if (arrInfo[5] == 1000) {
					// Declined
					strRowClass = "SelectedDeclineFiltering";
					strLblStyle = "text-decoration: line-through;";
				} else {
					strRowClass = "SelectedField";
					bCheckboxSelected = true;
				}
			}
			
			
			
			//markd - IMA sectors output
			//objH.push("<div onmousedown='FilterOptionMenu(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' oncontextmenu='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' id='frow" + arrInfo[0] + "' style='font-size: 8pt;' class='" + strRowClass + "'>");
			//objH.push("<tr><td colspan='3'>");
			objH.push("<table name='rowf" + arrInfo[0] + "' width='100%' cellpadding='2' cellspacing='0' border='0' onmousedown='FilterOptionMenu(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' oncontextmenu='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' id='frow" + arrInfo[0] + "' style='font-size: 8pt;' class='" + strRowClass + "'");
			objH.push("<tr>");			
			objH.push("<td valign='top' width='15' align='left'><input title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " name='f" + arrInfo[0] + "' type='checkbox' id='" + anotherid + "' onclick='SetFeatureFilter(this);'" + (bCheckboxSelected ? "checked='yes'" : "") + "/></td> ");
			objH.push("<td><span id='lbl" + arrInfo[0] + "' class='FieldName' style='"+ strLblStyle  + "'>");
			if (lQuoteField == 1) objH.push(strQuoteMarker);
			objH.push("<a href='#' title='" + arrInfo[1] + "\r\n" + strRightClickTooltip + "' onmousedown='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' oncontextmenu='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' onclick='SetDataField(" + arrInfo[0] + ", event);return KE(event);'>");
			objH.push(arrInfo[1]);
			objH.push("</a>");
			objH.push("</span>");
			objH.push("</td></tr></table>");
			//objH.push("</td></tr>");
			//objH.push("</div>");
			

		// Watch for selectable headers
		} else if (lFieldType == 1000) {
			objH.push("<tr>");
			if (lFieldId > 6000000) {
				objH.push("<td colspan='3' style='padding: 3px 2px 3px 0px; border-bottom: solid 1px #F0F0F0'>");
				if (lQuoteField == 1) objH.push(strQuoteMarker);
				objH.push("<a href='#' title='Show/hide the past performance fields for this sector' onclick='ShowHidePPBlock(" + lFieldId + ");return KE(event);'>");
				objH.push(arrInfo[1]);
				objH.push("</a>");
				objH.push("</td>");
				
				// We show the group by default if any of its items are filtered on
				bPPShowGroup = false;
				
				for (var iPP = iField + 1; iPP < ctFields; iPP++) {
					var arrPP = arrFields[iPP].split("`");
					if (Math.floor(arrPP[0] / 100) == Math.floor(lFieldId / 100)) {
						if (arrPP[6]) {
							bPPShowGroup = true;
							iPP = ctFields;
						}
					} else {
						iPP = ctFields;
					}
				}
				
				
			} else {
				objH.push("<td colspan='3' class='GF' style='padding: 4px 2px 4px 0px'><b>" + arrInfo[1] + "</b></td>");
			}

			objH.push("</tr>");
			lLastGroup = lFieldId;
			
		// All other types of ranking field			
		} else {
			if (lFieldId > 6000000 && lFieldId < 1000000000) {
				var strNameAttribute = "";
				if (whichBrs() == "Internet Explorer") {
					strNameAttribute = " id='pp" + lLastGroup + "' ";
				} else {
					strNameAttribute = " name='pp" + lLastGroup + "' ";
				}
				objH.push("<tr " + strNameAttribute + (bPPShowGroup ? "" : "style='display: none'") + ">");
				objH.push("<td style='padding-left: 5px' id='frow" + arrInfo[0] + "' " + ((arrInfo[6]) ? " class='SelectedField'" : " class='GF'") +  ">");
			} else {
				objH.push("<tr>");
				objH.push("<td id='frow" + arrInfo[0] + "' " + ((arrInfo[6]) ? " class='SelectedField'" : " class='GF'") +  ">");
			}
			//MarkD 04/2008
				//figure out which sectors we're using
				//var Schosensectortype = "";
				//if (arrInfo[1] == "Linked sectors" && lSectorType == 1) {
				//    Schosensectortype = "Linked Lipper Sectors";
				//}   else if (arrInfo[1] == "Linked sectors" && lSectorType == 2){
				//    Schosensectortype = "Linked IMA/ABI/AIC Sectors";
				//}
				
			    objH.push("<span class='FieldName'>");
			    if (lQuoteField == 1) objH.push(strQuoteMarker);
			    if (arrInfo[1] == "Linked sectors" && lSectorType == 0){
				    var bDisabled = true;
				    var sectorstatus = "No sector category selected.\\nPlease return to filtering and make a sector category selection before adding linked sectors to the grid."
				    objH.push("<a href='#' onclick='alert(\"" + sectorstatus + "\");'>");				
				} else {
				    objH.push("<a title='" + arrInfo[1] + "\r\n" + strRightClickTooltip +"' href='#' onmousedown='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' oncontextmenu='return CM(" + arrInfo[0] + ", this, event, false, " + lHasDef + ")' onclick='SetDataField(" + arrInfo[0] + ", event);return KE(event);'>");
				}
				//if (Schosensectortype != "") {
				//objH.push(Schosensectortype);
				//} else {
				objH.push(arrInfo[1]);
				//}
				objH.push("</a>");

				objH.push(FieldNoteHtml(arrInfo[2]));
				

			objH.push("</span>");
			objH.push("</td>");

				// Don't display the filtering fields for certain product types
				//if (lFieldType != 1 && lFieldType != 6 && lFieldType != 5 && lFieldType != 5000004 && lFieldType != 1003) {
				if (lFieldType != 1 && lFieldType != 5 && lFieldType != 5000004 && lFieldType != 1003) {
					objH.push("<td class='GMF'>");
						objH.push("<select title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " name='foper" + arrInfo[0] + "' style='font-size: 8pt' onchange='SetConditionFilterOperator(this)'>");
							objH.push("<option value='ge' " + ((Zval(arrInfo[5]) == 5) ? "selected='yes'" : "") + ">&gt;=</option>");
							objH.push("<option value='le' " + ((Zval(arrInfo[5]) == 6) ? "selected='yes'" : "") + ">&lt;=</option>");
							objH.push("<option value='eq' " + ((Zval(arrInfo[5]) == 1) ? "selected='yes'" : "") + ">=</option>");
						objH.push("</select>");
					objH.push("</td>");

					objH.push("<td class='GMF'>");
						switch (Zval(arrInfo[2])) {
//							case 101:	// AKG
//								objH.push("<select title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " name='f" + arrInfo[0] + "' lastvalue='" + arrInfo[6] + "' style='font-size: 8pt' onchange='SetConditionFilter(this)'>");

//									objH.push("<option/>");

//									var strRanks = "5,4,3,2,1";
//									var arrRanks = strRanks.split(",");
//									var ctRanks = arrRanks.length;
//									for (var iRank = 0; iRank < ctRanks; iRank++) {
//										objH.push("<option value='" + arrRanks[iRank] + "' " + ((arrRanks[iRank] == arrInfo[6]) ? "selected='yes'" : "") + ">" + arrRanks[iRank] + "</option>");
//									}

//								objH.push("</select>");
//								break;
							
//							case 102:	// Moody's
//								objH.push("<select title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " name='f" + arrInfo[0] + "' lastvalue='" + arrInfo[6] + "' style='font-size: 8pt' onchange='SetConditionFilter(this)'>");

//									objH.push("<option/>");

//									var strRanks = "Aaa,Aa1,Aa2,Aa3,A1,A2,A3,Baa1,Baa2,Baa3,Ba1,Ba2,Ba3,B1,B2,B3,Caa1,Caa2,Caa3,Ca,C";
//									var arrRanks = strRanks.split(",");
//									var ctRanks = arrRanks.length;
//									for (var iRank = 0; iRank < ctRanks; iRank++) {
//										objH.push("<option value='" + arrRanks[iRank] + "' " + ((arrRanks[iRank] == arrInfo[6]) ? "selected='yes'" : "") + ">" + arrRanks[iRank] + "</option>");
//									}

//								objH.push("</select>");
//								break;

//							case 103:	// S&P
//								objH.push("<select title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " name='f" + arrInfo[0] + "' lastvalue='" + arrInfo[6] + "' style='font-size: 8pt' onchange='SetConditionFilter(this)'>");

//									objH.push("<option/>");

//									var strRanks = "AAA,AA+,AA,AA-,A+,A,A-,BBB+,BBB,BBB-,BB+,BB,BB-,B+,B,B-,CCC+,CCC,CCC-,CC";
//									var arrRanks = strRanks.split(",");
//									var ctRanks = arrRanks.length;
//									for (var iRank = 0; iRank < ctRanks; iRank++) {
//										objH.push("<option value='" + arrRanks[iRank] + "' " + ((arrRanks[iRank] == arrInfo[6]) ? "selected='yes'" : "") + ">" + arrRanks[iRank] + "</option>");
//									}

//								objH.push("</select>");
//								break;
                            //MattM - 1761 - Now getting data from database as it should always have been. Can now deal with all FS fields the same 
                            case 101:   // AKG
						    case 102:   // Moody
						    case 103:   // S&P
							case 104:	// AKG Friendly Society
								objH.push("<select title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " name='f" + arrInfo[0] + "' lastvalue='" + arrInfo[6] + "' style='font-size: 8pt' onchange='SetConditionFilter(this)'>");

									objH.push("<option/>");

									var strRanks = "";
									strRanks = arrInfo[10];
									var arrRanks = strRanks.split(",");
									var ctRanks = arrRanks.length;
									for (var iRank = 0; iRank < ctRanks; iRank++) {
										objH.push("<option value='" + arrRanks[iRank] + "' " + ((arrRanks[iRank] == arrInfo[6]) ? "selected='yes'" : "") + ">" + arrRanks[iRank] + "</option>");
									}

								objH.push("</select>");
								break;

							case 1004:	// Product rating
								objH.push("<select title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " fieldtype='1004' name='f" + arrInfo[0] + "' lastvalue='" + arrInfo[6] + "' style='font-size: 8pt' onchange='SetConditionFilter(this)'>");
								objH.push("<option value=''/>");
								objH.push("<option value='2' " + ((2 <= arrInfo[6]) ? "selected='yes'" : "") + ">V.Good</option>");
								objH.push("<option value='1' " + ((1 == arrInfo[6]) ? "selected='yes'" : "") + ">Good</option>");
								objH.push("<option value='0' " + ((0 == arrInfo[6] && arrInfo[6]!='') ? "selected='yes'" : "") + ">Neutral</option>");
								objH.push("<option value='-1' " + ((-1 == arrInfo[6]) ? "selected='yes'" : "") + ">Bad</option>");
								objH.push("<option value='-2' " + ((-2 >= arrInfo[6]) ? "selected='yes'" : "") + ">Awful</option>");
								objH.push("</select>");
								break;
								
							default:
								objH.push("<input title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + " name='f" + arrInfo[0] + "' lastvalue='" + arrInfo[6] + "' value='" + arrInfo[6] + "' onkeydown='return NumericKeyOnly(event)' style='font-size: 8pt' type='text' size='4' onblur='SetConditionFilter(this)'/>");
								break;
						}
					objH.push("</td>");
				} else {
					objH.push("<td style='height: 20px' class='GF'>&nbsp;</td><td class='GF'>&nbsp;</td>");
				}

			objH.push("</tr>");
		}
	}
	
	// End of overall structure
	if (lBlockType == 2 || lBlockType == 12) {
		objH.push("{-}");
		if (lProductTypeId != FUND_PRODUCT_TYPE) {
			// Sectors. Put in the fund-link stuff
			
			// Get the contents of the field
			var arrInfo = arrFields[ctFields].split("`");

			objH.push("<div id='RequiredFundBlock' style='margin-top: 10px; padding: 10px 5px 5px 5px; border-top: solid 1px #808080'>");
			objH.push(RenderRequiredFundBlock(arrInfo[6], arrInfo[4], Zval(arrInfo[5]), Zval(arrInfo[7])));
			objH.push("</div>");
		}
	} else {
		// Need table
		objH.push("</table>");
	}
	return objH.join('');
}


function FieldNoteHtml(FieldType) {
	switch (Zval(FieldType)) {
		case 101:
			return " <a href='#' onclick='RatingsInfo(1)'><img title='Show information about AKG ratings' src='images/vsInfo.gif' class='vs'/></a>";
		case 102:
			return " <a href='#' onclick='RatingsInfo(2)'><img title='Show information about Moody`s ratings' src='images/vsInfo.gif' class='vs'/></a>";
		case 103:
			return " <a href='#' onclick='RatingsInfo(3)'><img title='Show information about S&P ratings' src='images/vsInfo.gif' class='vs'/></a>";
		case 1001:
		case 1002:
		case 1003:
		case 1004:
			return " <img title='This field is private to your firm. It is not maintained by Synaptic Systems.' src='images/vsPrivate.gif' class='vs'/>";
	}
}

function ShowHidePPBlock(GroupId, bForceDisplay) {
	var arrE = document.getElementsByName("pp" + GroupId);
	var ctE = arrE.length;
	for (var i = 0; i < ctE; i++) {
		arrE[i].style.display = ((arrE[i].style.display == "none" || bForceDisplay)? "" : "none");
	}
}


function NumericKeyOnly(e) {
	var k = e.which;
	if (!k) k = e.keyCode;
	if (k >= 65 && k <= 90) {
		e.returnValue = false;
		return false;
	}
}





// Passes the field id between the pop-up filter menu and the resulting event
var passFilterOnFieldId;
// Passes the field value between the pop-up filter menu and the resulting event
var passFilterOnFieldVal;
// Passes the field type between the pop-up filter menu and the resulting event
var passFilterOnFieldType;
// Passes the contract id between the pop-up filter menu and the resulting event
var passFilterOnContractId;
// Kills off the first onclick() after showing the pop-up menu. Originally a boolean,
// but now used to hold a time. Clicks are suppressed if they happen within a defined
// number of milliseconds of the menu being shown. bSuppressHideMenu is therefore
// used to hold the time at which the menu is displayed, for comparison purposes
var bSuppressHideMenu;

function NumericFilterMenu(FieldId, parent, e, FieldType, ContractId) {
	HideMenus(true);

	// Nasty way of getting the field value without having to pass it as a parameter
	// and therefore increasing the HTML size. Dependent on the HTML not changing...
	passFilterOnFieldVal = parent.innerHTML;
	passFilterOnFieldId = FieldId;
	passFilterOnFieldType = FieldType;
	passFilterOnContractId = ContractId;
	var objMenu = document.getElementById("mnuNumericFilter");

	var t = getXY(parent).top;
	var l = getXY(parent).left;
	
	// See if it's necessary to include the link related to the fund id
	if (FieldId >= 6000000 && FieldId <= 6999999) {
		document.getElementById("mnuNumericFilterFundInfo").style.display = "";
		document.getElementById("lnkShowFundPPContract").href = "javascript:ShowPPFund(" + FieldId + ", '" + ContractId + "')";
	} else {
		document.getElementById("mnuNumericFilterFundInfo").style.display = "none";
	}
	
	// Adjust for potential scrolling of the grid
	l -= document.getElementById("BodyBlockContainer").scrollLeft;
	t -= document.getElementById("BodyBlockContainer").scrollTop;

	// Adjust the top
	t += 15;
	// Check the width
	if (l + 140 > document.body.clientWidth) {
		l = document.body.clientWidth - 140;
	}
	// Check the top
	if (t + 150 > document.body.clientHeight) {
		t = document.body.clientHeight - 150;
	}

	objMenu.style.top = t + "px";
	objMenu.style.left = l + "px";
	objMenu.style.display = "";
	bSuppressHideMenu = new Date();
	document.onclick = HideMenus;
}

function FeatureContextFilter(FieldId, FieldValueIsYes, ContractId, parent) {
	HideMenus(true);

	// Nasty way of getting the field value without having to pass it as a parameter
	// and therefore increasing the HTML size. Dependent on the HTML not changing...
	passFilterOnFieldVal = FieldValueIsYes;
	passFilterOnFieldId = FieldId;
	passFilterOnFieldType = 2;
	var objMenu = document.getElementById("mnuFeatureContextFilter");

	// Set the links on the menu items
	if (FieldValueIsYes) {
		document.getElementById("lnkFCFFilter").href = "javascript:AddFeatureFilter(" + FieldId + ", 1, true)";
	} else {
		document.getElementById("lnkFCFFilter").href = "javascript:FilterNo(" + FieldId + ")";
	}
	document.getElementById("lnkFCFContents").href = "javascript:ShowFieldContents(" + FieldId + ", '" + ContractId + "')";

	var t = getXY(parent).top;
	var l = getXY(parent).left;

	// Adjust for potential scrolling of the grid
	l -= document.getElementById("BodyBlockContainer").scrollLeft;
	t -= document.getElementById("BodyBlockContainer").scrollTop;

	// Adjust the top
	t += 15;
	// Check the width
	if (l + 140 > document.body.clientWidth) {
		l = document.body.clientWidth - 140;
	}
	// Check the top
	if (t + 150 > document.body.clientHeight) {
		t = document.body.clientHeight - 150;
	}

	objMenu.style.top = t + "px";
	objMenu.style.left = l + "px";
	objMenu.style.display = "";
	bSuppressHideMenu = new Date();
	document.onclick = HideMenus;
}



// Finds which of the lists a field belongs to
function GetParentListForField(objField) {
	var objFind = objField;
	while (objFind.parentNode) {
		switch (objFind.parentNode.id) {
			case "FeatureFields":
			case "SectorFields":
			case "ConditionFields":
			case "RankingFields":
				return objFind.parentNode.id;
		}

		objFind = objFind.parentNode;
	}
	return "";
}

function DoNumericFilter(strOper) {
	var objField = document.getElementsByName("f" + passFilterOnFieldId)[0];

	// It's possible to do a refresh of the filter page, and then do a pop-up
	// menu before the applicable tab of fields has been loaded. If so,
	// we need to load them in order to set the UI
	if (!objField) {
		var lFieldBlock = 4;
		var lTab = 0;
		switch (passFilterOnFieldType) {
			case 4:
				// Condition
				lFieldBlock = 3;
				lTab = 3;
				break;
			case 200:
			case 201:
				// Past performance or volatility
				lFieldBlock = 5;
				lTab = 5;
				break;
			default:
				lTab = 4;
				break;
		
		}
		if (!arrTabsLoaded[lFieldBlock]) {
			SwitchTab(lFieldBlock);
			CreateStatusWindow("Loading fields...", strPathContext);
			LoadAllNonFeatureFields();
			KillStatusWindow();
		} else {
			SwitchTab(lFieldBlock);
		}
		objField = document.getElementsByName("f" + passFilterOnFieldId)[0];
		if (!objField) {
			alert("Please switch to the appropriate list of fields before using this pop-up menu.");
			return;
		}
	}
	
	// Set the filter operator in the user interface
	var objComboOper = document.getElementsByName("foper" + passFilterOnFieldId)[0];
	var ctOptions = objComboOper.options.length;
	for (var iOption = 0; iOption < ctOptions; iOption++) {
		if (objComboOper.options[iOption].value == strOper) {
			objComboOper.selectedIndex = iOption;
			iOption = ctOptions;
		}
	}

	// Set the filter value in the user interface. Complications caused
	// by the combo boxes for financial strength
	if (objField.tagName.toLowerCase() == "select") {
		// Can be financial strength or a bespoke product rating
		ctOptions = objField.options.length;

		if (objField.fieldtype == 1004) {
			// Convert textual rating value to numeric
			var lRatingVal = BespokeRatingTextToValue(passFilterOnFieldVal);
			for (iOption = 0; iOption < ctOptions; iOption++) {
				if (Xval(objField.options[iOption].value) == lRatingVal) {
					objField.selectedIndex = iOption;
					iOption = ctOptions;
				}
			}
		} else {
			for (iOption = 0; iOption < ctOptions; iOption++) {
				if (objField.options[iOption].value.toLowerCase() == passFilterOnFieldVal.toLowerCase()) {
					objField.selectedIndex = iOption;
					iOption = ctOptions;
				}
			}
		}
	} else {
		objField.value = passFilterOnFieldVal;
	}
	// Show the appropriate page of the options
	var strParent = GetParentListForField(objField);
	switch (strParent) {
		case "FeatureFields":
			SwitchTab(1);
			break;				
		case "SectorFields":
			SwitchTab(2);
			break;				
		case "ConditionFields":
			SwitchTab(3);
			break;				
		case "RankingFields":
			SwitchTab(4);
			break;	
		case "PPFields":
			SwitchTab(5);
			break;	
	}				

	if (passFilterOnFieldId >= 6000000) {
		ShowHidePPBlock(Math.floor(passFilterOnFieldId / 100) * 100, true);
	}

	// Make sure that the field in question is visible
	objField.scrollIntoView();



	// Trigger the filtering
	SetConditionFilter(objField);
}

function HideMenus(bForce) {
	if (bSuppressHideMenu) {
		var dtNow = new Date();
		if (dtNow.valueOf() - bSuppressHideMenu.valueOf() < 200) return;
	}
	bSuppressHideMenu = false;
	document.getElementById("mnuNumericFilter").style.display = "none";
	document.getElementById("mnuContractContext").style.display = "none";
	document.getElementById("mnuFieldFiltering").style.display = "none";
	document.getElementById("mnuGridOptions").style.display = "none";
	document.getElementById("mnuGridFieldHeader").style.display = "none";
	document.getElementById("mnuFeatureContextFilter").style.display = "none";
}


// Kill the normal page context menu when right clicking on a field
function Page_ContextMenu(e) {
	if (!bUseBodyEventHandling) return;
	
	var objElem = e.target;
	if (!objElem) objElem = e.srcElement;
	if (objElem.onmousedown) return false;
}


function CM(FieldId, f, e, bIsFeatureField, lHasDef) {
	//alert(lHasDef);
	FilterOptionMenu(FieldId, f, e, bIsFeatureField, lHasDef);
	
	return KE(e);
}


function ShowFieldDefinition(FieldId) {
    //alert(""+strSearchId+"");
	if (!FieldId) FieldId = ContextFieldId;
	var strUrl = "pFieldDefinition.asp?fieldid=" + FieldId + "&searchid=" + strSearchId;
	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: 400px; DialogHeight: 300px");
	} else {
		var h = 300;
		var w = 400;
		l = (screen.availWidth - w) / 2;
		t = (screen.availHeight - h) / 2;
		var objW = window.open(strUrl, "wndFieldDefinition", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function GetMouseButton(e) {
	var b = e.button;
	if (!b) b = e.which;
	// For Macs only, because of the single mouse button

	if (IsMac()) {
		if (e.ctrlKey) b = 2;
	}
	return b;
}

function FilterOptionMenu(FieldId, f, e, bIsFeatureField, lHasDef) {
	HideMenus(true);

	var b = GetMouseButton(e)
	if (b != 2) return true;
	
	var t = getXY(f).top;
	var l = getXY(f).left;

	// Adjust for potential scrolling of the grid
	l -= document.getElementById("FieldListContainer").scrollLeft;
	t -= document.getElementById("FieldListContainer").scrollTop;

	// Adjust the top
	t += 18;
	// Check the width
	if (l + 140 > document.body.clientWidth) {
		l = document.body.clientWidth - 140;
	}
	// Check the top
	if (t + 160 > document.body.clientHeight) {
		t = document.body.clientHeight - 160;
	}

	ContextFieldId = FieldId;

	// Get the field id
	var objField = FindFieldDef(FieldId);
	var lDetailFieldId = 0;
	if (objField) {
		lDetailFieldId = objField.DetailFieldId;
	}
	
	document.getElementById("lnkFieldFilterYes").href = "javascript:FilterYes(" + FieldId + ")";
	document.getElementById("lnkFieldFilterNo").href = "javascript:FilterNo(" + FieldId + ")";
	document.getElementById("lnkFieldFilterDecline").href = "javascript:FilterDecline(" + FieldId + ")";
	document.getElementById("lnkFieldFilterClear").href = "javascript:FilterClear(" + FieldId + ")";
	document.getElementById("lnkFieldAdd").href = "javascript:SetDataField(" + FieldId + ")";
	document.getElementById("lnkFieldDef").href = "javascript:ShowFieldDefinition(" + FieldId + ")";
	document.getElementById("lnkShowHideChildren").href = "javascript:ShowHideSubFields(" + FieldId + ");";



	if (document.getElementById("subfields" + FieldId)) {
		document.getElementById("ContainerSHC").style.display = "";
	} else {
		document.getElementById("ContainerSHC").style.display = "none";
	}


	if (bIsFeatureField) {
		// Feature
		document.getElementById("mnuFeatureFiltering").style.display = "";
		document.getElementById("mff1").style.display = "";
		document.getElementById("mff2").style.display = "";
		document.getElementById("mff3").style.display = "";
		document.getElementById("mff4").style.display = "";
	} else if (FieldId >= 3000000 && FieldId <= 3999999) {
		document.getElementById("mnuFeatureFiltering").style.display = "";
		document.getElementById("mff1").style.display = "none";
		document.getElementById("mff2").style.display = "none";
		document.getElementById("mff3").style.display = "";
		document.getElementById("mff4").style.display = "";
	} else {
		document.getElementById("mnuFeatureFiltering").style.display = "none";
	}
	// Shows Or Hides 'Show definition' in the Context Menu, when  in Past Performance Tab,  Oz C 06/08/07
	if (lHasDef==1) {
		document.getElementById("divFieldDef").style.display = "";// Show Method
	} else {
		document.getElementById("divFieldDef").style.display = "none";// Hide Method
	} 
	
	// Show or hide the detail field option
	document.getElementById("lnkDetailHeader").style.display = (lDetailFieldId ? "" : "none");
	if (lDetailFieldId) {
		document.getElementById("lnkDetail").href = "javascript:SetDataField(" + lDetailFieldId + ")";
	}

	var objMenu = document.getElementById("mnuFieldFiltering");
	objMenu.style.top = t + "px";
	objMenu.style.left = l + "px";
	objMenu.style.display = "";

	bSuppressHideMenu = new Date();
	document.onclick = HideMenus;
	e.cancelBubble = true;
	return false;
}

function ContractContextMenu(ContractId, f, e) {
	HideMenus(true);

	var b = GetMouseButton(e)
	if (b != 2) return true;

	var t = getXY(f).top;
	var l = getXY(f).left;

	// Adjust for potential scrolling of the grid
	//l -= document.getElementById("BodyBlockContainer").scrollLeft;
	t -= document.getElementById("BodyBlockContainer").scrollTop;

	// Adjust the top
	t += 15;
	
	// Check the width
	if (l + 140 > document.body.clientWidth) {
		l = document.body.clientWidth - 140;
	}
	// Check the top
	if (t + 120 > document.body.clientHeight) {
		t = document.body.clientHeight - 120;
	}

    //MarkD 04/2008 need to force a sectortype choice
    if (lSectorType !==1) {
        if (document.getElementById("lnkContractFunds")) {
        document.getElementById("lnkViewContract").href = "javascript:CheckForSectorChoice2('" + ContractId + "' , '" + strSearchId + "')";
        } else {
	    document.getElementById("lnkViewContract").href = "Contract.asp?id=" + ContractId + "&searchid=" + strSearchId;
	    }
	} 
	if (document.getElementById("lnkFundGraph")) {
		document.getElementById("lnkFundGraph").href = "javascript:FundGraph('" + ContractId + "')";
	}
	if (document.getElementById("lnkAddToManual")) {
		document.getElementById("lnkAddToManual").href = "javascript:AddToManualList('" + ContractId + "')";
	}
	document.getElementById("lnkExcludeContract").href = "javascript:ExcludeContract('" + ContractId + "')";
	document.getElementById("lnkContractNotes").href = "javascript:ShowFieldContents(5000004, '" + ContractId + "')";
	if (document.getElementById("lnkContractFunds")) {
		document.getElementById("lnkContractFunds").href = "ContractFundList.asp?id=" + ContractId + "&searchid=" + strSearchId;
		//document.getElementById("lnkFundPicker").href = "ContractFundList.asp?fp=1&id=" + ContractId + "&searchid=" + strSearchId;
		document.getElementById("lnkFundPicker").href = "javascript:CheckForSectorChoice('" + ContractId + "' , '" + strSearchId + "')";
		//document.getElementById("lnkFundPicker").href = "javascript:alert('" + ContractId + " , " + strSearchId + "')";
		
	}

	var objMenu = document.getElementById("mnuContractContext");
	objMenu.style.top = t + "px";
	objMenu.style.left = l + "px";
	objMenu.style.display = "";

	bSuppressHideMenu = new Date();
	document.onclick = HideMenus;

	e.returnValue = false;
	e.cancelBubble = true;
	return false;
}
///////////////////////////////////////////////////////////////////////

      function FundPicker2(ContractId,strSearchId) {
      var strUrl = "ContractFundList.asp?fp=1&id=" + ContractId + "&searchid=" + strSearchId;
      Goto(strUrl);
      }

      function CheckForSectorChoice(ContractId,strSearchId) {

      if (lSectorType > 0) {
      FundPicker2(ContractId,strSearchId);
      } else {
      var strUrl = "pSectorCategoryChoice.asp?id=" + ContractId + "&searchid=" + strSearchId;
      var h = 100;
      var w = 500;

      if (whichBrs() == "Internet Explorer") {
      var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + (w + 20) + "px; DialogHeight: " + (h + 30) + "px");
      if (strRet) {
      FundPicker2(ContractId,strSearchId);
      }
      } else {
      l = (screen.availWidth - w) / 2;
      t = (screen.availHeight - h) / 2;
      var objW = window.open(RefreshableUrl(strUrl), "PopupWindow", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
      if (!objW) {
      alert("Your browser software is preventing popup windows from being opened.");
      } else {
      objW.focus();
      }
      }
      }
      }

///////////////////////////////////////////////////////////////////////

      function Contractsheet(ContractId,strSearchId) {
       var strUrl = "contract.asp?id=" + ContractId + "&searchid=" + strSearchId;
      Goto(strUrl);
      }

function CheckForSectorChoice2(ContractId,strSearchId) {
       
      if (lSectorType > 0) {
      Contractsheet(ContractId,strSearchId);
      } else {
      var strUrl = "pSectorCategoryChoice.asp?fs=1&id=" + ContractId + "&searchid=" + strSearchId;
      var h = 100;
      var w = 500;

      if (whichBrs() == "Internet Explorer") {
      var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + (w + 20) + "px; DialogHeight: " + (h + 30) + "px");
      if (strRet) {
      Contractsheet(ContractId,strSearchId);
      }
      } else {
      l = (screen.availWidth - w) / 2;
      t = (screen.availHeight - h) / 2;
      var objW = window.open(RefreshableUrl(strUrl), "PopupWindow", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
      if (!objW) {
      alert("Your browser software is preventing popup windows from being opened.");
      } else {
      objW.focus();
      }
      }
      }
      }
/////////////////////////////////////////////////////////////////////////


function DoExclusions() {
	var lContracts = Zval(document.getElementById("ctContracts").value);
	var strUrl = "pManualExclusions.asp?searchid=" + strSearchId;

	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: 500px; DialogHeight: 540px");
		if (strRet == "update") {
			LoadContractList();
		}
	} else {
		var h = 500;
		var w = 480;
		l = (screen.availWidth - w) / 2;
		t = (screen.availHeight - h) / 2;
		var objW = window.open(strUrl, "ManualExclusions" + strSearchId, "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

// More nasty tweaks for the same reasons as Delay_DoExcludeContract() above
function Delay_LoadContractList() {
	tmrDelayLoad = setInterval("FirstContractLoad()", 10);
}
function Delay_DoChangeSearchCaption(strCaption) {
	tmrDelayLoad = setInterval("DoChangeSearchCaption(\42" + strCaption + "\42)", 10);
}


function ChangeSearchCaption() {
	var strUrl = "pChangeTitle.asp?searchid=" + strSearchId;

	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: 420px; DialogHeight: 170px");
		if (strRet != "") {
			DoChangeSearchCaption(strRet);
		}
	} else {
		var h = 120;
		var w = 400;
		l = (screen.availWidth - w) / 2;
		t = (screen.availHeight - h) / 2;
		var objW = window.open(strUrl, "ChangeTitle" + strSearchId, "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}


function DoChangeSearchCaption(strCaption) {
	clearInterval(tmrDelayLoad);
	if (strCaption == null) {
		// No change
	} else {
		var strUrl = "_ChangeSearchCaption.asp?searchid=" + strSearchId + "&caption=" + EncodeForUrl(strCaption);

		CreateStatusWindow("Changing title...", strPathContext);

		var objXML = CreateXMLObject();
		objXML.open("GET", RefreshableUrl(strUrl), true);
		objXML.onreadystatechange = newReadyStateHandler(objXML, ChangeSearchCaption2);
		objXML.send(null);
	}
}
function ChangeSearchCaption2(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
						// The response text contains the new caption...
						strCaption = objXML.responseText;
						document.getElementById("lblCaption").innerHTML = strCaption;	
						break;
					case 299:
						alert("Unable to set the title for this research:\r\n\r\n" + objXML.responseText);
						break;
					default:
						alert("An error occurred while trying to change the title. Please try again.");
						break;
				}
				objXML = null;			
				break;
		}
	}
}



function FilterYes(FieldId) {
	if (!FieldId) FieldId = ContextFieldId;
	AddFeatureFilter(FieldId, 1, true);
}

function FilterNo(FieldId) {
	if (!FieldId) FieldId = ContextFieldId;

	// Change the field display state
	document.getElementById("frow" + FieldId).className = "SelectedNoFiltering";
	document.getElementById("lbl" + FieldId).style.color = "#FF0000";

	// Set the status
	var objField = document.getElementsByName("f" + FieldId)[0];
	objField.checked = true;

	// Tell the user that we're reloading...
	SetLoadingCaption();

	// Do the XML communication
	var objXML = CreateXMLObject();
	var strUrl = "";
	strUrl = "_AddToSearchFilter.asp?searchid=" + strSearchId + "&fieldid=" + FieldId + "&operator=2&value=" + 1;
	if (bGotMaxRecords) strUrl += "&max=1";
	strUrl += "&ptype=" + lProductTypeId;
	
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
	objXML.send(null);
}

function FilterDecline(FieldId) {
	if (!FieldId) FieldId = ContextFieldId;

	// Change the field display state
	document.getElementById("frow" + FieldId).className = "SelectedDeclineFiltering";
	document.getElementById("lbl" + FieldId).style.textDecoration = "line-through";
	document.getElementById("lbl" + FieldId).style.color = "";

	// Set the status
	var objField = document.getElementsByName("f" + FieldId)[0];
	objField.checked = false;

	// Tell the user that we're reloading...
	SetLoadingCaption();

	// Do the XML communication
	var strUrl = "";
	var objXML = CreateXMLObject();
	
	strUrl = "_AddToSearchFilter.asp?searchid=" + strSearchId + "&fieldid=" + FieldId + "&operator=1000&value=0";
	if (bGotMaxRecords) strUrl += "&max=1";
	strUrl += "&ptype=" + lProductTypeId;
	
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
	objXML.send(null);
}

function FilterClear(FieldId) {
	if (!FieldId) FieldId = ContextFieldId;
	AddFeatureFilter(FieldId, 0, false);
}

function FeatureKeypress(FieldId, e, bIsFeature) {
	var k;
	if (e.which) 
		k = e.which;
	else
		k = e.keyCode;

	switch (k) {
		// Z - decline
		case 90:
		case 122:
			if (bIsFeature) FilterDecline(FieldId);
			break;
		// X or N - no
		case 88:
		case 120:
		case 78:
		case 110:
			if (bIsFeature) FilterNo(FieldId);
			break;
		// Y - yes
		case 89:
		case 119:
			if (bIsFeature) AddFeatureFilter(FieldId, 1, true);
			break;
		// C - clear filter
		case 67:
		case 99:
			if (bIsFeature) AddFeatureFilter(FieldId, 0, false);
			break;
		// D - definition
		case 68:
		case 100:
			ShowFieldDefinition(FieldId);
			break;
	}

}

function FindFieldDef(FieldId) {
	var ct = gFields.length;
	for (var i=0 ;i < ct; i++) {
		if (gFields[i].FieldId == FieldId) {
			return gFields[i];
		}
	}
	return new FieldDef(0);
}

// Takes the block of data about feature fields which is initially dumped into
// the textarea with FeatureFieldData, and renders it as HTML. Called on
// page load. Equivalent to the FeatureFields template in _ContractFieldList.xsl (and
// this XSL file is now redundant).

function RenderFeatureFields() {
	// Initialise the HTML string, and get the raw field data
	var objH = new Array();
	var strData = document.getElementById("FeatureFieldData").value;

		
	// Split the fields into an array
	var arrFields = strData.split("|");
	var ctFields;
	if (!strData) {
		ctFields = 0;
	} else {
		ctFields = arrFields.length;
	}
	
	gFields = new Array();
	
	// Keep track of whether we're in the subs of a parent
	var bInSubs = false;
	var lLastParentField = 0;
	var lLastOperator = 0;

	// Run through each field
	for (var iField = 0; iField < ctFields; iField++) {

		// Split the data for this individual field. Index into arrInfo is as created by the XSL:
		//  0 = fieldid
		//  1 = fieldname
		//  2 = fieldtype
		//  3 = headertype
		//  4 = group
		//  5 = filter operator
		//  6 = filter value
		//  7 = percentage coverage
		//	8 = preset mode
		//  9 = detail field id (or zero if none)
		
		var arrInfo = arrFields[iField].split("`");

		// Get the header type and field id
		var lHeaderType = Zval(arrInfo[3]);
		var lFieldId = Zval(arrInfo[0]);
		var lOperator = Zval(arrInfo[5]);
		var lGroup = Zval(arrInfo[4]);
		var lFieldType = Zval(arrInfo[2]);
		var lFilterVal = Zval(arrInfo[6]);
		var lPreset = Zval(arrInfo[8]);
		var lDetailFieldId = Zval(arrInfo[9]);
		var lHasDef = Zval(arrInfo[10]);
		var lQuoteField = Zval(arrInfo[11]);
		
		//if (lQuoteField == 1) alert("QuoteField");
		
		//alert(lHasDef);
		var lParentPreset;

		gFields.push(new FieldDef(lFieldId, arrInfo[1], lFieldType, lHeaderType, "", lDetailFieldId, lHasDef));

		if (lHeaderType != 3) {
			lLastParentField = lFieldId;
			lParentPreset = lPreset;
			
			// If the last item was a sub, we need to close the <div> containing the 
			// list of multiple subs
			if (bInSubs) objH.push("</div>");
			bInSubs = false;

			// Get the class
			var strClass = "";
			switch (lOperator) {
				case 1:
					strClass = "SelectedField";
					break;
				case 2:
					strClass = "SelectedNoFiltering";
					break;
				case 1000:
					strClass = "SelectedDeclineFiltering";
					break;
				default:
					strClass = "GF";
					break;
			}

			var bDisabled = false;
			
			// Disable all quote related fields
		    if (lQuoteField == 1 && bLockQuoteFields) bDisabled = true;
		
			var strTitle = "";
			var lCoverage = Xval(arrInfo[7]);
			if (lCoverage < 0) {
				strTitle = "(Add the field to the grid to see its coverage)";
			} else if (!lCoverage) {
				bDisabled = true;
				strTitle = "Not available on any contracts";
			} else if (lCoverage < lMinimumFeatureCoverage && lCoverage >= 0) {
				bDisabled = true;
				strTitle = "Only available on " + lCoverage + "% of contracts";
			} else {
				strTitle = lCoverage + "%";
			}
			
			if (lFieldType == 7) {
				// yes/no/optional
				objH.push("<div id='frow" + lFieldId + "' style='border-bottom: solid 1px #E0E0E0; padding-top: 2px; padding-bottom: 2px; font-size: 8pt;'>");
				objH.push("<table border='0' cellpadding='0' cellspacing='0' width='90%'><tr><td>");
				objH.push("<span class='FieldName'" + (lHeaderType == 2 ? " style='font-weight: bold'" : "") + ">");
				objH.push("<a title='" + strAddToGridTooltip + "' href='#' style='" + (lOperator==2 ? "color: red" : "") + (lOperator == 1000 ? "text-decoration: line-through" : "") + "' id='lbl" + lFieldId + "' onmousedown='CM(" + lFieldId + ", this, event, false, " + lHasDef + ");return KE(event);' oncontextmenu='CM(" + lFieldId + ", this, event, false, " + lHasDef + ");return KE(event);' onclick='SetDataField(\42" + lFieldId + "\42, event);return KE(event);'>");
				objH.push(arrInfo[1]);
				objH.push("</a></span>");
				objH.push("</td><td class='" + strClass + "' style='padding-left: 5px' align='right'>");
				objH.push("<select onchange='YNOFilterField(this)' name='f" + lFieldId + "'><option value=''/>");
				objH.push("<option value='2'" + (lFilterVal == 2 ? " selected " : "") + ">Yes</option>");
				objH.push("<option value='3'" + (lFilterVal == 3 ? " selected " : "") + ">Yes/Opt</option>");
				objH.push("<option value='1'" + (lFilterVal == 1 ? " selected " : "") + ">Opt</option>");
				objH.push("<option value='0'" + (lFilterVal == 0 && lOperator ? " selected " : "") + ">No</option>");
				objH.push("</select>");
				objH.push("</td></tr></table>");
				objH.push("</div>");
			} else {
				if (lPreset == 2) {
					strTitle += " - fixed preset";
				}
				
				if (lPreset == 2 || bSearchIsReadOnly) bDisabled = true;
				
				// Normal or parent feature
				//markd 15/11/2007 nasty hack for IE6 lack of support for min-height
				//objH.push("<div class='FieldContainer' &lt;!--&amp;#91;if lte IE 6 &amp;#93;&gt; style='height:20px;' &lt;!&amp;#91;endif&amp;#93;--&gt; >");
				//objH.push("<div class='" + strClass + "' onmousedown='return FilterOptionMenu(" + lFieldId + ", this, event, lHasDef)' id='frow" + lFieldId + "' " + ">");
				objH.push("<table width='95%' cellpadding='2' cellspacing='0' border='0' class='" + strClass + "' onmousedown='return FilterOptionMenu(" + lFieldId + ", this, event, true, " + lHasDef + ")' id='frow" + lFieldId + "'><tr>")
				/*
					if (lFieldId == 10000013) {
						bDisabled = true;
						strTitle = "Click on the icon to read the notes before using this field";
					}
				*/
				objH.push("<td valign='top' width='15' align='left'><input " + (bDisabled ? " disabled='yes' ": "") + " title='" + strTitle + "' " + (bDisabled ? " disabled='yes' permdisabled='1' " : "") + " type='checkbox' onclick='SetFeatureFilter(this, event);' onmousedown='FilterOptionMenu(" + lFieldId + ", this, event, true, " + lHasDef + ");' block='1' name='f" + lFieldId + "' group='" + lGroup + "' htype='" + lHeaderType + "' onkeydown='FeatureKeypress(\42" + lFieldId + "\42, event, true)'" + (lOperator!=0 && lOperator!=1000 ? " checked='yes' ": "") + "/> </td>");
				objH.push("<td><span class='FieldName'" + (lHeaderType == 2 ? " style='font-weight: bold'" : "") + ">");
				if (lQuoteField == 1) objH.push(strQuoteMarker);
				objH.push("<a title='" + arrInfo[1] + "\r\n" + strRightClickTooltip + "' href='#' style='" + (lOperator==2 ? "color: red" : "") + (lOperator == 1000 ? "text-decoration: line-through" : "") + "' id='lbl" + lFieldId + "' onmousedown='return CM(" + lFieldId + ", this, event, true, " + lHasDef + ")' oncontextmenu='return CM(" + lFieldId + ", this, event, true, " + lHasDef + ")' onclick='SetDataField(\42" + lFieldId + "\42, event);return KE(event);' onkeypress='FeatureKeypress(\42" + lFieldId + "\42, event, true);return KE(event);'>");
				objH.push(arrInfo[1]);
				
				if (lFieldId == 10000013) {
					objH.push(" <a href='#' onclick='RSMInfo()'><img title='Show terms and conditions for RSM ratings' src='images/vsInfoX.gif' class='vs'/></a>");
				}

				objH.push(FieldNoteHtml(arrInfo[2]));
				
				objH.push("</a></span>");
				if (lDetailFieldId != 0) {
					objH.push(GetDetailFieldHtml(lDetailFieldId));
				}
				objH.push("</td></tr></table>");
				//objH.push("</div>");
				//objH.push("</div>");
			}
		} else {
			// Sub-feature - note that this uses the value of lOperator which is retained by
			// the parent we just processed
			if (!bInSubs) {
				// Need to see if either the parent or any of its children are
				// selected
				var bShowGroup = false;

				if (lLastOperator == 1) {
					bShowGroup = true;
				} else {
					for (var iFindSub = iField; iFindSub < ctFields; iFindSub++) {
						var arrSubInfo = arrFields[iFindSub].split("`");
						if (Zval(arrSubInfo[3]) != 3) {
							iFindSub = ctFields;
						} else {
							if (Zval(arrSubInfo[5])) {
								bShowGroup = true;
								iFindSub = ctFields;
							}
						}
					}
				}
				//MarkD 10/2007 removed intdent from style declaration on subfields to correct word wrapping				
				objH.push("<div id='subfields" + lLastParentField + "' style=' font-size: 8pt; " + (bShowGroup ? "" : "display: none") + "'>");
				bInSubs = true;
			}

			// Get the class
			var strClass = "";
			switch (lOperator) {
				case 1:
					strClass = "SelectedField";
					break;
				case 2:
					strClass = "SelectedNoFiltering";
					break;
				case 1000:
					strClass = "SelectedDeclineFiltering";
					break;
				default:
					strClass = "GF";
			}

			var bDisabled = false;
			
			// Disable all quote related fields
		    if (lQuoteField == 1 && bLockQuoteFields) bDisabled = true;
			
			var bPermDisabled = false;
			var strTitle = "";
			var lCoverage = Xval(arrInfo[7]);
			if (lCoverage < 0) {

			} else if (!lCoverage) {
				bDisabled = true;
				bPermDisabled = true;
				strTitle = "Not available on any contracts";
			} else if (lCoverage < lMinimumFeatureCoverage) {
				bDisabled = true;
				bPermDisabled = true;
				strTitle = "Only available on " + lCoverage + "% of contracts";
			} else {
				strTitle = lCoverage + "%";
			}


			// Need to disable if part of a group, and one of the other members of
			// the group is disabled - but only if doing client-focused research
			if (bHasClients && !lOperator && lGroup) {
				// Loop through looking for other fields in this group with a Yes filter operator
				for (var iFind =0; iFind < ctFields; iFind++) {
					var arrLookIn = arrFields[iFind].split("`");
					if (Zval(arrLookIn[4]) == lGroup && Zval(arrLookIn[5]) == 1) {
						bDisabled = true;
						strTitle += "\r\n" + strMutualExclusivity;
						iFind = ctFields;
					}
				}
			}
			


			// Handle presets
			if (lPreset == 2) {
				bDisabled = true;
				strTitle += " - fixed preset";
			}

			if (lPreset == 2 || bSearchIsReadOnly) bDisabled = true;
			
			//objH.push("<div class='" + strClass + "' onmousedown='return FilterOptionMenu(" + lFieldId + ", this, event, true, " + lHasDef + ")' id='frow" + lFieldId + "'>");
			//MarkD 10/2007 put the checkboxes & field names into a table to tidy up word wrapping on long names
			//original div is now redundant
			//objH.push("<div class='FieldContainer' &lt;!--&amp;#91;if lte IE 6 &amp;#93;&gt; style='height:20px;' &lt;!&amp;#91;endif&amp;#93;--&gt; >");
			//objH.push("<div class='" + strClass + "' onmousedown='return FilterOptionMenu(" + lFieldId + ", this, event, true)' id='frow" + lFieldId + "'>");
			objH.push("<table width='95%' cellpadding='2' cellspacing='0' border='0' class='" + strClass + "' onmousedown='return FilterOptionMenu(" + lFieldId + ", this, event, true, " + lHasDef + ")' id='frow" + lFieldId + "'><tr>")
			objH.push("<td valign='top' width='35' align='right'><input title='" + strTitle + "' " + (bDisabled ? " disabled='yes' " : "") + (bPermDisabled ? " permdisabled='1' ": "") + " type='checkbox' onclick='SetFeatureFilter(this, event)' onmousedown='return FilterOptionMenu(" + lFieldId + ", this, event, true, " + lHasDef + ");' name='f" + lFieldId + "' groupid='" + lGroup + "' htype='" + lHeaderType + "' onkeydown='FeatureKeypress(\42" + lFieldId + "\42, event, true);return KE(event);' " + (lOperator!=0 && lOperator!=1000 ? " checked='yes' ": "") + " parentfield='" + lLastParentField + "'/> </td> ");
			objH.push("<td><span class='FieldName'" + (lHeaderType == 2 ? " style='font-weight: bold'" : "") + ">");
			objH.push("<a title='" + arrInfo[1] + "\r\n" + strRightClickTooltip + "' href='#' style='" + (lOperator==2 ? "color: red" : "") + (lOperator == 1000 ? "text-decoration: line-through" : "") + "' id='lbl" + lFieldId + "' onmousedown='return CM(" + lFieldId + ", this, event, true, " + lHasDef + ")' oncontextmenu='return CM(" + lFieldId + ", this, event, true, " + lHasDef + ")' onclick='SetDataField(\42" + lFieldId + "\42, event);return KE(event);' onkeypress='FeatureKeypress(\42" + lFieldId + "\42, event, true);return KE(event);'>");
			if (lQuoteField == 1) objH.push(strQuoteMarker);
			objH.push(arrInfo[1]);
			objH.push("</a></span>");

			if (lDetailFieldId != 0) {
				objH.push(GetDetailFieldHtml(lDetailFieldId));
			}
			
			objH.push("</td></tr></table>");
			//objH.push("</div>");

		}

		// Append the field HTML to the overall HTML
		lLastOperator = lOperator;
	}

	// If the last item was a sub, we need to close the <div> containing the 
	// list of multiple subs
	if (bInSubs) objH.push("</div>");
	
	if (!ctFields) objH.push("(This product type does not have any feature fields.)");
	
	// Dump the field HTML into the container
	document.getElementById("FeatureFields").innerHTML = objH.join('');	
}

function GetDetailFieldHtml(DetailFieldId) {
	//return " <a href='#' onclick='SetDataField(" + DetailFieldId + ")'><img title='This field is clarified by a policy condition. Click here to add/remove the policy condition to the grid.' src='images/vsmagnify.gif' class='vs'/></a>";
}

function ShowExclusions() {
	if (lProductTypeId == FUND_PRODUCT_TYPE && lBasisId <= 5) {
		if (!confirm("The audit trail for fund research can take a long time to compile (because of the potentially large number of funds) and only ever includes funds which are both primary and open.\r\n\r\nIf you want to know why a single specific fund has been filtered out, it may be simpler and more effective to open the factsheet for that fund and compare its performance to what you are filtering on.\r\n\r\nAre you sure you want to display the audit trail for this research?")) {
			return;
		}
	}

	var lContracts = Zval(document.getElementById("ctContracts").value);
	var lTotalContracts = document.getElementById("TotalContracts").value;
	var lExcluded = Zval(document.getElementById("ctExcluded").value);

	if (lContracts + lExcluded >= lTotalContracts) {
		if (lExcluded|| (lProductTypeId == FUND_PRODUCT_TYPE && lBasisId > 5)) {
			Goto("SearchExclusionMatrix.asp?searchid=" + strSearchId + "&exclusions=1");
		} else {
			alert("This research includes all contracts. Nothing has been filtered out or manually excluded.");
		}
	} else {
		Goto("SearchExclusionMatrix.asp?searchid=" + strSearchId);
	}	
}

// Shows the fund being used for a combination of contract, sector, and time period id
function ShowPPFund(FieldId, ContractId) {
	if (FieldId >= 6000000 && FieldId <= 6999999) {
		var lSectorId = Math.floor((FieldId - 6000000) / 100); 
		var lTimePeriod = (FieldId % 100);

		var strUrl = "pShowPPFund.asp?searchid=" + strSearchId + "&contractid=" + ContractId + "&sectorid=" + lSectorId + "&timeperiod=" + lTimePeriod;

		if (whichBrs() == "Internet Explorer") {
			var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: 400px; DialogHeight: 220px");
			if (strRet) {
				OpenFundFactsheet(strRet);
			}
		} else {
			var h = 170;
			var w = 400;
			l = (screen.availWidth - w) / 2;
			t = (screen.availHeight - h) / 2;
			var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
			if (!objW) {
				alert("Your browser software is preventing popup windows from being opened.");
			} else {
				objW.focus();
			}
		}
	} else {
		// Should never get here...
		alert("The selected field is not a past performance field.");
		return;
	}
}

function OpenFundFactsheet(FundId) {
	Goto("fund.asp?id=" + FundId + "&searchid=" + strSearchId);
}

var bDeletePresets = false;
function DeleteResearch(PresetMode) {
	if (PresetMode) {
		if (!confirm("Are you SURE that you want to delete these preset criteria?")) return;
		CreateStatusWindow("Deleting presets...", strPathContext);
		bDeletePresets = true;
	} else {
		if (!confirm("Are you SURE that you want to delete this research?")) return;
		CreateStatusWindow("Deleting research...", strPathContext);
		bDeletePresets = false;
	}


	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl("_DeleteSearch.asp?searchid=" + strSearchId), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, DeleteResearch2);
	objXML.send(null);
}


function DeleteResearch2(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
						if (bDeletePresets) {
							Goto("admin/Presets.asp");
						} else {
							Goto("index.asp");
						}
						break;
					case 299:
						alert("An error occurred while trying to delete this research:\r\n\r\n" + objXML.responseText);
						break;							
					default:
						alert("Unable to delete the research");
						break;							
				}						
				objXML = null;
		}
	}
}

function CreateCopyOfResearch(SearchId) {
	if (!confirm("Are you sure you want to start a new piece of research based on this research?")) return;
	Goto("CreateResearchCopy.asp?searchid=" + SearchId);
}

function Menu_ShowFieldContents() {
	ShowFieldContents(passFilterOnFieldId, passFilterOnContractId);
}

function ShowFieldContents(FieldId, ContractId) {
	HideMenus(true);
	var strUrl = "pFieldContents.asp?fieldid=" + FieldId + "&contractid=" + ContractId;
	var sFeatures;
	
	//MarkD Feb08 tidied up the pop up by centering it in the browser and giving it fixed dimensions
	var w = "650";
	var h = "550";
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	
	if (whichBrs() == "Internet Explorer") {
		sFeatures =  "resizeable=no,menubar=no,status=no,toolbar=no,scrollbars=yes,top="+wint+",left="+winl+",width="+w+",height="+h+"";
	} else {
		sFeatures =  "resizeable=no,menubar=no,status=no,toolbar=no,scrollbars=yes,top="+wint+",left="+winl+",width="+w+",height="+h+"";
	}	
	var objW = window.open(strUrl, "wndFieldContents", sFeatures);
		
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	
}


function YNOFilter(FieldId, FieldValue) {
	// Find the corresponding field
	var objF = document.getElementsByName("f" + FieldId)[0];
	var ctO = objF.options.length;
	for (var i = 0; i < ctO; i++) {
		if (objF.options[i].value == FieldValue) {
			document.getElementById("frow" + FieldId).className = "SelectedField";
			objF.selectedIndex = i;
			i = ctO;
		}
	}

	objF.scrollIntoView();
	DoYNOFilter(FieldId, FieldValue);
}

function YNOFilterField(f) {
	var strFieldVal = GetComboValue(f);
	var lFieldVal = 0;
	if (!strFieldVal) {
		lFieldVal = -1;	
	} else {
		lFieldVal = Zval(strFieldVal);
	}
	var strFieldId = f.name.substr(1);
	DoYNOFilter(strFieldId, lFieldVal);

	document.getElementById("frow" + strFieldId).className = ((strFieldVal) ? "SelectedField" : "GF");
}

function DoYNOFilter(FieldId, FieldValue)
{
	// Tell the user that we're reloading...
	SetLoadingCaption();

	// Do the XML communication
	var strUrl = "";
	var objXML = CreateXMLObject();
	if (FieldValue < 0) {
		strUrl = "_RemoveFromSearchFilter.asp?searchid=" + strSearchId + "&fieldid=" + FieldId;
	} else {
		strUrl = "_AddToSearchFilter.asp?searchid=" + strSearchId + "&fieldid=" + FieldId + "&operator=1&value=" + FieldValue;
		if (bGotMaxRecords) strUrl += "&max=1";
		strUrl += "&ptype=" + lProductTypeId;
	}
	
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
	objXML.send(null);
}




function DisplayContractCount() {

	var lContracts = Zval(document.getElementById("ctContracts").value);
	var lTotalContracts = document.getElementById("TotalContracts").value;
	var lExcluded = Zval(document.getElementById("ctExcluded").value);
	var lPercentageRemaining = Math.floor(Math.round(lContracts / lTotalContracts * 100));
	if (lPercentageRemaining == 0 && lContracts > 0) lPercentageRemaining = 1;
	if (lPercentageRemaining == 100 && lContracts < lTotalContracts) lPercentageRemaining = 99;

	var strCountCaption = "";
	if (lProductTypeId == FUND_PRODUCT_TYPE) {
		if (lContracts >= MAX_RECORDS) {
			//strCountCaption = "Only listing the <b>first</b> " + MAX_RECORDS + " funds - filter the grid to eliminate funds";
			//JohnC Defect 1-1451 - Display message about which funds are being shown.
			strCountCaption += "Showing " + ((((intCurrentPage - 1) * MAX_RECORDS) + 1) * 1) + " to " + (intCurrentPage * MAX_RECORDS) + " of " + lngTotalResults + " funds";
			bGotMaxRecords = true;
			
		} else {
			if (!lContracts) {
				if (lBasisId > 10) {
					// Not normal ut, life, pension research etc
					strCountCaption += "No funds";
				} else {
					// Research into ut funds, life pension etc.
					//MarkD 10/2007 added onclick call to display the show all sectors button
					shvalue = "showhide"
					strCountCaption += "No funds included - choose one or more <b><a href='#' onclick='SwitchTab(2);Showhide(shvalue);'>sectors</a></b>";
				}
			} else {
			    //Change here
			    if (lProductTypeId == FUND_PRODUCT_TYPE && lBasisId > 10 && lBasisId < 17) {
					if (lBasisId == 16 ){
					strCountCaption += lContracts + " " + (lContracts==1 ? "index" : "indices");
					} else {
				    strCountCaption += lContracts + " sector" + (lContracts==1 ? "" : "s");
				    }
				} else {
				    //strCountCaption += lContracts + " fund" + (lContracts==1 ? "" : "s");
				    //JohnC Defect 1-1451 - Display message about which funds are being shown.
				    //We are either on the last page of results or or there is only 1 page of results.
				    strCountCaption += "Showing " + ((((intCurrentPage - 1) * MAX_RECORDS) + 1) * 1) + " to " + lngTotalResults + " of " + lngTotalResults + " fund" + (lngTotalResults==1 ? "" : "s");
				}
			}
			
			if (lBasisId == MANUAL_FUND_LIST_PRODUCT_BASIS) {
				strCountCaption += " - <b><a href='#' onclick='AddFundToManualList()'>add a fund</a></b>";
			}

			bGotMaxRecords = false;
		}
		
				var strButtonBar = "";
				//strButtonBar += " <span style='padding-left: 20px'>";
				strButtonBar += "<input " + (lContracts ? "" : " disabled ") + "type='button' class='button' name='btnFC' value='Factsheets' title='Generate factsheets for funds in this list' onclick='FactsheetChoice()'/>";
				if (bAllowGraphing) {
					strButtonBar += " <input " + (lContracts ? "" : " disabled ") + "type='button' class='button' name='btnFC' value='Graph' title='Graph the funds in this list' onclick='FundGraphChoice()'/>";
				}
				//strCountCaption += "</span>";
				document.getElementById("CaptionButtonBar").innerHTML = strButtonBar;
		

		if (lBasisId != MANUAL_FUND_LIST_PRODUCT_BASIS) {
			lExcludedContracts = 0;
		}
	} else {
		strCountCaption = "<a title='Show the audit trail' class='WLB' href='#' onclick='ShowExclusions();return KE(event);'>";
		if (lContracts == lTotalContracts) {
			strCountCaption += "All " + lContracts + " contract" + (lContracts==1 ? "" : "s") + "";
			lExcludedContracts = 0;
		} else {
			strCountCaption += lContracts + " contract" + (lContracts==1 ? "" : "s") + " out of " + lTotalContracts + "";
			strCountCaption += " (" + lPercentageRemaining + "%)";
			lExcludedContracts = lTotalContracts - lContracts;
		}
		strCountCaption += "</a>";
		if (lExcluded) {
			strCountCaption += "  - <a title='Remove contracts from the grid' class='WLB' href='#' onclick='DoExclusions();return KE(event);'>" + lExcluded + " manually excluded</a>";
		} else {
			strCountCaption += "  - <a title='Remove contracts from the grid' class='WLB' href='#' onclick='DoExclusions();return KE(event);'>0 manually excluded</a>";
		}

	}
	document.getElementById("ContractCountCaption").innerHTML = strCountCaption;
	//MarkD added call to update counter display
	ShowCounter();
	
	// Bar chart
	if (lProductTypeId != FUND_PRODUCT_TYPE) {
		var strBar = "";
		strBar += "<div style='; height: 12px; width: " + lPercentageRemaining + "px; background-color: #008000; overflow: hidden;'></div>";
		document.getElementById("ContractPercentageBar").innerHTML = strBar;
		document.getElementById("ContractPercentageBar").title = "Contracts included: " + lPercentageRemaining + "%";
		document.getElementById("ContractPercentageBar").style.backgroundColor = "#FFF0F0";
	}
}

var strStoreContractData = "";
var strIncludeContractList = "";
var strDataBodyHtml = "";

var arrLine, szHeader, ctParts, ctFields, ctExcluded, ctContracts, arrContracts;
var ctSortFields, arrSortFields, arrFields;

//JohnC Defect 1-1451 declare variables for paging results
var intTotalPages = 0;
var lngTotalResults = 0;
var intCurrentPage = 1;
var arrPages;

var tmrDelayDisplayContractList;

function DisplayContractList(strData) {
	try {
		clearInterval(tmrDelayDisplayContractList);
		if (bInRenderingFlag) {
			// Need to delay by 100 milliseconds and then try again
			tmrDelayDisplayContractList = setInterval("DisplayContractList(\42" + strData + "\42)", 100);
			return;
		}

		bInRenderingFlag = true;

		SetRenderingCaption();
		if (!strData) {
			strData = strStoreContractData;
			if (!strData) return;
		} else {
			strStoreContractData = strData;
			strIncludeContractList = "";


			// Split the data into constituent lines
			arrLine = strData.split("`");
			szHeader = 4;
			// Work out the number of fields and contracts based on the size of the arrLine array
			ctParts = arrLine.length;
			ctFields = Zval(arrLine[0]);
			ctExcluded = Zval(arrLine[1]);
			ctContracts = ctParts - ctFields - szHeader;


			var strSortFields = arrLine[2];
			ctSortFields = 0;
			if (!strSortFields) {
				ctSortFields = 0;
				arrSortFields = new Array();
			} else {
				var arrSortF = strSortFields.split("~");
				ctSortFields = arrSortF.length;
				arrSortFields = new Array(ctSortFields);
				for (var iSort = 0; iSort < ctSortFields; iSort++) {
					var arrSortPart = arrSortF[iSort].split(":");
					arrSortFields[iSort] = new SortField(arrSortPart[0], arrSortPart[1]);
				}
			}				
			cacheCountOfSortFields = ctSortFields;


            //JohnC Defect 1-1451 extract paging info from the returned data string
            //get the total pages, current page and total results
            arrPages = arrLine[3].split("~");
            intCurrentPage = parseInt(arrPages[0]);
            intTotalPages = parseInt(arrPages[1]);
            lngTotalResults = parseInt(arrPages[2]);


			arrFields = new Array(ctFields);
			arrContracts = new Array(ctContracts);


			// Get the fields
			for (var iField = 0; iField < ctFields; iField++) {
				var strFieldDef = arrLine[iField + szHeader];
				var arrFieldDef = strFieldDef.split("~");
				arrFields[iField] = new FieldDef(Zval(arrFieldDef[0]),arrFieldDef[1],arrFieldDef[2],arrFieldDef[3],arrFieldDef[4],Zval(arrFieldDef[5]));


				var lColumnWidth = renderDefaultFieldWidth;
				switch (arrFields[iField].FieldType) {
					case 3:
					case 4:
						lColumnWidth = 100;
						break;
					case 5:
					case 6:
					case 5000004:
					case 1003:
						lColumnWidth = 200;
						//lRowHeight = 40;
						break;
					case 1:
						lColumnWidth = 150;
						break;
					default:
						lColumnWidth = 75;
						break;

				}
				arrFields[iField].RenderWidth = lColumnWidth;
			}

			// Get the contracts
			for (var iContract = 0; iContract < ctContracts; iContract++) {
				var strContractDef = arrLine[iContract + ctFields + szHeader];
				var arrContractDef = strContractDef.split("~");
				arrContracts[iContract] = new ContractDef(arrContractDef[0],arrContractDef[1],arrContractDef[2], arrContractDef[3], arrContractDef[4], arrContractDef);
			}
		}

		if (bFlipGrid) {
			tmrRenderingStage1 = setInterval("DisplayContractList_Flipped()", 10);
		} else {
			tmrRenderingStage1 = setInterval("DisplayContractList_Normal()", 10);
		}
	}
	catch (e) {
		SetFailedCaption();
		alert("An error occurred while trying to display the list of contracts.");
		Goto("FilterContracts.asp?searchid=" + strSearchId);
		bInRenderingFlag = false;
	}
}

var tmrRenderingStage1 = null;
var tmrRenderingStage2 = null;


function DisplayContractList_Normal() {
	try {
		clearInterval(tmrRenderingStage1);
		clearInterval(tmrRenderingStage2);

		var ctContracts = arrContracts.length;
		var ctFields = arrFields.length;
		var ctSortFields = arrSortFields.length;

		// See if we have scroll values to preserve
		lResetScrollLeft = 0;
		lResetScrollTop = 0;
		if (document.getElementById("BodyBlockContainer")) {
			lResetScrollLeft = document.getElementById("BodyBlockContainer").scrollLeft;
			lResetScrollTop = document.getElementById("BodyBlockContainer").scrollTop;
		}

		lRowHeight = renderRowHeight;
		lHeaderHeight = renderNormalHeaderHeight;


		// Get the fields
		var lScrollableColumnTotalWidth	= 0;
		for (var iField = 0; iField < ctFields; iField++) {
			lScrollableColumnTotalWidth += arrFields[iField].RenderWidth;
		}

		if (lScrollableColumnTotalWidth == 0 && lBasisId == 0) {
			lCompanyNameWidth = 200;
			lContractNameWidth = 225;
		} else if (lScrollableColumnTotalWidth <= 100 && lBasisId != 0) {
			lCompanyNameWidth = 200;
			lContractNameWidth = 275;
		} else if (lScrollableColumnTotalWidth <= 150 && lBasisId != 0) {
			lCompanyNameWidth = 200;
			lContractNameWidth = 200;
		} else {
			lCompanyNameWidth = 125;
			lContractNameWidth = 200;
		}
		lContractBasisNameWidth = 150;

		if (bIs800x600) {
			lCompanyNameWidth = 170;
			lContractNameWidth = 170;
		}

		// Hide the company name if dealing with unit trusts
		if (lProductTypeId == FUND_PRODUCT_TYPE) {
			lCompanyNameWidth = 0;
			if (lScrollableColumnTotalWidth == 0) {
				lContractNameWidth = 400;
			} else {
				lContractNameWidth = 275;
			}

			if (bIs800x600) {
				lContractNameWidth = 300;
			}
		}

		var lFixedColumnWidth = lCompanyNameWidth + lContractNameWidth;
		if (lBasisId == 0) lFixedColumnWidth += lContractBasisNameWidth;

		var lTotalRowHeight = ctContracts * lRowHeight;

		var lHeightSoFar = 0, lWidthSoFar = 0;

		var strHeaderClass = "", strClass = "";

		var objH = new Array();	

		var lInitial = 199;

		// Render!

		
		
		// JohnC Defect 1-1451
		// Set up paging links and display them on screen
		// Currently only shown for fund research
		if(lProductTypeId == FUND_PRODUCT_TYPE && intTotalPages > 1)
		{
		    var intPrevPage = intCurrentPage - 1;
		    var intNextPage = intCurrentPage + 1;
		    var pagesShown = 4;
		    var firstPage;
		    var lastPage;
    		
		    // Work out what range of page links to show on screen
		    firstPage = intCurrentPage - pagesShown;
		    if(firstPage < 1) firstPage = 1;
            lastPage = (intCurrentPage + pagesShown);
		    if(lastPage > intTotalPages) lastPage = intTotalPages;
    		
		    // Set up link to the next page if there is 1.
		    if(intNextPage > intTotalPages) 
		    {
		        strNextPage = "";
		    }
		    else
		    {
		        strNextPage = "<a href='#' style='font-weight:bolder' onclick='LoadContractList(" + intNextPage + ")'> &nbsp >>>  </a>";
		    }
    		
		    // Set up link to the previous page if there is 1.
		    if(intPrevPage < 1)
		    {
		        strPrevPage = "";
		    }
		    else
		    {
		        strPrevPage = "<a href='#' style='font-weight:bolder' onclick='LoadContractList(" + intPrevPage + ")'> <<< &nbsp </a>";
		    }
    		
		    //Create footer for the grid which will contain the page links
		    objH.push("<div id='ContractPageContainer' style=''>" + strPrevPage);
    		
		    //Loop through adding the page links
		    for(i=firstPage;i<=lastPage;i++)
		    {
		        if(i == intCurrentPage)
		        {
		            objH.push("<span style='font-weight:bold'>[" + i + "]</span>");
		        }
		        else
		        {
		            objH.push("<a href='#'  onclick='LoadContractList(" + i + ")'> " + i + " </a>");
		        }
		    }
            objH.push(strNextPage + "</div>");
        }		
		
		objH.push("<div class='BorderOnScreenOnly'>");		
		objH.push("<div style='position: relative;'>");

		// Hidden info fields
		objH.push("<input type='hidden' id='ctContracts' value='" + ctContracts + "'/>");
		objH.push("<input type='hidden' id='ctExcluded' value='" + ctExcluded + "'/>");
		objH.push("<input type='hidden' id='ctFields' value='" + ctFields + "'/>");
		objH.push("<input type='hidden' id='useRowHeight' value='" + lRowHeight + "'/>");
		objH.push("<input type='hidden' id='useScrollableWidth' value='" + lScrollableColumnTotalWidth + "'/>");
		objH.push("<input type='hidden' id='useScrollableHeight' value='" + lTotalRowHeight + "'/>");
		objH.push("<input type='hidden' id='useHeaderHeight' value='" + renderNormalHeaderHeight + "'/>");
		objH.push("<input type='hidden' id='useFixedColumnWidth' value='" + lFixedColumnWidth + "'/>");

		// Container for company and contract header
		objH.push("<div style='position: relative;'>");


			// Company name

			strHeaderClass = (IsSortField(arrSortFields, ctSortFields, 5000000) ? "CRowSortHeader" : "CRowHeader");
			objH.push("<div style='width: " + (lCompanyNameWidth - 2) + "px; height: " + (lHeaderHeight - 2) + "px; overflow: hidden;' class='" + strHeaderClass + "'>");
			objH.push("<table border='0' cellpadding='3' cellspacing='0' width='100%' height='100%'><tr><td>");
			objH.push("<a class='WL' href='#' onclick='SetSortField(5000000, event);return KE(event);'>Company</a>");

			objH.push("</tr></td></table>");
			objH.push("</div>");

			// Contract name
			strHeaderClass = (IsSortField(arrSortFields, ctSortFields, 5000001) ? "CRowSortHeader" : "CRowHeader");
			objH.push("<div style='position: absolute; top: 0px; left: " + lCompanyNameWidth + "px; width: " + (lContractNameWidth - 2) + "px; height: " + (lHeaderHeight - 2) + "px; overflow: hidden;' class='" + strHeaderClass + "'>");
			objH.push("<table border='0' cellpadding='3' cellspacing='0' width='100%' height='100%'><tr><td>");
			objH.push("<a class='WL' href='#' onclick='SetSortField(5000001, event);return KE(event);'>" + (lProductTypeId == FUND_PRODUCT_TYPE ? "Fund" : "Contract") + "</a>");
			objH.push("</tr></td></table>");
			objH.push("</div>");

			// Basis name
			if (lBasisId == 0) {
				strHeaderClass = (IsSortField(arrSortFields, ctSortFields, 5000008) ? "CRowSortHeader" : "CRowHeader");
				objH.push("<div style='position: absolute; top: 0px; left: " + (lCompanyNameWidth + lContractNameWidth) + "px; width: " + (lContractBasisNameWidth - 2) + "px; height: " + (lHeaderHeight - 2) + "px; overflow: hidden;' class='" + strHeaderClass + "'>");
				objH.push("<table border='0' cellpadding='3' cellspacing='0' width='100%' height='100%'><tr><td>");
				objH.push("<a class='WL' href='#' onclick='SetSortField(5000008, event);return KE(event);'>Basis</a>");
				objH.push("</tr></td></table>");
				objH.push("</div>");
			}

		// End of container for company and contract header
		objH.push("</div>");



		// Container for scrollable header rows
		objH.push("<div id='HeaderRowContainer' class='HideOverflowOnScreen' style='background-color: #F7F7F7; position: absolute; top: 0px; left: " + lFixedColumnWidth + "px; height: " + lHeaderHeight + "px; width: " + lInitial + "px'>");
		objH.push("<div style='position: relative; width: " + lScrollableColumnTotalWidth + "px; height: " + lHeaderHeight + "px; overflow: hidden;'>");

		// Header column for each field
		lWidthSoFar = 0;
		for (iField = 0; iField < ctFields; iField++) {
			strHeaderClass = (IsSortField(arrSortFields, ctSortFields, arrFields[iField].FieldId) ? "CRowSortHeader" : "CRowHeader");
			var lThisColumnWidth = arrFields[iField].RenderWidth;
			var strAlign = "";
			if (arrFields[iField].FieldType != 1 && arrFields[iField].FieldType != 1003  && arrFields[iField].FieldType != 5 && arrFields[iField].FieldType != 6 && arrFields[iField].FieldType != 5000004) strAlign = "AR";
			

			objH.push("<div ondragover='overDrag(event)' ondragenter='enterDrag(event)' ondrop='onDrop(event)' id='header" + arrFields[iField].FieldId + "' style='position: absolute; " + strAlign + "; top: 0px; left: " + lWidthSoFar + "px; height: " + (lHeaderHeight - 2) + "px; width: " + (lThisColumnWidth - 2) + "px; overflow: hidden' class='" + strHeaderClass + "'>");

			objH.push("<table border='0' cellpadding='3' cellspacing='0' width='100%' height='100%'><tr><td id='td" + arrFields[iField].FieldId + "' class='" + strAlign + "'>");

			// Title of field
			var strTooltip = arrFields[iField].FieldName;
			if (arrFields[iField].HeaderType == 3) strTooltip = arrFields[iField].ParentFieldName + ": " + strTooltip;

			objH.push("<a id='flink" + arrFields[iField].FieldId + "' ondragend='endDrag(event)' ondragstart='startDrag(event)' onmousedown='return GridFieldMenu(event, " + arrFields[iField].FieldId + ", this)' title=\42" + strTooltip + "\r\n" + strRightClickTooltip + "\42 class='WL' href='#' onclick='SetSortField(" + arrFields[iField].FieldId + ", event);return KE(event);'>");
			if (arrFields[iField].HeaderType == 3) objH.push("<em>");
			objH.push(arrFields[iField].FieldName);
			if (arrFields[iField].HeaderType == 3) objH.push("</em>");
			objH.push("</a>");

			objH.push("</tr></td></table>");

			objH.push("</div>");

			lWidthSoFar += lThisColumnWidth;
		}	

		// End of containers for scrollable header rows
		objH.push("</div></div>");


		objH.push("</div>");
		objH.push("<div style='position: relative'>");


	// CONTRACT NAME BOX
		objH.push("<div id='ContractNameContainer' class='HideOverflowOnScreen' style='position: relative; width: " + (lFixedColumnWidth - 1) + "px; height: " + lInitial + "px'>");
		objH.push("<div style='width: " + lFixedColumnWidth + "px; height: " + lTotalRowHeight + "px; overflow: hidden'>");
		lHeightSoFar = 0;



		if (ctContracts == 0 && lProductTypeId == FUND_PRODUCT_TYPE && lBasisId == MANUAL_FUND_LIST_PRODUCT_BASIS) {
			objH.push("<div style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; overflow: hidden; width: " + (lContractNameWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: " + lCompanyNameWidth + "px; top: " + 0 + "px' class='GT'>");
			objH.push("(Add funds to this manual list using the add-a-fund link above)");
			objH.push("</div>");
		}
		//MarkD 09/10/07 added showhide call to on click		
		if (ctContracts == 0 && lProductTypeId == FUND_PRODUCT_TYPE && lBasisId < 10 ) {
			shvalue = "showhide"
			objH.push("<div style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; overflow: hidden; width: " + (lContractNameWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: " + lCompanyNameWidth + "px; top: " + 0 + "px' class='GT'>");
			objH.push("(Add funds to this list by choosing <b><a href='#' onclick='SwitchTab(2);Showhide(shvalue);'>sectors</a></b>)");
			objH.push("</div>");
		}

		for (iContract = 0; iContract < ctContracts; iContract++) {
			strClass = ((iContract % 2) == 1) ? "CRowEven" : "CRowOdd";

			// Company name
			objH.push("<div style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; overflow: hidden; width: " + (lCompanyNameWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: 0px; top: " + lHeightSoFar + "px' class='" + strClass + "'>");
			if (bProviderFactsheets || !bHideDeadLinks) objH.push("<a title='" + Dequote(arrContracts[iContract].CompanyName) + "' href='Company.asp?id=" + arrContracts[iContract].CompanyId + "&searchid=" + strSearchId + "'>");
			objH.push(arrContracts[iContract].CompanyName);
			if (bProviderFactsheets || !bHideDeadLinks) objH.push("</a>");
			objH.push("</div>");

        //MarkD 04/2008 wednesday
			// Contract name
			objH.push("<div style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; overflow: hidden; width: " + (lContractNameWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: " + lCompanyNameWidth + "px; top: " + lHeightSoFar + "px' class='" + strClass + "'>");
			if (lProductTypeId == FUND_PRODUCT_TYPE && lBasisId == MANUAL_FUND_LIST_PRODUCT_BASIS) {
				objH.push("<a href='#' onclick='RemoveFundFromManualList(\42" + arrContracts[iContract].ContractId + "\42)' title='Remove this fund from the list'><img src='images/greycross.gif' class='vs'/></a> ");
			}
			    //MarkD 04/2008 need to force a sectortype choice
               var cntid = (arrContracts[iContract].ContractId);
               if (document.getElementById("lnkContractFunds")) {
               objH.push("<a title='" + Dequote(arrContracts[iContract].ContractName + "\r\n" + strRightClickTooltip) + "' href='javascript:CheckForSectorChoice2(\42" + cntid + "\42 , \42" + strSearchId + "\42)'  oncontextmenu='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)' oncontextmenu='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)' onmousedown='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)'>");
			   } else{
			   objH.push("<a title='" + Dequote(arrContracts[iContract].ContractName + "\r\n" + strRightClickTooltip) + "' href='Contract.asp?id=" + arrContracts[iContract].ContractId + "&searchid=" + strSearchId + "' oncontextmenu='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)' oncontextmenu='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)' onmousedown='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)'>");
			   }
			//objH.push("<a title='" + Dequote(arrContracts[iContract].ContractName + "\r\n" + strRightClickTooltip) + "' href = '#' onclick = 'OpenContractFactSheet(\42" + arrContracts[iContract].ContractId + "\42,\42" + strSearchId + "\42)' oncontextmenu='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)' oncontextmenu='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)' onmousedown='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)'>");
			objH.push(arrContracts[iContract].ContractName);
			objH.push("</a>");
			objH.push("</div>");

			// Basis name
			if (lBasisId == 0) {
				objH.push("<div style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; overflow: hidden; width: " + (lContractBasisNameWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: " + (lCompanyNameWidth + lContractNameWidth) + "px; top: " + lHeightSoFar + "px' class='" + strClass + "' title='" + arrContracts[iContract].BasisName + "'>");
				objH.push(arrContracts[iContract].BasisName);
				objH.push("</div>");
			}

			lHeightSoFar += lRowHeight;
		}		

		objH.push("</div></div>");


	// CONTAINER
	    //Qaisar 19/11/2008 Defect 1662
        lScrollableColumnTotalWidth = parseInt(lScrollableColumnTotalWidth) + 1;
                
		objH.push("<div onscroll='ScrollBodyBlock(this, event)' id='BodyBlockContainer' class='ScrollOnScreen' style='height: " + lInitial + "px; width: " + lInitial + "px; position: absolute; top: 0px; left: " + lFixedColumnWidth + "px'>");
		objH.push("<div id='BodyBlock' style='height: " + lTotalRowHeight + "px; width: " + lScrollableColumnTotalWidth + "px; overflow: hidden; '>");


		objH.push("<div class='GT' style='padding: 5px'>...</div>");
		objH.push("</div></div>");
		objH.push("</div></div>");


		// End of overall container	
		var strX = objH.join("");
		document.getElementById("ContractList").innerHTML = strX;	

		DisplayContractCount();
		Page_BodyResize();

		tmrRenderingStage2 = setInterval("DisplayContractRenderingStage2_Normal()", 10);
	}
	catch (err) {
		bInRenderingFlag = false;
	}
}



function DisplayContractList_Flipped(strData) {
	try {
		clearInterval(tmrRenderingStage1);
		clearInterval(tmrRenderingStage2);

		// See if we have scroll values to preserve
		lResetScrollLeft = 0;
		lResetScrollTop = 0;
		if (document.getElementById("BodyBlockContainer")) {
			lResetScrollLeft = document.getElementById("BodyBlockContainer").scrollLeft;
			lResetScrollTop = document.getElementById("BodyBlockContainer").scrollTop;
		}


		var lScrollableColumnTotalWidth	= 0;
		lRowHeight = renderRowHeight;


		var lFixedColumnWidth = lCompanyNameWidth + lContractNameWidth;
		var lTotalRowHeight = ctFields * lRowHeight;
		lScrollableColumnTotalWidth = ctContracts * renderFlippedColumnWidth;

		var lHeightSoFar = 0, lWidthSoFar = 0;

		var strHeaderClass = "", strClass = "";

		var objH = new Array();	

		var lInitial = 199;

		lFixedColumnWidth = renderFlippedRowHeader;
		lCompanyNameWidth = renderFlippedRowHeader;
		lContractNameWidth = 0;
		lHeaderHeight = renderFlippedHeaderHeight;

		// Render!
		objH.push("<div class='BorderOnScreenOnly'>");
		objH.push("<div style='position: relative'>");

		// Hidden info fields
		objH.push("<input type='hidden' id='ctContracts' value='" + ctContracts + "'/>");
		objH.push("<input type='hidden' id='ctExcluded' value='" + ctExcluded + "'/>");
		objH.push("<input type='hidden' id='ctFields' value='" + ctFields + "'/>");
		objH.push("<input type='hidden' id='useRowHeight' value='" + lRowHeight + "'/>");
		objH.push("<input type='hidden' id='useScrollableWidth' value='" + lScrollableColumnTotalWidth + "'/>");
		objH.push("<input type='hidden' id='useScrollableHeight' value='" + lTotalRowHeight + "'/>");
		objH.push("<input type='hidden' id='useHeaderHeight' value='" + renderFlippedHeaderHeight + "'/>");
		objH.push("<input type='hidden' id='useFixedColumnWidth' value='" + lFixedColumnWidth + "'/>");


		// Container for field name
		objH.push("<div style='position: relative'>");

			strHeaderClass = "FlippedHeader";
			objH.push("<div style='width: " + (lCompanyNameWidth - 2) + "px; height: " + (lHeaderHeight - 2) + "px; overflow: hidden;' class='" + strHeaderClass + "'>");
			objH.push("<table border='0' cellpadding='3' cellspacing='0' width='100%' height='100%'><tr><td style='border-bottom: solid 1px #E0E0E0'>");
			objH.push("Field/contract");
			objH.push("</tr></td></table>");
			objH.push("</div>");


		// End of container for field name
		objH.push("</div>");

		// Container for scrollable header rows
		objH.push("<div id='HeaderRowContainer' class='HideOverflowOnScreen' style='border-bottom: solid 1px #808080; background-color: #F7F7F7; position: absolute; top: 0px; left: " + lFixedColumnWidth + "px; height: " + (lHeaderHeight - 3) + "px; width: " + lInitial + "px'>");
		objH.push("<div style='position: relative; width: " + lScrollableColumnTotalWidth + "px; height: " + lHeaderHeight + "px; overflow: hidden;'>");

		// Header column for each contract
		lWidthSoFar = 0;
		for (iContract = 0; iContract < ctContracts; iContract++) {
			strHeaderClass = "CRowHeader";

			var strTooltip = arrContracts[iContract].CompanyName + ": " + arrContracts[iContract].ContractName + "\r\n\r\n" + strRightClickTooltip;


			var lThisColumnWidth = renderFlippedColumnWidth;
			var strAlign = "text-align: right";
			objH.push("<div style='position: absolute; " + strAlign + "; top: 0px; left: " + lWidthSoFar + "px; height: " + (lHeaderHeight - 2) + "px; width: " + (lThisColumnWidth - 2) + "px; overflow: hidden' class='CRowHeader'>");
			objH.push("<table border='0' cellpadding='3' cellspacing='0' width='100%' height='100%'><tr><td valign='top' title=\42" + strTooltip + "\42>");



			if (bProviderFactsheets || !bHideDeadLinks) objH.push("<a title='" + Dequote(arrContracts[iContract].CompanyName) + "' href='Company.asp?id=" + arrContracts[iContract].CompanyId + "&searchid=" + strSearchId + "'>");
			objH.push(arrContracts[iContract].CompanyName);
			if (bProviderFactsheets || !bHideDeadLinks) objH.push("</a>");
			    //MarkD 04/2008
               //var cntid = (arrContracts[iContract].ContractId)
                
			objH.push("</td></tr><tr><td valign='top' title=\42" + strTooltip + "\42>");
			objH.push("<a title='" + Dequote(arrContracts[iContract].ContractName + "\r\n" + strRightClickTooltip) + "' href='Contract.asp?id=" + arrContracts[iContract].ContractId + "&searchid=" + strSearchId + "' onmousedown='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)'>");
			//objH.push("<a title='" + Dequote(arrContracts[iContract].ContractName + "\r\n" + strRightClickTooltip) + "' href='#' onclick='CheckForSectorChoice2('" + ContractId + "' , '" + strSearchId + "')' onmousedown='return ContractContextMenu(\42" + arrContracts[iContract].ContractId + "\42, this, event)'>");
			objH.push(arrContracts[iContract].ContractName);
			objH.push("</a>");

			objH.push("</td></tr></table>");

			objH.push("</div>");

			lWidthSoFar += lThisColumnWidth;
		}	

		// End of containers for scrollable header rows
		objH.push("</div></div>");







		objH.push("</div>");
		objH.push("<div style='position: relative'>");



	// FIELD NAME CONTAINER
		objH.push("<div id='ContractNameContainer' class='HideOverflowOnScreen' style='position: relative; width: " + (lFixedColumnWidth - 1) + "px; height: " + lInitial + "px'>");
		objH.push("<div style='width: " + lFixedColumnWidth + "px; height: " + lTotalRowHeight + "px; overflow: hidden'>");
		lHeightSoFar = 0;

		if (lBasisId == 0) {
			var lThisColumnWidth = lCompanyNameWidth;
			strClass = "CRowEven";
			objH.push("<div title=\42" + strTooltip + "\42 style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; overflow: hidden; width: " + (lThisColumnWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: 0px; top: " + lHeightSoFar + "px' class='" + strClass + "'>");
			objH.push("Product basis");
			objH.push("</div>");

			lHeightSoFar += lRowHeight;
		}

		for (iField = 0; iField < ctFields; iField++) {
			strClass = ((iContract % 2) == 1) ? "CRowEven" : "CRowOdd";

			var lThisColumnWidth = lCompanyNameWidth;

			var strTooltip = arrFields[iField].FieldName;
			if (arrFields[iField].HeaderType == 3) strTooltip = arrFields[iField].ParentFieldName + ": " + strTooltip;

			// Field name
			objH.push("<div title=\42" + strTooltip + "\42 style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; overflow: hidden; width: " + (lThisColumnWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: 0px; top: " + lHeightSoFar + "px' class='" + strClass + "'>");
			if (arrFields[iField].HeaderType == 3) objH.push("<em>");
			if (arrFields[iField].HeaderType == 3) objH.push(arrFields[iField].ParentFieldName + ": ");
			objH.push(arrFields[iField].FieldName);
			if (arrFields[iField].HeaderType == 3) objH.push("</em>");
			objH.push("</div>");


			lHeightSoFar += lRowHeight;
		}		

		objH.push("</div></div>");


	// CONTAINER


		objH.push("<div onscroll='ScrollBodyBlock(this, event)' id='BodyBlockContainer' class='ScrollOnScreen' style='height: " + lInitial + "px; width: " + lInitial + "px; position: absolute; top: 0px; left: " + lFixedColumnWidth + "px'>");
		objH.push("<div id='BodyBlock' style='height: " + lTotalRowHeight + "px; width: " + lScrollableColumnTotalWidth + "px; overflow: hidden; '>");

		lHeightSoFar = 0;

		if (lBasisId == 0) {
			strClass = "CRowEven";
			lWidthSoFar = 0;
			for (iContract = 0; iContract < ctContracts; iContract++) {
				lThisColumnWidth = renderFlippedColumnWidth;

				var strAlign = "text-align: right";
				var strContents = arrContracts[iContract].BasisName;

				objH.push("<div class='" + strClass + "' style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; background-color: " + strBack + "; overflow: hidden; " + strAlign + "; width: " + (lThisColumnWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: " + lWidthSoFar + "px; top: " + lHeightSoFar + "px' title='" + strContents + "'>");
				objH.push(strContents);
				objH.push("</div>");
				lWidthSoFar += lThisColumnWidth;
			}

			lHeightSoFar += lRowHeight;
		}



		objH.push("<div class='GT' style='padding: 5px'>...</div>");
		objH.push("</div></div></div></div>");



		// End of overall container	

		document.getElementById("ContractList").innerHTML = objH.join('');	

		DisplayContractCount();
		Page_BodyResize();

		if (lResetScrollTop || lResetScrollLeft) {
			document.getElementById("BodyBlockContainer").scrollLeft = lResetScrollLeft;
			document.getElementById("BodyBlockContainer").scrollTop = lResetScrollTop;
			ScrollBodyBlock();		
		}

		tmrRenderingStage2 = setInterval("DisplayContractRenderingStage2_Flipped()", 10);
	}
	catch (err) {
		bInRenderingFlag = false;
	}
}

function DisplayContractRenderingStage2_Normal() {
	try {
		clearInterval(tmrRenderingStage1);
		clearInterval(tmrRenderingStage2);

		var objFieldBlock = new Array();
		strDataBodyHtml = "";

		var lWidthSoFar = 0, lHeightSoFar = 0;

		lHeightSoFar = 0;
		for (iContract = 0; iContract < ctContracts; iContract++) {
			strClass = ((iContract % 2) == 1) ? "CRowEven" : "CRowOdd";

			lWidthSoFar = 0;
			for (iField = 0; iField < ctFields; iField++) {
				var lThisColumnWidth = arrFields[iField].RenderWidth;

				var strAlign = "";
				if (arrFields[iField].FieldType != 1 && arrFields[iField].FieldType != 1003 && arrFields[iField].FieldType != 5 && arrFields[iField].FieldType != 6 && arrFields[iField].FieldType != 5000004) strAlign = "text-align: right";

				var x = RenderFieldContents(arrContracts, arrFields, iContract, iField);
				var strContents = x.FieldContents;
				var strBack = x.BackgroundColour;

				objFieldBlock.push("<div class='" + strClass + "' style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; background-color: " + strBack + "; overflow: hidden; " + strAlign + "; width: " + (lThisColumnWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: " + lWidthSoFar + "px; top: " + lHeightSoFar + "px'>");
				objFieldBlock.push(strContents);
				objFieldBlock.push("</div>");

				lWidthSoFar += lThisColumnWidth;
			}

			lHeightSoFar += lRowHeight;
		}
		strDataBodyHtml = objFieldBlock.join("");


		document.getElementById("BodyBlock").innerHTML = strDataBodyHtml;
		strDataBodyHtml = "";

		if (lResetScrollTop || lResetScrollLeft) {
			document.getElementById("BodyBlockContainer").scrollLeft = lResetScrollLeft;
			document.getElementById("BodyBlockContainer").scrollTop = lResetScrollTop;
			ScrollBodyBlock();		
		}
		bInRenderingFlag = false;
	}
	catch (err) {
		bInRenderingFlag = false;
	}
}

function DisplayContractRenderingStage2_Flipped() {
	try {
		clearInterval(tmrRenderingStage1);
		clearInterval(tmrRenderingStage2);

		var lWidthSoFar = 0, lHeightSoFar = 0;

		var objFieldBlock = new Array();

		for (iField = 0; iField < ctFields; iField++) {
			strClass = ((iContract % 2) == 1) ? "CRowEven" : "CRowOdd";

			lWidthSoFar = 0;
			for (iContract = 0; iContract < ctContracts; iContract++) {
				lThisColumnWidth = renderFlippedColumnWidth;

				var strAlign = "text-align: right";
				var x = RenderFieldContents(arrContracts, arrFields, iContract, iField);
				var strContents = x.FieldContents;
				var strBack = x.BackgroundColour;

				objFieldBlock.push("<div class='" + strClass + "' style='white-space: nowrap; padding: 2px; border-right: solid 1px #E0E0E0; background-color: " + strBack + "; overflow: hidden; " + strAlign + "; width: " + (lThisColumnWidth - 5) + "px; height: " + (lRowHeight - 5) + "px; position: absolute; left: " + lWidthSoFar + "px; top: " + lHeightSoFar + "px'>");
				objFieldBlock.push(strContents);
				objFieldBlock.push("</div>");
				lWidthSoFar += lThisColumnWidth;
			}

			lHeightSoFar += lRowHeight;
		}
		strDataBodyHtml = objFieldBlock.join("");

		document.getElementById("BodyBlock").innerHTML = strDataBodyHtml;
		strDataBodyHtml = "";

		if (lResetScrollTop || lResetScrollLeft) {
			document.getElementById("BodyBlockContainer").scrollLeft = lResetScrollLeft;
			document.getElementById("BodyBlockContainer").scrollTop = lResetScrollTop;
			ScrollBodyBlock();		
		}
		bInRenderingFlag = false;
	}
	catch (err) {
		bInRenderingFlag = false;
	}
}

function RenderFieldContents(arrContracts, arrFields, iContract, iField) {
	var strFieldVal = arrContracts[iContract].DataArray[iField + 5];
	var strAddStyle = "";
	var strAnchor = "";
	var strAnchorTitle = "";
	var strBackClr = "";
	var strContractId = arrContracts[iContract].ContractId;
    var strRightClick= "";

	if (strFieldVal == "#NULL#") {
		strFieldVal = "";
		strBackClr = "#C0C0C0";
	} else {
	    //alert(arrFields[iField].FieldType);
		switch (arrFields[iField].FieldType) {
		    case 13:
  				strAnchor = "NumericFilterMenu(" + arrFields[iField].FieldId + ", this, event," + arrFields[iField].FieldType + ", \42" + arrContracts[iContract].ContractId + "\42)";
  		//		alert(strFieldVal);
				if (Xval(strFieldVal) > 0) {
					strBackClr = "#E0FFE0";
				} else if (Xval(strFieldVal) < 0) {
					strBackClr = "#FFE0E0";
				}
				//strFieldVal = BespokeRatingToText(strFieldVal);
				break;
		    case 6:
  				strAnchor = "NumericFilterMenu(" + arrFields[iField].FieldId + ", this, event," + arrFields[iField].FieldType + ", \42" + arrContracts[iContract].ContractId + "\42)";
  		//		alert(strFieldVal);
				if (Xval(strFieldVal) > 0) {
					strBackClr = "#E0FFE0";
				} else if (Xval(strFieldVal) < 0) {
					strBackClr = "#FFE0E0";
				}
				//strFieldVal = BespokeRatingToText(strFieldVal);
				break;

			case 2:
			case 8:
			case 202:
			case 1001:
				// Feature field, sector, ethical feature, or custom boolean field
				if (!strFieldVal) {
					// Null feature field
					strBackClr = "#C0C0C0";
				} else if (strFieldVal == "Yes") {
					strBackClr = "#E0FFE0";
					strAnchor = "FeatureContextFilter(" + arrFields[iField].FieldId + ", 1, \42" + strContractId + "\42, this)";
				} else {
					strBackClr = "#FFE0E0";
					strAnchor = "FeatureContextFilter(" + arrFields[iField].FieldId + ", 0, \42" + strContractId + "\42, this)";
				}
				
				// Handling of special offers, which have an unusual anchor...
				if (arrFields[iField].FieldId == 5000009) {
					if (strFieldVal == "Yes") {
						strAnchor = "ShowSpecialOffer(\42" + arrContracts[iContract].ContractId + "\42)";
						strBackClr = "#FFFFE0";
					} else {
						strAnchor = "";
						strBackClr = "";
					}
				}
				break;

			case 7:
				// Yes/no/optional
				if (!strFieldVal) {
					// Null feature field
					strBackClr = "#C0C0C0";
				} else if (strFieldVal == "Yes") {
					strBackClr = "#E0FFE0";
					strAnchor = "YNOFilter(" + arrFields[iField].FieldId + ",2)";
				} else if (strFieldVal == "No") {
					strBackClr = "#FFE0E0";
					strAnchor = "YNOFilter(" + arrFields[iField].FieldId + ",0)";
				} else {
					strBackClr = "#E0E0FF";
					strAnchor = "YNOFilter(" + arrFields[iField].FieldId + ",1)";
				}
				break;

			case 100:
				// Sector field - do filtering on Yes only
				if (!strFieldVal) {
					// Null feature field
					strBackClr = "#C0C0C0";
				} else if (strFieldVal == "Yes") {
					strBackClr = "#E0FFE0";
					strAnchor = "FeatureContextFilter(" + arrFields[iField].FieldId + ", 1, \42" + strContractId + "\42, this)";
				} else {
					strBackClr = "#FFE0E0";
				}
				break;

			case 5:	
			case 1003:
			case 5000004:
				// Long text, which may have been trimmed
				if (strFieldVal.indexOf("...") != -1 || strFieldVal.length > 30) {
					strAnchor = "ShowFieldContents(" + arrFields[iField].FieldId + ", \42" + strContractId + "\42)";
					strAnchorTitle = "Show field contents";
				}
				break;

			case 3:
			case 4:
			case 50:
			case 101:
			case 102:
			case 103:
			case 200:
			case 201:
			case 1002:
				// Numbers, policy conditions, past performance, and financial strength
				strAnchor = "NumericFilterMenu(" + arrFields[iField].FieldId + ", this, event," + arrFields[iField].FieldType + ", \42" + arrContracts[iContract].ContractId + "\42)";
				break;
			
			case 1004:
				strAnchor = "NumericFilterMenu(" + arrFields[iField].FieldId + ", this, event," + arrFields[iField].FieldType + ", \42" + arrContracts[iContract].ContractId + "\42)";
				if (Xval(strFieldVal) > 0) {
					strBackClr = "#E0FFE0";
				} else if (Xval(strFieldVal) < 0) {
					strBackClr = "#FFE0E0";
				}
				strFieldVal = BespokeRatingToText(strFieldVal);
				break;
			case 5100000:
			case 5100001:
			case 5100004:
			    if (strFieldVal) {
					strAnchor = "QuotePopUp(\42" + strContractId + "\42, event)";
					strAnchorTitle = "Show quote details";					    
					strRightClick = "QuoteFieldMenu(" + arrFields[iField].FieldId + ", this, event," + arrFields[iField].FieldType + ", \42" + arrContracts[iContract].ContractId + "\42)";
					strAnchor = strRightClick;
					
			    }
			    
	    
			    break;
			case 5100003:
			    if (strFieldVal == 1) {
			        strFieldVal = strSelectFieldHTML;
				    strAnchor = "SetSelectedContract(\42" + strContractId + "\42)";
				    strAnchorTitle = "Select this contract and get illustrative quote";		
			    } else {
			        strFieldVal = "";
			    }		    
			    break;
		}
	}

	if (strFieldVal == "Yes" && FindFieldDef(arrFields[iField].FieldId).DetailFieldId) {
		strFieldVal = "<b>" + strFieldVal + "</b>";
		strAnchorTitle = "Further detail is available on this field. Click on the value and choose Show Contents.";
	}

	if (!strFieldVal) strFieldVal = "&nbsp;";

	var strHtml = "";
	if (strAnchor) {
		strHtml = "<a " + (strAnchorTitle ? " title='" + strAnchorTitle + "'": "") + " href='#' class='FL' onclick='return KE(event);' onmousedown='" + strAnchor + ";return KE(event);' >" + strFieldVal + "</a>";
	} else {
		strHtml = strFieldVal;
	}

	this.FieldContents = strHtml;
	this.BackgroundColour = strBackClr;
	return this;
}

function ScrollBodyBlock(f, e) {
	var objC = document.getElementById("BodyBlockContainer");
	document.getElementById("ContractNameContainer").scrollTop = objC.scrollTop;
	document.getElementById("HeaderRowContainer").scrollLeft = objC.scrollLeft;
}



var lScrollBarHeightWidth = 0;

var tLastResize = 0;
function Page_BodyResize(e) {
	if (!bUseBodyEventHandling) return;

	var d = new Date;
	//if (d.valueOf() - tLastResize < 10) return;
	tLastResize = d.valueOf();

	document.body.style.overflow = "hidden";

	try {
		// Get the width of the page
		var lPageWidth = document.body.clientWidth;
		var lPageHeight = document.body.clientHeight;

		// Get the width of the displayed tabs
		var lTabWidth;
		var lFieldWidth;
		if (bFieldsVisible) {
			lTabWidth = document.getElementById("TabContainer").clientWidth;

			// Calculate the width of the field box, but capped at 350px on wide screens
			lFieldWidth = lPageWidth * 0.3;
			if (lFieldWidth > 350) lFieldWidth = 350;
			
			// Don't allow the fields to be narrower than the tabs on top of them
			if (lFieldWidth < lTabWidth) lFieldWidth = lTabWidth;
		} else {
			lTabWidth = 0;
			lFieldWidth = 0;
		}
		

		// Give the contract list the rest of the space, less some margins
		var lContractWidth = lPageWidth - lFieldWidth - (bFieldsVisible ? 50 :28);
		document.getElementById("ContractCountBar").style.width = lContractWidth + "px";


		var objElemField = document.getElementById("FieldContainer");
		document.getElementById("FieldListContainer").style.width = lFieldWidth + "px";
		document.getElementById("FieldFooter").style.width = lFieldWidth + "px";

		var lAdjust = 10;
		var hList = document.getElementById("FieldListContainer").clientWidth;
		hList = hList - lAdjust;
		if (bFieldsVisible) {
			document.getElementById("ConditionFields").style.width = hList + "px";
			document.getElementById("RankingFields").style.width = hList + "px";
			document.getElementById("PPFields").style.width = hList + "px";
			document.getElementById("SectorFields").style.width = hList + "px";
			document.getElementById("NoteContainer").style.width = hList + "px";
		}
		
		var hField = getXY(document.getElementById("FieldListContainer")).top;
		hField += document.getElementById("FieldFooter").clientHeight;
		document.getElementById("FieldListContainer").style.height = (document.documentElement.clientHeight - hField - 30) + "px";


		// Check that the contract grid has been rendered
		if (document.getElementById("HeaderRowContainer")) {
			var lFixedColumnWidth = Zval(document.getElementById("useFixedColumnWidth").value);

			// Adjust the page height and width to take into account how much space there
			// is for the grid
			var lHeaderHeight = Zval(document.getElementById("useHeaderHeight").value);
			//JohnC Defect 1-1451 adjust the page height to include a footer for results pages links
			lPageHeight = lPageHeight - getXY(document.getElementById("ContractCountBar")).top - 54 - lHeaderHeight;
			
			if(lProductTypeId == FUND_PRODUCT_TYPE) {
			    if (document.getElementById("ContractPageContainer")) {
			        lPageHeight = lPageHeight - document.getElementById("ContractPageContainer").clientHeight;
			    }
			}
			var lScrollableContractWidth = lContractWidth - (lFixedColumnWidth);

			// Constant required to make sure that scroll bars get added to the
			// outside of the scrolling area
			if (lScrollBarHeightWidth <= 0) {
				lScrollBarHeightWidth = document.getElementById("ScrollbarTestArea").offsetWidth - document.getElementById("ScrollbarTestArea").scrollWidth;
				if (lScrollBarHeightWidth == 100) lScrollBarHeightWidth = 0;
			}

			var lScrollableWidth = Zval(document.getElementById("useScrollableWidth").value);
			var lScrollableHeight = Zval(document.getElementById("useScrollableHeight").value);

			var lAddToHeight = 0;
			var lAddToWidth = 0;

			if (lScrollableWidth > lScrollableContractWidth) lAddToHeight = (lScrollBarHeightWidth > 0 ? lScrollBarHeightWidth : renderDefaultScrollbarHeightWidth);
			if (lScrollableHeight > lPageHeight) lAddToWidth = (lScrollBarHeightWidth > 0 ? lScrollBarHeightWidth : renderDefaultScrollbarHeightWidth);
			if (lScrollableWidth + lAddToWidth > lScrollableContractWidth) lAddToHeight = (lScrollBarHeightWidth > 0 ? lScrollBarHeightWidth : renderDefaultScrollbarHeightWidth);
			if (lScrollableHeight + lAddToHeight > lPageHeight) lAddToWidth = (lScrollBarHeightWidth > 0 ? lScrollBarHeightWidth : renderDefaultScrollbarHeightWidth);
			if (lScrollableWidth + lAddToWidth > lScrollableContractWidth) lAddToHeight = (lScrollBarHeightWidth > 0 ? lScrollBarHeightWidth : renderDefaultScrollbarHeightWidth);

			document.getElementById("ContractList").style.width = (lContractWidth - lAddToWidth + 2) + "px";
			document.getElementById("ContractCountBar").style.width = (lContractWidth - lAddToWidth - 6) + "px";

			document.getElementById("HeaderRowContainer").style.width = (lScrollableContractWidth - lAddToWidth) + "px";
			document.getElementById("BodyBlockContainer").style.width = (lScrollableContractWidth ) + "px";

			document.getElementById("ContractNameContainer").style.height = (lPageHeight - lAddToHeight) + "px";
			document.getElementById("BodyBlockContainer").style.height = (lPageHeight) + "px";
			
			document.getElementById("BodyBlockContainer").style.overflowY =  (lScrollableHeight + lAddToHeight > lPageHeight) ? "scroll" : "auto";
			document.getElementById("BodyBlockContainer").style.overflowX =  (lScrollableWidth + lAddToWidth > lScrollableContractWidth) ? "scroll" : "auto";


		}
	}
	catch (e) {}
}


function Dequote(x) {
	return x.replace(/[']/g,'');
}


function ShowHideFields() {
	HideMenus(true);
	bFieldsVisible = !bFieldsVisible;
	document.getElementById("FieldHeader").style.display = (bFieldsVisible ? "" : "none");
	document.getElementById("FieldContainer").style.display = (bFieldsVisible ? "" : "none");
	document.getElementById("lnkShowHideFields").innerHTML = (bFieldsVisible ? "Hide field list" : "Show field list");

	// IE requires this to be done twice in order to get the positioning right.
	Page_BodyResize();
	Page_BodyResize();
}

function FlipGrid() {
	if (!ctFields) {
		alert("You have not selected any fields to display in the grid. The flipped orientation shows contracts along the top and fields down the side - nothing to display until you select some fields.");
		return;
	}

	HideMenus(true);
	document.getElementById("BodyBlockContainer").scrollTop = 0;
	document.getElementById("BodyBlockContainer").scrollLeft = 0;
	bFlipGrid = !bFlipGrid;
	DisplayContractList();

	var objFieldXML = CreateXMLObject();
	objFieldXML.open("GET", RefreshableUrl("_SetGridOrientation.asp?searchid=" + strSearchId + "&mode=" + (bFlipGrid ? 1 : 0)), true);
	objFieldXML.onreadystatechange = newReadyStateHandler(objFieldXML, IgnoreXmlResult);
	objFieldXML.send(null);
}
function IgnoreXmlResult(objXML) {

}

function Page_KeyDown(k, e) {
	if (!bUseBodyEventHandling) return;
	if (k == 70 && e.ctrlKey && e.shiftKey) {
		ShowHideFields();	
		return false;
	}
}

function ShowGridOptionMenu() {
	HideMenus(true);

	var objMenu = document.getElementById("mnuGridOptions");
	var objParent = document.getElementById("lnkGridOptions");

	// Count the number of fields
	var lFields = Zval(document.getElementById("ctFields").value);
	document.getElementById("lnkRemoveColumns").style.display = (lFields ? "" : "none");
	document.getElementById("lnkOrderColumns").style.display = ((lFields > 1) ? "" : "none");

	var l = getXY(objParent).left + objParent.offsetWidth - 120;
	var t = getXY(objParent).top + 15;


	objMenu.style.top = t + "px";
	objMenu.style.left = l + "px";
	objMenu.style.display = "";
	bSuppressHideMenu = new Date();
	document.onclick = HideMenus;
}

function ShowHideSubFields(FieldId) {
	var objSubFields = document.getElementById("subfields" + FieldId);
	if (objSubFields) {
		if (objSubFields.style.display == "none") {
			objSubFields.style.display = "";
			objSubFields.scrollIntoView();
		} else {
			objSubFields.style.display = "none";
		}
		return;
	}		
	return;
}

function FieldChooser() {
	HideMenus(true);
	
	var strUrl = "pFieldChooser.asp?searchid=" + strSearchId + "&sectortype=" + lSectorType;
	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: 450px; DialogHeight: 500px");
		if (strRet) {
			DoFieldChooser(strRet);
		}
	} else {
		var h = 500;
		var w = 450;
		l = (screen.availWidth - w) / 2;
		t = (screen.availHeight - h) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

// As ever, the use of the timer is to avoid problems when calling from an external popup window
// which gets closed in the course of the call. See the notes above on Delay_DoExcludeContract
var strPassFieldList;
var tmrPassFieldList;
function DoFieldChooser(FieldList) {
	strPassFieldList = FieldList;
	tmrPassFieldList = setInterval("DoFieldChooser2()", 1);
}

function DoFieldChooser2(FieldList) {
	clearInterval(tmrPassFieldList);
	if (!FieldList) FieldList = strPassFieldList;
	if (FieldList == "cancel") return;
	if (FieldList == "none") FieldList = "";

	SetLoadingCaption();
	var strUrl = "_SetSearchDataFieldList.asp?searchid=" + strSearchId;
	var objXML = CreateXMLObject();
	objXML.open("POST", RefreshableUrl(strUrl), true);
	objXML.setRequestHeader("content-type", "application/x-www-form-urlencoded");
	objXML.onreadystatechange = newReadyStateHandler(objXML, SetDataField2);
	objXML.send("fieldid=" + FieldList);
}

function RemoveAllColumns() {
	HideMenus(true);
	if (!confirm("Are you sure that you want to remove all columns of data from the grid")) return;
	DoFieldChooser("none");
}


// As above, some nasty workarounds for problems when
// functions are called from pop-up browser windows

var passPresetMode, passPresetLockMode, tmrDelaySetPreset;

function ChangePresetMode() {
	var strUrl = "pAskPresetMode.asp?presetid=" + strSearchId;

	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: 475px; DialogHeight: 350px");
		if (strRet) {
			var arrRet = strRet.split("|");
			if (arrRet.length == 2) {
				passPresetMode = arrRet[0];
				passPresetLockMode = arrRet[1];
				DoSetPresetMode();
			}
		}
	} else {
		var h = 300;
		var w = 450;
		l = (screen.availWidth - w) / 2;
		t = (screen.availHeight - h) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}


function SetPresetMode(PresetMode, PresetLockMode) {
	passPresetMode = PresetMode;
	passPresetLockMode = PresetLockMode;
	tmrDelaySetPreset = setInterval("DoSetPresetMode()", 1);
}

function DoSetPresetMode() {
	clearInterval(tmrDelaySetPreset);

	var lPresetMode = parseInt(passPresetMode);
	var lPresetLockMode = parseInt(passPresetLockMode);
	if (lPresetMode != 2) lPresetMode = 1;

	var strUrl = "_ChangePresetMode.asp?searchid=" + strSearchId + "&PresetMode=" + lPresetMode + "&PresetLockMode=" + lPresetLockMode;

	CreateStatusWindow("Changing presets...", strPathContext);

	var objXML = CreateXMLObject();
	objXML.open("POST", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnSetPresetMode);
	objXML.send("");
}

function OnSetPresetMode(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();

				switch (objXML.status) {
					case 200:
						Goto("FilterContracts.asp?searchid=" + strSearchId);
						break;

					case 299:
						alert(objXML.responseText);
						break;

					default:
						alert("An error occurred while trying to change the preset mode. Please try again.");
						break;
				}						
				objXML = null;
				break;							
		}
	}
}

function ShowSpecialOffer(ContractId) {
	var strUrl = "pContractSpecialOffer.asp?contractid=" + ContractId;

	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: 500px; DialogHeight: 400px");
		if (strRet) {
			OpenFundFactsheet(strRet);
		}
	} else {
		var h = 400;
		var w = 500;
		l = (screen.availWidth - w) / 2;
		t = (screen.availHeight - h) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function GridFieldMenu(e, FieldId, parent) {
	HideMenus(true);

	// Check that we're doing the right mouse button. If not, quit
	var b = GetMouseButton(e)
	if (b != 2) return true;

	var objMenu = document.getElementById("mnuGridFieldHeader");

	document.getElementById("lnkRemoveHeader").href = "javascript:RemoveField(" + FieldId + ")";
	document.getElementById("lnkSortAsc").href = "javascript:SetSortField(" + FieldId + ", null, 1)";
	document.getElementById("lnkSortDesc").href = "javascript:SetSortField(" + FieldId + ", null, 2)";

	// Get the position for the menu
	var t = getXY(parent).top;
	var l = getXY(parent).left;
	l -= document.getElementById("BodyBlockContainer").scrollLeft;
	
	t += 25;	
	// Check the width
	if (l + 140 > document.body.clientWidth) {
		l = document.body.clientWidth - 140;
	}

	objMenu.style.top = t + "px";
	objMenu.style.left = l + "px";
	objMenu.style.display = "";
	bSuppressHideMenu = new Date();
	document.onclick = HideMenus;

	e.returnValue = false;
	e.cancelBubble = true;
	return false;
}

function SendResearch() {
	var strUrl = "pSendResearch.asp?searchid=" + strSearchId;

	var h = 220;
	var w = 400;

	// Add in extra height if the user is allowed to do notes
	if (bAllowNotes) {
		h += 120;
	}

	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + (w + 20) + "px; DialogHeight: " + (h + 30) + "px");
		if (strRet) {
			var arrRet = strRet.split("|");
			DoSendResearch(arrRet[0], arrRet[1], arrRet[2], arrRet[3]);
		}
	} else {
		l = (screen.availWidth - w) / 2;
		t = (screen.availHeight - h) / 2;
		var objW = window.open(strUrl, RefreshableUrl(strUrl), "top=" + t + ",left=" + l + ",width=" + w + ",height=" + h + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function Delay_DoSendResearch(strUserId, bDelete, bRemoveClients, strNotes) {
	tmrDelayLoad = setInterval("DoSendResearch(\42" + strUserId + "\42, " + bDelete + "," + bRemoveClients + ", \42" + strNotes + "\42)", 10);
}

function DoSendResearch(strUserId, bDelete, bRemoveClients, strNotes) {
	clearInterval(tmrDelayLoad);

	// Build the URL
	var strUrl = "_SendResearch.asp";
	

	var strPost = "searchid=" + strSearchId;
	strPost += "&touserid=" + strUserId;
	strPost += "&deleteexisting=" + bDelete;
	strPost += "&removeclients=" + bRemoveClients;
	strPost += "&notes=" + NotePostEncode(strNotes);

	CreateStatusWindow("Sending...", strPathContext);

	var objXML = CreateXMLObject();
	objXML.open("POST", RefreshableUrl(strUrl), true);
	objXML.setRequestHeader("content-type", "application/x-www-form-urlencoded");
	objXML.onreadystatechange = newReadyStateHandler(objXML, DoSendResearch2);
	objXML.send(strPost);
}

function DoSendResearch2(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
						// The research has been sent, and this copy has not been deleted
						alert("This research has been sent.");
						break;
					
					case 280:
						// The research has been sent, and this copy has been deleted
						alert("This research has been sent and - as requested - this copy has been deleted.");
						Goto("index.asp");
						break;
					
					case 299:
						alert("Unable to send this research:\r\n\r\n" + objXML.responseText);
						break;

					default:
						alert("An error occurred while trying to send this research. Please try again.");
						break;
				}
				objXML = null;			
				break;
		}
	}
}

function NotePostEncode(value) {
	//value = value.replace(/[\x0D]/g, "%0D");
	//value = value.replace(/[\x0A]/g, "%0A");
	return escape(value);
}

function SaveNote() {
	var strNote = document.NoteForm.notetext.value;
	if (!strNote) {
		alert("You must enter some text for the note. You cannot save a blank note.");
		return;
	}
	
	var strPost = "searchid=" + strSearchId;
	strPost += "&note=" + NotePostEncode(strNote);
	
	var strUrl = "_SaveNote.asp"

	CreateStatusWindow("Saving...", strPathContext);

	var objXML = CreateXMLObject();
	objXML.open("POST", RefreshableUrl(strUrl), true);
	objXML.setRequestHeader("content-type", "application/x-www-form-urlencoded");
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnSaveNote);
	objXML.send(strPost);
}

function OnSaveNote(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
						document.getElementById("NoteContainer").style.display ='';
						var strReturnHTML = objXML.responseText;
						document.getElementById("NoteContainer").innerHTML = strReturnHTML;
						
						bHasNotes = Zval(document.getElementById("usernotecount").value);
						document.getElementById("NoteImg").src = strPathImg + (bHasNotes ? "/notes.gif" : "/nonotes.gif");
						break;
					
					case 299:
						alert("Unable to display the notes on this research:\r\n\r\n" + objXML.responseText);
						break;

					default:
						alert("An error occurred while trying to display the notes on this research. Please try again.");
						break;
				}
				objXML = null;			
				break;
		}
	}
}

function LoadNotes() {
	var strUrl = "_LoadNotes.asp?searchid=" + strSearchId;

	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnSaveNote);
	objXML.send(null);
}

function DeleteNote(NoteId) {
	CreateStatusWindow("Deleting...", strPathContext);

	var strUrl = "_DeleteNote.asp?searchid=" + strSearchId + "&noteid=" + NoteId;

	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnSaveNote);
	objXML.send(null);
}

function ShowNewNote(md) {
	document.getElementById("divNewNote").style.display = (md ? "" : "none");
	document.getElementById("divNoteList").style.display = (md ? "none" : "");
	if (md) {
		document.NoteForm.notetext.focus();
	}
}

var RequiredFundIdList = "";
var RequiredFundNameList = "";
var RequiredFundOperator = 21;
var RequiredFundPresetMode = 0;

function RenderRequiredFundBlock(strFundId, strFundName, lOperator, lPresetMode) {
	
	var objH = new Array();

	RequiredFundIdList = strFundId;
	RequiredFundNameList = strFundName;
	RequiredFundOperator = lOperator;
	RequiredFundPresetMode = lPresetMode;

	var ctNames = 0;
	if (strFundName) {
		var arrName = strFundName.split(",");
		var arrFundId = strFundId.split(",");
		if (strFundName) ctNames = arrName.length;
	}
	var iName = 0;
	
	objH.push("<div style='margin-bottom: 5px'>");
	objH.push("Contracts must include a link to ");
	objH.push("<select onchange='ChangeRequiredFundMode(this)' onclick='ChangeRequiredFundMode(this)' name='fundlinkmode'>")
	objH.push("<option value='21'>all</option>")
	objH.push("<option " + (lOperator == 20 ? "selected" : "") + " value='20'>any</option>")
	objH.push("</select>");
	objH.push(" of the following funds.");
	if (RequiredFundPresetMode == 2) {
		if (ctNames) {
			objH.push(" This list has been preset by your compliance officer and cannot be changed.");
		}
	} else {
		if (ctNames) {
			objH.push(" <a href='#' onclick='AddRequiredFund()'>Click here</a> to add another fund, or <a href='#' onclick='ClearRequiredFunds()'>clear the list</a>.");
		}
	}
	objH.push("</div>");

	if (!ctNames) {
		objH.push("<div class='GT'>(No specific funds required. <a href='#' onclick='AddRequiredFund()'>Click here</a> to add a fund");
		if (bAdHocFundLists) {
			objH.push(", or <a href='#' title='Import a list of funds from a manual fund list' onclick='ImportFundList()'>import from a manual fund list</a>");
		}
		objH.push(".)</div>");
	} else {
		for (iName = 0; iName < ctNames; iName++) {
			objH.push("<div class='PT3'>");
			if (RequiredFundPresetMode != 2) {
				objH.push("<a title='Remove this fund from the list' href='#' onclick='RemoveRequiredFund(\42" + arrFundId[iName] + "\42)'>");
			}
			objH.push(arrName[iName]);
			if (RequiredFundPresetMode != 2) {
				objH.push("</a>");
			}
			objH.push("</div>");
		}
	}
	
	return objH.join("");
}

function SubmitRequiredFundIdList() {
	var strUrl = "";
	if (!RequiredFundIdList) {
		strUrl = "_RemoveFromSearchFilter.asp?searchid=" + strSearchId + "&fieldid=5000030";
	} else {
		strUrl = "_AddToSearchFilter.asp?searchid=" + strSearchId + "&fieldid=5000030";
		strUrl += "&operator=" + (!RequiredFundOperator ? 21 : RequiredFundOperator);
		strUrl += "&value=" + RequiredFundIdList;
		if (bGotMaxRecords) strUrl += "&max=1";
		strUrl += "&ptype=" + lProductTypeId;
	}


	// Tell the user that we're reloading...
	SetLoadingCaption();

	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
	objXML.send(null);
}


function ChangeRequiredFundMode(elem) {
	var lNewOperator = GetComboNumericValue(elem);
	if (lNewOperator != RequiredFundOperator) {
		RequiredFundOperator = lNewOperator;
		if (RequiredFundIdList) {
			SubmitRequiredFundIdList();
		}
	}
}

function RemoveRequiredFund(FundId) {
	// Remove the ID from the list
	var arrId = RequiredFundIdList.split(",");
	var arrName = RequiredFundNameList.split(",");
	var ctFunds = arrId.length;

	RequiredFundIdList = "";
	RequiredFundNameList = "";

	for (var iFund = 0; iFund < ctFunds; iFund++) {
		if (arrId[iFund] != FundId) {
			RequiredFundIdList += (RequiredFundIdList != "" ? "," : "") + arrId[iFund];
			RequiredFundNameList += (RequiredFundNameList != "" ? "," : "") + arrName[iFund];
		}
	}

	SubmitRequiredFundIdList();
	document.getElementById("RequiredFundBlock").innerHTML = RenderRequiredFundBlock(RequiredFundIdList, RequiredFundNameList, RequiredFundOperator, RequiredFundPresetMode);
}


function AddFundToManualList() {
	AddFundDialog("fundlist");
}

function AddRequiredFund() {
	AddFundDialog("normal");
}

function ClearRequiredFunds() {
	if (!confirm("You can remove individual funds by clicking on their names. Are you sure you want to remove ALL the funds?")) return;
	
	RequiredFundIdList = "";
	RequiredFundNameList = "";
	SubmitRequiredFundIdList();
	document.getElementById("RequiredFundBlock").innerHTML = RenderRequiredFundBlock(RequiredFundIdList, RequiredFundNameList, RequiredFundOperator, RequiredFundPresetMode);
}

var gAddFundMode = "";
function AddFundDialog(mode) {
	// Do the dialog box for selecting a fund
	var dHeight = 400;
	var dWidth = 400;
	gAddFundMode = mode;	

	var strUrl = "pFundSearch.asp?";
	if (mode != "fundlist") strUrl += "parent=1";
	
	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + dWidth + "px; DialogHeight: " + dHeight + "px");
		if (strRet) {
			DoAddRequiredFund(strRet);
		}
	} else {
		l = (screen.availWidth - dWidth) / 2;
		t = (screen.availHeight - dHeight) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + dWidth + ",height=" + dHeight + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function Delay_DoAddRequiredFund(FundSpec) {
	tmrDelayLoad = setInterval("DoAddRequiredFund(\42" + FundSpec + "\42)",1);
}

function DoAddRequiredFund(FundSpec) {
	clearInterval(tmrDelayLoad);
	
	if (FundSpec) {
		switch (gAddFundMode) {
			case "fundlist":
				var arrList = FundSpec.split("|");
				var ctList = arrList.length;
				var strIdList = "";
				for (var iFund = 0; iFund < ctList; iFund++) {
					var arrF = arrList[iFund].split(",");
					strIdList += (strIdList ? "," : "") + arrF[0];
				}

				// Tell the user that we're reloading...
				SetLoadingCaption();

				var strUrl = "_AddFundToManualList.asp?searchid=" + strSearchId + "&fundid=" + strIdList;
				var objXML = CreateXMLObject();
				objXML.open("GET", RefreshableUrl(strUrl), true);
				objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
				objXML.send(null);
				break;
			
			default:
				var arrList = FundSpec.split("|");
				var ctList = arrList.length;
				for (var iFund = 0; iFund < ctList; iFund++) {
					var arrF = arrList[iFund].split(",");
					RequiredFundIdList += (RequiredFundIdList ? "," : "") + arrF[0];
					RequiredFundNameList += (RequiredFundNameList ? "," : "") + arrF[1];
				}

				SubmitRequiredFundIdList();
				document.getElementById("RequiredFundBlock").innerHTML = RenderRequiredFundBlock(RequiredFundIdList, RequiredFundNameList, RequiredFundOperator, RequiredFundPresetMode);
				break;
		}
	}
}

function RemoveFundFromManualList(FundId) {
	SetLoadingCaption();

	var strUrl = "_RemoveFundFromManualList.asp?searchid=" + strSearchId + "&fundid=" + FundId;
	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnFilterChange);
	objXML.send(null);
}

function startDrag(e) {
    srcObj = e.srcElement;
    var dragData = e.dataTransfer;
    dragData.setData('Text', e.srcElement.id);
    dragData.effectAllowed = 'linkMove';
    dragData.dropEffect = 'move';
}

function overDrag(e) {
    e.returnValue = false;
}

function enterDrag(e) {
    e.dataTransfer.getData('Text');
}

function endDrag(e) {
    e.dataTransfer.clearData();
}

function onDrop(e) {
    e.returnValue = false;
	try {
		// Check that the drag is from an element with the id flinkXXXX and to
		// an element with the id tdXXXXXX
		if (e.dataTransfer.getData('Text').indexOf("flink") ==0 && e.srcElement.id.indexOf("td") == 0) {
			var idFrom = Zval(e.dataTransfer.getData('Text').substr(5));
			var idTo = Zval(e.srcElement.id.substr(2));

			if (idFrom != idTo) {
				var idxFrom = -1;
				var idxTo = -1;
				for (var iField = 0; iField < ctFields; iField++) {
					if (arrFields[iField].FieldId == idFrom) {
						idxFrom = iField;
					}
					if (arrFields[iField].FieldId == idTo) {
						idxTo = iField;
					}
				}
				if (idxFrom >=0 && idxTo >= 0) {
					if (idxFrom > idxTo) {
						var objStore = arrFields[idxFrom];
						for (var iTr = idxFrom - 1; iTr >= idxTo; iTr--) {
							arrFields[iTr + 1] = arrFields[iTr];
						}
						arrFields[idxTo] = objStore;

						for (var iC = 0; iC < ctContracts; iC++) {
							var objStore = arrContracts[iC].DataArray[idxFrom + 5];
							for (var iTr = idxFrom - 1; iTr >= idxTo; iTr--) {
								arrContracts[iC].DataArray[iTr + 6] = arrContracts[iC].DataArray[iTr + 5];
							}
							arrContracts[iC].DataArray[idxTo + 5] = objStore;
						}

					} else {
						var objStore = arrFields[idxFrom];
						for (var iTr = idxFrom + 1; iTr < idxTo; iTr++) {
							arrFields[iTr - 1] = arrFields[iTr];
						}
						arrFields[idxTo - 1] = objStore;

						for (var iC = 0; iC < ctContracts; iC++) {
							var objStore = arrContracts[iC].DataArray[idxFrom + 5];
							for (var iTr = idxFrom + 1; iTr < idxTo; iTr++) {
								arrContracts[iC].DataArray[iTr + 4] = arrContracts[iC].DataArray[iTr + 5];
							}
							arrContracts[iC].DataArray[idxTo + 4] = objStore;
						}
					}

					DisplayContractList("");

					// Update the server
					var strList = "";
					for (var iField = 0; iField < ctFields; iField++) {
						if (iField) strList += ",";
						strList += arrFields[iField].FieldId;
					}

					var strUrl = "_SetSearchDataFieldList.asp?searchid=" + strSearchId;
					var objXML = CreateXMLObject();
					objXML.open("POST", RefreshableUrl(strUrl), true);
					objXML.setRequestHeader("content-type", "application/x-www-form-urlencoded");
					// Don't set up a readystatehandler to get the server's response.
					// Assume that this action worked...
					objXML.send("fieldid=" + strList);
				}
			}
		}
	}
	catch (err) {}
}


function OrderColumns() {
	HideMenus(true);
	
	if (ctFields < 2) {
		alert("There must be at least two fields in the data grid before you can change their order.");
		return;
	}
	var hDialog = 330;
	var wDialog = 450;
	var strUrl = "pFieldOrder.asp?searchid=" + strSearchId;
	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + wDialog + "px; DialogHeight: " + (hDialog + 30) + "px");
		if (strRet) {
			SetFieldOrder(strRet);
		}
	} else {
		l = (screen.availWidth - wDialog) / 2;
		t = (screen.availHeight - hDialog) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + wDialog + ",height=" + hDialog + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function Delay_SetFieldOrder(FieldList) {
	tmrDelayLoad = setInterval("SetFieldOrder(\42" + FieldList + "\42)",1);
}

function SetFieldOrder(FieldList) {
	clearInterval(tmrDelayLoad);
	SetDataField(FieldList, null, true);
}

function ImportFilter() {
	var hDialog = 350;
	var wDialog = 650;
	
	var strUrl = "pImportResearch.asp?searchid=" + strSearchId;
		strUrl += "&contracttypeid=" + strContractTypeId;  //Passes the contractypeid in the URL (could be appended onto above line)

	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + wDialog + "px; DialogHeight: " + (hDialog + 30) + "px");
		if (strRet) {
			DoImportFilter(strRet);
		}
	} else {
		l = (screen.availWidth - wDialog) / 2;
		t = (screen.availHeight - hDialog) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + wDialog + ",height=" + hDialog + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function Delay_DoImportFilter(FromSearchId) {
	tmrDelayLoad = setInterval("DoImportFilter(\42" + FromSearchId + "\42)",1);
}

// The value passed back from the pImportResearch.asp dialog is pipe-delimited into two
// parts: the search ID to import from, and the numeric flags for the import
function DoImportFilter(ImportSpec) {
	clearInterval(tmrDelayLoad);

	var arrP = ImportSpec.split("|");
	var FromSearchId = arrP[0];
	var lFlags = Zval(arrP[1]);
	
	CreateStatusWindow("Importing research...", strPathContext);

	var strUrl = "_ImportResearch.asp?fromsearchid=" + FromSearchId + "&intosearchid=" + strSearchId;
	strUrl += "&flags=" + lFlags;

	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.setRequestHeader("content-type", "application/x-www-form-urlencoded");
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnDoImportFilter);
	objXML.send(null);
}

function OnDoImportFilter(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
						Goto("LoadResearch.asp?id=" + strSearchId);
						break;
					
					case 299:
						alert("Unable to import the existing research:\r\n\r\n" + objXML.responseText);
						break;

					default:
						alert("An error occurred while trying to import the existing research. Please try again.");
						break;
				}
				objXML = null;			
				break;
		}
	}
}

function ShareResearch() {
	bIsShared = !bIsShared;
	CreateStatusWindow("Sharing research...", strPathContext);

	var strUrl = "_ShareResearch.asp?searchid=" + strSearchId;
	strUrl += "&mode=" + (bIsShared ? 1 : 0);

	var objXML = CreateXMLObject();
	objXML.open("GET", RefreshableUrl(strUrl), true);
	objXML.setRequestHeader("content-type", "application/x-www-form-urlencoded");
	objXML.onreadystatechange = newReadyStateHandler(objXML, OnShareResearch);
	objXML.send(null);
}

function OnShareResearch(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
						if (Zval(objXML.responseText)) {
							bIsShared = true;
							document.getElementById("lnkShare").innerHTML = "Shared";
						} else {
							bIsShared = false;
							document.getElementById("lnkShare").innerHTML = "Not shared";
						}
						break;
					
					case 299:
						alert("Unable to share/un-share the research:\r\n\r\n" + objXML.responseText);
						break;

					default:
						alert("An error occurred while trying to share/un-share the research. Please try again.");
						break;
				}
				objXML = null;			
				break;
		}
	}
}

function FundGraph(FundId) {
	// Work out the page location
	var hWindow = screen.availHeight * 0.8;
	var wWindow = screen.availWidth * 0.9;

	var tWindow = (screen.availHeight - hWindow) / 2;
	var lWindow = (screen.availWidth - wWindow) / 2;
	var strFeatures = "location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no";
	strFeatures += ",top=" + tWindow + ",left=" + lWindow + ",width=" + wWindow + ",height=" + hWindow;

	var strUrl = "fundgraph.asp?searchid=" + strSearchId + "&id=" + FundId;
	var objW = window.open(strUrl, "", strFeatures);
	if (!objW) {
		alert("Your browser software is preventing pop-up windows from being opened. Please switch off your pop-up blocker in order to see the fund graph.");
	}
}


function ImportFundList() {
	ManualFundListDialog("import");
}

// Do the dialog box for selecting a fund
function ManualFundListDialog(Mode) {
	gAddFundMode = Mode;
	
	var dHeight = 400;
	var dWidth = 400;

	var strUrl = "pChooseManualFundList.asp?pagemode=" + Mode;
	
	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + dWidth + "px; DialogHeight: " + dHeight + "px");
		if (strRet) {
			DoSelectFundList(strRet);
		}
	} else {
		l = (screen.availWidth - dWidth) / 2;
		t = (screen.availHeight - dHeight) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + dWidth + ",height=" + dHeight + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function Delay_DoSelectFundList(SearchId) {
	tmrDelayLoad = setInterval("DoSelectFundList(\42" + SearchId + "\42)",1);
}

function DoSelectFundList(SearchId) {
	clearInterval(tmrDelayLoad);
	
	if (SearchId) {
		switch (gAddFundMode) {
			case "import":		
				SetLoadingCaption();

				var strUrl = "_ImportFromFundList.asp?from=" + SearchId + "&into=" + strSearchId;
				var objXML = CreateXMLObject();
				objXML.open("GET", RefreshableUrl(strUrl), true);
				objXML.onreadystatechange = newReadyStateHandler(objXML, OnImportFromFundList);
				objXML.send(null);
				break;
				
			case "addfund":
				if (SearchId == strSearchId) {
					alert("The fund list you have chosen is this one - the one you are currently viewing.");				
				
				} else {
					var strUrl = "_AddFundToManualList.asp?nodata=yes&searchId=" + SearchId + "&fundid=" + gMenuContractId;
					var objXML = CreateXMLObject();
					objXML.open("GET", RefreshableUrl(strUrl), true);
					objXML.onreadystatechange = newReadyStateHandler(objXML, OnAddToManualList);
					objXML.send(null);
				}
				break;
		}
	}			
}

function OnAddToManualList(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
						if (confirm("The fund has been successfully added. Do you want to open the manual fund list now, to see the addition?")) {
							Goto("FilterContracts.asp?searchid=" + objXML.responseText);
						}
						break;
					
					case 299:
						alert("Unable to add the fund to the manual list:\r\n\r\n" + objXML.responseText);
						break;

					default:
						alert("An error occurred while trying to add the fund to the manual list. Please try again.");
						break;
				}
				objXML = null;			
				break;
		}
	}
}

function OnImportFromFundList(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
						// Need to re-populate the contract list
						LoadContractList();
						
						// Need to render the new fund list.
						// The format we've got is fundid,fundname|fundid,fundname etc.
						var strData = objXML.responseText;
						
						RequiredFundIdList = "";
						RequiredFundNameList = "";
						RequiredFundOperator = 21;

						var arrData = strData.split("|");
						for (var i = 0; i < arrData.length; i++) {
							var arrF = arrData[i].split(",");
							RequiredFundIdList += (RequiredFundIdList != "" ? "," : "") + arrF[0];
							RequiredFundNameList += (RequiredFundNameList != "" ? "," : "") + arrF[1];
						}
						document.getElementById("RequiredFundBlock").innerHTML = RenderRequiredFundBlock(RequiredFundIdList, RequiredFundNameList, RequiredFundOperator, RequiredFundPresetMode);
						break;
					
					case 299:
						alert("Unable to import from the selected fund research:\r\n\r\n" + objXML.responseText);
						break;

					default:
						alert("An error occurred while trying to import from the selected fund research. Please try again.");
						break;
				}
				objXML = null;			
				break;
		}
	}
}

function ConvertToManual() {
	if (!confirm("This action will convert this research from a filtered list of funds into a static, manual list. You will then be able to add further funds to the list manually.\r\n\r\nIf you want to create a static list in addition to keeping this research in its current form, create a copy of this research and then use this conversion option afterwards.\r\n\r\nDo you want to carry out this conversion now?")) return;
	Goto("ConvertToManualFundList.asp?id=" + strSearchId);
}

// Adds a fund to a manual list
function AddToManualList(ContractId) {
	gMenuContractId = ContractId;
	ManualFundListDialog("addfund");
}



function RSMInfo() {
	document.getElementsByName("f10000013")[0].disabled = false;

	// Work out the page location
	var hWindow = screen.availHeight * 0.6;
	var wWindow = screen.availWidth * 0.7;

	var tWindow = ((screen.availHeight - hWindow) / 2) - 30;
	var lWindow = (screen.availWidth - wWindow) / 2;

	var strUrl = "http://www.rsmgroup.co.uk/main.php?section=46&article=116&view=2";
	var objW = window.open(strUrl, "RSM", "top=" + tWindow + ",left=" + lWindow + ",width=" + wWindow + ",height=" + hWindow + ",menubar=1,location=1,resizable=1,scrollbars=1,status=0,titlebar=1,toolbar=1");
	if (!objW) {
		alert("Your browser software is preventing pop-up windows from being opened. Please switch off your pop-up blocker in order to see the help file.");
	}
	objW.focus();
}


function FundAvailability() {
	if (!ctContracts) {
		alert("The grid does not include any funds.");
		return;
	}

	var dHeight = 500;
	var dWidth = 500;

	var strUrl = "pFundAvailability.asp?norank=1&searchid=" + strSearchId;
	
	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + dWidth + "px; DialogHeight: " + dHeight + "px");
		if (strRet) {
			var arrB = strRet.split("{b}");
			ShowFundAvailability(arrB[0], arrB[1]);
		}
	} else {
		l = (screen.availWidth - dWidth) / 2;
		t = (screen.availHeight - dHeight) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + dWidth + ",height=" + dHeight + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function ShowFundAvailability(FundList, ContractType) {
	var strUrl = "FundAvailability.asp?fund=" + FundList + "&contract=" + ContractType;
	Goto(strUrl);
}


function PortfolioSettings() {
	if (!ctContracts) {
		alert("The grid does not include any funds.");
		return;
	}

	var dHeight = 500;
	var dWidth = 500;

	var strUrl = "pManualFundListSettings.asp?pagemode=full&searchid=" + strSearchId;
	
	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(RefreshableUrl(strUrl), "", "DialogWidth: " + dWidth + "px; DialogHeight: " + dHeight + "px");
		switch (strRet) {
			case "report":
				DoPortfolioReport();
				break;
			case "graph":
				DoPortfolioGraph();
				break;
		}
	} else {
		l = (screen.availWidth - dWidth) / 2;
		t = (screen.availHeight - dHeight) / 2;
		var objW = window.open(strUrl, "_blank", "top=" + t + ",left=" + l + ",width=" + dWidth + ",height=" + dHeight + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}

function DoPortfolioReport() {
	Goto("PortfolioReport.asp?id=" + strSearchId);
}

function DoPortfolioGraph() {
	FundGraph(strSearchId);
}


function OpenContractFactSheet(ContractID, SearchID) {
	var URL = "Contract.asp?id=" + ContractID + "&searchid=" + SearchID;
	if (lSectorType != 2) lSectorType = 1;
	URL += "&sectortype=" + lSectorType;
	Goto(URL);
}

function QuoteFieldMenu(FieldId, parent, e, FieldType, ContractId) {
	HideMenus(true);

	var b = GetMouseButton(e)
	if (b != 2){
	    ShowQuoteDetails(ContractId);
	    return true;
	}   

	// Nasty way of getting the field value without having to pass it as a parameter
	// and therefore increasing the HTML size. Dependent on the HTML not changing...
	passFilterOnFieldVal = parent.innerHTML;
	passFilterOnFieldId = FieldId;
	passFilterOnFieldType = FieldType;
	passFilterOnContractId = ContractId;
	var objMenu = document.getElementById("mnuNumericFilter");

	var t = getXY(parent).top;
	var l = getXY(parent).left;
	
	// See if it's necessary to include the link related to the fund id
	if (FieldId >= 6000000 && FieldId <= 6999999) {
		document.getElementById("mnuNumericFilterFundInfo").style.display = "";
		document.getElementById("lnkShowFundPPContract").href = "javascript:ShowPPFund(" + FieldId + ", '" + ContractId + "')";
	} else {
		document.getElementById("mnuNumericFilterFundInfo").style.display = "none";
	}
	
	// Adjust for potential scrolling of the grid
	l -= document.getElementById("BodyBlockContainer").scrollLeft;
	t -= document.getElementById("BodyBlockContainer").scrollTop;

	// Adjust the top
	t += 15;
	// Check the width
	if (l + 140 > document.body.clientWidth) {
		l = document.body.clientWidth - 140;
	}
	// Check the top
	if (t + 150 > document.body.clientHeight) {
		t = document.body.clientHeight - 150;
	}

	objMenu.style.top = t + "px";
	objMenu.style.left = l + "px";
	objMenu.style.display = "";
	bSuppressHideMenu = new Date();
	document.onclick = HideMenus;

}

function QuotePopUp(ContractId, e){
 	var b = GetMouseButton(e)
	if (b != 2){
        // Show quote details on left click
	    ShowQuoteDetails(ContractId);
	}   
	
}

function ShowQuoteDetails(ContractId) {

	var dHeight = 500;
	var dWidth = 750;

	var strUrl = RefreshableUrl("pQuoteDetails.asp?fromxml=y&searchid=" + strSearchId + "&contractid=" + ContractId);

	if (whichBrs() == "Internet Explorer") {
		var strRet = XshowModalDialog(strUrl, "", "DialogWidth: " + dWidth + "px; DialogHeight: " + dHeight + "px");
	
	} else {
		l = (screen.availWidth - dWidth) / 2;
		t = (screen.availHeight - dHeight) / 2;
		var objW = window.open(strUrl, "QuoteDetails", "top=" + t + ",left=" + l + ",width=" + dWidth + ",height=" + dHeight + ",location=no,menubar=no,status=no,toolbar=no");
		if (!objW) {
			alert("Your browser software is preventing popup windows from being opened.");
		} else {
			objW.focus();
		}
	}
}


// This function makes a call to the server via ajax to set the selected contract.
function SetSelectedContract(selectedContractId)
{
    //alert(strSearchId + " is thr searcg id: " + "_SetSelectedContract.asp?selectedcontractid=" + selectedContractId + "&searchid=" + strSearchId);
	//Create xmlHttpRequest object and make ajax request
	objXMLHttp = CreateXMLObject();

	objXMLHttp.open("GET", RefreshableUrl("_RequestQuote.asp?contractid=" + selectedContractId + "&searchid=" + strSearchId + "&setcontract=1"), true);
	objXMLHttp.onreadystatechange = newReadyStateHandler(objXMLHttp, SetSelectedContract2);
	objXMLHttp.send(null);
}


function SetSelectedContract2(objXML) {
	if (objXML) {
		switch (objXML.readyState) {
			case 4:
				KillStatusWindow();
				
				switch (objXML.status) {
					case 200:
                        Goto("ClientReport.asp?searchid=" + strSearchId);						
                        break;
					
					case 299:
                          var errCode = objXML.responseText;
                          switch (errCode) {
                            case "0":
                              alert("No Quotes for this type");
                              break;
                            case "-1":
                              lert("No Quotes for this contract");
                              break;
                            default:
                              alert("Error getting illustrative quote for selected contract. Please try again.");
                              break;
                              
                          }

					default:
						alert("An error occurred while trying to set the selected contract. Please try again.");
						break;
				}
				objXML = null;			
				break;
		}
	}
}
