//Work area functions
var nodeid;
var fullTarget;
var relativeFlag;
var postBody = null;



function onNavigate(eventObj)
{
  EPCM.getSAPTop().postBody = null;
  relativeFlag = "false";
  postBody = eventObj.dataObject.postBody;
  if  ((eventObj.dataObject.mode == 0) || typeof (eventObj.dataObject.Type) ==  "string")
  {
  	// before each in place navigate, clear all the help ids from the help center repository
  	if (typeof (EPCM.getSAPTop().LSAPI) !==  'undefined'  && EPCM.getSAPTop().LSAPI !== null)
	{
		EPCM.getSAPTop().LSAPI.getHelpCenterPlugin()._private.clearHelpCenter();
	}
	
    var params="";
    target = eventObj.dataObject.target;

    qm = target.indexOf("?");
    if (qm == -1)
    {
      nodeid = target;
    }
    else
    {
      	nodeid = target.substring(0,qm);
      	params = target.substr(qm+1);
    }

    EPCM.raiseEvent("urn:com.sapportals:navigation", "UpdateTLN", nodeid);
    navigateShowInPlace(params , eventObj.dataObject.postBody);
    try{
      EPCM.getSAPTop().navPanelStatus = "exp";
    }
    catch(e){
    }
  }
	else
	{
	    var contentAreaURL = frameworkSupport.contentAreaURL;
	    var portalUrl =      frameworkSupport.portalURL;
	    var navContext = eventObj.dataObject.context;
	    var windowId = eventObj.dataObject.windowId;
	    fullTarget = eventObj.dataObject.target;
	   
	   //If in personalize mode, and doing navigation, make sure the portal url is set to the 
	   //url of the personalize portal node, and win features of personalize 
	   if(frameworkSupport.frameworkPhase == "PERSONPORTAL")
       {
	       eventObj.dataObject.winfeatures = "toolbar=no,menubar=no,resizable=yes";
	       portalUrl = document.URLUnencoded;
	       //remove all parameters
	       i = portalUrl.indexOf('?');
	       if (i>0){
		       portalUrl = portalUrl.substring(0,i);
		   }
	       //portalUrl = contentAreaURL.substring(0,contentAreaURL.indexOf('personalize_portal')+18);
	      
       }
	    
	    if ((fullTarget.indexOf("/irj") != 0) && (fullTarget.indexOf("http") != 0))
		{
			target = eventObj.dataObject.target;
			qm = target.indexOf("?");
			if (qm == -1)
			{
				nodeid = target;
				if (target.indexOf("&") == -1)
				{
    			params = "NavigationTarget=" + encodeURIComponent(nodeid); 
    		}
    		else
    		{
    			params = "NavigationTarget=" + encodeURIComponent(target.substring(0,target.indexOf("&"))) + target.substr(target.indexOf("&"));  
    		}	
			}
			else
			{
				nodeid = target.substring(0,qm);
				params = "NavigationTarget=" + encodeURIComponent(nodeid) + "&" + target.substr(qm+1);
			}
			if (navContext != undefined && navContext != null && navContext !='')
				params += "&NavigationContext=" + encodeURIComponent(navContext);
			params=params+"&CurrentWindowId="+window.name;
			if (windowId != undefined && windowId != null)
				params += "&windowId=" + escape(windowId);
			if(eventObj.dataObject.mode != undefined && eventObj.dataObject.mode != null)
			{
				 params += "&NavMode=" + eventObj.dataObject.mode;
			}
			if(eventObj.dataObject.targetTitle != undefined && eventObj.dataObject.targetTitle != null && eventObj.dataObject.targetTitle != "")
		        {
				//This parameter is already encoded using the function encodeURI in js13_epcf.js inside EPCM.doNavigate 
		  		params += "&TarTitle=" + eventObj.dataObject.targetTitle;
		        }
			if (frameworkSupport.usedConnectors != '')
			{
					params += "&usedConnectors=" + frameworkSupport.usedConnector;
			}
	    		indexOfOBNPrefix = nodeid.indexOf("OBN");
		    	// Check if OBN appears at the beginning of the nodeid - if it is an OBN URL
		    	if (indexOfOBNPrefix == 0)
			    {
			    	indexOfOBNDynamicParameter = params.indexOf("DynamicParameter");
				// If there is no DynamicParameter in the parameters String then it should be added
				// for the purpose of activating ParametersMapping feature by AI (Application Integration)
				if ( (indexOfOBNDynamicParameter == -1)&&(!postBodyContainsParameter(eventObj.dataObject.postBody, "DynamicParameter")) )
			    	{
			      		params += "&DynamicParameter";
			    	}      
   			 }	
			if(eventObj.dataObject.mode == 1)
				fullTarget = contentAreaURL + "?" + params;
			else
				fullTarget = portalUrl + "?" + params;
		}
		
		if (eventObj.dataObject.winfeatures != "")
		{
			winfeatures = eventObj.dataObject.winfeatures + ",";
		}
		else
		{
			winfeatures = "";
		}
		
		//The next line was inserted due to internal message 0120061532 0002320788 2008:
		//When in work protect mode, and trying to navigate in the TLN to somewhere else, a new window is opened
		//and we need to keep the active first level of the TLN as it was before.
		//Only in case the new window was opened a result of the workprotect mode
		if (eventObj.dataObject.open_new_from_workprotect)
		{
			if ((typeof(gLevelOneOldActiveID) !== "undefined") && gLevelOneOldActiveID != null) {
				gLevelOneActiveID = gLevelOneOldActiveID;			
			}
		}
    	navigationToExternalWin(winfeatures, eventObj);
	}
}

