/* provide pretty mouse over effect on the (LHS) menu for IE6 and earlier - 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, '');	
}

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();
		 	};
		}
	}
}

// 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()
{
	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 < 2) 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('Page content');
	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('Top'); //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;
 }
 
 function doSearch (inputBoxId)
 {
	location.href = 'http://resources.renishaw.com?language=UKEnglish&terms=' + escape(document.getElementById(inputBoxId).value);
 }
 
 // Generate external link images on text links, display external link message from template
function modifyExternalLinks()
{

	var links = getElementsByTagNames('a');
	var message = document.getElementById('externalLinks');
	if (message)
	{
	   message.className = "hideExternalMessage";
	}
	for (var entryPosition=0; entryPosition<links.length; entryPosition++) 
	{
		var thisEntry = links[entryPosition];
	  //  thisEntry.innerHTML = thisEntry.name;
		if (thisEntry.name == '' )
	//	if (thisEntry.name != 'modal') 
		if (thisEntry.host != undefined ) 
		if (thisEntry.protocol !=undefined) 
		if (thisEntry.protocol != "mailto:") 
		if (!((thisEntry.host == document.location.host) || (thisEntry.host == document.location.host + ":80")))
		{
			thisEntry.className += " externalLink modal";
			var addText = false;
		
		
			for (var nodePosition=0; nodePosition< thisEntry.childNodes.length;nodePosition++)
			{
		        var currentText =  thisEntry.childNodes[nodePosition].data;
		
				if (currentText && currentText.trim() != '')
					addText = true;
					
				
			}
			if (addText) 	
			{
				thisEntry.className += " text";
		//		if (message)
		//		{
		//			message.className = "externalMessage";
			//	}
			}
			
		}
		
	}
	if (getCookie('externalLink') == '')
	{
	// now set up the modal request
	$$('a.modal').each(function(link){new Control.Modal(link,{contents:
	'<h1> Attention, you are now leaving the Wotton Travel web site</h1>'
	+'<p> Wotton Travel makes no representation or warranties about any other Web site which you may access through this one. '
	+ 'When you access non-Wotton Travel Web sites, such Web sites are independent of Wotton Travel and Wotton Travel has no control over '
	+ 'the operation of non-Wotton Travel Web sites. In addition, a link to a non-Wotton Travel Web site does not mean that Wotton Travel '
	+ 'endorses that Web site or has any responsibility for the use of such Web site.</p> '
	+ 'Do not show this again <input type="checkbox" id="externalCheck" /><br/> '

	+ '<a id="A2" name="modal" href="'+link.href+'" target="'+link.target+'" onclick="javascript:setCookie(\'externalLink\',365);" >Continue</a> '
	+ '<a class="fbox" name="modal" href="javascript:Control.Modal.close();">Cancel</a>'}); });
}
	
}

function setCookie(c_name,value,expiredays)
{
    if(document.getElementById("externalCheck").checked)
    {
        var exdate= new Date();
        exdate.setDate(exdate.getDate()+ expiredays)
        document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
    }
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 ;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}
 
function copyrightDate()
{
	// rewrite the copyright date
	// get todays year
	var d = new Date();
	var thisYear = d.getYear();
	
	var elementsInFooter = document.getElementById('footerLegal').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);