// JavaScript source code
var xmlHttp = false;
var sAction = "";
function doSubscribe()
{
	
/* Create a new XMLHttpRequest object to talk to the Web server */
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try 
{
  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) 
  {
  try 
  {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch (e2) 
  {
    xmlHttp = false;
  }
}
@end @*/

if (!xmlHttp && typeof XMLHttpRequest != 'undefined') 
{
  xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
	alert("unable to create request");
}

var emailAddress = document.getElementById("email").value;
var subAction = document.getElementsByName("subscribe");
if (subAction[0].checked)
{
	subAction = "subscribe";
	sAction = "Subscribe";
}
else
{
	subAction = "unsubscribe";
	sAction = "Unsubscribe";
}

var APIKey = "211f56ffc1019a15531a388713d42c75-us2";
var ListID = "98425eb8a5";
var method = "listSubscribe";
var extraCommand = "";

if (emailAddress == null || emailAddress == "")
{
	alert("email address is invalid!");
	return;
}

if (emailAddress.indexOf("@") == -1)
{
	alert("email address is invalid!");
	return;
}

if (subAction == "unsubscribe")
{
	method = "listUnsubscribe";
	extraCommand = "&delete_member=true";
	
	document.getElementById("email").value = "Unsubscribing...";
}
else
{
	document.getElementById("email").value = "Subscribing...";
}

var url = "http://us2.api.mailchimp.com/1.3/?method=" + method + "&apikey=" + APIKey + "&id=" + ListID + "&email_address=" + emailAddress + extraCommand;

//alert(subAction + " to " + emailAddress + ": " + url);

// Open a connection to the server
xmlHttp.open("GET", url, true);

 // Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = updatePage;

 // Send the request
xmlHttp.send(null);

}

function updatePage()
{
	if (xmlHttp.readyState == 4) 
	{
	    var response = xmlHttp.responseText;
	    if (response.indexOf("error") == -1)
	    {
			document.getElementById("email").value = sAction +" complete!";
		}
		else
		{
			document.getElementById("email").value = sAction +" failed:" + response;
		}
	}
}
