// Utilities Script v.1.0
// Miscellaneous common functions
// todd@mindsharp.com  www.MindsharpBlogs.com/Todd
// CopyRight © 2005, All Rights Reserved
// Last updated 8/1/2005
// Please don't delete this header

//Private Common Utility Function
//Comfirm the submission of the URL created in Custom_AddDocLibMenuItems
function utilityNoRestoreWarning(url, cookieName, isExplorer)
{
  try
  {
    //If there is a cookie and it has the data that identifies that this
    //page has already been warned about, do not warn again.
    //Other wise, set the cookie and give a context specific warning.
    //These warnings can be turned off globally by setting the constants
    //Warn_About_ExplorerView and/or Warn_About_Datasheet to false
    if(document.cookie &&
        (document.cookie.indexOf(url) < 0 |
         document.cookie.indexOf(cookieName) < 0)
      )
    {
      document.cookie = cookieName + "=" + url + "; path=/";

      if(isExplorer)
      {
        //Give the warning that documents cannot be restored in Web Folders
        if(Warn_About_ExplorerView)
        {
          alert(L_ExplorerWarning_Text);
        }
      }
      else
      {
        //Give the warning that documents cannot be restored in Datasheets
        if(Warn_About_Datasheet)
        {
          alert(L_DatasheetWarning_Text);
        }
      }
    }
  }
  catch(e){if(Silence_Errors){window.onerror = function(){return true;}}else{alert(e.message)};}
}

//Private Common Utility Function
//Comfirm the submission of the URL created in Custom_AddDocLibMenuItems
function utilityRestoreDocLibItem(itemType, resUrl)
{
  try
  {
    //Note itemType values represent Item=0 and Folder=1
    if(confirm(itemType == 1 ? L_STSResConfirm1_Text : L_STSResConfirm_Text))
    {
      if(SubmitFormPost)
      {
        SubmitFormPost(resUrl);
      }
    }
  }
  catch(e){if(Silence_Errors){window.onerror = function(){return true;}}else{alert(e.message)};}
}

//Private Common Utility Function
//Obtain Toolbar Button as TD using link ID, if found
//Return empty string if not found
//Globally change class=ms-toolbar to empty string on the returned TD
//A different CSS sytle will be used to render it
function utilityGetTdHTML(linkId)
{
  try
  {
    var tdHTML = "";
    var link = document.getElementById(linkId)
    if(link)
    {
      tdHTML = link.parentNode.parentNode.innerHTML.replace(/class=ms-toolbar/gi,"");
    }
    return tdHTML;
  }
  catch(e)
  {
    return ""
  }
}

//Put the Restore and Delete (permanent) options on the menu
//Do not show any of the other menu options
function utilityAddRestoreDocLibMenuItems(m, listGuid, itemId, itemUrl, itemType)
{
  try
  {
      //No restore allowed for items in a Deleted (restorable) folder
      var preventRestore = false;
      if(itemType == 0)
      {
        if(itemUrl.indexOf(L_PrefixDeletedFolder) >= 0)
        {
          preventRestore = true;
        }
      }

      //Create Restore menu option
      sDisplayText = L_RestoreDocItem_Text;
      if(preventRestore)
      {
        sAction = "JavaScript:alert(L_RestorePrevented_Text);";
      }
      else
      {
        newName = utilityRemoveDeletedPrefix(itemUrl);
        if(newName && newName.length > 0)
        {
          var mainForm = document.forms[MSOWebPartPageFormName];
          if(mainForm)
          {
            utilityCreateTag(mainForm, "urn:schemas-microsoft-com:office:office#_ModerationComments", "Restored on " + new Date());
          }

          sAction = "utilityRestoreDocLibItem(currentItemFSObjType, '" 
            + L_Owssvr_Path + "&Cmd=Save"
            + "&List=" + listGuid
            + "&ID=" + itemId 
            + "&owsfileref=" + escapeProperly(unescapeProperly(itemUrl))
            + "&owsnewfileref=" + newName
            + "&NextUsing=" + GetSource()
            + "')";
        }
        else
        {
          sAction = "JavaScript:alert('Could not determine new name for the file.');";
        }
      }
      CAMOpt(m, sDisplayText, sAction, L_RestoreDocItem_Image);

      sDisplayText = L_DeleteDocItem_Text;
      sAction = "DeleteDocLibItem('" 
        + L_Owssvr_Path + "&Cmd=Delete"
        + "&List=" + listGuid
        + "&ID=" + itemId
        + "&owsfileref=" + escapeProperly(unescapeProperly(itemUrl))
        + "&NextUsing=" + GetSource()
        + "')";
      CAMOpt(m, sDisplayText, sAction, L_DeleteDocItem_Image);
  }
  catch(e){if(Silence_Errors){window.onerror = function(){return true;}}else{alert(e.message)};}
}

