DEBUG = false;

var currentSubsec = null;
var currentSec = null;
var currentCSS = "blinds";
var styleSheets = ["plain","blinds","theta"];
var _isMobile = null;
function el(eltId) {
	return document.getElementById(eltId);
}
function addClass(elt, clsname) {
	if (DEBUG) console.log("addClass("+elt.id+",'"+clsname+"')");
	$(elt).addClass(clsname);
	if (DEBUG) console.log("class="+elt.className);
}
function remClass(elt, clsname) {
	if (DEBUG) console.log("remClass("+elt.id+",'"+clsname+"')");
	$(elt).removeClass(clsname);
}

/** Updates page state for a section and clears the state for subsections */
function setCurrentSection(elt) {
	if (DEBUG) console.log("setCurSec("+((elt==null)?"null":elt.id)+")");
	if (currentSec==elt)
		return;
	//if (DEBUG) console.log(" : currentSec==" + ((currentSec==null)?"null":currentSec.id));
	if (currentSec!=null) {
		remClass(currentSec,"current");
		setCurrentSubsection(null);
	}
	if (elt!=null)
		addClass(elt,"current");
	currentSec = elt;
	if (currentCSS=="theta") {
		// Show only content in the appropriate top-level section
		// Ideally these should be done with CSS, but not all browsers support the ~ operator
		$("#slotted > div,#slotted > h3").hide();
		$("#slotted > h2.current ~ div,#slotted > h2.current ~ h3").show();
		$("#slotted > h2.current ~ h2 ~ div,#slotted > h2.current ~ h2 ~ h3").hide();
		
		updateVerticalText();
	}
	else if (currentCSS=="blinds" || currentCSS=="m") {	// Show all section headings, at most one group of subsection headings, and at most one subsection's content
		// Show only content in the appropriate top-level section
		// Ideally these should be done with CSS, but not all browsers support the ~ operator
		$("#slotted > div,#slotted > h3").hide();
		$("#slotted > h2.current + div,#slotted > h2.current ~ h3").show();
		$("#slotted > h2.current ~ h2 ~ h3").hide();
	}
}

// Getting the rotated text to be positioned correctly with CSS in IE seems impossible, 
// so we move it in an operation that requires its absolute size (depends on length of text).
// Only applies to the 'theta' style.
var verttxt;
function updateVerticalText() {
	//var w = $("#frame").get(0).clientWidth;
	if (verttxt) verttxt.style.top = "";
	else verttxt = $("#updated .msg").get(0);
	
	var sizedTxt = $("#updated .msg > div > div").get(0);
	var txtLength = Math.max(sizedTxt.offsetHeight, sizedTxt.offsetWidth);	// The value we want is offsetHeight in IE but offsetWidth in Firefox and Safari
	verttxt.style.top = ($("#updated .dots").get(0).offsetTop - txtLength) + "px";
}

/** Updates page state for a subsection (but not its parent section) */
function setCurrentSubsection(elt) {
	if (DEBUG) console.log("setCurSub("+((elt==null)?"null":elt.id)+")");
	if (currentSubsec!=null)
		remClass(currentSubsec,"current");
	if (elt!=null)
		addClass(elt,"current");
	currentSubsec = elt;
	
	if (currentCSS=="blinds" || currentCSS=="m") {	// Show at most one group of subsection headings and one subsection's content
		// Show only content in the appropriate subsection
		// Ideally these should be done with CSS, but not all browsers support the ~ operator
		$("#slotted > div,#slotted > h3").hide();
		$("#slotted > h2.current ~ h3,#slotted > h3.current + div").show();
		$("#slotted > h2.current ~ h2 ~ h3").hide();
	}
}

/** Activate a section: update page state, (optionally) jump to the anchor on the page, 
 * and update the positions of navigation links (optionally animated)  */
function activateSection(eltId, anim, jumpAnchor) {
	if (DEBUG) console.log("activateSec("+eltId);
	var elt = el(eltId);
	setCurrentSection(elt);
	
	if (jumpAnchor)
		location = "#" + elt.id;
	
	if (currentCSS=="theta") {
		var iCur = $("h2").index(elt);
		$("h2").each(function (i) {
			$(this).animate({top: ((i-iCur)*25+142) + "px"}, (anim) ? 500 : 0);
		});
		var yyy = 165;
		var items = $("h3.subsection:visible");
		for (var j=items.size()-1; j>=0; j--) {
			var item = items.get(j);
			yyy -= item.clientHeight;
			$(item).css("top", yyy);
		}
	}
	
	document.title = "Nathan Schneider :: " + $("#"+eltId+" a").text();
	
	if (currentCSS=="blinds" && eltId=="pubs") {
		activateSubsection("pubs","pubs_peer");	// Go straight to publication list without displaying a splash image
	}
}
/** Activate a subsection, activating its parent section if necessary and 
 * jumping to the anchor on the page */
