/* 
	JQuery Externalify 0.2
	by Aaron Lozier (lozieraj-[at]-gmail.com) (Twitter: @ajlozier)
	version 0.2
		* "confirm function" and "before leave" function added
	
	* 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
 
	Basic Usage:
	
	$('a').externalify();
*/

(function(jQuery){
 jQuery.fn.externalify = function(options) {
    
	var defaults = {
		addClass: 'external',							//add class
		addRel: 'external',								//add rel parameter
		confirmFunction: true,
		beforeLeave: true,
		openNewWindow: true
	};
  
	var options = jQuery.extend(defaults, options);
	
	return this.each(function() {
	
		obj = jQuery(this);
		if(is_external(obj.attr('href'))){

			obj.click(function(){
				var thisEl = jQuery(this);	
				
				if(typeof(options.confirmFunction)=='function'){
					var confirm = options.confirmFunction();
				} else {
					var confirm = options.confirmFunction;
				}
				
				if(confirm){
					
					if(typeof(options.beforeLeave)=='function'){
						var beforeLeave = options.beforeLeave();
					} else {
						var beforeLeave = options.beforeLeave;
					}
					
					if(beforeLeave){
						if(options.openNewWindow){
							window.open(thisEl.attr('href'));
							return false;			
						} else {
							return true;
						}
					} else {
						return false;
					}
				} else {
					return false;
				}
				
			});
			
			if(options.addClass){
				obj.addClass(options.addClass);
			}
			
			if(options.addRel){
				obj.attr('rel',options.addRel);
			}
		}
		
		/* PARSING FUNCTIONS */
		
		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);