
/**
 *
 * TabManager - Singleton
 *
 */
 
var TabManager = new function()
{
	this.rgActionDesc = [];
	this.cancelClicked = false;
	this.dirtyView = false;
	this.bEditedForm = false;
	
	this.rgBugView = [
{ sCmd:'view',       sText:'View', sEdit:'View', sEmail:'None',  sPerson:'View',    sStatus:'View',   sCat:'View', sSubject:'None',    sTo:'None',  sEvent:'None',    sOk:'None',  sFile: 'None'},
{ sCmd:'assign',       sText:'Edit', sEdit:'Edit', sEmail:'None',  sPerson:'Edit',    sStatus:'View',   sCat:'Edit', sSubject:'None',    sTo:'None',  sEvent:'Edit',    sOk:'Edit',  sFile: 'Edit'},
{ sCmd:'edit',       sText:'Edit', sEdit:'Edit', sEmail:'None',  sPerson:'Edit',    sStatus:'View',   sCat:'Edit', sSubject:'None',    sTo:'None',  sEvent:'Edit',    sOk:'Edit',  sFile: 'Edit'},
{ sCmd:'editClosed', sText:'Edit', sEdit:'View', sEmail:'None',  sPerson:'View',    sStatus:'View',   sCat:'View', sSubject:'None',    sTo:'None',  sEvent:'Edit',    sOk:'Edit',  sFile: 'None'},
{ sCmd:'reopen',     sText:'Edit', sEdit:'Edit', sEmail:'None',  sPerson:'Edit',    sStatus:'Active', sCat:'Edit',  sSubject:'None',   sTo:'None',  sEvent:'Edit',    sOk:'Edit',  sFile: 'Edit'},
{ sCmd:'reactivate', sText:'Edit', sEdit:'Edit', sEmail:'None',  sPerson:'Edit',    sStatus:'Active', sCat:'Edit',  sSubject:'None',   sTo:'None',  sEvent:'Edit',    sOk:'Edit',  sFile: 'Edit'},
{ sCmd:'resolve',    sText:'Edit', sEdit:'Edit', sEmail:'None',  sPerson:'Resolve', sStatus:'Edit',   sCat:'View', sSubject:'None',    sTo:'None',  sEvent:'Edit',    sOk:'Edit',  sFile: 'Edit'},
{ sCmd:'close',      sText:'Edit', sEdit:'View', sEmail:'None',  sPerson:'View',    sStatus:'View',   sCat:'View', sSubject:'None',    sTo:'None',  sEvent:'Edit',    sOk:'Edit',  sFile: 'None'},
{ sCmd:'reply',      sText:'Edit', sEdit:'View', sEmail:'Email', sPerson:'Reply',    sStatus:'View',   sCat:'View', sSubject:'Reply',   sTo:'Reply', sEvent:'Reply',   sOk:'Email', sFile: 'Edit'},
{ sCmd:'email',      sText:'Edit', sEdit:'View', sEmail:'Email', sPerson:'View',    sStatus:'View',   sCat:'View', sSubject:'Email',   sTo:'Email', sEvent:'Edit',    sOk:'Email', sFile: 'Edit'},
{ sCmd:'forward',    sText:'Edit', sEdit:'View', sEmail:'Email', sPerson:'View',    sStatus:'View',   sCat:'View', sSubject:'Forward', sTo:'Email', sEvent:'Forward', sOk:'Email', sFile: 'Edit'}
			];

	this.rgField = [
			{sName:"sEventContainer",  sOn:"table-row", sType:'sText',    bSetName:false},
			{sName:"idAndTitle",       sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"projectAndArea",   sOn:"table-row", sType:'sCat',     bSetName:false},
			{sName:"actionButtons",    sOn:"table-row", sType:'sText',    bSetName:false},
			{sName:"actionButtons0",   sOn:"table-row", sType:'sText',    bSetName:false},
			{sName:"actionButtons1",   sOn:"table-row", sType:'sText',    bSetName:false},
			{sName:"fixFor",           sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"personAssignedTo", sOn:"table-row", sType:'sPerson',  bSetName:false},
			{sName:"status",           sOn:"table-row", sType:'sStatus',  bSetName:false},
			{sName:"category",         sOn:"table-row", sType:'sCat',     bSetName:false},
			{sName:"priority",         sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"dueDate",          sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"bugzScoutTitle",   sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"bugzScoutReports", sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"estimate",         sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"custom1",          sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"custom2",          sOn:"table-row", sType:'sEdit',    bSetName:false},
			{sName:"attachFile",       sOn:"block",    sType:'sText',    bSetName:false},
			{sName:"attachAuto",       sOn:"block",    sType:'sEvent',   bSetName:false},
			{sName:"ixBugEventAttachment",    sOn:"inline",    sType:'sEvent',   bSetName:true},
			{sName:"fromRow",          sOn:"table-row", sType:'sEmail',   bSetName:false},
			{sName:"sToRow",           sOn:"table-row", sType:'sTo',      bSetName:false},
			{sName:"sCCRow",           sOn:"table-row", sType:'sTo',   bSetName:false},
			{sName:"sBCCRow",          sOn:"table-row", sType:'sTo',   bSetName:false},
			{sName:"sSubjectRow",      sOn:"table-row", sType:'sSubject', bSetName:false},
			{sName:"submitButtons",    sOn:"block",     sType:'sOk',      bSetName:false},
			{sName:"sTo",              sOn:"inline",    sType:'sTo',      bSetName:true},
			{sName:"sCC",              sOn:"inline",    sType:'sTo',      bSetName:true},
			{sName:"sBCC",             sOn:"inline",    sType:'sTo',      bSetName:true},
			{sName:"sSubject",         sOn:"inline",    sType:'sSubject', bSetName:true},
			{sName:"sEvent",           sOn:"inline",    sType:'sEvent',   bSetName:true},
			{sName:"sFile",            sOn:"inline",    sType:'sFile',    bSetName:false}
			];
	
	this.clickChangeView = function(e, sCommand)
	{
		if (this.changeView(sCommand))
		{
			return cancel(e);
		}
		else
		{
			return true;
		}
	}
	
	this.changeView = function(sCommand)
	{
		if (window.opera || window.safari) return false;
		if (this.dirtyView)
		{
			elById('BugFields').innerHTML = this.cachedHTML;
			elById('ixProject').value = this.cachedProject;
			elById('ixArea').value = this.cachedArea;
			elById('ixFixFor').value = this.cachedFixFor;
			if (elById('ixStatus') && statusChange)
			{
				elById('ixStatus').onchange = statusChange;
			}
		}
		else
		{
			this.dirtyView = true;
			this.cachedProject = elById('ixProject').value;
			this.cachedArea = elById('ixArea').value;
			this.cachedFixFor = elById('ixFixFor').value;
			this.cachedHTML = elById('BugFields').innerHTML;
		}
		if (this.changeViewImpl(sCommand) && ViewHistoryManager)
		{
			ViewHistoryManager.oViewCurrent.sCommand = sCommand;
			ViewHistoryManager.addViewHistory();
			return true;
		}
		else
		{
			return false;
		}	
	}

	this.returnToView = function(sCommand)
	{
		if (window.opera || window.safari) return;
		showHelp('');
		this.changeViewImpl(sCommand);
	}

	this.setFormDisabledName = function(sName, sType)
	{
		var el = elById(sName + sType);
		if (el)
		{
			el.name = sName +'Disabled';
		}
	}

	this.setFormDisabledNames = function()
	{
		// If they clicked cancel, don't flip names to disabled, so the
		// contents are preserved
		if (this.cancelClicked)
		{
			this.cancelClicked = false;
			return;
		}

		var el;
		for (var i=0; i < this.rgField.length; i++)
		{
			if (this.rgField[i].bSetName)
			{
				this.setFormDisabledName(this.rgField[i].sName, 'Edit');
				this.setFormDisabledName(this.rgField[i].sName, 'Reply');
				this.setFormDisabledName(this.rgField[i].sName, 'Forward');
				this.setFormDisabledName(this.rgField[i].sName, 'Email');
				el = this.getCurrentEl(this.rgField[i].sName);
				if (el)
				{
					el.name = this.rgField[i].sName;
				}
			}
		}
	}

	this.changeViewImpl = function(sCommand)
	{
		if ('view' != sCommand)
		{
			window.onbeforeunload = function (e) {
				if (TabManager.bEditedForm &&
					!(document.all && 1 == elById('fIEFileBrowse').value))
				{
					return Lang.getString("FB_EDITS_WILL_BE_LOST");
				}
			}
		}

		KeyManager.deactivateHotKeys();
		this.cancelClicked = false;

		TabManager.blurCurrentSEventEl();

		var elBugTips = elById('TopBugTips');
		if (null != elBugTips)
		{
			elBugTips.style.display = 'none';
		}
		
		var i = 0;
		var viewShow = null;
		while (i < this.rgBugView.length)
		{
			if (this.rgBugView[i].sCmd == sCommand)
			{
				viewShow = this.rgBugView[i];
			}
			++i;
		}
		if (!viewShow) return false;
		try {safeFocus(elById(sCommand));} catch (err) {};
		try {safeFocus(elById(sCommand + '0'));} catch (err) {};
		for (i=0; i < this.rgField.length; i++)
		{
			try {elById(this.rgField[i].sName + "Close").style.display = 'none';} catch(err) {};
			try {elById(this.rgField[i].sName + "Edit").style.display = 'none';} catch(err) {};
			try {elById(this.rgField[i].sName + "Email").style.display = 'none';} catch(err) {};
			try {elById(this.rgField[i].sName + "Forward").style.display = 'none';} catch(err) {};
			try {elById(this.rgField[i].sName + "Reply").style.display = 'none';} catch(err) {};
			try {elById(this.rgField[i].sName + "Resolve").style.display = 'none';} catch(err) {};
			try {elById(this.rgField[i].sName + "View").style.display = 'none';} catch(err) {};
			var el = elById(this.rgField[i].sName + viewShow[this.rgField[i].sType]);
			if (el != null)
			{
				if (document.selection)
				{
					try {el.style.display = 'inline';} catch(err) {};
				}
				else
				{
					try {el.style.display = this.rgField[i].sOn;} catch (err) {};
				}
				if ('sEvent' == this.rgField[i].sName)
				{
					safeFocus(el); 
					adjustRows(el); 
					safeFocus(el); 
					if (!document.all)
					{
						if (el.setSelectionRange) el.setSelectionRange(0,0);
						setTimeout("TabManager.fixFirefoxCursorPlacement();", 0); // Firefox < 1.5 resets the selection to the end on display.
					}
				}
			}
		}
		for (i=0; i < this.rgActionDesc.length; i++)
		{
			if (this.rgActionDesc[i].action == sCommand)
			{
				elById('bugEventAction').innerHTML = this.rgActionDesc[i].desc;
			}
		}
		if (null != document.formWithProject) 
		{
			document.formWithProject.command.value = sCommand;
		}

		this.flipAttachDeleteIcons(sCommand);
		shrinkImagesToFit();
		ClockCalBinding.init();
		return true;
	}

	this.flipAttachDeleteIcons = function(sCommand)
	{
		// Flip the display of all the Attachment delete icons.		
		new ListBrowser(elById('BugEvents'),
					function(el) { return el.className && 'attachmentDeleteIcon' == el.className;},
					null,
					null,
					null,
					function(el) { el.style.display = ('edit' == sCommand) ? 'inline' : 'none'; },
					null );
	}

	// Firefox < 1.5 resets the selection to the end on display.
	this.fixFirefoxCursorPlacement = function()
	{
		var el = this.getCurrentSEventEl();
		
		if (!el) return;

		if (el.id == 'sEventEdit')
		{
			safeFocus(el);

		}
		else if (el && el.selectionStart == el.value.length)
		{
			el.setSelectionRange(0,0);
			safeFocus(el);
		}
	}

	this.blurCurrentSEventEl = function()
	{
		var el = this.getCurrentSEventEl();
		if (el)
		{
			safeFocus(el);
			el.blur();
		}
	}

	this.getCurrentSEventEl = function()
	{
		return this.getCurrentEl('sEvent');
	}

	this.getCurrentEl = function(sName)
	{
		var el;
		el = elById(sName + 'Edit');
		if (isDisplayed(el)) return el;
		el = elById(sName + 'Reply');
		if (isDisplayed(el)) return el;
		el = elById(sName + 'Forward');
		if (isDisplayed(el)) return el;
		el = elById(sName + 'Email');
		if (isDisplayed(el)) return el;
	}

} // End TabManager singleton


