// _lcid="1033" _version="11.0.5329"
// _localBinding
var sPWAProjId                    = "0";
var sPWAUrl                       = "";
var bHostedinPWA                  = false;
var nTimer                        = null;
var bInit                         = false;
var bUsePWAExtranet               = 0;
var g_bIsFolder                   = false;
var g_nRiskReportPageTitle        = -1;
var sDocListNameToDelete          = "";
var nPSProjId                     = 0;
var bAccessDenied                 = false;

var _nExecASPTimerID              = null;

var nPWATaskId = 0;
var nReqPageId = 0;
var sDocLibRedirectorUrl          = '';

var oXmlDoc                       = null;
var oXmlHttp                      = null;
var bNoXmlHttpAccess              = false;
var bXmlHttpInitialized           = false;

var const_Sts_ObjTypeProject      = 1;
var const_Sts_ObjTypeTask         = 2;
var const_Sts_ObjTypeDocument     = 3;
var const_Sts_ObjTypeIssue        = 4;
var const_Sts_ObjTypeRisk         = 5;

var const_Sts_LinkTypeGeneral     = 1;
var const_Sts_LinkTypeAffected    = 2;
var const_Sts_LinkTypeAction      = 3;
var const_Sts_LinkTypeImpact      = 4;
var const_Sts_LinkTypeTrigger     = 5;
var const_Sts_LinkTypeMitigation  = 6;
var const_Sts_LinkTypeContingency = 7;

var LISTTEMPLATE_RISK_TRACKER  =   1101;

// localization strings
var L_StatusActive_Text                      = '(1) Active';
var L_StatusPostponed_Text                   = '(2) Postponed';
var L_StatusClosed_Text                      = '(3) Closed';

var L_IssuePageTipNewForm_TXT                = "Create a New Issue";
var L_IssuePageTipDispForm_TXT               = "View Issue Details";
var L_IssuePageTipEditForm_TXT               = "Edit Issue";
var L_IssueCantUpdate_ERR                    = "Project Server failed to update the links between the issue and selected tasks. Log on to Project Web Access and link the issue to tasks from the Tasks, Resource Assignments, or Project Drill-down page.";
var L_IssueLinkDivLblTasksAffected_TXT       = "Affected Tasks";
var L_IssueLinkDivLblTasksResolving_TXT      = "Tasks to Resolve This Issue";
var L_IssueLinkDivLblTasksGeneral_TXT        = "Other Linked Tasks";
var L_IssueLinkHrefLblTasksAffected_TXT      = "Select project tasks that are impacted by this issue";
var L_IssueLinkHrefLblTasksResolving_TXT     = "Select project tasks that help to resolve this issue";
var L_IssueLinkHrefLblTasksGeneral_TXT       = "Select project tasks that are generally related to this issue";
var L_IssueLinkHrefLblIssues_TXT             = "Select other related issues in this project";
var L_IssueLinkHrefLblRisks_TXT              = "Select project risks that are related to this issue";
var L_IssueLinkHrefLblDocuments_TXT          = "Select project documents that are related to this issue";
var L_IssueDropMenuView_TXT                  = "View Issue";
var L_IssueDropMenuEdit_TXT                  = "Edit Issue";
var L_IssueDropMenuDelete_TXT                = "Delete Issue";

var L_RiskPageTipNewForm_TXT                 = "Create a New Risk";
var L_RiskPageTipDispForm_TXT                = "View Risk Details";
var L_RiskPageTipEditForm_TXT                = "Edit Risk";
var L_RiskCantUpdate_ERR                     = "Project Server failed to update the links between the risk and selected tasks. Log on to Project Web Access and link the risk to tasks from the Tasks, Resource Assignments, or Project Drill-down page.";
var L_RiskLinkDivLblTasksImpact_TXT          = "Affected Tasks";
var L_RiskLinkDivLblTasksTrigger_TXT         = "Triggers";
var L_RiskLinkDivLblTasksMitigation_TXT      = "Mitigation Tasks";
var L_RiskLinkDivLblTasksContingency_TXT     = "Contingency Plan Tasks";
var L_RiskLinkHrefLblTasksImpact_TXT         = "Select project tasks that are impacted by this risk";
var L_RiskLinkHrefLblTasksTrigger_TXT        = "Select project tasks that are triggers for this risk";
var L_RiskLinkHrefLblTasksMitigation_TXT     = "Select project tasks that are part of the mitigation plan";
var L_RiskLinkHrefLblTasksContingency_TXT    = "Select project tasks that are part of the risk contingency plan";
var L_RiskLinkHrefLblIssues_TXT              = "Select project issues that are related to this risk";
var L_RiskLinkHrefLblRisks_TXT               = "Select other related risks in this project";
var L_RiskLinkHrefLblDocuments_TXT           = "Select project documents that are related to this risk";
var L_RiskDropMenuView_TXT                   = "View Risk";
var L_RiskDropMenuEdit_TXT                   = "Edit Risk";
var L_RiskDropMenuDelete_TXT                 = "Delete Risk";

var L_LinkDivLblIssues_TXT                   = "Linked Issues";
var L_LinkDivLblRisks_TXT                    = "Linked Risks";
var L_LinkDivLblDocuments_TXT                = "Linked Documents";

var L_DocLinkHrefLblTasksGeneral_TXT         = "Select project tasks that are related to this document";
var L_DocLinkHrefLblIssues_TXT               = "Select project issues that are related to this document";
var L_DocLinkHrefLblRisks_TXT                = "Select project risks that are related to this document";

