
// Globals
var xMouse = 0;
var yMouse = 0;
var bCancelEvents = false;
var sDefaultURI; // URI of page with query string stripped
var bUserTyped = false;
var bSelectBoxChanged = 0;

function bodyLoad()
{
	Info.init();
	//Initialize history
	dhtmlHistory.initialize();
  
	// determine our current location so we can
	// initialize ourselves at startup
	var initialLocation = 
		dhtmlHistory.getCurrentLocation();
  
	// if no location specified, use the default
  	if (initialLocation == null)
    		initialLocation = window.location.href;

	sDefaultURI = Lang.getString("FB_DEFAULT_URL");
	ClockCalBinding.init();
	shrinkImagesToFit();
	hideMiniReports();
	ShadowManager.preload();
	initializeListView();
	for(var i=0; i < rgHelpTips.length; i++)
	{
		if ( rgHelpTips[i] != '' && elById(rgHelpTips[i]) != null )
			elById(rgHelpTips[i]).style.display = 'none';
	}

	// add ourselves as a listener for history
	// change events
	dhtmlHistory.addListener(handleHistoryChange);

	if (window.opera)
	{
		window.document.onkeypress = handleDocumentKeydown;
		window.document.onkeyup = handleDocumentKeyup;
	}
	else if (document.all)
	{ 
		window.document.onkeydown = handleDocumentKeydown;
		window.document.onkeyup = handleDocumentKeyup;
	}
	else
	{
		window.document.captureEvents(Event.KEYDOWN);
		window.document.captureEvents(Event.KEYUP);
		window.document.captureEvents(Event.MOUSEMOVE);
		window.document.onkeypress = handleDocumentKeydown;
	}

	window.document.onmouseup = mouseupDocument;
	window.document.onmousemove = mousemoveDocument;
	
	// IE/Safari: don't allow selection during column drag'n'drop, resize, etc
	window.document.onselectstart = function() {return !bCancelEvents;}
	window.onresize = resizeWindow;

	window.onscroll = ListControl.scrollWindow;
	
	KeyManager.setupGridBrowser();
	
	setFocusToWindow();
}

function bodyUnload()
{
	if (SelectionManager) SelectionManager.reset();
}

function setPageTitle()
{
	if (!XMLParser) XMLParser = new XMLParser();
	var sTitle = XMLParser.getCustomTagValueFrom(document, "fb:pagetitle");
	var sFilterName = XMLParser.getCustomTagValueFrom(document, "fb:filtername");
	if (sTitle)
	{
		ListControl.titlePrototype(sTitle);
		ListControl.filterName(sFilterName);
		if (sFilterName)
			document.title = swap1(ListControl.titlePrototype(), ListControl.filterName());
	}
}

function getInnerHTML(sId)
{
	var o = elById(sId);
	if (!o) return null;
	return o.innerHTML;
}

function resizeWindow(e)
{
	if (ListControl) ListControl.maximizeNavBar();
}

function mouseupDocument(e)
{
	SelectionManager.stopDragging();
	GridControl.stopActions();
	EditableTableManager.stopDragging();
}

// Record current mouse position
//
function mousemoveDocument(e)
{
	if (window.Event)
	{
		xMouse = e.pageX;
		yMouse = e.pageY;
		notifyMouseMovement();
		return;
	}
	
	xMouse = event.clientX;
	yMouse = event.clientY;
	
	if (document.documentElement.scrollLeft)	xMouse += document.documentElement.scrollLeft;
	else if (document.body.scrollLeft)			xMouse += document.body.scrollLeft;
	
	if (document.documentElement.scrollTop)		yMouse += document.documentElement.scrollTop;
	else if (document.body.scrollTop)			yMouse += document.body.scrollTop;
	
	notifyMouseMovement();
}

function notifyMouseMovement()
{
	GridControl.notifyMovement();
	SelectionManager.notifyMovement();
	EditableTableManager.notifyMovement();
}

function hideMiniReports()
{
	if (null == XMLParser.getCustomTagValueFrom(document, "fb:minireport")) return;
	
	var rgAs = document.getElementsByTagName('a');
	for(var i=0; i < rgAs.length; i++)
	{
		var el = rgAs[i];
		if ( el.id.substring(0, 5) == 'link_' )
		{
		 var id = el.id.substring(5);
		 if ( getCookie('fb_' + id) == '0')
		 {
			toggleVisible( elById(id) );
			elById('link_' + id).className = 'expand';
		 }
		}
	}
}

function handleDocumentKeydown(keyStroke)
{
	var keyCode = getKeyCode(keyStroke);

	// For shift key on list page
	SelectionManager.checkboxDown(keyCode);

	// Do hotkeys
	KeyManager.keystroke(keyStroke);
	
	if (keyCode == 27)
	{
		Process.haltAll();
		GridControl.cancelActions();
	}
}

function isTab(keyStroke)
{
	var keyCode = getKeyCode(keyStroke);
	// Safari reports shift-tab as 25

	return (keyCode == 9 || (window.safari && keyCode == 25));
}

function handleDocumentKeyup(keyStroke)
{
	var keyCode = getKeyCode(keyStroke);
	// for shift key on list page
	SelectionManager.checkboxUp(null, keyStroke);
	return true;
}

function handleHistoryChange(newLocation, historyData)
{
	if (ViewHistoryManager) ViewHistoryManager.handleHistoryChange(newLocation, historyData);
	// add other handleHistoryChange methods here
}


function shrinkImagesToFit()
{
	if (elById("bugGrid")) return; // Don't need to shrink any images on the grid
	var rgImages = document.getElementsByTagName("img");
	var i;
	for (i=0; i<rgImages.length; i++)
	{
		if (rgImages[i].getAttribute("inline") != null)
		{
			rgImages[i].xwidth = rgImages[i].width;
			rgImages[i].xheight = rgImages[i].height;
			var bWidthChanged = false;
			if (rgImages[i].width > 720)
			{
				bWidthChanged = true;
				rgImages[i].width = 720;
			}
			if (rgImages[i].height > 250)
			{
				if (bWidthChanged)
				{
					rgImages[i].width = rgImages[i].xwidth / (rgImages[i].xheight / 250);
				}
				rgImages[i].height = 250;
			}
		}
	}
}

function showSearchingInfo( e, oSource )
{
	if (e && e.metaKey) return; // case 325877 - don't show search banner if opening in new tab on safari
	if (oSource && oSource.form && oSource.form.searchFor)
	{
		if (oSource.form.searchFor.value.length > 0)
		{
			Info.show(Lang.getString("FB_SEARCHING"));
		}
	}
}

function showError( sErr )
{
	var el = elById( 'helpbox' );
	if ( el )
	{
		el.innerHTML = "<font color='red'>" + sErr + "</font>";
		if ( el.style.display == 'none' )
			toggleVisible( el );
	}
}