// Relative Navigation functions
// Implementating the relative navigation. resolved in server, therefore no TLN update here.
function onRelativeNavigate(eventObj)
{
	var params="";
	relativeFlag = "true";

	EPCM.getSAPTop().postBody = null;
	postBody = eventObj.dataObject.postBody;
		
	nodeid = eventObj.dataObject.basenodename;
    if(eventObj.dataObject.basenodename != undefined && eventObj.dataObject.basenodename != null)
    {
    	// if IE, the RelativeNavBase will be sent in post by submitting form, not added to regular params
    }
	else
    {
       	// if no relative base supplied, relative nav is impossible
       	return false;
    }
       
    if(eventObj.dataObject.levelsup != undefined && eventObj.dataObject.levelsup != null)
    {
    	params += "&RelativeLevelsup=" + escape(eventObj.dataObject.levelsup)
    }
        
    if(eventObj.dataObject.pathnameslist != undefined && eventObj.dataObject.pathnameslist != null)
    {
    	params += "&RelativePathlist=" + escape(eventObj.dataObject.pathnameslist);
    }

    if(eventObj.dataObject.history != undefined && eventObj.dataObject.history != null && eventObj.dataObject.history != "")
    {
  		params += "&HistoryMode=" + escape(eventObj.dataObject.history)
 		
    }
    
    if(eventObj.dataObject.context != undefined && eventObj.dataObject.context != null && eventObj.dataObject.context != "")
    {
    	params += "&NavigationContext=" + escape(eventObj.dataObject.context);
    }
    
    if(eventObj.dataObject.targetTitle != undefined && eventObj.dataObject.targetTitle != null && eventObj.dataObject.targetTitle != "")
    {
		//This parameter is already encoded using the function encodeURI in js13_epcf.js inside EPCM.doRelativeNavigate 
  		params += "&TarTitle=" + eventObj.dataObject.targetTitle;
    }
    params=params+"&CurrentWindowId="+window.name;

    if(eventObj.dataObject.windowId != undefined && eventObj.dataObject.windowId != null)
    {
  		params += "&windowId=" + escape(eventObj.dataObject.windowId)
    }
    
    if(eventObj.dataObject.addParams != undefined && eventObj.dataObject.addParams != null)
    {
         params += "&" + eventObj.dataObject.addParams;
    }
    //Adding the mode as part of the request parameters!
    if(eventObj.dataObject.mode != undefined && eventObj.dataObject.mode != null)
	{
		 params += "&NavMode=" + eventObj.dataObject.mode;
	}	    
		
	if (eventObj.dataObject.winfeatures != "")
	{
		winfeatures = eventObj.dataObject.winfeatures + ",";
	}
	else
	{
		winfeatures = "";
	}		

	if (params.charAt(0) == "&")
		params = params.substr(1);
		
	var contentAreaURL = frameworkSupport.contentAreaURL;
	var portalUrl =      frameworkSupport.portalURL;
	
    
    if(typeof(eventObj.dataObject.mode) == "undefined" || eventObj.dataObject.mode <= 1)
    	fullTarget = contentAreaURL + "?" + params;
    else
    	fullTarget = portalUrl + "?" + params;
	
    if (eventObj.dataObject.mode == 0) {
	   	navigateShowInPlace(params, postBody);
	   	relativeFlag = "false";
    } else {
	    navigationToExternalWin(winfeatures, eventObj);
	}
    
}




