// =======================================================================
// === RightFS Functions
// === Copyright  Dassault Systemes / Pierre SMEYERS (Jan 30 2006)
// =======================================================================
// === This Javascript Library contains functions used by the RightFS
// === frameset of the doc portal.
// === This frameset contains the breadcrumb frame and the main doc frame.
// === It is in charge of:
// ===  - restoring the required document passed with argument "show",
// ===  - handling onload event from the main doc frame, and triggering
// ===    the breadcrumb and the synchronize icon update.
// =======================================================================
/**
 * Dynamically builds the right frameset.
 * Looks for a document relative url in the parameters, and restores it in the main doc frame.
 * Default starting document is "Home.htm"
 */
  /*
	V2E : 10th Sep 2014 Copyright added in Right Frame
 */
function buildRightFS()
{
//	DebugMessage("creating right FrameSet...");
	// --- read doc url from url arguments
	var docUrl = "Pyp1UserMap/pyp-c-ov.htm";
	var args = extractParams();
	// show arg
	if (args["show"] != null) {
		docUrl = args["show"];
		}

	// sanytize URL 
	if (docUrl.match('[" =:]')) {
		console.log ("INVALID show argument: "+docUrl);
		docUrl = "Pyp1UserMap/pyp-c-ov.htm";
	}
	// V2E : To allow Search string highlighted when passed as parameter
	// http://someLink/English?show=map\file.htm&search=highlight
	if(args["search"] != null)
		docUrl = docUrl + "?search="+args["search"];
	// V2E : IR-225631V6R2014 & IR-2256306R2014 
	// added one more parameter for element ID to directly show the scrolled page
	if(args["ElemID"] != null)
		docUrl = docUrl + args["ElemID"];
	

	
	document.writeln('<frameset id ="BreadCrumbFrameset" rows="20,*,20" framespacing="0" border="0" frameborder="no">');
	document.writeln('<frame name="Breadcrumb" src="DSDocBreadcrumb.htm" scrolling="no" id="BreadCrumbFrame" noresize></frame>');
	// V2E : For IE onreadystatechange event is used as onload is triggered for PDF loading
	//if(navigator.appName.indexOf("Microsoft Internet Explorer") != -1 )
	//	document.writeln('<frame name="mainsm" onreadystatechange = onPageChanged(this.contentWindow); src="'+docUrl+'"></frame>');
	//else
	//	document.writeln('<frame name="mainsm" onload = onPageChanged(this.contentWindow); src="'+docUrl+'"></frame>');
	document.writeln('<frame name="Copyright" src="DSDocCopyRight.htm" scrolling="no" id="CopyRight" noresize></frame>');
	document.writeln('</frameset>');

	var mainsm    = document.createElement("frame");
	mainsm.name   = "mainsm";
	mainsm.src    = docUrl;
	mainsm.onload = function() { onPageChanged(mainsm.contentWindow)}; 
	var frameset  = document.getElementById("BreadCrumbFrameset");
	var copyrightframe  = document.getElementById("CopyRight");
	if (frameset) { frameset.insertBefore(mainsm, copyrightframe); }
}

/**
 * onLoad Event Handler from the main document frame.
 * This function triggers the breadcrumb and TOC update.
 */
