function email_ok(req)
{
    result = evalJSONRequest(req);

    if (result[0] == "ok")
    {
        ok_result = DIV({}, P({}, result[1]), P({}, A({"href":"/"}, "Return to Home Page")));
        replaceChildNodes("emailform", ok_result);
    }
    else if (result[0] == "error")
    {
        document.getElementById('status_text').style.color = "red";
        document.getElementById('status_text').firstChild.nodeValue = "Error: " + result[1];
    }
    else
    {
        document.getElementById('status_text').style.color = "red";
        document.getElementById('status_text').firstChild.nodeValue = "Error: " + "Unable to send email";
    }
}

function email_failed(req)
{
    document.getElementById('status_text').style.color = "red";
    document.getElementById('status_text').firstChild.nodeValue = "Error: " + "Unable to send email";
}

function send_mail()
{
    req = getXMLHttpRequest();

    emaildataform = document.getElementById('emaildata')

    postdata = {};
    postdata.user_name = emaildataform.user_name.value;
    postdata.user_email_from = emaildataform.user_email_from.value;
    postdata.user_msg = document.getElementById('user_msg').value;
    postdata.user_url = document.URL;
    postdata.user_referer = document.referrer;

    req.open('POST', '/sendemail', true);
    req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    result = sendXMLHttpRequest(req, queryString(postdata));
    result.addCallback(email_ok);
    result.addErrback(email_failed);
}

function initialize_email_form()
{
    cell_style = "margin-bottom: 0.5em;";
    label_style = "font-size:smaller; font-weight: bold;";
    field_style = "background-color:#fff;";

    js_form = FORM({"id":"emaildata", "action":""},
        DIV({"style":cell_style}, DIV({"style": label_style}, "Your Name:"),
            INPUT({"id": "user_name", "style": field_style, "type": "text", "value":"", "size":"70"})),
        DIV({"style":cell_style}, DIV({"style": label_style}, "Your Email Address:"),
            INPUT({"id": "user_email_from", "style": field_style, "type": "text", "value":"", "size":"70"})),
        DIV({"style":cell_style}, DIV({"style": label_style}, "Message:"),
            TEXTAREA({"id": "user_msg", "style": field_style, "rows":"10", "cols":"70"})),
        DIV({"style":cell_style}, SPAN({"id": "status_text", "style": "color: black;"}, " ")),
        DIV(null, INPUT({"id": "send_button", "type":"button", "value": "Send Message", "onclick": "send_mail()"}))
        );

    replaceChildNodes("emailform", js_form);
}

addLoadEvent(initialize_email_form);
