//
// App() 
// Object is responsible for the dirty pdmwcgi.exe calling so that later on
// we can easily remove it or update it...
// 
// All functions should be called based on the var a = new App() ; a.func() 
// method
//
// Copyright (C) 1999-2002 Solidworks Corporation
// All rights reserved.
//

function App () {
    this.ShowTreeLabelDialog = _app_showTreeLabelDialog;
    this.UpdateTreeLabels = _app_updateTreeLabels;
    this.Logout = _app_logout;
    this.Login = _app_login;
    this.ShowTree = _app_showTree;
    this.ShowAbout = _app_showAbout;
    this.SetMode = _app_setMode;
    this.GetMode = _app_getMode;
    this.ShowDocInfo = _app_docInfo;
    this.ShowReport = _app_showReport;
	this.UpdateReportPanel = _app_UpdateReportPanel;
    this.GetCurrentReport = _app_getCurrentReport;
    this.SetCurrentReport = _app_setCurrentReport;
    this.GetTreeNode = _app_getTreeNode;
    this.SetSelectedNodeId = _app_setSelectedNodeId; // Retrieves currently
    this.GetSelectedNodeId = _app_getSelectedNodeId; // selected tree node
    this.LeftClickTreeItem = _app_leftClickTreeItem;
    this.ExpandParents = _app_expandParents;
    this.OpenDoc = _app_openDoc;
    this.GetAllDocNodes = _app_getAllDocNodes;
    this.GetAllDocAndProjectNodes = _app_getAllDocAndProjectNodes;
    this.GenerateReport = _app_generateReport;
    this.GetGenerateReportArray = _app_getGenerateReportArray;
    this.SetValue = _app_setValue;
    this.GetValue = _app_getValue;
    this.SetWindowStatus = _app_setWindowStatus;
    this.ShowWindowStatus = _app_showWindowStatus;
    this.SetCurrentTab = _app_setCurrentTab;
    this.GetCurrentTab = _app_getCurrentTab;
    this.GetTreeProperties = _app_getTreeProperties;
    this.SetTreeProperties = _app_setTreeProperties;
    this.GetPersistentDate = _app_getPersistentDate;
    this.GetReportXML = _app_getReportXML;
    this.CreateProgressBar = _app_createProgressBar;
    this.DestroyProgressBar = _app_destroyProgressBar;
    this.IncrementProgressBar = _app_incrementProgressBar;
    this.ExpandNode = _app_expandNode;
    this.SetUser = _app_setUser;
    this.GetUser = _app_getUser;
    this.SetPassword = _app_setPassword;
    this.GetPassword = _app_getPassword;
    this.ViewDoc = _app_viewDoc;
	this.ViewPDF = _app_viewPDF;
	this.ShowHelp = _app_showHelp;
}
var LOGIN_MODE = 0;
var DOCINFO_MODE = 1;
var FIND_MODE = 2;
var REPORT_MODE = 3;
var CHANGE_LABELS_MODE = 4;
var ABOUT_MODE = 5;
var OVERVIEW_MODE = 6;

function _app_logout () {
    if (top.m_bWindowsAuthenticationEnabled) {
		alert(top.IDS_CANNOT_LOGOUT_WIN_AUTH);
    }
    else {
        if (confirm (top.IDS_PDMWEB_WANT_TO_LOGOUT)) {
            // RHM - 2/5/03 - Delete the session cookies, not the persistent
            deleteSessionCookie("sessionname");
            deleteSessionCookie("sessionpassword");
            _app_setUser("");
            _app_setPassword("");
            top.frames["framePanel"].document.location.href = "detail_blank.html";
            top.frames["frameTree"].document.location.reload();
            var frameLeft = top.document.getElementById("frameLeft");
            frameLeft.rows = "*,0"; // hide panel
	    top._mode = LOGIN_MODE;
        }
    }
}

function _app_showTree () {
    top.frames["frameTree"].document.location.href = "tree.html";
}


function _app_showAbout () {
    top.frames["frameDetail"].location.href = "about.html";
	top._mode = ABOUT_MODE;
}

function _app_setMode(i_mode) {
    var frameLeft = top.document.getElementById("frameLeft");
    if (i_mode == REPORT_MODE) {
		// Show report panel
		top.frames["framePanel"].document.location.href = "report_panel.html";
		frameLeft.rows = "*, 310";
		top._mode = REPORT_MODE;
		_app_UpdateReportPanel();
    }
    else if (i_mode == FIND_MODE) { // For Find mode
		top.frames["framePanel"].document.location.href = "find_panel.html";
		frameLeft.rows = "*, 200";
		top._mode = FIND_MODE;
    }
    else if (i_mode == DOCINFO_MODE) { // Assuming REPORT_MODE for now
		// Show doc info panel
		var reportInfo = _app_getCurrentReport();
		var treeSourceId = reportInfo.treeSourceId;
		_app_docInfo(treeSourceId);
		frameLeft.rows = "*, 0"; // hide panel
		top._mode = DOCINFO_MODE;
    }
	else if (i_mode == LOGIN_MODE) { // User is logging out
		frameLeft.rows = "*, 0"; // hide panel
		_app_login();
		// _app_login will set top._mode
	}
	else if (i_mode == ABOUT_MODE) {
		frameLeft.rows = "*, 0"; // hide panel
		_app_showAbout();
		// _app_showAbout will set top._mode
	}
	else if (i_mode == CHANGE_LABELS_MODE) {
		top._mode = CHANGE_LABELS_MODE;
    }
	else if (i_mode == OVERVIEW_MODE) {
		top._mode = OVERVIEW_MODE;
	}
    else {
		reportError("_app_setMode() -- Unhandled mode: " + i_mode);
    }
}

