function SubstituteFormSubmit(e, portletframe)
{
  portletWindow = document.getElementById(portletframe.name).contentWindow;
  portletDocument = portletWindow.document;
  portletWindow.adfpp_originalSubmit = new Object();
  //  alert("Substituting for "+portletframe.name);
  
  // For all form elements in the Portlets markup 
  // a. Attach the form's submit button to Portal specific function
  // b. If no submit button, Attach adfpp_formSub to the form submit
  // 
  for (var _f = 0; _f < portletDocument.forms.length; _f++)
  {
     
     //  just catch the form level submit
      if (portletDocument.forms[_f].attachEvent)
      {
          portletDocument.forms[_f].attachEvent('onsubmit', portletWindow.adfpp_formSub);
          // alert('Attaching adfpp_formSub for '+ portletDocument.forms[_f].name);
      }
      else
      {
            portletDocument.forms[_f].addEventListener('submit', portletWindow.adfpp_formSub, true);
      }
      
      // attach an event with all submit buttons to determine the source of submit event
      for (var _i = 0; _i < portletDocument.forms[_f].elements.length; _i++)
      {
          var _submitObj = portletDocument.forms[_f].elements[_i];
          if (_submitObj.type == 'submit')
          {
            if (_submitObj.attachEvent)
	    {
	        _submitObj.attachEvent('onclick', portletWindow.setSubName);
	              
	    }
	    else
	    {
	         _submitObj.addEventListener('click', portletWindow.setSubName, true);
            }
          }
      }
      
      // Required to handle onclick events originally attached with the form ( exp for Portlet bridge)
      portletWindow.adfpp_originalSubmit[_f] = portletDocument.forms[_f].submit;
      portletDocument.forms[_f].submit = portletWindow.adfpp_formSub;    
  }
   
  var portletAnchors = portletDocument.getElementsByTagName('a');
  
  for(var j=0; j < portletAnchors.length; j++)
  {
    // May be handle cases like javascript:window.location like
    // but that may get tricky.
    
    var anchorUrl = new String(portletAnchors[j].href);
    var lC_anchorUrl = anchorUrl.toLocaleLowerCase();
            
    // anchorUrl can be of these types
    // a. simple link starting with http://www.xxx.com
    // b. Urls pointing to same application starting with /xxx/yyy
    // c. Javascript execution function starting with javascript:function_name()
    // d. href=#
    
    // Do not attach any event with the javascript function
    //  alert('AnchorUrl '+ lC_anchorUrl);
    if ((lC_anchorUrl.indexOf("javascript") == 0) ||
        (lC_anchorUrl.indexOf("#") == (lC_anchorUrl.length - 1)))
    {
      continue;
    }
       
    try
    {   portletAnchors[j].attachEvent('onclick', portletWindow.adfpp_linkSub, false);
      // alert('IE attached '+portletAnchors[j].href);
    }
    catch(e)
    {  portletAnchors[j].addEventListener('click', portletWindow.adfpp_linkSub, false);
      // alert('Mozilla attached '+portletAnchors[j].href);
    }
  }
}



function cloneFormElements(sourceForm, portletComp_name, submitButtonName, prefixStr)
{
  //alert("submitButton: '" + submitButtonName + "'");
  
  for(var i = 0; i < sourceForm.elements.length; i++ )
  {
       cloneAndInportNode(portletComp_name, submitButtonName, prefixStr, sourceForm.elements[i]);
  }
 }

function cloneElements(portletComp_name, submitButtonName, prefixStr)
{
  portletWindow = document.getElementById(portletComp_name+'_iframe').contentWindow;
  portletDocument = portletWindow.document;
  
  var collObjects = portletDocument.getElementsByTagName('INPUT');
  
  destDiv = document.getElementById(portletComp_name+'_hidden_div');
  for(var i = 0; i < collObjects.length; i++ )
  {
    
    cloneAndInportNode(portletComp_name, submitButtonName, prefixStr, collObjects[i]);
  
  }
 }