function showHelp( id )
{
	var el = elById( id + "_help" );
	var help = elById( 'helpbox' );
	if ( help != null && el != null )
	{
		help.innerHTML = el.innerHTML;
		help.style.display = '';
	}
	else if ( help != null )
		help.style.display = 'none';
}

function hideHelp( id )
{
	var el = elById( "helpbox" );
	if (el) el.style.display = "none";
}

function quickSubscription( oLink, bSubscribe )
{
	var oContainer = elById("containerSubscribe");
	if (oContainer)
	{
		var oSubscribeSpan = XMLParser.getNodeUsingIdFrom(oContainer, "span", "subscribe");
		var oUnsubscribeSpan = XMLParser.getNodeUsingIdFrom(oContainer, "span", "unsubscribe");
		if (oSubscribeSpan && oUnsubscribeSpan)
		{
			oSubscribeSpan.style.display = (bSubscribe ? "none" : "");
			oUnsubscribeSpan.style.display = (bSubscribe ? "" : "none");
		}
	}
	
	sendNewSubscriptionRequest(oLink.href.replace("?", "?fAlaCarte=1&"));
}

function sendNewSubscriptionRequest( sHref )
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('sendNewSubscriptionRequest("'+sHref+'")', 500);
	}
	else
	{
		// fire and forget
		oAjaxRequest.initialize();
		oAjaxRequest.open("GET", sHref, true);
		oAjaxRequest.send(null);
	}
}

function quickDiscussModerate( oLink, ixDiscussTopic, fDelete )
{
	var oControls = elById("containerDiscussAdmin" + ixDiscussTopic)
	if (oControls)
	{
		var rgControlSpans = XMLParser.getNodeArrayFrom(oControls, "span");
		for (var ix = 0; ix < rgControlSpans.length; ix++)
		{
			if (rgControlSpans[ix].id)
			{
				if (rgControlSpans[ix].id == (fDelete ? "adminDeleting" : "adminApproving"))
					rgControlSpans[ix].style.display = "";
				else
					rgControlSpans[ix].style.display = "none";
			}
		}
	}
	
	sendNewDiscussModerateRequest(oLink.href.replace("?", "?fAlaCarte=1&"));
}

function sendNewDiscussModerateRequest( sHref )
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('sendNewDiscussModerateRequest("'+sHref+'")', 500);
	}
	else
	{
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeDiscussModeration);
		oAjaxRequest.open("GET", sHref, true);
		oAjaxRequest.send(null);
	}
}

function resultChangeDiscussModeration()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	
	var ixDiscussTopic = XMLParser.getTextFrom(oAjaxRequest.responseXML(), "ixDiscussTopic");
	if (ixDiscussTopic == null) return;
	var oContainer = elById("containerDiscussTopic" + ixDiscussTopic);
	var sHTML = XMLParser.getCDataFrom(oAjaxRequest.responseXML(), "sHTML");
	if (!oContainer || !sHTML || !sHTML.length) return;
	oContainer.innerHTML = sHTML;
}

var oElemQueued;
function quickEditFixFor(sTableId, ixProject, oElem)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		oElemQueued = oElem;
		setTimeout('quickEditFixFor("' + sTableId + '",'+ixProject+',null)', 500);
	}
	else
	{
		if (!oElem) oElem = oElemQueued;
		if (!oElem) return;
		
		var sPre = eval("oElem.form.preFixFor"+sTableId+".value");
		var fAnyProject = eval("oElem.form.fAnyProjectToEdit"+sTableId+".value");
		var ixFixFor = eval("oElem.form.ixFixForToEdit"+sTableId+".value");
		var sFixFor = encodeURIComponent(eval("oElem.form.sFixForToEdit"+sTableId+".value"));
		var sDate = eval("oElem.form.sDateToEdit"+sTableId+".value");
		
		var oBox1 = eval("oElem.form.fDeletedToEdit"+sTableId+"[0]");
		var oBox2 = eval("oElem.form.fDeletedToEdit"+sTableId+"[1]");
		var fDeleted = oBox1.checked ? oBox1.value : oBox2.value;
		
		sFixForTableToEdit = "FixForTable" + sTableId;
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeFixFor);
		oAjaxRequest.open("POST", sDefaultURI, true);
		oAjaxRequest.send("fAlaCarte=1&pre="+sPre+"&ixProject=" + ixProject + "&ixFixFor=" + ixFixFor + 
						  "&sFixFor=" + sFixFor + "&sDate=" + sDate + "&fDeleted=" + fDeleted + "&fAnyProject=" + fAnyProject);
	}
}

function quickEditArea(ixProject, oElem)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		oElemQueued = oElem;
		// request is already busy, wait half a sec and try again
		setTimeout('quickEditArea('+ixProject+',null)', 500);
	}
	else
	{
		if (!oElem) oElem = oElemQueued;
		if (!oElem) return;
		
		var sPre = oElem.form.preToEdit ? oElem.form.preToEdit.value : "";
		var ixArea = oElem.form.ixToEdit ? oElem.form.ixToEdit.value : "";
		var sArea = oElem.form.sToEdit ? encodeURIComponent(oElem.form.sToEdit.value) : "";
	
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeArea);
		oAjaxRequest.open("POST", sDefaultURI, true);
		oAjaxRequest.send("fAlaCarte=1&pre="+sPre+"&ixProject=" + ixProject + "&sArea=" + sArea + "&ixArea=" + ixArea);
	}
}

function quickEditSnippets(oElem)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		oElemQueued = oElem;
		setTimeout('quickEditSnippets(null)', 500);
	}
	else
	{
		if (!oElem) oElem = oElemQueued;
		if (!oElem) return;
		
		var sPre = oElem.form.preToEdit ? oElem.form.preToEdit.value : "";
		var ixSnippet = oElem.form.ixToEdit ? oElem.form.ixToEdit.value : "";
		var ixPerson = oElem.form.ixPersonToEdit ? oElem.form.ixPersonToEdit.value : "";
		var fGlobal = oElem.form.fGlobalToEdit ? oElem.form.fGlobalToEdit.value : "";
		var sName = oElem.form.sNameToEdit ? encodeURIComponent(oElem.form.sNameToEdit.value) : "";
		var sSnippet = oElem.form.sToEdit ? encodeURIComponent(jsToVbNewLines(oElem.form.sToEdit.value)) : "";
		var sComment = oElem.form.sCommentToEdit ? encodeURIComponent(oElem.form.sCommentToEdit.value) : "";
		
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeSnippet);
		oAjaxRequest.open("POST", sDefaultURI, true);
		oAjaxRequest.send("fAlaCarte=1&pre="+sPre+"&ixSnippet=" + ixSnippet + "&sName=" + sName + 
						  "&ixPerson=" + ixPerson + "&fGlobal=" + fGlobal + "&s=" + sSnippet+ "&sComment=" + sComment);
	}
}

function quickDeleteSnippet(ixSnippet)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('quickDeleteSnippet('+ixSnippet+')', 500);
	}
	else
	{
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeSnippet);
		oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pre=preDeleteSnippet&ixSnippet=" + ixSnippet, true);
		oAjaxRequest.send(null);
	}
}

