/*
**	CBA, 12/05/05; this file contains those Jscript calls used by pages/controls... 
**	this is the master file located on root for this 
**  app. You reference this file in your pages, ex: <script>.... src=""...</script>
**  A quick test is to add an alert("i am here") in the function call - but be aware it will affect ALL forms calling
**	the same function!! (ex: openQuickReportWindow).
**
**  CBA, 02/25/06; Fine tune calendar presentation while I am working on TO 14, Item 199. See OpenCalendar func.
**
*/
var popUp; 
var iIndex;
var newWindow; 
var popupsBlocked;

// These next group of global vars directly affect the functions for several controls.  It's too 'clunky' to
// update each page/control with this list.  Better maintaining references here.  Then again, better way to do this.
// example: porting to QBWEB_new spotlights defects.
		var prepend1 = "ctlEditProjectDetailsNew_LeftPane_"; // add a prepend string for each control page loaded
		var prepend2 = "EditProjectMainContent_";
		var prepend3 = "EditUpdates_";
		var prepend4 = "ProjectIssueManagement_";
		var prepend5 = "ProjectRiskManagement_";
		var prepend6 = "ProjectChangeManagement_";
		var prepend7 = "ctlReportOptions_";
		var prepend8 = "FilterBy_";
		var prepend9 = "SearchBy_";
		var prepend10 = "ProjectIssueManagementUpdate_";
		var prepend11 = "ProjectRiskManagementUpdate_";
		var prepend12 = "LeftPane_";
		var prepend13 = "ProjectDocuments_";
		


function OpenCalendar(idname, postBack)
{	
	popUp = window.open('Calendar.aspx?formname=' + document.forms[0].name + 
		'&id=' + idname + '&selected=' + document.forms[0].elements[idname].value + '&postBack=' + postBack, 
		'popupcal', 
		'width=270,height=270,left=50,top=100,resizable=yes');
}

function SetDate(formName, id, newDate, postBack)
{
	eval('var theform = document.' + formName + ';');
	popUp.close();
	theform.elements[id].value = newDate;
	if (postBack)
		__doPostBack(id,'');
}

function MoveSelected(lst1, lst2)
{
//alert(lst2)
//alert(document.forms[0].elements[lst2].length)
  var i;
  for (i=0; i<document.forms[0].elements[lst1].length; i++)
  {
   if (document.forms[0].elements[lst1].item(i).selected)
    {
  //  alert(document.forms[0].elements[lst1].item(i));
		document.forms[0].elements[lst2].items.Add(document.forms[0].elements[lst1].item(i));
          
    }
  }
}

function AddSelected(lst1, lst2, hiddenTextBox)
{

 
var i;
var valueSelected = null;
  for (i=0; i<lst1.length; i++)
  {
   if (lst1.item(i).selected)
    {    
	 AddItem(lst2, lst1.item(i).value, lst1.item(i).value);
	 
	 for (x = 0; x < (lst2.length);  x++)
			{
				 
				if(valueSelected == null)
				{
					
					valueSelected = lst2.item(x).value;
				}
				else
				{
					
					valueSelected = valueSelected + "," + lst2.item(x).value;
				}
				
			}
			
			hiddenTextBox.value =  valueSelected; 
    }
  }
}

function RemoveSelected(lst1, hiddenTextBox)
{
var i;
var valueSelected = null;
  for (i=0; i<lst1.length; i++)
  {
   if (lst1.item(i).selected)
    {    
	 RemoveItem(lst1, lst1.item(i).value);
	 
	 for (x = 0; x < (lst1.length);  x++)
			{
				 
				if(valueSelected == "")
				{
					
					valueSelected = lst1.item(x).value;
				}
				else
				{
					
					valueSelected = valueSelected + "," + lst1.item(x).value;
				}
				
			}
			
			hiddenTextBox.value =  valueSelected; 
    }
  }
}

function AddItem(lbxSelection,sDisplay,sKey)
{
RemoveItem(lbxSelection,sKey)
iIndex=lbxSelection.options.length;
lbxSelection.options[iIndex]=new Option(sDisplay,iIndex+1);
lbxSelection.options[iIndex].value=sKey;			 
				 
}

function RemoveItem(lbxSelection,sKey)
{
	var srcLen = lbxSelection.options.length;
	for (var x=srcLen-1; x>=0; x--)
   	if (lbxSelection.options[x].value == sKey) 
    	{
		lbxSelection.options[x]=null;
	}
}


function RemoveAll(lbxSelection, hiddenTextBox)
{
	var srcLen = lbxSelection.options.length;
	for (var x=srcLen-1; x>=0; x--)   	 
		lbxSelection.options[x]=null;
}

/*
**	CBA, 12/05/05; set up setFocus with correct code; used for followup to TO13, Item 141
**  objectID is passed in from the calling event in the .aspx page, NOT FROM CODEBEHIND FILE!
**  search in EditProjectDetailsNew.aspx for more info.
*/
function setFocus(objectID)
{
	var destControl = document.getElementById(objectID);
	if (destControl != null) {
		try {
			destControl.focus();
		}
		catch(e) {
			// do nothing; there is nothing we can do
			return;
		}
	}
}

/*
**	CBA, 12/07/05; FINALLY; figured way to trap key event and if tab key, goes to 
**	objectID passed in...this code was cabbaged from one of MANY Web page postings
**	See EditProjectDetailsNew.aspx for other side; 
**	CBA, 01/24/07; upgrade, makes call to CheckCollapsedPanels. 
*/
function setFocusOnTabKey( e, objectID ) {
	//alert( 'source element id: ' + e.srcElement.id); incorporate the srcElement.id into code 
	// use for case where the dest. id is disabled/invisible
	// next check is if we are Netscape, or other(IE)... if other, e.keyCode assigned to key
	var key = (navigator.appName == "Netscape") ? e.which : e.keyCode;
	switch (key)
	{
		case 9: // tab key pressed...
		var tempID = CheckCollapsedPanels(objectID);
		setFocus(tempID);
		break;
	}
}

