// AutoComplete field that searches a users tree for its names, and populates form elements with the persons data
// Wraps a the YUI AutoComplete

// Global shortcuts for the YUI
$D = YAHOO.util.Dom;
$ = $D.get;

if( document.implementation.hasFeature("XPath", "3.0") ){
	if( typeof XMLDocument == "undefined" ){ XMLDocument = Document; }
  XMLDocument.prototype.selectNodes = function(cXPathString, xNode){
    if( !xNode ) { xNode = this; } 
		var oNSResolver = this.createNSResolver(this.documentElement);
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++){aResult[i] =  aItems.snapshotItem(i);	}
		return aResult;
	};
	XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode){
		if( !xNode ) { xNode = this; } 
		var xItems = this.selectNodes(cXPathString, xNode);
		if( xItems.length > 0 ){return xItems[0];	}
		else{return null;	}
	};
	Element.prototype.selectNodes = function(cXPathString){
		if(this.ownerDocument.selectNodes){	return this.ownerDocument.selectNodes(cXPathString, this);}
		else{throw "For XML Elements Only";}
	};
	Element.prototype.selectSingleNode = function(cXPathString){	
		if(this.ownerDocument.selectSingleNode){return this.ownerDocument.selectSingleNode(cXPathString, this);	}
		else{throw "For XML Elements Only";}
	};
}

if(typeof TGN == 'undefined') {
	var TGN = {};	
	TGN.Search = {};
	TGN.SearchWidget = {};
	TGN.Search.BrowseDate = {};
}

if (typeof TGN.SearchWidget == 'undefined') {
	TGN.SearchWidget = {};
}

if (typeof TGN.Search == 'undefined')
{
	TGN.Search = {};
	TGN.Search.BrowseDate = {};
}

if (typeof TGN.Search.BrowseDate == 'undefined')
{
	TGN.Search.BrowseDate = {};
}

if (typeof dbid == 'undefined' && typeof TGN.SResults != 'undefined')
{
	if (typeof TGN.SResults.Browse != 'undefined')
	{
		if (typeof TGN.SResults.Browse.dbid != 'undefined')
		{
			dbid = TGN.SResults.Browse.dbid;
		}
	}
}

//This Array contains i18n strings populated server-side for the users culture
if(typeof TGN.I18N == 'undefined'){ TGN.I18N = []; }
//static failsafe method for obtaining defined strings
TGN.I18N.getTrans = 
    function(key){
        if(TGN.I18N[key] === null || TGN.I18N[key] == 'undefined'){
            return "$" + key;
        }
        else {return TGN.I18N[key];}
    };

TGN.SearchWidget.NameChanged = 0;
TGN.SearchWidget.TreeLoadingPanel = null;
TGN.SearchWidget.PersonACHandles = {};
TGN.SearchWidget.PersonAutoComplete = 
	function(CtrlName, lNameContainer, formFieldArray, guid, cache, tid, tName)  {

		this.NameTextBox = CtrlName; // + "_TextBox";
		this.NameContainer = lNameContainer;
		
		var aCDS = new YAHOO.widget.DS_XHR('AjaxBaseHandler.ashx', ["ResultSet.Result", "Name","YearRange","tid","pid"]);
		aCDS.scriptQueryAppend = "a=MFN.Shared.Search&f=MFN.Shared.Search.WebControls.PersonAutoComplete|DoCallback&guid=" + guid + "&tid=" + tid;
		aCDS.responseType = YAHOO.widget.DS_XHR.TYPE_JSON;
		aCDS.connTimeout = 4000;
		aCDS.queryMatchSubset = true;
	
        this.YUI_AC = new YAHOO.widget.AutoComplete(this.NameTextBox,this.NameContainer, aCDS);
		this.YUI_AC.animVert = false;
		this.YUI_AC.minQueryLength = 3;
		this.YUI_AC.maxResultsDisplayed = 12;
		this.YUI_AC.queryDelay = 0.2;
		this.YUI_AC.useShadow = true;
		this.YUI_AC.useIFrame = true; 
		this.YUI_AC.autoHighlight = false;

		this.setTid = function(newTid){
			this.YUI_AC.dataSource.scriptQueryAppend = "a=MFN.Shared.Search&f=MFN.Shared.Search.WebControls.PersonAutoComplete|DoCallback&guid=" + guid + "&tid=" + newTid;
			this.YUI_AC.dataSource.flushCache();
			var nTB = $(this.NameTextBox);
			if(nTB != null) {				
				this.YUI_AC.sendQuery(nTB.value);
				nTB.focus();
			}
		};

		this.fnFormatter = function(ResultSet, query) {          
			var returnV =  "<div class='treeName'>";
			returnV += ResultSet[0] + "</div><div class='treeYears'>"+ResultSet[1]+"</div>";
			return returnV;
		};
        this.YUI_AC.formatResult = this.fnFormatter;
      
		var PopulateForm = 
		{
			success: function(o) {
				if(TGN.SearchWidget.TreeLoadingPanel != null) {
					TGN.SearchWidget.TreeLoadingPanel.destroy();
					TGN.SearchWidget.TreeLoadingPanel = null;
				}
				if(TGN.SM.TreeLoadingFader != null) { 
					TGN.SM.TreeLoadingFader.stop(); 
				}

				var theGExactCB = $(o.argument.GlobalExactCB);
				if(theGExactCB != null && theGExactCB.checked){
					TGN.SM.Clear(o.argument.FormId,"",null,false);
				}
				else TGN.SM.Clear(o.argument.FormId);

				var person = eval('(' + o.responseText + ')');
				for(FieldName in o.argument.KVPairs){
					var fId = $(FieldName);
					if( fId != null) {
						if(fId.tagName != "SPAN") { fId.value = person[o.argument.KVPairs[FieldName]]; }
						else {
							if(fId.innerHTML != 'undefined') { fId.innerHTML = person[o.argument.KVPairs[FieldName]]; }
							else if(TGN.SM.GetText(fId) != null) { TGN.SM.SetText(fId, person[o.argument.KVPairs[FieldName]]); }
						}
					}
				}
				for(FuncName in o.argument.Callbacks){
					var tCallb = o.argument.Callbacks[FuncName];
					tCallb.callback(tCallb.domId,person[tCallb.fType],tCallb.args);
				}
				
				TGN.SearchWidget.NameChanged = 0;
			},
			failure: function(o) {
				if(o.status == 500) {
					if(TGN.SearchWidget.TreeLoadingPanel != null) {
						TGN.SearchWidget.TreeLoadingPanel.setBody("<div class='g_alert'><strong>" + TGN.I18N.getTrans("treeLoadingErrorH") +"</strong><br/>" +  TGN.I18N.getTrans("treeLoadingErrorB") + "</div>");
						setTimeout('TGN.SearchWidget.TreeLoadingPanel.destroy()',5000);
					}
					if(TGN.SM.TreeLoadingFader != null) { TGN.SM.TreeLoadingFader.stop(); }
				}
			},
			argument: formFieldArray
		};
		
		this.fnItemSelectEvent = function(oSelf, eArr, oData){
			var url = 'AjaxBaseHandler.ashx?a=MFN.Shared.Search&f=MFN.Shared.Search.WebControls.PersonAutoComplete|GetPersonCallback&guid=';
			url += guid;
			url += "&tid=" + eArr[2][2];
			url += "&pid=" + eArr[2][3];
			
			//find the enclosing form
			if(eArr[1] != null) {
				var cEl = eArr[1];
				while (cEl != null && cEl != document){
					//if(cEl.tagName.toUpperCase() == "FORM"){
					if(cEl.className.indexOf("search-form") >= 0 || cEl.className.indexOf("search-refined") >= 0 ){
						TGN.SM.ShowTreeLoading(cEl.id, cache);
						break;
					}
					cEl = cEl.parentNode;
				}
			}

			YAHOO.util.Connect.asyncRequest('GET',url, PopulateForm);
		};
		this.YUI_AC.itemSelectEvent.subscribe(this.fnItemSelectEvent);
		
		this.fnUnmatchedEvent = function(oSelf, sQuery){
			var gsfn = $(CtrlName + "_gsfn");
			if(gsfn !== null) gsfn.value = ""; //make sure field is cleared
			var gsln = $(CtrlName + "_gsln");
			if(gsln !== null) gsln.value = ""; //make sure field is cleared
		};
		this.YUI_AC.unmatchedItemSelectEvent.subscribe(this.fnUnmatchedEvent);
};