/**
 *
 * ViewHistoryManager - singleton
 *
 */
var ViewHistoryManager = new function()
{
	
	var bInited = false;

	this.oViewInit = null;
	this.oViewCurrent = null;

	this.init = function(sCommandInit, ixBugInit, fMostRecentEventFirstInit)
	{
		this.oViewInit =    {sCommand: sCommandInit, ixBug: ixBugInit, fMostRecentEventFirst: fMostRecentEventFirstInit, ixBugEventLatest: ixBugEventLatest};
		this.oViewCurrent = {sCommand: sCommandInit, ixBug: ixBugInit, fMostRecentEventFirst: fMostRecentEventFirstInit, ixBugEventLatest: ixBugEventLatest};
		this.bInited = true;
	}

	this.addViewHistory = function()
	{
		if (!this.bInited) return false;

		dhtmlHistory.add(this.oViewCurrent.sCommand + '_' + this.oViewCurrent.fMostRecentEventFirst + '_' + this.oViewCurrent.ixBug, 
				 {sCommand: this.oViewCurrent.sCommand, 
					ixBug: this.oViewCurrent.ixBug, 
					fMostRecentEventFirst: this.oViewCurrent.fMostRecentEventFirst, 
					ixBugEventLatest: ixBugEventLatest} );
		return true;
	}

	this.addBugView = function()
	{
		if (!this.bInited) return false;
		dhtmlHistory.add("" + ixBugEventLatest, 
				 {sCommand: this.oViewCurrent.sCommand, ixBug: this.oViewCurrent.ixBug, fMostRecentEventFirst: this.oViewCurrent.fMostRecentEventFirst, ixBugEventLatest: ixBugEventLatest} );
		return true;
	}

	this.setCurrentTo = function(oViewNew)
	{
		if (!this.bInited) return;

		if (this.oViewCurrent.sCommand != oViewNew.sCommand)
		{
			this.oViewCurrent.sCommand = oViewNew.sCommand;
			TabManager.returnToView(oViewNew.sCommand);
		}
		if (this.oViewCurrent.fMostRecentEventFirst != oViewNew.fMostRecentEventFirst)
		{
			this.oViewCurrent.fMostRecentEventFirst = oViewNew.fMostRecentEventFirst;
			this.oViewCurrent.ixBug = oViewNew.ixBug;
			setMostRecentEventFirst(this.oViewCurrent.ixBug, this.oViewCurrent.fMostRecentEventFirst, true)
		}
	}

	this.handleHistoryChange = function(newLocation, historyData)
	{
		if (!this.bInited) return false;

		if (null == historyData)
		{
			this.setCurrentTo(this.oViewInit);
		}
		else
		{
			if (historyData.ixBugEventLatest > ixBugEventLatest)
			{
				this.setCurrentTo(historyData);
				Info.show(Lang.getString("FB_LOADING_BUG_DATA"), "containerBugEdit", "bugEditTable");
				loadBug(historyData.ixBug, historyData.sCommand);
			}
			else
			{
				this.setCurrentTo(historyData);
			}
		}
		return true;
	}
} // End of ViewHistoryManager singleton

