﻿if (typeof Smith == 'undefined') Smith = {};

Smith.ContactForm = function(SiteRoot) {
    // FOR SOME ODD REASON, TEXT SIZE WASN'T AFFECTED ON CERTAIN CONTROLS
    // WHEN MODIFIED IN CSS FILE.  HAD TO MODIFY MANUALLY HERE.
    $("input").css("font-size","8pt");
    $("label").css("font-size","10pt");
    $("textarea").css("font-size","8pt");
    $("select").css("font-size","8pt").css("width","300px");
    Smith.base.clearSelectedNav();  

    // Hide the state dropdown and label
    $('#lblState, #ddlState').hide();

    /// WIRE EVENTS 

    // change the colors of validated fields back to white when the users click on them.
    $('#txtName, #txtAddress, #txtCity, #ddlState, #txtZip, #ddlCountry, #txtBusPhone, #txtEmail').focus(setValidateColor);

    $('#btnSubmit').click(submit);
    
    // CLEARS FORM
    function clearAll()
    {
        $('#txtName').val('').css('background-color','white');
        $('#txtTitle').val('').css('background-color','white');
        $('#txtCompany').val('').css('background-color','white');
        $('#txtAddress').val('').css('background-color','white');
        $('#txtCity').val('').css('background-color','white');
        $('#txtState').val('').css('background-color','white');
        $('#txtZip').val('').css('background-color','white');
        $('#txtCountry').val('').css('background-color','white');
        $('#txtBusPhone').val('').css('background-color','white');
        $('#txtEmail').val('').css('background-color','white');
        $('#cdyes').attr('checked', '').css('background-color','white');
        $('#cdno').attr('checked', '').css('background-color','white');
        $('#txtComments').val('').css('background-color','white');
        $('#ddlState').val('').css('background-color','white');
        $('#ddlCountry').val('').css('background-color','white');
        $('#txtProvince').val('').css('background-color','white');
    }
    
   // INITIALLY CLEAR FIELDS
   // TEXT AREA ORIGINALLY WAS BEING POPULATED WITH BLANK DATA
   // CAUSING CURSOR TO BE PUSHED TO MIDDLE OF TEXT AREA.
   clearAll();
   
   // CLEAR FIELDS WHEN "CLEAR" BUTTON CLICKED.
    $('#btnClear').click(function() {
        // Clear all the field values.   
       clearAll();

    });

    // If they choose the United States, show the State dropdown,
    // otherwise show the Province textbox
    $('#ddlCountry').change(function() {

        if ($(this).val() == 'US') {
            $('#lblState, #ddlState').show();
            //$('#ddlState')[0].selectedIndex = -1; // jQuery has issue with selectedIndex
            $('#ddlState').attr('selectedIndex', 0); // jQuery has issue with selectedIndex
            $('#lblProvince, #txtProvince').hide();

            // Just for fanciness
            $('#lblZip').html('Zip: <em>*</em>');
        }
        else {
            $('#lblState, #ddlState').hide();
            $('#lblProvince, #txtProvince').show();

            // Just for fanciness
            $('#lblZip').html('Postal Code: <em>*</em>');
        }
    });


    // Numbers only
    $('#txtBusPhone, #txtZip').keyup(function() {
        // Get the last character typed
        var c = $(this).val().charAt($(this).val().length - 1);
    });


    // PRIVATE FUNCTIONS

     function setValidateColor() {
        $(this).css('background-color', '');
    }

    function validateForm() {
        /// <summary>Verifies that all the required fields are filled. Internal Use Only.</summary>

        var errorList = [];

        // check to see if the email address is in the someone@someplace.com format
        var emailRegExp = new RegExp("^[\\w\\+-]+(\\.[\\w\\+-]+)?@((\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\|([\\w\\+-]+\\.[a-zA-Z]{2,}))$");
        var pos = $('#txtEmail').val().search(emailRegExp);

        if ($('#txtName').val().length == 0) {
            errorList[errorList.length] = 'Name cannot be blank.';
            $('#txtName').css('background-color', '#ffc');
        }
        if ($('#txtAddress').val().length == 0) {
            errorList[errorList.length] = 'Mailing Address cannot be blank.';
            $('#txtAddress').css('background-color', '#ffc');
        }
        if ($('#txtCity').val().length == 0) {
            errorList[errorList.length] = 'City cannot be blank.';
            $('#txtCity').css('background-color', '#ffc');
        }
        // only validate the state if the country is US
        if ($('#ddlCountry').val() == 'US') {
            if ($('#ddlState').attr('selectedIndex') == 0) {
                errorList[errorList.length] = 'Please choose a state.';
                $('#ddlState').css('background-color', '#ffc');
            }
        }
        if ($('#txtZip').val().length == 0) {
            // affect the verbiage depending on the country selected.
            ($('#ddlCountry').val() == 'US') ? errorList[errorList.length] = 'Zip Code cannot be blank.' : errorList[errorList.length] = 'Postal Code cannot be blank.';
            $('#txtZip').css('background-color', '#ffc');
        }
        if ($('#ddlCountry').attr('selectedIndex') == 0) {
            errorList[errorList.length] = 'Please choose a country.';
            $('#ddlCountry').css('background-color', '#ffc');
        }

        if ($('#txtEmail').val().length == 0) {
            errorList[errorList.length] = 'Email Address cannot be blank.';
            $('#txtEmail').css('background-color', '#ffc');
        }
        else if (pos < 0) {
            errorList[errorList.length] = 'Email Address format is incorrect.';
            $('#txtEmail').css('background-color', '#ffc');
        }
        return errorList;
    }


    function submit() {
        /// <summary>Validate and submit the data to the server. Internal Use Only.</summary>     

        var errorList = validateForm();
        var errorMsg = '';

        // if there are errors, show the message and exit out.
        if (errorList.length > 0) {
            // loop through the error list and concatenate the messages.
            $.each(errorList, function(i) {
                errorMsg += errorList[i] + '<br />';
            });
            Smith.base.ShowModal('Required', errorMsg);
            return;
        }

        // package up all the values
        var StateProvince
        
        // GET STATE/PROVINCE VAL
        if ($("#ddlState").val() == -1){
            StateProvince = $("#txtProvince").val();
        }
        else{
            StateProvince = $('#ddlState').val()
        }
        var arInfo = [$('#txtName').val(),
                       $('#txtTitle').val(),
                       $('#txtCompany').val(),
                       $('#txtAddress').val(),
                       $('#txtCity').val(),
                       StateProvince,
                       $('#txtZip').val(),
                       $('#ddlCountry').val(),
                       $('#txtBusPhone').val(),
                       $('#txtEmail').val(),
                       $('#txtFax').val(),
                       $('#Send01').attr('checked'),
                       $('#Send02').attr('checked'),
                       $('#Send03').attr('checked'),
                       $('#Send04').attr('checked'),
                       $('#Send05').attr('checked'),
                       $('#Send06').attr('checked'),
                       $('#Send07').attr('checked'),
                       $('#notifyEmail').attr('checked'),
                       $('#notifyFax').attr('checked'),
                       $('#txtComments').val()];

        // off it goes
        $.ajax({
            type: 'POST',
            url: SiteRoot + 'Services/Generic.asmx/SubmitContactInfo',
            data: '{ "ContactInfo" : [ "' + arInfo.join('", "') + '" ] }',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(result) {
                Smith.base.ShowModal('Success', result.d);
            },
            error: function(result) {
                // Parse the data
                (typeof result == 'String') ? result = $.parseJSON(result.d) : result = result.d;
                Smith.base.ShowModal('Error', result._message);
            }
        });

    }

};

