// supporting javascript for gary king website
if (window.name == 'ChangeDetectionWiz') {
	top.location.href = 'http://www.ChangeDetection.com/detect.html?url='+escape(document.location.href)+'&email=enter+email';
}

if (document.title.substring(0,9) != 'Gary King') {
	document.title = 'Gary King - ' + document.title;
}
var gFileName = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
if (gFileName.toLowerCase() == 'group.shtml') document.location.href = 'group.php?relations=Staff' + document.location.hash;
gFileName = gFileName.substring(0,gFileName.lastIndexOf("."))
var lp = location.pathname.toLowerCase()
var imgPrefix = '/';

//not on gking server, so make all img & hrefs absolute URL's, like if we're on google search results or VDC server. -rmesard 01-apr-2006
if ( location.hostname.toLowerCase().indexOf( "gking.harvard.edu" ) == -1 ) imgPrefix = 'http://gking.harvard.edu/';

var urlPrefix = imgPrefix;
var isOffSiteHost = false;
if ( location.hostname.toLowerCase().indexOf( "gking." ) != -1 ) {
	imgPrefix = '/';
	if ( lp.indexOf( "/beta" ) != -1 ) {
		urlPrefix = urlPrefix + 'beta/';
	}
} else {
	isOffSiteHost = true;
}
//alert(isOffSiteHost)
var headerCalled = false;
var footerCalled = false;
var isPrintPage = ( queryString('print',document.location) == '1' ) ? true : false;
var isGoogleCachePage = false; //used to decide if we need to bump all content down ~200px to accommodate search engine disclaimer text

if (document.location.search != 0 && isOffSiteHost) {
	if ( document.location.search.toLowerCase().indexOf( "q=" ) != -1 ) {
		isGoogleCachePage = ( queryString('q',document.location).toLowerCase().indexOf( "cache" ) != -1 ) ? true : false;
	}
	// look for additional clues that we're a search engine, use some generic but reliable URL tests. -rmesard 16-jan-2006
	if (!isGoogleCachePage) {
		//potential search query that's longer than 1 char, and we're not on an .edu server
		if (document.location.search.length > 4 && (location.hostname.toLowerCase().indexOf( ".edu" ) == -1)) {
			isGoogleCachePage = true;
		}
	}
	if ( top.window.frames.length > 0 || location.pathname.toLowerCase().indexOf( "/u/gking" ) != -1 ) {
		// we're on regular king-branded google search results, or...
		// we may be on some offsite URL that has additional content in its own top frame, like google translation - no need to bump page contents down
		isGoogleCachePage = false
	}
}

var isHomePage = false;
var thepathArray = location.pathname.split("/")
var isPrimaryPage = true;
var isAbstractPage = false;
//alert(thepathArray.length);
if (thepathArray.length == 2) {
	if (thepathArray[1] == 'homepage.html' || thepathArray[1] == '') isHomePage = true;
}

function checklp(inputStr) {
	if (lp.indexOf(inputStr) != -1) {
		isPrimaryPage = false;
		if (gFileName == 'index' || gFileName == '') {
			isAbstractPage = true;
		}
		//alert(location.pathname.substring(0,location.pathname.lastIndexOf('/')));
		if (location.pathname.substring(0,location.pathname.lastIndexOf('/')) == '/vign/eg') {
			isAbstractPage = true;
		}
	}
}

//exceptions to the isPrimaryPage rule go here
checklp("/amelia/amelia1/docs");
checklp("/clarify/docs");
checklp("/judgeit");
checklp("/galileo");checklp("/rsnl");
checklp("/matchit");
checklp("/whatif");
checklp("/yourcast");
checklp("/readme");
checklp("/va/");
checklp("/amelia");
checklp("/cem/");
checklp("/zelig");
checklp("/zelig/docs");
checklp("/vign/eg/");
checklp("/vign/eg/priv");
checklp("/vign");


if (isPrintPage) isPrimaryPage = false;
//alert(isPrimaryPage);

// browser version check
var ver="unknown";
bName = navigator.appName;
bVer = parseInt(navigator.appVersion);
if      (bName == "Netscape" && bVer >= 3) ver = "n3";
else if (bName == "Netscape" && bVer == 2) ver = "n2";
else if ( navigator.userAgent.toLowerCase().indexOf( "opera" ) != -1 ) ver = "o4";
else if (bName == "Microsoft Internet Explorer" && bVer >= 2)
        ver = "e3";

