// Global JavaScript functions for Red Gate website
// Written by SRJ, Studio 24 Ltd, 04/11/2006
// Last updated SRJ, 23/11/2006

// Load multiple functions on window onload and onresize
// Source: http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent (func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
// Adapted by S24 
function addResizeEvent (func, skip_onload) {
  // Add onload too?
  if (skip_onload != true) {
    addLoadEvent(func); 
  }
  // Set onresize
  var oldonresize = window.onresize;
  if (typeof window.onresize != 'function') {
    window.onresize = func;
  } else {
    window.onresize = function() {
      if (oldonresize) {
        oldonresize();
      }
      func();
    }
  }
}

// Global vars to track window dimensions
var window_x, window_y;

// Get current window dimensions
// Source: http://www.quirksmode.org/viewport/compatibility.html
function getWindowDimensions ()
{
	// Get current window width
	// Source: http://www.quirksmode.org/viewport/compatibility.html
	if (self.innerHeight) // all except Explorer
	{
		window_x = self.innerWidth;
		window_y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		window_x = document.documentElement.clientWidth;
		window_y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		window_x = document.body.clientWidth;
		window_y = document.body.clientHeight;
	}
}

addResizeEvent(getWindowDimensions);



//
// Code for swapping home banner images
//

// Global vars for banner images
var banner_small, banner_large;
var banners_valid = false;

// Preloads small and large home banner images
// This gets the current small home banner, interrogates the filename and works out the large image filename
// Ie. a small image filename of: BannerRG1_small.gif 
// would give us a large filename of: BannerRG1_large.gif
function preloadBannerImages ()
{
	if (!document.getElementById) return false;
	if (!document.images) return false;
	
	// Get banner image
	var bannerImg  = document.getElementById('feature-banner');
	
	//perform currency replacement
	if(ccyCode && ccyCode != 'USD')
	    bannerImg.src = bannerImg.src.replace(/USD/, ccyCode);
	
	// Get image names
	var src = bannerImg.getAttribute('src');
	var fname = src.substring(0, src.lastIndexOf('_small'));
	var ftype = src.substring(src.lastIndexOf('.'), src.length);
	
	// Preload images
	banner_small = document.createElement('img');
	banner_large = document.createElement('img');
	banner_small.setAttribute('src', src);
	banner_large.setAttribute('src', fname + '_large' + ftype);
	
	// Validate images
	var test_src_small = banner_small.getAttribute('src');
	var test_src_large = banner_large.getAttribute('src');
	if ((test_src_small.indexOf('_small') != -1) && (test_src_large.indexOf('_large') != -1)) {
		banners_valid = true;
	}
}
	

// Change home banner depending on window size
// Make sure preloadBannerImages() has been run before running this function
function updateHomeBanner () {
	if (!banners_valid) return false;
	if (!document.getElementById) return false;
	if (!document.images) return false;
	
	// Get banner image
	var bannerImg  = document.getElementById('feature-banner');
	
	// Switch banners
	if (window_x < 960) {
		bannerImg.src = banner_small.src;
	} else {
		bannerImg.src = banner_large.src;
	}
}

//
// END of Code for swapping home banner images
//

// sIFR
// Not currently in use
/*
function replaceHeadings () {
	sIFR.replaceElement(named({sSelector:"body h1", sFlashSrc:"/assets/swf/myriad_condensed.swf", sColor:"#1b1b1b", sBgColor:"#FFFFFF"}));
}
*/