var L_DocLinkDivLblTasks_TXT                 = "Linked Tasks";
var L_DocLinkDivLblIssues_TXT                = "Linked Issues";
var L_DocLinkDivLblRisks_TXT                 = "Linked Risks";

var L_DocCantUpdate_ERR                      = "Project Server failed to update the links in Project Server database. Please try again later or contact your administrator.";

var L_LnkDialogTitleDoc_Text                 = "Link to the selected documents";
var L_LnkDialogTitleIssue_Text               = "Link to the selected issues";
var L_LnkDialogTitleRisk_Text                = "Link to the selected risks";
var L_LnkDialogTitleTask_Text                = "Link to the selected tasks";

var L_LnkColumnLblLink_Text                  = "Link?";
var L_LnkColumnLblID_Text                    = "ID";
var L_LnkColumnLblTitle_Text                 = "Title";
var L_LnkColumnLblOwner_Text                 = "Owner";
var L_LnkColumnLblCreatedBy_Text             = "Created By";
var L_LnkColumnLblStatus_Text                = "Status";
var L_LnkColumnLblAssignedTo_Text            = "Assigned To";

var L_LnkStyleHTML_Text                      = "font-size: 0.8em; font-family: Verdana;";
var L_LnkItemNotFound_Text                   = "Project Web Access has finished searching the grid. The search item was not found.";
var L_LnkSearchFinished_Text                 = "Project Web Access has finished searching the grid.";
                                             
var L_LnkNoDocsAlertPart1_Text               = "There are no documents submitted to this project";
var L_LnkNoIssuesAlertPart1_Text             = "There are no issues submitted to this project";
var L_LnkNoRisksAlertPart1_Text              = "There are no risks submitted to this project";
var L_LnkNoTasksAlertPart1_Text              = "There are no tasks available.";
var L_LnkNoTasksAlertPart2_Text              = "Either the project has not been published to Project Server, or you do not have the permissions to view the tasks in Project Web Access.";

var L_RiskReportName0_Text                   = "Number of Risks By Category";
var L_RiskReportName1_Text                   = "Number of Risks by Person";
var L_RiskReportName2_Text                   = "Number of Risks Created over Date Range";
var L_RiskReportName3_Text                   = "Number of Risks for Date Range";

var L_RiskReportTitle0_Text                  = "Risks by category";
var L_RiskReportTitle1_Text                  = "Risks by person";
var L_RiskReportTitle2_Text                  = "Risks created over a date range";
var L_RiskReportTitle3_Text                  = "Risks for a date range";

var L_NumberOfRisks_Text                     = "Number Of Risks";

var L_DialogWindowHeight_Text                = "400px";
var L_DialogWindowWidth_Text                 = "550px";

var L_SynchronizeWithPWA_Text                = "If you have edited the list in Excel or Access, it is recommended that you synchronize items in ^0 with Project Server, so all the list items can be linked to the project.\n\nClick OK to synchronize the list with Project Server. It may take a few moments.\nClick Cancel to close the dialog box without synchronizing with Project Server.";
var L_SynchronizeWithPWAFailed_ERR           = "The server running Windows SharePoint Services failed to connect to Project Server.\nYour changes will not be saved into the Project Server database. Please try again later or contact your administrator.";
var L_SynchronizeWithPWADone_Text            = "The Project Server database has been successfully updated.";

var L_LnkColSizeLink_Text                    = 60;
var L_LnkColSizeID_Text                      = 40;
var L_LnkColSizeStatus_Text                  = 70;
var L_LnkColSizeTitleTas_Text                = 388;
var L_LnkColSizeTitleIss_Text                = 170;
var L_LnkColSizeTitleRis_Text                = 170;
var L_LnkColSizeTitleDoc_Text                = 190;
var L_LnkColSizeAssignedTo_Text              = 150;
var L_LnkColSizeOwner_Text                   = 124;
var L_LnkColSizeCreatedBy_Text               = 123;

var L_NoXmlHttpAccess_ERR                    = "Windows SharePoint Services cannot access information from Project Server. The possible reasons are:\n\n1. The cross domain data access security setting for your Internet browser is disabled.\n2. You have declined to access cross domain data when prompted.\n\nIt is recommended that you add the Project Server URL and the SharePoint URL to the list of trusted sites on the Security tab of the Internet Options dialog box, or enable cross domain data access on the Security tab or when prompted. Then refresh the page.\n\nProject Server URL: ^0\nSharePoint URL: ^1";

// Skip global init code for linked items html dialogs.  Running the init code unneccesarily causes problems with IE5.01
if (typeof(bSkipGlobalInit) == "undefined")
{
  GlobalInit();
}