// Sets up the section for multiple trees when using the name auto complete.
TGN.SearchWidget.GetTreeList = function(theDiv, guid, tid, personP){

	var el;
	var AddTreePicker = {
		success: function(o) {
			var resp = eval('(' + o.responseText + ')');
			if(resp != null)
			{
				var theSize = 0;
				for(el in resp)
				{
					theSize += 1;
				}
				
				if (theSize > 5)
				{
					theSize = 5;
				}
				
				var sBox = "<select style='width:225px' size='" + theSize + "' ";
				sBox += "onchange=\"TGN.SearchWidget.SetPrefTree('"+personP+"',this)\" >";								
				
				for(el in resp)
				{
					sBox += "<option value='" + resp[el];
					if(resp[el] == tid) {
						sBox += "' selected >";
					}
					else sBox += "'>";
					sBox += el + "</option>";
					
				}
				
				sBox = sBox + "</select>";

				if(sBox != "<select>") {
					var tCh = $(theDiv);
					if(tCh != null) {
						tCh.innerHTML = sBox;
					}
				}
			}
		},
		failure: function(o){
		alert('fail');
		}
	};

	YAHOO.util.Connect.asyncRequest('GET', 'AjaxBaseHandler.ashx?a=MFN.Shared.Search&f=MFN.Shared.Search.WebControls.PersonAutoComplete|GetAllTrees&guid=' + guid, AddTreePicker);

};

// Used for the select list setting the treeid
TGN.SearchWidget.SetPrefTree = function(personP, sBox) {
	TGN.SearchWidget.PersonACHandles[personP].setTid(sBox.options[sBox.selectedIndex].value);
	//personP.setTid(sBox.options[sBox.selectedIndex].value);
};

TGN.SearchWidget.PlaceAutoComplete = 
	function(PlaceTextBox, PlaceContainer, GpidHidden, lcid, GpidHierHidden, doMultiGpid, dbid, eventType)  {
		if(GpidHierHidden == null || GpidHierHidden == 'undefined' || GpidHierHidden == '') 
			GpidHierHidden = null;
		
		this.aCDS = new YAHOO.widget.DS_XHR('AjaxBaseHandler.ashx', ["ResultSet.Result", "PlaceText", "Gpid", "GpidH", "HitC"]);
		var scriptUrl = "a=MFN.Shared.Search&f=MFN.Shared.Search.WebControls.PlaceTypeAheadHandler|ProcessRequest&Use302Redirect=1&lcid=" + lcid;
		if(GpidHierHidden != null){ scriptUrl += "&GetGH=1"; }
		if(doMultiGpid != 'undefined' && doMultiGpid){ scriptUrl += "&MGpid=1"; }
		if(dbid != 'undefined' && dbid != -1) {scriptUrl += "&dbid=" + dbid; }
		if(eventType != 'undefined' && eventType != 0){ scriptUrl += "&eventT=" + eventType; }

		this.aCDS.scriptQueryAppend = scriptUrl;
		this.aCDS.responseType = YAHOO.widget.DS_XHR.TYPE_JSON;
		this.aCDS.connTimeout = 4000;

		this.YUI_AC = new YAHOO.widget.AutoComplete(PlaceTextBox,PlaceContainer, this.aCDS);			
		this.YUI_AC.minQueryLength = 3;
		this.YUI_AC.maxResultsDisplayed = 15;
		this.YUI_AC.animVert = false;
		this.YUI_AC.queryDelay = 0.2;
		this.YUI_AC.useShadow = true;
		this.YUI_AC.useIFrame = true; 
		this.YUI_AC.autoHighlight = false;
		
		this.fnFormatter = function(ResultSet, query) 
		{
			var rV = '';
			if(typeof ResultSet[3] != 'undefined') {
				if(ResultSet[3] != '0') {
					rV = " <span class='hitC'>" + ResultSet[0] +"  (" + ResultSet[3] + ")</span><span class='hitCAlt'>";
					if(ResultSet[0].length > 18) {
						rV += ResultSet[0].substring(0, 18) + "...";
					}
					else rV += ResultSet[0];
					rV += " (" + ResultSet[3] + ")</span>";
				}
				else { 
					rV = "<span class='zeroH'>"+ResultSet[0]+" (" + ResultSet[3] + ")</span><span class='zeroHAlt'>";
					if(ResultSet[0].length > 18) {
						rV += ResultSet[0].substring(0, 18) + "...";
					}
					else rV += ResultSet[0];
					
					rV += ' (0)';
					rV += '</span>';
				}
			}
			else rV = ResultSet[0];
			return rV;
		};
		this.YUI_AC.formatResult = this.fnFormatter;
		
		this.fnItemSelectEvent = function(oSelf, elItem, oData){
			var gPid = $(GpidHidden);
			if(gPid != null) { 
				gPid.value = elItem[2][1]; //set the gpid field
			}

			if(GpidHierHidden != null) {
				var gPidH = $(GpidHierHidden);
				if(gPidH != null) gPidH.value = elItem[2].length > 2 ? elItem[2][2] : ""; //set the gpidHier field
			}
		};
		this.YUI_AC.itemSelectEvent.subscribe(this.fnItemSelectEvent);

		this.fnUnmatchedEvent = function(oSelf, sQuery){
			var gPid = $(GpidHidden);
			if(gPid !== null) gPid.value = ""; //make sure field is cleared
			if(GpidHierHidden != null) {
				var gPidH = $(GpidHierHidden);
				if(gPidH !== null) gPidH.value = ""; //make sure field is cleared
			}
		};
		this.YUI_AC.unmatchedItemSelectEvent.subscribe(this.fnUnmatchedEvent);
	};
	
//SearchModule Instance methods, these methods require context, as there may be more than one SearchModule on a given page.
//DOMName is the name of page.
if(typeof TGN.SM == 'undefined') { 
	TGN.SM = {}; 
}

TGN.SM.SetVarCookie = function(key,value){
	var VarCookieSet = {
		success: function(o){ },
		failure: function(o){ },
		timeout: 1500,
		cache:false
	};
	var url = 'AjaxBaseHandler.ashx?a=MFN.Shared.Search&f=MFN.Shared.Search.Modulator.ModuleTemplate|SetAdvCallback';
	url += "&k=" + key + "&v=" + value;
	YAHOO.util.Connect.asyncRequest('GET',url,VarCookieSet);
};

TGN.SM.Inst = 
	function(moduleDiv, clientId, formId, showAdvOpts)
	{
		var i = 0;
		var l = 0;
		this.initShowAdv = showAdvOpts;
		this.showAdv = showAdvOpts;
		TGN.SM.InstContainer[moduleDiv] = this;//this makes it so you can call it without the instance handle
		this.moduleDiv = moduleDiv;
		this.clientId = clientId;
		this.XCBArray = new Array();

		this.ToggleAdv = function(qString) {
			this.showAdv = !this.showAdv;//toggle the advanced flag
			if(qString == null) qString = '';
			var alltags;
			var oField;
			var smDiv = $(moduleDiv);
			var gExctb = $(this.clientId + "_xcb");
			
			if(gExctb != null && gExctb.checked){
				gExctb.checked = !gExctb.checked;
				this.AdvCBToggle(gExctb);
			}
			
			var msAvVal = "0"; 
			if(this.showAdv){
				if(gExctb != null) { msAvVal = gExctb.checked?"2":"1"; }
				else { msAvVal = this.showAdv?"1":"0"; }
			}
			TGN.SM.SetVarCookie("MSAV", msAvVal);
			var msAvHdn = $(this.clientId + "_msAV");
			if(msAvHdn != null) msAvHdn.value = msAvVal;
			
			//populate the advanced/standard fields based on the currently displayed version
			var fullNF = $(clientId+"_Name");
			var gsfn_hid = $(clientId+"_Name_gsfn");
			var gsln_hid = $(clientId+"_Name_gsln");
			if(gsfn_hid != null && gsln_hid != null && fullNF != null){
				if(this.showAdv){
					fullNF = fullNF.value;
					if(gsfn_hid.value == "" && gsln_hid.value == "") {
						if(fullNF != null){
							gsfn_hid.value = fullNF.substring(0, fullNF.lastIndexOf(" "));
							gsln_hid.value = fullNF.substring(fullNF.lastIndexOf(" ")+1);
						}
					}
				}
				else {
					fullNF.value = gsfn_hid.value;
					if(gsln_hid.value != "") {
						fullNF.value += " " + gsln_hid.value;
					}
				}
			}
			
			if(smDiv != null) {//do all the show/hide stuff
				if(this.showAdv) {
					smDiv.className = smDiv.className + " advanced";
				}
				else {
					smDiv.className = smDiv.className.replace(" advanced", "");
				}

				alltags = smDiv.getElementsByTagName("INPUT");
				if(this.showAdv) {
					for(i=0, l=alltags.length; i < l; i++){
						if(alltags[i].className.indexOf("SM_regOpt") > -1){
							oField = $(alltags[i].id + "-x");
							if(oField !== null){
								var oyear = alltags[i].value.match(/\d{4}/);
								if(oyear !== null && oyear != ""){
									oField.value = oyear;
								}
							}
						}
					}
				}
				else {
					for(i=0, l=alltags.length; i < l; i++){
						if(alltags[i].className.indexOf("SM_advOpt") > -1){
							var idName = alltags[i].id.substring(0,alltags[i].id.length-2);//strip the ending -x and look
							oField = $(idName);
							if(oField != null && oField.value == "") {
								oField.value = alltags[i].value;
							}
						}
					}
				}
			}
			var theHidden = $(clientId + "_msAV");
			if(theHidden != null) { //change the advanced search flag
				if(this.showAdv)	theHidden.value = "1";
				else theHidden.value = "0";
			}

			//This forces IE6 to repaint the open modules, IE6 doesn't reposition absolute divs(Place and Person widgets) in the flow properly when the total height of its container changes.
			if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie < 7) {
				alltags = YAHOO.util.Dom.getElementsByClassName("mod open");
				for(var i=0, l=alltags.length; i < l; i++){
					var cB = new TGN.SM.AdvElem(alltags[i]);
					setTimeout(cB.go,1);
				}
			}

		};
		
		this.ExactCBToggle = function(theCB){
			var gExct = $(this.clientId + "_xcb");
				if(theCB.checked == true) {
					if(this.p_CheckCB(theCB, true)){
						gExct.checked = theCB.checked;		
					}
					else gExct.checked = false;		
				}
				else {
					gExct.checked = false;		
				}
		};

		this.p_CheckCB = function(theCB, toCheckBool)
		{
			var gExct = $(this.clientId + "_xcb");
			var form = $(this.moduleDiv);
			if(form != null) {
				var alltags = form.getElementsByTagName("INPUT");
				for(var i=0, l=alltags.length; i < l; i++){  
					if(alltags[i].type == "checkbox") {
						if(alltags[i] == theCB || alltags[i] == gExct ) continue;
						if(alltags[i].checked != toCheckBool) return false;
					}
				}
			}	
			return true;
		};

		this.AdvCBToggle = function(theCB)
		{
			if (theCB == null) theCB = $(this.clientId + "_xcb");
			var form = $(this.moduleDiv);
			if(form != null) {
				var alltags = form.getElementsByTagName("INPUT");
				for(var i=0, l=alltags.length; i < l; i++){  
					if(alltags[i].type == "checkbox") {
						alltags[i].checked = theCB.checked;
					}
					else if(alltags[i].type == "hidden" && (alltags[i].name.indexOf("_x") + 2) == alltags[i].name.length)
					{
						alltags[i].value = theCB.checked ?"1":"";
					}
				}
				/*NOT NEEDED? 
				var ne = $(this.clientId + "_nedd");
				if (ne == null || !$D.isAncestor(form, ne))
				    ne = $(this.clientId + "_NationalityEthnicity_nedd");
				if (ne == null || !$D.isAncestor(form, ne))
				    ne = $("refineT_nedd");
				if (ne != null) ne.disabled=theCB.checked;*/
			}
			TGN.SM.SetVarCookie("MSAV", theCB.checked?"2":"1");
		};

	};