function activateSubsection(secId,subsecId) {
	if (DEBUG) console.log("activateSub("+secId+","+subsecId+")");
	var secelt = el(secId);
	if (secelt!=currentSec)
		activateSection(secId, true, false);
	var subsecelt = el(subsecId);
	setCurrentSubsection(subsecelt);
	
	if (currentCSS=="theta") {
		subsecelt.children[0].href = "#" + subsecId;
	}
}

/**
 * Toggles the display of a section, hiding any subsections as necessary
 * @param sec
 * @return
 */
function togSection(sec) {
	if (DEBUG) console.log("togSection("+sec.id+")");	
	if (sec==null) return;
	if ($(sec).hasClass("current"))
		setCurrentSection(null);
	else
		setCurrentSection(sec);
}

/**
 * Toggle the display of a subsection (does not affect its containing section)
 * @param sec Header for the section containing the designated subsection
 * @param subsec
 * @return
 */
function togSubsection(sec,subsec) {
	if (DEBUG) console.log("togSubsection("+subsec.id+")");
	if (subsec==null) return;
	
	if (!$(sec).hasClass("current"))
		setCurrentSection(sec);
	
	if ($(subsec).hasClass("current"))
		setCurrentSubsection(null);
	else
		setCurrentSubsection(subsec);
}

function init() {
	//var ignoreMe = document.body.offsetWidth;	// forces Safari to finish computing layout before proceeding
	
	if (DEBUG && (!$.browser.mozilla || !console || !console.log)) {
		console = {"log": function (s) { alert(s); }};
	}
	if (DEBUG) console.log("init()");
	
	var s = location.search;
	
	// Redirect to mobile style by default for mobile browsers
	if (s=="" && isMobile()) {
		var base = location.href;
		if (location.hash!="")
			base = base.substring(0,base.indexOf("#"));
		location = base + "?view=m";
		return;
	}
	
	$("h2").each(function (i) {
		$(this).addClass("n"+(i+1));	// For IE, since IE8 doesn't support the ':nth-of-type()' pseudoclass
	});
	$("h2,h3,h4[id!=],h5[id!=]").each(function (i) { 
		$(this).wrapInner('<a href="#' + this.id + '" onclick="location=this.href; parseHash();"></a>');
	});
	$(".pubs-list li").each(function (i) {
		$(this).find(".abstract,.bib,.note,.link").wrapAll('<span class="meta"></span>');
	});
	$(".pubs-list li .meta").hide().before('<a href="javascript:return true;" class="meta-link">&raquo;</a> ').prev().click(function() {
		$(this).next().toggle();
		var t = ($(this).text()=='»') ? '«' : '»';
		$(this).text(t);
		updateVerticalText();
	}).hover(function() { if ($(this).text()=='»') { $(this).text('«').next().fadeIn(100); updateVerticalText(); } });
	$(".pubs-list li .meta > *").hide().each(function (i) {
		var type = this.className;
		if (type=="link") {	// move with the [abstract], etc. links so if that content is expanded this link doesn't move
			$(this).insertBefore($(this).parent().find('span:first')).show().after(' ');	// space separating links was being deleted
		}
		else {	// create a link to toggle display of content
			$(this).parent().find('span:first').before('<a href="javascript:return true;" class="' + type + '-link">[' + type + ']</a> ').prev().click(function () {
				$(this).nextAll('.'+type).toggle();
				$(this).toggleClass("selected");
				updateVerticalText();
			});
		}
	});
	
	// Already redirected to mobile style by default for mobile browsers
	currentCSS = "";
	if (s=="?view=plain") {
		setActiveStyleSheet("plain");
		if (isMobile())
			$("#mobileBrowserWarning").show();
	}
	else if (s=="?view=blinds" || s=="?view=theta") {
		var styleTitle = s.substring(s.indexOf("=")+1);
		setActiveStyleSheet(styleTitle);
		if (isMobile())
			$("#mobileBrowserWarning").show();
		else if (!isBrowserCompatible(styleTitle))
			$("#browserWarning").show();
	}
	else if (s=="?view=m") {	// Mobile style
		setActiveStyleSheet("m");
	}
	else {	// Default style
		if (isBrowserCompatible("theta"))
			setActiveStyleSheet("theta");
		else if (isBrowserCompatible("blinds"))
			setActiveStyleSheet("blinds");
		else
			setActiveStyleSheet("plain");
	}
	
	
	// Random Unicode character in Typography section
	loadContent('http://www.ark.cs.cmu.edu/nschneid/unirand/unirand.php', updateVerticalText);
	// Changes the height of the page, hence the callback for updateVerticalText()

	
	if (reply!="")
		getContactInfo();
	
	parseHash();
	
	if (DEBUG) console.log("done with init()");
}

/** Returns whether the browser is compatible with the given style. */
function isBrowserCompatible(styleTitle) {
	if (styleTitle=="plain") return true;
	else if (styleTitle=="theta")	// Uses CSS not supported in IE 7
		return $.support.boxModel && (!$.browser.msie || $.browser.version>7.999);
	else if (styleTitle=="blinds")
		return $.support.boxModel && (!$.browser.msie || $.browser.version>7.999) && !isMobile();
}