function navigateShowInPlace(requestParams , postBody)
{
	
       frm = document.getElementById("frmChangeContent");
       
       
       if(frameworkSupport.frameworkPhase == "PERSONPORTAL")
       {
       		//remove the windowId parameter for new window
		
			requestParams = requestParams.replace(/\?windowId=[^&\n]*&/ , "?");//windowId is the first parameter but not last.
			requestParams = requestParams.replace(/(\?windowId=[^&\n]*)|(&?windowId=[^&\n]*)/ , "");//window is first and last, 
																					  // last or in the middle 
       } 
       var innerPage = frameworkSupport.innerPage;
       var frameURL  = frameworkSupport.innerPageFrameURL;
       var frameWinObj = pageSupport.getIvuFrameObj(innerPage);		

	   var isHeaderLess=false;
	   var isHeaderLessEmbedded=false;
	   var innerPageIndex = 0;
	   try
	   {	
			isHeaderLessEmbedded=frameURL.indexOf("com.sap.portal.embedded_headerless_frameworkpage")>0
			isInnerPageEmbedded=pageSupport._getIViewBank(pageSupport._getIvuPageId(innerPage)).getIsolation()==pageSupport.EMBEDDED						
			innerPageIndex = frameURL.indexOf("!2fcom.sap.portal.innerpage");      		
	    }
		catch(e) {}

       if(frameworkSupport.frameworkPhase == "framework" && frameWinObj != null)
       {
			frm.target = frameWinObj.name;
       		frm.action = frameURL + "?" + requestParams;
       }
       else if(frameworkSupport.frameworkPhase == "framework" && isHeaderLessEmbedded &&  isInnerPageEmbedded && innerPageIndex>0)
       {
			frm.target = "_self";
			frameURL=frameURL.substr(0,innerPageIndex);
       		frm.action = frameURL + "?" + requestParams;
       }
       else if(frameworkSupport.quickLink != undefined)
       {
       		frm.target + "_self";
       		var locationStr = frameworkSupport.portalURL;
       		frm.action = locationStr + "?standAlone=true&" + requestParams;
       }
       else
       {
       		frm.target + "_self";
       		var locationStr  = document.location.href;
      		var index = locationStr.indexOf("?");
      		if (index > 0)
        		locationStr = locationStr.substr(0, index);
       		frm.action = locationStr + "?standAlone=true&" + requestParams;
       }
       
       frm.NavigationTarget.value = nodeid;
       if (relativeFlag == "true")
       	   frm.RelativeNavBase.value = nodeid;
       else
       	   frm.RelativeNavBase.value = "";	

	   var oldHTML = frm.innerHTML;
       if(postBody)
       {
       		
       		var innerHTML = frm.innerHTML;
       		var str = "<input type=hidden name='UsePost' id='UsePost' value='true'></input>\n";
			
			innerHTML += str;
       		for(var i = 0 ; i < postBody.length ; i++)
       		{
       			var paramName = ESCAPE_TO_HTML( postBody[i].name );
       			var paramValue = ESCAPE_TO_HTML( postBody[i].value );
       			
       			var str = "<input type=hidden name='"+paramName+"' id='"+paramName+"' value='"+paramValue+"'></input>\n";
       			innerHTML += str;
       		}
       		frm.innerHTML = innerHTML;
       		EPCM.getSAPTop().postBody = postBody;
       }
	
	var sessionTermination = "";
	try {
	   sessionTermination = getSessionTerminationKeys();
	   if(sessionTermination != "")
	   {
		   frm.innerHTML = frm.innerHTML + sessionTermination;
	   }
	}
	catch(e) {}
		//add the UsedConnectors list
		if (frameworkSupport.usedConnectors != ''){
			var str = "<input type=hidden name='UsedConnectors' id='UsedConnectors' value='"+frameworkSupport.usedConnectors+"'></input>\n";
	   		frm.innerHTML += str;
		}
       frm.submit();
       
	   if(postBody || sessionTermination!= "")
	   {
	   		frm.innerHTML = oldHTML;
	   }    
   
}