TGN.SM.InstContainer = new Array();
TGN.SM.InstMgr = function(moduleDiv, clientId)
{
	var hasInst = TGN.SM.InstContainer[moduleDiv];
	if(hasInst == null) {
		hasInst = new TGN.SM.Inst(moduleDiv, clientId, '', true);
	}
	return hasInst;
};

TGN.SM.AdvElem = function(el){
	this.go = function(){
		el.className = "mod";
		el.className = "mod open";
	};
};
	
//array of configuration details for TG.SM static methods that is populated from server side code on init
if(typeof TGN.SM.CONFIG == 'undefined') TGN.SM.CONFIG = new Array(); 
TGN.SM.GetConfig = function(key) {return TGN.SM.CONFIG[key];};
	
//STATIC methods of SM .. No context needed for these
	TGN.SM.SyncExactCB = function(theCB,hidden){
		var theHidden = $(hidden);
		if(theHidden != null) {
			if(theCB.checked) theHidden.value = '1';
			else theHidden.value = '';
		}
	};
	TGN.SM.HideShow = function(id) {
		var module = $(id);
		var x = module.className.indexOf(' open');
		if(x > 0)
			module.className = module.className.substring(0, x);
		else
			module.className = module.className + ' open';
	};
	TGN.SM.TogSumCat = function(theDiv) {
		tEl = $(theDiv);
		if(tEl != null){
			var x = tEl.className.indexOf(' closed');
			if(x > 0)
				tEl.className = tEl.className.substring(0, x);
			else
				tEl.className = tEl.className + ' closed';
		}
	};
	TGN.SM.showMoreLocation = function(maxRes, tName, zIndex){
		var newLoc = 0;
		var maxFilled = 0;
		for(var i = 1; i <= maxRes; i++){
			var newD = $(tName+i+'_Div');
			if(newD != null) {
				if(newLoc == 0 && newD.innerHTML == ''){
					newLoc = i;	
					maxFilled = i;
					zIndex -= (newLoc-1) * 2;
				}
				else if(newD.innerHTML != ''){
					if(newD.style.display == 'none'){
						newD.style.display = 'block';
						return;
					}
					maxFilled = i;
				}
				else break;
			}	
		}
		if( (maxFilled+1) > maxRes) {
			var AddAnother = $("resAddAnother");
			if(AddAnother != null) 
				AddAnother.style.display = 'none';
		}

		if(newLoc == 0) return;

		newD = $(tName+newLoc+'_Div');
		if(newD != null){

			newD.innerHTML += "<style type='text/css'> #"+tName+newLoc+"_AutoComplete .yui-ac-content{ z-index:" + 
				zIndex + ";} #"+tName+newLoc + "_AutoComplete .yui-ac-shadow { z-index:"+(zIndex-1)+"; } #"+tName+newLoc+"_AutoComplete { z-index:"+zIndex+" } </style> " + 
				"<input type='hidden' class='clear' id='"+tName+newLoc+"_Gpid' name='msrpn"+newLoc+"' value='' />" + 
				"<div class='PlaceBox_CN'><div id='"+tName+newLoc+"_AutoComplete'><input type='text' id='"+tName+newLoc + 
				"_ftp' name='msrpn"+newLoc+"__ftp' value='' class='field' />" + 
				"<div id='"+tName+newLoc+"_ACContainer'></div> </div></div>";
			
			newD.style.display = 'block';	

			(function() {
				this.personWidget = new TGN.SearchWidget.PlaceAutoComplete(tName+newLoc+"_ftp",tName+newLoc+ "_ACContainer",tName+newLoc+"_Gpid","1033","");
			})();

			//IE has a hard time paring style declarations in innerHTML.  Add needed zIndex after insert here.
			if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie <= 8) {
				var t2 = $(tName+newLoc+"_AutoComplete");
				if(t2 != null) t2.style.zIndex = zIndex;
				var elArray = YAHOO.util.Dom.getElementsByClassName('yui-ac-content',null,tName+newLoc+'_AutoComplete');
				if(elArray != null && elArray.length > 0) {
					elArray[0].style.zIndex = zIndex;
				}
				//IE is also weak minded when it comes to adding elements to the dom.. help it along
				YAHOO.util.Dom.getElementsByClassName('PlaceBox_CN','div',null,function(el) {el.className=el.className + " clear"; } );
			}
			if(typeof TGN.KeyWatcher != 'undefined') {
				var nRes = $(tName+newLoc+"_ftp");
				if(nRes != null) {
					TGN.KeyWatcher.addListener(nRes);
				}
			}
		}
	};
	TGN.SM.popGenderR = function(id,value,args){
		if(value == "m") value = "f";
		else if (value == "f") value = "m";
		TGN.SM.popGender(id,value,args);
	};
	TGN.SM.popGender = function(id, value, args){
		var dd = $(id);
		//The gender dd submits the opposite of the real value as we do a 
		//not exclude filter on this value instead.  So we must reverse the stated value.
		if(value == "m") value = "f";
		else if (value == "f") value = "m";
		if(dd != null) {
			for(var iI=0, l=dd.options.length; iI < l; iI++){
				if( dd.options[iI].value == value) {
					dd.selectedIndex = iI;
					if(args[0] != null) {
						modD = $(args[0]);
						if(modD != null) {
							if(modD.innerHTML != 'undefined') { modD.innerHTML = dd.options[iI].text; }
							else if(TGN.SM.GetText(modD) != null) { TGN.SM.SetText(modD, dd.options[iI].text); }
						}
					}
					break;
				}
			}
		}
	};
	TGN.SM.cFormEl = function(name,value) {
		var kv = document.createElement("input");
		kv.setAttribute("type", "hidden");
		kv.setAttribute("name", name);
		kv.setAttribute("value", value);
		return kv;		
	};
	TGN.SM.PersonKeyPress = function(e){
		if(e.keyCode != 13 && e.keyCode != 9 && !(e.keyCode >= 37 && e.keyCode <= 40) && !(e.keyCode >= 16 && e.keyCode <= 19) ) { 
			TGN.SearchWidget.NameChanged += 1;
		}
	};
	TGN.SM.CloseSSO = function(explicit) {
		if(explicit || TGN.SM.CloseTimer != null) { //should indicate that the mouse is still over hover
			var hContent = $("startsearchoverDD");
			if(hContent != null && hContent.className.indexOf("indivHide") == -1) 
				hContent.className += ' indivHide';
			YAHOO.util.Event.removeListener("ssoClose",'blur');
		}
	};
	TGN.SM.CloseTimer = null;
	TGN.SM.CloseSSOM = function(){ TGN.SM.CloseTimer = setTimeout(function(){TGN.SM.CloseSSO(false);},3000);	};
	TGN.SM.SSOMOver = function(){ if(TGN.SM.CloseTimer != null) {clearTimeout(TGN.SM.CloseTimer); TGN.SM.CloseTimer = null; } };
	TGN.SM.InitSSOLink = function() {
		var hContent = $("startsearchoverDD");
		hContent.style.position = 'absolute';
		hContent.style.zIndex = 50;

		function AddHoverEffect(el) { el.className += ' yuimenuitem-selected'; }
		function AddHoverOut(el) { el.className = el.className.replace(' yuimenuitem-selected', ''); }
		YAHOO.util.Dom.getElementsBy(function(){return true;},'li',hContent,function(el){ YAHOO.util.Event.addListener(el,'mouseover',function(){AddHoverEffect(el);}); YAHOO.util.Event.addListener(el,'mouseout',function(){AddHoverOut(el);});} );
		
		/*
		//Disappearing facet bug.
		//After the left column controls were all wrapped in a containing div id=leftcolumn, this hack no longer was needed
		if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie <= 7) {
			var cat = $("categories");
			if(cat != null) { cat.style.zIndex = -1; }
		}
		*/

		function onclicker(domElem) { 
			return (function() {

				if(domElem.className.indexOf("indivHide") >= 0) {
					domElem.className = domElem.className.replace(' indivHide', '');
					YAHOO.util.Dom.setX(domElem, YAHOO.util.Dom.getX("ssoLink")-5);
					YAHOO.util.Dom.setY(domElem, YAHOO.util.Dom.getY("ssoLink")+10); 
					var closer = $("ssoClose");
					if (closer != null) closer.focus();	
					YAHOO.util.Event.addListener("ssoClose", 'blur', function(){TGN.SM.CloseSSO(false);});
				}
				
			});
		}
		var doOnclicker = onclicker(hContent);//wrap dom element in closer
		YAHOO.util.Event.addListener("ssoLink", "click", doOnclicker);

	};
	TGN.SM.ClearedValues = null;
	TGN.SM.ClearAndSave = function(id) {
		var i = 0;
		if(TGN.SM.ClearedValues == null) {
			TGN.SM.ClearedValues = new Array();
		}
		else {
			TGN.SM.Clear(id, "");//don't need to save it again. just clear um
			return;
		}

		var clearValue = "";
		var form = $(id);
		if(form != null) {
			var alltags = form.getElementsByTagName("INPUT");
			for(i=0, l=alltags.length; i < l; i++){  
				if(alltags[i].type == "checkbox") {
					TGN.SM.ClearedValues[alltags[i].id] = alltags[i].checked;
					alltags[i].checked = false;
				}
				else if(alltags[i].type == "text" && alltags[i].className.indexOf("field") >= 0 ) {
					TGN.SM.ClearedValues[alltags[i].id] = alltags[i].value;
					alltags[i].value = clearValue;
				}
				else if(alltags[i].type == "hidden")
				{
					if(alltags[i].className.indexOf("clear") >= 0) {
						TGN.SM.ClearedValues[alltags[i].id] = alltags[i].value;
						alltags[i].value = "";
					}
				}
			}

			alltags = form.getElementsByTagName("SELECT");
			for(i=0, l=alltags.length; i < l; i++){
				if (alltags[i].name=='ne')
					continue;

				TGN.SM.ClearedValues[alltags[i].id] = alltags[i].selectedIndex;
				alltags[i].selectedIndex = 0;
			}	
		}
	};
	TGN.SM.RestoreClear = function(id) {
		var i = 0;
		var l = 0;
		var form = $(id);
		if(TGN.SM.ClearedValues == null) return;
		var vArr = TGN.SM.ClearedValues;
		if(form != null) {
			var alltags = form.getElementsByTagName("INPUT");
			for(i=0, l=alltags.length; i < l; i++){  
				if(alltags[i].type == "checkbox" && vArr[alltags[i].id] != 'undefined') {
					alltags[i].checked = TGN.SM.ClearedValues[alltags[i].id];
				}
				else if(alltags[i].type == "text" && vArr[alltags[i].id] != 'undefined' && alltags[i].className.indexOf("field") >= 0 ) 
				{
					alltags[i].value = TGN.SM.ClearedValues[alltags[i].id];
				}
				else if(alltags[i].type == "hidden" && vArr[alltags[i].id] != 'undefined')
				{
					if(alltags[i].className.indexOf("clear") >= 0) {
						alltags[i].value =  TGN.SM.ClearedValues[alltags[i].id];
					}
				}
			}

			alltags = form.getElementsByTagName("SELECT");
			for(i=0, l=alltags.length; i < l; i++){
				if (alltags[i].name=='ne' || vArr[alltags[i].id] != 'undefined')
					continue;

				alltags[i].selectedIndex = TGN.SM.ClearedValues[alltags[i].id];
			}	
		}
	};
	TGN.SM.Clear = function(id, clearValue, showConfirm, togExtCB ) {
		var i = 0;
		var l = 0;
		if(clearValue == null) clearValue = "";//default is to clear the fields with empty
		if(togExtCB == null) togExtCB = true;
		var form = $(id);
		if(form != null) {
			if(showConfirm == null || confirm(showConfirm)) {
				var alltags = form.getElementsByTagName("INPUT");
				for(i=0, l=alltags.length; i < l; i++){  
					if(alltags[i].type == "checkbox" && togExtCB) {
						alltags[i].checked = false;
					}
					else if(alltags[i].type == "text" && alltags[i].className.indexOf("field") >= 0 ) {
						alltags[i].value = clearValue;
					}
					else if(alltags[i].type == "hidden")
					{
						if(alltags[i].className.indexOf("clear") >= 0) {
							alltags[i].value = "";
						}
					}
				}

				alltags = form.getElementsByTagName("SELECT");
				for(i=0, l=alltags.length; i < l; i++){
				    if (alltags[i].name=='ne')
				        continue;
					alltags[i].selectedIndex = 0;
				}
			}
		}
	};
	TGN.SM.TrackTemplate = function(isNew, isAdv) {
		var omniT=s_gi(s_account);
		var adv = "Simple";
		if(isAdv)
		{
			adv = "Advanced";
		}

		var level = "unknown";
		if(typeof TGN.Ancestry.Search.SearchInfo != 'undefined') {
			if(typeof TGN.Ancestry.Search.SearchInfo.pageType != 'undefined') {
				level = TGN.Ancestry.Search.SearchInfo.pageType;
			}
		}

		var pName = "Search:RForm:"+level+":"+adv;
		if(isNew) {
			pName = "Search:RForm:"+level+":"+adv;
		}

		s_pageName = pName;

		/*jsl:ignore*/
		void(omniT.t());
		/*jsl:end*/
	};
	TGN.SM.ToggleSearchCat = function(qString,isGlobal) {
		TGN.SM.HideNewSearch();
		TGN.SM.ShowNewSearch(qString, isGlobal, false, true);
	};
	TGN.SM.SubmitForm = function(id, btn, txt, adv, isTop){
		if(typeof isTop == 'undefined') {
			var b = $(btn);
			b.focus();
		}
		//allows a chance for any outstanding events to complete before inspecting the form for submission - team 42143
		setTimeout("TGN.SM.SubmitFormNow('"+id+"','"+btn+"','"+txt+"','"+adv+"')", 1);
	};
	TGN.SM.SubmitFormNow = function(id, btn, txt, adv) {
		var i = 0;
		var l = 0;
		//Search Buttons
		var b = $(btn);
		b.className = b.className + ' disabled';
		var topBtn = $("top_"+btn);
		if(topBtn != null) {
			topBtn.className = topBtn.className + ' disabled';
		}

		//Search Button Text
		$(txt).innerHTML = TGN.I18N.getTrans("Searching"); //'Searching...';
		var tSearchTxt = $("top_"+txt);
		if(tSearchTxt != null) {
			tSearchTxt.innerHTML = TGN.I18N.getTrans("Searching"); //'Searching...';
		}

		var form = $(id);
		//Validation code added here
		
		var advHidden = $(adv);
		var isAdv = false;
		var advClass = "SM_advOpt";
		if(advHidden != null && (advHidden.value == "1" || advHidden.value == "2")) 
		{	
			advClass = "SM_regOpt"; 
			isAdv = true;
		}

		//create form and only add those elements that should be
		//submitted to it.  (Lose empty values and hidden input elements)	
		var subForm = document.createElement("form");   
		subForm.setAttribute("method", "GET");
		subForm.setAttribute("action", form.action);
		
		alltags = form.getElementsByTagName("INPUT");
		var kv;
		for(i=0, l=alltags.length; i < l; i++){         
			if(    alltags[i].className.indexOf(advClass) > -1 || alltags[i].name == null || alltags[i].value == null || alltags[i].name == '' || alltags[i].value == '' ) 
			{   
				continue;   
			}
			if(alltags[i].type == "checkbox" || alltags[i].type == "radio") {
				if(alltags[i].checked){
					kv = TGN.SM.cFormEl(alltags[i].name,alltags[i].value);
					kv.checked = alltags[i].checked;
					subForm.appendChild(kv);
				}
			}
			else if (alltags[i].type == "hidden"){
				//clears the hidden exact cb values when query isn't an advanced query
				if(!isAdv && (alltags[i].name.indexOf("_x") + 2) == alltags[i].name.length)
				{
					if(alltags[i].className.indexOf("SM_DND") <= -1)
						continue;
				}
				kv = TGN.SM.cFormEl(alltags[i].name, alltags[i].value);
				subForm.appendChild(kv);
			}
			else {
				//Needed for IE7
				if( !isAdv && (alltags[i].name == 'gsfn' || alltags[i].name == 'gsln' ) && TGN.SearchWidget.NameChanged > 0) 
				{
					continue;	
				}

				kv = TGN.SM.cFormEl(alltags[i].name, alltags[i].value);
				subForm.appendChild(kv);
			}
		}
		
		alltags = form.getElementsByTagName("SELECT");
		for(i=0, l=alltags.length; i < l; i++){
			if(alltags[i].className.indexOf(advClass) > -1) {
				continue;
			}
			else if (alltags[i].value != ''){
				kv = TGN.SM.cFormEl(alltags[i].name, alltags[i].value);
				subForm.appendChild(kv);
			}
		}
		
		document.body.appendChild(subForm);
		subForm.submit();
		return false;
	};
	TGN.SM.RegSubmit = function(formId, submitFunc) 
	{
		var tElm = document.getElementById(formId);
		if(tElm != null) {

			var subMeth = function(e) {
				if(typeof e != 'undefined') {
					if (e.keyCode == 13) {
						submitFunc();
					}
				}
			};

			for(var i = 0; i < tElm.length; i++) {
				if(tElm[i].type == "text") {
					YAHOO.util.Event.addListener(tElm[i], 'keydown', subMeth);
				}
			}
		}
	};
	TGN.SM.ShowWaitMessage = function(msg){
		if (typeof TGN.SM.WaitPanel == 'undefined' || TGN.SM.WaitPanel == null){
			var div = document.createElement('div');
			div.setAttribute('id','waitPanel');
			document.body.appendChild(div);

			TGN.SM.WaitPanel = new YAHOO.widget.Panel('waitPanel',{
				close: false,
				draggable: false,
				modal: true,
				visible: true,
				width: 200,
				underlay:'none',
				zIndex:101});
			TGN.SM.WaitPanel.setBody(msg);
			TGN.SM.WaitPanel.render(document.body);
		}
		TGN.SM.PositionAndShow(TGN.SM.WaitPanel);
	};
	TGN.SM.TreeLoadingFader = null;
	TGN.SM.ShowTreeLoading = function(id,cache){
		if(typeof TGN.SM.TreeWaitPanel == 'undefined' || TGN.SM.TreeWaitPanel == null){
			var sTemp = $(id);
			if(sTemp != null){
				TGN.SM.TreeLoadingFader = new YAHOO.util.Anim(id, {opacity: {to:0.1}},3,YAHOO.util.Easing.easeOut);
				TGN.SM.TreeLoadingFader.onComplete.subscribe(function() { 
					sTemp.style.opacity = 1; 
					if(sTemp.style.filter != null) sTemp.style.filter = '';
				});
				TGN.SM.TreeLoadingFader.animate();

				var div = document.createElement('div');
				div.setAttribute('id','treeWaitPanel');
				sTemp.appendChild(div);
				YAHOO.util.Dom.setXY(div,YAHOO.util.Dom.getXY(sTemp));

				TGN.SearchWidget.TreeLoadingPanel = new YAHOO.widget.Panel('treeWaitPanel',
					  {constrainttoviewport: true, close:false, underlay:'none', visible:true, draggable:false} ); 
				TGN.SearchWidget.TreeLoadingPanel.setBody("<img src='" + cache + "/css/search/i/Loading32.gif' /><span class='loadingMsg'>" + TGN.I18N.getTrans("loadingMsg") + "</span>");
				TGN.SearchWidget.TreeLoadingPanel.render();
			}
		}
	};
	TGN.SM.HideWaitMessage = function(){
		if (typeof TGN.SM.WaitPanel != 'undefined' && TGN.SM.WaitPanel != null){
			TGN.SM.WaitPanel.hide();
		}
	};
	TGN.SM.ShowMore = function(id, linkId){
		var div = $(id);
		var link = $(linkId);
		if(div != null) div.style.display = 'block';
		if(link != null) link.style.display = 'none';
	};
	TGN.SM.ShowSearchPanel = function(){
		TGN.SM.PositionAndShow(TGN.SM.NewSearchPanel);
		TGN.SM.HideWaitMessage();
		TGN.SM.FocusFirstInput('newT_search-form');
	};
	TGN.SM.PositionAndShow = function(p){
		var x = $D.getDocumentScrollLeft() + (($D.getViewportWidth() -  p.element.offsetWidth) / 2);
		if (x < 10)
			x=10;
		var y = $D.getDocumentScrollTop()+50;
		p.cfg.setProperty("zIndex", 201);
		p.cfg.setProperty("x", x);
		p.cfg.setProperty("y", y);
		p.show();
	};
	TGN.SM.SetACZ = function(div,TopZ) {
		if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie <= 7) {
			var locA = YAHOO.util.Dom.getElementsByClassName('yui-ac','div',div);
			if(document.styleSheets && document.styleSheets.length > 0) {
				var styleNode = document.styleSheets[0];
				if(typeof(styleNode.addRule) == "object") {
					for(var i = 0; i < locA.length; i++) {
						if(locA[i].id != null && locA[i].id != ""){
								styleNode.addRule("#"+locA[i].id, "z-index:"+TopZ);
								styleNode.addRule("#"+locA[i].id+ " .yui-ac-content", "z-index:"+TopZ--);
								styleNode.addRule("#"+locA[i].id+ " .yui-ac-shadow", "z-index:"+TopZ--);
						}
					}
				}
			}
		}
	};
	TGN.SM.HandleSuccess = function(o){
		if (typeof TGN.SM.NewSearchPanel == 'undefined' || TGN.SM.NewSearchPanel == null){
			if(o.responseText != 'undefined'){
				var div = document.createElement('div');
				div.setAttribute('id','newSearch');
				//IE likes to have the element appended to the DOM first before executing
				//scripts that are added via innerHTML assignment.  Everyone doesn't like.
				if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie <= 7) {
					document.body.appendChild(div);
					div.innerHTML += o.responseText;
					//IE doesn't parse css declarations consistantly
					//	TGN.SM.SetACZ(div,150);
				} 
				else {
					div.innerHTML += o.responseText;
					document.body.appendChild(div);
				}
				TGN.SM.NewSearchPanel = new YAHOO.widget.Panel('newT_search-form',{
					close: true,
					draggable: true,
					modal: true,
					visible: true,
					width: 450,
					underlay:'none',
					effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.1}});

				TGN.SM.NewSearchPanel.cfg.getProperty("strings").close = " ";
				//need to do it here becuase visible=true does not fire a show event	
				if(typeof TGN.KeyWatcher != 'undefined') {
					TGN.KeyWatcher.disable();
					TGN.KeyWatcher.lockState();
				}
				TGN.SM.NewSearchPanel.hideEvent.subscribe(function() {
					if(typeof TGN.KeyWatcher != 'undefined') {
						TGN.KeyWatcher.unlockState();
						TGN.KeyWatcher.enable();
					}
				});	   
				TGN.SM.NewSearchPanel.showEvent.subscribe(function() {
					if(typeof TGN.KeyWatcher != 'undefined') {
						TGN.KeyWatcher.disable();
						TGN.KeyWatcher.lockState();
					}
				});

				TGN.SM.NewSearchPanel.element.className+=' modal';
				var p=$('newT_search-form');
				p.className = p.className.replace(' yui-panel', '');
				TGN.SM.NewSearchPanel.render(document.body);

				$('newT_mod-search').innerHTML += "<span class='lnk-cancel'>&nbsp;" + TGN.I18N.getTrans("or") +"&nbsp;<a href='javascript:TGN.SM.HideNewSearch();'>" + TGN.I18N.getTrans("newSearchCancel") + "</a></span>";
				if(o.argument[0] == 'clear'){
					TGN.SM.Clear('newT_search-form');
				}

				TGN.SM.ShowSearchPanel();

				if (YAHOO.env.ua.ie <= 7) {
					var closerF = function(divN, clZ) { return function() { TGN.SM.SetACZ(divN,clZ); }; };
					setTimeout(closerF(TGN.SM.NewSearchPanel.element,150), 1);
				}
			}
		}
		else{
			TGN.SM.ShowSearchPanel();
		}
	};
	TGN.SM.HandleFailure = function(o){
		document.location.href = '/';
	};
	TGN.SM.ShowNewSearch = function(qString, isGlobalLevel, alwaysRefreshFlg, keepFormPop){
		if(typeof isGlobalLevel == 'undefined') isGlobalLevel = true;

		// Added new var to force refresh of overlay everytime.
		if(typeof alwaysRefreshFlg == 'undefined') alwaysRefreshFlg = false;

		if(qString == null) qString = '';

		if(typeof TGN.SM.NewSAdvT == 'undefined') TGN.SM.NewSAdvT = 0;
		var rTemplate = TGN.SM.NewSAdvT;
		if(isGlobalLevel) { 
			TGN.SM.NewSAdvT= 1;
		}
		else TGN.SM.NewSAdvT = 2;

		// In case, always refresh flg is set, and newSearchPanel exists, change rTemplate to force destroying of newSearchPanel.
		if (alwaysRefreshFlg && typeof TGN.SM.NewSearchPanel != 'undefined')
			rTemplate	 = TGN.SM.NewSAdvT + 1;

		if(rTemplate != 0 && rTemplate != TGN.SM.NewSAdvT){
			//clean up the last template out of the DOM
			TGN.SM.NewSearchPanel.destroy();
			if(TGN.SM.WaitPanel != null) TGN.SM.WaitPanel.destroy();
			TGN.SM.NewSearchPanel = null;
			TGN.SM.WaitPanel = null;
		}
		if (typeof TGN.SM.NewSearchPanel == 'undefined' || TGN.SM.NewSAdvT != rTemplate || alwaysRefreshFlg){
			if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie <= 7) TGN.SM.ShowWaitMessage(TGN.I18N.getTrans("Loading"));

			var clear = 'clear';
			if(typeof keepFormPop != 'undefined' && keepFormPop)
				clear = 'keep';

			setTimeout("YAHOO.util.Connect.asyncRequest('GET', '/Mercury/Pages/AJAX/DefaultSearchTemplate.aspx"+qString.replace(/'/g, "&#39;")+"', {success: TGN.SM.HandleSuccess, argument:['" + clear + "'], failure: TGN.SM.HandleFailure})",1);
		}
		else {
			TGN.SM.ShowSearchPanel();
		}
	};
	TGN.SM.HideNewSearch = function(){
		if (typeof TGN.SM.NewSearchPanel != 'undefined')
			TGN.SM.NewSearchPanel.hide();
		TGN.SM.HideWaitMessage();
	};

