
function addLoadEvent(functionToAdd) {
  var oldOnload = window.onload; 
  if (typeof window.onload != 'function') { 
    window.onload = functionToAdd; 
  } else { 
    window.onload = function() {
      oldOnload(); 
      functionToAdd(); 
    }
  }
}

/*
 *  Attach an event handler to any anchor or area tag that requests an external site.  An external 
 *  site is determined by the current host and context.  Must determine if external here
 *  because this is where we cancel the anchor tag onclick functionality.
 */
function initializeExternalNavigation() { 
  if (document.getElementsByTagName) {
    var nav1 = document.getElementsByTagName('A');
    var nav2 = document.getElementsByTagName('AREA');
  } else if (document.all) {
    var nav1 = document.all.tags('A');
    var nav2 = document.all.tags('AREA');
  } else {
    return;	
  }
  // determine current host and context root
  var currenthost = window.location.host;
  var currentContext = currenthost + getContextRoot();
  // process the HREF attributes of all the navigation tags
  processHrefs(currentContext, nav1);
  processHrefs(currentContext, nav2);
}

/*
 * Process the HREF attributes of the given tags and attach a JavaScript function to the onlick
 * event that check the given URL to see if it is an external or internal link and perform navigation
 * or display the speedbump.
 */
function processHrefs(currentContext, xNav) {
  for (var i = 0; i < xNav.length; i++) {	//this is outside, could be a  javascript method or an http call doesn't matter
    var href = xNav[i].href;
    var target = xNav[i].target;
    //add if not null, not in context and not mailto
    if (href != null && href.indexOf(currentContext) == -1 && href.toLowerCase().indexOf("mailto:") == -1 && href.toLowerCase().indexOf("javascript:") == -1) {
      //transert the object in a valid format
      var validCall = xNav[i].href.replace("\"", "\\\"");
      if (xNav[i].onclick == null || xNav[i].onclick == "") {
        //alert('inserting onclick event for' + href);
        xNav[i].onclick= new Function("leavingSite(\"" + validCall + "\", \"" + target + "\");return false;");			  	
      }
    }//if..else
  }//for
}



var popUpWindow;
function popupWindow(url, width, height, status) {
  // close the existing window
  if (!status || status == null) {
    closeWindow = true;
  } else {
    closeWindow =  false;
  }
  if (closeWindow == true) {
    if (popUpWindow && !popUpWindow.closed) {
      popUpWindow.close();	
    }  
  }
  if (!width || width == null) {
    popupWidth = 552;
  } else {
    popupWidth = width
  }
  if (!height || height == null) {
    popupHeight = 581;
  } else {
    popupHeight = height
  }
  popupLeftLoc= (window.screen.width - popupWidth) / 2;
  popupTopLoc = (window.screen.height - popupHeight) / 2;
  return popUpWindow = window.open(url, "_blank", "width=" + popupWidth + ",height=" + popupHeight + ",left=" + popupLeftLoc + ",top=" + popupTopLoc + ",buttons=no,scrollbars=yes,location=no,menubar=no,resizable=yes,status=no,directories=no,toolbar=no"); 
}

function sendToUrl(destinationUrl) {
  if (popUpWindow && !popUpWindow.closed) {
    popUpWindow.close();	
  }  
  window.top.location.href= destinationUrl;
}


/*
 * Open Window function that incorporates speedbump functionality.  Use this function in the application
 * instead of window.open() so that the speedbump will be displayed if the new window is opening an
 * external web site.
 *
 */
function openWindow(url, windowName, windowFeatures) {
  if(urlIsExternal(url) && isNavigableProtocol(url)) {
    // the url is an external site
    return leavingSite(url, null, windowName, windowFeatures);    
  } else {
    // url is an internal link or non-http protocol (e.g. javascript:)
    return performLeavingNavigation(false, url, null, null, windowName, windowFeatures);	
  }
}

/*
 * Check whether given URL leaves the current host and context root (i.e. it is external)
 */
function urlIsExternal(url) {
  var currenthost = window.location.host;
  var currentContext = currenthost + getContextRoot();
  if (url != null && url.indexOf(currentContext) == -1 && url.indexOf(contextPath) == 0) {
    return false;
  } else {
    return true;
  }
}


/*
 * Check whether the given URL includes a navigable protocol (i.e. not javascript:)
 */
function isNavigableProtocol(url) {
  if (url != null &&
      url.toLowerCase().indexOf("mailto:") == -1 && 
      url.toLowerCase().indexOf("javascript:") == -1) {
    return true;
  } else {
    return false;
  }
}

var currentTarget = null;
var currentExternalLink = null;
var currentWindowName = null;
var currentWindowFeatures = null;
var navToggle = false;
var timer = null;
/**
 * trap all navigation that is trying to go outside of the web site.  
 * notify user of external navigation request. 
 */
