// 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"
                 , "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);
//				document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
			},
			setCookie: function(name,value,options) {
				if (verbose) $h.console.log("$h.util.setCookie: "+name+":"+value)
				/****************
				 * TESTING OUT NEW COOKIE SETTING MODE
				 */
			    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('');
				}
				/*
				if (verbose) $h.console.log("$h.util.setCookie: "+name+":"+value)
				var domain = location.hostname.split('.');
				domain[0] = '';
				domain = domain.join('.');
				document.cookie = name + "=" + encodeURIComponent(value) + ";domain=" + domain + ";path=/";
				*/
			},
			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;
				/************
				 * TESTING OUT NEW COOKIE GETTING CODE
				 */
/*
				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 (verbose) $h.console.log("$h.util.buildScriptTag: "+src)
				if (!!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){
		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.util.buildScriptTag("/registration/get_mag_user.js?cachebust="+$h.session.cacheBust);
		} else {
			// if cookie was NOT found, make an empty mag_user object..
			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("/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);
			$h.session.ready = true;
			/**
			 * 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
			
			    // This check is done incase mag_user differs from hearst_user.  Used to default to mag_user.
			    // If local site's cookie's user_name is different from user_name found in services.hearstmags,
			    // lets log them out of local site ONLY, and the redirect to clearandgo should take care of loggin in to local site
			    // using hearst_user!
			    var cookie_user_name = $h.util.getCookie('user_name');
			    if( cookie_user_name && cookie_user_name != hearst_user.user_name ) {
			         var next_url = window.location;
//					 alert("hearst_user.user_name exists but does not match the user_name cookie! executing /registration/clearandgo?next+url="+escape(next_url));
			         window.location.href = '/registration/clearandgo?next_url=' + escape(next_url);
			    }
			
			    // now set local site fSpace cookies
			   if (!$h.util.getCookie('fSpaceSSOUserId')) {
			      $h.util.setCookie('fSpaceSSOUserId',hearst_user.user_name);
			      $h.util.setCookie('fSpaceSSOUserEmail',hearst_user.email);
			      $h.util.setCookie('fSpaceSSOUserCheck',hearst_user.encString);
			      $h.util.setCookie('fSpaceSSOExpires',hearst_user.expires);
			      window.location.reload(true); // this re-renders page, next getMyHash call will pick up cookies
			   }
			}
			var hearst_user_logged_in = false;
			if (hearst_user.logged_in) {
			  hearst_user_logged_in = true;
			}
			
			/** GRANDFATHERED CODE FROM:
			 *  /cm/shared/scripts/multi_logout.js
			 */
			if (!hearst_user_logged_in) {
			  if (mag_user.logged_in) {
			    var redirUrl = "/registration/logout?next_url=" + document.URL;
			    window.location.href = redirUrl;
			  }
			}

		}
	},500)
	
	
})();