function quickDeleteAttachment(oElem)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('quickDeleteAttachment('+ixAttachment+')', 500);
	}
	else
	{
		var ixBug = oElem.form.ixBugToEdit ? oElem.form.ixBugToEdit.value : "";
		var ixBugEvent = oElem.form.ixBugEventToEdit ? oElem.form.ixBugEventToEdit.value : "";
		var ixAttachment = oElem.form.ixToDelete ? oElem.form.ixToDelete.value : "";
	
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeAttachment);
		oAjaxRequest.ixContainerTarget = ixBugEvent; // store ixBugEvent so we know which DOM container to fill when result returns
		oAjaxRequest.open("GET", sDefaultURI + 
								"?fAlaCarte=1&pre=preDeleteFile&pg=pgAlaCarteAttachmentList&ixBugEvent=" + ixBugEvent + 
								"&ixBug=" + ixBug + "&ixAttachment=" + ixAttachment + "&command=edit", true);
		oAjaxRequest.send(null);
	}
}

function quickEditHoliday(oElem)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		oElemQueued = oElem;
		// request is already busy, wait half a sec and try again
		setTimeout('quickEditHoliday(null)', 500);
	}
	else
	{
		if (!oElem) oElem = oElemQueued;
		if (!oElem) return;
		
		var sPre = oElem.form.preHolidayToEdit ? oElem.form.preHolidayToEdit.value : "";
		var ixHoliday = oElem.form.ixHolidayToEdit ? oElem.form.ixHolidayToEdit.value : "";
		var sHoliday = oElem.form.sHolidayToEdit ? encodeURIComponent(oElem.form.sHolidayToEdit.value) : "";
		var dtHoliday = oElem.form.dtHolidayToEdit ? oElem.form.dtHolidayToEdit.value : "";
		
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeHoliday);
		oAjaxRequest.open("POST", sDefaultURI, true);
		oAjaxRequest.send("fAlaCarte=1&pre="+sPre+"&ixHoliday=" + ixHoliday + "&sHoliday=" + sHoliday + "&dtHoliday=" + dtHoliday);
	}
}

function quickEditReleaseNotes(oElem)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		oElemQueued = oElem;
		// request is already busy, wait half a sec and try again
		setTimeout('quickEditReleaseNotes(null)', 500);
	}
	else
	{
		if (!oElem) oElem = oElemQueued;
		if (!oElem) return;
		
		var sPre = oElem.form.preToEdit ? oElem.form.preToEdit.value : "";
		var sPg = oElem.form.pgToEdit ? oElem.form.pgToEdit.value : "";
		var ixBug = oElem.form.ixToEdit ? oElem.form.ixToEdit.value : "";
		var sReleaseNotes = oElem.form.sReleaseNotesToEdit ? encodeURIComponent(jsToVbNewLines(oElem.form.sReleaseNotesToEdit.value)) : "";

		oAjaxRequest.sContainerId = oElem.form.sContainerId ? oElem.form.sContainerId.value : "";
		
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeReleaseNotes);
		oAjaxRequest.open("POST", sDefaultURI, true);
		oAjaxRequest.send("fAlaCarte=1&pg="+sPg+"&pre="+sPre+"&ixBug=" + ixBug + "&sReleaseNotes=" + sReleaseNotes);
	}
}

function quickDeleteHoliday(ixHoliday)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('quickDeleteHoliday('+ixHoliday+')', 500);
	}
	else
	{
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeHoliday);
		oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pre=preDeleteHoliday&ixHoliday=" + ixHoliday, true);
		oAjaxRequest.send(null);
	}	
}

function quickDeleteArea(ixProject, ixArea)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('quickDeleteArea('+ixProject+','+ixArea+')', 500);
	}
	else
	{
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeArea);
		oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pre=preDeleteArea&ixProject=" + ixProject + "&ixArea=" + ixArea, true);
		oAjaxRequest.send(null);
	}
}

function quickDeleteFilter(ixFilter)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('quickDeleteFilter('+ixFilter+')', 500);
	}
	else
	{
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeFilter);
		oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pre=preDeleteFilter&ixFilter=" + ixFilter, true);
		oAjaxRequest.send(null);
	}
}

function changeFilterName(sFilter)
{
	var oFilterLabel = elById("idFilterLinkPopRefine");
	if (oFilterLabel) oFilterLabel.innerHTML = escapeLtGt(sFilter);
	document.title = swap1(ListControl.titlePrototype(), sFilter);
	ListControl.filterName(sFilter);
	ListControl.updateSignature();
}

function quickFilterSaveAs(oElem)
{
	if ((!ListControl.getListDiv()) || (!oElem.form.sFilterName)) return false;
	var sFilter = trim(oElem.form.sFilterName.value);
	if (!sFilter.length) return true; // do nothing
	
	Info.showBriefly(swap1(Lang.getString("FB_CURRENT_FILTER_SAVED_AS"), encodeLTGT(sFilter)), null, null);
	
	sendFilterSaveAsRequest(sFilter);
	changeFilterName(sFilter);
	Icons.changeIcons(Icons.CONFIRMED, null, null, Icons.ENABLED);
	theMgr.hideAllPopups();
	return true;
}

var oFilterSaveRequest;
function sendFilterSaveAsRequest(sFilterName)
{
	if (!oFilterSaveRequest) oFilterSaveRequest = new AjaxRequest();
	if (oFilterSaveRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('sendFilterSaveAsRequest("'+sFilterName+'")', 500);
	}
	else
	{
		oFilterSaveRequest.initialize();
		oFilterSaveRequest.onreadystatechange(resultFilterSaveAs);
		oFilterSaveRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pre=preSaveCurrentFilterAs&pg=pgAlaCarteFilterMenu&sFilterName=" + encodeURIComponent(sFilterName), true);
		oFilterSaveRequest.send(null);
	}
}

function resultFilterSaveAs()
{
	if (!oFilterSaveRequest || !oFilterSaveRequest.isReady()) return;
	var oContainer = ListControl.getFilterMenuContainer();
	if (!oContainer) return;
	var sHTML = XMLParser.getCDataFrom(oFilterSaveRequest.responseXML(), "sHTML");
	if (sHTML && sHTML.length) oContainer.innerHTML = sHTML;
	var ixPerson = XMLParser.getTextFrom(oFilterSaveRequest.responseXML(), "ixPerson");
	var ixFilter = XMLParser.getTextFrom(oFilterSaveRequest.responseXML(), "ixFilter");
	var sFilter = XMLParser.getTextFrom(oFilterSaveRequest.responseXML(), "sFilter");
	if (ixPerson != null && ixFilter != null) setFilterRssHref(ixPerson, ixFilter, sFilter);
}

function resultChangeAttachment()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	EditableTableManager.result('AttachmentList_' + oAjaxRequest.ixContainerTarget, oAjaxRequest.responseXML());
	oAjaxRequest.ixContainerTarget = null;
	shrinkImagesToFit(); // might have replaced some inline images, need to re-shrink
}