function clickChangeBug(e, ixBug, sAttr, sVal, sCommand)
{
	changeBug(ixBug, sAttr, sVal, sCommand, 'pgBugFields');
	return cancel(e);
}

function clickReply(ixBug, ixPerson)
{
	changeBug(ixBug, 'ixPersonAssignedTo', ixPerson , 'reply', 'pgBugAssignAlaCarte');
}

var ixBugEventLatest = 0;
var sCommand = '';

function changeBug(ixBug, sAttr, sVal, sCommand, sPg)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout("changeBug('"+ixBug+"','"+sAttr+"', '"+sVal+"', '"+sCommand+"', '"+sPg+"');", 500);
	}
	else
	{
		oAjaxRequest = new AjaxRequest();
		oAjaxRequest.initialize();
		oAjaxRequest.bDefaultFailureBehavior = false;
		oAjaxRequest.onreadystatechange(resultSubmitBug);
		oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pre=preChangeBug&pg=" + sPg + "&ixBug=" + ixBug + "&" + sAttr + "=" + sVal + "&ixBugEventLatest=" + ixBugEventLatest + "&fMostRecentEventFirst=" + ViewHistoryManager.oViewCurrent.fMostRecentEventFirst + "&command=" + sCommand, true);
		oAjaxRequest.send(null);
	}
	
}