/*
**	CheckCollapsedPanels, 01/24/07; 
**	CBA, 01/24/07; Need to make another custom one-off to deal with the collapsed panels and focus and tabbing
**	through the fields.
**
*/
function CheckCollapsedPanels( objectID) {
	// for now, just hardwire the id's as I need to get this done ASAP and it is a custom one-off for 
	// PlanIT situations. Works. Now, how do I make this more dynamic? Need to design something.
	var SummaryPanelStatus =  document.getElementById(prepend2 + 'colProjectSummary_currentState');
	var PlanningPanelStatus =  document.getElementById(prepend2 + 'colProjectPlanning_currentState');
	var PlansPanelStatus =  document.getElementById(prepend2 + 'colPlans_currentState');
	var AnalysisPanelStatus =  document.getElementById(prepend2 + 'colAnalysis_currentState');
	
	// now, based on which initial objectID, we need to check the dest panels if they are collapsed/expanded.
	switch (objectID) {	
		case prepend2 + 'lblProjectId' :
		// last panel to first panel
		if (SummaryPanelStatus != null) {
			if (SummaryPanelStatus.value == 'false')
				return objectID;
			else { // bad. now need to check if next panel is collapsed or not.
				if (PlanningPanelStatus != null) {
					if (PlanningPanelStatus.value == 'false') {
						// set new dest, which is first item in Project Planning.
						return prepend2 + 'lblObjectives';
					}
					else { // doublebad. now need to check 3rd panel in sequence
						if (AnalysisPanelStatus != null) {
							if (AnalysisPanelStatus.value == 'false') {
								// set new dest, which is first item in Project Planning.
								return prepend2 + 'lblImpactCost';
							}
							else { // aint nowhere else to go but this panel!
								return prepend2 + 'lblQualityAssurance';
							}
						}
						else
							return prepend2 + 'lblQualityAssurance';	
					}
				}
				else
					return objectID;
			}
		}
		else
			return objectID;
		break;
		
		case prepend2 + 'lblObjectives' :
		// Project Summary (first panel) to Project Planning (2nd panel)
		if (PlanningPanelStatus != null) {
			if (PlanningPanelStatus.value == 'false')
				return objectID;
			else { // bad. now need to check if next panel is collapsed or not.
				if (AnalysisPanelStatus != null) {
					if (AnalysisPanelStatus.value == 'false') {
						// set new dest, which is first item in Project Planning.
						return prepend2 + 'lblImpactCost';
					}
					else { // doublebad. now need to check 3rd panel in sequence
						if (PlansPanelStatus != null) {
							if (PlansPanelStatus.value == 'false') {
								// set new dest, which is first item in Project Planning.
								return prepend2 + 'lblQualityAssurance';
							}
							else { // aint nowhere else to go but this panel!
								return prepend2 + 'lblProjectId';
							}
						}
						else
							return prepend2 + 'lblProjectId';	
					}
				}
				else
					return objectID;
			}
		}
		else
			return objectID;
		break;
		
		case prepend2 + 'lblImpactCost' :
		// Project Planning (2nd panel) to Analysis (3rd panel)
		if (AnalysisPanelStatus != null) {
			if (AnalysisPanelStatus.value == 'false')
				return objectID;
			else { // bad. now need to check if next panel is collapsed or not.
				if (PlansPanelStatus != null) {
					if (PlansPanelStatus.value == 'false') {
						// set new dest, which is first item in Project Planning.
						return prepend2 + 'lblQualityAssurance';
					}
					else { // doublebad. now need to check 3rd panel in sequence
						if (SummaryPanelStatus != null) {
							if (SummaryPanelStatus.value == 'false') {
								// set new dest, which is first item in Project Planning.
								return prepend2 + 'lblProjectId';
							}
							else { // aint nowhere else to go but this panel!
								return prepend2 + 'lblObjectives';
							}
						}
						else
							return prepend2 + 'lblObjectives';	
					}
				}
				else
					return objectID;
			}
		}
		else
			return objectID;
		break;
		
		case prepend2 + 'lblQualityAssurance' :
		// Analysis (3rd panel) to Plans (last panel)
		if (PlansPanelStatus != null) {
			if (PlansPanelStatus.value == 'false')
				return objectID;
			else { // bad. now need to check if next panel is collapsed or not.
				if (SummaryPanelStatus != null) {
					if (SummaryPanelStatus.value == 'false') {
						// set new dest, which is first item in Project Planning.
						return prepend2 + 'lblProjectId';
					}
					else { // doublebad. now need to check 3rd panel in sequence
						if (PlanningPanelStatus != null) {
							if (PlanningPanelStatus.value == 'false') {
								// set new dest, which is first item in Project Planning.
								return prepend2 + 'lblObjectives';
							}
							else { // aint nowhere else to go but this panel!
								return prepend2 + 'lblImpactCost';
							}
						}
						else
							return prepend2 + 'lblImpactCost';	
					}
				}
				else
					return objectID;
			}
		}
		else
			return objectID;
		break;
		
		default:
		return objectID;
		break;
	}
}

/*
**	CBA, 08/31/06; Release 2.1, ID 196; build a filter string from supplied pairs.
**	This function is called repeatedly.  It takes in the string, the supplied arg pairs and the delimiter
**	It then appends the arg pairs to the string and returns rebuilt string. Initially used in openQuickReportWindow
*/

function BuildFilterString( InputString, LeftArg, RightArg, Delimiter ) {
	var OString = InputString + Delimiter + LeftArg + '=' + RightArg;
	return OString;
}