function resultChangeArea()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	EditableTableManager.result('AreaTable', oAjaxRequest.responseXML());
}

function resultChangeFilter()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	EditableTableManager.result('FilterTable', oAjaxRequest.responseXML());
}

function resultChangeSnippet()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	var sSnippetJS = XMLParser.getCDataFrom(oAjaxRequest.responseXML(), "sSnippetJS");
	if (sSnippetJS)
	{
		rgSnippet = eval(sSnippetJS);
		populateSnippetSelect();
		refreshSnippetHelper();
	}
	EditableTableManager.result('SnippetTable', oAjaxRequest.responseXML());
}

function resultChangeHoliday()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	EditableTableManager.result('HolidayTable', oAjaxRequest.responseXML());
}

function resultChangeReleaseNotes()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	var oXML = oAjaxRequest.responseXML();
	if (oAjaxRequest.sContainerId && oAjaxRequest.sContainerId.length)
	{
		EditableTableManager.result('ReleaseNotes', XMLParser.getNodeFrom(oXML, "NoteLink"), oAjaxRequest.sContainerId + "Link");
		EditableTableManager.result('ReleaseNotes', XMLParser.getNodeFrom(oXML, "Note"), oAjaxRequest.sContainerId);
	}
	else
	{
		// Update bug events
		var sHTMLBugEvents = XMLParser.getCDataFrom(oXML, "BugEventsHTML");
		if (sHTMLBugEvents) doReplaceBugEvents(sHTMLBugEvents);

		var ixBugEventLatestPre = XMLParser.getTextFrom(oXML, "ixBugEventLatestPre"); // ixLatest before the release note change
		var ixBugEventLatestPost = XMLParser.getTextFrom(oXML, "ixBugEventLatestPost"); // ixLatest after the release note change
		if (updateBugEventLatest(ixBugEventLatestPre, ixBugEventLatestPost))
		{
			// We updated the latest bug event, so we need to update the action buttons
			updateActionButtons(oXML);
		}

		EditableTableManager.result('ReleaseNotes', oAjaxRequest.responseXML());
	}
}


var sFixForTableToEdit;
function resultChangeFixFor()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	EditableTableManager.result(sFixForTableToEdit, oAjaxRequest.responseXML());
}

// quickSortChange
//
// Start a client-side sort using ixColumn
// as the new primary sort
//
// sId - id of link initiating the sort change
// iSortID - sortID to be passed back to FogBugz
//           in order to save filter update
// 
// Return true if eligible for a quick sort,
// otherwise return false
//
function quickSortChange( sId, iSortID )
{
	if (!GridControl.isReady()) return false;
	Info.show(Lang.getString("FB_SORTING"), null, null);
	// Don't quicksortchange if the maximum number of bugs are displayed,
	// because proper sort behavior may require new info from the server
	// ...but always quicksortchange if we're looking at search results
	if (GridControl.isOverflowing() && !GridControl.isSearchResult()) return false;
	// Sort the grid client-side
	setTimeout("GridControl.sortBy('"+sId+"')", 1);
	// Tell FogBugz that the sort changed so it can save the filter
	setTimeout("sendNewSortChangeRequest("+iSortID+")", 1);
	return true;
}

function sendNewSortChangeRequest( iSortID )
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout('sendNewSortChangeRequest('+iSortID+')', 500);
	}
	else
	{
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultChangeSort);
		oAjaxRequest.bDefaultFailureBehavior = false;
		oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pre=preSaveFilterChangeSort&sortID=" + iSortID, true);
		oAjaxRequest.send(null);
	}
}

// resultChangeSort
//
// onreadystatechange handler for AjaxRequest
// called by sendNewSortChangeRequest()
//
function resultChangeSort()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	Icons.changeIcons(Icons.ENABLED, null, null, Icons.DISABLED);
	GridControl.synchServerSort(oAjaxRequest.responseXML());
}

function mousedownColHeader( oHeader )
{
	GridControl.startDragOrResize(oHeader);
}

function mousemoveColHeader( oHeader )
{
	oHeader.style.cursor=GridControl.getHeaderCursor(oHeader);
}

function dblclickColHeader( oHeader )
{
	GridControl.autoResize(oHeader);
}

function mousedownGridRow( ixBug, e )
{
	if (bCancelEvents || (getButtonCode(e) != MOUSE_BUTTON_LEFT)) return;
	var ixRow = GridControl.rowFromBug(ixBug);
	if (ixRow < 0) return;
	SelectionManager.gridClick(ixRow, e.shiftKey, isCtrlOrMeta(e));
	SelectionManager.startDragging();
}

function mouseupGridRow()
{
	removeTextSelections();
}

function dblclickGridRow( ixBug, sURL )
{
	if (bCancelEvents || SelectionManager.lastClickFromCheckbox()) return;
	var ixRow = GridControl.rowFromBug(ixBug);
	if (ixRow < 0) return;
	if (!SelectionManager.isChecked(ixRow)) SelectionManager.gridClick(ixRow, false, false);
	document.location = sURL;
}

function mouseoverGridRow( ixBug, e )
{
	if (bCancelEvents || internalRowEvent(e)) return;
	var ixRow = GridControl.rowFromBug(ixBug);
	if (ixRow < 0) return;
	if (SelectionManager.isDragging())
		SelectionManager.gridClick(ixRow, false, false)
	else
		SelectionManager.tempHighlight(ixRow);
	
	var elNew = document.bulkForm['ixBulkBug'][ixRow];
	if (null != elNew && null != KeyManager && null != KeyManager.oGridBrowser)
	{
		if (elNew != KeyManager.oGridBrowser.elCurrent && null != KeyManager.oGridBrowser.elCurrent) 
		{
			KeyManager.oGridBrowser.fxLeave(KeyManager.oGridBrowser.elCurrent);
		}
		KeyManager.oGridBrowser.setElCurrent(elNew);
	}
	
	removeTextSelections();
}

function mouseoutGridRow( ixBug, e )
{
	if (bCancelEvents || internalRowEvent(e)) return;
	var ixRow = GridControl.rowFromBug(ixBug);
	if (ixRow < 0) return;
	var oRow = SelectionManager.highlightRow(ixRow);
	if (oRow) SelectionManager.setInfoColor(oRow, "rgb(151,151,151)");
	if (KeyManager.oGridBrowser) KeyManager.oGridBrowser.setElCurrent(null);
}

function mouseoverCaseId( ixBug, oLink )
{
	IdPop.startTimer(ixBug, oLink);
}

function mouseoutCaseId()
{
	IdPop.hide();
}

function keypressGridCheckbox(e, cBug, ixBug, dblClickUrl)
{
	if (32 == getKeyCode(e))  // space bar
	{ 
		SelectionManager.gridClick(cBug, e.shiftKey, true);
		return cancel(e);
	} 
	else if (13 == getKeyCode(e)) // enter
	{
		if (dblclickGridRow) dblclickGridRow(ixBug, dblClickUrl);
		return cancel(e);
	}
	return true;
}