function _app_getMode() {
    return top._mode;
}

function _app_showHelp() {
	var help_window;
	if (top._mode == REPORT_MODE) {
		help_window = window.open(top.m_strLangHelpDir + "/PDMWorksWebPortalHelp.htm?topic=reporting","pdmworks_help","height=400,width=700,scrollbars=yes,resizable=yes");
	}
	else if (top._mode == FIND_MODE) {
		help_window = window.open(top.m_strLangHelpDir +"/PDMWorksWebPortalHelp.htm?topic=findsearch","pdmworks_help","height=400,width=700,scrollbars=yes,resizable=yes");
	}
	else if (top._mode == DOCINFO_MODE) {
		help_window = window.open(top.m_strLangHelpDir +"/PDMWorksWebPortalHelp.htm?topic=rdi","pdmworks_help","height=400,width=700,scrollbars=yes,resizable=yes");
	}
	else if (top._mode == LOGIN_MODE) {
		help_window = window.open(top.m_strLangHelpDir +"/PDMWorksWebPortalHelp.htm?topic=login","pdmworks_help","height=400,width=700,scrollbars=yes,resizable=yes");
	}
	else if (top._mode == CHANGE_LABELS_MODE) {
		help_window = window.open(top.m_strLangHelpDir +"/PDMWorksWebPortalHelp.htm?topic=changelabels","pdmworks_help","height=400,width=700,scrollbars=yes,resizable=yes");
	}
	else if (top._mode == OVERVIEW_MODE) {
		help_window = window.open(top.m_strLangHelpDir +"/PDMWorksWebPortalHelp.htm?topic=overview","pdmworks_help","height=400,width=700,scrollbars=yes,resizable=yes");
	}
	else {
		help_window = window.open(top.m_strLangHelpDir +"/PDMWorksWebPortalHelp.htm","pdmworks_help","height=400,width=700,scrollbars=yes,resizable=yes");
	}
	help_window.focus();
}

function  _app_docInfo (i_treeSourceId) {

    var objNode = _getTreeNode(i_treeSourceId);
    if (objNode == null) {
		// source id is null when nothing is selected, so commenting out error
		// reportError ('_app_docInfo(' + i_treeSourceId + ') is null.');
		return false;
    }
    if (objNode.nodeName == "doc") {
		if (objNode.getAttribute("access") == 3) {
	    	top.frames["frameDetail"].document.location.href 
				= "DocInfoNoAccess.html";
		}
		else {
        	var strDocName = objNode.getAttribute("name");
	    	top.frames["frameDetail"].document.location.href 
				= "DocInfo.html?Document=" + encodeURIComponent(strDocName);
			top._mode = DOCINFO_MODE;
		}
    }
	else
	{
		// Show a blank doc info page
		top.frames["frameDetail"].document.location.href
			= "DocInfo.html";
	}
    return true;
}

function _app_showReport () {
    // First go around to just display the items under the list
    // Retrieve settings on how to format
    // grab handle to XML document
    var reportInfo = _app_getCurrentReport();
    var treeSourceId = reportInfo.treeSourceId;
    var objNode = _app_getTreeNode(treeSourceId);
    if (objNode == null) {
		return 0; // Did not set tree node yet
	}
	top.m_strReportItem = objNode.getAttribute("name")
	// Format item type to be as type for data
   top.frames["frameDetail"].location.href = "reporting.html";
	top._mode = REPORT_MODE;
}

function _app_UpdateReportPanel() {
    var reportInfo = _app_getCurrentReport();
    var treeSourceId = reportInfo.treeSourceId;
    var objNode = _app_getTreeNode(treeSourceId);
    if (objNode == null) {
        return 0; // Did not set tree node yet
    }
    top.m_strReportItem = objNode.getAttribute("name");
    // Format item type to be as type for data
    var app = new App();
    var reportInfo = app.GetCurrentReport();
    reportInfo.revision = "";
    reportInfo.config = "";
    top.frames["framePanel"].location.href = "report_panel.html";
    top._mode = REPORT_MODE;
}


function _app_getReportXML() {
    return top.m_strReportDocs;
}
function _app_getTreeNode(i_treeSourceId) {
    var objNode = null;
    if (i_treeSourceId == "ALL") { // Special case to get whole vault view
	objNode = _getTopTreeNode();
    }	
    else {
	objNode = _getTreeNode(i_treeSourceId);
    }
    return objNode;
}

function _getAppForm() {
    var objForm = top.frames["frameToolbar"].document.forms["frm"];
    return objForm;
}

