/**
 * Commands and utilities used by the eAISCommands frame
 */
 
 /** Enable the debugging messages */
 var DEBUG = false;
 
 /**********************************/
 /**     PDF-related commands     **/
 var PDF_LOCATION = "/pdf/";
 /** HTML is located in /html/eAIP or /html/eAIC or /html/eSUP*/
 var HTML_LOCATION = /\/html\/\D{4}\//;
 
  //pattern for pdf pages are
  var PDF_LANG_PATTERN=/_([a-z]{2})\.pdf/;
  
 function getAsPdf(href) {
 
 //if a pdf is already open and user selected PDF page again, don't do anything
  var splitNamePdf = href.split(PDF_LANG_PATTERN); 
  if (splitNamePdf.length > 1) // IE splits in 2
  { 
 	return href;
  }
 	    
/**  Given a HREF, this function returns a string with the the PAMS compliant
PDF name of the file */
var HTML_string = ".html" ;
// This value is not used - we just want to know the length of what to chop off the end of the file name.
var Amtputate = "-CC" ;
/*
// NOTE: This function was edited by SPB @ M-AIS on 20070927
// When PDF is generated from FrameMaker, using the "Print" function, the
"Adobe PDF" must be the the default printer. 
// If "Generate Acrobat Data" is switched on, and the Acrobat "PDF Setup"
dialog is set to generate Bookmarks, based
// on Paragraph tags, Acrobat Distiller will create the PDF file, with named
links - BUT the links are prefixed with "E.", typical!
*/
        // find out where to take the file name part
        var startlocn = href.lastIndexOf("/") + 1;
        // get the name of the HTML file without the path, nor the the country specifier and hyphen, e.g -HU
        var step1 = href.substring(startlocn, href.lastIndexOf(HTML_string) - Amtputate.length);
		
		//find if in the name of the file eAIC substring exists, if yes, then we are processing the path to AIC file 
		//- in pdf the name is slightly different - 'eAIC' needs to be changed to 'Circ'
		var eAICstring = step1.indexOf("eAIC");
		if(eAICstring!=-1)
		{
			step1 = getNameOfCircular(step1);
		}
		
		var eSUPstring = step1.indexOf("eSUP");
		if(eSUPstring!=-1)
		{
			step1 = step1.replace("eSUP", "Sup");
		}
	
        // get the path part of the href
        var mypath = href.substring(0, startlocn);
        // to get the anchor part of the href
        var anchor = href.substr(href.lastIndexOf(HTML_string) + HTML_string.length + 1);
        // translate "-" & "." into "_", and glue them together, with the anchor
        var step2 = mypath + step1.replace(/[-.]/g, "_") + ".pdf" ;
        if (anchor.length > 0 ) 
        {   
            //if amdt=show bit is present, remove it
            var indexOfShowAmdt = anchor.indexOf("amdt=show#");
	    	if(indexOfShowAmdt!=-1)
	    	{
	    	    anchor = anchor.replace("amdt=show#","");
	    	}
            step2 += "#E." + anchor ;
        }
        // return the correct name of the PAMS PDf file, based on the corresponding directory?
        return step2.replace(HTML_LOCATION, PDF_LOCATION);
 }
 
 //name of pdf file of AIC is slightly different than of the any other part file,
 //therefore path to it needs some more processing
  function getNameOfCircular(pName) {
 	 pName = pName.replace("eAIC", "Circ");
 	 var index = pName.indexOf("Circ-")+5;
 	 var beginning = pName.substr(0,index); 	 
 	 var year = pName.substr(index, 4);
 	 index = index + 5;
 	 var number = pName.substr(index, 3);
 	 index = index + 4;
 	 var seriesLetter = pName.substr(index, 1); 
 	 if(seriesLetter == "-" )	
 	 {
 	    seriesLetter = "";
 	    index++;
 	 }else
 	 {
 	    index = index + 2;
 	 }	 
 	    
 	 var ending = pName.substr(index);
 	 
 	 var AICname = beginning + year + '-' + seriesLetter + '-' + number + '-' + ending;
 	 return AICname;
 }
 
 /**
  * Return the URL displayed in the content frame, but as target the associated PDF file
  */
 function getContentAsPdf() {
 	var frame = window.top.frames["eAISContent"];
 	var loc = frame.location.href;
 	return getAsPdf(loc);
 }
 
 /**
  * Change the href property of an element with the URL of the PDF with the content
  * the HTML currently viewed
  */
 function changeHrefToPdf(pElement) {
 	pElement.href = getContentAsPdf();
 }
 
 /**********************************/
 /**  Language switching commands **/
 
 /** String used in url rewriting to specify the target */
 var TARGET = "target";
 var MENUSTATE = "menuState";
 
 /** String used to separate entries */
 var SEPARATOR = ",";
 /** String used in url rewriting to specify the elements which are opened in the navigation menu */
 var IDREF = "idRef";
 
 
 /**
  * Append to the href property of element the modified target with changed language
  *
  * @param element And element that has an href property
  */
 function appendTarget(pElement) {

 	var hyperlink = new String(pElement.href);
 	var lang = getLanguage(hyperlink);
 	if (DEBUG) alert("lang is " + lang);
 	
 	// Get the target
 	var target = window.top.frames["eAISContent"].location.href;
 	if (DEBUG) alert("Target is " + target);
 	
 	// Replace the language
 	var newTarget = changeLanguage(target, lang);
 	if (DEBUG) alert("newTarget is " + newTarget);
 	
 	// Append to the URL the link
 	var result = hyperlink + "?" + TARGET + "=" + escape(newTarget);
 	//if (DEBUG) alert("result is " + result);
 	
 	// Append the menu state
 	//var menuState = getMenuState(lang);
 	//var result2 = result + "&" + MENUSTATE + "=" + menuState;
 	if (DEBUG) alert("result2 is " + result);
 	
 	//element.href = result2;
 	pElement.href = result;
 }
 
 /**
  * Open the target specified on the location of the top frame in the eAISContent frame
  */
 function openTarget() {
 	// Parse the URL
 	var loc = window.top.location.href; 
 	if (DEBUG) alert("Location: " + unescape(loc));
 	var target = extractTarget(loc);
 	if (DEBUG) alert("Opening target: " + unescape(target));
 	if (target) {
	 	// Set the eAISContent frame location to that value
	 	window.top.frames["eAISContent"].location.href = unescape(target);
 	}
 	
 	var menuState = extractMenuState(loc);
 	if (menuState) {
 		redirectMenu(menuState);
 	}
 }
 
 /**
  * Get the menu page that is opened, and the ids of the elements that are opened
  *
  * @param language The language that will be substituted in the locations
  * @return state as a string, with the language changed
  * @see #restoreMenuState(String)
  */
 function getMenuState(language) {
 	var targetWindow = window.top.frames["eAISNavigationBase"].frames["eAISNavigation"];
 	var loc = targetWindow.location.href;
 	if (DEBUG) alert("Location of eAISNavigation is" + loc);
 	
 	// Change the language of the location
 	var newLoc = changeLanguage(loc, language);
 	if (DEBUG) alert("New location " + newLoc);
 	
 	var result = new String(escape(newLoc));
 	
 	// Get the a elements that contain an id ending with plus
 	var links = targetWindow.document.getElementsByTagName("A");
 	// The regexp matches IDplus, where ID is the id that we want to expand
 	var PLUS = /(.*)plus/;
 	
 	for (i=0; i < links.length; i++) {
 		// See if it has an id that finishes with plus
 		var id = new String(links[i].id);
 		//if (DEBUG) alert("Trying finding element in: " + id );
 		var match = id.match(PLUS);
 		
 		if (match && links[i].innerHTML == "-") { // A - denotes an opened section
 			var elementId = match[1]; //
 			if (DEBUG) alert("Element matches: " + elementId );
 			// Append the element name to the string
 			result = result + SEPARATOR + elementId;
 		}
 		
 	}
 	return result;
 }
 
 /**
  * 
  */
 function redirectMenu(loc) { 
 
 	// redirect the menu to the right navigation menu
 	// passing as parameters the ids of the nodes to be expanded
 	var targetWindow = window.top.frames["eAISNavigationBase"].frames["eAISNavigation"];
 	
 	// Location of the first separator
 	firstSep = loc.indexOf(SEPARATOR);
 	
 	if (firstSep > 0) {
 	 	
	 	// The target is the substring from 0 to firstSep
	 	var redirect = loc.substr(0, firstSep);
	 	if (DEBUG) alert("Redirect menu location is: " + redirect); 
	 	
	 	// Then we append the rest as a parameter called id
	 	// +1 is because we skip the separator
	 	var completeRedirect = unescape(redirect) + "?" + IDREF + "=" + loc.substr(firstSep + 1, loc.length);
	 	if (DEBUG) alert("Complete redirect menu location is: " + completeRedirect);
	 	
	 	targetWindow.location.href = completeRedirect;
 	} else {
 		// There are no other arguments after the target
 		targetWindow.location.href = unescape(loc);
 	}
 	// Then we run restore menus state on that frame
 	//restoreMenuState();
 }
 
 /**
  * Restore the state of the menu
  */
 function restoreMenuState() {
 	var loc = window.location.href;
 	
 	// Extract the stuff after IDREF
 	var afterIDRef = loc.split(IDREF + "=");
 	if (afterIDRef.length < 2) return;
 	
 	// then expand these ids if they exist
 	expandIds(afterIDRef[afterIDRef.length - 1]);
 }
 
 /**
  * Restore the menu state from a string by expanding the ids in a list
  *
  * @param state is a SEPARATOR delimited String containing a list of ids to be expanded
  */
 function expandIds(state) {
 	
 	var splitted = state.split(SEPARATOR);
 	
 	for (i=0; i<splitted.length; i++) {
 		var id = splitted[i];
 		if (DEBUG) alert("Showing id: " + id);
 		showHide(id, SHOW);
 	}
 }
 
 /**
  * Extract the target from a string
  *
  * @return String that is after TARGET =
  */
 function extractTarget(string) {
 	var temp = new String(string);
 	if (DEBUG) alert("string: " + unescape(string));
 	//var split = temp.split(TARGET + "=");
 	var splitAtEquals = temp.split("=");
 	if (DEBUG) alert("split: " + unescape(splitAtEquals));
 	if (splitAtEquals.length < 2) return;
 	var splitAtAmp = splitAtEquals[splitAtEquals.length - 1].split("&");
 	return splitAtAmp[0];
 }
 
  /**
  * Extract the menu state from a string
  *
  * @return String that is after MENUSTATE =
  */
 function extractMenuState(string) {
 	var temp = new String(string);
 	var splitMenuState = temp.split(MENUSTATE + "=");
 	if (splitMenuState.length < 2) return;
 	return splitMenuState[splitMenuState.length - 1];
 }
 
 
 /**********************************/
 /**          Utilities           **/
 
 /** Languages are encoded as -xx-XX. */
 var LANG_PATTERN=/-([a-z]{2}-[A-Z]{2})\./;
 
 //pattern for pdf pages are
  //var PDF_LANG_PATTERN=/_([a-z]{2})\.pdf/;
 
 /**
  * Change the language pattern inside an URL.
  * 
  * @param target: String holding the URL which will be 
  *       parsed and the language replaced by language
  * @param language: String holding the language code
  *		  in the form xx-XX, e.g. en-GB
  * @return String target with the language replaced
  */
 function changeLanguage(target, language) {
 	
 	var splitName = target.split(LANG_PATTERN);
 	// If the size is not 2 we have a problem
 	if (DEBUG) for (i=0; i <splitName.length; i++)
 		alert("Split values at " + i + " is " + splitName[i]);
 	if (splitName.length == 3) { // Mozilla splits in 3
 		var result = splitName[0] + "-" + language + "." + splitName[2];
 		return result;
 	}
 	if (splitName.length == 2) { // IE splits in 2
 		var result = splitName[0] + "-" + language + "." + splitName[1];
 		return result;
 	}
 	
 	//check if it's not pdf
 	if(splitName.length == 1)
 	{
 	    var languageCode = language.substr(0,2);
 	    var splitNamePdf = target.split(PDF_LANG_PATTERN); 	    

 	    if (splitNamePdf.length == 3) { // Mozilla splits in 3
 		    var result = splitNamePdf[0] + "_" + languageCode + ".pdf" + splitNamePdf[2];
 		    return result;
 	    }
 	    if (splitNamePdf.length == 2) { // IE splits in 2
 		    var result = splitNamePdf[0] + "_" + languageCode + ".pdf" + splitNamePdf[1];
 		    return result;
 	    }
 	}
 	
 	alert("Cannot change language on name " + target);
 	return "";
 }
 
 /**
  * Extract the language from a string
  * @return the language in xx-XX pattern, or null if there is no language match in the name
  */
 function getLanguage(value) {
 	var matches = value.match(LANG_PATTERN);
 	if (matches)
 		return matches[1]; // 0, is the complete string
 	return; 
 }

 
function formatLinks(pElement) {

var path = pElement.location.href;
var language = path.split(LANG_PATTERN);

var result ='';
 	if (language.length == 3) { // Mozilla splits in 3
 		result = language[1].substr(0,2);
 	}
 	if (language.length == 2) { // IE splits in 2
		var firstsplit = language[0];
		var languageCodes = path.substr(firstsplit.length+1);
 		result = languageCodes.substr(0,2);
 	}

	if(result != '')
	{
		var foundElement = document.getElementById(result);
		if(foundElement)
		{
			foundElement.style.color="black";
		}
	}
return false;
}

function historyDropdownSelection(menu)
{
	ref=menu.historyDropdown.options[menu.historyDropdown.selectedIndex].value;
	splitc=ref.lastIndexOf("*");
	target="";
	var isSelectionCoverPage = ref.indexOf("-cover-") != -1;
	if (splitc!=-1)
	{
		loc=ref.substring(0,splitc);
		target=ref.substring(splitc+1,1000);
	}
	else 
	{
		loc=ref; target="_self";
	};
	if (ref != "" && isSelectionCoverPage)
	{
		parent.frames["eAISContent"].location=loc;
	}
	else if (ref != "")
	{
		parent.location=loc;
	}
}