/* Refine Search Rewrite */
	TGN.SM.HideRefineSearch = function(){
		if(typeof TGN.SM.RefineSearchPanel != 'undefined'){
			TGN.SM.RefineSearchPanel.hide();
		}
		TGN.SM.HideWaitMessage();
	};
	TGN.SM.InitRefineSearch = function() {
		TGN.SM.RefineSearchPanel = new YAHOO.widget.Panel('refineT_search-form',{
			close: true,
			draggable: true,
			modal: true,
			visible: false,
			width: 450,
			underlay:'none'});

		TGN.SM.RefineSearchPanel.cfg.getProperty("strings").close = " ";
		TGN.SM.RefineSearchPanel.hideEvent.subscribe(function() {
			if(typeof TGN.KeyWatcher != 'undefined') {
				TGN.KeyWatcher.unlockState();
				TGN.KeyWatcher.enable();
			}
		});	   
		TGN.SM.RefineSearchPanel.showEvent.subscribe(function() {
			if(typeof TGN.KeyWatcher != 'undefined') {
				TGN.KeyWatcher.disable();
				TGN.KeyWatcher.lockState();
			}
		});

		TGN.SM.RefineSearchPanel.element.className+=' modal';
		var p=$('refineT_search-form');
		p.className = p.className.replace(' yui-panel', '');
		
		TGN.SM.RefineSearchPanel.render(document.body);
		$('refineT_mod-search').innerHTML += "<span class='lnk-cancel'>&nbsp;" + TGN.I18N.getTrans("or") +"&nbsp;<a href='javascript:TGN.SM.HideRefineSearch();'>" + TGN.I18N.getTrans("newSearchCancel") + "</a></span>";
	};
	TGN.SM.LoadModTemplate = function(o) {
		var div = $('ModTemplateStore');
		if(div != null) {
			if(o.responseText != 'undefined'){

				if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie <= 7) {
					div.innerHTML += o.responseText;
					//Directly apply zindex styles after they have been fully parsed into the dom.
					//Inline style declarations are ignored by the tard browsers 
					//TGN.SM.SetACZ(div,150);
				}
				else {
					var ffdiv = document.createElement('div');
					ffdiv.innerHTML += o.responseText;
					div.appendChild(ffdiv);
				}

				if(typeof TGN.KeyWatcher != 'undefined') {
					TGN.KeyWatcher.addListeners();
				}

				if(o.argument[0] == 'refine') {
					TGN.SM.InitRefineSearch();
					TGN.SM.PositionAndShow(TGN.SM.RefineSearchPanel, o.argument[1]+'_search-form');
					TGN.SM.ShowMore('more_'+o.argument[1],'moreLink_'+o.argument[1]);
				}
				else {
					var it = 0;
					//TGN.SM.InitRefineSearch();
					//TGN.SM.PositionAndShow(TGN.SM.NewSearchPanel, o.argument[1]+'_search-form');
				}
				if(o.argument[2] == true){
					TGN.SM.ClearAndSave(o.argument[1]+"_search-form");
				}

				if (YAHOO.env.ua.ie == 7) {
					var closerF = function(divN, clZ) { return function() { TGN.SM.SetACZ(divN,clZ); }; };
					setTimeout(closerF(TGN.SM.RefineSearchPanel.element,150), 1);
				}
			}
		}
	};
	TGN.SM.ShowRefineLock = true;
	TGN.SM.ShowRefineSearchT = function(clearIt){
		if(clearIt) {
			TGN.SM.ShowRefineSearchImpl('true');
		}
		else {
			TGN.SM.ShowRefineSearchImpl('false');
		}
	};
	TGN.SM.ShowRefineSearch = function(evt, keypress){
		var clearP = 'false';
		if(typeof keypress != 'undefined' && keypress[1].keyCode == 78) {
			clearP = 'true';	
		}
		TGN.SM.ShowRefineSearchImpl(clearP);
	};
	TGN.SM.ShowRefineSearchImpl = function(clearP){
		if(!TGN.SM.ShowRefineLock) return;
		else {TGN.SM.ShowRefineLock = false; }

		if(typeof TGN.KeyWatcher != 'undefined') {
			TGN.KeyWatcher.disable();
		}

		var advHidden = $("refineT_msAV");
		var isAdv = false;
		if(advHidden != null && (advHidden.value == "1" || advHidden.value == "2")) 
		{	
			isAdv = true;
		}
		//don't want to slow the show template for sake of tracking, do this after
		setTimeout(function() { TGN.SM.TrackTemplate(clearP, isAdv); }, 10);

		//check for Template cached on page. 
		var qString = document.location.search;
		var Tcache = $("ModTemplateStore");
		if(Tcache != null){
			if(typeof TGN.SM.RefineSearchPanel != 'undefined') {

				TGN.SM.PositionAndShow(TGN.SM.RefineSearchPanel);
				TGN.SM.ShowMore('more_refineT','moreLink_refineT');
				if(clearP == 'true') { 
					TGN.SM.ClearAndSave('refineT_search-form');
					//TGN.SM.Clear('refineT_search-form');
				}
				else {
					TGN.SM.RestoreClear('refineT_search-form');
				}
			}
			else {
				setTimeout("YAHOO.util.Connect.asyncRequest('GET', '/Mercury/Pages/AJAX/DefaultSearchTemplate.aspx"+qString.replace(/'/g, "&#39;")+"&tDomId=refineT', {success: TGN.SM.LoadModTemplate, argument:['refine','refineT',"+clearP+"], failure: TGN.SM.HandleFailure})",1);
			}
		}
		if(typeof TGN.KeyWatcher != 'undefined') {
			TGN.KeyWatcher.enable();
		}

		TGN.SM.ShowRefineLock = true;
	};
/* Refine Search Rewrite done */

	TGN.SM.getStyle = function(el,prop){
		return null;
	};
	if (document.body.currentStyle)
		TGN.SM.getStyle = function(el,prop){
			return el.currentStyle[prop];
		};
	else if (window.getComputedStyle)
		TGN.SM.getStyle = function(el,prop){
			return document.defaultView.getComputedStyle(el,null).getPropertyValue(prop);
		};
	TGN.SM.FocusFirstInput = function(root){
		try {
			var el = $(root).getElementsByTagName('input');
			var t=null;
			for (var i = 0, l = el.length; i < l; i++) {
				t=el[i].type;
				if (!el[i].disabled && !el[i].readOnly && ('text'==t || 'password'==t)) {
					if(TGN.SM.isDisplayed(el[i])){
						var fEl = $(el[i].id);
						if(fEl.value != null && fEl.value == ""){
							setTimeout(function(){if(fEl.value == '')try{fEl.focus();}catch(e){}},1);
						}
						break;

					}
				}
			}
		} catch (e) { }
	};
	TGN.SM.isDisplayed = function(el) {
		var frm=el.form;
		while(el!= frm) {
			if(TGN.SM.getStyle(el,"display")=="none" || TGN.SM.getStyle(el,"visibility")=="hidden")
				return false;
			else
				el=el.parentNode;
		}
		return true;
	};
//SM Static Methods done

TGN.SM.GetHitReason = function(type){
	switch(type)
	{
	case "exact":
		return " matched exactly.";
		break;
	case "wildcard":
		return " matched a specified wildcard.";
		break;
	case "normalized":
		return " matched because of a normalized name match or a place authority lookup match.";
		break;
	case "initial":
		return " matched because the first letter of a specified name matches this initial.";
		break;
	case "soundex":
		return " matched based on Soundex which matches mispelled names or names that sound similar when pronounced (e.g. Smith, Smyth, and Smythe all sound alike).";
		break;
	case "proximity":
		return " matched because it was close to a date or location specified.";
		break;
	case "range":
		return " matched because it was within a range of dates, numbers, or text strings.";
		break;
	case "county":
		return " matched because the location specified does not correspond exactly but is contained within the same county.";
		break;
	case "state":
		return " matched because the location specified does not correspond exactly but is contained within the same state.";
		break;
	case "country":
		return " matched because the location specified does not correspond exactly but is contained within the same country.";
		break;
	default:
		break;
	}
	return "";
};
TGN.SM.GetHitShortReason = function(type){
	switch(type)
	{
	case "exact":
		return " matched exactly.";
		break;
	case "wildcard":
		return " matched a wildcard.";
		break;
	case "normalized":
		return " matched a normalized name or place.";
		break;
	case "initial":
		return " matched first letter of a name.";
		break;
	case "soundex":
		return " matched based on Soundex.";
		break;
	case "proximity":
		return " matched by proximity.";
		break;
	case "range":
		return " matched range of dates, numbers, or text strings.";
		break;
	case "county":
		return " matched because location is contained within the same county.";
		break;
	case "state":
		return " matched because location but is contained within the same state.";
		break;
	case "country":
		return " matched because location is contained within the same country.";
		break;
	default:
		break;
	}
	return "";
};
TGN.SM.HideRecordHits = function(){
	if (null != TGN.SM.HitDetailPanel){
		TGN.SM.HitDetailPanel.hide();
		TGN.SM.HitDetailPanel.destroy();
		TGN.SM.HitDetailPanel = null;
	}
};
TGN.SM.IndivRecCallback = {
// Callback object with success and failure members defined inline.
	success: function(o) {
		//success handler code
		var rXml = o.responseXML;
		var lbl, val;
		if(rXml != undefined){
			var fields = rXml.selectNodes("/response/record/field");
			for (var i = 0, l = fields.length; i < l; i++)
			{
				lbl = TGN.SM.GetText(fields[i].childNodes[0]);
				if (lbl != "DBTitle" && lbl != "ImageID")
				{
					val = TGN.SM.GetText(fields[i].childNodes[1]);
				}
			}
		}

	},
	failure: function(o) {/*failure handler code*/debugger;},
	argument: []
};
TGN.SM.ShowRecordHits = function(){
		var div = document.createElement('div');
		div.setAttribute('id','HitDetail');
		document.body.appendChild(div);
		var hitWid = 450;
		var hr='<table  border="0" cellpadding="0" cellspacing="0" class="srchTerms">';
		var ob = document.getElementById('searchDescCategory');
		if (null != ob)
			hr+='<tr><td>' + 'Category:' + '</td><td>' + TGN.SM.GetText(ob) + '</td></tr>';
		var ids = ['Name','Birth','Death','FamilyMembers','Migration','MilitaryService','Marriage','Other'];
		for (j in ids)
		{
			ob = document.getElementById('refine_'+ids[j]+'_mod');
			if (undefined != ob)
			{
				var lbls = ob.getElementsByTagName('strong');
				var spans = ob.getElementsByTagName('span');
				if (spans.length > 0)
				{
					var txt = TGN.SM.GetText(spans[0]);
					if (txt != null && txt.length > 0)
						hr+='<tr><td>' + TGN.SM.GetText(lbls[0]) + '</td><td>' + txt + '</td></tr>';
				}
			}
		}
		hr += '</table>';
		
		var record = $D.getAncestorByClassName(this, 'record');
		if (null != record)
		{
			var hov = $D.getElementsByClassName('srchFoundDB', 'span', record);
			if (hov.length > 0)
			{
				var hovHtml = hov[0].parentNode.innerHTML;
				var start = hovHtml.indexOf("showIndiv2(");
				if (start != -1)
				{
					start += 11;
					var end = hovHtml.indexOf(")", start);
					if (end != -1)
					{
						// params[0] = theEvent
						// params[1] =  theDB
						// params[2] =  theRec
						// params[3] =  headerTxt
						// params[4] =  subDb
						// params[5] =  iid
						// params[6] =  rc
						// params[7] =  xtraQSParam
						// params[9] =  noHover
						var params = hovHtml.slice(start, end).replace(/'/g, "").split(",");
						var ajUrl = "/Mercury/Pages/Ajax/IndivRec.aspx?IndivAjax=1&recid="+params[2]+"&db="+params[1]+"&output=xml&Use302Redirect=t";

						if(params[4]) ajUrl += "&noSub=1";
						if( params[9] ) ajUrl += "&NonHover=1";

						if(params[5] != null && params[6] != null)
							ajUrl += "&iid=" + params[5] + "&rc="+ params[6];

						if( params[7] != null) ajUrl += "&" + params[7];
						var transaction = YAHOO.util.Connect.asyncRequest('GET', ajUrl, TGN.SM.IndivRecCallback, null);  		

					}
				}
			}
			hr += '<div id="results"><div id="results-main"><table  border="0" cellpadding="0" cellspacing="0" class="s_gsResults">' + record.innerHTML + '</table></div></div><div id="hitIndiv"></div><br />';
			hitWid = record.offsetWidth + 52;
		}
		hr += TGN.SM.HitReason(this);
		hr += '<br /><a class="closeBtn btn btn-cta" href="javascript:TGN.SM.HideRecordHits()"><span>Close</span></a>';
		TGN.SM.HitDetailPanel = new YAHOO.widget.Panel('HitDetail',
		{
			close: true,
			draggable: true,
			modal: true,
			visible: true,
			width: hitWid,
			underlay:'none',
			effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.5}
		} );
		TGN.SM.HitDetailPanel.setHeader("<h3>Why Am I Seeing This Record?</h3>");
		TGN.SM.HitDetailPanel.setBody(hr);
		TGN.SM.HitDetailPanel.render(document.body);
		
		TGN.SM.PositionAndShow(TGN.SM.HitDetailPanel);

};
TGN.SM.HitReason = function(star){
	var hr="";
	var reasons=star.getElementsByTagName("hlt");
	if (reasons.length != 0){
		hr="This record is dispayed as a match for your search because the following items matched exactly or were considered similar to the terms you specified:<ul>";
		for(var r=0, l=reasons.length; r < l; r++){
			var att = reasons[r].attributes;
			hr+="<li>\"<strong>"+att['match'].nodeValue+"</strong>\" was found "+att['count'].nodeValue+" times in this record and "+TGN.SM.GetHitReason(att['type'].nodeValue)+" Total score: "+att['score'].nodeValue+"</li>";
		}
		hr += "</ul>The overall score calculated for this record was " + star.getAttribute('score');
	}
	return hr;
};


TGN.SM.HitReasonTip = function(star){
	var hr="";
	var hlts=star.getElementsByTagName("hlt");
	if (hlts != null && hlts.length > 0){
		var reasons = [];
		for (var j = 0, l = hlts.length; j < l; j++)
		{
			var itype = 99;
			switch(hlts[j].getAttribute('type'))
			{
			case "exact":
				itype = 1;
				break;
			case "wildcard":
				itype = 2;
				break;
			case "normalized":
				itype = 3;
				break;
			case "initial":
				itype = 4;
				break;
			case "soundex":
				itype = 5;
				break;
			case "proximity":
				itype = 6;
				break;
			case "range":
				itype = 7;
				break;
			case "county":
				itype = 8;
				break;
			case "state":
				itype = 9;
				break;
			case "country":
				itype = 10;
				break;
			default:
				itype = 99;
				break;
			}
			hlts[j].setAttribute('itype', itype);
			reasons.push(hlts[j]);
		}
		reasons.sort(function(a,b){
			var at=a.getAttribute('itype');
			var bt=b.getAttribute('itype');
			if (at == bt)
				return b.getAttribute('score') - a.getAttribute('score');
				
			return at - bt;
			});
		var lastType = "";
		hr += "<ul>";
		for(var r in reasons){
			var att = reasons[r].attributes;
			var t = att['type'].nodeValue;
			var m = "\"<strong>"+att['match'].nodeValue+"</strong>\"";
			var c = att['count'].nodeValue != null ? 1*att['count'].nodeValue : 0;
			if (c > 1)
				m += " (" + c + " occurrences)";
			if (lastType == t)
			{
				var n = r*1;
				if (n == reasons.length - 1 || t != reasons[n + 1].getAttribute('type'))
					hr+=" and " + m;
				else
					hr+=", " + m;
			}
			else
			{
				if (r == 0)
					hr += "<li>" + m;
				else
					hr += TGN.SM.GetHitShortReason(lastType)+ "</li><li>" + m;
				lastType = t;
			}
		}
		hr += TGN.SM.GetHitShortReason(lastType) + "</li></ul><br />Click for detailed reasons.";
	}
	return hr;
};
TGN.SM.HitHighlightInit = function(){
	var records = YAHOO.util.Dom.getElementsByClassName("record", "tr", $("results-main"));
	var spanId=0, starId=0;
	var fieldTips=new Array();
	var recordTips=new Array();
	for (var r in records){
		var spans = records[r].getElementsByTagName("span");
		for (var s=0, l = spans.length; s < l; s++){
			if (spans[s].className.indexOf("stars") > -1){
				var star = spans[s];
				star.id = "star"+starId++;
				star.onclick=TGN.SM.ShowRecordHits;
				var reason=TGN.SM.HitReasonTip(star);
				if (reason.length > 0){
					star.title=reason;
					recordTips.push(star.id);
				}
			}
			if (spans[s].className.indexOf("srchMatch") > -1/* || spans[s].className.indexOf("srchHit") > -1*/)
			{
				spans[s].id = 'srchMatch' + spanId++;
				var hit = TGN.SM.GetText(spans[s]);
				//score – integer between 0 and 1000
//				var score = 0;
//				if (spans[s].getAttribute('score') != null)
//					Math.round((spans[s].getAttribute('score')*100)/1000);
//				//type – string indicating an exact match to a search term or an expanded match as below:
				var type = spans[s].getAttribute('type');
				if (type != null)
					spans[s].title = "<strong>" + hit + "</strong>" + TGN.SM.GetHitShortReason(type); //+ "  " + score + "%";
				fieldTips.push(spans[s].id);
			}
		}
	}
	if (fieldTips.length !=0){
		var fieldTT=new YAHOO.widget.Tooltip('matchFieldTips',{appendtodocumentbody:true,context:fieldTips,width:'300px',autodismissdelay:10000,effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.2}});
		fieldTT.element.className+=' alert';
		//fieldTT.setHeader('<h5>How Did This Match?</h5>');
	}
	if (recordTips.length !=0){
		var recordTT=new YAHOO.widget.Tooltip('whyMatchTip',{appendtodocumentbody:true,context:recordTips,width:'300px',autodismissdelay:15000,effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.2}});
		recordTT.element.className+=' alert';
		recordTT.setHeader('<h5>Why Am I Seeing This Record?</h5>');
	}
};
TGN.SM.GetText = function(el)
{
	if (el.innerText != undefined)
		return el.innerText;
	if (el.textContent != undefined)
		return el.textContent;
	if (el.innerHtml != undefined)
		return el.innerHtml;
	return null;
};
TGN.SM.SetText = function(el, txt)
{
	if (el.innerText != undefined)
		el.innerText = txt;
	if (el.textContent != undefined)
		el.textContent = txt;
};
//YAHOO.util.Event.on(window, 'load', TGN.SM.HitHighlightInit);
//