/*
** 	CBA, 02/28/06; per TO 14, Item 175; dynamically change the cursor
**	for cases where mouseonhover, and showing 'wrong' cursor...
**	current cursor styles - ref Web Development -> HTML and CSS -> etc...
**	Most common options:
**	'crosshair'
**	'hand'
**	'help'
**	'pointer'
**	'progress'
**	'text'
**	and so on... see MSDN reference.
*/
function setCursor(objectID, sCursor) {
	var tempobject = document.getElementById(objectID);
	if (tempobject != null) {
		tempobject.style.cursor = sCursor;
	}
	// hmmmm... best to leave else out for now, should not occur(yea, right!), but I dont need users
	// raising hoolabaloola either.
//	else
//		alert("Cursor Object is NULL");

}

/*
**	CBA, 03/16/06; per TO14, Item 199; opening a second window (or popup)
**	from a link... code is combination of my hackwork and solid script
**	(with good explanations) at www.quirksmode.org/js/croswin.html#topopup
**  JEEZ... heavy mods done related to popupblocker and focus... always case
**  of something simple costing mucho time.  See important comments in code as well.
**	CBA, 11/07/07; HAH!!! Figured out how to set the window title once its opened!  Stupid one-liner!
**	Now add this feature to function passed in as a parm.  Nope.  Back out on this related to file downloads.
**	Still timing issues; that's why check for null value in place.
*/

function openNewWindow(sURL, sName, sFeatures, sWindowTitle) {
	// CBA, 04/09/06; something screwy going on... newWindow is pointing at 'old' window on postback!!!
	// CBA, 04/10/06; went to strict javascript to launch new window, uncomment code and check...
	// nope... on a postback (such as saving a record), newwindow is pointing at 'old' page!!
	// CBA, 09/04/06; Followup Comment, CODE NOTE:  The problem is so long as your browser window is not
	// refreshed (i.e. postback), the current vars are good and ALL windows using this common script.js will
	// work.  I was originally posting back, doing autosave, THEN opening a new report window.  I am leaving this
	// comment in as a reference.  Current code is stable.
		var tempWindow = window.open(sURL, sName, sFeatures );
		if((typeof(tempWindow)=="undefined") || (tempWindow==null)) {
			popupsBlocked = true;
			resetReportCookie();
			alert('Your popupblocker is turned on.  Please add this website to your allowed list, or press the <CTRL> button while pressing the "GO" button.');
			return false; //leave function
		}
		else {
			popupsBlocked = false;
			try{
				if (sWindowTitle != null)
					tempWindow.document.title = sWindowTitle;
			}
			catch(e) {
				// 11/07/07; continue with program; this is a non-fatal error; followup research needed later.
			}
		}
		
	// add a 2nd check if newWindow still there, then set focus....
	if (!popupsBlocked) {
		try{
			tempWindow.focus();
		}
		catch(e) {
			// error occurs because yahoo popup blocker is NOT returning same as MSIE or GoogleBar so add this general try/catch
			popupsBlocked = true;
			resetReportCookie();
			alert('Your popup blocker is turned on.  Please add this website to your allowed list, or press the <CTRL> button while pressing the "GO" button.');
			return false; //leave function
		}
	}
	return false;
}