//--------------------------------------------------------------------------------
function GlobalInit()
{
  try
  {
    if(window.parent != window)
    {
      bHostedinPWA = true;
    }
  }
  catch(e)
  {
    bHostedinPWA = true;
  }

  // If this is a ListEdit.aspx page then we need to insert a hidden IFrame. When deleting list we will source
  // the submit action to this IFrame.
  var sCurrentPage = window.location.href.split('?')[0];
  sCurrentPage = sCurrentPage.substr(sCurrentPage.lastIndexOf('/') + 1).toUpperCase();
  
  if(sCurrentPage == "REQACC.ASPX")
  {
    bAccessDenied = true;
  }

  if(sCurrentPage == "LISTEDIT.ASPX")
  {
    document.write('<IFRAME ID="idPWADelListFrame" NAME="idPWADelListFrame" SCROLLING="YES" STYLE="display:none;"></IFRAME>');
  }

  if(!bAccessDenied)
  {
    document.write('<IFRAME id="idPWAPropFrame" SRC="/_layouts/pwainc/pwaredir.aspx?sInputURL=' + window.location.href + '&sDestURL=/_layouts/pwainc/pwaprop.aspx" STYLE="display:none"></IFRAME>');
  }

  window.attachEvent("onload",PageOnLoad);

  if(StURLGetVar("ShowInGrid").toLowerCase() == "true")
  {
    window.attachEvent("onunload", PageOnUnload);
  }

  var oStyle = null;
  for (var i = 0; i < document.styleSheets.length;i++) {
	  if (document.styleSheets[i].href.match(/ows.css/) != null) {
	  oStyle = document.styleSheets[i];
	  break;
	  }
  }

  // If inside PWA framework, we hide page elements on load, to avoid blinking effect
  // Also, we do this for Risk Reports, even outside PWA, because
  // we need to customize page elements after they are initially loaded.
  if (GetUrlKeyValue("pwartitle") != "")
  {
    g_nRiskReportPageTitle = Number(GetUrlKeyValue("pwartitle"));
  }

  if (isNaN(g_nRiskReportPageTitle) || g_nRiskReportPageTitle < 0 || g_nRiskReportPageTitle > 3)
  {
    g_nRiskReportPageTitle = -1;      
  }

  if ((bHostedinPWA || (g_nRiskReportPageTitle >= 0)) && (oStyle != null)) {
	  for (var i = 0; i < oStyle.rules.length;i++) {
	    if (oStyle.rules[i].selectorText == ".ms-main") {
		    oStyle.rules[i].style.display = "none";
		    break;
	    }
	  }
  }
}

//--------------------------------------------------------------------------------
function WaitForComplete(fnOnComplete)
{
  try
  {
    if(bAccessDenied || (document.frames['idPWAPropFrame'].document.readyState.toLowerCase() == 'complete'))
    {
      PageInit();
    }
  }
  catch(e)
  {
    window.clearInterval(nTimer);
    nTimer = null;
  }
}

//--------------------------------------------------------------------------------
function PageOnLoad()
{
  if (bInit)
    return;

  bInit = true;
  nTimer = window.setInterval('WaitForComplete()', 10);
}

//--------------------------------------------------------------------------------
function PWACancel_OnClick()
{
  window.history.back();
}

//--------------------------------------------------------------------------------
function PWAUpdateMyAlerts()
{
  window.location = "mysubs.aspx";
}

//--------------------------------------------------------------------------------
function PWAReorderCancel()
{
  window.location = "mysubs.aspx";
}

// We need to override all references to window.parent object with window object
// that happen while inside of PWA framework
//--------------------------------------------------------------------------------
function OverrideWindowParent()
{
  if (document.all.BtnCancel)             document.all.BtnCancel.onclick        = PWACancel_OnClick; // subedit.aspx
  if (document.all.btnCancel)             document.all.btnCancel.onclick        = PWACancel_OnClick; // setanon.aspx
  if (document.all.btnClose)              document.all.btnClose.onclick         = PWACancel_OnClick; // newgrp.aspx
  if (document.all.btnDefault)            document.all.btnDefault.onclick       = PWACancel_OnClick; // subnew.aspx
  if (document.all.CancelBtn)             document.all.CancelBtn.onclick        = PWACancel_OnClick; // addrole.aspx
  if (document.all.onetidCancel)          document.all.onetidCancel.onclick     = PWACancel_OnClick; // formEdt.aspx
  if (document.all.onetidCancelItem)      document.all.onetidCancelItem.onclick = PWACancel_OnClick; // FldNew.aspx
  if (document.all.onetidClose)           document.all.onetidClose.onclick      = PWACancel_OnClick; // subchoos.aspx
  if (document.all.onetidUpdateMyAlerts)  document.all.onetidUpdateMyAlerts     = "javascript:PWAUpdateMyAlerts();"; // userdisp.aspx  
  if (document.all.onetidReorderCancel)   document.all.onetidUpdateMyAlerts     = "javascript:PWAReorderCancel();"; // reorder.aspx  
}

// Customize Risk Report page (ReportRich.aspx)
//--------------------------------------------------------------------------------
function CustomizeRiskReports()
{
  var rType = Number(GetUrlKeyValue("Type"));
  var aReportName = new Array;

  aReportName[0] = L_RiskReportName0_Text;
  aReportName[1] = L_RiskReportName1_Text;
  aReportName[2] = L_RiskReportName2_Text;
  aReportName[3] = L_RiskReportName3_Text;

  var aReportTitle = new Array;

  aReportTitle[0] = L_RiskReportTitle0_Text;
  aReportTitle[1] = L_RiskReportTitle1_Text;
  aReportTitle[2] = L_RiskReportTitle2_Text;
  aReportTitle[3] = L_RiskReportTitle3_Text;
  
  PageTitleLabel.innerText = aReportTitle[g_nRiskReportPageTitle];
  
  if (document.ChartSpace1)
  {
    document.ChartSpace1.Charts(0).Title.Caption = aReportName[rType];
    document.ChartSpace1.Charts(0).Axes(1).Title.Caption = L_NumberOfRisks_Text;
  }
  
  if (((rType == 2) || (rType == 3)) && (typeof(DynamicChartTable) != "undefined"))
  {
    DynamicChartTable.rows(0).cells(1).innerText = L_NumberOfRisks_Text;
  }

  backtoReportsLink.href = backtoReportsLink.href.replace("reporthome.aspx","rrephome.aspx");
}