// internalRowEvent
//
// IE only: returns true if an event's fromElement and toElement
// originate from children of the same row node
//
function internalRowEvent(e)
{
	var idParentSrc;
	var idParentTo;
	if (document.all)
	{
		if (window.event && window.event.fromElement && window.event.toElement)
		{
			idParentSrc = getidParentRow(window.event.fromElement, null);
			idParentTo = getidParentRow(window.event.toElement, null);
		}
	}
	else
	{
		if (e && e.target && e.relatedTarget)
		{
			idParentSrc = getidParentRow(e.target, null);
			idParentTo = getidParentRow(e.relatedTarget, null);
		}
	}
	return (idParentSrc && idParentTo && (idParentSrc == idParentTo));
}

// internalGridEvent
//
// Returns true if an event's fromElement and/or (depending on bAnd) toElement
// originate from gridview rows
//
function internalGridEvent(e, bAnd)
{
	var idA = null;
	var idB = null;
	if (document.all)
	{
		if (window.event && window.event.fromElement && window.event.toElement)
		{
			idA = getidParentRow(window.event.toElement, "bugDetails");
			idB = getidParentRow(window.event.fromElement, "bugDetails");
		}
	}
	else
	{
		if (e && e.target && e.relatedTarget)
		{
			idA = getidParentRow(e.target, "bugDetails");
			idB = getidParentRow(e.relatedTarget, "bugDetails");
		}
	}
	return bAnd ? (idA != null && idB != null) : (idA != null || idB != null);
}

// getidParentRow
//
// Return the id of element's grid row parent
// or a parent w/ id matching sIdAlt.
//
// If no parent id matches grid row or sIdAlt,
// return null
//
function getidParentRow(oElem, sIdAlt)
{
	if (oElem.id && oElem.id.indexOf("row_") == 0 && oElem.id != "row_spam")
		return oElem.id;
	else if (sIdAlt && oElem.id && oElem.id == sIdAlt)
		return oElem.id;

	if (oElem.parentNode)
		oElem = oElem.parentNode;
	else
		return null;
	
	return getidParentRow(oElem, sIdAlt);
}

function initializeListView()
{
	ListControl.storeOriginalScrollState();
	if (ListControl.fixCacheState()) return;
	ListControl.init();
	Icons.init();
	
	// If no matching cases were found, disable column popup
	if (XMLParser.getCustomTagValueFrom(document, "fb:empty"))
	{
		Icons.changeIcons(null, Icons.DISABLED, null, null);
	}	
	
	enableBulk();
	setPageTitle();
	theHoverTipMgr.reset();
	
	if (SelectionManager.isIxBugConflict())
	{
		// Current grid bugs do not match the
		// bugs the previously cached list of bugs...
		// so do not use previously cached form state (FF, case 323388)
		SelectionManager.doUnselectAll();
	}

	if (elById("bugGrid"))
	{
		// Grid View
		GridControl.init();
		ListControl.maximizeNavBar();
	}
}

function setFocusToWindow()
{
	if (bUserTyped) return;

	if (!bUserTyped && typeof(oFocusStart) != 'undefined' && oFocusStart)
	{
		safeFocus(oFocusStart);
		return;
	}

	// don't scroll down if there is an error at the top
	if (elById("bugerror") != null) return;
	
	var el = TabManager.getCurrentSEventEl();
	if (el != null) 
	{
		tryToFocus(el);
	}
	else
	{
		var oMainArea = elById("mainArea");
		if (!oMainArea) return;
		var rgTables = XMLParser.getNodeArrayFrom(oMainArea, "table");
		var bBigListFound = false;
		for (var ix = 0; ix < rgTables.length; ix++)
		{
			// Search for the first input or link of any FB biglist table
			if (rgTables[ix].className == "biglist")
			{
				bBigListFound = true;
				var rgInputs = XMLParser.getNodeArrayFrom(rgTables[ix], "input");
				for (var ixInput = 0; ixInput < rgInputs.length; ixInput++)
				{
					if (rgInputs[ixInput].type.toLowerCase() != 'hidden' && 
						rgInputs[ixInput].type.toLowerCase() != 'checkbox' && 
						rgInputs[ixInput].style.display != 'none')
					{
						el = rgInputs[ixInput];
						break;
					}
				}
				if (el) break;
			}
		}
		if (el && el.style.display != "none")
			tryToFocus(el);
	}
}


function showAssignSpan()
{
	var o = elById('spanTo');
	o.style.display = (o.style.display == 'none')?'':'none';
	var oDropdown = XMLParser.getNodeFrom(o, "select");
	if (oDropdown) safeFocus(oDropdown);
	return false;
}
function hideAssignSpan()
{
	var o = elById('spanTo');
	if (o) { o.style.display = 'none'; }
	return false;
}
function showMoveSpan()
{
	var o = elById('moveTo');
	o.style.display = (o.style.display == 'none')?'':'none';
	var oDropdown = XMLParser.getNodeFrom(o, "select");
	if (oDropdown) safeFocus(oDropdown);
	return false;
}
function hideMoveSpan()
{
	var o = elById('moveTo');
	if (o) { o.style.display = 'none'; }
	return false;
}
function clickDoesNothing()
{
	return false;
}
function clickSubmitsForm()
{
	document.body.style.cursor = "wait";
	if (this.id == "spam")
	{
		document.bulkForm.pre.value = "preSpam";
	}
	document.bulkForm.command.value = this.getAttribute("command");
	setBugValues(false);
	document.bulkForm.submit();
	return false;
}

// setBugValues
//
// Set bulkform.ixBug.value by concatenating
// all selected ixBugs into a comma-delimited string
//
// bForce - if true, concatenate all ixBugs regardless
//			of selected state 
//
// oOptTarget - if non-null, target of comma-delimited string,
//		if null, target is bulkForm.ixBug
//
function setBugValues(bForce, oOptTarget)
{
	var s = getBugValues(bForce);
	if (oOptTarget)
		oOptTarget.value = s;
	else
		document.bulkForm.ixBug.value = s;
}

// getBugValues
//
// Concatenate all (selected-only if bForce == false) ixBug
// values into comma-delimited string
//
function getBugValues(bForce)
{
	var s = "";
	var i = 0;
	var bf = document.bulkForm['ixBulkBug'];
	if (bf)
	{ 
		if (bf.length)
		{
			for (i=0; i<bf.length; i++)
			{
				if (bf[i].checked || bForce)
					s += bf[i].value + ",";
			}
		}
		else
		{
			s += bf.value + ",";
		}
	}
	if ( s.length > 0 )
		s = s.slice(0, -1);
	return s;
}