/***************************************/
/* BEG Merge browseDate.js information */
/***************************************/

TGN.Search.BrowseDate.Calendar = function (Month,Year)
{
	var output = '';
	output += '<div id="browse_body"><table width="408" id="calendar"><tr align="center" valign="top">';
	output += '<td height="30" colspan="7"><nobr><select id="Month" name="Month" onchange="TGN.Search.BrowseDate.changeMonth();">';
	var monthIndex = 0;
	for (im = 0; im < availMonths[Year].length; im++) 
	{
		if (availMonths[Year][im] == Month)
		{
			output += '<option value="' + availMonths[Year][im] + '" SELECTED>' + monthNames[availMonths[Year][im]-1] + '<\/option>';
			monthIndex = im;
		}
		else
			output += '<option value="' + availMonths[Year][im] + '">' + monthNames[availMonths[Year][im]-1] + '<\/option>';  
	}
	output += '<\/select>&nbsp;&nbsp;<select ID="Year" NAME="Year" onChange="TGN.Search.BrowseDate.changeYear();">';
	for(iy = 0; iy < years.length; iy++)
	{
		if (years[iy] == Year)
			output += '<option value="' + years[iy] + '" SELECTED>' + years[iy] + '<\/option>';
		else
			output += '<option value="' + years[iy] + '">'          + years[iy] + '<\/option>';
	}
	output += '<\/select></nobr><\/td><\/tr>';
	firstDay = new Date(Year,Month-1,1);
	startDay = firstDay.getDay();
	if (((Year % 4 == 0) && (Year % 100 != 0)) || (Year % 400 == 0))
		browseDateDays[1] = 29;
	else
		browseDateDays[1] = 28;
	output += '<tr id="days">';
	for (i=0; i<7; i++)
		output += '<td>' + dow[i] +'<\/td>';
	output += '<\/tr><tr class="week">';
	var column = 0;
	for (i=0; i<startDay; i++, column++)
		output += '<td class="blank">&nbsp;<\/td>';
	for (i=1; i<=browseDateDays[Month-1]; i++, column++) 
	{
		if(availDays[Year][monthIndex] & (1 << (i-1)))
			output += '<td><a href="javascript:TGN.Search.BrowseDate.submitDay(\'' + dbid + '\',' + i + ',' + Month + ',' + Year + ')">' + i + '<\/a><\/td>';
		else
			output += '<td class="blank">' + i + '<\/td>';
		if (column == 6 && i != browseDateDays[Month-1]) 
		{
			output += '<\/tr><tr class="week">';
			column = -1;  
		} 
	}
	if (column > 0) 
	{
		for (i=1; column<7; i++, column++)
			output +=  '<td class="blank">&nbsp;<\/td>';
	}
	output += '<\/tr><\/table></div>';
	return output;
};

