/* 
	JQuery Externalify
	by Aaron Lozier (lozieraj-[at]-gmail.com)
	Feb 20, 2009 
	
	* Binds a click event to all anchor tags passed to it which evaluates whether or not the href is a part of the current domain or not.
	* If it is, returns true and click is treated normally.
	* If not, location is opened in a new window.
	* No options at this time.
	* Wishlist: New window parameters and/or ability to create custom callbacks.
		
	Project Page:	
		* http://informationarchitech.com/externalify/
		
	Dependencies:
		* jQuery 1.2.x
 
	Usage:
	
	$('a').externalify();
*/

(function(jQuery){
 jQuery.fn.externalify = function(options) {
    
	var defaults = {
		addClass: 'external',							//add class
		addRel: 'external',								//add rel parameter
		openNewWindow: true
	};
  
	var options = jQuery.extend(defaults, options);
    
	return this.each(function() {
	
		obj = jQuery(this);
		
		if(is_external(obj.attr('href'))){
			if(options.addClass){
				obj.addClass(options.addClass);
			}
			if(options.addRel){
				obj.attr('rel',options.addRel);
			}
		}
		
		if(options.openNewWindow){
			obj.click(function(){
				var thisEl = jQuery(this);			
				if(is_external(thisEl.attr('href'))){
					window.open(thisEl.attr('href'));
					return false;
				} else {
					return true;
				}
			});
		}
		
		function isolate_site(the_url){		
			try{	
				var first_split = the_url.split("//");
				var without_resource = first_split[1];
				var second_split = without_resource.split("/");
				var the_site = second_split[0];
				return the_site;
			} catch(e) {
				return false;
			}
		}
		
		function isolate_domain(the_site){
			var num_parts = the_site.split(".").length;
			var parts = the_site.split(".");
			if(num_parts > 1){
				the_domain = parts[num_parts-2] + '.' + parts[num_parts-1];
			}
			return the_domain;	
		}	
		
		function is_external(the_url){							
			the_site = isolate_site(the_url);
			if(the_site){
				the_site_domain = isolate_domain(the_site);
				this_domain = isolate_domain(document.domain);
				if(the_site_domain != this_domain){
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}	
		
	});
 };
})(jQuery);