function onPageChanged(win)
{
//	DebugMessage("Page Changed On: "+win.nodeName+": "+win.document.location);
	// --- update URL with the show option into the address bar to enable copy/paste and easy bookmarks
	// Contextual help access URL example: file:///N:/PreInt422/wsDoc/win_b64.doc/English/TechWebDoc.htm?show=TechWebMap/TechWeb-c-KB-AboutKnowledgeBase.htm&collapse=true&contextscope=onpremise#c-KBMetricsFollowUp
	// Direct access URL example: file:///N:/PreInt422/wsDoc/win_b64.doc/English/TechWebDoc.htm then select 
	// Retrieve the complete requested url
	var documentUrl = parent.parent.document.URL;                           // Ex: documentUrl = "file:///N:/PreInt422/wsDoc/win_b64.doc/English/TechWebDoc.htm?show=TechWebMap/TechWeb-c-KB-AboutKnowledgeBase.htm&collapse=true&contextscope=onpremise#c-KBMetricsFollowUp"
	var documentUrlAnchorTab = documentUrl.split(/\#/);
	var documentUrlParamsTab = documentUrlAnchorTab[0].split(/\?/);
	var rootUrl = documentUrlParamsTab[0];                                  // Ex: rootUrl = "file:///N:/PreInt422/wsDoc/win_b64.doc/English/TechWebDoc.htm"
	rootUrl = rootUrl.replace(/\\/g, "/");
	// Retrieve the loaded page in right frame, possibly removing the part after the question mark coming from the search
	var pageUrl = win.document.URL;                                         // Ex: pageUrl = "file:///N:/PreInt422/wsDoc/win_b64.doc/English/TechWebMap/TechWeb-c-KB-AboutKnowledgeBase.htm#c-KBMetricsFollowUp"
	var pageUrlAnchorTab = pageUrl.split(/\#/);
	var fileUrl = pageUrlAnchorTab[0].split(/\?/)[0];                       // Ex: fileUrl = "file:///N:/PreInt422/wsDoc/win_b64.doc/English/TechWebMap/TechWeb-c-KB-AboutKnowledgeBase.htm"
	fileUrl = fileUrl.replace(/\\/g, "/");
	// Split the page url to keep only the module and the file
	var fileUrl = fileUrl.split(/\|=|&|\//g);
	var module = fileUrl[fileUrl.length-2];
	var pagePath;
	if (!module || module.startsWith('English') || module.startsWith('French') || module.startsWith('German') || module.startsWith('Spanish') || module.startsWith('Italian') || module.startsWith('Japanese') || module.startsWith('Simplified_Chinese')) {
		pagePath = fileUrl[fileUrl.length-1];                               // for pages directly under <language> folder
	} else {
	    pagePath = module+"/"+fileUrl[fileUrl.length-1];                    // Ex: pagePath = "TechWebMap/TechWeb-c-KB-AboutKnowledgeBase.htm"
	}
	// Build the loaded page url with the show parameter
	var urlToLoad = rootUrl+"?show="+pagePath;
	// Add params (ignore collapse and MyApps* ones)
	if (documentUrlParamsTab.length===2) {
    	var paramTab = documentUrlParamsTab[1].split(/\&/);
		var paramLength = paramTab.length;
		for (i=0; i<paramLength; i++) {
			//if (!paramTab[i].startsWith('show')/* && !paramTab[i].startsWith('MyApps') && !paramTab[i].startsWith('collapse')*/)
			if (!paramTab[i].startsWith('show') && !paramTab[i].startsWith('MyApps') && !paramTab[i].startsWith('collapse'))
				urlToLoad = urlToLoad+"&"+paramTab[i];
	}
	}
	// Add anchor
	if (pageUrlAnchorTab.length===2)
		urlToLoad = urlToLoad+'#'+pageUrlAnchorTab[1];                      // Ex: urlToLoad = "file:///N:/PreInt422/wsDoc/win_b64.doc/English/TechWebDoc.htm?show=TechWebMap/TechWeb-c-KB-AboutKnowledgeBase.htm&collapse=true&contextscope=onpremise#c-KBMetricsFollowUp"
	var urlTitle = win.document.title;
	// Replace the current page in the history by itself and set the URL with the show option in the address bar 
	if (typeof (parent.parent.history.replaceState) != "undefined") {
        //alert("urlToLoad = "+urlToLoad+"\nurlTitle = "+urlTitle);
		var obj = { Title: urlTitle, Url: urlToLoad };
		parent.parent.history.replaceState(obj, urlTitle, urlToLoad);
    	var titleBase = parent.parent.document.title.split(/ - /)[0];
		parent.parent.document.title = titleBase + ' - ' + urlTitle;
	} else {
        //alert("This browser does not implement HTML5");
	}
	
	// --- update breadcrumb
	 try {
		var breadcrumbWin = win.parent.frames["Breadcrumb"];
		if(isWindowLoaded(breadcrumbWin) && breadcrumbWin.updateBreadcrumb)
			breadcrumbWin.updateBreadcrumb(win);
	}catch (e) {
	}	
	
	// --- update TOC
    if (navigator.appName.indexOf("Microsoft Internet Explorer") != -1) {        
		try 
		{
			// V2E : Synchronise TOC only after complete loading of respective document        
			if (win.frames.frameElement.readyState == "complete"){	
			var tocBarWin = win.parent.parent.frames["LeftFS"].frames["TocBar"];	
				if(isWindowLoaded(tocBarWin) && tocBarWin.updateSyncToc)		
					tocBarWin.updateSyncToc(win);
			}     
		}catch (e){     
		}    
	}    
	else {        
		try{	
			var tocBarWin = win.parent.parent.frames["LeftFS"].frames["TocBar"];
			if(isWindowLoaded(tocBarWin) && tocBarWin.updateSyncToc)
				tocBarWin.updateSyncToc(win);
		}catch (e) {
		}
	}
}