//
// _getTreeNode
// Retrieves tree node at selected node
// Throws Exception
//
function _getTreeNode(i_treeSourceId) {
    var objXML = top.frames["frameTree"].m_xmlDoc;
    if (typeof(objXML) == "undefined") {
        return null;
    }
    var objId = 
    objXML.selectSingleNode('//doc [@id = "' + i_treeSourceId + '"] | //project [@id="' + i_treeSourceId + '"] | //range [@id="' + i_treeSourceId + '"]');
    return objId;
}

//
// _getTopTreeNode
//
function _getTopTreeNode() {
    var objXML = top.frames["frameTree"].m_xmlDoc;
    var objId = objXML.selectSingleNode("//tree");
    return objId;
}


function _app_getCurrentReport() {
    return top.m_reportInfo;
}


function _app_setCurrentReport(i_obj) {
    top.m_reportInfo = i_obj;
}

//
// _app_leftCli
// Performs left click on tree item
//
function _app_leftClickTreeItem(i_treeSourceId) {
    return top.frames["frameTree"].treeDocItem_onLeftClick(i_treeSourceId);
}

function _app_expandParents(i_treeSourceId) {
    return top.frames["frameTree"].expandParents(i_treeSourceId);
}

function _app_expandNode(i_strNode, i_obj) {
    return top.frames["frameTree"].expandNode(i_strNode, i_obj);
}

function _IsFileTypeSolidWorksOnly(i_objNode) {
    var fileType = i_objNode.getAttribute("type");
    if (fileType >= 2 && fileType <= 5) {
	return true;
    }
    else {
        return false;
    }
}

function _IsFileTypePartOrAssy(i_objNode) {
    var fileType = i_objNode.getAttribute("type");
    if (fileType == 2 || fileType == 3) {
	return true;
    }
    else {
        return false;
    }
}

// i_strObjName -- string i.e. node2 or node3 of object to be selected
function _app_setSelectedNodeId(i_strObjName) {
    top.m_strSelectedTreeNodeId = i_strObjName;
}

// returns object of XML tree node currently selected (not view)
// 
function _app_getSelectedNodeId() {
    return top.m_strSelectedTreeNodeId;
}

// returns true or false whether or not the revision with
// the given name in the revision pulldown is obsolete / archived.
// If the " (Archived)" string is in the name, then obsolete.
function _IsRevObsolete(i_strRevText) {
	var strArchived = top.IDS_PDMWEB_ARCHIVED;

	// Is rev name shorter than archive string?
	if (i_strRevText.length < strArchived.length) {
		return false;
	}

	// Is archive string embedded in rev name
	if (i_strRevText.indexOf(strArchived) > 0) {
		return true;
	}

	// Default to not archived / obsolete
	return false;
}

// returns "rw", "ro", "un" or "no" for revision access
// using the given color in the revision pulldown.
// see docinfo.js for color values
function _GetRevAccess(i_strRevColor) {

	if (i_strRevColor == "#000000") {	// black text - rw
		return "rw";
	}
	else if (i_strRevColor == "#EC6A00" ||
			 i_strRevColor == "#ec6a00") {	// orange text - ro
		return "ro";
	}
	else if (i_strRevColor == "#1C60A0" ||
			 i_strRevColor == "#1c60a0") {	// blue text - unmanaged
		return "un";
	}

	return "no";
}

