var activeNav = 0;
var onUnloadSet = 0;

// none of this is needed anymore, but older code might still use it
// do not use this in new code!

browser = navigator.appName;
IE = (browser == "Microsoft Internet Explorer");
NS = ((browser == "Netscape") || (browser == "Mozilla"));
os = navigator.platform; 
MAC = (os == "MacPPC");  // i.e. pre OS X!
version = parseInt(navigator.appVersion);
if (IE && ( version >= 4 )) {
    temp    = navigator.appVersion.split("MSIE");
    version = parseInt(temp[1])
    if (version == 0) { version = 5 }  
}                                                                                                                        
V5pl  = (version >= 5); 
V4pl  = (version >= 4); 
V4    = (version == 4); 
NS5pl = (NS && V5pl); 
NS4pl = (NS && V4pl);
NS4   = (NS && V4);
IE4pl = (IE && V4pl);
IE4   = (IE && V4);
IE5pl = (IE && V5pl);
doAll = document.all ? 1 : 0;
doGEl = document.getElementById ? 1 : 0;  

function setLocationBeforeLeaving() {
    if (activeNav) {
        if (window.location.hash) {
            curlocation = window.location.href;
            newlocation = curlocation.replace(/#.*/, "#" + "navDiv=" + activeNav);
            window.location.replace(newlocation);
        } else {
            window.location.replace(window.location.href + "#" + "navDiv=" + activeNav);
        }
    }
    else if (window.location.hash) {
        curlocation = window.location.href;
        newlocation = curlocation.replace(/#.*/, "#");
        window.location.replace(newlocation);
    }
}

function pseudoSetLocationBeforeLeaving() {
    if (activeNav) {        
        window.location.hash = "#" + "navDiv=" + activeNav;
    } else if (window.location.hash.indexOf('navDiv=') != -1) {
        window.location.hash = "";
    }
}

function showNav(navNum, ignoreLocation) {
    hideNavs(1);
    navName = "navDiv" + navNum;
    document.getElementById(navName + "_inner").style.visibility='visible';
    document.getElementById(navName + "_outer").style.visibility='visible';
    activeNav = navNum;
    if (!onUnloadSet) {
        onUnloadSet = 1; 
        // this makes back button slower, so do only if a navbar was clicked on.
        dojo.addOnUnload(setLocationBeforeLeaving);
    }
}
function hideNavs(ignoreLocation) {
    activeNav = 0;
    for (var i = 1; i <= 6; i++) {    
        navName = "navDiv" + i;
	document.getElementById(navName + "_outer").style.visibility='hidden';
        document.getElementById(navName + "_inner").style.visibility='hidden';
    }
}

function setDocumentTitle() {
   
   if (document.title != "The National Bureau of Economic Research") {
     return true;
   }

   var a = dojo.byId("mainTitle");
   if (a != null) {
     document.title = a.innerHTML;
     return true;
   } else {
     var b = document.getElementsByTagName("H1")[0];
     if (b != null) {
        document.title = b.innerHTML;
        return true;
     } else {
        var c = document.getElementsByTagName("H1")[0];
        if (c != null) {
           document.title = c.innerHTML;
           return true;
        }
     }
   }
}

function setCurrentDate() {
  var localDate = new Date();
  var utc = localDate.getTime() + (localDate.getTimezoneOffset() * 60000);

  var boston = -5;  

  if (localDate.getMonth() >= 2 && localDate.getMonth() <= 9) {
    boston = -4 // hack, since there are 15 days a year when this is off by an hour; but who really cares...
  }

  var bostonTime = utc + (60*60*1000*boston);

  var now = new Date(bostonTime);
  var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

  year_four_digits = (now.getYear() < 1000) ? now.getYear() + 1900 : now.getYear();

// Join it all together
  today =  days[now.getDay()] + ", " +
      months[now.getMonth()] + " " +
      now.getDate() + ", " +
      year_four_digits;

  dojo.byId('currentDate').innerHTML = today
}

bottomUrl = "" // override this in your HTML <script> tag

function getBottomSection() {
    if (dojo.byId("bottomHtml") == null) {
       if (!bottomUrl) {
         bottomUrl = '/2009_redesign/bottom_stories.pl'
       }
       dojo.xhrGet( {
            url: bottomUrl,
            handleAs: "text",

            timeout: 5000, // Time in milliseconds

                    // The LOAD function will be called on a successful response.
            load: function(response, ioArgs) { 
                    dojo.byId("bottomSectionContent").innerHTML = response; 
                    return response;
            },

                    // The ERROR function will be called in an error case.
            error: function(response, ioArgs) {
                    console.error("HTTP status code: ", ioArgs.xhr.status);
                    return response;
                }
            });
    } else {
        dojo.byId("bottomSectionContent").innerHTML = dojo.byId("bottomHtml").innerHTML
    }
}

function getWeather() {
       dojo.xhrGet( {
            url: '/2009_redesign/short_weather.txt',
            handleAs: "text",

            timeout: 5000, // Time in milliseconds

                    // The LOAD function will be called on a successful response.
            load: function(response, ioArgs) { 
                    dojo.byId("currentWeather").innerHTML = response; 
                    return response;
            },

                    // The ERROR function will be called in an error case.
            error: function(response, ioArgs) {
                    console.error("HTTP status code: ", ioArgs.xhr.status);
                    return response;
                }
            });
}

var loadScript = 0 // pre-dojo way of setting onLoad(), still used...

function showOnLoad() {
   if (window.location.hash) {
     matchArray = window.location.hash.match("navDiv=[1-9]");
     if (matchArray.length > 0) {
         matchDiv = matchArray[0];
         if (matchDiv != null) {
             divId = matchDiv.match("[1-9]")[0];
             showNav(divId, 1); //ignoreLocation
         }
     }
   }
   if (document.forms['googleSearchForm']) {
     document.forms["googleSearchForm"].reset();
   }
   if (document.forms['wpSearchForm']) {
       document.forms["wpSearchForm"].reset();
   }
   if (document.forms['booksSearchForm']) {
       document.forms["booksSearchForm"].reset();
   }
   if (document.forms['peopleSearchForm']) {
       document.forms["peopleSearchForm"].reset();
   }
   setDocumentTitle();
   setCurrentDate();
   getBottomSection();
   if (loadScript) {
       loaded();
   }
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if  cookie does not exist
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
    } else
      begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
      end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}

function getUsername() {
    // returns the username as found in the ticket cookie
    // the ticket could be old, so it is not a guarantee that
    // the user is logged in.
    var ucook = getCookie('username_ticket_cookie');
    if (ucook) {
       var begin = ucook.indexOf('-');
       return unescape(ucook.substring(begin + 1, ucook.length));
    } else { return "" }
}

var smart_loginbox = 1;  // this value gets changed in NBER::Style

var dl = "";
var dl2 = "";
dl = "https://www.nber.org/login.pl?post_login_url=" + document.location;
dl2 = "https://www.nber.org/prefs/prefs_or_login.pl?post_login_url=" + document.location;
var mouseOverLink=""

function changeLoginDiv() {
    var user = getUsername();
    if (user.length == 0) { //no user cookie
        dojo.byId('loginSection').innerHTML = '<h3 class="rightHeading"><a href="' + dl + '" ' + mouseOverLink + '>Customize this site by logging in</a></h3>';
    } else {
        // while waiting
        dojo.byId('loginSection').innerHTML = '<h3 class="rightHeading">Loading customized settings for <b><a href="https://www.nber.org/prefs/prefs.pl" onMouseOver="get_hide(\'loginbar\')">' + user +  '</a></b>';
        // load them...
        substituteLoginLinks('loginSection');
    }
}

function substituteLoginLinks(loginDiv) {
    dojo.xhrGet( {
            url: '/2009_redesign/userinfo/',
            handleAs: "text",

                timeout: 14000, // Time in milliseconds                                                                        

                // The LOAD function will be called on a successful response.                                         
                load: function(response, ioArgs) {
                dojo.byId(loginDiv).innerHTML = response;
                return response;
            },

                // The ERROR function will be called in an error case.                                                
                error: function(response, ioArgs) {
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
        });
}



dojo.addOnLoad(showOnLoad)
