﻿/*
Copyright (c) 2007-2009 Renishaw plc. All rights reserved
Created: Jan 2007
Last updated: June 2009
*/
/* 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) { item.className=item.className.replace(new RegExp("\\b(\\s)?menuSideHover\\b"), "");}

/* 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("\\b(\\s)?over\\b"), "");}
        }
    }
}

// Provides a way of attaching (and detaching) multiple functions to page load.
function addLoadListener(functionName) /*legacy*/
{
	$(document).ready(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 'es':
			topText = 'Arriba';
			pageContentText = 'Contenido de la página';				
			break;	
		case 'fr':
			topText = 'Haut de page';
			pageContentText = 'Sur cette page';				
			break;	
		case 'it':
			topText = 'All\'inizio';
			pageContentText = 'Contenuto della pagina';				
			break;	
		case 'jp':
			topText = 'トップへ';
			pageContentText = 'ページコンテンツ';
			break;
		case 'ko':
			topText = '맨 위';
			pageContentText = '페이지 내용';
			break;
		case 'nl':
			topText = 'Naar boven';
			pageContentText = 'Op deze pagina';			
			break;		
		case 'pl':
			topText = 'Do góry';
			pageContentText = 'Zawartość strony';
			break;
		case 'pt':
			topText = 'Topo da página';
			pageContentText = 'Conteúdo da página';
			break;
		case 'ru':
			topText = 'К началу';
			pageContentText = 'Содержание страницы';
			break;
		case 'sl':
			topText = 'Navzgor';
			pageContentText = 'Vsebina strani';
			break;
		case 'sv':
			topText = 'Upp';
			pageContentText = 'Sidans innehåll';
			break;
		case 'tr':
			topText = 'En başa';
			pageContentText = 'Sayfa içeriği';
			break;
		case 'tw':
			topText = '頂部';
			pageContentText = '頁面內容';
			break;	
		case 'zh':
			topText = '顶部';
			pageContentText = '网页内容';				
			break;
		default:
			topText = 'Top';
			pageContentText = 'Page content';
			break;
	}
		
	var menu = document.getElementById('TOC');
	
	if (null == menu){return;}/*nothing to do*/
	
	var headings = getElementsByTagNames('h2,h3,h4', document.getElementById('colContent'));
	var anchorContainer, anchor, linkId;
	
	if (headings.length < 4) 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') {	 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
 var Search = {
	langcode:'en',
	sb:{},
	init:function() {
		Search.sb = $('#terms');
		if(location.pathname != null && location.pathname.length > 0) {
			var lc = location.pathname.match(/\/([a-zA-Z\-]{2,5})\//i);
			if((null != lc) && (lc[1])) { Search.langcode = lc[1] };
			//if(lc[1]) Search.langcode = lc[1];
		}
		Search.sb.keydown(Search.Keypress);
	},
	submit:function() {
		try {
			if(Search.sb.val().length > 0) {
				location.href = 'http://resources.renishaw.com/'  + encodeURI(Search.langcode) + '/search/' + encodeURI(Search.sb.val());
			} 
		} catch ( e ) {
			alert("No search terms entered"); //needs translation?
		}
		return false;		
	},
	Keypress: function(e) {
		if (e.keyCode == '13'){	
			if(e.preventDefault) e.preventDefault();
			if(e.stopPropagation) e.stopPropagation();
			setTimeout(Search.submit, 250);
			e.cancelBubble = true;
			e.returnValue = false;			
		}		
	}
 }
function searchSite(searchBoxId, languageCode)
{
	var searchBox = document.getElementById(searchBoxId);
	if ((searchBox != null) && (searchBox != 'undefined'))
	{
		location.href = 'http://resources.renishaw.com/'  + encodeURI(languageCode) + '/search/' + encodeURI(searchBox.value);
	}
	else
	{
		alert ("No search terms entered.");
	}
	return false;
}
 $('document').ready(Search.init);
 /* End Search */
 
function ctaEnhance()
{
	var killTagsRegex = /<\/?[^>]*?>/gim; // Removes tags |  gim - all matches, case insensitive, multiline		
 
	var targets = new Array(	document.getElementById('helpZoneInfo'),document.getElementById('helpZoneQuote'),document.getElementById('helpZoneSupport'),document.getElementById('nextStepsInfo'),document.getElementById('nextStepsQuote'),document.getElementById('nextStepsLocalOffices') );	
	var menuItems = $('#colLeft td.menuItem');	
	if (menuItems.length > 0){ //.com template always has prod line as first item (.info has site name)
		var ProdLine = menuItems[0].innerHTML.replace(killTagsRegex, '');	
		var querystringAddition = '';
		if (ProdLine != '')	{
			var ProdLineId = ProductLineLookup(ProdLine);
			if (!isNaN(ProdLineId)) /*is a number*/ {	querystringAddition = '&productline=' + ProdLineId; /*add productline ID*/	}	}

		for (var i=0; i< targets.length; i++){ if (targets[i] != undefined) { targets[i].href = targets[i].href + querystringAddition;	}}
	}
}
$(document).ready(ctaEnhance);
 
function ProductLineLookup(ProductLineName)
 {
	switch (ProductLineName)
	{
		case 'Laser calibration and ballbar':
			return '1';
		case 'CMM probes, software and retrofits':
			return '2';
		case 'Corporate':
			return '10';
		case 'incise™ dental cad/cam':
			return '4';	
		case 'Digitising':
			return '1';
		case 'Laser encoders':
			return '6';
		case 'Machine tool probes and software':
			return '7';
		case 'Neurological':
			return '12';
		case 'Position encoders':
			return '5';
		case 'Raman spectroscopy':
			return '8';
		case 'Styli for touch probes':
			return '9';
		default:
			var tmp = ProductLineName.substring(0,6);
			if (ProductLineName.substring(0,6) == 'incise')	{return '4';}
			break;
	}
 }

function hideTableRows(tableId, tableRowId, collapse) {
    switch (collapse) {
        case true:
            {
                $("#table_" + tableId + "_row_" + tableRowId).hide();
                $("#table_" + tableId + "_row_" + (tableRowId - 1)).show();
                break;
            }
        case false:
            {
                $("#table_" + tableId + "_row_" + (tableRowId - 1)).hide();
                $("#table_" + tableId + "_row_" + tableRowId).show();
                break;
            }
    }
}

function hideTableColumns(tablename, tableHeight, tableColumnId, collapse) {
    switch (collapse) {
        case true:
            {
                for (var tableRowId = 0; tableRowId < tableHeight; tableRowId = tableRowId + 2) {
                    $("#table_" + tablename + "_row_" + tableRowId + "_column_" + tableColumnId).hide();
                    $("#table_" + tablename + "_row_" + tableRowId + "_column_" + (parseInt(tableColumnId) + 1)).show();
                }
                break;
            }
        case false:
            {
                for (var tableRowId = 0; tableRowId < tableHeight; tableRowId = tableRowId + 2) {
                    $("#table_" + tablename + "_row_" + tableRowId + "_column_" + (parseInt(tableColumnId) + 1)).hide();
                    $("#table_" + tablename + "_row_" + tableRowId + "_column_" + tableColumnId).show();
                }
                break;
            }
    }
}


function addComparisionTable() {
    var tableList = getElementsByClassName(getElementsByTagNames('TABLE'), 'interactiveTable');
	var isFireFox = false;
	
    for (var i = 0; i < tableList.length; i++) {
        var tableRows = tableList[i].getElementsByTagName("TR");
        var rowCount = (tableRows.length * 2);
        var colsToHide = "";
        for (var j = 0; j <= tableRows.length; j=j+2) {
            if (j == 0) {
                // add empty header row
                var newCell = tableRows[j].insertCell(0);
                newCell.innerHTML = '<br />';
            } else {
                // add minus image and javascript on click event
                tableRows[j - 1].id = 'table_' + i + '_row_' + j;

                var newCell = tableRows[j - 1].insertCell(0);
                newCell.innerHTML = '<a onclick=hideTableRows("' + i + '","' + j + '",true);><img src="http://www.renishaw.com/media/shared/icons/minus.gif" /></a>';

                var newRow = tableList[i].insertRow(j - 1);
                newRow.insertCell(0);
                newRow.insertCell(1);
                
                var firstCell = newRow.cells[0];
                firstCell.innerHTML = '<a onclick=hideTableRows("' + i + '","' + j + '",false);><img src="http://www.renishaw.com/media/shared/icons/plus.gif" /></a>'
                
                var lastCell = newRow.cells[1];
                lastCell.colSpan = tableRows[j].cells.length - 1;
                var test = tableRows[j].cells[1];
                if (tableRows[j].cells[1].childNodes[0].data == "\n") {
                    lastCell.innerHTML = tableRows[j].cells[1].childNodes[1].innerHTML;
                }
                else {
                    lastCell.innerHTML = tableRows[j].cells[1].childNodes[0].innerHTML;
                }

                newRow.id = 'table_' + i + '_row_' + (j - 1);
                $("#" + newRow.id).hide();
            }
            
            // add columns
            var tableColumns = tableRows[j].childNodes;
			var firefox = 0;
			var firefox2 = 2;
			var firefox3 = 0;
			var loop = tableColumns.length;
			if (isFireFox) {
				loop = tableColumns.length;
			}
			
            for (var k = 1; k < loop; k = k + 2) {
				if (tableRows[j].childNodes[0].data != "\n") {
					loop++;
					if (j == 0) {
						var toolTip = "";
						toolTip = tableRows[j].childNodes[k].innerHTML;
						
						tableRows[j].childNodes[k].id = 'table_' + i + '_row_' + j + '_column_' + k;
						tableRows[j].childNodes[k].innerHTML = '<a onclick=hideTableColumns("' + i + '","' + rowCount + '","' + k + '",true);><img src="http://www.renishaw.com/media/shared/icons/minus.gif" /></a>' + tableRows[j].childNodes[k].innerHTML;

						var newCell = tableRows[j].insertCell(k + 1);
						newCell.id = 'table_' + i + '_row_' + j + '_column_' + (k + 1);
						newCell.innerHTML = '<a onclick=hideTableColumns("' + i + '","' + rowCount + '","' + k + '",false); title="' + toolTip + '"><img src="http://www.renishaw.com/media/shared/icons/plus.gif" /></a>'
						colsToHide += newCell.id + ",";
					}
					else {
						tableRows[j].childNodes[k].id = 'table_' + i + '_row_' + j + '_column_' + k;
						
						var newCell = tableRows[j].insertCell(k + 1);
						newCell.id = 'table_' + i + '_row_' + j + '_column_' + (k + 1);
						newCell.innerHTML = '<br />';
						colsToHide += newCell.id + ",";
					}
				}
				else
				{
					isFireFox = true;
					firefox += firefox2;
					if (j == 0) {
						var toolTip = "";
						
						toolTip = tableRows[j].childNodes[firefox].innerHTML;
					
						tableRows[j].childNodes[firefox].id = 'table_' + i + '_row_' + j + '_column_' + k;
						tableRows[j].childNodes[firefox].innerHTML = '<a onclick=hideTableColumns("' + i + '","' + rowCount + '","' + k + '",true);><img src="http://www.renishaw.com/media/shared/icons/minus.gif" /></a>' + tableRows[j].childNodes[firefox].innerHTML;

						if (k!=1) {
							firefox -= firefox3;
						}
						
						var newCell = tableRows[j].insertCell(firefox);
						newCell.id = 'table_' + i + '_row_' + j + '_column_' + (firefox);
						newCell.innerHTML = '<a onclick=hideTableColumns("' + i + '","' + rowCount + '","' + k + '",false); title="' + toolTip + '"><img src="http://www.renishaw.com/media/shared/icons/plus.gif" /></a>'
						colsToHide += newCell.id + ",";
					}
					else {
						tableRows[j].childNodes[firefox].id = 'table_' + i + '_row_' + j + '_column_' + k;
						
						if (k!=1) {
							firefox -= firefox3;
						}
						
						var newCell = tableRows[j].insertCell(k+1);
						newCell.id = 'table_' + i + '_row_' + j + '_column_' + (k+1);
						newCell.innerHTML = '<br />';
						colsToHide += newCell.id + ",";
					}
					firefox2++;
					firefox3++;
				}
            }
        }

        // hide all new empty columns
        var colsToHideArray = colsToHide.split(",");
        for (var colId = 0; colId < colsToHideArray.length-1; colId++) {
            $("#" + colsToHideArray[colId]).hide();
        }
    }
}
$(document).ready(addComparisionTable);

/*Load hidden shadowbox inline divs*/
/*Note: this is a temp setup until fully integrated with the CMS*/
function ManualInlineLinks()
{
	if ($("#ElementHTML25760 img").length == 1) 
	{
		//add click events to trigger
		$("#ElementHTML25760 img").bind(
			"click", 
			function() {
				var clone = $("#ElementHTML25990").clone();
				$('.shadowbox-inline', clone).removeClass("shadowbox-inline");
			
				Shadowbox.open({
					content: clone.html(),
					player: "html",
					title: "Typical FASTRACK&trade; linear encoder system hysteresis graph",
					width: 1000,
					height: 600
				});
			}
		);			
	}
}
$(document).ready(ManualInlineLinks);
/*END Load hidden shadowbox inline divs*/


/***********************/
/*     Page Specific   */

	/* Resolute imagemap pg 10940 */
	function resoluteImageMapInit()
	{
		if ($("body#page10940").length == 1) 
		{
			//Add the area map after the image and then init the shadowbox details
			try
			{
			
				var mapstring = '<map id="ResoluteProdTourMap" name="ResoluteProdTourMap">' +
						'<area shape="circle" coords="140,320,15" href="#ElementHTML26203" alt="Area 1">' +
						'<area shape="circle" coords="208,184,15" href="#ElementHTML26204" alt="Area 2">' +
						'<area shape="circle" coords="260,120,15" href="#ElementHTML26205" alt="Area 3">' +
						'<area shape="circle" coords="396,70,15" href="#ElementHTML26206" alt="Area 4">' +
						'<area shape="circle" coords="350,110,15" href="#ElementHTML26207" alt="Area 5">' +
						'<area shape="circle" coords="278,100,15" href="#ElementHTML26208" alt="Area 6">' +
						'<area shape="circle" coords="294,220,15" href="#ElementHTML26209" alt="Area 7">' +
						'<area shape="circle" coords="140,355,15" href="#ElementHTML26210" alt="Area 8">' +
						'<area shape="circle" coords="225,146,15" href="#ElementHTML26211" alt="Area 9">' +
						'<area shape="circle" coords="208,257,15" href="#ElementHTML26212" alt="Area 10">' +
					'</map>';
				//append the map to the html
				//$("#ElementHTML26025 .htmlInner img").after(mapstring);
				//update the attributes
				$("#ElementHTML26025 .htmlInner img").attr('usemap', '#ResoluteProdTourMap');
				//check for IE 6 or lower
				if($.browser.msie) {					
					//clone the node, add the clone and remove the original to force IE to re-render the image forcing the image map to work
					$("#ElementHTML26025 .htmlInner img").clone().insertAfter("#ElementHTML26025 .htmlInner img");
					$("#ElementHTML26025 .htmlInner img:first").remove();
				}
				// setup image map demo
				Shadowbox.setup($("#ResoluteProdTourMap area")); 				
			}
			catch(err){/*alert(err);*/}
		}
	}
	$(document).ready(resoluteImageMapInit);
	/* End Resolute imagemap pg 10940 */
	
/*  End Page Specific  */
/***********************/