function leavingSite(element, target, windowName, windowFeatures) {    
  currentExternalLink = element;
  currentWindowName = windowName;
  currentWindowFeatures = windowFeatures;
  currentTarget = target;
  var url = "/credit/speedbump/service?destination=" + currentExternalLink;
  window.status = 'Opening page ' + currentExternalLink;		
  // set timeout so that navigation will happen automatically if response does not come back
  timer = setTimeout("performLeavingNavigation(false,'" + element + "',null,'" + target + "','" + windowName + "','" + windowFeatures + "')",3000);		
  // if timeout occurred and navigation already underway, then just quit
  if (navToggle == true) {
    navToggle = false;
    window.status = '';
    return;
  }
  // make Ajax request to determine if speedbump should show
  new Ajax.Request(url, {
    method:'get',
    requestHeaders: {Accept: 'application/json'},
    onSuccess: function(transport) { 
      var response;
      try {
        // get json response data
        response = transport.responseText.evalJSON(true);
      } catch (exception) {          
        // on exception go ahead with navigation
        return performLeavingNavigation(false, element, null, target, windowName, windowFeatures);
      }
      if (response != null) {
        if (response.speedbumpSearch.errors != null && response.speedbumpSearch.errors.length != 0) {
          // on error condition go ahead with navigation
          return performLeavingNavigation(false, element, null, target, windowName, windowFeatures);
        } else {          
          // perform navigation with response data
          return performLeavingNavigation(response.speedbumpSearch.showSpeedbump, element, response.speedbumpSearch.thirdPartySite, target, windowName, windowFeatures);
        }
      }        
    },
    onFailure: function(transport) {
      // on failure go ahead with navigation
      return performLeavingNavigation(false, element, null, target, windowName, windowFeatures);        
    }
  });	  	
  return;
}

/*
 * Perform navigation - either show the speedbump popup, open link in new window, or forward parent
 * window to destination link.
 */
function performLeavingNavigation(showPopup, externalLink, thirdPartySite, target, windowName, windowFeatures) {  
  // if timeout occurred and navigation already underway, then just quit
  if (navToggle == true) {
    reinitialize();
    window.status = '';
    return;
  }
  // flip toggle so that this function won't be called multiple times concurrently
  navToggle = true;
  
  if (showPopup == 'true' || showPopup == true) {
    //'relative position, null width, 100 px from top
    //showPopWin(contextPath + "/leavingSite.do?locationCode=" + locationCode + "&destination=" + externalLink + "&thirdPartySite=" + thirdPartySite, 500, 400, null, "relative", null, 100);
    window.top.status = 'Leaving Site...';
    confirm(externalLink + "&thirdPartySite=" + thirdPartySite);
  } else if (windowName != null && windowName != 'undefined' && windowFeatures != null && windowFeatures != 'undefined') {	  	  	
    var newWindow = window.open(externalLink, windowName, windowFeatures);
    reinitialize();
    return newWindow;
  } else if (target != null && target != '' && target != 'undefined') {
    var targetWindow = eval("window.top.frames['" + target + "']"); 	  	  	  
    if (targetWindow == null || targetWindow == 'undefined') {
      targetWindow = window.open(externalLink, target, '');
    } else {
      targetWindow.location.href = externalLink;
    }
    reinitialize();
    return targetWindow;
  } else {
    window.location.href = externalLink;
    reinitialize();
  }		
  return;
}

/**
 * Re-initialize variables
 */
function reinitialize() {
  navToggle = false; 		
  if (timer && timer != null) {
    clearTimeout(timer);
  }
}

/**
 * Will close the leaving window when we have confirmed that it loaded properly. 
 */
function leavingSiteConfirm(link) {     
    window.top.hidePopWin();
    window.top.status = '';    
		if(link == null){
		  window.top.reinitialize();
			return;
		}									
		if(link.indexOf("http") > -1){		
		  if (window.top.currentWindowName != null && window.top.currentWindowFeatures != null)
		  {
		    var win = window.open(link, window.top.currentWindowName, window.top.currentWindowFeatures);	
   		  window.top.reinitialize();
		    return win;
		  }
      else if (window.top.currentTarget != null && window.top.currentTarget != '' && window.top.currentTarget != 'undefined')
     	{
	      var targetWindow = eval("window.top.frames['" + window.top.currentTarget + "']"); 	  	  	  
	      if (targetWindow == null || targetWindow == 'undefined')
	      {
	        targetWindow = window.open(window.top.currentExternalLink, window.top.currentTarget, '');
	      }
	      else
	      {
	        targetWindow.location.href = window.top.currentExternalLink;
	      }
	      window.top.reinitialize();
	      return targetWindow;
	    }
		  else
		  {		    
			  window.top.location.href = link;
			}
		}else{
			eval(link);
		}//if..else				
    window.top.reinitialize();
		return;
}

function getContextRoot() {
  return '/credit';
}