/*
 * Copyright (c) 2007 Publishing Technology, plc.
 *
 * Code licensed under the BSD License:
 * http://labs.ingenta.com/ijs/license.txt
 */
 
 
/**
 * The Ingenta Linking routines and utilities namespace
 */
Ingenta.Links = window.Ingenta || {};

/**
 * Regex matching IngentaConnect urls
 */
Ingenta.Links.DOMAIN_PATTERN = "http://[a-zA-Z\.]+.ingentaconnect.com/";
/**
 * Regex matching IngentaConnect title link urls
 */
Ingenta.Links.TITLE_PATTERN = Ingenta.Links.DOMAIN_PATTERN + "content/[a-zA-Z]+/[a-zA-Z0-9]+";

/**
 * Regex matching IngentaConnect article link urls
 */
Ingenta.Links.ARTICLE_PATTERN = Ingenta.Links.TITLE_PATTERN + "/[0-9]+/[a-zA-Z0-9]+/[a-zA-Z0-9]+/[a-zA-Z0-9]+";

/**
 * Link matcher function that tests for articles
 *
 * @param {String} href A URL to be tested
 */
Ingenta.Links.articleMatcher = function(href) {
  return href.match( Ingenta.Links.ARTICLE_PATTERN );
}

/**
 * Link matcher function that tests for links to IngentaConnect
 *
 * @param {String} href A URL to be tested
 */
Ingenta.Links.domainMatcher = function(href) {
  return href.match( Ingenta.Links.DOMAIN_PATTERN );
}

/**
 * Link matcher function that matches ALL links
 *
 * @param {String} href A URL to be tested
 */
Ingenta.Links.alwaysMatcher = function(href) {
  return true;
}

/**
 * Link processor callback function used for debugging
 *
 * @param {DOMNode} anchor Anchor node
 * @param {String} href The URL extracted from the anchor
 */
Ingenta.Links.debugCallback = function(anchor, href) {
  alert("Element: " + anchor + " href: " + href);
}

/**
 * Link Processor
 *
 * Supports walking through all anchors in a document, applying the 
 * supplied matcher to each link. If the matcher returns true, then the 
 * callback is invoked, passing in the node reference and (as a convenience) 
 * the href.
 *
 * @param {Object} match Matcher function
 * @param {Object} callback Callback function
 * @constructor
 */
Ingenta.Links.LinkProcessor = function(matcher, callback) {
   this.matcher = matcher;
   this.callback = callback;
}

/**
 * Process links in a document, according to the previously supplied 
 * matching rules and callback.
 */
Ingenta.Links.LinkProcessor.prototype.process = function() {

    anchors = document.getElementsByTagName('a');

    for (var i=0, anchor; anchor = anchors[i]; i++)
    {
      var href = anchor.href;
      if ( this.matcher(href) )
      {
        this.callback(anchor, href);
      }
    }

}

