dojo.provide("mdg.sniff");

//
// Browser history sniffing, based on infamous blog post:
// <http://www.niallkennedy.com/blog/2008/02/browser-history-sniff.html>
//
// Sample usage:
//
//    dojo.require("mdg.sniff");
//    var usedYahoo = mdg.sniff.isVisited("http://www.yahoo.com");
//    var usedGoogleMaps = mdg.sniff.isAnyVisited([
//          "http://maps.google.com",
//          "http://maps.google.com/maps"]);
//    var usedFacebook = mdg.sniff.isAnyVisited([
//          "http://www.facebook.com",
//          "http://www.facebook.com/index.php",
//          "https://login.facebook.com/login.php"]);
//
// Works with Dojo 1.3 and 1.4 (*may* work with 1.2 as well)
//

dojo.require("dojox.html.styles");

(function(){

    var _this = this;

    this.sniffCache = {};

    dojox.html.insertCssRule(".dojohistorysniff a", "color:#000000;");
    dojox.html.insertCssRule(".dojohistorysniff a:visited", "color:#ff0000 !important;");

    this.isAnyVisited = function(/*Array*/urls) {
        for (i=0; i<urls.length; i++) {
            if (_this.isVisited(urls[i])) {
                return true;
            }
        }
        return false;
    };

    this.isVisited = function(/*String*/url) {
        if (typeof(_this.sniffCache[url]) != 'undefined') {
            return _this.sniffCache[url];
        }
        var link = _this.addLink(url);
        var color = new dojo.Color(dojo.style(link, "color"));
        if (color.r == 255) {
            _this.sniffCache[url] = true;
            return true;
        }
        _this.sniffCache[url] = false;
        return false;
    };

    this.insertSniffDiv = function() {
        return dojo.create("div", {className: "dojohistorysniff"}, dojo.body());
    };

    this.getSniffDiv = function() {
        var divs = dojo.query("div.dojohistorysniff");
        if (divs.length > 0) {
            return divs[0];
        }
        return _this.insertSniffDiv();
    };

    this.addLink = function(/*String*/url) {
        var div = _this.getSniffDiv();
        return dojo.create("a", {href: url}, div);
    };

    /**
     * mdg.sniff.isVisited
     * Check whether or not a URL has been visited
     * @param url String
     * @return boolean
     */
    mdg.sniff.isVisited = this.isVisited;

    /**
     * mdg.sniff.isAnyVisited
     * Check whether or not *any* of the URLs specified have been visited
     * @param urls Array of Strings
     * @return boolean
     */
    mdg.sniff.isAnyVisited = this.isAnyVisited;

})();