// setIxBugHref
//
// Updates the href of an actionbutton to reflect the ixBugs of currently
// selected cases on the list/grid view.  In case user uses ctrl-click or
// the browser's context menu to open the link (and bypasses the link's onclick in favor of href),
// we set this onmousedown.
//
function setIxBugHref( o )
{
	if (!ListControl.isListOrGridView()) return; // Only change the href of grid/list view action buttons
	if (!o || !o.href || !o.href.replace) return;

	// Possibility of JS disabled browser means we have actionbuttons w/
	// href="#" instead of their appropriate links.  If we're at this point,
	// JS is enabled, so we can swap out the href w/ the correct link and
	// let JS take care of "return false"'ing if the link is disabled.
	//
	var sHrefEnabled = o.getAttribute("hrefEnabled");
	if (sHrefEnabled && sHrefEnabled != o.href) o.href = sHrefEnabled;

	o.href = o.href.replace(/ixBug=[,0-9]*[&|$]/i, "ixBug=" + getBugValues(false) + "&");
}

function updateBulkActions()
{
	var i = 0;
	var fBitsAllowed = 0xfffffffff;
	var bAtLeastOneChecked = false;
	
	if ( !document.bulkForm ) return;
	
	var bf = document.bulkForm['ixBulkBug'];
	if ( bf )
	{
		if (!bf.length)
		{
			if (bf.checked == true)
			{
				fBitsAllowed = (fBitsAllowed & bf.getAttribute("bulk"));
				bAtLeastOneChecked = true;
			}
		}
		else
		{
			for (i=0; i<bf.length; i++)
			{
				if (bf[i].checked == true)
				{
					fBitsAllowed = (fBitsAllowed & bf[i].getAttribute("bulk"));
					bAtLeastOneChecked = true;
				}
			}
		}
	}
	
	if (!bAtLeastOneChecked)
	{
		fBitsAllowed = 0;
		hideAssignSpan();
		hideMoveSpan();
	}
		
	activate( fBitsAllowed & 1, elById('edit') );
	activate( fBitsAllowed & 2, elById('assign') );
	activate( fBitsAllowed & 4, elById('resolve') );
	activate( fBitsAllowed & 8, elById('reactivate') );
	activate( fBitsAllowed & 16, elById('close') );
	activate( fBitsAllowed & 32, elById('reopen') );
	activate( fBitsAllowed & 64, elById('spam') );
	if ( elById('move') != null )
		activate( fBitsAllowed & 128, elById('move') );
	activate( fBitsAllowed & 256, elById('remind') );

}

function activate( bActive, el )
{
	if ( ! el ) return;
	if ( bActive )
	{
		if (el.id == "assign")
		{
			el.onclick = showAssignSpan;
		}
		else if (el.id == "move")
		{
			el.onclick = showMoveSpan;
		}
		else
		{
			el.onclick = clickSubmitsForm;
		}
		el.className = 'actionButton';
	}
	else
	{
		el.onclick = clickDoesNothing;
		el.className = 'actionButtonDisabled';
	}
}

function enableBulk()
{
	if (window.opera) return;
	
	var i;
	if (document.bulkForm)
	{
		var bf = document.bulkForm['ixBulkBug'];
		if (bf)
		{ 
			if (bf.length)
			{
				for (i=0; i<bf.length; i++)
				{
					bf[i].disabled = false;
				}
			}
			else
			{
					bf.disabled = false;
			}
		}
		updateBulkActions();
	}
}	

var rgHelpTips = new Array();

//A set of tabbed pages is like a book. Here, each page has a tab and a block. Each tab has a radio button. 
function Book(){
	this.ids = new Array();
	this.addPage = function(id){
		this.ids.push(id);
		return true;
	}
}

function showTab(book, id){
	//for each page, show or hide:
	for(var i=0; i < book.ids.length; i++){
		if(book.ids[i]==id){
			//turn on:
			elById("blk_" + book.ids[i]).style.display = '';
			elById("tab_" + book.ids[i]).style.backgroundColor = '#f3f6f9'; 
			elById("tab_" + book.ids[i]).style.color = '#000000';
			elById("rdo_" + book.ids[i]).checked = true;
		}
		else{
			//turn off:
			elById("blk_" + book.ids[i]).style.display = 'none';
			elById("tab_" + book.ids[i]).style.backgroundColor = ''; 
			elById("tab_" + book.ids[i]).style.color = '#444444';
			elById("rdo_" + book.ids[i]).checked = false;
		}
	}
}


function HoverTipMgr(nameInit, theDivIdInit) {
	this.varName = nameInit;
	this.divId = theDivIdInit;
	this.reset();
}

HoverTipMgr.prototype.reset = function() {
	this.fadeIn = false;
	this.instantFade = false;
	this.contents = '';
	this.theTip = null;
	this.delayFade = 950;
	this.keepInMode = 3000;
	this.xOffset = 10;
	this.yOffset = 15;
	this.num = 0;
}

HoverTipMgr.prototype.initTip = function() {
	if (this.theTip == null) {
		this.theTip = elById(this.divId);
	}
}

HoverTipMgr.prototype.fadeInTip = function(theSpanId, event) {
	this.initTip();
	if ( this.theTip != null )
	{
		++this.num;
		if (this.num > 10000) this.num = 0;
		this.contents = elById(theSpanId).innerHTML;
		if (document.all) {
			this.theTip.style.left = (event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft + this.xOffset) + 'px';
			this.theTip.style.top = (event.clientY + document.documentElement.scrollTop + document.body.scrollTop + this.yOffset) + 'px';
		} else {
			this.theTip.style.left = (event.pageX + this.xOffset) + 'px';
			this.theTip.style.top = (event.pageY + this.yOffset) + 'px';
		}
		this.fadeIn = true;
		if (this.instantFade) {
			this.doFade(true, this.num)
		} else {
			setTimeout(this.varName +'.doFade(true, ' + this.num + ')', this.delayFade);
		}
	}
}

HoverTipMgr.prototype.fadeOutTip = function() {
	this.initTip();
	if ( this.theTip != null )
	{
		this.fadeIn = false;
		this.theTip.style.display = "none";
		this.theTip.innerHTML = this.contents = '';
		++this.num;
		if (this.num > 10000) this.num = 0;
		setTimeout(this.varName + '.doFade(false, ' + this.num + ')', this.keepInMode);
	}
}

HoverTipMgr.prototype.doFade = function(fadeIn, exNum) {
	if (fadeIn == this.fadeIn && exNum == this.num) {
		if (this.fadeIn) {
			this.theTip.innerHTML = this.contents;
			this.theTip.style.display = "";
			this.instantFade = true;
		} else {
			this.instantFade = false;
		}
	}
}

function mouseoverTip(sSpanId, event)
{
	if (typeof theHoverTipMgr != 'undefined') theHoverTipMgr.fadeInTip(sSpanId, event);
}

function mouseoutTip()
{
	if (typeof theHoverTipMgr != 'undefined') theHoverTipMgr.fadeOutTip();
}

function PopupMgr() {
	this.ids = new Array();
	this.noHideIds = new Array();
	this.add = function(id){
		this.ids.push(id);
		return true;
	}
	this.addNoHide = function(id){
		this.noHideIds.push(id);
		return true;
	}
}