/*
**	openQuickReportWindow:
**	CBA, 10/03/06; shoot... I knew this should have been placed in the common script.js file.  Things have gotten complicated
**	now that we have gone to tab pages and (correctly) go modular with common controls embedded in common pages/controls.
**	'Commonizing' this function eliminates the issue of multiple definitions with the same function name in your rendered page.
	// CBA, 08/31/06; DESIGN NOTES:  To pass arguments from our calling page to the next one, 
	// we will need to add a Query String for the filter, and manage that in QuickReporting.aspx.
	// Here is the reason why.  1) using JavaScript, and it cannot easily access Session State in
	// ASP.NET (unless a state server is set up).  2) The information passed is the filtering
	// information, so security is ok.  3)  While I could use another cookie, we dont need to do this.
	// Okay, here is the tricky part of the design.  We are setting up the Query String in JavaScript
	// or client side, but we process the string ON THE SERVER in C#, when we build the page.  Here is
	// the tricky part.  Either the string is processed in QuickReporting.aspx, or in the control page.
**	CBA, 01/31/08; Need to add for new Reports in Home.aspx, EditProjectMainContent.ascx; great, how can
**	I better bullet-proof this? 
**	CBA, 02/08/08 put Excel back in related to allowing more than one Excel being open.  see Switch(OutputOptions).
**
*/
function openQuickReportWindow( CONTROLID )
{	

	var prepend = getPrependString( CONTROLID );
	
	var LastReport = document.getElementById(prepend + 'QuickReportTextBox');
	var LastReportValue = LastReport.value; // used later in code
	// CBA, 04/01/06; had to change lblSelectedId from asp:label to asp:textbox; for whatever
	// reason, label doesnt work and I dont have time to hack around.  Leave this comment in
	// as a reference... ddl - works...
	
	// CBA, 08/30/06; Need to force ReportId value to -1 which then triggers the process
	// downstream to select all.  Alternatively, if a user inputs a string in the
	// search box, tbProjectId, in Home.aspx, then take this into account.  Shit. Force to all 'Ids'
	// reason I had to back out is that 'ProjectId' that user inputs is NOT the unique Project Id,
	// and I need to find a way to get the unique Project Id correlating with the user's input (might
	// have it since we need to force a postback?) I dont know.
	// ?10/04/06 - need to revisit this issue? YES reason is that now we are going modular and 
	// have to take into account for Issue/Risk/ChangeManagement search boxes, and for single Id
	// values for the Update boxes.
	
	// 1st one, covers EditProjectMainContent,EditUpdates, Issue/RiskManagement,
	// 2nd one, not only uses projectid, but also uses Issue/RiskId, covers IssueUpdate,RiskUpdate
	// 3rd one, trickiest, in Home.aspx, user selects by a [Project Id], which needs to be correlated to 
	// a unique project record id.
	var ReportId;
	
	var Idbox = document.getElementById(prepend2 + 'lblSelectedId');
	//scenario one : EditProjectMainContent,etc.
	if (Idbox != null) 
		ReportId = Idbox.value;
	// scenario two
	// ReportId = ??get the Issue or Risk unique Id's
	
	if (ReportId == null) // default to all if problems or if none selected; depends on page as well.
		ReportId = "-1";

	var ReportFormat = document.getElementById(prepend + 'ddlReportFormat').value;  // you get the selected value returned.
	var OutputOptions = document.getElementById(prepend + 'ddlOutputOptions').value;
	
	switch(OutputOptions) 
	{
		case 'MS Word (DOC)' :
		case 'Portable Document(PDF)' :
		case 'MS Excel - Data Only Extract'	: // 02/08/08; MARKER, put back in.
			LastReport.value = 'pdf'; // used by this internal scripts on next round back.
			break;
		default:
			LastReport.value = 'HTML';
			break;
	}

	// this next code block was originally written for EditProjectDetailsNew.aspx
	// before I went modular with the design. Related to getting/setting the report cookie.
		var CurrentSessionId = getCookieValue('ASP.NET_SessionId');
		var currentCookie = getCookie('PlanITQuickReportingWindow');
		if (currentCookie != null){
			var CurrentCookieValue = getCookieValue('PlanITQuickReportingWindow');
			var ReportSessionId = CurrentCookieValue.substring(0,CurrentCookieValue.indexOf('::'));
			var Status = CurrentCookieValue.substring( (CurrentCookieValue.length - 1), CurrentCookieValue.length );
			if (ReportSessionId == CurrentSessionId)
			{
				if (Status == '1'){
					if (LastReportValue != "pdf" )  //check if previous report is NOT ms word or pdf; THIS IS IMPORTANT!
						return false;
				}
			}
			else // session Id's are not equal; cannot open window.
			{
				return false;
			}
		}

		var CookieValue = CurrentSessionId + '::' + ReportFormat + '::' + OutputOptions + '::' + ReportId;
		if (LastReport.value == "pdf" ) // now check if current is pdf -> leave cookiestatus as 0
			CookieValue = CookieValue + '::0';
		else
			CookieValue = CookieValue + '::1';
		
		// build the expire object; this was not as 'trivial' as in C# (or VB.NET)
		var currentDate = new Date();
		var currentYear = currentDate.getFullYear();
		var currentMonth = currentDate.getMonth();
		var nextDay = currentDate.getDate() + 1; //set the expire to next day
		var currentHour = currentDate.getHours();
		var currentMinute = currentDate.getMinutes();
			
		var expires = new Date(currentYear, currentMonth, nextDay, currentHour, currentMinute);
		// leave expires object in for reference, and if we wish to use a cookie that expires the next day
		// right now, going with Session cookie (expires when session is done).

		var newCookie = setCookie('PlanITQuickReportingWindow', CookieValue);

	// straight from MS docco.
	var sURL = 'QuickReporting.aspx?formname=QuickReporting&id=QuickReporting&postBack=false';

	// 08/31/06 add-on, build the filter string, use the '&' as delimiter
	var sFilter = "";
	var tempString = "";
	// next batch of code is hardwired to the Home.aspx filters (better way?)
	// CBA, 10/03/06; need to take into account other controls!!!
	// try parent.parent (same hierarchy?) what about document.xx? Trickier; time to learn more JavaScript if 
	// you wish a more elegant solution! Have to revisit this later - I see this getting too bulky/clunky.

	switch (CONTROLID) {
		case 'Home' : 
			for (i = 0; i < 7; i++) {
				switch (i){
					case 0 :
						tempString = "ddlPriorityCodes";
						break;
					case 1 :
						tempString = "ddlStatusCodes";
						break;
					case 2 :
						tempString = "ddlSponsorOrgs";
						break;
					case 3 :
						tempString = "ddlApprovalCodes";
						break;
					case 4 :
						tempString = "ddlCategoryCode";
						break;
					case 5 :
						tempString = "ddlTypeCode";
						break;
					case 6:
						tempString = "ddlMngrCode";
						break;
				}
				sFilter = BuildFilterString(sFilter, tempString, document.getElementById(tempString).value, '&');
			}
			// finally, add the CONTROLID;
			sFilter = BuildFilterString(sFilter, 'CONTROLID', CONTROLID, '&'); 

			break;
		case 'ProjectIssueManagement' :
		case 'ProjectRiskManagement' :
			var prepend = prepend8;
			if (CONTROLID == 'ProjectIssueManagement')
				prepend = prepend4 + prepend8;
			else
				prepend = prepend5 + prepend8;
		//	var prepend = getPrependString( CONTROLID );
			for (i = 0; i < 2; i++){
				switch (i) {
					case 0 :
						tempString = prepend + "ddl1";
						break;
					case 1 :
						tempString = prepend + "ddl2";
						break;
				}
				sFilter = BuildFilterString(sFilter, tempString, document.getElementById(tempString).value, '&'); 
			}
			// finally, add the CONTROLID;
			sFilter = BuildFilterString(sFilter, 'CONTROLID', CONTROLID, '&'); 
			
			break;
		case 'EditProjectMainContent' :
		case 'EditUpdates' :
			// finally, add the CONTROLID;
			sFilter = BuildFilterString(sFilter, 'CONTROLID', CONTROLID, '&');
			break;
		case 'ProjectDocuments' :
		case 'ProjectIssueManagementUpdate' :
		case 'ProjectRiskManagementUpdate' :
			// finally, add the CONTROLID;
			sFilter = BuildFilterString(sFilter, 'CONTROLID', CONTROLID, '&'); 
			break;
	}
	
	sURL = sURL + sFilter;
	// End add-on

	var sName = '_blank';
	var sFeatures = 'menubar=yes,toolbar=yes,location=no,resizable=yes,scrollbars=yes,titlebar=yes,status=yes,left=50,top=100,focus=yes'
	var sWindowTitle = 'PlanIT - QuickReporting Window...';
	
	return ( openNewWindow(sURL, sName, sFeatures, sWindowTitle ));
} // end openQuickReportWindow


