// code yanked from ajaxian: http://ajaxian.com/archives/graceful-degradation-of-firebug-$h.console-object Thanks, ajaxian! :-) - Alex
// code yanked from the Yahoo media player. Thanks, Yahoo.
if (!("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupCollapsed"
                 , "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() { };
}

/** initial instantiation check for hearst object
*  I call it: $h
*   - Alex
*/
if (!window.$h) { window.$h = {}; }


// heehee, mapping console to $hearst obj
window.$h.console = window.console;





/*
* Hearst Utilities Object
* - first we have to assess whether or not this utilties object already exists...
* 
*/
(function() {
    // local var to spam console messages, set verbose to false to turn off the spam
    var verbose = true;
    if ($h.util) {
        if (verbose) $h.console.warn("$h.utilities object exists");
    } else {
        if (verbose) $h.console.log("building: $h.util");
        $h.util = {
            deleteCookie: function(name) {
                if (verbose) $h.console.log("$h.util.deleteCookie: " + name);
                $h.util.setCookie(name, null);
            },
            setCookie: function(name, value, options) {
                if (verbose) $h.console.log("$h.util.setCookie: " + name + ":" + value)
                if (typeof value != 'undefined') { // name and value given, set cookie
                    options = options || {};
                    if (value === null) {
                        value = '';
                        options.expires = -1;
                    }
                    var expires = '';
                    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                        var date;
                        if (typeof options.expires == 'number') {
                            date = new Date();
                            date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                        } else {
                            date = options.expires;
                        }
                        expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                    }
                    // CAUTION: Needed to parenthesize options.path and options.domain
                    // in the following expressions, otherwise they evaluate to undefined
                    // in the packed version for some reason...
                    var path = options.path ? '; path=' + (options.path) : '';
                    var domain = options.domain ? '; domain=' + (options.domain) : '';
                    var secure = options.secure ? '; secure' : '';
                    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
                }
            },
            getCookie: function(name) {
                if (verbose) $h.console.log("$h.util.getCookie: " + name);
                var nameEQ = name + "=";
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                }
                return null;
            },
            getParameter: function(name, optstring) {
                if (verbose) $h.console.log("$h.util.getParameter: " + name)
                var thestring = (!optstring) ? window.location.href : "?" + optstring;
                name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var regexS = "[\\?&]" + name + "=([^&#]*)";
                var regex = new RegExp(regexS);
                var results = regex.exec(thestring);
                if (results == null)
                    return "";
                else
                    return results[1];
            },
            buildScriptTag: function(src) {
                if (typeof (src) == "undefined") { src = "" }
                var t_src = src.split("&ha=1")[0];
                if (!!!t_src || (t_src == "undefined")) {
                    if (verbose) $h.console.log("$h.util.buildScriptTag[FAILED]:" + src);
                } else {
                    if (verbose) $h.console.log("$h.util.buildScriptTag: " + src);
                    document.write('<scr' + 'ipt src="' + src + '" language="javascript"></scr' + 'ipt>');
                }
            },
            alert: function(txt) {
                if (verbose) $h.console.log("$h.util.alert: " + txt)
                alert(txt);
            }
        };
    }
})();