function cloneAndInportNode(portletComp_name, submitButtonName, prefixStr, sourceField)
{
   destDiv = document.getElementById(portletComp_name+'_hidden_div');
   if(sourceField.type == 'button')
   {
      return;
   }
    
   var destInput = sourceField.cloneNode(true);

   if (destInput.type == 'submit')
   {
      if (destInput.name == submitButtonName)
      {
      createHiddenField(destDiv, prefixStr + destInput.name, destInput.value);
      }
      return;
   }
    // need to actually append this to a hidden div in the form
    // so that the cloned inputs aren't visible
    if(document.importNode)
    {
      try
      {
       
        destInput = document.importNode(destInput, true);
        if  (destInput.type == 'textarea')
        {
         destInput.value = sourceField.value;
        }
        else if (destInput.type.indexOf('select') == 0)
	{
	  // importNode is not setting the 'selected' value for select one and select multiple
	  // elements, bug 5653206
	  for (var i = 0; i < destInput.options.length;i++)
	  {
	      destInput.options[i].selected = sourceField.options[i].selected;
	  }
        }
        
        // alert(destInput.name + ' ' +destInput.value);
	destInput.name  = prefixStr + destInput.name;
        
        destDiv.appendChild(destInput);
      }
      catch(e)
      {
        alert(e.message);
      }
    }
    else
    { // IE as importNode not available in IE
    
      try
      {
          if (destInput.type.indexOf('select') == 0)
            destInput = importNode_for_select(sourceField, true);
          else
          destInput = _importNode(sourceField, true);
            
          destInput.name  = prefixStr + destInput.name;
          destDiv.appendChild(destInput);
         
          // For IE, the checked boolean value of the cloned object is getting 
          // lost, hence forcing to change the propertly after appending
               
          if((destInput.type == 'radio')||(destInput.type == 'checkbox'))
          {
             if(sourceField.checked)
      	        destInput.checked='true';
          } 
          else if (destInput.type.indexOf('select') == 0)
	  { // bug 5653206 select multiple is not getting selected boolean
	     for (var i = 0; i < destInput.options.length;i++)
	     {
	         destInput.options[i].selected = sourceField.options[i].selected;
      }
          }   
      }
      catch(e)
      {
         alert(e.message);
      }
  }
 
}
// Added for select multiple and single as on IE _importNode() was
// behaving incorrectly and was selecting only a single option
// Still selection needs to be reset/set on the source after importing the node
function importNode_for_select (oNode, bDeep) 
{
	var nodeHTML = oNode.xml||oNode.outerHTML;
	if(!nodeHTML) throw "importNode: nodeHTML is null or undefined";
	if(typeof bDeep == "undefined") throw "importNodeIE: not enough arguments";
	var tmpNode = document.createElement("div");
	tmpNode.innerHTML = nodeHTML;
	return tmpNode.firstChild.cloneNode(bDeep);
}

function _importNode(oNode, bImportChildren)
{
  var oNew;
  
  switch(oNode.nodeType)
  {
    case 1:
    {
      oNew = document.createElement(oNode.nodeName);

      var attr = oNode.attributes;
      for (var i = 0; i < attr.length; i++)
      {
        var attrib = attr[i];
        if ((attrib && attrib.specified) ||
	    (attrib.name == 'name') ||
	    (attrib.name == 'selected') ||
            (attrib.name == 'value'))
        {
           try
           {        oNew.setAttribute(attrib.name,attrib.value); }
           catch(e)
           {continue;}
        }
      }
      
      // We don't copy the value attribute for a textarea
      // since it's also available as a child node.
      if (oNode.nodeName != 'TEXTAREA')
      {
        oNew.value = oNode.value;
      }
      
      
      if(oNode.nodeName == 'OPTION')
      { 
         oNew.selected = oNode.selected;
      }
      break;
    }
    case 3:
    {
      oNew = document.createTextNode(oNode.nodeValue);
      break;
    }
  }
		
  if(bImportChildren && oNode.hasChildNodes())
  {
    for(var oChild = oNode.firstChild; oChild; oChild = oChild.nextSibling)
    {
	oNew.appendChild(_importNode(oChild, true));
    }
  }
	
  return oNew;
}