//Private Common Utility Function
//Create a dynamic custom toolbar that only shows options that
//are currently available and valid on a restore page: Up, Filter,
//Hide Filter Choices, and Edit in Datasheet.
//Dependant on a custom style called "this-toolbar" that is typcally
//defined in a toolbar.css file also stored in the /Forms folder
function utilityCreateCustomToolbar()
{
  try
  {
    //Replace div placeholder with toolbar table found in Page_xxx.js
    var customToolbar = document.getElementById("customToolbar");
    if(customToolbar)
    {
      var separator = "<TD class=ms-separator>|</TD>"; 

      //Obtain current toolbar buttons that we care about
      var upTD = utilityGetTdHTML("diidUp");
      var filterTD = utilityGetTdHTML("diidFilterButton")
      var datasheetTD = utilityGetTdHTML("diidEditInGridButton");

      //Begin construction of table
      var table = "<TABLE class=this-toolbar style=margin-left: 3px; cellpadding=2 cellspacing=0 border=0><TR>";

      //Add Up button, if any
      table += upTD;

      //Add separator, if any
      if(upTD.length > 0 &
         filterTD.length > 0)
      {
        table += separator;
      }

      //Add Filter button, if any
      table += filterTD;

      //Add separator, if any
      if((upTD.length > 0 |
          filterTD.length > 0) &
          datasheetTD.length > 0)
      {
        table += separator;
      }

      //Add Edit In Datasheet button, if any
      table += datasheetTD;

      //End construction of table
      table += "<TD width=99% align=right nowrap id=align01>&nbsp;</td></TR></table>";

      customToolbar.innerHTML = table;
    }
  }
  catch(e){if(Silence_Errors){window.onerror = function(){return true;}}else{alert(e.message)};}
}

//Private Common Utility Function
//Replace the HTML in a link on a page that contains a certain text
function utilityReplaceLink(searchText, replacementHTML, replaceEntireLink)
{
  try
  {
    var links = document.getElementsByTagName("A");
    for(var i=0; i<links.length; i++)
    {
      var currLink = links[i];
      if(currLink.innerHTML.indexOf(searchText) >= 0)
      {
        if(replaceEntireLink)
        {
          currLink.outerHTML = replacementHTML;
        }
        else
        {
          currLink.innerHTML = replacementHTML;
        }
        break;
      }
    }
  }
  catch(e){if(Silence_Errors){window.onerror = function(){return true;}}else{alert(e.message)};}
}

//Private Common Utility Function
//Remove the !![deleted...] prefix from every link on the page
//Constants defined in Constants.js
function utilityTrimPrefix()
{
  try
  {
    var linkText = "";
    var links = document.getElementsByTagName("A");
    for(var i=0; i<links.length; i++)
    {
      link = links[i];
      if(link)
      {
        linkText = link.innerText;
        if(linkText)
        {
          //Remove the prefix for a deleted item
          if(linkText.indexOf(L_PrefixDeletedItem) >= 0)
          {
            link.innerText = linkText.substring(linkText.indexOf(L_PrefixDeletedItem)
              + L_PrefixDeletedItem.length);
          }
          //Remove the prefix for a deleted folder
          else if(linkText.indexOf(L_PrefixDeletedFolder) >= 0)
          {
            link.innerText = linkText.substring(linkText.indexOf(L_PrefixDeletedFolder)
              + L_PrefixDeletedFolder.length);
          }
        }
        //Add an alt text to each item's document icon
        //Determine which folder the document is located in and change the icon alt tag
        //This feature can turned off by setting the Show_Folder_Tooltip constant to false
        else if(linkText.length == 0)
        {
          if(Show_Folder_Tooltip && link.outerHTML)
          {
            var folder = link.href;
            if(folder)
            {
              var listUrl = ctx.listUrlDir;
              if(listUrl)
              {
                var altTag = "'Found in ";
                folder = folder.substring(folder.indexOf(listUrl) + listUrl.length + 1, folder.lastIndexOf(L_PrefixDeleted));
                if(folder.length > 0)
                {
                  if(folder.toUpperCase().indexOf("JAVASCRIPT") < 0)
                  {
                    var deletedFolder = folder.indexOf(L_PrefixDeletedFolder);
                    if(deletedFolder >= 0)
                    {
                      folder = folder.substring(folder.indexOf(L_PrefixDeletedFolder) + L_PrefixDeletedFolder.length);
                      altTag += L_DeleteDocItem_Restorable + " ";
                    }
                     //Remove the trailing slash ("/") and uppercase
                    folder = folder.substring(0, folder.length - 1).toUpperCase();
                    altTag += "Folder: " + folder + "'";
                  }
                  else
                  {
                    altTag = listUrl;
                  }
                }
                else
                {
                  altTag += "Root Folder'";
                }
                link.outerHTML = link.outerHTML.replace("Icon", altTag);
              }
            }
          }
        }
      }
    }
  }
  catch(e){if(Silence_Errors){window.onerror = function(){return true;}}else{alert(e.message)};}
}

