var myAccordion;
var stretchers;
var toggles;

function init(sectionTitleToOpen){
	stretchers = document.getElementsByClassName('stretcher');
	toggles = document.getElementsByClassName('toggle');
	myAccordion = new fx.Accordion(toggles, stretchers, {opacity: true, duration: 400});
	var found = false;
	toggles.each(function(toggle, i) {
		if (toggle.title && window.location.href.lastIndexOf(toggle.title) > 30) {
			myAccordion.showThisHideOpen(stretchers[i]);
			found = true;
		}
	});
	if (!found) {
		toggles.each(function(toggle, i) {
			if (toggle.title == sectionTitleToOpen) {myAccordion.showThisHideOpen(stretchers[i]);}
		});
	}
	if (document.getElementById('emailform')) {
		document.forms[0].onsubmit = doAjaxEmailSubmit;
	}
}

function doAjaxEmailSubmit() {
	var theForm = document.forms[0];
	var doPassthrough = false;
	
	if (theForm.email.value.length > 0) {
		var thePost = "email=" + theForm.email.value;
		thePost += "&XID=" + theForm.XID.value;
		thePost += "&ACT=" + theForm.ACT.value;
		thePost += "&RET=" + theForm.RET.value;
		thePost += "&list=" + theForm.list.value;
		
		new ajax (theForm.action, {postBody: thePost, onComplete: ajaxEmailSubmitCallback});
		
	} else {
		alert("Please enter your email address.");
	}
	return doPassthrough;
}

function ajaxEmailSubmitCallback(request){
	if (request.responseText.indexOf("confirmation email") > 0) {
		ajaxEmailSubmitShowResponse("You have been sent a confirmation email. Please click the link contained in the email to activate your mailing list account.");
	} else if (request.responseText.indexOf("already in the mailing list") > 0) {
		ajaxEmailSubmitShowResponse("Your email address is already in the mailing list.");
	} else if (request.responseText.indexOf("Invalid email") > 0) {
		alert("Invalid email address.");
	} else {
		document.body.innerHTML = request.responseText.replace(/JavaScript:history\.go\(-1\)/, window.location.href);
	}
}

function ajaxEmailSubmitShowResponse(responseText) {
	var theForm = new fx.Opacity('emailform', {onComplete: function(){var theResponse = new fx.Opacity('emailresponse'); theResponse.hide(); theResponse.toggle();} });
	var theResponse = new fx.Opacity('emailresponse');
	
	theResponse.setOpacity(0);
	document.getElementById('emailresponse').innerHTML = "<p>" + responseText + "</p>";
	
	theForm.toggle();
}
