/**
 ******************************************************************************
 * Copyright © 2001 - 2008 EMC Corporation.  All Rights Reserved.
 ******************************************************************************
 *
 * Project        WDK 5.3
 * Created on     04/18/2004
 * Tab width      3
 *
 ******************************************************************************
 *
 * PVCS Maintained Data
 *
 * Revision       $Revision: 27$
 * Modified on    $Date: 11/27/2008 8:26:39 AM$
 *
 * Log at EOF
 *
 ******************************************************************************
 */

if (typeof wdk.xfer == "undefined")
{
   wdk.xfer = {};
}

wdk.xfer.ucfRequiredInclude = undefined;
wdk.xfer.ucfRequiredExclude = undefined;

var LISTBOX_SUFFIX = "_listbox";

/**
 * Event handler for single http downloads.
 */
function httpDownloadContent()
{
   if(wdk.xfer.__isDownloadEventStale(arguments) == false)
   {
      var i, len = arguments.length;
      for(i = 1; i < len; i++)
      {
         var newurl = arguments[i];
         if(!wdk.xfer.__isKeyStateArg(newurl))
         {
            newurl = addBrowserIdToURL(newurl);
            
            if (g_clientInfo.isBrowser(ClientInfo.MSIE))
            {
               // This is a workaround since window.location.replace() does not work
               // properly in IE if the window is created using showModalDialog() API.
               if ((!!(window.dialogArguments)) && (!!(window.dialogArguments.m_isWDKModalPopup)) && (!!(dialogArguments.topLevelWindow)))
               {
                   var newWin = dialogArguments.topLevelWindow.open(newurl);
                   registerPopupWnd(newWin);
               }
               else  {
                   var newWin = window.open(newurl);
                   registerPopupWnd(newWin);
               }
            }
            else
            {
               var newWin = window.open(newurl);
               registerPopupWnd(newWin);
            }

         }
      }
      wdk.xfer.__makeDownloadEventStale(arguments);
   }
}


/**
 * Event handler for multiple http downloads.
 */
function httpMultiDownloadContent()
{
   if(wdk.xfer.__isDownloadEventStale(arguments) == false)
   {
      var contentIds = new Array();
      contentIds.push("Reload");
      contentIds.push(new String(new Date().getTime()));
      var i, len = arguments.length;
      for(i = 1; i < len; i++)
      {
         if(!wdk.xfer.__isKeyStateArg(arguments[i]))
         {
            contentIds.push("contentId");
            contentIds.push(arguments[i]);
         }
      }
      var componentUrl = generateComponentUrl(getVirtualDir(), "httpmultifiledownload", contentIds);
     // var newwin = window.open(componentUrl);
      if (g_clientInfo.isBrowser(ClientInfo.MSIE))
            {
               // This is a workaround since window.location.replace() does not work
               // properly in IE if the window is created using showModalDialog() API.
               if ((!!(window.dialogArguments)) && (!!(window.dialogArguments.m_isWDKModalPopup)) && (!!(dialogArguments.topLevelWindow)))
               {
                   var newWin = dialogArguments.topLevelWindow.open(componentUrl);

               }
               else  {
                   var newWin = window.open(componentUrl);

               }
            }
            else
            {
               var newWin = window.open(componentUrl);
               
            }
      wdk.xfer.__makeDownloadEventStale(arguments);
   }
}

/**
 * Event handler for ACS Http downloads.
 */
function httpDownloadContentFromAcs()
{
   if(wdk.xfer.__isDownloadEventStale(arguments) == false)
   {
      // Only attempt 1st ACS Url for now. In future, we can attempt failover if multiple URLs
      var url = arguments[1];
      if (url )
      {
         /* No addBrowserIdToUrl required - URL is external : going to ACS */
         var newWin = window.open();
         registerPopupWnd(newWin);
         var formHtml = generateFormHTML('acsForm', url);

         if (Trace_CONTENTTRANSFER)
         {
            wdk.xfer.__trace_contentxfer("Form Parameters for ACS POST:");
            wdk.xfer.__dump_contentxfer(formHtml);
         }

         var childDoc = newWin.document;
         childDoc.write("<html><head></head><body>" + formHtml + "</body></html>");
         childDoc.close();
         childDoc.forms['acsForm'].submit();
      }
   }
}