/*
* Hearst Session Object
* -the intention is to create this anonymously and map to window.$h
* - in the first iteration, we create a basic session object and map it.
* - let's work on fleshing this out
*/
(function() {
    // intialize the session state
    var _session = {
        "ready": false,
        "ha": !!$h.util.getParameter("ha"),
        "cacheBust": Math.floor(Math.random() * 100001),
        "mag_user": null,
        "hearst_user": null,
        "mag_user_listener": null,
        "hearst_user_listener": null,
        "hearst_and_mag_user_listener": null

    };
    $h.session = _session;
    //$h.console.log($h.session);

    /************************************************************
    *  $h.session skeleton is ready, lets build out some stuff..
    */

    /* check High Availability
    *  during HA, vars mag_user and hearst_user are empty objects, I can either call the script tag with HA set on,
    *  or simply build my own empty objects. I'm gonna build my own empty object to limit unnecessary server calls
    */
    if ($h.session.ha) {
        $h.console.log("SESSION: high availability");
        window.hearst_user = {};
        window.mag_user = {};
        //$h.util.buildScriptTag(_ghearst_vars.ams_ads_script_src+"&ha=1")
    } else {
        // when we aren't in HA mode, build regular script tag..
        //$h.util.buildScriptTag(_ghearst_vars.ams_ads_script_src)

        // build get_hearst_user.js script tag..
        $h.util.buildScriptTag("http://services.hearstmags.com/registration/get_hearst_user.js");

        // and finally, ghetto cookie hack to find if any of these cookies exist..
        /* KEEP IN MIND this is the ghetto function used to check for the cookie, instantiated anonymously
        * 
        */
        if ((function() {
            var cookiefound = false;
            var cookies = ["fSpaceSSOUserId", "fSpaceSSOUserEmail", "fSpaceSSOUserCheck", "fSpaceSSOExpires", "cgi-session-id", "hm_userid", "user_name"];
            for (var i in cookies) { if (!!$h.util.getCookie(cookies[i])) { cookiefound = true; } }
            return cookiefound;
        })()// end the anonymous function call
		) {
            // if cookie was found  build the get_mag_user.js script tag..
            $h.console.log("SESSION: session cookies found");
            $h.util.buildScriptTag("http://www.realage.com/registration/get_mag_user.js?cachebust=" + $h.session.cacheBust);
        } else {
            // if cookie was NOT found, make an empty mag_user object..
            $h.console.log("SESSION: creating empty mag_user");
            window.mag_user = {};
        }
    }


    /*
    * docloc grandfathered code that's left over from get_mag_user.js
    *  - ugly as sin, standardize via $h.util.setCookie("docloc",document.location);
    *  - maintenance code needs a place to live however.
    */
    var docloc = new String(document.location);
    if (docloc.indexOf("http://www.realage.com/registration/") < 0) document.cookie = 'docloc=' + docloc + ";path=/";





    /*********************************
    *  Listen for mag_user and hearst_user, once these are both found, call $h.session.init
    *  
    *  Listeners are put in because of the async nature of these vars coming in place
    *   - via script tags which have the vars defined
    *   - typically will only really matter when a user has logged in at some point
    *   - but its better to be safe than sorry..
    *  
    */
    $h.session.mag_user_listener = setInterval(function() {
        if (!!window.mag_user) {// mag_user exists! MAP it to $h.session
            $h.session.mag_user = window.mag_user;
            window.clearInterval($h.session.mag_user_listener);
        }
    }, 500);

    $h.session.hearst_user_listener = setInterval(function() {
        if (!!window.hearst_user) {// hearst_user exists! MAP it to $h.session
            $h.session.hearst_user = window.hearst_user;
            window.clearInterval($h.session.hearst_user_listener);
        }
    }, 500);

    $h.session.hearst_and_mag_user_listener = setInterval(function() {
        if ((!!$h.session.mag_user) && (!!$h.session.hearst_user)) {
            window.clearInterval($h.session.hearst_and_mag_user_listener);
            /* We've turned session.ready into an object
            * WARNING: beware the distinction between the Bool session.ready and Obj session.isReady
            */
            $h.session.ready = true;

            /** Putting in some assertion checks
            * 
            */
            var assert_cookie_username = $h.util.getCookie('user_name');
            $h.console.assert((mag_user.user_name == hearst_user.user_name), "[AUTH] mag_user.user_name and mag_user.user_name mismatch! [mag_user:" + mag_user.user_name + "][hearst_user:" + hearst_user.user_name + "]");
            $h.console.assert(((assert_cookie_username == mag_user.user_name) && (assert_cookie_username == hearst_user.user_name) && (mag_user.user_name == hearst_user.user_name)), "[AUTH] user_name mismatch! [cookie:" + assert_cookie_username + "][mag_user:" + mag_user.user_name + "][hearst_user:" + hearst_user.user_name + "]");
            $h.console.assert((assert_cookie_username == mag_user.user_name), "[AUTH] cookie user_name and mag_user.user_name mismatch! [cookie:" + assert_cookie_username + "][mag_user:" + mag_user.user_name + "]");


            /** A couple things to check for..
            * If the hearst_user is empty but mag_usre is not, that means user is attempting log out using an external source. Finish off the log out internally.
            */
            /** inherited code based off of:
            *  /cm/shared/scripts/multi_logout.js
            */
            if ((!hearst_user.hasOwnProperty("user_name")) && (mag_user.hasOwnProperty("user_name"))) {
                var objdump = "\n\n\n" + dumpObj(mag_user, "mag_user", "  ", 5) + "\n\n\n" + dumpObj(hearst_user, "hearst_user", "  ", 5);
                $h.console.error("[SESSION COOKIE] : logged_in session check" + objdump);
                var redirUrl = "http://www.realage.com/registration/logout?next_url=" + document.URL;
                // gonna see if deleting these cookies will work..
                $h.util.deleteCookie('fSpaceSSOUserId');
                $h.util.deleteCookie('fSpaceSSOUserId');
                $h.util.deleteCookie('fSpaceSSOUserEmail');
                $h.util.deleteCookie('fSpaceSSOUserCheck');
                $h.util.deleteCookie('fSpaceSSOExpires');
                window.location.href = redirUrl;
            }




            /**
            * this is where we put our grandfathered dev code
            */


            /** GRANDFATHERED CODE FROM:
            *  /cm/shared/scripts/multi_login.js
            */
            if (hearst_user.logged_in) {
                // services.hearstmags logged in

                // yikes, that old script was causing some craziness. Here is a new check to call clearandgo
                // as long as the following properties in mag_user and hearst_user match, we should be fine
                // since these are the properties that the user edits.
                if ((function() {
                    if (mag_user["birth_date"] !== hearst_user["birth_date"]) return true;
                    if (mag_user["city"] !== hearst_user["city"]) return true;
                    if (mag_user["email"] !== hearst_user["email"]) return true;
                    if (mag_user["first_name"] !== hearst_user["first_name"]) return true;
                    if (mag_user["last_name"] !== hearst_user["last_name"]) return true;
                    if (mag_user["location"] !== hearst_user["location"]) return true;
                    if (mag_user["password"] !== hearst_user["password"]) return true;
                    if (mag_user["user_name"] !== hearst_user["user_name"]) return true;
                    //if (mag_user[""] !== hearst_user[""]) return true;
                    return false;
                })()) {
                    $h.console.log("[SESSION OBJ MATCH] failed");
                    var next_url = window.location;
                    //window.location.href = 'http://www.realage.com/registration/clearandgo?next_url=' + escape(next_url);
                }

                // now set local site fSpace cookies - ok, this time it's not local. 
                if (!$h.util.getCookie('fSpaceSSOUserId')) {
                    var tdocdomain = document.domain;
                    var tdocindex = tdocdomain.indexOf(".");
                    var tdomain = tdocdomain.substring(tdocindex);

                    tdomain = "realage.com"

                    $h.util.setCookie('fSpaceSSOUserId', hearst_user.user_name, { "path": "/", "domain": tdomain });
                    $h.util.setCookie('fSpaceSSOUserEmail', hearst_user.email, { "path": "/", "domain": tdomain });
                    $h.util.setCookie('fSpaceSSOUserCheck', hearst_user.encString, { "path": "/", "domain": tdomain });
                    $h.util.setCookie('fSpaceSSOExpires', hearst_user.expires, { "path": "/", "domain": tdomain });

                    var curloc = document.location;

                    // accounts for either hlo=1 or hli=1
                    if (curloc.href.toLowerCase().indexOf('myacnt.aspx?hl') >= 0) {
                        window.location.reload(true); // this re-renders page, next getMyHash call will pick up cookies
                    }
                }
            }

            // keeping this cruft in
            var hearst_user_logged_in = false;
            if (hearst_user.logged_in) {
                hearst_user_logged_in = true;
            }



        }
    }, 500)


})();
