//default the afns_email_alert variable
var afns_email_alert;
if(afns_email_alert == undefined) {
    afns_email_alert = false;
}
var email_form_error_state = false;
var sms_url = afns_base_url+"sms/sms.php";

function email_submit_ticket(theForm) {
    var from_email = $(theForm).find(".email_from").val();
    var to_email = $(theForm).find(".email_to").val();
    if (from_email.length > 40) {
        alert("The from address must be less than 40 characters");
        return false;
    }
    var params = "action=ticket";
    $.post(sms_url, params, function (xml) {
        email_submit_message(theForm, xml);
    });
    return false;
}

function email_clear_status(theForm) {
    email_form_error_state = false;
    $(theForm).find(".email_submit_line").css('visibility', "visible");
    email_setStatus(theForm, '');
}

function email_submit_message(theForm, xml) {
    /* warning: while jquery $("method",xml).text(); is great, ie6 can't handle it */
    var method = xml.documentElement.getElementsByTagName("method")[0].firstChild.nodeValue;
    var result = xml.documentElement.getElementsByTagName("result")[0].firstChild.nodeValue;
    var error = xml.documentElement.getElementsByTagName("error")[0].firstChild.nodeValue;

    if(error != "0") {
        email_error(error);
    } else {
        $(theForm).find(".email_ticket").val(result);
        $(theForm).find(".email_action").val("message");
	params = $(theForm).serializeArray()
        email_setStatus(theForm, 'Sending message...');
        $.post(sms_url, params, function(xml) {
            email_submit_done(theForm, xml);
        });
    }
}

function email_submit_done(theForm, xml) {
    var method = xml.documentElement.getElementsByTagName("method")[0].firstChild.nodeValue;
    var error = xml.documentElement.getElementsByTagName("error")[0].firstChild.nodeValue;

    if (error != "0") {
        email_error(theForm, error);
        email_form_error_state = true;
    } else {
        email_success(theForm);
        $(theForm).add(".email_this").each(function(){this.reset();});
    }
}

function email_error(theForm, error) {
    if (afns_email_alert) {
        alert(error)
    } else {
        email_setStatus(theForm, '<span class="error">' + error + '</span>');
    }
}

function email_success(theForm) {
    var success_msg = "Your message has been sent.";

    if(afns_email_alert) {
        afns_track_click('email_ad_' + $(theForm).find(".email_nid").val());
        alert(success_msg);
    } else {
        afns_track_click('email_' + $(theForm).find(".email_nid").val());
        email_setStatus(theForm, success_msg);
    }
}
function email_setStatus(theForm, html) {
    if(!afns_email_alert) {
        $(theForm).find(".email_status").html(html);
    }
}

function inline_email_this(isBottom) {
    document.getElementById("email_to").value = "Enter Destination Email";
    $('#emtf_inline').toggle();
}