document.writeln("<link rel='stylesheet' href='" + imgPrefix + "gking.css' media='all' type='text/css' />");
document.writeln("<!--[if IE 6]><link rel=\"stylesheet\" href=\"/fix-ie.css\" type=\"text/css\"><![endif]-->");
document.writeln("<style type='text/css'>");
var addH = 0;

if (document.compatMode == 'CSS1Compat' && ver != 'o4') {
	document.writeln(" #navalsodiv { left: -6px; } ");
}

if (isGoogleCachePage) {
	addH = 210;
	document.writeln(" #logo  { top: " + eval(0 + addH) + "px; } ");
	document.writeln(" #photo { top: " + eval(-1 + addH) + "px; } ");
	document.writeln(" #homecopy { top: " + eval(190 + addH) + "px; } ");
	document.writeln(" #gking_name_shimbox, #orangeline_horiz { top: " + eval(90 + addH) + "px; } ");
	document.writeln(" #content-main { top: " + eval(23 + addH) + "px; } ");
	document.writeln(" #sidebar-left { top: " + eval(70 + addH) + "px; } ");
	//document.writeln(" #gkingheadbox { display: none; } ");
}

// ensure we don't display headshot jpg offsite, causes too much trouble
if (document.location.search != 0 && isOffSiteHost) document.writeln(" #gkingheadbox { display: none; } ");

if (!isPrimaryPage) {
	document.writeln(" #content-main { left: 10px !important; top:23px !important; } ");
	document.writeln(" #gking_name_shim3, #orangeline_vert, #orangeline_horiz, #logotd, #gkingheadbox { display: none; } ");
} else {
	document.writeln("td.latexnavhome { display: none; } ");
	if (isHomePage) {
		if (!isPrintPage && !isGoogleCachePage) document.writeln(" #maindiv { top: " + eval(142 + addH) + "px; } ");
		document.writeln(" #footerspecial {	height: 422px ! important; } ");
	}
}
if (isAbstractPage) {
	document.writeln(" span.copyright { display: none; } ");
}

//var addthis_disable_flash=true;
document.writeln("</style>");
document.writeln("<script src=\"/jquery.js\" type=\"text/javascript\"></script>");
document.writeln("<script src=\"/twitter.js\" type=\"text/javascript\"></script>");

//cookie code, copied from pre-2006 gking site
var cookie_name = "gCookie";
function doCookie() {
    if(document.cookie) {
            index = document.cookie.indexOf(cookie_name);
    } else {
            index = -1;
    }

    if (index == -1) {
            document.cookie=cookie_name+"=1;";
    } else {
            countbegin = (document.cookie.indexOf("=", index) + 1);
            countend = document.cookie.indexOf(";", index);
            if (countend == -1) {
                    countend = document.cookie.length;
            }
            count = eval(document.cookie.substring(countbegin, countend)) + 1;
            document.cookie=cookie_name+"="+count+";";
    }
}

function gettimes() {
    if(document.cookie) {
    index = document.cookie.indexOf(cookie_name);
    if (index != -1) {
        countbegin = (document.cookie.indexOf("=", index) + 1);
        countend = document.cookie.indexOf(";", index);
            if (countend == -1) {
                countend = document.cookie.length;
            }
        count = document.cookie.substring(countbegin, countend);
        return (parseInt(count));
    }
    }
    return (0);
}

//utility functions, for getting name/val pairs off of querystring
var __gbl_qstr = stripQuery(this.location);
function queryString(key, src) {
  var __qstr = stripQuery(src);
  var strIndex = __qstr.indexOf(key+'=');
  if(strIndex == -1) return null;
  var strReturn = '', ch = '';

  for(var i = strIndex + key.length; i < __qstr.length; i++) {
    ch = __qstr.charAt(i);
    if(ch == '&' || ch == ';') break;
    if(ch == '+') strReturn += ' ';
    else if(ch != '=') strReturn += ch;
  }
  return unescape(strReturn);
}

function stripQuery(src) {
  if(src == null) return __gbl_qstr;

  if(typeof src == 'string') {
    var __qstr   = new String();
    var __tmpNum = src.indexOf('?');

    __qstr = (__tmpNum != -1)
             ? src.substr(
                 __tmpNum + 1, src.length
               )
             : null;

    delete __tmpNum;
    return __qstr;
  }
  else if(typeof src == 'object') { // assumes the object is of type location
    return location.search.substr(1, location.search.length);
  }
  else return __gbl_qstr;
}

// allows arbitrary places in the page to register window.onload handlers
var gk_onLoadFunctions;    // the array of registered handlers