function loadBug(ixBug, sCommand)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (!oAjaxRequest.isBusy())
	{
		oAjaxRequest = new AjaxRequest();
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultSubmitBug);
		oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pg=pgEntireBug&ixBug=" + ixBug + "&command=" + sCommand, true);
		oAjaxRequest.send(null);
	}

}


// updateActionButtons
//
// Replace contents of action button containers 
// w/ new HTML from source oXML
//
function updateActionButtons( oXML )
{
	var rgActionButtons = XMLParser.getNodeArrayFrom(oXML, "ActionButtons");
	if (!rgActionButtons || !rgActionButtons.length) return;

	for (var ix = 0; ix < rgActionButtons.length; ix++)
	{
		var sId = XMLParser.getTextFrom(rgActionButtons[ix], "idContainer");
		var sHTML = XMLParser.getCDataFrom(rgActionButtons[ix], "sHTML");
		if (sId && sHTML)
		{
			var o = elById(sId);
			if (o)
			{
				o.innerHTML = sHTML;
			}
		}
	}
}

// updateBugEventLatest
//
// Update ixBugEventLatest w/ new post-event ixBugEvent (ixBugEventLatestPost)
// iff there have not been any intermittent bugevents since the page was loaded
//
function updateBugEventLatest(ixBugEventLatestPre, ixBugEventLatestPost)
{
	if (!ixBugEventLatestPre || !ixBugEventLatestPost) return false;
	if (ixBugEventLatestPre == ixBugEventLatestPost) return false;

	// If we want to update the client-side latest bug event (to ixBugEventLatestPost),
	// we are only safe to do so if the second-latest bug event (ixBugEventLatestPre)
	// is equal to the client-side current ixBugEventLatest
	// (If this is not true, then somebody else has edited the bug since user viewed the case)
	//
	if (ixBugEventLatestPre == ixBugEventLatest)
	{
		ixBugEventLatest = ixBugEventLatestPost;
		if (document.bugform && document.bugform.ixBugEventLatest)
			document.bugform.ixBugEventLatest.value = ixBugEventLatest;
		if (document.formWithProject && document.formWithProject.ixBugEventLatest)
			document.formWithProject.ixBugEventLatest.value = ixBugEventLatest;

		return true;
	}
	return false;
}