PopupMgr.prototype.isNoHideId = function(id)
{
	for (var i=0; i < theMgr.noHideIds.length; i++)
		if (id == theMgr.noHideIds[i]) return true;
	return false;
}

PopupMgr.prototype.showPopup = function(id, elPlacement, xOffset, yOffset)
{
	this.hideAllPopups(true);
	var nMaskWidth =  documentWidth();
	var popEl = elById(id);
	if (popEl && popEl.style.display == 'none')
	{
		this.hideSelects(id);

		popEl.style.visibility = "hidden";
		popEl.style.display = '';

		if ( elPlacement != null )
		{
			var pt = getAbsolutePosition(elPlacement);
			popEl.style.top = (pt.y + yOffset) + 'px';
			if ((pt.x + xOffset + popEl.offsetWidth) > windowRight())
			{
				// If there is no room to the right of elPlacement for the popup,
				// push it to the left
				popEl.style.left = (pt.x - xOffset - popEl.offsetWidth + elPlacement.offsetWidth) + 'px';
			}	
			else
			{
				popEl.style.left = (pt.x + xOffset) + 'px';
			}
		}

		popEl.style.visibility = "visible";
		
		if ( elPlacement != null)
		{
			// Correct position of popup in case the popup was nested within
			// another absolutely positioned element
			var y1 = calculateOffset(popEl, 'offsetTop');
			var y2 = calculateOffset(elPlacement, 'offsetTop');
			var x1 = calculateOffset(popEl, 'offsetLeft');
			var x2 = calculateOffset(elPlacement, 'offsetLeft');
			var diffY = (y1 - (y2 + yOffset));
			var diffX = (x1 - (x2 + xOffset));
			
			if (diffY > 0)
			{
				popEl.style.top = ((y2+yOffset) - diffY) + 'px';
			}
			if (diffX > 0)
			{
				popEl.style.left = ((x2+xOffset) - diffX) + 'px';
			}
		}
		
		this.maskClicks(nMaskWidth);
	}
	return false;
}

PopupMgr.prototype.hidePopup = function (id)
{
	var popEl = elById(id);
	if ( !popEl ) return true;
		
	if ( popEl.style.display == '' )
	{
		popEl.style.display = 'none';
	}
	return false;
}

PopupMgr.prototype.hideAllPopups = function( bPreShowPopup )
{
	if (!bPreShowPopup && !EditableTableManager.isVisible())
	{
		// Only restore select and mask state if we're
		// not about to show another popup, 
		// and if no editable table popups are visible
		this.showSelects();
		this.unmaskClicks();
	}
	for(var i=0; i < theMgr.ids.length; i++)
	{
		theMgr.hidePopup(theMgr.ids[i]);
	}
	return false;
}			

PopupMgr.prototype.hideSelects = function (id)
{
	if (!window.ie) return; // only IE has bleedthrough problem
	// hide all selects so we don't get bleedthrough
	var rgEl = document.getElementsByTagName('select');
	var pt;
	for ( var i = 0; i < rgEl.length; i ++ )
	{
		if ( rgEl[i].style.display != 'none' && !this.isNoHideId(rgEl[i].id) )
		{
			var oHider = elById('input_' + i);
			if (oHider && oHider.style.display != 'none')
			{
				// This select is already hidden by a previous popup
				continue;
			}
			pt = getAbsolutePosition(rgEl[i]);
			var el;
			if (oHider)
			{
				el = oHider;
			}
			else
			{
				el = document.createElement('INPUT');
				el.type = 'text';
				el.id = 'input_' + i;
				el.style.position = 'absolute';
			}
			el.style.left = pt.x + 'px';
			el.style.top = pt.y + 'px';
			el.style.display = "";
			if (rgEl[i].selectedIndex >= 0)
				el.value = ' ' + trim(rgEl[i].options[rgEl[i].selectedIndex].innerHTML);
			else if (rgEl[i].options.length > 0)
				el.value = ' ' + trim(rgEl[i].options[0].innerHTML);
			el.value = decodeLTGT(el.value);
			el.className = rgEl[i].className + '_pseudo';
			if ( rgEl[i].style.width.length )
				el.style.width = rgEl[i].style.width;
			if ( rgEl[i].style.fontSize.length )
				el.style.fontSize = rgEl[i].style.fontSize;
			if ( rgEl[i].style.fontFamily.length )
				el.style.fontFamily = rgEl[i].style.fontFamily;
			if (el.style.width != '' )
				el.style.width = (parseInt(el.style.width, 10) - 6) + 'px';
			if (rgEl[i].offsetHeight)
				el.style.height = rgEl[i].offsetHeight-4 + "px";
			
			if (!oHider) rgEl[i].parentNode.insertBefore(el, rgEl[i]);
			rgEl[i].style.visibility = 'hidden';
		}
	}
}

PopupMgr.prototype.showSelects = function ()
{
	if (!window.ie) return; // only IE has bleedthrough problem
	// show all selects so we don't get bleedthrough
	var rgEl = document.getElementsByTagName('select');
	for ( var i = 0; i < rgEl.length; i ++ )
	{
		var el = elById('input_' + i);
		if ( el )
		{
			el.style.display = "none";
		}
		rgEl[i].style.visibility = 'visible';
	}
}

PopupMgr.prototype.maskClicks = function (nMaskWidthInit)
{
	var nMaskWidth;
	if (null == nMaskWidthInit)
	{
		nMaskWidth = documentWidth();
	}
	else
	{
		nMaskWidth = nMaskWidthInit;
	}
	
	var o = elById('menuDisappearingMask' + maskType());
	if (o)
	{
		o.style.display = '';
		o.style.height = documentHeight() + 'px';
		o.style.overflow = 'hidden';
		o.style.width = nMaskWidth + 'px';
	}
	var rg = XMLParser.getNodeArrayUsingIdFrom(document, maskType().toLowerCase(), "menuDisappearingMaskSmall" + maskType());
	for (var ix = 0; ix < rg.length; ix++)
	{
		rg[ix].style.height = "100%";
		rg[ix].style.width = "100%";
		rg[ix].style.display = '';
	}
}

PopupMgr.prototype.unmaskClicks = function ()
{
	var o = elById('menuDisappearingMask' + maskType());
	if (o) o.style.display = 'none';
	var rg = XMLParser.getNodeArrayUsingIdFrom(document, maskType().toLowerCase(), "menuDisappearingMaskSmall" + maskType());
	for (var ix = 0; ix < rg.length; ix++)
	{
		rg[ix].style.display = 'none';
	}
}

function maskType()
{
	return (document.all) ? "Img" : "Div";
}

// Pop the help window, or bring it to the front if it already exists
function popHelpWin(e, url) {
	var helpWin = window.open('help/' + url, 'fbHelp', 'width=800, height=600, scrollbars=yes, toolbar=yes, location=no, status=no, menubar=no, copyhistory=no, resizable=yes'); 
	safeFocus(helpWin); 
	return cancel(e);
}