/*
**	openFileDownload:  popupwindow related to using file downloads
**	08/26/07; 'quick' test pushing the download to a popup window so main window can also
**	be updated when file download thread closes.  Works; two threads now function 'correctly', i.e.
**	popup window functions on one Response thread (file download) and main thread continues.
**	CBA, 11/07/07; found a solution to set the popup window title to display a custom message, but
**	there is a timing issue, so get intermittent script errors, handled in openNewWindow.
*/
function openFileDownload( FilePath, projectDocoUniqueId )
{	

	// straight from MS docco.
	var sURL = "FileDownload.aspx?FileName=" + FilePath + 
	"&projectDocoUniqueId=" + projectDocoUniqueId + "&postBack=false";
	var sName = '_blank';
	// on features, basically turn off, unless we wish to add some stuff to the placeholder window.
	// also, tried to make it just a 1px x 1px window, didnt seem to take that; 
	var sFeatures = 'menubar=no,toolbar=no,location=yes,resizable=yes,scrollbars=yes,titlebar=yes,status=yes,left=50,top=100,height=25,width=400,focus=yes'
	var sWindowTitle = 'PlanIT - DOWNLOADING FILE...';
		 
	return ( openNewWindow(sURL, sName, sFeatures, sWindowTitle ));
	
	/* 
	from code example, doing file download in popup window; leave in for reference until this is dialed down.
	Response.Redirect(string.Format("WebFormDownload.aspx?FileName={0}&ExportName={1}", fileName, strReportName));

WebFormDownload page:

protected void Page_Load(object sender, EventArgs e) 
{

if (!Page.IsPostBack) 
{

//Prepare response for streaming

Response.Clear(); 
Response.ContentType = "application/vnd.ms-excel";

string header = String.Format("attachment; filename={0}.xls", ExportName); Response.AddHeader("Content-Disposition", header); 
//Stream workbook to response

Response.WriteFile(FileName, true); 
//Delete temporary file

File.Delete(FileName); 
//End response

Response.End(); 
}

end code example	*/

} // end openFileDownload


/*
**	getPrependSring can be used from the forms/controls as well to get the prebuilt strings.
**	
**	ISSUE: This code is still too customized!  I need to make it more general if I wish to extend it further
**			for other situations.
*/
function getPrependString( CONTROLID ) {

	// need to add code to see which page/control we are launching from:
	// i.e. Home.aspx, EditProjectMainContent.ascx, Issue/Risk/ChangeManagement.ascx or Issue/Risk/ChangeManagementUpdates.ascx
	// thus, prepend can be assigned to one of the global vars prependxx
	//see above for values of prependxx
	// NOTE:  the ID's are set for EACH page/control; 
	switch (CONTROLID) {
		case 'Home' :
			return prepend7; // if the control is directly buried in an aspx page, it is just the id itself
			break;
		case 'EditProjectMainContent' :
			return (prepend2 + prepend7); // I had combined to id's into one (first doing this).
			break;
		case 'ProjectIssueManagement' :
			return(prepend4 + prepend7); 
			break;
		case 'ProjectRiskManagement' :
			return( prepend5 + prepend7 );
			break;
		case 'EditUpdates' :
			return(prepend3 + prepend7);
			break;
		case 'ProjectIssueManagementUpdate' :
			return (prepend10 + prepend7);
			break;
		case 'ProjectRiskManagementUpdate' :
			return (prepend11 + prepend7);
			break;
		case 'ProjectDocuments' :
			return (prepend13 + prepend7);
			break;
	}
	
}

/*
**
**	CBA, 11/14/06; revisit handling textbox changed event in javascript.
**	Trying to resolve issues when the textbox content is TRULY changed.  Wire event to here, on client
**	side.
**
*/
function GenericTextBoxHandler(objectID, containerID){
	// template work. clean up if nogo or place in Scripts.js if go.
	var prepend = containerID + '_'; // need to revisit using getPrependString
	if ( prepend == null )
		prepend = ""; // default to an mt string
	var stateBox = document.getElementById('tbSaveData'); // this better be in main page, so no prepend needed.
	var tempObject = document.getElementById(prepend + objectID);

	if (stateBox != null) {
		// process based upon which page/user control we are in (by containerID)
		stateBox.value = containerID + '::' + 'true'; 
	}
}

function CancelEdit(objectID, containerID) {

	var prepend = containerID + '_';
	var stateBox = document.getElementById('tbSaveData');
	var cancelbutton = document.getElementById(prepend + objectID);
	if (stateBox != null) {
		stateBox.value = ''; // reset so autosave does not trigger
	}
	if (cancelbutton != null) {
		cancelbutton.click(); // and trigger postback on cancel button.
	}
}

// CBA, 06/10/07; marker uncommented; mod'd code for fixes related to tbdoccosave and tbtest(testing)
function HandleAttachmentDownload(tbObject, tbFileName, btnObject, containerID, tempBool){
	var prepend = containerID + '_';
	var btnTemp = document.getElementById(prepend + btnObject);
	//var tbTemp = document.getElementById(prepend + tbObject);
	var tbTemp = document.getElementById(tbObject); // for box in main page, no prepend needed
	var tbFile = document.getElementById(prepend + tbFileName);
	
	//tbTemp.value = "TEST";
	//bTemp = true;
	//tbTemp.enabled = true;
	//tbTemp.value = tbTemp.enabled;
	//window.alert(tbTemp.enabled);
	
	// CBA, 08/26/07; add-on, open file download window; tbTemp now has DocoProjectUniqueId
	//window.alert( 'DocoProjectUniqueId: ' + tbtemp.value );
	openFileDownload(tbFile.value,tbTemp.value); // fill out empty strings 
	if (btnTemp != null) {
		btnTemp.click(); 
	}
	

}

