/**
 * UserAgent.js
 * @author Matthew Ratzloff
 * @copyright Copyright (c) 2006 Matthew Ratzloff
 */

/**
 * Class UserAgent collects browser information.  This shouldn't be 
 * used for anything more than style quirks and things of a relatively 
 * trivial nature.  You should always include the generic rules prior 
 * to applying customized rules to attempt to degrade gracefully, and 
 * for users without JavaScript enabled.
 */
function UserAgent()
{
    var name;
    var version;
    var platform;

    if(navigator.userAgent)
    {
        this.__construct(navigator.userAgent);
    }
}

/**
 * UserAgent functions (including helpers).
 */
UserAgent.prototype = 
{
    /**
     * @param string User agent
     */
    __construct: function(userAgent)
    {
        this.name     = this.parseName(userAgent);
        this.version  = this.parseVersion(userAgent);
        this.platform = this.parsePlatform(userAgent);
    },

    /**
     * @param string Stylesheet URI
     */
    importStylesheet: function(stylesheet)
    {
        document.write('<style type="text/css">@import url("' + stylesheet + '");</style>');
    },

    /**
     * @param string User agent
     * @return string Name
     */
    parseName: function(userAgent)
    {
        if(userAgent.match(/Opera/i))
        {
            return "Opera";
        }

        if(userAgent.match(/MSIE/i))
        {
            return "Internet Explorer";
        }

        if(userAgent.match(/Firefox/i))
        {
            return "Firefox";
        }

        if(userAgent.match(/Safari/i))
        {
            return "Safari";
        }

        return null;
    },

    /**
     * @param string User agent
     * @return float|null Version
     */
    parseVersion: function(userAgent)
    {
        if(this.name == "Opera")
        {
            return Number(userAgent.match(/Opera ([0-9\.]+)/i)[1]);
        }

        if(this.name == "Internet Explorer")
        {
            return Number(userAgent.match(/MSIE ([^;]+)/i)[1]);
        }

        if(this.name == "Firefox")
        {
            var version = userAgent.match(/Firefox\/([0-9\.]+)/i)[1];
            version = version.split(".");
            version = version[0] + "." + version[1];
            return Number(version);
        }

        if(this.name == "Safari")
        {
            var revision = Number(userAgent.match(/Safari\/([0-9\.]+)/i)[1]);
            var version  = (revision < 400) ? 1 : 2;
            return version;
        }

        return null;
    },

    /**
     * @param string User agent
     * @return string Platform
     */
    parsePlatform: function(userAgent)
    {
        if(userAgent.match(/Windows/i))
        {
            return "Windows";
        }

        if(userAgent.match(/Mac/i))
        {
            return "Macintosh";
        }

        return null;
    }
}