//--------------------------------------------------------------------------------
function PageInit()
{
  var oEntirePage;
  var bFound = false;
  for (var i = 0; i < document.body.childNodes.length; i++)
  {
    oEntirePage = document.body.childNodes(i);
    if(oEntirePage.tagName == "TABLE")
    {
      bFound = true;
      break;
    }
    else if(oEntirePage.tagName == "FORM")
    {
      for(var j = 0; j < oEntirePage.childNodes.length; j++)
      {
        oMainSection = oEntirePage.childNodes(j);
        if(oMainSection.tagName == "TABLE")
        {
          bFound = true;
          oEntirePage = oMainSection;
          break;
        }
      }
    }
    
    if(bFound)
    {
      break;
    }
  }

  if(bHostedinPWA && bFound) 
  {
    oEntirePage.rows(0).style.display = "none";
  }
  oEntirePage.style.display = "block";

  if(!bAccessDenied)
  {
    sPWAProjId = document.frames['idPWAPropFrame'].document.all.idPWAProjID.value;
    bUsePWAExtranet = Number(document.frames['idPWAPropFrame'].document.all.idIsPWAExtranet.value);
    if(!bUsePWAExtranet)
    {
      sPWAUrl = document.frames['idPWAPropFrame'].document.all.idPWAURL.value;
    }
    else
    {
      sPWAUrl = document.frames['idPWAPropFrame'].document.all.idPWAExtranetUrl.value;
      // If the trailing slash is missing, add it.
      if(sPWAUrl.charAt(sPWAUrl.length - 1) != '/')
      {
        sPWAUrl += "/";
      }
    }
    nPSProjId = Number(sPWAProjId);
    if (isNaN(nPSProjId))
    {
      nPSProjId = -1;
    }

    if((nPSProjId != -99) && (typeof(idSynchPWATR) != "undefined"))
    {
      idSynchPWATR.style.display = "block";
    }

    if ((typeof(InitForPWA) != "undefined") && (nPSProjId > 0))
    {
      InitForPWA();
    }
    else
    {
      if(typeof(idPwaOrigGoBackBtnSpan) != "undefined")
      {
        idPwaOrigGoBackBtnSpan.style.display = "block";
      }
    }
  }

  window.clearInterval( nTimer );
  nTimer = null;

  if(bAccessDenied)
  {
    return;
  }
  
  if (typeof(OnLoadWrapper) != "undefined")
  {
    OnLoadWrapper();
  }
  
  if (g_nRiskReportPageTitle >= 0)
  {
    CustomizeRiskReports();
  }

  // Hide the content approval section.
  // Check for "onetidReadSecurity" is added here to fix bug #6215 (see it for more details).
  // We need to hide the content approval section for docs, issues and risks lists only. 
  if((typeof(HideSection1) != "undefined") && (typeof(onetidReadSecurity)== "undefined"))
  {
    HideSection1.style.display = "none";

    if(typeof(HideSection2) != "undefined")
    {
      HideSection2.style.display = "none";
    }

    if(typeof(HideSection3) != "undefined")
    {
      HideSection3.style.display = "none";
    }

    if(typeof(HideSection4) != "undefined")
    {
      HideSection4.style.display = "none";
    }

    if(typeof(HideSection5) != "undefined")
    {
      HideSection5.style.display = "none";
    }

    if(typeof(HideSection6) != "undefined")
    {
      HideSection6.style.display = "none";
    }
  }

  if (bHostedinPWA)
  {
    OverrideWindowParent();
  }
} // End of PageInit()

// This function overrides ows.js
//--------------------------------------------------------------------------------
function Custom_AddListMenuItems(m, ctx)
{
    if ((ctx.listTemplate != LISTTEMPLATE_ISSUE_TRACKER) && (ctx.listTemplate != LISTTEMPLATE_RISK_TRACKER))
    {
      return false;
    }

    strDisplayText = (ctx.listTemplate == LISTTEMPLATE_ISSUE_TRACKER) ? L_IssueDropMenuView_TXT : L_RiskDropMenuView_TXT;
    strAction = "STSNavigate('" + ctx.displayFormUrl+"?ID="+ currentItemID + "&Source=" +
                GetSource() + "')";
    strImagePath = "";
    CAMOpt(m, strDisplayText, strAction, strImagePath);
    strDisplayText = (ctx.listTemplate == LISTTEMPLATE_ISSUE_TRACKER) ? L_IssueDropMenuEdit_TXT : L_RiskDropMenuEdit_TXT;
    strAction = "STSNavigate('" + ctx.editFormUrl+"?ID="+ currentItemID + "&Source=" +
                GetSource() + "')";
    strImagePath = ctx.imagesPath + "edititem.gif";
    CAMOpt(m, strDisplayText, strAction, strImagePath);

    if (currentItemID.indexOf(".0.") < 0)
    {
      strDisplayText = (ctx.listTemplate == LISTTEMPLATE_ISSUE_TRACKER) ? L_IssueDropMenuDelete_TXT : L_RiskDropMenuDelete_TXT;
		strAction = "Custom_DeleteListItem()";
		strImagePath = ctx.imagesPath + "delitem.gif";
		CAMOpt(m, strDisplayText, strAction, strImagePath);
    }

    if (currentItemID.indexOf(".0.") < 0)
    {
        strDisplayText = L_Subscribe_Text;
        strAction = "NavigateToSubNewAspx('" + ctx.HttpRoot + "', 'List=" + ctx.listName + "&ID=" + currentItemID +"')";
        strImagePath = "";
        CAMOpt(m, strDisplayText, strAction, strImagePath);
    }
    if (ctx.isModerated == true &&
        ctx.listBaseType != BASETYPE_SURVEY)
    {
        strDisplayText = L_ModerateItem_Text;
        strAction = "STSNavigate('" + ctx.editFormUrl+"?ID="+ currentItemID + "&ChangeApproval=TRUE&Source=" +
                    GetSource() + "')";
        strImagePath = "";
        CAMOpt(m, strDisplayText, strAction, strImagePath);
    }
    
    return true;
} // End of Custom_AddListMenuItems