// call this from a script element in the page to register a function to be called
// when loading is completed. The function should be parameterless.
// If fn is a string, then, at onLoad time, we just eval the string. This is useful when the function
// referenced is not defined at the time of the call, e.g. it is in a different script file.
function gk_RegisterOnLoad(fn)
{
  if (typeof gk_onLoadFunctions == "undefined")
  {
    // this is the first one we've seen, create the array
    gk_onLoadFunctions = new Array();
    if (window.onload)
    {
      // we already had a (statically defined) onload - include it in the array
      gk_onLoadFunctions.push(window.onload);
    }
    // set our master handler to run when the window has completed loading
    window.onload = gk_execOnload;
  }
  // add our function to the array
  gk_onLoadFunctions.push(fn);
}

// called when gk_RegisterOnLoad() has been used to register onload handlers
// calls each of the registered functions in turn
function gk_execOnload()
{
  if (gk_onLoadFunctions)
  {
    for(var i = 0; i < gk_onLoadFunctions.length; i++)
    {
			var fn = gk_onLoadFunctions[i];
			if (typeof(fn) == "string")
				eval(fn)
			else
				fn();
    }
  }
}

function clearInputField(inputObject) {
	if(inputObject.value.substring(0,5) == 'Enter')
		{inputObject.value = '';}
	return false; }

function printWin() {
	if (isPrimaryPage) {
		document.location = document.location + '?print=1';
	} else {
		window.print();
	}
}

function print_page() {
  if (navigator.userAgent.toLowerCase().indexOf("mac") != - 1 && ! window.netscape)
    {
      window.print();
//      alert("Press Command+P to Print");
    }
  else
    {
      window.print();
    }
}

function spacerImg(h,w) {
	return '<img src="' + imgPrefix + 'images/c.gif" height="'+h+'" width="'+w+'" alt="" class="spacer" />';
}

function displayNavItem(text,link) {
	return '<li><a href="'+ link + '">' + text + '</a></li>';
}

function navItem(text, link) {
	this.text = text;
	this.link = link;
}


function displayBodyClasses() {
    w('<body class="'+(isPrimaryPage?'primary':'not-primary')+(isHomePage?' front':'')+'">');
}
//MAIN LAYOUT

function displayHeader() {
	if (!headerCalled) {
		var headerHTML, shieldsLinks, frontPhoto;
		headerHTML ='<div id="header"><h1 id="logo"><a href="'+urlPrefix+'homepage.html">Gary King</a></h1></div>';
		shieldsLinks = '<div id="iqharv"><a id="iqlogo" href="http://iq.harvard.edu">IQSS</a><a  id="harvsheild" href="http://harvard.edu">Harvard University></a></div>';
        frontPhoto ='<div id="gkingshead"></div>';


		if (isPrimaryPage) {
		    w(headerHTML);
            displaySidebarleft();
            w(shieldsLinks);
            }

        if(isHomePage) {
            w(frontPhoto);
            }

		headerHTML = '<div id="main-wrap"><div class="content-wrap"><div class="content-right"></div><div class="content">'
		w(headerHTML);
		headerCalled = true;
	}
}



//MAIN CONTENT AND SIDEBAR Markup



function displayNavMenu() {
	var navItemArray = new Array();
	navItemArray[0] = new navItem("Bio &amp; C.V.", urlPrefix + "bio.shtml");
	navItemArray[1] = new navItem("Writings", urlPrefix + "writings.shtml");
	navItemArray[2] = new navItem("Software", urlPrefix + "stats.shtml");
	navItemArray[3] = new navItem("Dataverse", "http://dvn.iq.harvard.edu/dvn/dv/king");
	navItemArray[4] = new navItem ("Research Group", urlPrefix + "group.php");
	navItemArray[5] = new navItem ("Class Materials", urlPrefix + "class.shtml");
	navItemArray[6] = new navItem ("Links", urlPrefix + "links.shtml");
	navItemArray[7] = new navItem ("Contact", urlPrefix + "contact.shtml");

	var navItemArray2;
	var navMenuHTML;
	navMenuHTML = '<div id="nav"><ul>'
	for (var i=0;i<navItemArray.length;i++) {
		navMenuHTML += displayNavItem(navItemArray[i].text,navItemArray[i].link);
	}
	navMenuHTML += '</ul></div><!--/nav-->';
	w(navMenuHTML);
}

function doChangeDetectionPopup() {
	window.open(document.location,'ChangeDetectionWiz','resizable=yes,scrollbars=yes,width=624,height=460');
	return true;
}

