function isBadEmail(str) {
	if (/@.*@/.test(str)) return true;
	if (/[\000-\037 ()<>,;:\\"[\]\177]/.test(str)) return true;
	if (/.+@[A-Za-z0-9\-]+\.[A-Za-z0-9\-.]*/.test(str)) return false;
	return true;
}

var SearchResults = Object();
SearchResults.open = function (itemId) {
	Effect.BlindUp("ItemClosed-" + itemId, { duration: 0.25, queue: "front" });	
	Effect.BlindDown("ItemOpened-" + itemId, { duration: 0.5, queue: "end" });
}
SearchResults.close = function (itemId) {
	Effect.BlindUp("ItemOpened-" + itemId, { duration: 0.5, queue: "front" });	
	Effect.BlindDown("ItemClosed-" + itemId, { duration: 0.25, queue: "end" });
}
	
function signUpErrorHandler() {
	Effect.BlindDown("SignUpPanelErrorMsg", { duration: 0.25 });
	$("SignUpPanelLoading").hide();
	if ($("SignUpPanelForm").hasClassName("Disabled"))
		$("SignUpPanelForm").removeClassName("Disabled");
	new Effect.Opacity("SignUpPanelForm", { from: 0.5, to: 1.0, duration: 0.1 });
}
	
function loginErrorHandler() {
	Effect.BlindDown("MarginLoginErrorMsg", { duration: 0.25 });
	$("MarginLoginLoading").hide();
	if ($("MarginLoginForm").hasClassName("Disabled"))
		$("MarginLoginForm").removeClassName("Disabled");
	new Effect.Opacity("MarginLoginForm", { from: 0.5, to: 1.0, duration: 0.1 });
}

var flashPlayerVersion = swfobject.getFlashPlayerVersion();

document.observe("dom:loaded", function() {

	/*--------------------------------------------------------------------------*/

	if ($("SearchResults")) {
		var itemSets = $("SearchResults").select("div.ItemSet");
		var itemSetCt = itemSets.length;
		for (var i = 0; i < itemSetCt; i++) {
			var itemSet = itemSets[i];
			
			// extract the item id
			var result = /\d+$/.exec(itemSet.id);
			if (result.length > 0) {
				var itemId = result[0];
				
				// get the item description
				var itemOpened = $("ItemOpened-" + itemId);
				var itemOpenedSrc = itemOpened.innerHTML;
				
				var maxCharsPerLine = parseInt(($(itemOpened).getWidth() / 6));	// 5px per character
				var posOfBr = itemOpenedSrc.search(/<br ?\/?>/i);	// <br /> node
				
				// add more link if <div>:
				//   - is greater than 33px (33 = line height * 2)
				//   - has a character count greater than the max characters per line time 2 lines
				//   - contains a <br> node
				if ($(itemOpened).getHeight() >= 33 && ((itemOpenedSrc.length > (maxCharsPerLine * 2)) || (posOfBr != -1))) {
				
					// copy the item description for short description
					var itemClosed = itemOpened.cloneNode(true);
					
					// truncate the short description
					var itemClosedSrc = itemClosed.innerHTML;
					if (posOfBr != -1 && posOfBr <= (maxCharsPerLine * 2)) {
						itemClosedSrc = itemClosedSrc.substring(0, posOfBr);
					}
					else if (itemClosedSrc.charAt(maxCharsPerLine * 2) == " ") {
						itemClosedSrc = itemClosedSrc.substring(0, (maxCharsPerLine * 2));
					}
					else {
						itemClosedSrc = itemClosedSrc.substring(0, (maxCharsPerLine * 2));
						// remove the trailing truncated word 
						itemClosedSrc = itemClosedSrc.replace(/\w+$/, "");
					}
					// remove trailing spaces
					itemClosedSrc = itemClosedSrc.replace(/\s+$/, "");
					// the non-breaking space is added before the link
					// for spacing and to force the link to 'stick' to
					// the last word and prevent the 'More' link from
					// being orphaned onto a newline
					itemClosedSrc += '&nbsp;<a href="javascript: SearchResults.open(' + itemId + '); void 0;" class="MoreBtn">More...</a>';
					itemClosed.innerHTML = itemClosedSrc;
					
					// append the short description
					itemSet.insertBefore(itemClosed, itemOpened);
					
					// append the close button
					var closeBtn = document.createElement("div");
					var closeBtnSrc = '<a href="javascript: SearchResults.close(' + itemId + '); void 0;" class="CloseBtn">(X) Close</a>';
					closeBtn.innerHTML = closeBtnSrc;
					closeBtn.className = "CloseBtn";
					itemOpened.appendChild(closeBtn);
					
					// initialize the short description
					itemClosed.id = "ItemClosed-" + itemId;
					itemClosed.className = "ItemClosed";
					
					// initialize the description
					itemOpened.className = "ItemOpened";	
		
					$("ItemOpened-" + itemId).hide();		
					
					itemSet.style.position = "relative";
				}
			}
		}
	}

	/*--------------------------------------------------------------------------*/

	if ($("ArchiveMenu")) {
		// highlight the link of the current archive year
		var url = window.location.href;
		var archiveLinks = $("ArchiveMenu").select("a");
		var archiveLinkCt = archiveLinks.length;
		for (var i = 0; i < archiveLinkCt; i++) {
			if (archiveLinks[i] == url) {
				archiveLinks[i].addClassName("On");
			}
		} 
	}

	/*--------------------------------------------------------------------------*/
	
	if ($("MarginLoginForm")) {
		
		$("MarginLoginForm","MarginLoginLoading","MarginLoginErrorMsg","MarginUserInfo").invoke("hide");
		
		$("MarginLoginForm").source.value = "Ajax";
		
		if (flashPlayerVersion.major > 8) {
			swfobject.embedSWF("/swf/loading_mc.swf", "MarginLoginLoadingMc", "35", "35", "8.0.0", null, { mcColor: "55707F" }, { wmode: "transparent" });
		}
		
		// initialize form validation
		Event.observe("MarginLoginForm", "submit", function(event) {
			var errorMsg = "";
			var email = $("MarginLoginEmail").value.strip();
			if (email == "") {
				errorMsg += "<li>Please enter email.</li>";
			}
			else if (isBadEmail(email)) {
				errorMsg += "<li>Please enter valid email.</li>";
			}
			if ($("MarginLoginPassword").value.strip() == "") errorMsg += "<li>Please enter password.</li>";
			if (errorMsg != "") {
				errorMsg = "<ul>" + errorMsg + "</ul>";
				$("MarginLoginErrorMsg").innerHTML = errorMsg;
				Effect.BlindDown("MarginLoginErrorMsg", { duration: 0.5 });
				Event.stop(event);	// stop the onsubmit event
			}
			else {
				Effect.BlindUp("MarginLoginErrorMsg", { duration: 0.25 });
				new Ajax.Request("/doclib/doclib_login.cgi", { 
					method: "post",
					parameters: $("MarginLoginForm").serialize(true),
					onCreate: function() {
						Event.stop(event);	// stop the onsubmit event
						$("MarginLoginLoading").show();
						if (!$("MarginLoginForm").hasClassName("Disabled"))
							$("MarginLoginForm").addClassName("Disabled");
					},
					onSuccess: function(transport) {
						// alert(transport.responseText);
						var json = transport.responseJSON;
						if (json.response.status.toLowerCase() == "success") {
							// create cookie
							if (json.response.cookie) document.cookie = json.response.cookie;
							// test cookie support
							if (document.cookie) {
								// load the user's info
								new Ajax.Request("/doclib/doclib_user_info.cgi", { 
									method: "post",
									parameters: { response_format: "html" },
									onSuccess: function(transport) {
										// alert(transport.responseText);
										var response = transport.responseText;
										$("MarginUserInfo").innerHTML = response;
										if ($("UserEmail")) {
											/* 	the user's info must be displayed temporarily in order to get 
												the width of the user's email address
												trailing characters are removed from the email address until 
												the width of the email address is less than the width of the 
												container panel */
											$("MarginUserInfo").show();
											// get the maximum width of the email address
											var maxWidth = $("MarginUserInfo").getWidth() - 10;	// 10 = pixels for "..."
											if ($("UserEmail").offsetWidth > maxWidth) {
												// truncate the user's email address
												var email = $("UserEmail").innerHTML;
												while($("UserEmail").offsetWidth > maxWidth) {
													$("UserEmail").innerHTML = $("UserEmail").innerHTML.substr(0, $("UserEmail").innerHTML.length - 2);
												}
												$("UserEmail").innerHTML += "...";
											}
											$("MarginUserInfo","MarginLoginLoading").invoke("hide");
											new Effect.Parallel([
												new Effect.BlindDown("MarginUserInfo", { sync: true }), 
												new Effect.SlideUp("MarginLoginForm", { sync: true })
											], { duration: 0.5 });
										}
									},
									onFailure: function() {
										// handle login the old-fashion way
										$("MarginLoginForm").source.value = "";
										$("MarginLoginForm").submit();
									}
								});
							}
							else {
								$("MarginLoginErrorMsg").innerHTML = "<p>In order to access restricted documents, you must" +
									" set your browser to allow cookies. This site uses cookies to authenticate users upon" +
									" login and to ensure that only authorized users have access to restricted documents.</p>";
								loginErrorHandler();
							}							
						}
						else if (json.response.status.toLowerCase() == "error") {
							var error_msg = json.response.message;
							if (error_msg.indexOf("The email address and password you entered do not match our records.") != -1) {
								error_msg = '<ul><li>We have recently updated our site, and as a result your' +
									' password may no longer work.<br /><br /><a href="/register/">Click here</a>' +
									' to request a new password. We are sorry for any inconvenience.</li></ul>';
							}
							$("MarginLoginErrorMsg").innerHTML = error_msg;
							loginErrorHandler();
						}
						else {
							// handle login the old-fashion way
							$("MarginLoginForm").source.value = "";
							$("MarginLoginForm").submit();
						}
					},
					onFailure: function() {
						// handle login the old-fashion way
						$("MarginLoginForm").source.value = "";
						$("MarginLoginForm").submit();
					}
				});
			}
		});
	}

	/*--------------------------------------------------------------------------*/
	
	
	// use flash-based titles for non-Linux/Firefox browsers
	if (!(navigator.userAgent.indexOf("Linux") >= 0 && navigator.userAgent.indexOf("Firefox") >= 0)) {
		
		// load the SWF page title over the default <h1>
		// by capturing the contents of the <h1> node
		// retrieve the color of the <h1> node and pass
		// both as parameters to the SWF movie
	
		function toHexFixed(num) {
			return isNaN(num) ? "NaN" : (num < 16 ? "0" + num.toString(16) : num.toString(16));
		}
		
		function RGBtoHEX(rgb) {
			if (/^rgb\(([01]?\d\d?|2[0-4]\d|25[0-5]), ?([01]?\d\d?|2[0-4]\d|25[0-5]), ?([01]?\d\d?|2[0-4]\d|25[0-5])\)$/.test(rgb)) {
				return toHexFixed(Number(RegExp.$1)).toString() + 
					toHexFixed(Number(RegExp.$2)).toString() + 
					toHexFixed(Number(RegExp.$3)).toString();
			}
			else {
				return "E96435";
			}
		}
		
		// take a hex color (#FF0000) and return the numeric part (FF0000)
		function HEXtoNum(hex) {
			if (/^#?([A-Fa-f0-9]{6})$/.test(hex)) {
				return (RegExp.$1).toString();
			}
			else {
				return "E96435";
			}
		}
	
		if ($("PageTitle")) {
			if (flashPlayerVersion.major >= 8) {
				// get the page title's text 
				var pageTitleTxt = $("PageTitle").innerHTML;
				
				// get the page title's color
				var pageTitleColor = "E96435";
				if ($("PageTitle").currentStyle) {
					pageTitleColor = HEXtoNum($("PageTitle").currentStyle["color"]);
				}
				else if (window.getComputedStyle) {
					pageTitleColor = RGBtoHEX(document.defaultView.getComputedStyle($("PageTitle"),null).getPropertyValue("color"));
				}
				
				var pageTitleCopy = $("PageTitle").cloneNode(true);
				pageTitleCopy.className = "PrintTitle";
				pageTitleCopy.id = "PrintTitle";
				$("PageTitle").insert({ after: pageTitleCopy });
				
				// load the movie
				swfobject.embedSWF("/swf/page_title_mc.swf", "PageTitle", "600", "50", "8.0.0", null, { 
					titleTxt: encodeURIComponent(pageTitleTxt), 
					titleColor: encodeURIComponent(pageTitleColor)
					}, { wmode:"opaque" });
			}
		}
	}
	
	/*--------------------------------------------------------------------------*/

	if ($("SignUpLink")) {
		var signUpFormLoaded = false;
		new Ajax.Updater("SignUpLink", "/forms/sign_up_form.html", { 
			method: "get",
			insertion: Insertion.After,
			onSuccess: function() {
				signUpFormLoaded = true;
			},
			onComplete: function() {
				if (signUpFormLoaded) {
					$("SignUpPanel","SignUpPanelLoading","SignUpPanelErrorMsg","SignUpPanelResponse").invoke("hide");

					if (flashPlayerVersion.major > 8) {
						swfobject.embedSWF("/swf/loading_mc.swf", "SignUpPanelLoadingMc", "45", "45", "8.0.0", null, { mcColor: "345E8F" }, { wmode: "transparent" });
					}
	
					Event.observe("SignUpLink", "click", function(event) {
						if ($("SignUpPanel")) {
							Event.stop(event);
							if (!$("SignUpLink").hasClassName("On")) {
								$("SignUpLink").addClassName("On");
								Effect.BlindDown("SignUpPanel", {
									duration: 0.5,
									afterFinish: function () {
										$("SignUpPanelFirstName").focus();
									}
								});
							}
						}
					});	
					Event.observe("SignUpPanelCloseBtn", "click", function(event) {
						Event.stop(event);
						$("SignUpPanelCloseBtn").blur();
						if ($("SignUpLink").hasClassName("On")) {
							Effect.BlindUp("SignUpPanel", {
								duration: 0.5, 
								afterFinish: function () {
									$("SignUpPanel","SignUpPanelLoading","SignUpPanelErrorMsg","SignUpPanelResponse").invoke("hide");
									$("SignUpPanelContent").show();
									$("SignUpPanelForm").enable().show().reset();
									if ($("SignUpLink").hasClassName("On"))
										$("SignUpLink").removeClassName("On");
									if ($("SignUpPanelForm").hasClassName("Disabled"))
										$("SignUpPanelForm").removeClassName("Disabled");
								}
							});
						}
					});
					Event.observe("SignUpPanelForm", "submit", function(event) {
						Event.stop(event);
						var errorMsg = "";
						var email = $("SignUpPanelEmail").value.strip();
						if ($("SignUpPanelFirstName").value.strip() == "") errorMsg += "<li>Please enter your first name.</li>";
						if ($("SignUpPanelLastName").value.strip() == "") errorMsg += "<li>Please enter your last name.</li>";
						if ($("SignUpPanelCompany").value.strip() == "") errorMsg += "<li>Please enter your company name.</li>";
						if (email == "") {
							errorMsg += "<li>Please enter your email address.</li>";
						}
						else if (email != $("SignUpPanelConfirmEmail").value.strip()) {
							errorMsg += "<li>The email address and confirm email address don't match.</li>";
						}
						else if (isBadEmail(email)) {
							errorMsg += "<li>Please enter a valid email address.</li>";
						}
						
						if (errorMsg != "") {
							errorMsg = "<ul>" + errorMsg + "</ul>";
							$("SignUpPanelErrorMsg").innerHTML = errorMsg;
							Effect.BlindDown("SignUpPanelErrorMsg", { duration: 0.25 });
						}
						else {
							Effect.BlindUp("SignUpPanelErrorMsg", { duration: 0.25 });
							new Ajax.Request("/contact/sign_up.cgi", { 
								method: "post",
								parameters: $("SignUpPanelForm").serialize(true),
								onCreate: function() {
									$("SignUpPanelLoading").show();
									if (!$("SignUpPanelForm").hasClassName("Disabled"))
										$("SignUpPanelForm").addClassName("Disabled");
								},
								onSuccess: function(transport) {
									// var json = transport.responseText.evalJSON();
									var json = transport.responseJSON;
									if (json.response.status.toLowerCase() == "success") {
										$("SignUpPanelLoading").hide();
										new Effect.Parallel([
											new Effect.BlindDown("SignUpPanelResponse", { sync: true }), 
											new Effect.SlideUp("SignUpPanelContent", { sync: true })
										], { duration: 1.0 });
									}
									else if (json.response.status.toLowerCase() == "error") {
										$("SignUpPanelErrorMsg").innerHTML = json.response.message;
										signUpErrorHandler();
									}
									else {
										$("SignUpPanelErrorMsg").innerHTML = "<p>I'm sorry. An error occurred while processing" +
											" your request. Please try re-submitting your information in a few minutes. (invalid response)</p>";
										signUpErrorHandler();
									}
								},
								onFailure: function() {
									$("SignUpPanelErrorMsg").innerHTML = "<p>I'm sorry. An error occurred while processing" +
										" your request. Please try re-submitting your information in a few minutes. (no response)</p>";
									signUpErrorHandler();
								}
							});
						}
					});
				}
			}
		});
	}
	
	/*--------------------------------------------------------------------------*/

	/*
	// replace the login form with the user's information
	// if the user is logged in and information is available
	if ($("MarginUserInfo")) {
		var cookies = document.cookie;
		var cookieName = "doclib_user_id";
		var cookieNameStart = cookies.indexOf(cookieName + "=");
		if (cookieNameStart != -1) {
			var cookieValueStart = cookieNameStart + cookieName.length + 1;
			var cookieValueEnd = cookies.indexOf(";", cookieValueStart);
			if (cookieValueEnd == -1) cookieValueEnd = cookies.length;
			if (cookies.substring(cookieValueStart, cookieValueEnd)) {
				$("MarginUserInfo").hide();
				new Ajax.Request("/doclib/doclib_user_info.cgi", { 
					method: "post",
					parameters: { response_format: "html" },
					onSuccess: function(transport) {
						// alert(transport.responseText);
						var response = transport.responseText;
						$("MarginUserInfo").innerHTML = response;
						if ($("UserEmail")) $("UserEmail").hide();
						Effect.BlindDown("MarginUserInfo", { 
							duration: 0.5, 
							afterFinish: function () {
								if ($("UserEmail")) {
									$("UserEmail").show();
									if ($("UserEmail").offsetWidth > 140) {
										var email = $("UserEmail").innerHTML;
										while($("UserEmail").offsetWidth > 140) {
											$("UserEmail").innerHTML = $("UserEmail").innerHTML.substr(0, $("UserEmail").innerHTML.length - 2);
										}
										$("UserEmail").innerHTML += "...";
									}
								}
							}
						});
					},
					onFailure: function() {
						Effect.BlindDown("MarginUserInfo", { duration: 0.5 });
					}
				});
			}
		}
	}
	*/
	
	/*--------------------------------------------------------------------------*/
});