
var HIDE_AMDTS_SS = "Hide Amendments Changes";
var SHOW_AMDTS_SS = "Show Amendments Changes";

/** Show or hide AMDTs as requested */
function setAMDTsTasks() {
    if (showAMDTsRequested()) {
        showAMDTsTasks();
    } else {
        hideAMDTsTasks();
    }
}

/** Inverse the AMDTs visibility */
function toggleAMDTs() {
    if (getActiveStyleSheet() == SHOW_AMDTS_SS) {
        hideAMDTs();
    } else {
        showAMDTs();
    }
}

/** show AMDTs, tick the checkbox and change links in navigation frame */  
function showAMDTs() {
//alert("show amdts");
    // IE 6 bug: first hide then show...
    if (isIE()) {
        setActiveStyleSheet(HIDE_AMDTS_SS);
     }
    setActiveStyleSheet(SHOW_AMDTS_SS);
    showAMDTsTasks();
}

/** hide AMDTs, untick the checkbox and change links in navigation frame */  
function hideAMDTs() {
    setActiveStyleSheet(HIDE_AMDTS_SS);
    hideAMDTsTasks()
}

function showAMDTsTasks() {
    document.getElementById("checkBox").checked = true;
    
    // Get document's base, to compare with other hrefs
    var base = getBase( location.href );
    padHrefs(window, base);
    try {
        var navigationFrame = window.top.frames["eAISNavigationBase"].frames["eAISNavigation"];
        if (navigationFrame) {
            padHrefs(navigationFrame, base);
        }
    } catch (e) {
        // Do nothing, we are not in a frameset
    }
    //moveToAnchor(window.location.href);
}

function hideAMDTsTasks() {
    document.getElementById("checkBox").checked = false;
    
    unpadHrefs(window); // Change in the current window
    try {
        var navigationFrame = window.top.frames["eAISNavigationBase"].frames["eAISNavigation"];
        if (navigationFrame)
        	unpadHrefs(navigationFrame);
    } catch (e) {
        // Do nothing, we are not in a frameset
    }
    moveToAnchor(window.location.href);
}

function setRequestedStyleSheet() {
    if (showAMDTsRequested()) {
        setActiveStyleSheet(SHOW_AMDTS_SS);
    } else {
        setActiveStyleSheet(HIDE_AMDTS_SS);
    }
}

function setActiveStyleSheet(title) {
   var i, links;
   links = document.getElementsByTagName("link");
   for(i=0; i < links.length; i++) {
      if (links[i].getAttribute("rel").indexOf("stylesheet") != -1 && links[i].getAttribute("title")) {
         if (links[i].getAttribute("title") == title) {
            links[i].disabled = false;
         } else {
            links[i].disabled = true;
         }
      }
   }
}

function getActiveStyleSheet() {
   var i, links;
   links = document.getElementsByTagName("link");
   for(i=0; i < links.length; i++) {
      if (links[i].getAttribute("rel").indexOf("stylesheet") != -1 &&
          links[i].getAttribute("title") &&
          !links[i].disabled) {
         return links[i].getAttribute("title");
      }
   }
   return "";
}

function toggleStyleSheet() {
    toggleAMDTs();
}


// ============= Menu highlighting ============
function menu_on(el) {
//  if (alreadyActivated(el)) return;
//  el.style.backgroundColor = '#aaa';
}

function menu_off(el) {
//  if (alreadyActivated(el)) return;
//  el.style.backgroundColor = 'transparent';
}

function alreadyActivated(el) {
  if (el.id.indexOf("menu-amdt-") != -1) {
    var activesheet = getActiveStyleSheet();
    var status = el.id.substr(10); // position of Hide and Show in the id
    return (activesheet.indexOf(status) != -1); // return true if the clicked stylesheet is already activated
  }
}

// ============ Show amendments persistence ==============

/** value appended to links which is checked for to display amdts by default*/
SHOW_AMDT = "amdt=show";

/** 
 * Adds at the end of all internal links SHOW_AMDT 
 * @param win Window which contains the links to be updated
 */
function padHrefs(win, base) {
	var elems = win.document.getElementsByTagName("A");
	for ( i=0; i < elems.length; i++ ) {
		// See if they are relative = contain the base
		if ( elems[i].href.indexOf( base ) != -1 || elems[i].target == "_self") {
			if (elems[i].search.search(SHOW_AMDT) != -1) //Skip if it already exists
				continue;
			// Remember the hash, because we are redoing the url by hand
			if (elems[i].search == "") { 
				elems[i].search = "?" + SHOW_AMDT;
			} else {
				elems[i].search = elems[i].search +"&"+ SHOW_AMDT;
			}
			remakeUrl(elems[i]); // Fix IE bug
		}
	}
}

/**
 * Same as above but without the base checking
 * Warning: this will pad links that point externally. Make
 * sure there are no such links in the window from which you
 * call this function
 */
function padHrefsNoBase(win) {
	var elems = win.document.getElementsByTagName("A");
	for ( i=0; i < elems.length; i++ ) {
		if (elems[i].search.search(SHOW_AMDT) != -1) //Skip if it already exists
					continue;
		if (elems[i].search == "") { 
			elems[i].search = "?" + SHOW_AMDT;
		} else {
			elems[i].search = elems[i].search +"&"+ SHOW_AMDT;
		}
		remakeUrl(elems[i]); // Fix IE bug
	}
}