//Set the focus back in the new window
var newWin = null;

function enhanceWinFeatures(winFeatures) {
    var widthExpr = /width\s*=\s*(\d+)%\s*/;
    var heightExpr = /height\s*=\s*(\d+)%\s*/;

    var widthMatches = winFeatures.match(widthExpr);
    var heightMatches = winFeatures.match(heightExpr);

    if (widthMatches) {
        var realWidth = screen.width * parseInt(widthMatches[1]) / 100;
    
        winFeatures = winFeatures.replace(widthMatches[0], "width=" + realWidth + "px");
    }

    if (heightMatches) {
        var realHeight = screen.height * parseInt(heightMatches[1]) / 100;
    
        winFeatures = winFeatures.replace(heightMatches[0], "height=" + realHeight + "px");
    }

    return winFeatures;
}



function navigationToExternalWin(windowFeatures, eventObj)
{
  winname = eventObj.dataObject.winname;
  if (winname == "DefaultExternal" || winname == "") { 
	var curDate = new Date();
	winname = "WID"+ winname+curDate.getTime();
  }
  // since the window name must begin with a letter ([A-Za-z]) 
  // and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), and colons (":") we encode it
  // it will not change leagal names
  winname = encodeURIComponent(winname).replace(/%/g,"");  
  winname = winname.replace(".","");
  var path = frameworkSupport.childHtmlPath;

  try 
  {
	windowFeatures=enhanceWinFeatures(windowFeatures);
  } 
  catch(e) 
  {
  }

  newwin = window.open(path,winname, windowFeatures);
  //Set the focus back in the new window
  window.setTimeout("newwin.focus()",1500);
    
}

// This function is called from the child.html file.
function fillFrmDetails(frm) 
{
	frm.NavigationTarget.value = nodeid;
	if (relativeFlag == "true")
	{
		frm.RelativeNavBase.value = nodeid;
		fullTarget += "&RelativeNavBase=" + nodeid;
	}
	
	
	//remove the windowId parameter for new window
		
	fullTarget = fullTarget.replace(/\?windowId=[^&\n]*&/ , "?");//windowId is the first parameter but not last.
	fullTarget = fullTarget.replace(/(\?windowId=[^&\n]*)|(&?windowId=[^&\n]*)/ , "");//window is first and last, 
																					  // last or in the middle 
	//fullTarget = fullTarget.replace(/(\?|&)windowId=[^&\n]*$/ , "");
	//fullTarget = fullTarget.replace(/(\?|&)windowId=[^&\n]*&/ , RegExp.$1);
	frm.action = fullTarget;
	if(postBody)
   {
   		var innerHTML = frm.innerHTML;
   		var str = "<input type=hidden name='UsePost' id='UsePost' value='true'></input>\n";
		
		innerHTML += str;
   		for(var i = 0 ; i < postBody.length ; i++)
   		{
   			var paramName = ESCAPE_TO_HTML( postBody[i].name );
   			var paramValue = ESCAPE_TO_HTML( postBody[i].value );
   			
   			var str = "<input type=hidden name='"+paramName+"' id='"+paramName+"' value='"+paramValue+"'></input>\n";
   			innerHTML += str;
   		}
   		frm.innerHTML = innerHTML;
   		EPCM.getSAPTop().postBody = postBody;
   }
   relativeFlag = "false"; 
}


