/* JS Document */
var jiats_reader_url = "/global/php/jiats_reader.php" ; 
var current_issue = 5; // Back up in case Ajax call does not set variable properly
var jiatspwd = "6627fbb19123330fae965ffc3aa756c2";

$.getScript("/collections/texts/jiats/js/md5.js");

// Document Ready Function
$(document).ready( function() {
	// Get current issue number
	 $.ajax({
		url: jiats_reader_url,
		data: "url=/currentIssueNumber/",
		async: true,
		success: function( data ) {
			current_issue = (data * 1);
		}
	 });
	 
	 if(getCookieValue("thl-jiats-pwd") == jiatspwd) {
		$("#shwlf").html('<i>You are logged into the <a id="workedlnk">upcoming edition</a> of JIATS!</i>');
		$("#workedlnk").attr("href",$("#workingButton a").attr("href"));
	} else {
		$("#shwlf").html('<i><a href="#" onclick="javascript: showLogon();">Logon for Editors and Authors of This Issue</a></i>');
	}
		
	$("#masthead-navbar li").click(function () {
		var mclass = Trim($(this).attr("class").replace("alpha",""));
		$("body").attr("class", mclass + " jiats");
	});
	
	$("#masthead-navbar li a").click(function() {
		var hrf = $(this).attr("href");
		var cls = Trim($(this).parent().attr("class").replace("alpha",""));
		$("body").attr("class","jiats " + cls);
		if (hrf.indexOf("wiki=") > -1) { $("body").addClass("wiki"); }
		$("#list1 a.selected").removeClass("selected");
	});
	
	if(isCurrentIssue()) {
		$("body").attr("class", "current jiats");
	} else if (isProtectedIssue()) {
		$("body").attr("class", "working jiats");
	} else if ((window.location.hash).match(/\/\d{2}\//) != null || (window.location.hash).indexOf("downloads") > -1) {
		$("body").attr("class", "archive jiats");
	} else if ((window.location.hash).indexOf("thlpeople") > -1) {
		$("body").attr("class", "contributors jiats");
	}
	

	$("#list1 ul li a").click(function() {
		var bodycls = "home";
		if($(this).attr("href").indexOf("downloads") > -1) { bodycls = "archive";}
		if ($(this).attr("href").indexOf("wiki") > -1) { bodycls += " wiki";}
		$("body").attr("class",bodycls);
	});
	
	if(getCookieValue("thl-jiats-pwd") == jiatspwd) { $("#workingButton").show();} else { $("#workingButton").hide(); }
		
	ActivateLinks(' * ');
	
});

// Other Functions in alphabetical order

function ActivateNavArrows(pref) {
	$(pref + " a.backarrow").click(function() {
		var preva = $(".article-toc li[class!='control'] a.selected").parent().prev().children("a");
		if($(preva).attr("href")) {
			window.location.hash = $(preva).attr("href");
			$(".article-toc li[class!='control'] a.selected").removeClass("selected");
			$(preva).addClass("selected");
		} 
	});
	
	$(pref + " a.forwardarrow").click(function() {
		var preva = $(".article-toc li[class!='control'] a.selected").parent().next().children("a");
		if($(preva).attr("href")) {
			window.location.hash = $(preva).attr("href");
			$(".article-toc li[class!='control'] a.selected").removeClass("selected");
			$(preva).addClass("selected");
		}
	});
	
	$(pref + " a.uparrow").click(function() {
		var preva = $(".article-toc li[class!='control']:eq(0)").children("a");
		if($(preva).attr("href")) {
			window.location.hash = $(preva).attr("href");
			$(".article-toc li[class!='control'] a.selected").removeClass("selected");
			$(preva).addClass("selected");
		}
	});
}

function checkJIATSToc() {
	// I think this is an old outdated function replaced by one below! ndg 4-29-09
	var pgid = $("#jiats-page-id").text();
	var tocid = $("#jiats-toc-id").text();
        if($("#jiats-page-id").length == 1) {
		if((pgid + "-toc") != tocid ) {
			if((pgid == "jiats-general" || pgid == "") && pgid != "jiats-general-toc") {
				loadJIATSMainToc();	
			} else {
				var tocloc = pgid.substr(pgid.indexOf('article-') - 1);
				tocloc = tocloc.replace(/-/g,'/') + "/toc/";
				getJIATSToc(tocloc);
			}
		}
        } 
	fixNavBar();
}

function checkJIATSTocByUrl(url) {
	if ($("#jiats-toc-id").length > 0) {
		var urlid = url.split('/').slice(1,3).join('-');
		var jtocid = ($("#jiats-toc-id").text()).split('-').slice(2,4).join('-');
		if(urlid == jtocid) {return;} // TOC already loaded so return
	}
		
	if(url.search(/\/\d\d\//) > -1 && url.indexOf('announce') == -1 && url.indexOf('downloads') == -1) {
		var jurl = ("/article/" + url + "/toc/");
		getJIATSToc( jurl.replace(/\/\//g,'/').replace(/\/[abc][0-9]+\//,'/'));
	} else {
		if ($("#jiats-toc-id").length == 0 || $("#jiats-toc-id").text() != "jiats-general-toc") { loadJIATSMainToc(); }
	}
}

function doJiatsImgLinks() {
	$(".essay-body a.large-pic").each(function() {
		var winid = "jqmwin" + ($(".jqmWindow").length + 1);
		var mysrc = ($(this).find("img").attr("src")).replace('-sm','');
		var mytitle = $(this).find("img").attr("title");
		var arttitle = ($(".essay-body h2.title").html() == null)?$(".essay-body div.title").html():$(".essay-body h2.title").html();
		if(arttitle == null) { arttitle = "JIATS Article"; } else { arttitle = '&#x201c;' + $.trim(arttitle.replace('class="note','class="note hidden')) +  '&#x201d;'; }
		var myhead = '<h3>Image from ' + arttitle + '</h3>';
		var mycaption = $(this).parent().next("h6").html();
		$("body").append('<div id="' + winid + '" class="jqmWindow" style="overflow: auto; width: 730px;"><div class="closebtn"><a href="#" class="jqmClose">Close</a></div></div>');
		var imgsize = 'width="700px"';
		$("#" + winid).append('<div class="conx-content" style="width:710px;">' + myhead + '<div class="img-left-shadow"><div><img src="' + mysrc + '" title="' + mytitle + '" ' + imgsize + '/></div><h6 style="width: 95%;">' + mycaption + '</h6></div></div>\n');
		var viewvar = getCookieValue('thl-essay-view');
		if( viewvar == "popular") { 
			$("#" + winid).find(".scholar").hide();
			$("#" + winid).find(".popular").show(); 
		} else {
			$("#" + winid).find(".popular").hide(); 
			$("#" + winid).find(".scholar").show();
		}
		$("#" + winid).jqm({trigger: this});
		$("#" + winid).jqmAddClose(".closebtn");
			/*
		var alnk = this;
		$.ajax({
			url: "/global/php/get-image-size.php",
			data: "img=" + mysrc,
			async: false,
			success: function( data ) {
				var imgsize = 'height="500px"';
				if(($(data).find("width").text()) * 1 > 550) { imgsize = 'width="550px"';}
				$("#" + winid)
					.append('<div class="conx-content">' + myhead + '<div class="img-left-shadow"><div><img src="' + mysrc + '" title="' + mytitle + '" ' + imgsize + '/></div><h6>' + mycaption + '</h6></div></div>\n')
					.jqm({trigger: alnk, closeClass: "closebtn"});
			}
		});
		*/
	});
}


function fixNavBar() {
	var myhash = window.location.hash;
	window.status = myhash.indexOf('issue') + " : " + myhash.search(/\/\d+\//);
	if(myhash.indexOf('issue') > -1 || myhash.search(/\/\d+\//) > -1) {
		if(isCurrentIssue()) {
			$("body").attr("class","jiats current");
		} else {
			$("body").attr("class","jiats archive");
		}
	}
}

function getJIATSToc(loc) {
	if(loc.substr(0,1) != '/') {loc = '/' + loc;}
	loc = loc.replace('/all/','/').replace('/notes/','/');
        $.ajax({
		url: jiats_reader_url,
		data: "url=" + loc,
		async: true,
		success: function( data ) {
			var tocloc = $("#list0").parent();
			$("#list0").html(data);
			ActivateNavArrows("#side-column");
			$.ajax({
					url: "/collections/texts/jiats/side-column-ajax.php",
					async: false,
					success: function( data ) {
						var jl1 = $(data).find("#list1");
						$(jl1).find("h4").remove();
						$("#list1").append($(jl1).html());
						$("#list1 h3.head").removeClass("selected").next("ul").hide();
						$("#list1 h3.head:first").addClass("selected");
					}
				});
			InitSideColumn();
			InitAccordion();
			$("#list1 h3").next("ul").hide();
			$("#list1 h3:first").next("ul").show();
			if($("#list1 ul.issue-toc").length = 1) {
			    $("#list1 ul.issue-toc a").removeClass("selected");
			    $("#list1 ul.issue-toc a").each(function() {
				var myhref = $(this).attr("href");
				if (myhref == window.location.hash) {
				    $(this).addClass("selected");
				}
			    });
			}
			
			$(".article-toc a[href^='#jiats']").click(function () {
				var lnkhash = window.location.hash;
				if(lnkhash.indexOf("/all/") > -1) {
					var sectId = ($(this).attr("href")).match(/[abc]\d+/);
					scrollToId(sectId);
					return false;
				} 
				$(".article-toc .selected").removeClass("selected");
				$(this).addClass("selected");
			});
		}
	});
	
	// add click function to TOC links and to buttons to selected chosen section
	$("#list1 ol.article-toc li a").click(function () {  UpdateJIATSTocSelection($(this));   });
}

function isCurrentIssue() {
	var isCurr = false;
	var myhash = window.location.hash;
	if (!myhash.match(/per\d\d\d\d/) && myhash.match(/(\d\d)/)) {
		var myiss = myhash.match(/(\d\d)/)[1] * 1; // the first set of two digits is the issue number in all JIATS urls.
		if(myiss == current_issue) { isCurr = true; }
	} else if(myhash.indexOf('current') > -1) {
		isCurr = true;
	} 
	return isCurr;
}
			
function isProtectedIssue(url) {
	var isProt = false;
	if (typeof(url) == "undefined" || url == "") {url = window.location.hash;}
	if(url.indexOf("/04/winkler/") > -1 || url.indexOf("thlpeople") > -1 || url.indexOf("contributors") > -1) {return false;}
	if (url.match(/(\d\d)/)) {
		var thisiss = url.match(/(\d\d)/)[1] * 1; // the first set of two digits is the issue number in all JIATS urls.
		if(thisiss > current_issue) {
			isProt = true;
		}
	}
	return isProt;
}

function jiatsLogon() {
	var epwd = MD5(document.forms['logonfm'].jpwd.value);
	if(epwd == jiatspwd) {
		writePersistentCookie('thl-jiats-pwd',epwd,"days",1);
		jhash = getCookieValue("jiatsurl");
		if(typeof(jhash) == "undefined" || jhash == false || jhash == "") {
			window.location.href=$("#workingButton a").attr("href");
		} else {
			window.location.href="/collections/texts/jiats/#jiats=" + jhash;
		}
		
		deleteCookie("jiatsurl");
		$("#workingButton").show();
	} else {
		alert("You entered the incorrect password! Please try again or contact a THL administrator!");
	}
}

function loadJIATSMainToc() {
	$("body").append('<div id="toc-temp" class="hide"></div>');
	$.ajax({
		url: "/collections/texts/jiats/side-column-ajax.php",
		async: false,
		success: function( data ) {
			var jl1 = $(data).find("#list1");
			$("#list1").html($(jl1).html());
			InitAccordion();
			InitSideColumn();
			$("#list1 ul li a").click(function() {
				var bodycls = "home";
				if ($(this).attr("href").indexOf("wiki") > -1) { bodycls += " wiki";}
				$("body").attr("class",bodycls);
			});
		}
	});
}

function showAbs(did,lnk) {
	if(did=='all') {
		$("div#abstract-div div").show();
	} else {
		$("div#abstract-div div").hide();
		$("#"+did).show();
	}
	$("#abslinks .selected").removeClass("selected");
	$(lnk).addClass("selected");
}

function showContribs(did,lnk) {
	var sel = "p." + did;
	$("p.all, h3.all").hide();
	if(did != "all") { did += ", h3." + did; }
	$("p." + did).show();
	$("#cntrblinks .selected").removeClass("selected");
	$(lnk).addClass("selected");
}

function showDownloads(did,lnk) {
	$("div[id*=dl_]").removeClass("hidden");
	$("div[id*=dl_]").hide();
	if(did == "all") {$("div[id*=dl_]").show();} else {$("#" + did).show();}
	$("#cntrblinks .selected").removeClass("selected");
	$(lnk).addClass("selected");
}

function switchToLgVid(url,wdth,hgt) {
	var vobj = $(".video-pane object");
	var vlnk = $(".video-pane a.switchvid");
	var oldurl = $(vobj).find("param[name=src]").attr("value");
	var oldw = $(vobj).attr("width");
	var oldh = $(vobj).attr("height");
	$(vobj).remove();
	$(".video-pane").prepend('<object codebase="http://www.apple.com/qtactivex/qtplugin.cab" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="' + wdth + '" height="' + hgt + '"><param value="' + url + '" name="src"><param value="true" name="autoplay"><param value="true" name="controller"><param value="video/quicktime" name="type"><param value="' + wdth + '" name="width"><param value="' + hgt + '" name="height"><param value="http://www.apple.com/quicktime/download/indext.html" name="pluginspage"><embed pluginspage="http://www.apple.com/quicktime/download/" autoplay="true" controller="true" target="myself" type="video/quicktime" src="' + url + '" width="' + wdth + '" height="' + hgt + '"></object>');
	/*
	var oldurl = $(vobj).attr("width",wdth).attr("height",hgt).find("param[name=src]").attr("value");
	$(vobj).attr("width",wdth).attr("height",hgt).find("param[name=src]").attr("value",url);
	$(vobj).find("param[name=width]").attr("value",wdth);
	$(vobj).find("param[name=height]").attr("value",hgt);
	$(vobj).find("embed").attr("src",url).attr("width",wdth).attr("height",hgt);
	*/
	$(vlnk).attr("href","javascript: switchToLgVid('" + oldurl + "','" + oldw + "','" + oldh + "');");
	if(parseInt(oldh) < parseInt(hgt) || parseInt(oldw) < parseInt(wdth)) {
		$(vlnk).html("View Smaller Version – for lower-speed connections");
	} else {
		$(vlnk).html("View Larger Version – for high-speed connections");
	}
}
/*<div class="video-pane">

*/
function UpdateJIATSTocLinks() { // Called from class_external.js in global js folder
	var myhash = window.location.hash;
	var sectLink = $("#list1 ol.article-toc li[class!=control] a.selected");
	var prevLink = $(sectLink).parent().prev("li").find("a").attr("href");
	if(typeof(prevLink) == "undefined") { prevLink = $("#list1 ol.article-toc li[class!=control] a:last").attr("href"); }
	var nextLink = $(sectLink).parent().next("li").find("a").attr("href");
	if(typeof(nextLink) == "undefined") { nextLink = $("#list1 ol.article-toc li[class!=control] a:first").attr("href"); }
	
	// If links are for whole document section, but no longer showing whole document
	if(typeof(prevlink) != "undefined" && prevLink.indexOf("scrollToId") > -1 ) { prevLink = myhash + prevLink.match(/'([abc]\d+)'/)[1] + "/"; } 
	if(typeof(nextLink) != "undefined" && nextLink.indexOf("scrollToId") > -1 ) { nextLink = myhash + nextLink.match(/'([abc]\d+)'/)[1] + "/"; } 
	
	$("body a.prev-button").attr("href", prevLink);
	$("body a.next-button").attr("href", nextLink);
	
	$(".article-toc .selected").removeClass("selected");
	$(".article-toc a[href^='#jiats']").each(function () {
		var mylnk = $(this).attr("href");
		if(mylnk == window.location || mylnk == window.location.href || mylnk == window.location.hash) {
			$(this).addClass("selected");
		}
	});	
	if($(".article-toc .selected").length == 0) { $(".article-toc a[href^='#jiats']:first").addClass("selected"); }
	// Add issue number to download link or remove as necessary
		$("#fxSideMenu a[href*=download]").each(function () {
				if(($("#jiats-page-id").text()).indexOf("issue-") > -1) {
					var myhref = $(this).attr("href");
					if(myhref.indexOf("/download") > -1) {
						var pts = $("#jiats-page-id").text().split("-");
						var issnum = pts[2];
						if(parseInt(issnum) == NaN) { issnum = "" } else {issnum += "/";}
						$(this).attr("href", "#jiats=/" + issnum + "downloads/");
					}
				} else {
					$(this).attr("href", "#jiats=/downloads/");
				}
		});
		
	/*
	if ((window.location.hash).indexOf('/all') == -1) {
		$("#list1 ol.article-toc li a[href*=scrollToId], .shell-1 > .nav-button-span a[href*=scrollToId]").each(function() {
			var myhref = $(this).attr("href");
			var myhash = window.location.hash;
			try {
				myhref = myhash + myhref.match(/'([abc]\d+)'/)[1] + "/";
				$(this).attr("href",myhref);
				$(this).click(function() {GoToPage($(this).attr("href"));});
			} catch (e) {}
		});
	} else {
		$("#list1 ol.article-toc li a[href*=#jiats], .shell-1 > .nav-button-span a[href*=#jiats]").each(function() {
			var myclass = $(this).attr("class");
			if(myclass != "up-button") {
				var myhref = $(this).attr("href");
				var hrparts = myhref.split('/');
				var sectId = hrparts.pop();
				if (typeof(sectId) != "string" || sectId == "") {sectId = hrparts.pop();}
				myhref = "javascript:scrollToId('" + sectId + "');";
				$(this).attr("href",myhref);
				$(this).click(function() {GoToPage($(this).attr("href"));});
			}
		});
	}*/
}

	
	