/** 
 * Remove at the end of all internal links SHOW_AMDT, if it exists 
 * @param win Window in which to do the unpadding
 */

function unpadHrefs(win) {

    // go through all hrefs and see if they are padded.
    var elems = win.document.getElementsByTagName("A");

    for ( i=0; i < elems.length; i++ ) 
    {
		if ( elems[i] == null ) 
			return;

        var attr = getAttributes( elems[i].search );
        //var currentTextOfAlink = elems[i].innerText;
        var result = new String();      

        for ( j=0; j<attr.length; j++)
		{
            if (attr[j] != SHOW_AMDT) 
                result = addAttribute( result, attr[j] );
        }

        // IE Bug. IE sometimes forgets the hash when we update the search
        var temp = elems[i].hash.split('#')[1];
        elems[i].search = result;

        if (temp != null)
			elems[i].hash = temp;

        remakeUrl(elems[i]); // Fix IE bug
        //elems[i].innerText = currentTextOfAlink;
    }
}

/** Checks if we should show or not the amendments 
*  return Boolean True means we should show the amendments
*/
function showAMDTsRequested() {
	attr = getAttributes( location.search );
	for ( i=0; i<attr.length; i++) {
		if (attr[i] == SHOW_AMDT){
			return true;
		}
	}
	return false;
}

/**
 * Switch on show amendments on all links in the calling window, if requested by the URL.
 */
function toggleAmendment() {
	if (showAMDTsRequested()) {
		// Base is the the URL of the content window
		//var base = getBase(window.top.frames["eAISContent"].document.location.href);
		//padHrefs(window, base);
		padHrefsNoBase(window);
	}
}


/** Get the attributes in an array from a string starting with a ?*/
function getAttributes( fromHere ) {
	attributes = fromHere.split("?")[1]; //Get the string after the ?
	if ( attributes == null ) {
		return "";
	} else return attributes.split("&"); //If there are several attributes, split them
}
/**
 *  Adds an attribute to the list,; separated by &
 * list: String containing attributes.
 * attribute: String containing the attribute in attr=value form
 */
function addAttribute( list, attribute ) {
	separator = "&";
	if (list=="") {
		separator = "?";
	}
	return list + separator + attribute;
}

/** Strips the end of an URL, to get a kind of base */
function getBase( href ) {
	// find position of last /
	last = href.lastIndexOf("/");
	// Basename is from 0 to that
	if (last == -1) return "";
	return href.substring(0,last);
}

/**
 * Function to bypass IE braindamage search / hash ordering
 * It reorders properly the href part with search and anchor.
 * @param a location which has search, href and hash attributes
 */
function remakeUrl(loc) {

	if (isIE()) {
	
		// Strip search part
		var temp = loc.href.split('?')[0];
		// Strip Anchor part
		temp = temp.split('#')[0];
		// Append search
		temp = temp + loc.search;
		// Append anchor
		temp = temp + loc.hash;
		
		loc.href = temp;
	}
}

//==================================
// Amdt highlighting

/** Launch the CSS3 target pseudo-class emulation for IE<7.
  *  Called by init() on load event.
  */ 
function initTargetEmulation() {
    // Simple normalization function to clean extra white-space.
    String.prototype.normalize = function(){
	return this.replace(/\s+/g, " ");
    };
    window.attachEvent("onload", emulateCSSPseudoClassTarget);
}

function isIE() {
	return ((navigator.appName == 'Microsoft Internet Explorer') || 
			((navigator.appName == 'Netscape') && 
			 (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null)));
}

// The following is copied from
// http://tests.novemberborn.net/javascript/emulate-css-pseudo-class-target-in-ie.html

/*	Emulate the CSS :target Pseudo-Class in IE
	Copyright 2005 Mark Wubben <http://novemberborn.net/colophon>

	This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/

/*	The hack: this function gets executed on load. It'll set `.target` on the element who's ID matches the fragment identifier of the URI.
	It then monitors this identifier every 200 ms for changes. Originally I wanted to use the propagation of the `focus` event so I could 
	check it every time an element got focus, but unfortunately this is not supported in IE.
*/
function emulateCSSPseudoClassTarget(){
	var sCurrentTargetID = getFragmentID();
	
	function setClass(sID){
		var node = document.getElementById(sID);
		if(node == null){
			return;
		};
		var sClassName = node.className;
		if(sClassName == null){
			sClassName = "target";
		} else {
			sClassName = sClassName.normalize() + (sClassName == "" ? "" : " ") + "target";
		};
		node.className = sClassName;
	};
	
	function removeClass(sID){
		var node = document.getElementById(sID);
		if(node == null){
			return;
		};
		node.className = node.className.replace(/\btarget\b/, "");
	};
	
	function getFragmentID(){
		return document.location.hash.replace(/^#(.*)$/, "$1");
	};
	
	function monitor(){
		var sNewTargetID = getFragmentID();
		if(sNewTargetID != sCurrentTargetID){
			removeClass(sCurrentTargetID);
			setClass(sNewTargetID);
			sCurrentTargetID = sNewTargetID;
		};
	};
	
	setClass(sCurrentTargetID);
	
	// Your brain (well, the conscious part) won't notice a change if it happens inside a time-frame of 200 ms. Therefore this is a safe interval.
	setInterval(monitor, 150);
};
