/*
 * Created on Mar 3, 2009 by plucas/thoward: fixed CVSITE-2002
 * This function improves upon a previous solution implemented in footer.html and footer1024.html (aka function linkFix).
 * Overview:
 * As an <a> is clicked, this function determines if the link is external (compares hosts).
 * If it is external, then:
 *  1. Its 'target' attribute is changed to '_blank' to open the link in a new window.
 *  2. The URL '/includes/track_click.jsp' is invoked, which handles the SQL query to store the external link. Note: This JSP was implemented well before this new feature.
 * 
 * For performance reasons, the SQL query is invoked asynchronously. This does require that the link be opened in a new window.
 * At the time this ticket was fixed, this behavior had already been requested and implemented.
 */
 function externalizeLink(eventObject) {
	/*
	 * This regex is compliments of jQuery plugin:
	 * 			http://projects.allmarkedup.com/jquery_url_parser/
	 */
	var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

	var uriInfo = parser.exec(decodeURI(window.location));
	// 0=source, 1=protocol, 2=authority, 3=userInfo, 4=user, 5=password, 6=host, 7=port, 8=relative, 9=path, 10=directory, 11=file, 12=query, 13=anchor
	var serverHost = uriInfo[6];

	// kick off AJAX call to track the click (note: JSP handles both internal and external links, and contains the SQL)
	if (isExternalLink(this.href, serverHost)) {
		ajax_InvokeTrackClick(this.href);
                if(jQuery(this).hasClass('targetSelf')){
                  jQuery(this).attr('target', '_self');
                }else{  
                        jQuery(this).attr('target', '_blank');
               }
	}
}

/*
 * Helper method called by externalizeLink.
 * Params:
 * 		href: The link to be checked (value of 'href' attribute for DOM element <a>)
 *		serverHost: The host of the server (as opposed to the server of 'href' parameter)
 */
function isExternalLink(href, serverHost) {
	/*
	 * This regex is compliments of jQuery plugin:
	 * 			http://projects.allmarkedup.com/jquery_url_parser/
	 */
	var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

	var linkInfo = parser.exec(decodeURI(href));
	// 0=source, 1=protocol, 2=authority, 3=userInfo, 4=user, 5=password, 6=host, 7=port, 8=relative, 9=path, 10=directory, 11=file, 12=query, 13=anchor
	var hrefSource = linkInfo[0];
	var hrefHost = linkInfo[6];

	// console.log("------------------------------------------");
	// console.log("href = " + href);
	// console.log("serverHost = " + serverHost);
	// console.log("hrefSource = " + hrefSource);
	// console.log("hrefHost = " + hrefHost);
	// console.log("\t" + "hrefHost != serverHost = " + (hrefHost != serverHost));
	// console.log("\t" + "hrefHost != '' = " + (hrefHost != ''));
	// console.log("\t" + "!isStartsWith(hrefSource, '#') = " + !isStartsWith(hrefSource, '#'));
	// console.log("\t" + "!isStartsWith(hrefSource, 'javascript', true) = " + !isStartsWith(hrefSource, 'javascript', true));

	return hrefHost != '' // relative path indicates internal link
			&& !isStartsWith(hrefSource, '#') // intra-page links are certainly internal
			&&  hrefHost != serverHost // hosts must match
			&& !isStartsWith(hrefSource, 'javascript', true); // assume javascript-href is internal
}

/*
 * Helper function called by isExternalLink.
 */
function isStartsWith(str, startsWith, caseSensitive) {
	if (caseSensitive == true) {
		return (startsWith == str.substring(0, startsWith.length));
	} else {
		return (startsWith.toLowerCase() == str.substring(0, startsWith.length).toLowerCase());
	}
}

/*
 * Helper function called by externalizeLink.
 * Encapsulates invocation of URL '/includes/track_click.jsp'.
 * See discussion in comment for externalizeLink concerning requirements for this call to be made asynchronously.
 * Parameters:
 * 		eventObject: The jQuery event object (generated by the click action)
 */
function ajax_InvokeTrackClick(p_href) {

	jQuery.ajax({
		type: "GET",
		async: true,
		url: "/includes/track_click.jsp",
		dataType: "html",
		data: { href: p_href }
	});
}


/*
 * Explanation:
 * This is our first use of the jQuery live() feature, which allows us to define an event delegate instead of binding to individual elements.
 * This has several benefits:
 * 	1. More scalable. jQuery docs cite this site as a reference: http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/
 *  2. Works better with asynchronous DOM. This is especially important, given that a bind()-based solution would have to be re-invoked whenever the DOM was modified (eg: Keyfacts data on hub page)
 * 
 * Here's how it works:
 * We use live() to register the 'externalizeLink' function on all <a> tags (we do a live binding of ).
 * That method converts the target=_blank for the clicked link only if it's an external link.
 * By converting *each* <a> in DOM, we guarantee that the specific link that was clicked will open in a new window (when browser handles navigation immediately after this method completes).
 */
// as per documentation, live() may only be called on a selector (not individual elements), which is the desired functionality
jQuery('a').live('click', externalizeLink);