/**
 * Returns true if the arguments contain a stale event id. A stale event is one whose id has been
 * registered with wdk.xfer.__makeDownloadEventStale
 */
wdk.xfer.__isDownloadEventStale = function(callerArgs)
{
   var eventId = parseInt(callerArgs[0]);
   var lastId = getCookie("lastHttpDownloadContent");
   // we will only trigger download if the event is not stale (got it with back button)
   return (lastId != null && parseInt(lastId) >= eventId);
}

/**
 * Remembers the current download event id. Once an event id is remembered it is stale and
 * wdk.xfer.__isDownloadEventStale will return true.
 * @see wdk.xfer.__isDownloadEventStale
 */
wdk.xfer.__makeDownloadEventStale = function(callerArgs)
{
  var eventId = parseInt(callerArgs[0]);
  setCookie("lastHttpDownloadContent", eventId + 1, null, null);
}

function getUcfSessionId(formElement, reqKey)
{
   var retval = null;
   var applet = wdk.xfer.__findUcfInvokerApplet(formElement);
   if(applet != null)
   {
      try
      {
         // this first simple call into liveconnect, believe it or not, speeds up the getUcfSessionId
         // call below there is no busywait type of cpu hogging
         applet.getSessionRequestKey();
         retval = {};
         retval.ucfSessionId = reqKey ? applet.getUcfSessionId(reqKey) : applet.getUcfSessionId();
         retval.cookieValue = applet.getUcfCookie();
      }
      catch(e)
      {
         // liveconnect not supported - kick off the handshake with the InitConnection applet
         // TODO: this only works on mozillas - it's ok for now because we come in here only
         // on netscape on mac os - the rest has liveconnect working
         var cloned = applet.cloneNode(true);
         cloned.setAttribute("code", "com.documentum.web.applet.ucfinvoker.InitConnection.class");
         if (cloned.tagName == "OBJECT")
         {
            cloned.setAttribute("classid", "java:com.documentum.web.applet.ucfinvoker.InitConnection.class");
         }
         cloned.setAttribute("height", "0");
         cloned.setAttribute("width", "0");
         // we render the invoker applet within a span element
         applet.parentNode.appendChild(cloned);
         // we would only be here on mac os x mozilla, but this is just a sanity check
         if (g_clientInfo.isBrowser(ClientInfo.MOZILLA))
         {
            // This is to allow the dom to be updated with the applet and to introduce a small delay
            // of one roundtrip to make sure the handshake more or less happens early enough. Without
            // this the dom won't update until we return from the caller
         	req = new XMLHttpRequest();
            var url = "/" + getVirtualDir() + "/wdk/blank.htm?Reload=" + (new Date().getTime());
            req.open('GET', url, false);
            req.send(null);
         }
      }
   }
   if(Trace_CONTENTTRANSFER) wdk.xfer.__trace_contentxfer("ucfSessionId=" + retval.ucfSessionId);
   return retval;
}

