﻿$(document).ready(function () {
    ionmx = {};
    ionmx.astepro = function () {
        return {
            errorFields: [],
            validate: function () {
                //Clear previous errors
                $('#successMsg').hide();
                if (ionmx.astepro.errorFields.length > 0) {
                    var label = null;
                    var field = null;
                    jQuery.each(ionmx.astepro.errorFields, function (i, entry) {
                        field = entry.field;
                        label = $('#' + field + '_label');

                        if (label != null) {
                            label.toggleClass('req');
                            if (label.text() == 'Required selection')
                                label.text('');
                            else
                                label.text(label.text().split(' - ')[0]);
                        }
                    });
                }

                ionmx.astepro.errorFields = []; //find a better way to do this.

                //collect any errors
                var email = $('#email').val();
                var confirmEmail = $('#confirmEmail').val();

                if (ionmx.astepro.isNullOrEmpty(email)) {
                    ionmx.astepro.errorFields.push({ field: 'email', errorMsg: 'required' });
                }

                if (ionmx.astepro.isNullOrEmpty(confirmEmail)) {
                    ionmx.astepro.errorFields.push({ field: 'confirmEmail', errorMsg: 'required' });
                }

                if (!(ionmx.astepro.isNullOrEmpty(email) || ionmx.astepro.isNullOrEmpty(confirmEmail))) {
                    if (email != confirmEmail) {
                        ionmx.astepro.errorFields.push({ field: 'email', errorMsg: 'must match with confirmation email' });
                    }
                    else {
                        //Check for invalid email.
                        var emailPattern = /^([a-zA-Z0-9_\.\-''])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                        if (!emailPattern.test(email)) {
                            ionmx.astepro.errorFields.push({ field: 'email', errorMsg: 'invalid email format' });
                        }

                        if (!emailPattern.test(confirmEmail)) {
                            ionmx.astepro.errorFields.push({ field: 'confirmEmail', errorMsg: 'invalid email format' });
                        }
                    }
                }
                /*
                var password = $('#password').val();
                var confirmPassword = $('#confirmPassword').val();
                if (ionmx.astepro.isNullOrEmpty(password)) {
                ionmx.astepro.errorFields.push({ field: 'password', errorMsg: 'required' });
                }

                if (ionmx.astepro.isNullOrEmpty(confirmPassword)) {
                ionmx.astepro.errorFields.push({ field: 'confirmPassword', errorMsg: 'required' });
                }

                if (!(ionmx.astepro.isNullOrEmpty(password) || ionmx.astepro.isNullOrEmpty(confirmPassword))) {
                if (confirmPassword != password) {
                ionmx.astepro.errorFields.push({ field: 'password', errorMsg: 'must match with confirmation password' });
                }
                else {
                //Check for invalid email.
                var passwordPattern = /\d+/;
                if (!passwordPattern.test(confirmPassword) || confirmPassword.length < 6) {
                ionmx.astepro.errorFields.push({ field: 'confirmPassword', errorMsg: 'minimum of six characters, one of which must be a number' });
                }

                if (!passwordPattern.test(password) || password.length < 6) {
                ionmx.astepro.errorFields.push({ field: 'password', errorMsg: 'minimum of six characters, one of which must be a number' });
                }
                }
                }
                */
                if (ionmx.astepro.isNullOrEmpty($('#firstName').val())) {
                    ionmx.astepro.errorFields.push({ field: 'firstName', errorMsg: 'required' });
                }

                if (ionmx.astepro.isNullOrEmpty($('#lastName').val())) {
                    ionmx.astepro.errorFields.push({ field: 'lastName', errorMsg: 'required' });
                }

                if ($('#professionalDesignation').val() == 0) {
                    ionmx.astepro.errorFields.push({ field: 'professionalDesignation', errorMsg: 'Required selection' });
                }

                if ($('#specialty').val() == 0) {
                    ionmx.astepro.errorFields.push({ field: 'specialty', errorMsg: 'Required selection' });
                }
                /*
                if (ionmx.astepro.isNullOrEmpty($('#state_licence_number').val())) {
                ionmx.astepro.errorFields.push({ field: 'state_licence_number', errorMsg: 'required' });
                }

                if (ionmx.astepro.isNullOrEmpty($('#securityAnswer').val())) {
                ionmx.astepro.errorFields.push({ field: 'securityAnswer', errorMsg: 'required' });
                }
                
                if (ionmx.astepro.isNullOrEmpty($('#workAddress1').val())) {
                ionmx.astepro.errorFields.push({ field: 'workAddress1', errorMsg: 'required' });
                }
                */

                //Validate zip code
                var zipPattern = /^\d{5}([\-]\d{4})?$/;
                if (ionmx.astepro.isNullOrEmpty($('#zip').val())) {
                    ionmx.astepro.errorFields.push({ field: 'zip', errorMsg: 'required' });
                }

                else if (!zipPattern.test($('#zip').val())) {
                    ionmx.astepro.errorFields.push({ field: 'zip', errorMsg: 'invalid ZIP code format' });
                }

                /*if (!$('#consent').attr("checked")) {
                ionmx.astepro.errorFields.push({ field: 'consent', errorMsg: 'You must agree to the terms.' });
                }*/


                if (ionmx.astepro.errorFields.length > 0) {
                    var field;
                    var errorMsg;
                    var label = null;
                    var msg = '';
                    jQuery.each(ionmx.astepro.errorFields, function (i, entry) {
                        field = entry.field;
                        errorMsg = entry.errorMsg;
                        msg += errorMsg + '\n';
                        alert(field + " = " + errorMsg);

                        label = $('#' + field + '_label');

                        if (label != null) {
                            label.toggleClass('req');
                            if (ionmx.astepro.isNullOrEmpty(label.text()))
                                label.text(errorMsg);
                            else
                                label.text(label.text() + ' - ' + errorMsg);
                        }
                    });

                    return false;
                }

                return true;


            },
            wireupEventHandlers: function () {
                $('#submitButton').click(function () {
                    ionmx.astepro.tryToSubmit();
                });
            },
            tryToSubmit: function () {

                if (ionmx.astepro.validate()) {

                    var entries = { 'reqData': {
                        'email': $('#email').val(),
                        'confirmEmail': $('#confirmEmail').val(),
                        'firstName': $('#firstName').val(),
                        'lastName': $('#lastName').val(),
                        'professionDesignation': $('#professionDesignation option:selected').text(),
                        'specialy': $('#specialy option:selected').text(),
                        'workAddress1': $('#workAddress1').val(),
                        'workAddress2': $('#workAddress2').val(),
                        'city': $('#city').val(),
                        'state': $('#state option:selected').text(),
                        'zip': $('#zip').val()
                    }
                    }
                    /*
                    var entries = {
                    'email': $('#email').val(),
                    'confirmEmail': $('#confirmEmail').val(),
                    'firstName': $('#firstName').val(),
                    'lastName': $('#lastName').val(),
                    'professionalDesignation': $('#professionalDesignation option:selected').text(),
                    'specialty': $('#specialty option:selected').text(),
                    'workAddress1': $('#workAddress1').val(),
                    'workAddress2': $('#workAddress2').val(),
                    'city': $('#city').val(),
                    'state': $('#state option:selected').text(),
                    'zip': $('#zip').val(),
                    'state_licence_number': $('#state_licence_number').val(),
                    'password': $('#password').val(),
                    'securityAnswer': $('#securityAnswer').val(),
                    'securityQuestion': $('#securityQuestion option:selected').text()
                    }*/
                    var jo = JSON.stringify(entries);

                    var originalImage = $('#submitButton').attr("src");
                    $('#submitButton').attr("src", "../css/images/ajax-loader-1.gif");
                    alert(0);
                    pageTracker._trackEvent('Submissions', 'Signup', 'e-Sampling');
                    alert(1);



                    //////***** REMOVE AFTER DEBUG
                    var jqxhr = $.post("http://www.besentient.com/", function () {
                        alert("success");
                    })
    .success(function () { alert("second success"); })
    .error(function () { alert("error"); })
    .complete(function () { alert("complete"); });
                    alert(jqxhr);.
                    return false;
                    //////***** REMOVE AFTER DEBUG



                    // Set another completion function for the request above
                    jqxhr.complete(function () { alert("second complete"); });

                    $.post('http://www.astepro.com/physicians/registration.ashx',
                        { regData: jo },
                        function (response) {
                            alert(response);
                            if (response == '1') {
                                $('#thankyouPage').removeAttr('style');
                                $('#thankyouPage').attr('style', 'display:block');

                                $('#submitButton').hide();


                            }
                            else if (response = "Error") {
                                alert('An error has occurred.  Please try your request later.');
                                $('#submitButton').attr("src", originalImage);
                            }
                            else
                            //Data validation messages from the server.
                                alert(JSON.parse(response));
                        },
                        'text'
                     )
                     .success(function () { alert("second success"); })
                     .error(function () { alert("error"); });
                    /*
                    $.ajax({
                    type: 'POST',
                    url: 'ajaxHelpers/registration.ashx',
                    regData: jo,
                    Data: jo,
                    dataType: 'JSON',
                    success: function() { $('#successMsg').show(); }
                    });
                    */
                }
                else { window.scroll(0, 0); }

            },
            isNullOrEmpty: function (value) {
                return jQuery.trim(value) == '' || value == null;
            }
        }
    } ();
    ionmx.astepro.wireupEventHandlers();
});