// Close all popups and don't cancel any events
function doPopupClick() {
	theMgr.hideAllPopups();
	return true;
}

function popFilterPopup(sName, elemTarget, e, sText) {

	if (!KeyManager.oMenuBrowser) 
	{ 
		KeyManager.browseMenus('idFilterDescription');
		KeyManager.oMenuBrowser.setElCurrent(elemTarget);
	}

	if (elById('idFilterOpt' + sName) != null)
	{
		theMgr.showPopup('idFilterOpt' + sName, elemTarget, 0, elemTarget.offsetHeight + 2);
	}
	else
	{
		// Filter refine popups haven't been loaded yet
		theMgr.showPopup('idFilterOptLoading', elemTarget, 0, elemTarget.offsetHeight + 2);
		return cancel(e);
	}

	if (null != elById('idPopText' + sName))
	{
		if (sName != "SaveFilterAs") populateTextBox('idPopText' + sName, sText);
		giveTextBoxFocus('idPopText' + sName);
	}
	else if (null != elById('idPopix' + sName))
	{
		safeFocus(elById('idPopix' + sName));
	}
	else
	{
		KeyManager.browsePopup('idFilterOptInner' + sName);
	}

	return cancel(e);
}

function setFilterRssHref(ixPerson, ixFilter, sFilter)
{
	var o = elById('imgRssStatus');
	if (!o || !o.parentNode || !o.parentNode.getAttribute("sURLPrototype")) return;

	var sHrefNew = swap2(o.parentNode.getAttribute("sURLPrototype"), ixPerson, ixFilter);
	o.parentNode.href = sHrefNew;

	// Add a new <link> so FF's live bookmark updates as well
	// ...currently unable to remove old live bookmark, so
	//    user will have choice
	o = elById('idRssFeed');
	if (!o) return;

	var oNewFeed = o.cloneNode(true);
	oNewFeed.title = sFilter;
	oNewFeed.href = sHrefNew;
	document.head.appendChild(oNewFeed);
}

function toggleFilterRefine(sName, e) {
	var elemToggle = elById('idRefineFilter' + sName);
	var elemImg = elById('filterMenuPlus' + sName);
	return togglePopupSubMenu(elemToggle, elemImg, e);
}

function togglePopupSubMenu(elemToggle, elemImg, e)
{
	var retval = true;
	if (elemToggle.style.display == "none")
	{
		elemToggle.style.display = "block";
		elemImg.src = "minus.gif";
	}
	else
	{
		elemToggle.style.display = "none";
		elemImg.src = "plus.gif";
		retval = false;
	}
    	if (e.cancelable) 
           	e.preventDefault();
	e.returnValue = false;
	return retval;
}

function handleListOfHoursKeydown(elem, e)
{
	var key = getKeyCode(e);
	// setTimeout here in order to let tab focus change properly in IE
	if(isTab(e)) setTimeout("theMgr.hideAllPopups()",1);
	else if (key == 13 || key == 32)
	{
		if (elem.onclick)
			elem.onclick.apply(elem, []);
		return cancel(e);
	}
	return true;
}

function handleFilterChangeKeydown(elem, e)
{
	if (getKeyCode(e) == 13)
	{
		theMgr.hideAllPopups();
		elem.form.submit();
		if (e) e.returnValue = false;
		return false; // already changed filter via form submit, don't resubmit
	}
	else if (getKeyCode(e) == 27)
	{
		theMgr.hideAllPopups();
	}
	return true;
}

function handleFilterChangeClick(elem)
{
	theMgr.hideAllPopups();
	elem.form.submit();
}

function handleFilterSaveAsClick(elem)
{
	if (!quickFilterSaveAs(elem))
	{
		theMgr.hideAllPopups();
		elem.form.submit();
	}
	return false;
}

function handleFilterSaveAsKeydown(elem, e, bAllowSpace)
{
	bAllowSpace = (bAllowSpace && window.safari); // Browsers other than Safari will fire the space as an onclick as well
	if (getKeyCode(e) == 13 || (bAllowSpace && getKeyCode(e) == 32))
	{
		if (!quickFilterSaveAs(elem))
		{
			theMgr.hideAllPopups();
			elem.form.submit();
		}
		if (e) e.returnValue = false;
		repairFocus(elem);
		return false; // already saved filter via form submit, don't resubmit	
	}
	else if (getKeyCode(e) == 27)
	{
		theMgr.hideAllPopups();
	}
	return true;
}

function doDlgConfirmation( ix )
{
	enableInputsWithin("dlgConfirmation_" + ix, false);
	Info.show(Lang.getString("FB_SUBMITTING"), null, null);
}

// addColumnDropdown
//
// On options page, show another
// grid view column dropdown
//
function addColumnDropdown()
{
	var i = 0;
	var o;
	// Find the first hidden dropdown
	for (i = 0; true; i++)
	{
		o = elById("gridCol_" + i);
		if (!o)
		{
			disableElementById("addColumnButton");
			return;
		}
		if (o.style.display == "none") break;
	}
	o.style.display = "";
	o = elById("gridCol_" + (i+1));
	if (!o)	disableElementById("addColumnButton");
}


function statusChange()
{
	if (elById('ixStatus').options[elById('ixStatus').selectedIndex].value == 4)
	{
		elById('sDuplicatesEdit').style.display = '';
	}
	else
	{
		elById('sDuplicatesEdit').style.display = 'none';
	}
	return false;
}

function tryToFocus( el )
{
	try{safeFocus(el);} catch(err) {};
	if (document.all && !document.selection) 
	{
		if ( el && el.setSelectionRange )
		try {el.setSelectionRange(0,0); } catch (err) {};
	}
}

function toggleReply( el )
{
	var elToggle = nextSiblingOfType(el, "span");
	if (!elToggle) return;

	if ( elToggle.style.display == 'none' )
	{
		elToggle.style.display = "";
		el.firstChild.innerHTML = Lang.getString("FB_HIDE_QUOTED_TEXT");
	}
	else
	{
		elToggle.style.display = 'none';
		el.firstChild.innerHTML = Lang.getString("FB_SHOW_QUOTED_TEXT");
	}
}

function toggleSnippetPlaceholderTip()
{
	var o = elById("snippetPlaceholdersTip");
	if (o) toggleVisible(o);
}

function flipCheckbox(oBox)
{
	if (oBox) oBox.checked = !oBox.checked;
}

function toggleCheckins()
{
	var oCheckins = elById('containerCheckins');
	var oLink = elById('linkToggleCheckins');
	if (!oCheckins || !oLink) return;
	toggleVisible(oCheckins);
	if (isVisible(oCheckins))
	{
		if (!oLink.sHTMLOld) oLink.sHTMLOld = oLink.innerHTML;
		oLink.innerHTML = Lang.getString("FB_HIDE_CHECKINS");
	}
	else
	{
		oLink.innerHTML = oLink.sHTMLOld;
	}
}
