// AUXILIAR METHODS
// ----------------

String.prototype.contains = function(s)
{
	return (this.indexOf(s) != -1);
}

String.prototype.startsWith = function(s)
{
	return (this.indexOf(s) == 0);
}

var DOMAIN = "cattya.com";

// POSSIBLE DEFAULT BEHAVIORS
// --------------------------

// If the link:
//    * starts with http://DOMAIN
//    * starts with http://www.DOMAIN
//    * does not start with http://
//  then we deduce that is an INTERNAL link, and set target=''.
// Otherwise, it is EXTERNAL and we set target='_blank' for it.
function configureLinkByURL(anchor)
{
	var href = anchor.attr("href");

	if (href.startsWith("http://" + DOMAIN) ||
        href.startsWith("http://www." + DOMAIN) ||
	    !href.startsWith("http://")
	   )
	{
		anchor.attr("target", "");
	}
	else {
		anchor.attr("target", "_blank");
	}
}

// Set link as external.
function configureLinkExternal(anchor)
{
	anchor.attr("target", "_blank");
}

// Set link as internal.
function configureLinkInternal(anchor)
{
	anchor.attr("target", "");
}

// MAIN FUNCTION
// -------------

// Goes through all anchors and applies them the appropriate target.
// There is a default behavior, defined by a function that process a single
// anchor. The default behavior is established by choosing the function call.

// You can also have exceptional links, handled with three rel categories:
//    * targetblank: sets target='_blank'.
//    * targetnone: unsets target.
//    * targetinvert: inverts the default behavior.
// If more than one of these categories are present, only one
// will be taken into account. The former list indicates the priority, being
// the topmost the most prioritary.

function configureExternalLinks() {
	jQuery("a").each(function(index, anc) {
		anchor = jQuery(anc);
		if (anchor.attr("href")) {
			var rel = anchor.attr("rel");

			if (rel !== undefined) {
				if (rel.contains("targetblank")) {
					anchor.attr("target", "_blank");
				}
				else if (rel.contains("targetnone")) {
					anchor.attr("target", "");
				}
				else {
					// Uncomment one of these three default behaviors:

					// configureLinkInternal(anchor);
					// configureLinkExternal(anchor);
					   configureLinkByURL(anchor);

					if (rel.contains("targetinvert")) {
						if (anchor.attr("target") == "_blank") {
							anchor.attr("target", "");
						}
						else {
							anchor.attr("target", "_blank");
						}
					}
				}
			}
			else {
			   configureLinkByURL(anchor);
			}
		}
	});
}

jQuery(function() {
	configureExternalLinks();
});