// This function overrides ows.js
//--------------------------------------------------------------------------------
function Custom_DeleteListItem()
{
   if (! IsContextSet())
      return;
   var ctx = currentCtx;
   if (confirm(L_STSDelConfirm_Text))
   {
      if(typeof(document.frames['idForPWAIFrame']) != "undefined")
      {
         var form = document.forms[0];

         if (null != form)
         {
            form.target = "idForPWAIFrame";
         }
      }

      SubmitFormPost(ctx.HttpPath + "&Cmd=Delete&List=" + ctx.listName + 
                  "&ID=" + currentItemID + "&NextUsing=" + GetSource());

      if (null != form)
      {
         if (form.target == "idForPWAIFrame")
         {
            _nExecASPTimerID = window.setInterval('ExecHTML_WaitForComplete_DeleteListItem()', 50);
         }
      }
   }
}

// This function overrides ows.js
//--------------------------------------------------------------------------------
function PWAValidateAndSubmit(fUI)
{
  if(frm.fPreviewMode)
  {
    var L_cantSave_Text = "This form cannot be saved when previewing this page.";
    window.alert(L_cantSave_Text);
    return;
	}
  if(frm.FValidate(fUI))
	{
    frm.FPostProcess();
    if((typeof(document.frames['idForPWAIFrame']) != "undefined") && !g_bIsFolder)
    {
      frm.form.target = "idForPWAIFrame";
    }
  	frm.form.submit();
    if(frm.form.target == "idForPWAIFrame")
    {
      if((typeof(ctx) != "undefined") && (typeof(ctx.listBaseType) != "undefined") && (ctx.listBaseType == BASETYPE_ISSUE))
      {
        _nExecASPTimerID = window.setInterval('ExecHTML_WaitForComplete_Issues()', 50);
      }
      else
      {
        _nExecASPTimerID = window.setInterval("ExecHTML_WaitForUploadComplete_Docs()", 50);
      }
	  }
	}
} // End of PWAValidateAndSubmit().

//--------------------------------------------------------------------------------
function InsertPwaLinksHtml(aDivLbl, aDivId, aHrefLbl, aHrefTarget)
{
   var sHtml = "";

   for (i in aDivId)
   {
      var sRow = aDivLbl[i] + "</LABEL></TD><TD><DIV ID=\"" + aDivId[i] + "\" STYLE=\"display: block;\"></DIV>";

      if (bIsNew || bIsEdit)
      {
         sRow += "<A CLASS=\"ms-toolbar\" HREF=\"" + aHrefTarget[i] + "\" TARGET=\"_self\">" + aHrefLbl[i] + "</A>";
      }

      sHtml += "<TR VALIGN=\"top\"><TD WIDTH=\"30%\"><LABEL CLASS=\"ms-formlabel\">" + sRow + "</TD></TR>";
   }

   sHtml = "<TABLE>" + sHtml + "</TABLE>";

   idPwaHtml.innerHTML += sHtml;
} // End of InsertPwaLinksHtml()

// All objects in the oArgs must be of the same oArgs.LinkType
// It is only used to determine whether the item is linked and should be displayed in the table
//--------------------------------------------------------------------------------
function ConstructLinkedItemsTable(oArgs, nObjType, bHyperLink)
{
   var sRows = "";
   var sItem = "";
   var sHref = "";

   for(i in oArgs.ID)
   {
      if(oArgs.LinkType[i])
      {
         if (bHyperLink && (nObjType != const_Sts_ObjTypeTask))
         {
            switch (nObjType)
            {
            case const_Sts_ObjTypeDocument:
               sHref = oArgs.EncodedAbsUrl[i];
               break;
            case const_Sts_ObjTypeIssue:
               sHref = ctx.HttpRoot + "/Lists/Issues/DispForm.aspx?ID=" + oArgs.ID[i] + "&Source=" + GetUrlKeyValue("Source");
               break;
            case const_Sts_ObjTypeRisk:
               sHref = ctx.HttpRoot + "/Lists/Risks/DispForm.aspx?ID=" + oArgs.ID[i] + "&Source=" + GetUrlKeyValue("Source");
               break;
            }

            sItem = "<A HREF=\"" + sHref + "\" TARGET=\"_self\">" + oArgs.Title[i] + "</A>";
         }
         else
         {
            sItem = oArgs.Title[i];
         }

         sRows += "<TR CLASS=\"ms-formdescription\"><TD WIDTH=\"5%\">"
               + oArgs.ID[i]
               + ". </TD><TD WIDTH=\"65%\">"
               + sItem + "</TD></TR>";
      }
   }

   return ("<TABLE WIDTH=\"100%\" STYLE=\"font-size: 0.8em;\" CELLPADDING=\"0\" CELLSPACING=\"0\" BORDER=\"0\">" + sRows + "</TABLE>");

} // End of ConstructLinkedItemsTable().