/*
**	CBA, 11/15/06; set up new function, called by tabpage onclick event (if assigned to it)
**	ProcessTabClick()
**	CBA, 11/24/06; Reuse this code for the admin tab page.
**	CBA, 12/08/06; Extend design to last object focus on exit/entrance. This extends the FirstFocus usage.
*/

function ProcessTabClick() {
	var stateBox = document.getElementById('tbSaveData');
	var navBox = document.getElementById('tbNavigationTextBox');
	var navStatus = document.getElementById('tbNavigationStatus');
	var tabindexbox = document.getElementById('tbTabIndexFocus'); // for postback focus tbTabIndexFocus
	
	// BE AWARE: This next call is handling an event which occurs AFTER you have moved to the new tab page
	// So problem is (and I see this coming!) user may not wish to see the double-blink/flicker; see next comment.
	// 
	// I have taken advantage of this 'feature' when designing/extending/implementing object focus.
	
	var tabindex = document.getElementById('TabStrip1').selectedIndex; // selected index is a property
	if (tabindex == null)
		tabindex = 0; // default to first tab page.

	if (stateBox.value != null && stateBox.value != "") { 
		if (navBox != null)
			// upgrades, check if navBox is populated (due to ddl change) APPEND tab index to end
			// and Administration.aspx.cs will handle it.
			if (navBox.value != null && navBox.value != "")
				navBox.value = navBox.value + '::' + tabindex;
			else
				navBox.value = tabindex; 
		if (navStatus != null)
			navStatus.value = 'tabpostback::autosave'; // make this parameter?
			
		if (tabindexbox != null)
			tabindexbox.value = tabindex; // use this to make sure you retain focus on a specific tab page.
		
		// at this point, we can only postback and let server side code do its job.
		__doPostBack('TabStrip1', '');
	}
	else {
		if (tabindexbox != null)
			tabindexbox.value = tabindex; // use this to make sure you retain focus on a specific tab page.
		SetTabPageObjectFocus( tabindex, Retrieve_LastFocusObject(tabindex) );
	} 
}

/*
**	CBA, 12/03/06; SetTabPageObjectFocus; spinoff from ProcessTabClick;
**	Repairs the issue of the default object focus that was broken when we went to tabpages.
**	Also sets the focus to the last object when we leave/re-enter the tab page.
*/
function SetTabPageObjectFocus( tabindex, objectid )
{
	// Currently handling EditProjectDetailsTab page or AdministrationTabPage
	// Weird bug; need to check for both string value representation of number OR 
	// long value.  tab page bug? Found it when testing AdministrationTabPage.
	if (document.title == 'EditProjectDetailsTabPage'){
		switch ( tabindex ) {
			case 0:
			case '0':
				if (objectid == '')
					objectid = prepend2 + 'tbProjectId'; // default
				var tempobject = document.getElementById(objectid);
				// CODE NOTE: Originally, had segwayed into checking if the panel state is collapsed or not, 
				// but dont need it since I added checks in setFocus (errors or not).  At the least, I know how
				// to check if state of panel is collapsed or not.
				if (tempobject != null)
					if (!tempobject.disabled)
						setFocus(objectid);
				break;
			case 1:
			case '1':
				if (objectid == '')
					objectid = prepend4 + 'tbIssueTitle'; // default
				var tempobject = document.getElementById(objectid);
				if (tempobject == null) { // next case, issueupdate control is loaded
					objectid = prepend10 + 'tbUpdateComments'
					tempobject = document.getElementById(objectid);
				}
				// okay, now set focus
				if (tempobject != null)
					if (!tempobject.disabled)
						MetaBuilders_FirstFocus_Focus(objectid, objectid);

				break;
			case 2:
			case '2':
				if (objectid == '')
					objectid = prepend5 + 'tbRiskTitle'; // default
				var tempobject = document.getElementById(objectid);
				if (tempobject == null) { // next case, riskupdate control is loaded
					objectid = prepend11 + 'tbUpdateComments'
					tempobject = document.getElementById(objectid);
				}
				// okay, now set focus
				if (tempobject != null)
					if (!tempobject.disabled)
						MetaBuilders_FirstFocus_Focus(objectid, objectid);
				break;
			case 3:
			case '3':
				if (objectid == '')
					objectid = prepend3 + 'tbUpdateComments'; // default
				var tempobject = document.getElementById(objectid);
				if (tempobject != null)
					if (!tempobject.disabled)
						MetaBuilders_FirstFocus_Focus(objectid, objectid);
				break;
			default:
				break;
		}
	}
	else if(document.title == 'AdministrationTabPage'){
		switch ( tabindex ) {
			case '0':
			case 0:
				if (objectid == '')
					//objectid = 'ctlUserIDsContainer_UserSecurity_tbUserName'; // default focus
					objectid = 'ctlUserIDsContainer_UserSecurity_tdHeader'; // new default focus
				break;
			case '1':
			case 1:
				if (objectid == '')
					//objectid = 'ctlHelpContainer_HelpMaint_tbHelpText'; // default focus
					objectid = 'ctlHelpContainer_FilterBy_ddl1'; // new default focus
				break;
			case '2':
			case 2:
				if (objectid == ''){
					//objectid = 'ctlCodesContainer_CodesMaint_tbCode'; // default focus
					objectid = 'ctlCodesContainer_FilterBy_ddl1'; // new default focus
					// quick check which control is loaded in ctlCodesContainer
					var tempobject = document.getElementById(objectid);
					if (tempobject == null)
						//objectid = 'ctlCodesContainer_ResourceMaint_tbResourceName'; 
						objectid = 'ctlCodesContainer_FilterBy_ddl1'; // new default focus
				}
				break;
			case '3':
			case 3:	
				if (objectid == '')
					objectid = 'ctlSystemMaintContainer_SystemMaint_tbSysAdminName'; // default focus
				break;
			default:
				break;
		}
		ProcessCase(objectid);
	}
}