//
// 
function _app_openDoc() {
    var objTree = this.GetTreeNode(this.GetSelectedNodeId());
    if ((objTree == null) || (objTree.nodeName != "doc")) {
		alert (top.IDS_PDMWEB_PLS_SELECT_DOC_TO_OPEN);
		return 0;
    }
    var strDocName = objTree.getAttribute("name");
    var strRev = objTree.getAttribute("revision");
	var strRevText = "";
	var strRevAccess = "no";
	var bRevObsolete = false;
	var strConfig = "";
	var strRevColor = "";

    // Retrieve doc and rev
    // Try to open based on revision shown in Document info
    try {
        var strLoc = top.frames["frameDetail"].location.href;
		var re = /docinfo.html/i;
		if (strLoc.match(re)) { // We should check user's selected revision
			var objWnd = top.frames["frameDetail"].document;
			var elTxtDoc = objWnd.getElementById("txtDocument");
			strDocName = elTxtDoc.value;
			var elCboRev = objWnd.getElementById("cboRevision");
			strRev = elCboRev.options[elCboRev.selectedIndex].value;
			strRevText = elCboRev.options[elCboRev.selectedIndex].text;
			bRevObsolete = _IsRevObsolete(strRevText);
			strRevColor = elCboRev.options[elCboRev.selectedIndex].style.color;
			strRevAccess = _GetRevAccess(strRevColor);
			var elCboConfigs = objWnd.getElementById("cboConfigs");
			strConfig = elCboConfigs.options[elCboConfigs.selectedIndex].value;
		}
    }
    catch (e) {
        reportWarning("_app_openDoc() -- Caught exception, using defaults.");
    }

    // Test to see if user has permissions to open document
	var iAccess = objTree.getAttribute("access");
	// If user has both no access to document and no access to revision,
	// just show error saying they don't have access to document
    if (iAccess == 3 && strRevAccess == "no") {
		// Does not have read access
	    alert (top.IDS_PDMWEB_NO_READ_ACCESS);
		return 0;
    }

	// If user has access to the document but not the selected revision,
	// then show a more specific error saying that.
	if (strRevAccess == "no") {
		// Does not have read access to the selected revision
		alert(top.IDS_PDMWEB_NO_REVISION_READ_ACCESS);
		return 0;
	}

    if (iAccess == 4 || strRevAccess == "un") {
		// Does not have read access
	    alert (top.IDS_PDMWEB_NOT_REVMANAGED_ACCESS);
		return 0;
    }

	// Test to see if the revision is obsolete
	if (bRevObsolete) {
		// Revision obsolete / archived
		alert (top.IDS_PDMWEB_CANNOT_OPEN_ARCHIVED_DOC_REVISION);
		return 0;
	}

	// Should we open the document in eDrawings or via the document's MIME type?
	var bOpenInEDrawings = false;
	var bReadOnlyUser = false;
	var bReadOnlyUserAllowedToOpenDocs = getReadOnlyUserAllowedToOpenDocs();

	// PDF documents are always RO, so allow all RO users to open
	var strFileExtension = _GetFileExtension(strDocName);
    if (strFileExtension == "pdf")
		bReadOnlyUserAllowedToOpenDocs = true;

	if (iAccess == 2 || strRevAccess == "ro") {

		bReadOnlyUser = true;

		// Has read-only access - redirect to eDrawings in as many cases as possible
		// Determine file type here for now, but probably want
		// to get it from the server via XML in the long term
		switch (strFileExtension) {
		case "eprt":
		case "easm":
		case "edrw":
		case "edw":
		case "markup":
		case "dwg":
		case "dxf":
		case "sldprt":
		case "sldasm":
		case "slddrw":
			if (bReadOnlyUserAllowedToOpenDocs==false) {
				bOpenInEDrawings = true;
			}
			break;
	
		case "prt":
		case "asm":
		case "drw":
			if (bReadOnlyUserAllowedToOpenDocs==false) {
		        bOpenInEDrawings = getRecognizeShortExtensionsAsSW();
			}
			break;

		case "pdf":
			// PDF documents are always RO, so allow all RO users to open
			bReadOnlyUserAllowedToOpenDocs==true;
		        bOpenInEDrawings = false;
			break;
	
		default:
			bOpenInEDrawings = false;
			break;
		}
	}

	if (bOpenInEDrawings) {
		// Launch viewing window
		try {
			var strDocNameEscaped = escapeCharsForEDrawings(strDocName);
			var viewingURL = "viewing.html?Request=GetEDrawing&Revision=" + encodeURIComponent(strRev) + "&Config=" + encodeURIComponent(strConfig) + "&Z1=" + convert_value_z(_app_getUser()) + "&Z2=" + convert_value_z(_app_getPassword()) + "&loginname=" + _app_getUser() + "&loginpassword=" + _app_getPassword() + "&Document=" + encodeURIComponent(strDocName) + "&ZDoc=/" + strDocNameEscaped;
			var eDrawingsWindow = window.open(viewingURL,getUniqueWindowName(),"height=565,width=600,resizable=yes");			
			eDrawingsWindow.focus();
		}
		catch (e) {
			alert("_app_openDoc() - Caught exception opening viewing window.");
		}
	}
	else
	{
		// Normal open
		if (bReadOnlyUser && (bReadOnlyUserAllowedToOpenDocs==false)) {
			alert(top.IDS_PDMWEB_NO_ACCESS_TO_OPEN);
		}
		else {
			var frm = top.frames["frameToolbar"].document.forms["frmOpenDoc"];
			frm.action = "./pdmwcgi.exe?Request=GetDoc&Document=" + encodeURIComponent(strDocName) + "&Revision=" + encodeURIComponent(strRev) + "&Z1=" + convert_value_z(_app_getUser()) + "&Z2=" + convert_value_z(_app_getPassword())  + "&ZDoc=/" + strDocName;
			frm.elements["loginname"].value = _app_getUser();
			frm.elements["loginpassword"].value = _app_getPassword();
			frm.submit();
		}
	}
}

//
// Return if the given string is a number or not.
// All the characters must be 0 to 9 to be a number.
//
function _IsNumber(strInput)
{
var i;
var oneChar;

   for (i=0; i<strInput.length; i++)
   {
      oneChar = strInput.substring(i,i+1)
      if (oneChar < "0" || oneChar > "9")
      {
        return false
      }
   }
   return true
}

