// instantiate email XMLHttpRequest object
var emailXMLHttpObj=getXMLHttpRequestObject();

function getXMLHttpRequestObject()
{
    var xmlobj;
    
    // check for existing requests
    if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4)
    {
        xmlobj.abort();
    }
    try
    {
        // instantiate object for Mozilla, Nestcape, etc.
        xmlobj=new XMLHttpRequest();
    }
    catch(e)
    {
        try
        {
            // instantiate object for Internet Explorer
            xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch(e){
            // Ajax is not supported by the browser
            xmlobj=null;
            return false;
        }
    }
   
    return xmlobj;
}

function sendEmailRequest(to, subject, message, optout, name, phone)
{
    emailXMLHttpObj.open('POST','sendmail.php',true);
    emailXMLHttpObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
    emailXMLHttpObj.send("password=babycakes&to=TO:" + to + "&subject=SUBJECT:" + subject + message + "&optedout=" + optout+"&name=NAME:"+name+"&phone=PHONE:"+phone);
    emailXMLHttpObj.onreadystatechange=emailStatusChecker;
}

function emailStatusChecker()
{
    // if mail request is completed
    if(emailXMLHttpObj.readyState==4)
    {
        if(emailXMLHttpObj.status==200)
        {
            // if status == 200 display server response
            displayServerResponse();
        }
        else
        {
            alert('Failed to get response :'+emailXMLHttpObj.statusText);
        }
    }
}

function getServerResponse()
{   
    // display messages by <h1> header
    return emailXMLHttpObj.responseText;  
}