﻿/*
Created: Jan2007
Created: Jan2007
Last updated: Dec 2007
*/
/* provide pretty mouse over effect on the (LHS) menu for IE6 and earlier - most others are CSS driven */
function menuHighlightOn(item) 
{	
	item.className += ' menuSideHover';	
}
function menuHighlightOff(item) 
{
	var pattern = /\b\s?menuSideHover\b/;
	item.className = item.className.replace(pattern, '');	
}

/* Suckerfish drop down menu script, extended slightly */
sfHover = function()
{
    var siteNavElement = document.getElementById("siteNav")
    if( siteNavElement != null )
    {
        var sfEls = siteNavElement.getElementsByTagName("LI");
        for (var i=0; i<sfEls.length; i++) 
		{
            sfEls[i].onmouseover=function() 
			{
                this.className+=" over";
            }

            sfEls[i].onmouseout=function()
			{
                this.className=this.className.replace(new RegExp("\\s?over\\b"), "");
            }
        }
    }
}

// Provides a way of attaching (and detaching) multiple functions to page load.
function addLoadListener(functionName)
{
	if (typeof window.addEventListener != 'undefined') 
	{
		window.addEventListener('load', functionName, false);
	}
	else if (typeof document.addEventListener != 'undefined') 
	{
		document.addEventListener('load', functionName, false);
	}
	else if (typeof window.attachEvent != 'undefined') 
	{
		window.attachEvent('onload', functionName);
	}	
	else
	{
		var oldfn = window.onload;
		if (typeof window.onload != 'function')
		{
			window.onload = functionName;
		}	
		else
		{
		 	window.onload = function()
		 	{
		 		oldfn();
		 		functionName();
		 	};
		}
	}
}


function attachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.addEventListener != "undefined")
  {
    target.addEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.attachEvent != "undefined")
  {
    target.attachEvent("on" + eventType, functionRef);
  }
  else
  {
    eventType = "on" + eventType;

    if (typeof target[eventType] == "function")
    {
      var oldListener = target[eventType];

      target[eventType] = function()
      {
        oldListener();

        return  functionRef();
      }
    }
    else
    {
      target[eventType] = functionRef;
    }
  }

  return true; 
}


// Courtesy of http://www.quirksmode.org/dom/getElementsByTagNames.html
function getElementsByTagNames(list,obj)
{
	if (!obj) var obj = document;
	
	var tagNames = list.split(',');
	var resultArray = new Array();
	
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
				
	return resultArray;
}