//--------------------------------------------------------------------------------
function GotoAllDocLibs(sPath)
{
  if(bHostedinPWA)
  {
    // This should never happen. But just in case the site variables are not set
    // that we don't crash.
    if(sPWAUrl == "")
    {
      window.history.back();
      return;
    }
    window.parent.location.href = sPWAUrl + "DocLib/DocLibRedirector.asp?NextPageUrl=DocLib/DocLibMain.asp&ProjID=" + sPWAProjId;
  }
  else
  {
    window.location.href = sPath;
  }
} // End of GotoAllDocLibs().

//--------------------------------------------------------------------------------
function SynchronizeWithPWA(sListName, sListDisplayName, nObjectType, bShowWarning, sErrMsg)
{
  if((sPWAUrl == "") || isNaN(nPSProjId) || ((nPSProjId < 1) && (nPSProjId != -99)))
  {
    alert(L_SynchronizeWithPWAFailed_ERR);
    return;
  }

  if(bShowWarning)
  {
    if(!confirm(L_SynchronizeWithPWA_Text.replace("^0", sListDisplayName)))
    {
      return;
    }
  }

  if (typeof(sErrMsg) == "undefined")
  {
    sErrMsg = L_DocCantUpdate_ERR;
  }

  if (!InitXmlHttpObjects())
  {
    alert(sErrMsg);
    return;
  }

  try
  {
    // Create the root node.
    var oRoot;
    var oNewNode;
    
    oRoot = oXmlDoc.createNode(1, "XMLFormData", "");
    oXmlDoc.appendChild(oRoot);

    // Create 'ProjID' node.
    oNewNode = oXmlDoc.createNode(1, "ProjectID", "");
    oNewNode.text = sPWAProjId;
    oRoot.appendChild(oNewNode);

    // Create 'Operation' node.
    oNewNode = oXmlDoc.createNode(1, "Operation", "");
    oNewNode.text = "UpdateObjectsAfterDataSheetEntry";
    oRoot.appendChild(oNewNode);

    // Create 'ListGUID' node.
    oNewNode = oXmlDoc.createNode(1, "ListGUID", "");
    oNewNode.text = sListName;
    oRoot.appendChild(oNewNode);

    // Create 'ObjectType' node.
    oNewNode = oXmlDoc.createNode(1, "ObjectType", "");
    oNewNode.text = nObjectType;
    oRoot.appendChild(oNewNode);

    if(!(oRoot = ExecXmlHttpRequest()))
    {
      alert(sErrMsg);
      return;
    }

    if(oRoot.selectSingleNode("Result").text.toUpperCase() == "ERROR")
    {
      alert(oRoot.selectSingleNode("Description").text);
      return;
    } 

  }
  catch(e)
  {
    alert(sErrMsg);
    return;
  }

  if(bShowWarning)
  {
    alert(L_SynchronizeWithPWADone_Text);
  }

  return;

} // End of SynchronizeWithPWA().

//--------------------------------------------------------------------------------
function PageOnUnload()
{
  if(nPSProjId == -99)
  {
    return;
  }

  if((typeof(ctx) != "undefined") && ctx)
  {
    // Documents, Risks or Issues.
    //
    var nObjectType = 0;
    if(ctx.listTemplate == LISTTEMPLATE_DOCUMENT_LIBRARY)
    {
      nObjectType = const_Sts_ObjTypeDocument;
    }
    else if(ctx.listTemplate == LISTTEMPLATE_ISSUE_TRACKER)
    {
      nObjectType = const_Sts_ObjTypeIssue;
    }
    else if(ctx.listTemplate == LISTTEMPLATE_RISK_TRACKER)
    {
      nObjectType = const_Sts_ObjTypeRisk;
    }

    if(nObjectType > 0)
    {
      SynchronizeWithPWA(ctx.listName, "", nObjectType, false, L_SynchronizeWithPWAFailed_ERR);
    }
  }

  return;

} // End of PageOnUnload().

//--------------------------------------------------------------------------------
function SetOwner()
{
   var userSelect = document.all.item("urn:schemas-microsoft-com:office:office#Owner");
   var nOptions = userSelect.options.length;

   userSelect.options(userSelect.selectedIndex).selected = false;

   for (var i = 0; i < nOptions; ++i)
   {
      if (userSelect.options(i).value == ctx.UserID)
      {
         userSelect.options(i).selected = true;
         break;
      }
   }
}

//--------------------------------------------------------------------------------
function FormatNoXmlHttpAccessMessage()
{
  var re = /[^\/]\/[^\/]/; // find first single forward slash
  var sWSSUrl = window.location.href.substring(0,window.location.href.search(re) + 1);
  return L_NoXmlHttpAccess_ERR.replace('^0', sPWAUrl).replace('^1', sWSSUrl);
}

//--------------------------------------------------------------------------------
function ExecXmlHttpRequest()
{
  if (bNoXmlHttpAccess)
  {
    alert(FormatNoXmlHttpAccessMessage());
    return null;
  }
  
  try
  {
    oXmlHttp.open("POST", sPWAUrl + "DocLib/svr_DbDocLib.asp", false);
    oXmlHttp.send(oXmlDoc.xml);
    oXmlDoc.load(oXmlHttp.responseXML);
  }
  catch(e)
  {
    bNoXmlHttpAccess = true;
    alert(FormatNoXmlHttpAccessMessage());
    return null;
  }

  return oXmlDoc.documentElement;
}