//Private Common Utility Function
//Determine if file or folder and rename
function utilityAddDeletedPrefix(itemUrl, itemType)
{
  try
  {
    var newName = "";
    var lastSlash = itemUrl.lastIndexOf("/");
 
    //Note itemType values represent Item=0 and Folder=1
    if (itemType == 0)
    {
      //Determine if item has an extension
      //and rename it accordingly
      var lastDot = itemUrl.lastIndexOf(".");
      if(lastDot >= 0)
      {
        newName = L_PrefixDeletedItem 
          + itemUrl.substring(lastSlash+1, lastDot);
      }
      else
      {
        newName = L_PrefixDeletedItem
          + itemUrl.substring(lastSlash+1);
      }
    }
    else
    {
      //Prepend the folder name
      //Even if they contain a dot,
      //folders never have an extension
      newName = L_PrefixDeletedFolder
        + itemUrl.substring(lastSlash+1);
    }

    return newName;
  }
  catch(e)
  {
    return null;
  }
}

//Private Common Utility Function
//Determine if file or folder and rename
function utilityRemoveDeletedPrefix(itemUrl)
{
  try
  {
    var newName = "";
    var lastBracket = itemUrl.lastIndexOf("]");
    var lastDot   = itemUrl.lastIndexOf(".");

    //Folders (and some files) do not have an extension
    if(lastDot >= 0)
      newName = itemUrl.substring(lastBracket+1, lastDot);
    else
      newName = itemUrl.substring(lastBracket+1);

    return newName;
  }
  catch(e)
  {
    return null;
  }
}

//Private Common Utility Function
//Generate input tags that will be POSTED to the server
function utilityCreateTag(existingForm, fieldName, fieldValue)
{
  try
  {
    var existingField = document.getElementById(fieldName);
    if(existingField)
    {
      //Rename the existing form field
      existingField.name = "old_" + fieldName;
    }
     
    //Create a new, hidden, element to hold the new file name
    //This will effectively pass the new value without
    //negatively effecting the EditForm.aspx display
    var hiddenField = document.createElement("Input");
    if(hiddenField)
    {
      //Populate new field with values
      hiddenField.name  = fieldName;
      hiddenField.value = fieldValue;
      hiddenField.type  = "Hidden";

      //Append the hidden field to the form
      existingForm.appendChild(hiddenField);
    }
  }
  catch(e){if(Silence_Errors){window.onerror = function(){return true;}}else{alert(e.message)};}
}

//Private Common Utility Function
//Setup form to submit and submit
function utilityRecycleItem(listGuid, itemId, itemUrl, itemType)
{
  try
  {
    //Note itemType values represent Item=0 and Folder=1
    if(confirm(itemType == 1 ? L_STSDelConfirm1_Text : L_STSDelConfirm_Text))
    {
      itemUrl = unescape(itemUrl);

      var newName = utilityAddDeletedPrefix(itemUrl, itemType);
      if(newName && newName.length > 0)
      {
        var mainForm = document.forms[MSOWebPartPageFormName];
        if(mainForm)
        {
          utilityCreateTag(mainForm, "Cmd",            "Save");
          utilityCreateTag(mainForm, "List",           listGuid);
          utilityCreateTag(mainForm, "ID",             itemId);
          utilityCreateTag(mainForm, "owsfileref",     itemUrl);
          utilityCreateTag(mainForm, "owsnewfileref",  newName);
          utilityCreateTag(mainForm, "urn:schemas-microsoft-com:office:office#_ModerationComments", "Deleted on " + new Date());

          if(SubmitFormPost)
          {
            SubmitFormPost(L_Owssvr_Path);
          }
        }
      }
    }
  }
  catch(e){if(Silence_Errors){window.onerror = function(){return true;}}else{alert(e.message)};}
}