function parseHash() {
	if (DEBUG) console.log("parseHash()");
	
	var h = location.hash;
	if (h.indexOf("?")>-1)
		h = h.substr(1,h.indexOf("?"));
	else
		h = h.substr(1);
	
	if (h!="" && (currentCSS=="plain" || h!="contact")) {
		if (h.indexOf("_")>-1) {
			var psecId = h.substring(0,h.indexOf("_"));
			if (currentCSS=="m")
				togSubsection(el(psecId),el(h));
			else if (currentCSS!="plain")
				activateSubsection(psecId, h);
		}
		else {
			if (currentCSS=="m")
				togSection(el(h));
			else
				activateSection(h,true);
		}
	}
	else if (currentCSS!="plain")
		activateSection('abstract',false);	// Show the Abstract section by default
	
}

function setActiveStyleSheet(title) {
   if (DEBUG) console.log("setActiveStyleSheet('"+title+"')");
   var i, a;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
   
   if (title=="m" && $("head meta[name=viewport]").size()==0)
	   $("head").append("<meta content='width=320, user-scalable=yes' name='viewport' />");
   else if (title!="m")
	   $("head meta[name=viewport]").empty();
   
   $("a.changecss").each(function (i) {
	   var targetView = this.id.substr(1);
	   if (targetView.indexOf("_")>-1)
		   targetView = targetView.substring(0,targetView.indexOf("_"));
	   $(this).attr("href","javascript:location=location.href.replace('?view=" + title + "','').replace(location.hash,'') + '?view=" + targetView + "' + location.hash;");
	   $(this).attr("onclick","parseHash();");
   });
   currentCSS = title;
   $("#a"+currentCSS).addClass("currentStyle deactivated").attr("onclick", "return false;");
   
   if (currentCSS=="theta") {
	   var clones = $("h3").clone().attr("class","subsection").each(function (i) {
		  $(this).attr("id",this.id+"_sub");
	   });
	   $("h3").each(function (i) {
		  $(this).after(clones.get(i));
	   });
   }
   else if (currentCSS=="blinds") {	// Extra h3 elements break this view, so remove them
	   $(".subsection").remove();
   }
}

var CAPTCHA_COOKIE_NAME = "captchaAnswer";
var reply = readCookie(CAPTCHA_COOKIE_NAME);
if (reply==null)
	reply = "";

function getTextInput(msg, maxchars) {
	if (currentCSS != "blinds") {
		reply = window.prompt(msg.replace(new RegExp("<i>","gi"),"").replace(new RegExp("</i>","gi"),"")).toUpperCase();
		getContactInfo();
		return;
	}
		
	el("pquestion").innerHTML = msg;
	el("txtinput").maxLength = maxchars;
	el("txtinput").size = maxchars;
	el("acontact").style.display="none";
	el("inputdiv").style.display="inline";
	el("txtinput").focus();
}
function getContactInfo() {
	if (reply.substr(0,3)=="MAM" && reply.substr(3,3)=="MAL") {
		el("inputdiv").style.display="none";
		var eparts = ["", "han", "", "cm", "edu", "nat", "", "", "u.", "@"];
		var acontact = el("acontact");
		acontact.onclick = function () { window.location="mailt" + "o:" + eparts[5] + eparts[1] + eparts[6] + eparts[2] + eparts[7] + eparts[0] + eparts[9] + eparts[3] + eparts[8] + eparts[4]; };
		acontact.innerHTML = eparts[5] + eparts[1] + eparts[6] + eparts[2] + eparts[7] + eparts[0] + eparts[9] + eparts[3] + eparts[8] + eparts[4];
		acontact.style.display="inline";
		//var afteremail = '&ensp;&middot;&ensp; 412.268.4950 &ensp;&middot;&ensp; 2602E <a href="http://www.hcii.cmu.edu/about_us/NSH.html">Newell-Simon Hall</a>';
		//el("afteremail").innerHTML = afteremail;
		
		createCookie(CAPTCHA_COOKIE_NAME, reply, 100);	// Cookie will store the user's answer for 100 days
	}
	else {
		var msg = "Category including cats and elephants, but not lizards:";
		getTextInput(msg, 6);
	}
}
function setReply() {
	reply = el("txtinput").value.toUpperCase();
	getContactInfo();
}

/** Source: http://detectmobilebrowser.com/ 
 * Determine whether the user agent is a mobile browser.
 */
function isMobile() {
	if (_isMobile==null)
		_isMobile = (function(a){if(/android|avantgo|blackberry|blazer|elaine|hiptop|ip(hone|od)|kindle|midp|mmp|mobile|o2|opera mini|palm( os)?|pda|plucker|pocket|psp|smartphone|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce; (iemobile|ppc)|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))return true; return false;})(navigator.userAgent||navigator.vendor||window.opera);
	return _isMobile;
}

$(document).ready(init);

