﻿(function ($) {

	$.fn.externalLinks = function (options) {

		var settings = { mode: 'externalLinks' };

		return this.each(function () {

			if (options) {
				$.extend(settings, options);
			}

			function isLocal(url) {
				// if begins with 'http://'
				if (url.substring(0, 7).toLowerCase() == 'http://') {
					var $localURLs = [	'http://localhost',
										'http://www.gravity-insight.com',
										'http://gravity-insight.com',
										'http://gravity.flyingatom.everycity.co.uk'];

					for (var j = 0; j < $localURLs.length; j++) {
						var localUrl = $localURLs[j];
						var result = url.substring(0, localUrl.length);
						if (result.toLowerCase() == localUrl.toLowerCase())
							return true;
					}

					return false;
				}
				else
					return true;
			}

			if (settings.mode == 'externalLinks') {
				// if url is external and doesn't alrady have a target attribute
				if ($(this).is('a[href]') && $(this).not('a[target]')) {
					var url = $(this).attr('href');
					if (!isLocal(url)) {
						$(this).attr('target', '_blank');
					}
				}
			}
			else if (settings.mode == 'all') {
				if ($(this).is('a[href]') && $(this).not('a[target]')) {
					$(this).attr('target', '_blank');
				}
			}

		});

	};
})(jQuery);

