/**
 *  _speedbump.js
 *  @Author: Paul McLanahan <paul.mclanahan at digitalinsight dot com>
 *      with a lot of code from  Stuart Langridge's NiceTitles at http://kryogenix.org/
 *  @Usage: Simply add the following line to the <head> of your HTML page and this script
 *      will seek out all links that point to a 3rd party domain and add a 3rd party Speed Bump (SB)
 *      to them.  All that's really required of you is that you add elements to the 'allowedDomains'
 *      array to tell the script which links to ignore.
 *  @Code: <script language="JavaScript" type="text/javascript" src="/path/to/script/_speedbump.js"></script>
 *  @CSS: The class for the SB <div> will be 'speedbump', so you may style accordingly. The following style elements
 *      are set by the JS, so you don't need to worry about them.
 *          d.style.position = 'absolute';
 *          d.style.width = '<sbWidth>px'; // where <sbWidth> is the variable below
 *          d.style.top = <link_position - SB height + sbYOffset>; // where <link_position is the calclated y position of the link relative to the page, which is added to sbYOffset> which is a variable below.
 *          d.style.left = <link_position + sbXOffset>; // where <link_position is the same as above, and sbXOffset> is a variable below.
 *      The rest of the CSS should go in _styles.css and in a declaration that looks like:
 *          div.speedbump{
 *              border:2px solid #685539;
 *              background:#fff;
 *              padding:5px;
 *              etc...
 *          }
 *      But using your own values for the actual styles of course.
 *      You may then style any elements you add to the 'sbContent' variable below using the following example:
 *          div.speedbump h2{
 *              color: #685539;
 *              font-size: 2em;
 *              letter-spacing: 3px;
 *              etc...
 *          }
 */

/////// start configuration ////////////

var debug = false; // set to true to show an alert on page load with all links that will have the SB added.
var sbXOffset = -100; // x offset. This is only used if sbCentered is false.  Negative number means move left, positive means right. If 0 the left side of the SB will line up with the leftmost part of the link.
var sbYOffset = -10; // y offset. Negative number means move up, positive means down. If 0 the bottom of the SB will align with the top of the link. This also sets how far the top of the SB is from the top of the window.
var sbWidth = 315; // width of the SB div
var sbCentered = true; // whether or not to center the SB on the page. If false, the SB will be aligned relative to the link.
var openInNewWindow = false;  // whether or not to open the 3rd party links (TPLs) in new windows. This should always be false unless specifically asked for by the FI!
var allowedDomains = [ // array containing strings which, if any one is found in a link, will cause the SB not to be added to said link.
	"javascript", // DO NOT REMOVE. This will find all links that use JavaScript in the href and ignore them.
	"metcapbank"  // add your FI's domain here.
];

// Edit the html in the 'sbContent' variable below to modify the contents of the SB div.
// Place the string ##SBLINK## inside an <a> tag (example below). ##SBLINK## will be replaced by the necessary 'href' and/or 'onclick' attributes.
var sbContent = '';
sbContent += '<div class="speedbumpIB"><img src="'+(document.location.href.indexOf('/site/')==-1?'':'../')+'images/logo.gif" width="309" height="50" alt="" border="0">';
sbContent += '<h2>Third Party Site Disclaimer</h2>';
sbContent += '<p>By accessing the noted link you will be leaving your financial institution\'s website and entering a website hosted by another party. Your financial institution has not approved this as a reliable partner site.  Please be advised that you will no longer be subject to, or under the protection of, the privacy and security policies of your financial institution\'s website. We encourage you to read and evaluate the privacy and security policies of the site you are entering, which may be different than those of your financial institution\'s.</p>';
sbContent += '<div align="center" class="sblinks"><a ##SBLINK##>Continue</a>&nbsp;&nbsp;<a href="#" onclick="hideSpeedBump();return false;">Decline</a></div></div>';

/////// end configuratin ////////////////
/////// do not edit below this line /////

addEvent(window, "load", makeSpeedBumps);

var XHTMLNS = "http://www.w3.org/1999/xhtml";
var CURRENT_SPEEDBUMP;

function makeSpeedBumps(){
	if (!document.createElement || !document.getElementsByTagName) return;
	// add namespace methods to HTML DOM; this makes the script work in both
	// HTML and XML contexts.
	if(!document.createElementNS){
	    document.createElementNS = function(ns,elt){
	        return document.createElement(elt);
	    }
	}
	// do our best to get the links[] array.
	if( !document.links ){
	    document.links = document.getElementsByTagName("a");
	}
	if(document.links){
		if(debug)var out = "Links to which SBs will be attached:\n------------------------------------------\n";
		// test every link
		for(i=0;i<document.links.length;i++){
			var isTPL = true;
			var lnk = document.links[i];
			if(lnk.href){
				// test every allowedDomain against every link with an href attrib.
				for(j=0;j<allowedDomains.length;j++){
					// if we get a hit, call it not a TPL and stop the loop
					if(lnk.href.toLowerCase().indexOf("http") != 0 || lnk.href.indexOf(allowedDomains[j]) > -1){
						isTPL = false;
						break;
					}
				}
				// if it didn't match any allowedDomains, add the SB stuff
				if(isTPL){
					if(debug)out += "-> " + lnk.href + "\n";
					lnk.setAttribute("speedbump",lnk.href);
					lnk.setAttribute("href","javascript:void(0);");
		            addEvent(lnk,"click",showSpeedBump);
		            addEvent(lnk,"mouseover",fakeStatus);
		            addEvent(lnk,"mouseout",clearStatus);
				}
			}
		}
		if(debug)alert(out);
	}
}