function ProcessCase(objectid) {
	var tempobject = document.getElementById(objectid);
	if (tempobject != null)
		if (!tempobject.disabled)
			//setFocus('ctlUserIDsContainer_UserSecurity_tbUserName');
			MetaBuilders_FirstFocus_Focus(objectid, objectid);
}

function Retrieve_LastFocusObject (tabpageindex) {

	switch (tabpageindex) {
		case 0:
		case '0':
			if (document.TestTabsProjectContainer != null){
				var textbox = document.getElementById(prepend2 + 'tbLastFocusObject');
			}
			else
				var textbox = document.getElementById('ctlUserIDsContainer_UserSecurity_tbLastFocusObject');
			break;
		case 1:
		case '1':
			if (document.TestTabsProjectContainer != null)
				var textbox = document.getElementById(prepend4 + 'tbLastFocusObject');
			else
				var textbox = document.getElementById('ctlHelpContainer_HelpMaint_tbLastFocusObject');
			break;
		case 2:
		case '2':
			if (document.TestTabsProjectContainer != null)
				var textbox = document.getElementById(prepend5 + 'tbLastFocusObject');
			else {
				var textbox = document.getElementById('ctlCodesContainer_CodesMaint_tbLastFocusObject');
				if (textbox == null)
					textbox = document.getElementById('ctlCodesContainer_ResourceMaint_tbLastFocusObject');
			}
			break;
		case 3:
		case '3':
			if (document.TestTabsProjectContainer != null)
				var textbox = document.getElementById(prepend3 + 'tbLastFocusObject');
			else
				var textbox = document.getElementById('ctlSystemMaintContainer_SystemMaint_tbLastFocusObject');
			break;
		default:
			break;
	}
	return ProcessTB(textbox);
}

function ProcessTB(textbox){
	if (textbox != null){
		if (textbox.value != null)
			return textbox.value;
		else 
			return '';
	}
	else
		return '';
}

/******************************  Assign Event Handlers Section  ************************************/
/*
**	CBA, 12/15/06; this section is set up so that we can implement autosave features on the client side
**	which is part of a complete solution to the issue of autosaving the record if a user has made 
**	changes.
**
*/
var activeElement = null;
function blurHandler(evt) {
	activeElement = null;
}
function focusHandler(evt) {
	var e = evt ? evt: window.event;
	if (!e) return;
	if (e.target)
		activeElement = e.target;
	else if(e.srcElement)
		activeElement = e.srcElement;
		
	processTabPage();
}

function processTabPage(){

// find the correct LastObjectBox based on tabindex

	var tabindex = document.getElementById('TabStrip1').selectedIndex;
	if (tabindex == null)
		tabindex = 0; // default to first one

	if (document.TestTabsProjectContainer != null) {
		switch (tabindex){
			case 0:
			case '0':
				var lastbox = document.getElementById(prepend2 + 'tbLastFocusObject');
				if (lastbox != null){
					lastbox.value = document.activeElement.id;
				}
				break;
			case 1:
			case '1':
				var lastbox = document.getElementById(prepend4 + 'tbLastFocusObject');
				if (lastbox != null){
					lastbox.value = document.activeElement.id;
				}

				break;
			case 2:
			case '2':
				var lastbox = document.getElementById(prepend5 + 'tbLastFocusObject');
				if (lastbox != null){
					lastbox.value = document.activeElement.id;
				}

				break;
			case 3:
			case '3':
				var lastbox = document.getElementById(prepend3 + 'tbLastFocusObject');
				if (lastbox != null){
					lastbox.value = document.activeElement.id;
				}

				break;
			default:
				break;
			
		}
	}
	else if (document.AdministrationTabPage != null) {
		switch (tabindex){
			case 0:
			case '0':
				var lastbox = document.getElementById('ctlUserIDsContainer_UserSecurity_' + 'tbLastFocusObject');
				break;
			case 1:
			case '1':
				var lastbox = document.getElementById('ctlHelpContainer_HelpMaint_' + 'tbLastFocusObject');
				break;
			case 2:
			case '2':
				var lastbox = document.getElementById('ctlCodesContainer_CodesMaint_' + 'tbLastFocusObject');
				break;
			case 3:
			case '3':
				var lastbox = document.getElementById('ctlSystemMaintContainer_SystemMaint_' + 'tbLastFocusObject');
				break;
			default:
				break;
		}
		if (lastbox != null){
			lastbox.value = document.activeElement.id;
		}
	}
	
}

function loadHandlerTestTabsContainer() {
	var i, j;
	for( j = 0; j < document.TestTabsProjectContainer.elements.length; j++) {
		if ( FilterObjects(document.TestTabsProjectContainer.elements[j]) ) {
			document.TestTabsProjectContainer.elements[j].onfocus = focusHandler
			document.TestTabsProjectContainer.elements[j].onblur = blurHandler
		}
	}
}

function loadHandlerAdministrationTabPageContainer() {
	var i, j;
	for( j = 0; j < document.AdministrationTabPage.elements.length; j++) {
		if ( FilterObjects(document.AdministrationTabPage.elements[j]) ) {
			document.AdministrationTabPage.elements[j].onfocus = focusHandler
			document.AdministrationTabPage.elements[j].onblur = blurHandler
		}
	}
}

function FilterObjects( FObject ) {
	if (FObject.id.search(/tbLastFocusObject/) > -1)
		return false;
	else if (FObject.id.search(/TabStrip1/) > -1)
		return false;
	else if (FObject.id.search(/tbNavigationTextBox/) > -1)
		return false;
	else if (FObject.id.search(/tbNavigationStatus/) > -1)
		return false;
	else if (FObject.id.search(/tbProjectID1/) > -1)
		return false;
	else if (FObject.id.search(/tbProjectTitle1/) > -1)
		return false;
	else if (FObject.id.search(/tbSaveData/) > -1)
		return false;
	else if (FObject.id.search(/tbTabIndexFocus/) > -1)
		return false;
	else if (FObject.id.search(/btnResourceDeleteYes/) > -1)
		return false;
	else if (FObject.id.search(/btnResourceDeleteNo/) > -1)
		return false;
	else if (FObject.id.search(/btnResourceDelete/) > -1)
		return false;
	else
		return true;
}