function resultSubmitBug()
{
	if (!oAjaxRequest) return;
	if (oAjaxRequest.isReady())
	{	
		var oXML = oAjaxRequest.responseXML();

		if (XMLParser.getTextFrom(oXML, "sError"))
		{
			alert(XMLParser.getTextFrom(oXML, "sError"))
		}

		if (XMLParser.getTextFrom(oXML, "forceReload") && '1' == XMLParser.getTextFrom(oXML, "forceReload"))
		{
			window.location.reload();
			return;	
		}

		if (XMLParser.getTextFrom(oXML, "loadPage"))
		{
			window.location.search = XMLParser.getTextFrom(oXML, "loadPage");
			return;	
		}

		var ixBugEventLatestNew = XMLParser.getTextFrom(oXML, "ixBugEventLatest");
		if (null != ixBugEventLatestNew && ixBugEventLatestNew != ixBugEventLatest)
		{
			ixBugEventLatest = ixBugEventLatestNew;
			var bugEventHTML = XMLParser.getCDataFrom(oXML, "BugEventHTML");
			if (bugEventHTML)
			{
				document.formWithProject.ixBugEventLatest.value = ixBugEventLatest;
				if (XMLParser.getTextFrom(oXML, "fRemoveOldToggle") == '1' && elById('BugEventOrderToggle'))
					elById('BugEventOrderToggle').innerHTML = "";
				if (elById('newBugEventInsertBelowPoint'))
					elById('newBugEventInsertBelowPoint').innerHTML = bugEventHTML + elById('newBugEventInsertBelowPoint').innerHTML;
				else if (elById('newBugEventInsertAbovePoint')) 
					elById('newBugEventInsertAbovePoint').innerHTML = elById('newBugEventInsertAbovePoint').innerHTML + bugEventHTML;
			}
		}

		var EditFooterHTML = XMLParser.getCDataFrom(oXML, "EditFooterHTML");
		if (EditFooterHTML)
		{
			var oContainer = elById("EditFooter");
			if (oContainer) oContainer.innerHTML = EditFooterHTML;
		}

		var BugFieldsHTML = XMLParser.getCDataFrom(oXML, "BugFieldsHTML");
		if (BugFieldsHTML)
		{
			TabManager.blurCurrentSEventEl();
			KeyManager.deactivateHotKeys();

			elById('BugFields').innerHTML = BugFieldsHTML;
			SetupAreaProjectMapping();
			SetupFixForProjectMapping();
			SetupPrimaryContactMapping();
			setTimeout('if (isDisplayed(elById(\'ixStatus\'))) statusChange();', 1);
			var elArea = document.formWithProject.ixArea.options;
			var elFixFor = document.formWithProject.ixFixFor.options;
			projectChanged(document.formWithProject.ixProject.options.selectedIndex, elArea[elArea.selectedIndex].value, elFixFor[elFixFor.selectedIndex].value);
			updatePageTitle(document.formWithProject.sTitle.value);
			
			TabManager.dirtyView = false;

			var el = TabManager.getCurrentSEventEl();
			if (null != el)
			{
				safeFocus(el);
				if (!document.selection) 
				{
					if ( el && el.setSelectionRange )
						try {el.setSelectionRange(0,0); } catch (err) {};
				}
			}
			var sCommand = XMLParser.getTextFrom(oXML, "sCommand");
			if (sCommand)
			{
				ViewHistoryManager.oViewCurrent.sCommand = sCommand;
				ViewHistoryManager.addBugView();
			}

			TabManager.bEditedForm = false;
			setElementOnChanges();
		}

		var bugEventsHTML = XMLParser.getCDataFrom(oXML, "BugEventsHTML");
		if (bugEventsHTML)
		{
			elById('BugEvents').innerHTML = bugEventsHTML;
		}
		else
		{
			TabManager.flipAttachDeleteIcons(sCommand);
		}
			
		Info.hide();
		IdPop.hide();
		ClockCalBinding.init();
		try { frames.attachFrame.initMSel(); } catch (e) {};
	}

}

