/**
 * Pager Class
 */
Pager = new Class({
    /**
     * Constructor
     *
     * @param string, the base url, corresponds with the php constant BASE_URL
     */
    initialize: function(base_url) {
        this.base_url = base_url;
 
        this.parseExternalLinks();
    },
 
    /**
     * @param Element, optional HTML element
     * @return void
     */
    parseExternalLinks: function(root) {
        if (! $type(root)) {
            root = $(document.body);
        }

        // get all anchors and loop through them
        var anchor_arr = root.getElements('a');
        for (var i = 0; i < anchor_arr.length; i++) {
            var url = this.getAnchorUrl(anchor_arr[i]);

            if (! this.isExternalUrl(url)) {
                continue;
            }

            anchor_arr[i].addEvent('click', function(event) {
                event.stop();

                // open a new window/tab
                window.open(this.get('href'), '_blank');
            });
        }
    },

    /**
     * @param string
     * @return boolean
     */
    isExternalUrl: function(url) {
        // the regular expressions a href has to match to open in a new window/tab
        var file_re       = /\.[a-z0-9]{2,4}$/i;
        var http_re       = /^https?\:\/\//i;

        // the regular expressions a href has NOT to match to open in a new window/tab
        var mailto_re     = /^mailto\:/;
        var javascript_re = /^javascript\:/;

        // if the href does not match go to the next anchor in the array
        // a mailto href with an email address will match the re for a file
        if (mailto_re.test(url) || javascript_re.test(url) || ! (file_re.test(url) || http_re.test(url))) {
            return false;
        }

        return true;
    },

    /**
     * @param Element
     * @return string
     */
    getAnchorUrl: function(anchor) {
        var url = anchor.get('href');
        var http_re = /^https?\:\/\//i;
        var base_url = window.location.protocol +'//'+ window.location.host;

        // guard
        if (! url) {
            return;
        }

        // ie makes the href absolute
        url = url.replace(base_url, '');

        if (http_re.test(this.base_url)) {
            url = url.replace(this.base_url);
        }

       return url;
    }
});