function displaySearchGoogle() {
	var searchGoogleHTML;
	var q = ( (location.hostname.toLowerCase().indexOf( "google." ) != -1) && (queryString('q',document.location) != null ) ) ? queryString('q',document.location) : 'Enter search text';
	//<!-- Search Google -->
	searchGoogleHTML = '<div id="google-search"><form method="get" action="http://www.google.com/u/gking" name="googlesearch" onSubmit="if (document.forms.googlesearch.q.value == \'\' || document.forms.googlesearch.q.value == \'Enter search text\'){document.forms.googlesearch.q.focus();return false;}if (document.forms.googlesearch.sitesearch[2].checked){document.location.href=\'http://scholar.google.com/scholar?q=\'+document.forms.googlesearch.q.value;return false};">'
	+ '<div class="row"><input type="text" name="q" size="31" maxlength="255" value="' + q + '" class="txtinput" id="txtinputgoogle" title="Google Search" onFocus="return clearInputField(this)" /></div>'
	+ '<div><input type="hidden" name="domains" value="gking.harvard.edu"></div>'
	+ '<div class="row"><input type="radio" name="sitesearch" id="sitesearch1" value="gking.harvard.edu" selected /> <label for="sitesearch1">This Site</label></div>'
	+ '<div class="row"><input type="radio" name="sitesearch" id="sitesearch2" value="harvard.edu" /> <label for="sitesearch2">Harvard University</label></div>'
	+ '<div class="row"><input type="radio" name="sitesearch" id="sitesearch3" value="scholar.google.com" /> <label for="sitesearch3">Google Scholar</label></div>'
	+ '<div class="row"><input type="radio" name="sitesearch" id="sitesearch4" value="" /> <label for="sitesearch4">The Web</label></div>'
	+ '<div class="row"><button name="sa" class="button" id="buttongoogle" onClick="this.className=\'b2\';if (document.forms.googlesearch.q.value == \'\' || document.forms.googlesearch.q.value == \'Enter search text\'){document.forms.googlesearch.q.focus();return false;}if (document.forms.googlesearch.sitesearch[2].checked){document.location.href=\'http://scholar.google.com/scholar?q=\'+document.forms.googlesearch.q.value;return false};document.forms.googlesearch.submit();" onBlur="this.className=\'button\'">Google Search</button></div>'
	+ '</form></div>'
	//<!-- Search Google -->
	w(searchGoogleHTML);
//	alert('qstr = ' + qStr);
}

function displayTools() {
	var toolsHTML = '<div id="tools"><form name="translate" method="get" action="http://translate.google.com/translate" target="_top">'
	+ '<input type="hidden" name="u" value="' + document.location.href + '" />'
	+ '<input type="hidden" name="langpair" value="" />'
	// not on google search results or translated page
	if (location.hostname.toLowerCase().indexOf( "google." ) == -1 && location.pathname.toLowerCase().indexOf( "translate_c" ) == -1) {
		toolsHTML += '<a href="http://www.ChangeDetection.com/detect.html" target="ChangeDetectionWiz" onClick="window.open(\'\',\'ChangeDetectionWiz\',\'resizable=yes,scrollbars=yes,width=624,height=460\');return true"><img src="' + imgPrefix + 'images/delta.gif" height="15" width="15" alt="" /><span class="toolslink">Track changes</span></a>'
	}

	toolsHTML += '<div class="translate">'
	if (location.pathname.toLowerCase().indexOf( "translate_c" ) == -1) {
		toolsHTML += '<a href="javascript:onClick=document.forms.translate.langpairstub.focus()"><img src="' + imgPrefix + 'images/translate.gif" width="15" height="12"  alt="" /></a>'
		+ '<select name="langpairstub" onChange="langpair.value=this.options[this.selectedIndex].value;this.selectedIndex=0;submit()">'
		+ '<option value="" selected>Translate page to...</option>'
		+ '<option value="en|de">German</option>'
		+ '<option value="en|es">Spanish</option>'
		+ '<option value="en|fr">French</option>'
		+ '<option value="en|it">Italian</option>'
		+ '<option value="en|pt">Portuguese</option>'
		+ '<option value="en|ja">Japanese</option>'
		+ '<option value="en|ko">Korean</option>'
		+ '<option value="en|zh-CN">Chinese (Simplified)</option>'
		+ '</select>'

	}
	w(toolsHTML);
	//alert(toolsHTML);
	w('</div></form></div></div>');
}