// Generate a ToC from page headings
function generateTOC()
{
	//Get language or fallback to english
	var lang = document.getElementsByTagName('html')[0].getAttribute('Lang');
	if (lang == 'undefined')
	{
		lang = 'en';
	}
	
	var topText, pageContentText;

	switch(lang)
	{
		case 'cs':
			topText = 'Horní strana';
			pageContentText = 'Obsah strany';				
			break;
		
		case 'de':
			topText = 'Nach oben';
			pageContentText = 'Seiteninhalt';				
			break;
		
		case 'fr':
			topText = 'Sous';
			pageContentText = 'Sur cette page';				
			break;	
		
		case 'it':
			topText = 'All\'inizio:';
			pageContentText = 'Contenuto della pagina';				
			break;	
		
		case 'nl':
			topText = 'Naar boven';
			pageContentText = 'Op deze pagina';			
			break;	
		
		case 'pl':
			topText = 'Do góry';
			pageContentText = 'Zawartość strony';
			break;
		
		case 'zh':
			topText = '页首';
			pageContentText = '页面内容';				
			break;
		
		default:
			topText = 'Top';
			pageContentText = 'Page content';
			break;
	}
	
	
	var menu = document.getElementById('TOC');
	
	if (null == menu)
		return;
	
	var headings = getElementsByTagNames('h2,h3,h4', document.getElementById('colContent'));
	var anchorContainer, anchor, linkId;
	
	if (headings.length < 3) return;	//only make a TOC if more than one heading
	
	// Don't allow more than 10 headings unless they're all top level ones
	if (headings.length > 10)
		headings = getElementsByTagNames('h2', document.getElementById('colContent'));

	
	menu.className = 'TOC'; //add classname; only do this now we know we have items as it will make the element appear - visible borders etc

	var tocAnchor = document.createElement('a');
	tocAnchor.setAttribute('name', 'pageTop');
	tocAnchor.id = 'pageTop';
	tocAnchor.className = 'TOCTitle';
	
	var anchorText = document.createTextNode(pageContentText);
	tocAnchor.appendChild(anchorText);
	menu.appendChild(tocAnchor);

	//Create the TOC
	tocList = document.createElement("ul");
	
	for (var entryPosition=0; entryPosition<headings.length; entryPosition++) 
	{
		var thisEntry = headings[entryPosition];
		
		// Determine the link
		linkId = thisEntry.id || uniqueId('tocTarget' + entryPosition);

		// Define the anchor container
		anchorContainer = document.createElement("li");
		anchorContainer.className = 'tocEntry' + thisEntry.nodeName.toLowerCase();

		// Define the anchor
		var anchor = document.createElement("a");
		var killTagsRegex = /<\/?[^>]*?>/gim; // Removes tags |  gim - all matches, case insensitive, multiline
		var tocText = thisEntry.innerHTML.replace(killTagsRegex, '');
		anchor.innerHTML = tocText;
		anchor.href = '#' + linkId;

		// Add the item
		anchorContainer.appendChild(anchor);
		if (anchor.innerHTML.replace(/\&nbsp;/, '').replace(/\&#160;/, '').replace(/\s/, '').length > 0) //not an empty link
		{
			tocList.appendChild(anchorContainer);

			// Modify the link target
			thisEntry.id = linkId;	// Change the element to ensure it has an id

			//Make the wrapper around heading so we can add 'top of page' etc with impunity
			var goTopWrapper = document.createElement('a');
			goTopWrapper.href='#pageTop';
			goTopWrapper.className = 'top';

			var goTopContent = document.createTextNode(topText); //Language concerns?
			goTopWrapper.appendChild(goTopContent);

			var hWrapper = document.createElement('div');
			hWrapper.className = 'tocHeader';
			hWrapper.appendChild(goTopWrapper);


			//then copy heading inside wrapper
			var hClone = thisEntry.cloneNode(true);
			hWrapper.appendChild(hClone);	

			//add wrapper next to target...
			thisEntry.parentNode.replaceChild(hWrapper, thisEntry);
		}
	}

	menu.appendChild(tocList);
}

// Generate a unique identity name
// Field: Identity to form the root
function uniqueId(root)
{
	var unique = root;
	
	while (document.getElementById(unique)) 
	{
		unique += "_";
	}
	
	return unique;
}

//Create alternate row styles on correct table types
function highlightAlternateRows ()
{
	var tables = document.getElementsByTagName('table');
	var contentTables = getElementsByClassName(tables, 'contentTable');
	
	for(var i = 0; i < contentTables.length; i++)
	{
		//get child nodes of type TBODY - but only the first so we don't affect tables within the one we want to update
		var TBodyNode = contentTables[i].getElementsByTagName('TBODY')[0];
	
		//get child nodes of TBODY that are TRs
		var TBodyChildren = TBodyNode.childNodes;
		var TRs = new Array();
		
		//get an array of all TRs
		for (var m = 0; m < TBodyChildren.length; m++)
		{
			var isHeader = false;
			
			if (TBodyChildren[m].nodeName == 'TR')
			{	
				var cells = TBodyChildren[m].childNodes;
								
				for (var cell = 1; cell < cells.length; cell++) //start at one so we keep row highlighting for tables with vertical headers
				{
					//var thClassName = /\b\s?th\b/; //regex pattern for classname of th
					if (cells[cell].nodeName == 'TH') /*|| (thClassName.test(cells[cell].className )) )*/
						 isHeader = true;
				}
				
				if (isHeader == false)
					TRs[TRs.length] = TBodyChildren[m];
			}
		}
			
		for(var j = 0; j < TRs.length; j++)
		{
			if ( j % 2 != 0) //even row
				TRs[j].className = " altRow"; //leave a space so we don't interfere with existing classes
		}	
	}
}

function getElementsByClassName(elementArray, NameofClass)
{
	var matchedArray = new Array();
	
	for (var i = 0; i < elementArray.length; i++)
	{
 		var pattern = new RegExp("(^| )" + NameofClass + "( |$)");

		if (pattern.test(elementArray[i].className))
		{
			matchedArray[matchedArray.length] = elementArray[i];
		}
      }
      return matchedArray;
 }
 
  
 //Search box
 function doSearch (inputBoxId)
 {
	location.href = 'http://resources.renishaw.com?language=UKEnglish&terms=' + escape(document.getElementById(inputBoxId).value);
 }
 
 function setupSearchSubmit()
 {
	var searchBox = document.getElementById('terms');
	if ((searchBox != null) && (searchBox != 'undefined'))
		attachEventListener(searchBox, 'keypress', searchSubmitOnKeypress, false);
 }
 addLoadListener(setupSearchSubmit);
  
 function searchSubmitOnKeypress(event)
 {
	if (event.keyCode == '13')
	{
		doSearch('terms');
	}
 }
 
function copyrightDate()
{
	// rewrite the copyright date
	// get todays year
	var d = new Date();
	var thisYear = d.getYear();
	
	var elementsInFooter = document.getElementById('footer').getElementsByTagName('P');
	for (var i=0;i<elementsInFooter[0].childNodes.length;i++) {
		var el = elementsInFooter[0].childNodes[i];
		if (el.nodeType==3 && el.data.match(new RegExp('2008'))) {
			el.data = el.data.replace(new RegExp('2008'), thisYear);
			break;
		}
	}
}
addLoadListener(copyrightDate);