//--------------------------------------------------------------------------------
function InitXmlHttpObjects()
{
  try
  {
    if (!bXmlHttpInitialized)
    {
      bXmlHttpInitialized = true;
      oXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      oXmlDoc  = new ActiveXObject("Microsoft.XMLDOM");

      // Dummy call to take care of Bug 10804
      var oRoot = oXmlDoc.createNode(1, "Root", "");
      oXmlDoc.appendChild(oRoot);

      var oNewNode = oXmlDoc.createNode(1, "Operation", "");
      oNewNode.text = "TestXmlHttpAccess";
      oRoot.appendChild(oNewNode);

      ExecXmlHttpRequest();
      // End of Dummy call
    }

    oXmlDoc.loadXML("");
  }
  catch(e)
  {
    bNoXmlHttpAccess = true;
    alert(FormatNoXmlHttpAccessMessage());
  }
  
  return (!bNoXmlHttpAccess);
}

//--------------------------------------------------------------------------------
function Custom_AddDocLibMenuItems(m, ctx)
{
  var RootFolder = GetRootFolder(ctx);
  setupMenuContext(ctx);

  if(currentItemFileUrl == null)    { currentItemFileUrl    = itemTable.ServerUrl; }
  if(currentItemFSObjType == null)  { currentItemFSObjType  = itemTable.FSObjType; }

  ctx.ID        = currentItemID;
  g_bIsFolder   = ((currentItemFSObjType == 1) ? true : false);

  var currentItemEscapedFileUrl = escapeProperly(unescapeProperly(currentItemFileUrl));
  if(currentItemFSObjType != 1) 
  {
    strDisplayText = L_ViewProperties_Text;    
    strAction = "STSNavigate('" + ctx.displayFormUrl+"?ID="+ currentItemID + "&Source=" + GetSource() + RootFolder + "')";
    strImagePath = "";
    CAMOpt(m, strDisplayText, strAction, strImagePath);
  }

  strDisplayText  = L_EditProperties_Text;    
  strAction       = "STSNavigate('" + ctx.editFormUrl+"?ID="+ currentItemID + "&Source=" + GetSource() + RootFolder + "')";
  strImagePath    = ctx.imagesPath + "edititem.gif";
  CAMOpt(m, strDisplayText, strAction, strImagePath);
  if(currentItemFSObjType != 1) 
  {
    if(ctx.isWebEditorPreview == 0)
    {
      if(ctx.listTemplate == LISTTEMPLATE_IMAGE_LIBRARY && itemTable.IsImage == "1")
      {
        strDisplayText  = L_EditInOIS_Text;
        strAction       = "EditSingleImage('" + currentItemID  + "')";
        strImagePath    = ctx.imagesPath + "oisweb.gif";
        CAMOpt(m, strDisplayText, strAction, strImagePath);
      }
      else
      {
        setDocType();
        if(currentItemAppName != "" && currentItemOpenControl != "")
        {
          strDisplayText  = StBuildParam(L_EditIn_Text, currentItemAppName);
          strAction       = "editDocumentWithProgID2('" + currentItemFileUrl + "', '" + currentItemProgId + "', '" + currentItemOpenControl + "')";
          strImagePath    = ctx.imagesPath + currentItemIcon;
          CAMOpt(m, strDisplayText, strAction, strImagePath);
        }
      }
    }
  }

  strDisplayText = L_DeleteDocItem_Text;
  strAction = "Custom_DeleteDocLibItem('" + ctx.HttpPath + "&Cmd=Delete&List=" + ctx.listName + "&ID=" + currentItemID + "&owsfileref=" + currentItemEscapedFileUrl + "&NextUsing=" + GetSource() + "')";
  strImagePath = ctx.imagesPath + "delitem.gif";
  CAMOpt(m, strDisplayText, strAction, strImagePath);
  if(ctx.isModerated == true)
  {
    strDisplayText = L_ModerateItem_Text;
    strAction = "STSNavigate('" + ctx.editFormUrl+"?ID="+ currentItemID + "&ChangeApproval=TRUE&Source=" + GetSource() + RootFolder + "')";
    strImagePath = "";
    CAMOpt(m, strDisplayText, strAction, strImagePath);
  }
  if(currentItemFSObjType != 1 && ctx.listTemplate == LISTTEMPLATE_IMAGE_LIBRARY)
  {
    strAction       = "DownloadOriginalImage(" + currentItemID + ")";
    strImagePath    = ctx.imagesPath + "download.gif";
    strDisplayText  = L_DownloadOriginal_Text;
    CAMOpt(m, strDisplayText, strAction, strImagePath);
  }
  if(currentItemFSObjType != 1) 
  {
    CAMSep(m);
    AddCheckinCheckoutMenuItem(m, ctx, currentItemEscapedFileUrl);
    AddVersionsMenuItem(m, ctx, currentItemEscapedFileUrl);
	  CAMSep(m);
    if(ctx.PortalUrl != null)
    {
      strDisplayText  = L_AddToMyLinks_Text;
      strAction       = "Portal_Tasks('PinToMyPage')"; ;
      strImagePath    = "";
      CAMOpt(m, strDisplayText, strAction, strImagePath);
      strDisplayText  = L_AddToCategory_Text;
      strAction       = "Portal_Tasks('Categorize')"; ;
      strImagePath    = "";
      CAMOpt(m, strDisplayText, strAction, strImagePath);
      CAMSep(m);
    }
  }
  strDisplayText = L_Subscribe_Text;
  strAction = "NavigateToSubNewAspx('" + ctx.HttpRoot + "', 'List=" + ctx.listName + "&ID=" + currentItemID + "')";
  strImagePath = "";
  CAMOpt(m, strDisplayText, strAction, strImagePath);
  if(currentItemFSObjType != 1) 
  {
    strDisplayText = L_Discuss_Text;
    strAction = "STSNavigate('" + ctx.HttpPath + "&Cmd=COMMFRMS&URL=";
    if(ctx.isWebEditorPreview == 0)
    {
      strAction += currentItemEscapedFileUrl;
    }
    strAction += "')";
    strImagePath = ctx.imagesPath + "icdisc.gif";
    CAMOpt(m, strDisplayText, strAction, strImagePath);
    // Hide the "Show in Workspace" if we are hosted in PWA.
    if(!bHostedinPWA)
    {
      if(ctx.listTemplate != LISTTEMPLATE_IMAGE_LIBRARY)
      {
     	  AddWorkspaceMenuItem(m, ctx);
      }
    }
  }

  return true;

} // End of Custom_AddDocLibMenuItems().