// Link highlighter for nav-secondary
// Red Gate JavaScript
function linkHighlight()
{
	var positions = getPathPositions(location.href);
	// alert(positions);
	// loop through each link to test it
	var count = document.links.length;
	var match1 = new RegExp("page", "");
	var match2 = new RegExp("basedir", "");
	var match3 = new RegExp("dir", "");
	var match4 = new RegExp("index", "");
	for (i = 0; i < count; i++)
	{
		
		if (document.links[i].className.match(match1))		// Class matches 'page'
		{
			
			if (urlsMatch(location.href, document.links[i].href, 0, positions))	// Is it a link to this page?
			{
				document.links[i].className += " on";
			}
		}
		else if (document.links[i].className.match(match2))	// Class matches 'basedir'
		{
			var urlLength = document.links[i].href.split("/").length;
			
			if (urlsMatch(location.href, document.links[i].href, urlLength - 2, positions)	// Check that the lefthand-most two directories match the current page
				&& document.links[i].href.split("/").length <= 	location.href.split("/").length			// Check that the link is a parent of the current one
				&& document.links[i].href.match(match4)							// Check that the link is to an index page
			)
			{
				document.links[i].className += " on";
			}
		}
		else if (document.links[i].className.match(match3))	// Class matches 'dir' (this is last because 'basedir' will also match 'dir')
		{
			if (urlsMatch(location.href, document.links[i].href, -2, positions)	// Check that the righthand-most directory name in the link is the same as in the current page
				&& document.links[i].href.split("/").length == location.href.split("/").length	// Check that there's the same number of directories
				&& document.links[i].href.match(match4)							// Check that the link is to an index page
			)
			{
				document.links[i].className += " on";
			}
		}
		
	}
	applyMouseCursor(); // loads the linkbox code below
}

addLoadEvent(linkHighlight);

// Linkboxes - turns the cursor into a hand/pointer if the user has javacsript enabled, so they know they can click on it
function applyMouseCursor() {
       try {
	   var divTags = document.getElementsByTagName( "div" );
	   var divTag;
	   var reg1 = new RegExp( "linkbox" );

	   for( var i=0; i<divTags.length; i++ ) {
	       divTag = divTags[i];
	       if (!divTag.className) continue;
	       if (!divTag.className.match( reg1 )) continue;
	       try {
		   divTag.style.cursor = "pointer";
	       } catch (e) {
		   // Some browsers don't understand "pointer"
		   divTag.style.cursor = "hand";
	       }
	   }
       } catch (e) {
	   // Gracefully fail on error
	   alert( e );
       }
}

/*
	Usage:
		positions = getPostions(url);

		if (urlsMatch(url, testUrl, level, positions) && (some other condition)) {
			// do something
		}

		where level is the number of directories you want to match
		if level is 0, the entire url needs to match

		Note that something that matches at level 2 will always match at
		level 1 as well so you might need to be careful with the order in
		which you process things as	you might otherwise get entertaining
		results.

*/

	function getPathPositions(url) {
		var pos = 0;
		positions = new Array();
		pathParts = url.split("/");
		count = pathParts.length;
		for (x = 0; x < count; x++) {
			pos = pos + pathParts[x].length + 1;
			positions[x] = pos;
		}
		return positions;
	}

	function urlsMatch(url, testUrl, level, positions) {
		// Debuigging lines
		//alert( 'URLS:\n' + url+ ' '+testUrl);
		//alert(document.links[i].href.split("/").length);
		if (testUrl.substr(0,1) == "/") {
			testUrl = testUrl.substr( 1 );
		}
		if (url.charAt( url.length-1 ) == "/") url = url + "index.html";
		if (level < 0) {
			level = positions.length + level;
		}
		if(level == 0) {
			return (url == testUrl);
		} else {
			// Debugging lines
			//alert('BD ' + url + ' ' +testUrl);
			//alert( 'SUBS:\n' +url.substr(0, positions[level])+' ' +testUrl.substr(0, positions[level]) );
			return (url.substr(0, positions[level]) == testUrl.substr(0, positions[level]))
		}
	}




// DOM-based rollovers
// Adds a rollover to any image with the class 'rollover'. The hover image is based on the image filename. The image my_picture.gif will on hover show
// the image my_picture_over.gif
// Rewritten to use JQuery 11 March 2009 by Theo Spears

function initRollovers() {
	$('img.rollover').each(function(key,elem) {
		var base_image = $(elem).attr('src');
		var hover_image = base_image.replace(/(\.[a-z]+)$/i, "_over$1");
		
		// Preload the image. If you do not assign this to a variable, IE6 does not preload.
		var preloadedImage = $('<img>').attr('src', hover_image);
		
		$(elem).hover(
			function() { $(this).attr('src', hover_image); },
			function() { $(this).attr('src', base_image); }
		);
		
	});
}

if(window.jQuery) {
	jQuery(document).ready(initRollovers);
}

// End of Red Gate JS