function createHiddenFieldForPage(dest, myURL)
{
  
  var index = myURL.indexOf('?');
  var pair = null;
  if (index > 0)
  {
    var query = myURL.slice(index+1);
    var paramsWithValue = query.split('&');
    for (var i = 0; i < paramsWithValue.length; i++)
    {
      pair = paramsWithValue[i].split('=');
      if (pair[0])
      {
        if (pair[1])
          createHiddenField(dest, pair[0], pair[1]);
        else
          createHiddenField(dest, pair[0], '');
      }
    }
  }
}


/* Create Hidden field for the Portlet  */
 function createHiddenField(dest, name, value)
 {
   var  newEl = document.createElement('INPUT');
   newEl.type='hidden';
   newEl.name=name;
   newEl.value=value;
   dest.appendChild(newEl);
 }

 function isURLForCurrentPage(url,facesFormURL)
 {
   // Special case: if the URL is destined for full page mode then we don't want 
   // to submit a form.
   var isFullPageModeLink = url.indexOf('_adfp_full_Page_Mode=true');
   if (isFullPageModeLink > -1)
     return false;
    
   var pageURL = stripParams(facesFormURL);
   var targetURL = stripParams(url);
   pageURL = qualifyUrl(pageURL);
   targetURL = qualifyUrl(targetURL);
   if ((pageURL.indexOf('%') > -1) && (targetURL.indexOf('%') > -1))
   {
      pageURL = fixMBChars(pageURL);
      targetURL = fixMBChars(targetURL);
   }
   
   return (pageURL == targetURL);
 }
 
 function qualifyUrl(url)
 {
  if (url.indexOf('/') == 0)
  {
    // append hostname
    var _indexUrl = window.location.href.substring(8).indexOf('/');
    var _appendUrl = window.location.href.substring(0,_indexUrl+8);
    var _newUrl = _appendUrl + url;
    return _newUrl;
    
  }
  return url;
 }
 
 
 function doesURLrequiresSubmit(url, iframeUrl)
 {
   // If the URL is destined for full page mode then we don't want to submit a
   // form.
   var isFullPageModeLink = url.indexOf('_adfp_full_Page_Mode=true');
   if (isFullPageModeLink > -1)
     return false;
    
   // Check if the URL has a Portlet Action so we need to submit a FORM
   // for full JSF lifecycle
   var isPortletAction = url.indexOf('__adfpwp_action_portlet');
   if (isPortletAction > -1)
     return true;
   
   var iframeURL_strip = stripParams(iframeUrl);
   var targetURL = stripParams(url);
   if ((iframeURL_strip.indexOf('%') > -1) && (targetURL.indexOf('%') > -1))
   {
      iframeURL_strip = fixMBChars(iframeURL_strip);
      targetURL = fixMBChars(targetURL);
   }
   
   return (iframeURL_strip == targetURL);
 }
 
  function fixMBChars(url)
  {
     var _indexUrl  = url.substring(8).indexOf('/')+9;
     var _hostUrl = url.substring(0,_indexUrl);
     var _contextPathIdx = url.substring(_indexUrl).indexOf('/');
     var _contextPath = url.substring(_indexUrl,_contextPathIdx+_indexUrl);
     _contextPath = _contextPath.toLowerCase();
     var remaining = url.substring(_contextPathIdx+_indexUrl);
     return _hostUrl + _contextPath + remaining;
 }
 
 function stripParams(url)
 {
   var strippedURL = url;
   var queryIdx = url.indexOf('?');
   if (queryIdx > -1)
   {
     strippedURL = url.substring(0, queryIdx);
   }
   var sesIdx = strippedURL.indexOf(';');
   if (sesIdx > -1)
   {
     strippedURL = strippedURL.substring(0, sesIdx);
   }
   return strippedURL;
 }
 