function updatePageTitle( sBugTitle )
{
	if (!sBugTitle || !sBugTitle.length || !document.titlePrototype) return;
	document.title = swap1(document.titlePrototype, sBugTitle);
}

function clickEventOrderToggle(e, ixBug, fMostRecentEventFirst)
{
	if (setMostRecentEventFirst(ixBug, fMostRecentEventFirst, false) && ViewHistoryManager)
	{
		elById("BugEventOrderToggle").innerHTML = "";
		ViewHistoryManager.oViewCurrent.fMostRecentEventFirst = fMostRecentEventFirst;
		ViewHistoryManager.oViewCurrent.ixBug = ixBug;
		ViewHistoryManager.addViewHistory();
	}
	return cancel(e);
}

function setMostRecentEventFirst(ixBug, fMostRecentEventFirst, fRetry)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		if (fRetry)
		{
			// Request is already busy. If you requested retry, wait half a sec and try again.
			setTimeout('setMostRecentEventFirst('+fMostRecentEventFirst+', '+ixBug+')', 500, true);
			return true;
		}

		return false;
	}
	
	oAjaxRequest = new AjaxRequest();
	oAjaxRequest.initialize();
	oAjaxRequest.onreadystatechange(resultReplaceBugEvents);
	oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pre=preSetMostRecentEventFirst&pg=pgBugEvents&ixBug=" + ixBug + "&fMostRecentEventFirst=" + fMostRecentEventFirst, true);
	oAjaxRequest.send(null);
	return true;
}

