// scripts for use with Common Standards Monitoring pages
// Ulric Wilson
// Oct 2005

// On html page load, fn addEvent runs, passed parameters (elm=window, evType=load, fn=installListeners, useCapture=false)
// fn installListeners calls fn moveContext() to move Context DIV into tabbed menu navigation
// fn installListeners then adds an onClick event to each link of class='menuitem' to call fn tabbedMenuClick
// fn tabbedMenuClick calls fn find_taget to find out which link was clicked
//	then removes current tab highlight, adds new selected tab highlight
//	and trims id of selected tab and used this to make selected content DIV visible 

function addEvent(elm, evType, fn, useCapture) {
  // cross-browser event handling for IE5+, NS6 and Mozilla 
  // By Scott Andrew 
  if (elm.addEventListener) { 
    elm.addEventListener(evType, fn, useCapture); 
    return true; 
  } else if (elm.attachEvent) { 
    var r = elm.attachEvent('on' + evType, fn); 
    return r; 
  } else {
    elm['on' + evType] = fn;
  }
}

// =======================================================================

function installListeners() {	// attaches onClick events to all links in DIV id='tabmenu' and runs other functions onLoad to set up page
moveContext()					// move DIV id='context' to within tabs

var tabmenu = document.getElementById('tabbedmenu');	// ref to tabmenu div
var all_links = tabmenu.getElementsByTagName('a');		// get array of all anchors within tabmeu
for (var i = 0; i < all_links.length; i++) {			// iterate thro array, if class=menuitem attach onClick event
	var link = all_links[i];
	if (link.className &&
		(' ' + link.className + ' ').indexOf(' menuitem ') != -1)
		{
		link.onclick = tabbedMenuClick;
		}
	}
}      

// ========================================================================

function find_target(e) {								// cross browser identification of target that was clicked
  // Begin the DOM events part
  var target; 

  if (window.event && window.event.srcElement)			// cross browser bit
    target = window.event.srcElement;
  else if (e && e.target)
    target = e.target;
  if (!target)
    return null;

  while (target != document.body &&						// some browser return the href as the target but we
      target.nodeName.toLowerCase() != 'a')				// want the <a> so climb DOM tree to get it
    target = target.parentNode;							// stopping at <body> if we get there

  if (target.nodeName.toLowerCase() != 'a')
    return null;

  return target;
}

// ==========================================================================

function ascendDOM(e, tag) {							// function ascends DOM tree to the supplied tag
	while (e.nodeName.toLowerCase() != tag && 
		e.nodeName.toLowerCase() != 'html')
	e = e.parentNode;
	
	return (e.nodeName.toLowerCase() == 'html') ? null : e;
}

// ==========================================================================

function tabbedMenuClick(e) {							// response to tab being clicked
  var target = find_target(e);							// get target
  if (!target) return;									// if no target, then degrade nicely
  if (!target.className == 'menuitem') return;			// double check class = menuitem
  
  // highlight selected tab, but first remove any previously selected highlight
  var tabmenu = document.getElementById('tabbedmenu');	// get ref to tabbedmenu DIV
	var all_tabs = tabmenu.getElementsByTagName('li');	// array of all LI within tabbed menu
	for (var i = 0; i < all_tabs.length; i++) {
	var tab = all_tabs[i];
	if (tab.id &&
		(' ' + tab.id + ' ').indexOf(' selectedtab ') != -1)
		{
		tab.removeAttribute('id');						// remove highlight CSS styling of id=selected tab 
		}
	}

  // take event 'target', ascend DOM to <LI> parent and set ID='selectedtab' to provide highlight
  var selectedtab = ascendDOM(target,'li');
  selectedtab.id = 'selectedtab'
  
  // get DIV selection from Link Id
  var chosenLinkId = target.id							// the id of the clicked link(tab)
  	for (var i = 0; i < all_tabs.length; i++) {
  	if (!all_tabs[i].firstChild.firstChild.id) return;	// check it exists
	var linkId = all_tabs[i].firstChild.firstChild.id;	// id of link where LI > SPAN > A
	
	var divId = Mid(linkId, 4, (linkId.length - 4));	// trims off 'Link' from begining of link id to leace DIV id
	
	var tDiv = document.getElementById(divId);			// ref to chosen DIV
	
	if (chosenLinkId == 'Linkpage2') {
		moveGraph()
	}
	
   if (chosenLinkId == 'Linkshowall')   {				// force evaluation to true so all divs shown
	  linkId = chosenLinkId;							// if 'Show all' clicked	  
   }
	
	if (!tDiv) return;									// check valid ref
	if (linkId == chosenLinkId) {						
		tDiv.style.display = 'block';					//un-hide selected div
	}
	 else {
		tDiv.style.display = 'none';					//hide all non-selected divs
	}

   }
   }

// =======================================================================================

function moveContext() {								// move Context DIV onto tab

var divSummary = document.getElementById('summarytable')	// ref to SummaryTable DIV
//var divAssessment = document.getElementById('assessments')	// ref to Assessment DIV (context goes infront of this)
var divContext = document.getElementById('context')			// ref to contect DIV
var divPlaceholder = document.getElementById('placeholder')	// ref to placeholder DIV that contains all DIVs
divPlaceholder.insertBefore(divContext, divSummary);		// inserts Context before summarytable in DOM tree removing it from original location	
divContext.appendChild(divSummary);							// moves summarytable to be child of newly moved context so it is on context tab

  // highlight Context div and mark others invisible
    var tabmenu = document.getElementById('tabbedmenu');	// ref to tabbedmenu

	var all_tabs = tabmenu.getElementsByTagName('li');		// array of LI tags
	for (var i = 1; i < all_tabs.length; i++) {				// Context is first (i=0) so interate through all
	var tab = all_tabs[i];									// others from i=1 to hide them
	
	if (!tab.firstChild.firstChild.id) return;				// check it exists
	var linkId = tab.firstChild.firstChild.id;				// id of link where LI > SPAN > A
	
	var divId = Mid(linkId, 4, (linkId.length - 4));	// trim 'Link' off id = target DIV id
	var tDiv = document.getElementById(divId);			// get ref to DIV
	if (!tDiv) return;									// check it exists
   tDiv.style.display = 'none';							//hide all non-selected divs
	

   
   // highlight Context tab on tabbed menu
  var tabmenu = document.getElementById('tabbedmenu');	// ref to tabbedmenu div
  tabmenu.style.display = 'block';

	var all_tabs = tabmenu.getElementsByTagName('li');	// array of LIs in tabbedmenu
	var selectedtab = all_tabs[0];						// highlight first one (=context tab)
	selectedtab.id = 'selectedtab'

}
}

// =================================================================================

addEvent(window, 'load', installListeners, false);		// key function runs on window load event and 
														// fires function 'installListeners'
// ===============================================================================

// =====================														
	//Utility functions

     // JavaScript Functions Written by:
     //    Scott Mitchell
     //    mitchell@4guysfromrolla.com
     //    http://www.4GuysFromRolla.com
     
// Mid(string, start, length): Returns a specified number of characters from a string
//============================================================================

        function Mid(str, start, len)
        /***
                IN: str - the string we are LEFTing
                    start - our string's starting position (0 based!!)
                    len - how many characters from start we want to get

                RETVAL: The substring from start to start+len
        ***/
        {
                // Make sure start and len are within proper bounds
                if (start < 0 || len < 0) return "";

                var iEnd, iLen = String(str).length;
                if (start + len > iLen)
                        iEnd = iLen;
                else
                        iEnd = start + len;

                return String(str).substring(start,iEnd);
        }

     