function setUcfSessionIdElement(strFormName, strUcfSessionHiddenName, strUcfCookieHiddenName, reqKey)
{
   if (strFormName && strUcfSessionHiddenName && strUcfCookieHiddenName)
   {
      var ucfForm = document.forms[strFormName];
      if (ucfForm)
      {
         // make sure that the event requires UCF session
         var formId = ucfForm.elements["__dmfFormId"].value;
         var action = ucfForm.elements["__dmfAction"].value;
         // event name is of the form formId + "_" + handlerMethod;
         var handlerMethod = action.substr((formId + "_").length);
         // if ucfRequiredExclude is defined and method explicitly excluded, then return
         if (wdk.xfer.ucfRequiredExclude && wdk.xfer.ucfRequiredExclude[handlerMethod]) 
         {
            return;
         }
         // if ucfRequiredInclude is defined and method not explicitly included, then return
         if (wdk.xfer.ucfRequiredInclude && !wdk.xfer.ucfRequiredInclude[handlerMethod])
         {
            return;
         }
         
         // As per design, assumes only 1 LaunchRuntimeApplet and hence 1 session id element per top level form.
         var sessionIdElement = ucfForm.elements[strUcfSessionHiddenName];
         var cookieElement = ucfForm.elements[strUcfCookieHiddenName];
         if (sessionIdElement && cookieElement)
         {
            function setSessionIdOnForm(retval) 
            {
               // Generic check for if(ucfSessionId) crashes Mozilla on Unix. Hence checking specifically for null.
               if (retval && retval.ucfSessionId != null)
               {
                  sessionIdElement.value = retval.ucfSessionId;
                  if (Trace_CONTENTTRANSFER) wdk.xfer.__trace_contentxfer("Set element: " + strUcfSessionHiddenName + ", in Form:" + strFormName + " to :" + retval.ucfSessionId);
               }
               if (retval && retval.cookieValue != null)
               {
                  cookieElement.value = retval.cookieValue;
                  if (Trace_CONTENTTRANSFER) wdk.xfer.__trace_contentxfer("Set element: " + strUcfCookieHiddenName + ", in Form:" + strFormName + " to :" + retval.cookieValue);
               }
            }
            
            var retval = getUcfSessionId(ucfForm);
            if (retval != null)
            {
               setSessionIdOnForm(retval);
            }
            else
            {
               var topwnd = getTopLevelWndForApplication();                
               if (topwnd.wdk && topwnd.wdk.xfer && topwnd.wdk.xfer.getInvokerFrame)
               {
                  var invokerWindow = topwnd.wdk.xfer.getInvokerFrame();
                  for (var i = 0; i < invokerWindow.document.forms.length; i++)
                  {
                     var formElement = invokerWindow.document.forms[i];
                     // pass the request key as ResidentLaunchRuntime uses it to log any errors on the server side
                     // they can then be retrieved by the request with that key, and displayed on the client
                     retval = invokerWindow.getUcfSessionId(formElement, reqKey);
                     if (retval && retval.ucfSessionId != null) 
                     {
                        retval.ucfSessionId = retval.ucfSessionId + ";" + reqKey;
                     }
                     setSessionIdOnForm(retval);
                     break;
                  }
               }
            }
         }
      }
   }
}

wdk.xfer.__findUcfInvokerAppletByTagName = function(formElement, tagName)
{
   var applet = null;
   for(var applts = formElement.getElementsByTagName(tagName), i = 0; i < applts.length; i++)
   {
      // Since liveconnect on safari only works when applets are accessed in the form
      // document.appletName we have to find out what the name of the applet is. No
      // attributes of the applet tag cam be accessed through dom (bug in liveconnect)
      // we have to get to parameter invoker_applet_tag_name which carries applet's name
      if(g_clientInfo.isBrowser(ClientInfo.SAFARI))
      {
         for(var params = formElement.ownerDocument.getElementsByName("appletName515f7ddee55e428b964a3839a78fbaa6"), j = 0; j < params.length; j++)
         {
            if(params[j].tagName == "PARAM" && params[j].parentNode == applts[i])
            {
               var appletName = params[j].value;
               var appletTmp = eval("formElement.ownerDocument." + appletName);
               applet = appletTmp;
               break;
            }
         }
      }
      else
      {
         var id = applts[i].getAttribute("id");
         // if id has our guid, then it must be our applet
         if(id != null && id.indexOf("515f7ddee55e428b964a3839a78fbaa6") != - 1)
         {
            applet = applts[i];
         }
      }
   }
   return applet;
}

// write applet markup using a script to work around the IE issue of "clicking
// to activate an activeX control"
function activateXAutoActivate(appletMarkup)
{
   document.write(appletMarkup);
}

wdk.xfer.__findUcfInvokerApplet = function(formElement)
{
   var applet = wdk.xfer.__findUcfInvokerAppletByTagName(formElement, "APPLET");
   if (applet == null)
   {
      applet = wdk.xfer.__findUcfInvokerAppletByTagName(formElement, "OBJECT");
   }
   return applet;
}

