// 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.getAttribute("href");

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

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

// Set link as internal.
function configureLinkInternal(anchor)
{
	anchor.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() {
	if (!document.getElementsByTagName)
		return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];

		if (anchor.getAttribute("href"))
		{
			var rel = anchor.getAttribute("rel");

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

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

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

window.onload = configureExternalLinks;