//
// Return the file extension in the given filename.  The extension
// returned will be in lowercase.
//
// Note that if the filename has a version (e.g. "foo.prt.1"), this
// function will return the file extension without the version (e.g. "prt").
//
function _GetFileExtension(strFileName)
{
var strExtension;
var iPeriodIndex;
var strFileNameMinusNumber;

   strExtension = "";

   if (strFileName != "") {
       iPeriodIndex = strFileName.lastIndexOf(".");
       if (iPeriodIndex != -1) {
          strExtension = strFileName.substring(iPeriodIndex+1,strFileName.length);
          strExtension = strExtension.toLowerCase();

          // If a number, move back one period (for handling filenames with version numbers - like Pro/E)
          if (_IsNumber(strExtension)) {
             strFileNameMinusNumber = strFileName.substring(0,iPeriodIndex);
             iPeriodIndex = strFileNameMinusNumber.lastIndexOf(".");
             if (iPeriodIndex != -1) {
                strExtension = strFileNameMinusNumber.substring(iPeriodIndex+1,strFileNameMinusNumber.length);
                strExtension = strExtension.toLowerCase();
             }
             else
             {
                strExtension = "";
             }
          }
       }
   }

   return strExtension;
}

//
// 
function _app_viewDoc() {
    var i_SelectedNodeId = this.GetSelectedNodeId();
    var objTree = this.GetTreeNode(i_SelectedNodeId);
    if ((objTree == null) || (objTree.nodeName != "doc")) {
		alert (top.IDS_PDMWEB_PLS_SELECT_DOC_TO_VIEW);
		return 0;
    }
    var strDocName = objTree.getAttribute("name");
    var strRev = objTree.getAttribute("revision");
	var strRevText = "";
	var bRevObsolete = false;
    var strConfig = "";

	// Determine file type here for now, but probably want
	// to get it from the server via XML in the long term
	var bOkToView = false;
	var strFileExtension = _GetFileExtension(strDocName);
	switch (strFileExtension) {
	case "eprt":
	case "easm":
	case "edrw":
	case "markup":
	case "dwg":
	case "dxf":
	case "edw":
	case "sldprt":
	case "sldasm":
	case "slddrw":
		bOkToView = true;
		break;

	case "prt":
	case "asm":
	case "drw":
		bOkToView = getRecognizeShortExtensionsAsSW();
		break;

	default:
		bOkToView = false;
		break;
	}

	if (bOkToView) {
	   // Retrieve doc and rev
	   // Try to view based on revision and config shown in Document info
	   try {
		   var strLoc = top.frames["frameDetail"].location.href;
		   var re = /docinfo.html/i;
		   var strRevColor = "";
		   var strRevAccess = "no";
		   if (strLoc.match(re)) { // We should check user's selected revision
			  var objWnd = top.frames["frameDetail"].document;
			  var elTxtDoc = objWnd.getElementById("txtDocument");
			  strDocName = elTxtDoc.value;
			  var elCboRev = objWnd.getElementById("cboRevision");
			  strRev = elCboRev.options[elCboRev.selectedIndex].value;
			  strRevText = elCboRev.options[elCboRev.selectedIndex].text;
			  bRevObsolete = _IsRevObsolete(strRevText);
			  strRevColor = elCboRev.options[elCboRev.selectedIndex].style.color;
			  strRevAccess = _GetRevAccess(strRevColor);
			  var elCboConfigs = objWnd.getElementById("cboConfigs");
			  strConfig = elCboConfigs.options[elCboConfigs.selectedIndex].value;
		   }
	   }
	   catch (e) {
		   reportWarning("_app_viewDoc() -- Caught exception getting revision / config, using defaults.");
	   }

	   // Test to see if user has permissions to view document
	   // Note that if they don't have access to the document, they
	   // may still have access to the selected revision.
	   if (objTree.getAttribute("access") == 3 && strRevAccess == "no") {
		  alert (top.IDS_PDMWEB_NO_READ_ACCESS);
		  return 0;
	   }

	   // If user has access to the document but not the selected revision,
	   // then show a more specific error saying that.
	   if (strRevAccess == "no") {
		   // Does not have read access to the selected revision
		   alert(top.IDS_PDMWEB_NO_REVISION_READ_ACCESS);
		   return 0;
	   }

	   if (objTree.getAttribute("access") == 4 || strRevAccess == "un") {
		  alert (top.IDS_PDMWEB_NOT_REVMANAGED_ACCESS);
		  return 0;
	   }

	   // Test to see if the revision is obsolete
	   if (bRevObsolete) {
		   // Revision obsolete / archived
		   alert (top.IDS_PDMWEB_CANNOT_VIEW_ARCHIVED_DOC_REVISION);
		   return 0;
	   }

	   // Launch viewing window
	   try {
		   var strDocNameEscaped = escapeCharsForEDrawings(strDocName);
           var viewingURL = "viewing.html?Request=GetEDrawing&Revision=" + encodeURIComponent(strRev) + "&Config=" + encodeURIComponent(strConfig) + "&Z1=" + convert_value_z(_app_getUser()) + "&Z2=" + convert_value_z(_app_getPassword()) + "&loginname=" + _app_getUser() + "&loginpassword=" + _app_getPassword() + "&Document=" + encodeURIComponent(strDocName) + "&ZDoc=/" + strDocNameEscaped;
		   var eDrawingsWindow = window.open(viewingURL,getUniqueWindowName(),"height=565,width=600,resizable=yes");
		   // var eDrawingsWindow = window.open(viewingURL,"eview","height=565,width=600,resizable=yes");
		   eDrawingsWindow.focus();
	   }
	   catch (e) {
		   alert("_app_viewDoc() - Caught exception opening viewing window.");
	   }
	}
	else {
		alert(top.IDS_PDMWEB_MAY_NOT_VIEW_DOC_IN_EDRAWINGS);
	}
}

