function renderDialog(href, target){
	var link = "<a id=\"exit_anchor\" href=\"" + href + "\" ";
	if (target != "" && target != null) {
		link += "target=\"" + target + "\" ";
	}
	link += ">" + href + "</a>";
	
	var content = "Click the link to access " + link + " ";
	if (target != "" && target != null) {
		content += "(link opens in a new window)";
	}
	content += "<br/><br/>We hope your visit was informative and enjoyable.";

	$("#exit_div").html(content);
}

//a parsed URL
function UrlInfo(url) {
  var setProperties = function(url) {
	  var protocolPos = url.indexOf("://") + 3;
	  if (protocolPos > 0) {
	  	that.protocol = url.substr(0, protocolPos - 3);
	  }
	
	  var ret =  url.substr(protocolPos, url.length - protocolPos);
	  var slash = ret.indexOf("/");
	  var qmark = ret.indexOf("?");
	  if (qmark < 0)  qmark = Math.max() * -1; //why is max a negative #... very strange
	  
	  var pos = (slash <= qmark) ? slash : qmark;
	  
	  if (pos> 0) {
	  	that.host = ret.substr(0, pos);
	  	that.pathAndQuerystring= ret.substr(pos, ret.length - pos); 
	  } else {
	  	that.host = ret;
	  }
		  		
	  var dot = that.host.lastIndexOf(".");
	  if (dot > 0) {
	    that.extension = that.host.substr(dot + 1);
	  }
	  
	  return url;
  };

  var that = this; // workaround to ecmascript bug that enables setting public properties in 'private' method setProperties 
  this.protocol = "";
  this.host = "";
  this.pathAndQuerystring = "";
  this.extension = "";
  this.fullUrl = setProperties(url);
}

// Creating custom :external selector
$.expr[':'].external = function (obj) {
  return (obj.hostname != location.hostname && obj.href.indexOf("javascript") < 0);
};

$(document).ready(function () {

  try {
	  // Add 'external' CSS class to all external links - try/catch to avoid edit mode errors.
	  $('a:external').addClass('external');
  } catch (err) { }

  $(".external").click(function (d, e) {
  	var url = new UrlInfo($(this).attr("href"));
  	if (url.host == "www.addthis.com") return true; 
  	
    if(url.host != "")
    {
	    var showModal = !(url.extension == "gov" || url.extension == "gov:8001" || url.extension == "mil" || url.host == "service.govdelivery.com" || url.host == "www.youtube.com" || url.host == "www.flickr.com");
		var newWindow = $(this).attr("target") != null && $(this).attr("target") != "";
		
	    if (!showModal) {
	    	if (newWindow) {
	    		window.open(url.fullUrl);
	    	} else {
		      location.open(url.fullUrl);
		    }
	    } else {
		  renderDialog(url.fullUrl, $(this).attr("target"));
		  
	      $("#exit_div").dialog({ modal: true, closeOnEscape: true, height: 275, width: 375, autoOpen: false });
	      $("#exit_div").dialog('open');
	    }
	    return false;
    }
  });

  $("#exit_anchor").live("click", function () {
  	$("#exit_div").dialog('close');
  });

});