EPCM.subscribeEvent("urn:com.sapportals:navigation", "Navigate", onNavigate);
EPCM.subscribeEvent("urn:com.sapportals:navigation", "RelativeNavigate", onRelativeNavigate);


// Object Based Navigation functions
function onObjBasedNavigate(eventObj)
{
	var obnForm = document.getElementById("obnNavForm");
	obnForm.operation.value = "";
	obnForm.action = frameworkSupport.ObjBasedNavigationURL;
	obnForm.systemAlias.value = eventObj.dataObject.systemAlias;
	obnForm.businessObjName.value = eventObj.dataObject.businessObjName;
	obnForm.objValue.value = eventObj.dataObject.objValue;

	if (typeof(eventObj.dataObject.operation) != "undefined" &&  eventObj.dataObject.operation != null)
	{
  		obnForm.operation.value = eventObj.dataObject.operation;
  	}
  	
  	if (typeof(eventObj.dataObject.resolvingMode) != "undefined" &&  eventObj.dataObject.resolvingMode != null)
	{
  		obnForm.resolvingMode.value = eventObj.dataObject.resolvingMode;
  	} 
  	else
  	{
	  	obnForm.resolvingMode.value = "Default";
	  	
	  	if (typeof(eventObj.dataObject.postBody) != "undefined" &&
	  		eventObj.dataObject.postBody != null &&
	  		typeof(eventObj.dataObject.postBody) == "string")
		{
	  		obnForm.resolvingMode.value = eventObj.dataObject.postBody;
	  	}
  	}
  	
  	//source for GP and SourceRole mode
	try {
	  	obnForm.source.value=EPCM.getSAPTop().gHistoryFrameworkObj.GetActiveTrackingEntryValue().URL;
	} catch(e) {
		obnForm.source.value="";
	}
  	
  	var obnPostBody = eventObj.dataObject.postBody;
  	
  	if(obnPostBody != null && typeof(obnPostBody) == "object")
  	{
  		obnForm.usePost.value = "true";
  		var innerHTML = obnForm.innerHTML;
  		var oldInnerHTML = innerHTML;
  		for(var i = 0 ; i < obnPostBody.length ; i++)
   		{
   			var paramName = obnPostBody[i].name;
   			var paramValue = obnPostBody[i].value;
   			
   			var str = "<input type=hidden name='"+paramName+"' id='"+paramName+"' value='"+paramValue+"'></input>\n";
   			innerHTML += str;
   		}
   		obnForm.innerHTML = innerHTML;
  		
  	}
  	else
  	{
  		obnForm.usePost.value = "false";
  	}
  	EPCM.getSAPTop().obnTriggered='true';
    obnForm.submit(); 
    if(obnPostBody != null && typeof(obnPostBody) == "object")
    {
    	obnForm.innerHTML = oldInnerHTML;
    }  	
}

// Checks if postBody contains the given parameter
function postBodyContainsParameter(postBody,paramName)
{
 	if(postBody != null && typeof(postBody) == "object")
  	{
  		for(var i = 0 ; i < postBody.length ; i++)
   		{
   			var tempParamName = postBody[i].name;
   			if(tempParamName == paramName)
   			{
   				return true;
   			}
   		}
   	}
   	return false;
  }
  
EPCM.subscribeEvent("urn:com.sapportals:navigation", "ObjBasedNavigate", onObjBasedNavigate);