//
// 
function _app_viewPDF() {
    var objTree = this.GetTreeNode(this.GetSelectedNodeId());
    if ((objTree == null) || (objTree.nodeName != "doc")) {
		alert (top.IDS_PDMWEB_PLS_SELECT_DOC_TO_OPEN);
		return 0;
    }
    var strDocName = objTree.getAttribute("name");
    var strRev = objTree.getAttribute("revision");
	var strRevText = "";
	var strRevAccess = "no";
	var bRevObsolete = false;
	var strConfig = "";
	var strRevColor = "";

    // Retrieve doc and rev
    // Try to open based on revision shown in Document info
    try {
        var strLoc = top.frames["frameDetail"].location.href;
		var re = /docinfo.html/i;
		if (strLoc.match(re)) { // We should check user's selected revision
			var objWnd = top.frames["frameDetail"].document;
			var elTxtDoc = objWnd.getElementById("txtDocument");
			strDocName = elTxtDoc.value;
			var elCboRev = objWnd.getElementById("cboRevision");
			strRev = elCboRev.options[elCboRev.selectedIndex].value;
			strRevText = elCboRev.options[elCboRev.selectedIndex].text;
			bRevObsolete = _IsRevObsolete(strRevText);
			strRevColor = elCboRev.options[elCboRev.selectedIndex].style.color;
			strRevAccess = _GetRevAccess(strRevColor);
			var elCboConfigs = objWnd.getElementById("cboConfigs");
			strConfig = elCboConfigs.options[elCboConfigs.selectedIndex].value;
		}
    }
    catch (e) {
        reportWarning("_app_openPDF() -- Caught exception, using defaults.");
    }

    // Test to see if user has permissions to open document
	var iAccess = objTree.getAttribute("access");
	// If user has both no access to document and no access to revision,
	// just show error saying they don't have access to document
    if (iAccess == 3 && strRevAccess == "no") {
		// Does not have read access
	    alert (top.IDS_PDMWEB_NO_READ_ACCESS);
		return 0;
    }

	// If user has access to the document but not the selected revision,
	// then show a more specific error saying that.
	if (strRevAccess == "no") {
		// Does not have read access to the selected revision
		alert(top.IDS_PDMWEB_NO_REVISION_READ_ACCESS);
		return 0;
	}

    if (iAccess == 4 || strRevAccess == "un") {
		// Does not have read access
	    alert (top.IDS_PDMWEB_NOT_REVMANAGED_ACCESS);
		return 0;
    }

	// Test to see if the revision is obsolete
	if (bRevObsolete) {
		// Revision obsolete / archived
		alert (top.IDS_PDMWEB_CANNOT_OPEN_ARCHIVED_DOC_REVISION);
		return 0;
	}

	// Should we open the document in eDrawings or as a PDF?
	var bOpenInEDrawings = false;
	var bOpenAsPDF = false;
	var bUseGetPDFRequest = false;

	var strFileExtension = _GetFileExtension(strDocName);
	switch (strFileExtension) {
	    case "eprt":
		case "easm":
		case "edrw":
		case "edw":
			bOpenInEDrawings = true;
			break;

		case "slddrw":
			if (getHasPDF(strDocName,strRev))
			{
				bOpenAsPDF = true;
				bUseGetPDFRequest = true;
			}
			else
				bOpenInEDrawings = true;
			break;

		case "pdf":
			bOpenAsPDF = true;
			bUseGetPDFRequest = false;
			break;
	
		case "drw":
			var bRecognizeDrwAsSW = getRecognizeShortExtensionsAsSW();
			if (bRecognizeDrwAsSW) {
				if (getHasPDF(strDocName,strRev))
				{
					bOpenAsPDF = true;
					bUseGetPDFRequest = true;
				}
				else
					bOpenInEDrawings = false;
			}
			break;
	
		default:
			bOpenInEDrawings = false;
			bOpenAsPDF = false;
			break;
	}

	if (bOpenInEDrawings)
	{
		// Launch eDrawings viewing window
		try {
			var strDocNameEscaped = escapeCharsForEDrawings(strDocName);
			var viewingURL = "viewing.html?Request=GetEDrawing&Revision=" + encodeURIComponent(strRev) + "&Config=" + encodeURIComponent(strConfig) + "&Z1=" + convert_value_z(_app_getUser()) + "&Z2=" + convert_value_z(_app_getPassword()) + "&loginname=" + _app_getUser() + "&loginpassword=" + _app_getPassword() + "&Document=" + encodeURIComponent(strDocName) + "&ZDoc=/" + strDocNameEscaped;
			var eDrawingsWindow = window.open(viewingURL,getUniqueWindowName(),"height=565,width=600,resizable=yes");			
			eDrawingsWindow.focus();
		}
		catch (e) {
			reportError ("_app_viewPDF() -- Caught exception opening eDrawings viewing window.");
		}
	}
	else if (bOpenAsPDF)
	{
		try {
			var strCGIUrl = getPDMCGIUrl();
			var strUrl;
			if (bUseGetPDFRequest) {
				// Use GetPDF request to get PDF file for a drawing
				//strUrl = strCGIUrl + "?Request=GetPDF&Revision=" + encodeURIComponent(strRev) + "&Z1=" + convert_value_z(_app_getUser()) + "&Z2=" + convert_value_z(_app_getPassword()) + "&loginname=" + _app_getUser() + "&loginpassword=" + _app_getPassword() + "&Document=" + encodeURIComponent(strDocName) + "&ZDoc=/" + strDocName;

				var frm = top.frames["frameToolbar"].document.forms["frmOpenDoc"];
				frm.action = "./pdmwcgi.exe?Request=GetPDF&Revision=" + encodeURIComponent(strRev) + "&Z1=" + convert_value_z(_app_getUser()) + "&Z2=" + convert_value_z(_app_getPassword()) + "&Document=" + encodeURIComponent(strDocName) + "&ZDoc=/" + strDocName;
				frm.elements["loginname"].value = _app_getUser();
				frm.elements["loginpassword"].value = _app_getPassword();
				frm.submit();
			}
			else
			{
// Forms approach, but causes an empty IE window to appear
				var frm = top.frames["frameToolbar"].document.forms["frmOpenDoc"];
				frm.action = "./pdmwcgi.exe?Request=GetDoc&Document=" + encodeURIComponent(strDocName) + "&Revision=" + encodeURIComponent(strRev) + "&Z1=" + convert_value_z(_app_getUser()) + "&Z2=" + convert_value_z(_app_getPassword())  + "&ZDoc=/" + strDocName;
				frm.elements["loginname"].value = _app_getUser();
				frm.elements["loginpassword"].value = _app_getPassword();
				frm.submit();

				// Use GetDoc request to get raw PDF file from vault
//				strUrl = strCGIUrl + "?Request=GetDoc&Revision=" + encodeURIComponent(strRev) + "&Z1=" + convert_value_z(_app_getUser()) + "&Z2=" + convert_value_z(_app_getPassword()) + "&loginname=" + _app_getUser() + "&loginpassword=" + _app_getPassword() + "&Document=" + encodeURIComponent(strDocName) + "&ZDoc=/" + strDocName;
			}

//			var pdfframedoc = top.frames["frameToolbar"].document;
//			var objIFrame = pdfframedoc.getElementById("PDFViewFrame");


//			if (objIFrame == null) {
//				reportError("_app_viewPDF() -- PDFViewFrame null");
//			}
//			else
//			{
				// Open PDF, causing Adobe Reader to open
//				objIFrame.src = strUrl;
//			}
		}
		catch (e) {
			reportError ("_app_viewPDF() -- Caught exception Viewing As PDF.  Please reinstall Adobe Reader.");
		}
	}
	else
	{
		alert (top.IDS_PDMWEB_CANNOT_VIEW_IN_ADOBE_READER);
	}
}