//--------------------------------------------------------------------------------
function Custom_DeleteDocLibItem(delUrl)
{        
  if(!IsContextSet())
  {
    return;
  }

  if(confirm(currentItemFSObjType == 1 ? L_STSDelConfirm1_Text : L_STSDelConfirm_Text))
  {
    if(typeof(document.frames['idForPWAIFrame']) != "undefined")
    {
      var form = document.forms[0];
      if(null != form)
      {
        form.target = "idForPWAIFrame";
      }
    }

    SubmitFormPost(delUrl);

    if(null != form)
    {
      if(form.target == "idForPWAIFrame")
      {
        _nExecASPTimerID = window.setInterval('ExecHTML_WaitForComplete_DeleteDocListItem()', 50);
      }
    }
  }
} // End of Custom_DeleteDocLibItem().

//--------------------------------------------------------------------------------
function Custom_DeleteList()
{
  if(confirm(strConfirm)) 
  {
    if(typeof(document.frames['idPWADelListFrame']) != "undefined")
    {
      var form = document.forms[0];
      if(null != form)
      {
        form.target = "idPWADelListFrame";
      }
    }

    sDocListNameToDelete = unescapeProperly(GetUrlKeyValue("List"));
    document.tpViewEdit.submit();

    if(null != form)
    {
      if(form.target == "idPWADelListFrame")
      {
        _nExecASPTimerID = window.setInterval('ExecHTML_WaitForComplete_DeleteDocList()', 50);
      }
    }
  }
  
  return true;

} // End of Custom_DeleteList().

//--------------------------------------------------------------------------------
function ExecHTML_WaitForComplete_DeleteDocList()
{
  if((typeof(document.frames['idPWADelListFrame'].window.location.href) == "unknown") || 
    (document.frames['idPWADelListFrame'].window.location.href.toLowerCase() == "about:blank") ||
    (document.frames['idPWADelListFrame'].window.document.readyState.toLowerCase() != 'complete'))
  {
    return;
  }

  window.clearInterval(_nExecASPTimerID);
  _nExecASPTimerID = null;

  var sFullUrl = document.frames['idPWADelListFrame'].window.location.href;

  var sNewUrl = sFullUrl.split('?')[0];
  sNewUrl = sNewUrl.substr(sNewUrl.lastIndexOf('/') + 1).toUpperCase();
  if(sNewUrl == "REQACC.ASPX")
  {
    window.location.href = document.frames['idPWADelListFrame'].window.location.href;
    return;
  }

  if(sNewUrl == "OWSSVR.DLL")
  {
    var sTxt = document.frames['idPWADelListFrame'].window.document.childNodes.item(0).innerText;
    if(sTxt)
    {
      alert(sTxt);
    }
    window.location.reload();
    return;
  }

  if(sPWAUrl == "" || sPWAProjId == "")
  {
    alert(L_DocCantUpdate_ERR);
    window.location.reload();
    return;
  }

  if(Number(sPWAProjId) == -99)
  {
    if(bHostedinPWA)
    {
      window.location.href = sPWAUrl + "DocLib/DocLibRedirector.asp?NextPageUrl=DocLib/DocLibMain.asp&ProjID=-99";
    }
    else
    {
      window.location.href = sFullUrl;
    }
    return;
  }

  InitXmlHttpObjects();

  // Create the root node.
  var oRoot = oXmlDoc.createNode(1, "XMLFormData", "");
  oXmlDoc.appendChild(oRoot);

  // Create 'ProjID' node.
  var oNewNode = oXmlDoc.createNode(1, "ProjectID", "");
  oNewNode.text = sPWAProjId;
  oRoot.appendChild(oNewNode);

  // Create 'Operation' node.
  oNewNode = oXmlDoc.createNode(1, "Operation", "");
  oNewNode.text = "DeleteAllDocLibLinks";
  oRoot.appendChild(oNewNode);

  // Create 'DocLibName' node.
  oNewNode = oXmlDoc.createNode(1, "DocLibName", "");
  oNewNode.text = sDocListNameToDelete;
  oRoot.appendChild(oNewNode);

  // We don't check the result code here because there is not much user can do anyway if the session times out etc.
  ExecXmlHttpRequest();

  if(bHostedinPWA)
  {
    window.location.href = sPWAUrl + "DocLib/DocLibRedirector.asp?NextPageUrl=DocLib/DocLibMain.asp&ProjID=" + sPWAProjId;
  }
  else
  {
    window.location.href = sFullUrl;
  }

  return;

} // End of ExecHTML_WaitForComplete_DeleteDocList().