function resultReplaceBugEvents()
{
	if (!XMLParser) XMLParser = new XMLParser();
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	var oXML = oAjaxRequest.responseXML();
	var bugEventsHTML = XMLParser.getCDataFrom(oXML, "BugEventsHTML");
	if (bugEventsHTML)
	{
		doReplaceBugEvents(bugEventsHTML);
		shrinkImagesToFit();
	}
}

function doReplaceBugEvents(sHTML)
{
	var o = elById("BugEvents");
	if (o && sHTML) o.innerHTML = sHTML;
}

function clickBugSubmit(e, elForm, fXMLSubmit, sValue, bOK)
{
	window.onbeforeunload = null;

	if (bOK)
	{
		Process.start(this, "resultSubmitBug", failureSubmitBug, Lang.getString("FB_SUBMITTING"), "containerBugEdit", "containerInnerBugEdit");
		TabManager.setFormDisabledNames();
	}
	else
	{
		Process.start(this, "resultSubmitBug", failureSubmitBug, Lang.getString("FB_CANCELLING"), "containerBugEdit", "containerInnerBugEdit");
		TabManager.cancelClicked = true;
	}
	
	try { frames.attachFrame.mSel.cleanupDupes(); } catch (e) {};

	enableInputsWithin('submitButtonsEmail', false);
	enableInputsWithin('submitButtonsEdit', false);

	if (window.opera || window.safari) return true;

	if ((1 == fXMLSubmit) && (elForm.nFileCount) && (1 == elForm.nFileCount.value && '' == elForm.File1.value))
	{
		var sQuery = formToQueryString(elForm);
		oAjaxRequest = new AjaxRequest();
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultSubmitBug);
		oAjaxRequest.onfailure(failureSubmitBug);
		oAjaxRequest.open("POST", sDefaultURI, true);
		oAjaxRequest.send("fAlaCarte=1&pre=preSubmitBug&pg=pgBugFields&fMostRecentEventFirst=" + ViewHistoryManager.oViewCurrent.fMostRecentEventFirst + "&" + "OK=" + encodeURIComponent(sValue) + "&" + sQuery);
		return cancel(e);
	}
	
	return true; 
}

function failureSubmitBug()
{
	enableInputsWithin('submitButtonsEmail', true);
	enableInputsWithin('submitButtonsEdit', true);
}

function changeAssignedToSelect(el, e)
{
	if (window.opera || window.safari)
	{
		document.bugform.command.value = 'assign';
		document.bugform.ixPersonAssignedToOverride.value = el.value;
		document.bugform.submit(); 
	}
	else
	{
		var ixPersonAssignedToTemp = el.value; 
		TabManager.changeView('assign'); 
		setTimeout('document.formWithProject.ixPersonAssignedTo.value=' + ixPersonAssignedToTemp + ';', 0);
	}
	return cancel(e);
}