//If the ctrl key is pressed when the content transfer action is invoked, fireClientEvent passes key state as
// one of the argument. We need to ignore it.
wdk.xfer.__isKeyStateArg = function(argvalue)
{
   return (argvalue == "shiftKeyPressed" || argvalue == "ctrlKeyPressed" || argvalue == "altKeyPressed" );
}

wdk.xfer.__trace_contentxfer = function(msg)
{
   Trace_println("contenttransfer.js: " + msg);
}

wdk.xfer.__dump_contentxfer = function(obj)
{
   Trace_println("contenttransfer.js:");
   Trace_dump(obj);
}

if (typeof(wdk.xfer.g_include_contenttransfer) == "undefined")
{
   wdk.xfer.g_include_contenttransfer = true;
   registerClientEventHandler(null, "httpDownloadContent", httpDownloadContent);
   registerClientEventHandler(null, "httpDownloadContentFromAcs", httpDownloadContentFromAcs);
   registerClientEventHandler(null, "httpMultiDownloadContent", httpMultiDownloadContent);
}
var g_lastSelection=null;
// Used for accessibility users.Called when the user clicks on the
// Add Files button on the import page.
function startJSFileSelection()
{
   g_lastSelection = "AddFiles";
   var controlId = document.getElementById("fileselector").id;
   if (Trace_CONTENTTRANSFER) wdk.xfer.__trace_contentxfer("Add Files ");
   document.getElementById(controlId).openAddFiles();  
}

// Used for accessibility users. Called when the user clicks on the
// Add Folders button on the import page.
function startJSFolderSelection()
{
   g_lastSelection = "AddFolders";
   var controlId = document.getElementById("fileselector").id;
   if (Trace_CONTENTTRANSFER) wdk.xfer.__trace_contentxfer("Add Folders ");
   document.getElementById(controlId).openAddFolders();
}

// Used for accessibility users. Called when the user selects files
// to remove and clicks on the Remove button on the import page.
function startJSRemoveSelections()
{
   g_lastSelection = "RemoveFiles";
   var controlId = document.getElementById("fileselector").id;
   var listBox = document.getElementById(controlId + LISTBOX_SUFFIX);
   var strIndex = "";
   for (var i=listBox.length-1; i>=0; i--)
   {
      if (listBox.options[i].selected)
      {
         strIndex +=i+",";
         listBox.remove(i);
      }
   }

   if (listBox.length > 0)
   {
      listBox.options[0].selected="true";
   }
   if (strIndex.length > 0)
   {
      if (Trace_CONTENTTRANSFER) wdk.xfer.__trace_contentxfer("Remove selection, list:"+strIndex);
      document.getElementById(controlId).removeSelected(strIndex);
   }
}

// Since the import applet is not accessible through the keyboard a listbox and html buttons are
// used instead of it. Here the listbox is updated with the files selected for import.
function updateListbox()
{
   var controlId = document.getElementById("fileselector").id;
   var listBox = document.getElementById(controlId + LISTBOX_SUFFIX);
   for (var i = listBox.length; i >= 0; i--)
   {
      listBox.remove(i);
   }
   for (var i = 0; i < updateListbox.arguments.length; i++)
   {
      var opt = document.createElement("option");
      opt.title = opt.text = updateListbox.arguments[i];
      listBox.options.add(opt);
      if (listBox.length >0)
      {
         listBox.options[0].selected="true";
      }
   }
   if (Trace_CONTENTTRANSFER) wdk.xfer.__trace_contentxfer("Update listbox");
}

// Display an alert on the files/folders that are added to/removed from the
// fileselector applet for accessibility users.
function displayAlert()
{
   alert(displayAlert.arguments[0]);
   if (g_lastSelection != null && g_lastSelection != undefined)
   {
      var control = document.getElementById(g_lastSelection);
      if (control != null && control != undefined)
      {
         control.focus();
      }
   }
}