function showSpeedBump(e) {
	hideSpeedBump();
	if(lnk = getLnkObj(e)){
	    lnkPos = findPosition(lnk);
	    lnkPosX = lnkPos[0];
	    lnkPosY = lnkPos[1];
		
		// create the DIV via the DOM
		var d = document.createElementNS(XHTMLNS,"div");
	    
		// add styles
		d.className = "speedbump";
		d.style.width = sbWidth + 'px';
		d.style.position = 'absolute';
		
		// calculate the left position. Either centered or relative to the link
	    if (sbCentered && document.body && document.body.offsetWidth) {
	    	d.style.left = ((document.body.offsetWidth - sbWidth)/2) + 'px';
		}
		else{
			d.style.left = (lnkPosX+sbXOffset) + 'px';
		    if (document.body && document.body.offsetWidth && ((lnkPosX+sbWidth) > document.body.offsetWidth)) {
		        d.style.left = (document.body.offsetWidth - sbWidth - 0) + "px";
		    }
		}
		
		// add the sbContent
		var reSBLink = /##SBLINK##/g;
		var sbHREF = lnk.getAttribute("speedbump");
		var sbATag = openInNewWindow ? 'href="#" onclick="window.open(\'' + sbHREF + '\');hideSpeedBump();return false;"' : 'href="' + sbHREF + '" onclick="document.location.href=this.href;hideSpeedBump();return false;"';
		d.innerHTML = sbContent.replace(reSBLink,sbATag);
		
		// append the DIV to the body of the document
	    document.getElementsByTagName("body")[0].appendChild(d);
		
		// calculate the top position of the div by getting its height after the sbContent is in
		if(d.offsetHeight){
			// if we can get the height of the div, then use it
			var dTop = lnkPosY - d.offsetHeight + sbYOffset;
		}
		else{
			// otherwise, we'll guess that they'll be 250px high on average
			var dTop = lnkPosY - 250 + sbYOffset;
		}
		d.style.top = dTop + 'px';
				    
		// scroll the window such that the top of the SB is sbYOffset from the top of the window
		window.scrollTo(0,dTop + sbYOffset);
		
		CURRENT_SPEEDBUMP = d;
	}
	return false;
}

function hideSpeedBump() {
    if (!document.getElementsByTagName) return;
    if (CURRENT_SPEEDBUMP) {
        document.getElementsByTagName("body")[0].removeChild(CURRENT_SPEEDBUMP);
        CURRENT_SPEEDBUMP = null;
    }
}

function fakeStatus(e){
	if(lnk = getLnkObj(e)){
	//	alert("Link to: "+lnk.getAttribute("speedbump"));
	    window.status = lnk.getAttribute("speedbump");
		return true;
	}
	else{
	    window.status = 'Third Party Website';
		return true;
	}
}

function clearStatus(e){
	window.status = '';
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}

function getLnkObj(e){
	if(!document.getElementsByTagName) return false;
	if(window.event && window.event.srcElement) {
		lnk = window.event.srcElement
	}
	else if(e && e.target){
		lnk = e.target;
	}
	if(!lnk) return false;
	if(lnk.nodeName.toUpperCase() != "A") {
		// lnk is a textnode -- ascend parents until we hit a link
		lnk = getParent(lnk,"A");
	}
	if(!lnk) return false;	
	return lnk;
}

function findPosition( oLink ) {
	if( oLink.offsetParent ) {
		for( var posX = 0, posY = 0; oLink.offsetParent; oLink = oLink.offsetParent ) {
			posX += oLink.offsetLeft;
			posY += oLink.offsetTop;
		}
		return [ posX, posY ];
	} else {
		return [ oLink.x, oLink.y ];
	}
}

// Add an eventListener to browsers that can do it somehow.
// Originally by the amazing Scott Andrew.
function addEvent(obj, evType, fn){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, true);
//		if(debug)alert("obj.addEventListener worked");
		return true;
	}
	else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
//		if(debug)alert("obj.attachEvent worked");
		return r;
	}
	else if (document.getElementById){
		// feeble attempt to get this to work in IE for Mac
//		if(debug)alert("obj.on"+evType+"=fn worked");
		eval("obj.on"+evType+"=fn");
	}
	else{
		if(debug)alert("addEvent won't work");
		return false;
	}
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}