function _app_getAllDocNodes() {
    var objXML = top.frames["frameTree"].m_xmlDoc;
    if (objXML == null) {
	reportError ("_app_getAllDocsNodes() -- frameTree null.");
	return null;
    }
    return objXML.selectNodes("//doc");
}

function _app_getAllDocAndProjectNodes() {
    var objXML = top.frames["frameTree"].m_xmlDoc;
    if (objXML == null) {
	reportError("App::GetAllDocAndProjectNodes() -- frameTree null.");
	return null;
    }
    return objXML.selectNodes("//doc | //project ");
}

//
// _app_generateReport
// Generates report information 
//
function _app_generateReport(i_objXML) {
//    top.m_arrFilteredGenerateReports = i_arrDocs;
//    top.m_strReportDocs = i_strDocs;
    top.m_objGenerateReports = i_objXML;
    top.frames["frameDetail"].location.href 
		= "generate_report_results.html";
	top._mode = REPORT_MODE;
    // objForm.elements["Request"].value = "GenerateReport";
}

function _app_getGenerateReportArray() {
    return top.m_arrFilteredGenerateReports;
}

function _app_getValue(i_strName) {
    return top.m_mapValues[i_strName.toLowerCase()];
}


function _app_setValue(i_strName, i_strValue) {
    top.m_mapValues[i_strName.toLowerCase()] = i_strValue;
}

function _app_setWindowStatus(i_strStatus) {
    _app_setValue("window_status", i_strStatus);
}


function _app_showWindowStatus() {
    top.status = _app_getValue("window_status");
}


//
// End App object
////


// ReportInfo object
//

function ReportInfo(i_bIncludeSelectedItem, i_bIndentDocumentName, i_fileTypes,
        i_startingLevel, i_bAutoUpdate, i_startRange, i_endRange) {
    this.bIncludeSelectedItem = i_bIncludeSelectedItem;
    this.bIndentDocumentName = i_bIndentDocumentName;
    this.fileTypes = i_fileTypes;
    this.startingLevel = i_startingLevel;
    this.bAutoUpdate = i_bAutoUpdate;
    this.StartRange = i_startRange;
    this.EndRange = i_endRange;
}


