//  don't assume jQuery
window.CC = window.CC || {};
window.CC.host = {
    //  second-level (Live) or third-level domain
    //  WARNING:  do not modify the level: line without updating common/tasks/appconfig.rake
    level: 2,

    //  returns the current hostname (of the Window)
    current: function() {
        // realWindow won't be available if global.js isn't loaded
        return CC.realWindow ? CC.realWindow().location.hostname : window.location.hostname;
    },

    //  returns a Set-Cookie domain, to facilitate cross-subdomain AJAX requests
    domain: function() {
        var names = this.current().split(".");
        return names.slice(names.length - this.level).join('.');
    },

    //  returns true if the cross-subdomain Set-Cookie domain has been set
    isXD: function() {
        return (document.domain == this.domain());
    },

    //  generates a hostname for our domain based upon a function (eg. purpose)
    name: function(func) {
        return func + '.' + this.domain();
    },

    //  composes a URL for the function (eg. purpose)
    //  protocol defaults to current for page
    //  alternate call:  path only, in which case the current hostname AND protocol are used
    url: function(func, path, protocol) {
        // realWindow won't be available if global.js isn't loaded
        var win = CC.realWindow ? CC.realWindow().location : window.location;
        protocol = (protocol || win.protocol).replace(/:.*$/,'');
        var host;
        if (! path) {
            //  fore-shortened call -- just the path, so use the current hostname
            path = func;
            host = this.current();
        }
        else {
            host = this.name(func);
        }
        return [ protocol, '://', host, path ].join('');
    },

    //  returns true if the current host provides the function (eg. purpose)
    hasFunction: function(func) {
        return (this.current().indexOf(func + '.') == 0);
    },

    //  returns true if the current host provides the Serv.io service
    isServio: function(service) {
        //  it will be the top-most path
        //  see use of :current_business in frontio/config/routes.rb
        var path = window.location.pathname + '/';
        if (path[0] != '/') {
            path = '/' + path;
        }
        return (path.indexOf('/' + service + '/') == 0);
    },

    //  returns true if we're in Local (eg. Development) mode
    isLocal: function() {
        return (this.domain().indexOf('local.') == 0);
    },

    //  returns a if we're in Local mode, b otherwise
    //      a defaults to true, b defaults to null
    //      if a or b is a function, it is called and the function's value is returned instead
    ifLocal: function(a,b) {
        var v;
        if (this.isLocal()) {
            v = ((a === undefined) ? true : a);
        }
        else {
            v = ((b === undefined) ? null : b);
        }
        if (typeof(v) === "function")  { v = v(); }
        return v;
    }
}