/******************************  END Assign Event Handlers Section  *********************************/

/*
**	CBA, 11/24/06; AdminTabPage_ProcessDDL set up related to the 'new' Help and Codes/Resource tab pages in
**	administrationtabpage.  This is more of a custom one-off, placed here instead of in the FilterBy.ascx
**	user control, so dont get multiple copies gen'd up.
**	CODE NOTE: look at the ddl code for reference - also related discussion on SELECT and OPTION elements
**	in my javascript books.
**
*/
function AdminTabPage_ProcessDDL(ddlID) {
	var ddl = document.getElementById(ddlID);
	// these next two are contained in AdministrationTabPage
	var navBox = document.getElementById('tbNavigationTextBox');
	var navStatus = document.getElementById('tbNavigationStatus');
	var codesDDL = document.getElementById('tbCodesDDLStatus');
	var helpDDL = document.getElementById('tbHelpDDLStatus');
	var lastcodeDDLSelected = document.getElementById('tbLastCodeDDLSelected');
	if (ddl != null){
	//	var ddlvalue = ddl.value;
		if (navBox != null)
			navBox.value = ddlID + '::' + ddl.value + '::' + ddl.options[ddl.selectedIndex].text;
			if (ddlID.search(/ctlHelpContainer/) > -1)
				helpDDL.value = navBox.value;
			else{
				navBox.value = navBox.value + "::" + lastcodeDDLSelected.value;
				lastcodeDDLSelected.value = ddl.value; // for next round
				codesDDL.value = navBox.value;
			}
		if (navStatus != null)
		{
			if (navStatus.value == null || navStatus.value == '' )
				navStatus.value = 'admin_ddls::indexchanged'; // again, parameter?
			else
				navStatus.value = navStatus.value + '::admin_ddls::indexchanged' // autosave AND transition
		}
	}
}
/*
**	CBA, 11/25/06; WrapperSaveClick is used strictly for the ResourceMaint, Code and
**	Help ascx controls in AdministrationTabPage.  Another custom one-off, related to the ddl, the save function,
**	and autosave all working correctly.  I will assign this handler to the bt_Save click event. See appropriate
**	controls.
**
*/

function WrapperSaveClick( ddlID ) {
	// first populated nav boxes
	AdminTabPage_ProcessDDL(ddlID);
	// and save the record calling the tab click handler
	ProcessTabClick()
}

/******************************  Manage Cookies Section  ********************************************/
/*
**	CBA,03/22/06;  this section added for Cookies solution related to issues when opening
**	a second window(popup) and timing issues.  This is for client side, equivalent code will be in 
**	new class, ManageCookies.cs?  End up doing code in EditProjectDetailsNew.aspx to check for cookie
**	This code was cabbaged from several web sites: www.webreference.com, www.the-cool-place.co.uk, arachna 
**	web site, Walther's book and other places used for reference.
*/

function listCookies() {
	//alert('What a RAW cookie looks like: ' + document.cookie );
    var theCookies = document.cookie.split(';');
    var aString = '';
    for (var i = 1 ; i <= theCookies.length; i++) {
        aString += i + ' ' + theCookies[i-1] + "\n";
    }
    return aString;
}

function setCookie(name, value, expires, path, domain, secure) {
	//alert('In setCookie. parms: ' + name + ' ' + expires + ' ' + path + ' ' + domain + ' ' + secure + ' ' );
    var curCookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = curCookie;
    return curCookie;
}

function getCookie(name) {
	// Use alternate code version (ref Y. Shiran code); searches whole string.
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);  // takes into account if it is first in string
		if (begin != 0) return null; // not found
	} else
		begin += 2; // places pointer at first letter of 'name'
	var end = document.cookie.indexOf(";", begin);
	if( end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name) {
    var aCookie = getCookie(name);
    if (aCookie != null) {
	//	alert('In deleteCookie; before deleting cookie; name: ' + name );
        document.cookie = aCookie + '; expires=Thu, 01-Jan-70 00:00:01 GMT';  // a cookie is deleted by changing date to previous date.
        return name;
    }
    return null; // add default
}

function getCookieValue(name) {
    var theCookies = document.cookie.split(/[; ]+/); // uses regex, search on '; ' more than one occurence
    for (var i = 0 ; i < theCookies.length; i++) {
        var aName = theCookies[i].substring(0,theCookies[i].indexOf('='));
        if (aName == name) {
			var value = unescape(theCookies[i].substring( (theCookies[i].indexOf('=') + 1),(theCookies[i].length) ));
			return value;
        }
    }
}

function setCookieValue(name, value) {
	var aCookie = getCookie(name);
	if (aCookie != null) {
		setCookie(name,value,null,null,null,null); // will this work? Yep... it does update current cookie value.
	}
}

// CBA, 03/24/06; add cleanup function for case where popupblocker blocked window, need to reset cookie
function resetReportCookie(){
	var CurrentSessionId = getCookieValue('ASP.NET_SessionId');
	var CookieValue = CurrentSessionId + '::0';
	setCookieValue( 'PlanITQuickReportingWindow',CookieValue);
}

/******************************  End Manage Cookies Section  ****************************************/


/******************************  String Management Section  *****************************************/
/*
**	CBA, 03/24/06; This section contains (or will) string manipulation
**	functions using provided javascript internal funcs...
**	1) the string function I wrote in PB to parse a string
**	2) the string funcs I wrote in C
*/

/******************************  End String Management Section  *************************************/


