﻿var FormSet, FormKeywords, FormInputs, FormSubmit, FormError, FormSuccess, AjaxLoader, FormSubject, FormCaptcha, FormReqFields = '';

$(document).ready(function() {
    FormSet = $('#EmailForm');

    if (FormSet.is('div')) {
        FormSetup();
    }
});

function FormSetup() {
    FormInputs = FormSet.find('input:text,input:radio,input:checkbox,select,textarea');
    FormSubmit = FormSet.find('#Submit');
    //FormKeywords = FormSet.find('input[type="hidden",name="keyword"]');
    //FormKeywords = FormSet.find('input[type="hidden",id="keyword"]');
    FormKeywords = FormSet.find('#keyword');
    FormReqFields = FormSet.find('.Required');

    FormReqFields.each(function () {
        $('<span style="padding-left:5px;color:red;font-weight:bold;">*</span>').insertAfter($(this));
    });

    //Look for the optional form subject. 
    //if not found, set a generic subject.
    FormSubject = FormSet.find('#EmailSubject');
    if (!(FormSubject.is('input[type=hidden]')))
        FormSubject = "Website Contact";
    else
        FormSubject = FormSubject.val();

    //Add ajax load indicator.  keeps user from thinking the form froze.
    FormSubmit.after('<div class="AjaxLoader" style="margin: 0 8px; display:none;"><img style="border:none;" id="imgAjaxLoader" src="' + AbsoluteAppRootPath + 'Assets/images/ajax-loader.gif" width="16px" height="16px"/></div>');
    AjaxLoader = FormSet.find('div.AjaxLoader');
    //add error window in case something goes wrong later.
    FormSet.append('<p class="FormError" style="margin: .5em 0;padding: 1em;background-color: #fafad2;border: 3px #ff0000 solid;color: #ff0000;display: none;"></p>');
    //add success window for when everything goes right.
    FormSet.append('<p class="FormSuccess" style="margin: .5em 0;padding: 1em;background-color: #d2fad7;border: 3px #00ff60 solid;color: #019639;display: none;"></p>');
    FormError = FormSet.find('p.FormError');
    FormSuccess = FormSet.find('p.FormSuccess');

    //Make ajax call to get server time and set to hidden variable for security purposes.
    $.ajax({
        type: 'POST',
        url: AbsoluteAppRootPath + 'ServerCode/FormSecurity.asmx/SetToken',
        data: '{}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(results) {
            FormSet.append('<input id="CaptchaCode" type="hidden" value="' + results.d + '"/>');
            FormCaptcha = FormSet.find('#CaptchaCode');
        },
        error: function(xhr, textStatus) {
            AjaxEmailResponse(false, xhr.statusText);
        }
    });

    FormSubmit.click(SubmitEmail);
}


function SubmitEmail() {
    var invalidData = false;
    var invalidField = '';
    if (FormError.is(':visible')) {
        FormError.hide();
    }
    FormSubmit.attr('disabled', 'disabled');
    AjaxLoader.css('display', 'inline');

    //check for required fields
    FormReqFields.each(function () {
        if ($(this).val() == '') {
            debugger;
            invalidData = true;
            invalidField = $(this).attr('title');
            //break out of .each function
            return false;
        }
    });

    //if anything returned invalid, show it to the user
    if (invalidData) {
        window.setTimeout(function () { AjaxEmailResponse(false, invalidField + ' is required.') }, 2000);
        return;
    }

    var inputIds = FormInputs.map(function() {
        
        if ($(this).attr('title'))
            return $(this).attr('title');
        else
            return $(this).attr('id');
    }).get();

    var inputData = FormInputs.map(function() {
        if ($(this).is('input[type=checkbox]')) {
            if ($(this).is(':checked'))
                return "True";
            else
                return "False";
        }
        return $(this).val();
    }).get();

    var keywords = FormKeywords.map(function() { return $(this).val(); }).get();

    var param = {
        "FieldNames": inputIds,
        "EmailData": inputData,
        "EmailSubject": FormSubject,
        "keywords": keywords
    };

    $.ajax({
        type: 'POST',
        url: AbsoluteAppRootPath + 'ServerCode/FormSecurity.asmx/CheckToken',
        data: "{'CaptchaTime':'" + FormCaptcha.val() + "'}",
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(result) {
            if (result.d == true) {
                $.ajax({
                    type: 'POST',
                    url: AbsoluteAppRootPath + 'ServerCode/Email.asmx/SendEmail',
                    data: JSON.stringify(param),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function(msg) {
                        //set timeout to give illusion the page is thinking
                        //window.setTimeout(AjaxEmailResponse, 2000, true, '');
                        window.setTimeout(function() { AjaxEmailResponse(true, '') }, 2000);
                    },
                    error: function(xhr, textStatus) {
                        //var ajaxerror = eval('(' + xhr.responseText + ')');
                        //window.setTimeout(AjaxEmailResponse, 2000, false, xhr.statusText);
                        window.setTimeout(function() { AjaxEmailResponse(false, xhr.statusText) }, 2000);
                    }
                });
            }
            else {
                //window.setTimeout(AjaxEmailResponse, 2000, false, 'Processing halted for suspicious activity');
                window.setTimeout(function() { AjaxEmailResponse(false, 'Processing halted for suspicious activity.') }, 2000);
            }
        },
        error: function(xhr, textStatus) {
            //var ajaxerror = eval('(' + xhr.responseText + ')');
            //window.setTimeout(AjaxEmailResponse, 2000, false, 'Error checking token: ' + xhr.statusText);
            window.setTimeout(function() { AjaxEmailResponse(false, 'Error checking token: ' + xhr.statusText) }, 2000);
        }
    });

    
}

function AjaxEmailResponse(IsSuccessful, err) {
    AjaxLoader.hide();
    if (IsSuccessful) {
        FormSubmit.val('Thank you!');
        FormSuccess.text('Thank you! Your input was submitted.').slideDown();
        ResetFormFields();
    }
    else {
        FormError.text('We\'re sorry, there was an error submitting your form - ' + err).slideDown();
        FormSubmit.attr('disabled', '');
        AjaxLoader.css('display', 'none');
    }
}

function ResetFormFields() {
    FormInputs.map(function() {
        if ($(this).is('input[type=checkbox]')) {
            $(this).removeAttr('checked');
        }
        else {
            $(this).val('');
        }
    });
}

