//LINK PROCESSOR FOR EXTERNAL AND FILE LINKS
//Sets link target for external and media file links
//Requires jQuery
jQuery(document).ready(function($){
	$('a').each(function(){

		//For each link, find the URL, convert to lowercase, and strip whitespace
		url=$.trim(this.href.toLowerCase());
		//Remove the query string and hash tag (if any)
		urlShort=url;
		if (urlShort.lastIndexOf('#')!=-1) {
			urlShort=url.substr(0,url.lastIndexOf('#'));
		}
		if (urlShort.lastIndexOf('?')!=-1) {
			urlShort=urlShort.substr(0,urlShort.lastIndexOf('?'));
		}
		
		if (urlShort=='' || url.indexOf('mailto:')==0 || url.indexOf('javascript:')==0){
			//Do nothing with links with no destination, or links to the same page with a new query string or fragment
			//Do nothing with mailto links
			//Do nothing with JavaScript links
		} else if (urlShort.substr(urlShort.length-4)=='.pdf' || urlShort.substr(urlShort.length-4)=='.doc' || urlShort.substr(urlShort.length-5)=='.docx' || urlShort.substr(urlShort.length-4)=='.xls' || urlShort.substr(urlShort.length-5)=='.xlsx' || urlShort.substr(urlShort.length-4)=='.ppt' || urlShort.substr(urlShort.length-5)=='.pptx'){
			//PDFs, Word Docs, Excel Spreadsheets, PowerPoints
			$(this).attr('target','_blank');
		} else if(url.indexOf('://')>0){
			//Test above excludes links without a protocol (like http://), since they can't be external
			
			//Find the host of the link destination (without any port number)
			urlHost=url.substr(url.indexOf('://')+3);
			if (urlHost.indexOf('/')!=-1){
				urlHost=urlHost.substr(0,urlHost.indexOf('/'));
			}
			if (urlHost.indexOf(':')!=-1){
				urlHost=urlHost.substr(0,urlHost.indexOf(':'));
			}
			urlHost=$.trim(urlHost);
			
			//Find the host of the current page (without any port number, and without a 'www.' prefix)
			host=window.location.host;
			if (host.indexOf(':')!=-1){
				host=host.substr(0,host.indexOf(':'));
			}
			if (host.indexOf('www.')==0){
				host=host.substr(4);
			}
			host=$.trim(host.toLowerCase());
			
			if (!(urlHost==host || (urlHost.length>=host.length+2 && urlHost.indexOf(host)==urlHost.length-host.length && urlHost.charAt(urlHost.length-host.length-1)=='.') || urlHost=="fkhealth.com")){
				//If the host of the link is not the same as (or a subdomain of) the current page host
				//And if the host of the link is not the domain of the main site
				//Set external links to open in a new window
				$(this).attr('target','_blank');
			}
		}
	});
});