TGN.Search.BrowseDate.submitDay = function (id,day,month,year)
{
    TGN.Search.BrowseDate.submitFromCalendar(day, month, year);
    setDictionaryCookie("BROWSES", 'bm', month, null, null);
    setDictionaryCookie("BROWSES", 'by', year, null, null);
};

TGN.Search.BrowseDate.submitFromCalendar = function(day,month,year)
{
	document.location = "/Browse/view.aspx?dbid=" + dbid + "&path=" + year + "." + month + "." + day;
};

TGN.Search.BrowseDate.fnReplaceHtml = function (el, html) 
{
	var oldEl = YAHOO.util.Dom.get(el);
	
	if ('undefined' != typeof oldEl && null != oldEl) {
		var newEl = document.createElement(oldEl.nodeName);
		
		// Preserve the element's id and class (other properties are lost)
		newEl.id = oldEl.id;
		newEl.className = oldEl.className;

		// Replace the old with the new
		newEl.innerHTML = html;
		oldEl.parentNode.replaceChild(newEl, oldEl);

		/* Since we just removed the old element from the DOM, return a reference to the new element, which can be used to restore variable references. */
	}
	
	return newEl;
};

TGN.Search.BrowseDate.reload = function (month,year)
{
	var cs = YAHOO.util.Dom.get('CalendarSpot');
	var ca = TGN.Search.BrowseDate.Calendar(month,year);
	
    setDictionaryCookie("BROWSES", 'bm', month, null, null);
    setDictionaryCookie("BROWSES", 'by', year, null, null);
	
	TGN.Search.BrowseDate.fnReplaceHtml(cs, ca);
};