function clickAttach ()
{
	parent.document.getElementById('fIEFileBrowse').value = 1; 
	frames.attachFrame.setTimeout('elById(\'clickMSel\').onclick();', 1);
}

function setElementOnChanges()
{
	// Get HTMLCollections of element types
	var rghcel = ['input', 'textarea', 'select'].map(function (_) { return document.getElementsByTagName(_); });

	// For each of the collections of elements
	rghcel.foreach( function(hcel)
			{ 
				// For each element in the collection
				foreach ( 
					function(el) 
					{ 
						var f = el.onchange;

						// Set the onchange to dirty the form, then do the old onchange
						el.onchange = function(e) 
						{ 
							TabManager.bEditedForm = true; 
							if (f) return f.apply(el, [e]); 
						}; 
					}, 
					hcel 
				);
			}
	);
}

function getQuotedText(el, ixBugEvent)
{
	//Disable the link
	el.onclick = function(){return false;};
	el.firstChild.innerHTML = Lang.getString("FB_FETCHING");

	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		if (fRetry)
		{
			// Request is already busy. If you requested retry, wait half a sec and try again.
			setTimeout(function(){getQuotedText(el, ixBugEvent);}, 500);
			return true;
		}

		return false;
	}

	oAjaxRequest = new AjaxRequest();
	oAjaxRequest.initialize();
	oAjaxRequest.onreadystatechange(resultInsertQuotedText);
	oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pg=pgQuotedEmail&ixBugEvent=" + ixBugEvent, true);
	oAjaxRequest.elTarget = el;
	oAjaxRequest.send(null);
	return true;
}

function resultInsertQuotedText()
{
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	var oXML = oAjaxRequest.responseXML();
	var sQuoted = XMLParser.getCDataFrom(oXML, "QuotedText");
	if (sQuoted)
	{
		var elSpan = nextSiblingOfType(oAjaxRequest.elTarget, "span");
		if (elSpan)
		{
			elSpan.innerHTML = sQuoted;
			var elOnclickTarget = oAjaxRequest.elTarget; 
			oAjaxRequest.elTarget.onclick = function(){toggleReply(elOnclickTarget);  return false;};
			elOnclickTarget.onclick();
		}
	}
}

function goToRelativeBug(ixBug, sCommand, sSearch, sSearchFor, sAlsoSearchClosedBugs, sIgnoreMax)
{
	if (!oAjaxRequest) oAjaxRequest = new AjaxRequest();
	if (oAjaxRequest.isBusy())
	{
		// request is already busy, wait half a sec and try again
		setTimeout("goToRelativeBug('"+ixBug+"','"+sCommand+"','"+sSearch+"','"+sSearchFor+"','"+sAlsoSearchClosedBugs+"','"+sIgnoreMax+"');", 500);
	}
	else
	{
		oAjaxRequest = new AjaxRequest();
		oAjaxRequest.initialize();
		oAjaxRequest.onreadystatechange(resultGoToRelativeBug);
		oAjaxRequest.open("GET", sDefaultURI + "?fAlaCarte=1&pg=pgRelativeBugURL&ixBug=" + ixBug + "&command="+ sCommand + "&search=" + sSearch + "&searchFor=" + sSearchFor + "&bAlsoSearchClosedBugs=" + sAlsoSearchClosedBugs + "&bIgnoreMax=" + sIgnoreMax, true);
		oAjaxRequest.send(null);
	}

	return false;
}

function resultGoToRelativeBug()
{
	if (!XMLParser) XMLParser = new XMLParser();
	if (!oAjaxRequest || !oAjaxRequest.isReady()) return;
	var oXML = oAjaxRequest.responseXML();
	var sRelativeBugURL = XMLParser.getTextFrom(oXML, "RelativeBugURL");
	if (sRelativeBugURL)
	{
		window.location = sRelativeBugURL;
	}
}


