 // scripts for use with Biodiversity In Your Pocket (BIYP) pages
// Ulric Wilson
// Dec 2006

// On html page load, fn addEvent runs, passed parameters (elm=window, evType=load, fn=installListeners, useCapture=false)
// 
// 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
addShowall()
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;
		addEvent(link,'click',tabbedMenuClick,false);
		if (!window.event) {link.onclick = cancelClickSafari();}
		}
	}
	//tabmenu.style.display = 'block';
	//var page2 = document.getElementById('page2');	// ref to page2 div
	//page2.style.display = 'none';
	selectDefault()										// highlight default tab
}      

// ========================================================================

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'
  
  	if (target.id == 'Linkpage2') {					// If Assessment tab is clicked need to copy graph
		moveGraph();
	}
	if (target.id == 'Linkshowall') {				// If graph exists in Assessment div (page2) then hide it so it doesn't appear twice
		hideGraph();
	}
	

  // get DIV selection from Link Id
  var chosenLinkId = target.id;							// the id of the clicked link(tab)
    //alert("chosenLinkId = " + chosenLinkId);
  	for (var i = 0; i < all_tabs.length-1; 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
		//alert("linkId = " + linkId);
	var divId = Mid(linkId, 4, (linkId.length - 4));	// trims off 'Link' from begining of link id to leace DIV id
		//alert("divId = " + divId);
		//test
		//var testId = 'page1'
		//alert("testId = " + testId);
		//var testDiv = document.getElementById('page3');
		//alert("testDiv = " + testDiv);
		// end test
	var tDiv = document.getElementById(divId);			// ref to chosen DIV
		//alert("tDiv = " + tDiv);
		
   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
	}
   }
   //try here
   if (window.event) {									// stop propagation and default behaviour
	//alert("window.event default behaviour stopped");
	window.event.cancelBubble = true;
	window.event.returnValue = false; 

    }
   if (e && e.stopPropagation && e.preventDefault) {
	//alert("e. default behaviour stopped");
	e.stopPropagation();
	e.preventDefault();
	
   }

//alert("Almost at the end");

   }
// =======================================================================================

function addShowall() {
	var tabmenu = document.getElementById('tabbedmenu');		// ref to tabbedmenu DIV
	var tabs = tabmenu.getElementsByTagName("li");				// collection of LIs
	var newLi = tabs[0].cloneNode(true);						// clone first LI 
	var newA = newLi.getElementsByTagName('a');
	newA[0].id = 'Linkshowall';			// change id
	newA[0].title = 'Link: Show all';		// change title
	var url = newA[0].href					// ref to href of A
	var hash = url.indexOf("#");								// location of hash #
	var newurl = url.substring(0,hash+1) + "top";				// trim off old anchor and add 'top'
	newA[0].href = newurl;					// update href of A
	newA[0].firstChild.nodeValue = "Show All";
	var menuUl = tabmenu.getElementsByTagName('ul');							// ref to UL
	menuUl[0].appendChild(newLi);
}

// =======================================================================================

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'

}
}

// =======================================================================================

function selectDefault() {									// seletct default 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'

}
}

// =======================================================================================

function moveGraph() {								// move 'trendgraph' DIV onto 'Assessment' tab

var graphAlreadyMoved = document.getElementById('copytrendgraph');
var assessmentGraph = document.getElementById('assessmentgraph');
if(!assessmentGraph) {return;}
if(graphAlreadyMoved) {
	assessmentGraph.style.display = 'block';
	return;
}

var trendGraph = document.getElementById('trendgraph');
if(!trendGraph) {return;}

var copyTrendGraph = trendGraph.cloneNode(true);
copyTrendGraph.id = 'copytrendgraph';



assessmentGraph.appendChild(copyTrendGraph);
//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


}

// =================================================================================

function hideGraph() {										// hide duplicate graph if Show All tab clicked

	var copyTrendGraph = document.getElementById('copytrendgraph');
	if(!copyTrendGraph) {return;}							// it hasn't been created so return
	
	var assessmentGraph = document.getElementById('assessmentgraph');	// reference parent node of duplicate graph
	if(!assessmentGraph) {return;}
	
	assessmentGraph.style.display = 'none';					// hide duplicate graph
}

// =================================================================================

addEvent(window, 'load', installListeners, false);		// key function runs on window load event and 
														// fires function 'installListeners'
// ===============================================================================

// Helper functions

function cancelClick(e){

		if (window.event){
			window.event.cancelBubble = true;
			window.event.returnValue = false;

			return;
		}

		if (e){
			e.stopPropagation();
			e.preventDefault();
		}
	}
	
function cancelClickSafari () {
		if (!window.event){return false;}
	}

// =====================														
	//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);
        }

     