TGN.Search.BrowseDate.changeMonth = function ()
{
    var oMon = $("Month");
    var oYear = $("Year");
    var month = oMon.options[oMon.selectedIndex].value;
    var year = oYear.options[oYear.selectedIndex].value;
	TGN.Search.BrowseDate.reload(month,year);
	oMon.focus();
};

TGN.Search.BrowseDate.changeYear = function ()
{
    var oMon = $("Month");
    var oYear = $("Year");
    var month = oMon.options[oMon.selectedIndex].value;
    var year = oYear.options[oYear.selectedIndex].value;
	var bValidMonth = false;
	for(i = 0; i < availMonths[year].length; i++)
	{
		if(month == availMonths[year][i])
		{
			bValidMonth = true;
			break;
		}
	}
	if(!bValidMonth)
		month = availMonths[year][0];
	TGN.Search.BrowseDate.reload(month,year);
	oYear.focus();
};

TGN.Search.BrowseDate.buildCalendar = function ()
{
	var bd;
    var by = null;
    var bm = null;
    var path = getQueryStringParameter("path");
	if(null != path)
	{
		var parts = path.split('.');
		if(parts.length > 0 && parts[0].length == 4)
		{
			by = parts[0];
			if (parts.length > 1)
			    bm = parts[1];
			else
			    bm = availMonths[by][0];
		}
	}
	if (null == bm || null == by || null == availMonths[by]) {

	    by = getDictionaryCookie("BROWSES", "by");
	    bm = getDictionaryCookie("BROWSES", "bm");
	}

	if(null == bm || null == by || null == availMonths[by])
	{
		by = years[years.length-1];
		bm = availMonths[by][availMonths[by].length-1];
	}
	
	bd = TGN.Search.BrowseDate.Calendar(bm,by);
	TGN.Search.BrowseDate.fnReplaceHtml('CalendarSpot', bd);
};

var browseDateDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

/***************************************/
/* END Merge browseDate.js information */
/***************************************/