// 
// getFriendlyFileType
// Returns friendly filetype
function getFriendlyFileType(i_fileType) {
    var strFileType = 0;
    switch (i_fileType) {
	case "1":
	    strFileType = top.IDS_PDMWEB_PROJECT;
	    break;
	case "2":
	    strFileType = top.IDS_PDMWEB_SW_ASSEMBLY_DOC;
	    break;
	case "3":
	    strFileType = top.IDS_PDMWEB_SW_PART_DOC;
	    break;
	case "4":
	    strFileType = top.IDS_PDMWEB_SW_DRAWING_DOC;
	    break;
	case "5":
	    strFileType = top.IDS_PDMWEB_SW_LIBRARY_FEATURE_PART_DOC;
	    break;
	case "6":
	    strFileType = top.IDS_PDMWEB_DRT_FILE;
	    break;
	case "7":
	    strFileType = top.IDS_PDMWEB_MS_WORD_DOCUMENT;
	    break;
	case "8":
	    strFileType = top.IDS_PDMWEB_MS_EXCEL_WORKSHEET;
	    break;
	case "9":
		strFileType = top.IDS_PDMWEB_MS_POWERPOINT_PRESENTATION;
	    break;
	case "10":
	    strFileType = top.IDS_PDMWEB_DWG_FILE;
	    break;
	case "11":
	    strFileType = top.IDS_PDMWEB_APPLICATION;
	    break;
	case "12":
	    strFileType = top.IDS_PDMWEB_IMAGE;
	    break;
	case "13":
	    strFileType = top.IDS_PDMWEB_TEXT_DOC;
	    break;
	case "14":
	    strFileType = top.IDS_PDMWEB_IGES_FILE;
	    break;
	case "15":
	    strFileType = top.IDS_PDMWEB_DXF_FILE;
	    break;
	case "16":
	    strFileType = top.IDS_PDMWEB_ADOBE_ACROBAT_DOC;
	    break;
	case "17":
	    strFileType = top.IDS_PDMWEB_ZIP_FILE;
	    break;
	default:
	    strFileType = top.IDS_PDMWEB_UNKNOWN_FILE;
	    break;
    }
    return strFileType;
}

function _app_setCurrentTab (i_strValue) {
    top.m_strCurrentTab = i_strValue;
}

function _app_getCurrentTab () {
    return top.m_strCurrentTab;
}

function _app_login() {
    if (top.m_bWindowsAuthenticationEnabled) {
		alert(top.IDS_CANNOT_LOGIN_WIN_AUTH);
    }
    else {
        _app_setSelectedNodeId("");
        var str = top.frames['frameDetail'].document.location.href;
        var results = str.match(new RegExp("login.html", "ig"));
        if ((results == "") || (results == null)) {
            top.frames['frameDetail'].document.location.href = 'login.html';
	    top._mode = LOGIN_MODE;
        }
    }
}


function _app_showTreeLabelDialog() {
    top.frames['frameDetail'].document.location.href = 'selectTreeLabelsDlg.html';
	top._mode = CHANGE_LABELS_MODE;
}


function _app_getTreeProperties() {
    return top.m_treeProperties;
}

function _app_setTreeProperties(i_treeProperties) {
    top.m_treeProperties = i_treeProperties;
}


function _app_updateTreeLabels() {
    top.frames["frameTree"].updateTreeLabels();
}

function _app_getPersistentDate() {
    return top.m_persistDate;
}

function _app_createProgressBar() {
    top.m_inProgress = true;
    window.status = "Working";
    var curBody = null;
    for (var i = 0 ; i < top.frames.length ; ++i) {
		curBody = top.frames[i].document.body;
		if (curBody != null) {
	    	curBody.style.cursor = "wait";
		}
    }
}

function _app_destroyProgressBar() {
    top.m_inProgress = false;
    window.status = top.IDS_PDMWEB_DONE;
    for (var i = 0 ; i < top.frames.length ; ++i) {
        try {
	    	top.frames[i].document.body.style.cursor = "default";
        }
        catch(e) {
	    	window.setTimeout(function() { clearCursor(i) }, 100);
		}
    }
}

function clearCursor(i_frame) {
    try {
        top.frames[i_frame].document.body.style.cursor = "default";
    }
    catch(e) {
		reportWarning("clearCursor() was null.");
    }
}

function _app_incrementProgressBar() {
    if (top.m_inProgress == false) {
		return;
    }
    if (top.m_dots < 5) {
        window.status += ".";
		++top.m_dots;
    }
    else {
		window.status = top.IDS_PDMWEB_WORKING;
		top.m_dots = 0;
    }
}


function _app_setUser(i_str) {
  top.m_strUser = i_str;
}

function _app_getUser() {
  return top.m_strUser;
}

function _app_setPassword(i_str) {
  top.m_strPassword = i_str;
}

function _app_getPassword() {
  return top.m_strPassword;
}