function addBookmark() {
	if (ver == 'e3') {
		window.external.AddFavorite(document.location,document.title);
	} else if (ver == 'o4') {
		alert('Press CTRL-T to bookmark: \n' + document.title);
	}
	  else {
		alert('Press CTRL-D to bookmark: \n' + document.title);
	}
}





function displayAlsoBox() {
	var alsoBoxHTML, alsoBoxHTML2, alsoBoxHTML3, alsoBoxHTML4;
	//<!-- also of interest box -->

	alsoBoxHTML = '<div id="social-tools">'
	alsoBoxHTML2 = '<div id="firstgroup"><div class="content-wrap"><div class="content-right"></div><div class="content">'
	alsoBoxHTML3 = '</div></div></div><!--/content,content-wrap,firstgroup-->'
  alsoBoxHTML4 = '</div><!--/social-tools-->'


	w(alsoBoxHTML);
	w(alsoBoxHTML2);
	displaySearchGoogle();
	displayTools();
	//displayShare();
	w(alsoBoxHTML3);
	w(alsoBoxHTML4);
}



function displaySidebarleft() {
    var sidebarleftHTML, sidebarleftHTML2;
    sidebarleftHTML = '<div id="sidebar-left">'
    sidebarleftHTML2 = '</div><!--/sidebar-left-->'

    w(sidebarleftHTML);
    displayNavMenu();
    displayAlsoBox();
    w(sidebarleftHTML2);

}

//FOOTER

function displayFooter() {
	if (!footerCalled) {
//		alert(document.getElementsByTagName("address").length);
		var isLatexPage = (document.getElementsByTagName("address").length != 0) ? true : false;
		var minWidth = (isPrimaryPage) ? 524 : 714;
		var minHeight = (isHomePage) ? 441 : 561;
		var footerHTML = ''
		//if (!isLatexPage) {
			footerHTML += '</div><!--/content -->'
			+ '<div id="footer"><div class="content-right"></div>'
			+ '<div class="content">'
			+ '<div id="copyright-notice">'
			+ '<span class="copyright"><a name="end">'
			+ '<a href="'+urlPrefix+'copyright.shtml">Copyright</a>	&copy; 1996-2009</span> <a href="'+urlPrefix+'">';
			if (isAbstractPage) {
				footerHTML += '<img id="footerlogo" src="' + imgPrefix + 'images/gking_name_sm.gif" height="30" width="119" alt="Gary King" />';
			} else {
				footerHTML += 'Gary King';
			}
			footerHTML += '</a><span class="copyright">, All Rights Reserved.</span>'
			+ '</div><!--/copyright notice-->'
			+ '</div><!--/content-->'
			+ '</div><!--/ footer-->'
			+ '</div><!--/content-wrap-->'
			+ '</div><!--/main-wrap-->'
		//}
		footerHTML += '		<!-- ChangeDetection.com id="2w10djcjjd" -->'
		w(footerHTML);

		// hide old-fashioned latex navigation buttons. -rmesard 23dec2005
		for (var i=0;i<document.images.length;i++) {
			if ( (document.images[i].src.toLowerCase().indexOf( "/home.gif" ) != -1 ) || (document.images[i].src.toLowerCase().indexOf( "/previous_" ) != -1 ) || (document.images[i].src.toLowerCase().indexOf( "/up_" ) != -1 ) || (document.images[i].src.toLowerCase().indexOf( "/next_" ) != -1 ) )
			{
//				document.images[i].width = 0;
//				document.images[i].height = 0;
				document.images[i].style.display = 'none';
			}
		}

/*		for (var i=0;i<document.links.length;i++) {
			alert(document.links[i]);
		}
*/
		if (isPrintPage) {
			gk_RegisterOnLoad(print_page);
			w('<div id="backdiv">');
			if (document.referrer != '') {
				w('<a id="backlink" href="' + document.referrer + '">');
			} else {
				w('<a id="backlink" href="javascript:history.back()">');
			}
			w('&lt;&lt; back</a>')
			w('&nbsp;&nbsp;<a href="javascript:printWin()" title="Print Page" onMouseOver="self.status=this.title;return true;" onMouseOut="self.status=\'\';return true;">print</a>');
			w('</div>');
		}
		footerCalled = true;
	}

//document.write("</script>");
document.write("<script defer=\"defer\" src='http://www.google-analytics.com/urchin.js' type='text/javascript'></script>");
document.write("<script defer=\"defer\" type='text/javascript'>");
document.write("_uacct = \"UA-301128-1\"; ");
document.write("urchinTracker();");
document.write("</script>");
}


function w(thetext) {
	document.writeln(thetext);
}

//alert(document.compatMode)