// portlet_compId -- Portlet Component Id
// facesForm_id   -- Faces Form Component Id
// clientid,      -- Portlet Client id, use for providing namespace prefix that
//                   only the source portlet can see
// submit_raw_url_params       -- boolean indicating that we submit raw names for url paramters
//                    if anchor tag click is causing this submit
// submittedobject - Object initiating this submit method
// submitButtonName - submit button name OR link url in case anchor tag
// urlParamsOnly   -- boolean indicating if we should also submit other portlet fields


function portletSubmit(portlet_compId, facesForm_id, clientid, submit_raw_url_params, 
           submittedobject, submitButtonName, urlParamsOnly)
 {
   var handleSubmit = false;
   var isFormSubmission = false;
   var submittedForm;
   var _portFrameURL = document.getElementById(portlet_compId+'_iframe').src;
   var prefixStr = '_adfp_portlet_field___adfpfp'+clientid + '.';
   var destHiddenDiv = document.getElementById(portlet_compId+'_hidden_div');
   var facesFormURL = document.getElementById(facesForm_id).action;
   //alert(facesFormURL);
   
   // alert('submitttedobject '+submittedobject);
   // alert('SubmitButtonName '+submitButtonName);
   
   // SubmittedOject can be
   // 0. NULL
   // 1. FORM
   // 2. LINK
   // 3. Submit type button INPUT
   // alert('tagName '+ submittedobject.tagName);
   // Fix the tag name, ideally the calling method should send the correct
   // object
   
   if ((submittedobject != null) &&
       ((submittedobject.tagName != 'A') &&
       (submittedobject.tagName != 'INPUT') &&
       (submittedobject.tagName != 'FORM')))
   {
     while (submittedobject != null)
     {
       submittedobject = submittedobject.parentNode;
        if ((submittedobject.tagName == 'A') ||
           (submittedobject.tagName == 'INPUT') ||
           (submittedobject.tagName == 'FORM'))
         break;  
     }
     // alert('fixed object tagName '+ submittedobject.tagName);
   }
   
 
   if (submittedobject == null)
   {
     if (isURLForCurrentPage(submitButtonName,facesFormURL))
     {
           //createURLElement(submitButtonName,portlet_compId );
           createHiddenField(destHiddenDiv, '_adfp_portlet_field_link_url', submitButtonName);
           handleSubmit = true; 
     }
     else
     {
       // its a window change location
       //URL link to a different page
       window.location = submitButtonName;
     }
   }
   else if (submittedobject.tagName == 'A')
   {
     if (doesURLrequiresSubmit(submittedobject.href, _portFrameURL) ||
         isURLForCurrentPage(submittedobject.href,facesFormURL))
     {
       createHiddenField(destHiddenDiv, '_adfp_portlet_field_link_url', submittedobject.href);
       if (submit_raw_url_params == 'true')
         createHiddenFieldForPage(destHiddenDiv, submittedobject.href);
       submittedForm = submittedobject;
       while (submittedForm != null && submittedForm.tagName != 'FORM') 
          submittedForm = submittedForm.parentNode;
       handleSubmit = true;
     }
     else
     {
       // anchor tag is clicked and submit is not required, so change the location
       // alert('target = '+submittedobject.target);
       // alert('href '+submittedobject.href);
       var portletWindow = document.getElementById(portlet_compId+'_iframe').contentWindow;
              
       var anchor_target = submittedobject.target;
       // if _self or not defined then, change the location of the 
       // iframe parent ( since the iframe should be hidden for user exp)
       if ((anchor_target == "_self") ||
           (anchor_target == "") ||
           (!anchor_target) ||
           (anchor_target == undefined) )
       {
         //alert('changing the portlet page location to '+submittedobject.href);
         portletWindow.parent.location = submittedobject.href;
       }
       else if (anchor_target == "_top")
       {
         //alert('changing the top.window location to '+submittedobject.href);
         top.window.location = submittedobject.href;
       }
       else if (anchor_target == "_parent")
       {
         if (portletWindow.parent.parent)
         {
          portletWindow.parent.parent.location = submittedobject.href;
         }
         else
           portletWindow.parent.location = submittedobject.href;
       }
       else if (anchor_target == "_blank")
       {
         window.open(submittedobject.href, anchor_target);
       }
       else
       {
         // Handle the cases where the target is some object Id
         var targetObj = document.getElementById(anchor_target);
         if (targetObj)
           targetObj.contentWindow.location = submittedobject.href;
       }
       isFormSubmission = false;
       return false;
     }
   }
   else if ((submitButtonName == 'Submit')  || 
            (submittedobject.tagName == 'FORM') || 
            (submittedobject.tagName == 'INPUT'))
   {
     
     submittedForm = submittedobject;
     while (submittedForm != null && submittedForm.tagName != 'FORM') 
          submittedForm = submittedForm.parentNode;
          
      
     if ((isURLForCurrentPage(submittedForm.action,facesFormURL))||
         (isURLForCurrentPage(submittedForm.action,_portFrameURL)))
     { 
        handleSubmit = true;
     }
     else
     {
       // alert('2 WHAT TO DO should just change location');
        isFormSubmission = true;
        
        //Add back in the submit button value
        if (submittedobject.tagName == 'INPUT' && submittedobject.type == 'submit')
        {
          var portletWindow = document.getElementById(portlet_compId+'_iframe').contentWindow;
          var submittedInput = submittedobject;
          var newField = portletWindow.document.createElement('INPUT');
          newField.name = submittedInput.name;
          newField.type = 'hidden';
          newField.value = submittedInput.value;
          submittedForm.appendChild(newField);
        }
     }
   }
   else
   {
    // alert('3 WHAT SHOULD I DO NOW');
   }
   
 
   
   
    // This function is called to so that on IE, we don't get the PPR issue
    // where ADF Faces tries to set focus on a hidden command button and
    // gives error
    // Here we call ADF Faces function to set the focus node which is the minimize
    // image
   _setRequestedFocusNode(document, portlet_compId+'_minimizeOrRestore_minimized', false, window); 
   
   // We only want to handle form submissions or URL links back to the same
   // page, otherwise we reinstate the standard submit method for the form
   if (handleSubmit)
   {
     var upload_done = handleUpload(submittedForm, portlet_compId+'_iframe');
          
     if (upload_done == true)
       return false;
   
     //createUseRequestWrapperField(portlet_compId);
     createHiddenField(destHiddenDiv,'_adfp_use_portlet_request_wrapper','true');
     createHiddenField(destHiddenDiv,'_adfp_submitted_portlet.'+ clientid, 'true');
     //createClientIdField(portlet_compId, clientid);
     if (!urlParamsOnly)
     {
     if (submittedForm != null)
     {
       createHiddenField(destHiddenDiv,'_adfp_portlet_field_portlet_form_action_url',submittedForm.action);
       cloneFormElements(submittedForm,portlet_compId, submitButtonName, prefixStr);
     }
     else
       {
       cloneElements(portlet_compId, submitButtonName, prefixStr);
       }
     }
       
     submitForm(facesForm_id, 0, {source:portlet_compId});  
     //_adfspu(facesForm_id,1,0,portlet_compId,0,1,0);
   }
   else
   {
     if (isFormSubmission)
     {
       var portletWindow = document.getElementById(portlet_compId+'_iframe').contentWindow;
       var portletDocument = portletWindow.document;
       _resetForms(portletWindow,portletDocument);
       //portletDocument.forms[0].submit = portletWindow.adfpp_originalSubmit;
       submittedForm.target = "_top";
       submittedForm.submit();
     }
     else
     {
       return true; //Anchor clicked
     }
   }
   return false; 
 }
 // Due to browser security we can not import file input tags to parent frame o IE
 // hence we force the iframe to submit with proper action url
 
 function handleUpload(submittedForm, iframe_id)
 {
     var portletObj = document.getElementById(iframe_id);
     var portletWindow = portletObj.contentWindow;
     var portletDocument = portletWindow.document;
     var uploadRequired = checkIfUploadNeeded(submittedForm, portletDocument);
     if (uploadRequired)
     {
       var lindex = submittedForm.action.indexOf('?');
       var form_params = submittedForm.action.substring(lindex+1);
       var new_action_url = portletObj.src + '&_adfp_portlet_form_submit=true' +'&'+form_params;
       submittedForm.action = new_action_url;
       _resetForms(portletWindow,portletDocument);
      // submittedForm.submit = portletWindow.adfpp_originalSubmit;
       if (submittedForm.detachEvent)
       {
         submittedForm.detachEvent('onsubmit', portletWindow.adfpp_formSub);
       }
       submittedForm.submit();
     }
     return uploadRequired;
 }
  
 function checkIfUploadNeeded(submittedForm, portletDocument)
 {
    var input_file = false;
    if (submittedForm == null)
     return false;
    for (var i = 0; i < submittedForm.elements.length; i++)
    {
      var elem = submittedForm.elements[i];
      if (elem.type == 'file')
      {
        input_file = true;
      }
    }
    
    if ((input_file == true) && (submittedForm.enctype == 'multipart/form-data'))
      return true;
    else
      return false;
 }


 // Get the Faces style sheet for the iframes
 // This will only work for a page containing single style sheet
 // Should be expanded
 function getFacesPageStyleSheet()
 {
   
   if(document.styleSheets)
   {
     return window.document.styleSheets;
   }
   return;
 }
 
 function _resizePortletIframe(iframeId)
 {
   _resizePortletIframeHeight(iframeId);
   _resizePortletIframeWidth(iframeId)
 }
   
 function _resizePortletIframeHeight(iframeId)
 {
   var iframeElement = parent.document.getElementById(iframeId);
   var iframeWindow  = iframeElement.contentWindow;
 
   if (iframeWindow.document.height)
   {
       iframeElement.style.height = iframeWindow.document.documentElement.scrollHeight + 'px';
       
   }
   else if (document.all)
   {
      var _sh;
      if (iframeWindow.document.compatMode &&
           iframeWindow.document.compatMode != 'BackCompat')
       {
         _sh = iframeWindow.document.documentElement.scrollHeight;
       }
       else
       {
         _sh = iframeWindow.document.body.scrollHeight;
       }
      if ((_sh != undefined) && (_sh != '') && (_sh > 0))
           iframeElement.style.height =  _sh + 7 + 'px';
   }
 }
 
 function _resizePortletIframeWidth(iframeId)
 {
   var iframeElement = parent.document.getElementById(iframeId);
   var iframeWindow  = iframeElement.contentWindow;
 
   if (iframeWindow.document.width)
   {
       iframeElement.style.width = iframeWindow.document.documentElement.scrollWidth +  'px';
   }
   else if (document.all)
   {
      var _sw;
      if (iframeWindow.document.compatMode &&
           iframeWindow.document.compatMode != 'BackCompat')
       {
         _sw = iframeWindow.document.documentElement.scrollWidth;
       }
       else
       {
         _sw = iframeWindow.document.body.scrollWidth;
       }
       if ((_sw != undefined) && (_sw != '') && (_sw > 0))
           iframeElement.style.width = _sw  + 7 + 'px';
   }
 }
 function _resetForms(portletWindow,portletDocument)
 {
   for (var f = 0; f < portletDocument.forms.length; f++)
   {
     portletDocument.forms[f].submit = portletWindow.adfpp_originalSubmit[f];  
   }  
 }
