$(document).ready(function() {
    /* -------------------------------------------------- */
    /* prevent enter keypress on the registration form, which causes a form submit that triggers the search */

    $('#reg-form').bind('keypress', function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
        }
    });
    /* -------------------------------------------------- */

    /* -------------------------------------------------- */
    /* preload images */

    $.imgpreload('/images/ajax-loader2.gif', {});
    /* -------------------------------------------------- */

    /* -------------------------------------------------- */
    /* set up the registration section show/hide */

    function expandRegSection(header) {
        var regSectionFieldset = header.parents('.babyclub-reg-section').find('fieldset');
	header.css('background-position', 'left -28px');
	regSectionFieldset.show();
	//header.closest('.babyclub-reg-section-filled').removeClass('babyclub-reg-section-filled').addClass('babyclub-reg-section');
	header.closest('.babyclub-reg-section-header').css('background-position', 'left bottom');
	header.closest('.babyclub-reg-section').find('.babyclub-reg-section-bottom-filled').removeClass('babyclub-reg-section-bottom-filled').addClass('babyclub-reg-section-bottom');
    }
    function contractRegSection(header) {
        var regSectionFieldset = header.parents('.babyclub-reg-section').find('fieldset');
	header.css('background-position', 'left 5px');
	regSectionFieldset.hide();
	//header.closest('.babyclub-reg-section').removeClass('babyclub-reg-section').addClass('babyclub-reg-section-filled');
	header.closest('.babyclub-reg-section-header').css('background-position', 'left top');
	header.closest('.babyclub-reg-section').find('.babyclub-reg-section-bottom').removeClass('babyclub-reg-section-bottom').addClass('babyclub-reg-section-bottom-filled');
    }

    function showRegSection(sectionNr) {
	expandRegSection($('.babyclub-reg-section-header-inner:eq(' + sectionNr + ')'));
    }

    // hide all and show the first section, on first load    
    $('.babyclub-reg-section-header-inner').each(function(index) {
	contractRegSection($(this));
    });
    showRegSection(0)

    // the show/hide click handler
    $('.babyclub-reg-section-header-inner').click(function() {
        var regSectionFieldset = $(this).parents('.babyclub-reg-section').find('fieldset');
        if (regSectionFieldset.is(':visible')) {
		contractRegSection($(this));
        }
        else {
		expandRegSection($(this));
        }
    });
    /* -------------------------------------------------- */

    /* -------------------------------------------------- */
    /* display a check and auto-expand the next section when all required fields in the current section are filled out correctly. */
    /* error messages are only displayed once the form is submitted (except in specific cases). */
    /* when validating a section, remove the related messages if it exists (in case the form has already been submitted). */

    function markValid(sectionNr)
    {
        var currentSectionHeader = $('.babyclub-reg-section-header:eq(' + (sectionNr) + ')');
        if (currentSectionHeader.find('img').length == 0)
            currentSectionHeader.prepend($('<img />').attr('src', '/images/babyclub/babyclub-section-complete.png').attr('alt', 'Complete').attr('class', 'babyclub-section-complete'));
    }
    
    function clearValid(sectionNr)
    {
        var currentSectionHeader = $('.babyclub-reg-section-header:eq(' + (sectionNr) + ')');
        currentSectionHeader.find('img').remove();
    }

    function removeErrorMsgAndLabelHighlight(label, messageField, message)
    {
        if (label != null)
            label.removeClass('highlight-label');
            
        if (messageField != null)
        {
            messageField.html(messageField.html().replace(message + ' <br />', ''))
            messageField.html(messageField.html().replace(message + ' <br/>', ''))
            messageField.html(messageField.html().replace(message + ' <br>', ''))
            messageField.html(messageField.html().replace(message + ' <BR>', ''))
        }
    }

    function addErrorMsgAndLabelHighlight(label, messageField, message, messagesToRemove)
    {
        removeErrorMsgAndLabelHighlight(label, messageField, message);

        var messageFieldContent = messageField.html().replace('<p class="highlight-message">', '').replace('</p>', '');

        $.each(messagesToRemove, function(item) {
            messageFieldContent.replace(messagesToRemove[item] + ' <br />', '');
            messageFieldContent.replace(messagesToRemove[item] + ' <br/>', '');
            messageFieldContent.replace(messagesToRemove[item] + ' <br>', '');
            messageFieldContent.replace(messagesToRemove[item] + ' <BR>', '');
        });

        messageField.html('<p class="highlight-message">' + messageFieldContent + message + ' <br /></p>')

        label.addClass('highlight-label');
    }

    function validatePersonalDetailsSection() {
        var isValid = true;
        
        if ($('#' + drpTitleId).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + drpTitleId).parents('.fieldset-row'), $('#' + spnPersonalDetailsFeedbackId), 'Please choose a title.')
        else
            isValid = false;

        if ($('#' + txtFirstNameId).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + txtFirstNameId).parents('.fieldset-row'), $('#' + spnPersonalDetailsFeedbackId), 'Please enter your first name.')
        else
            isValid = false;

        if ($('#' + txtSurnameId).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + txtSurnameId).parents('.fieldset-row'), $('#' + spnPersonalDetailsFeedbackId), 'Please enter your surname.')
        else
            isValid = false;
        
        if (isValidDate($('#' + drpBabyBirthDateDayId).val() + '/' + $('#' + drpBabyBirthDateMonthId).val() + '/' + $('#' + drpBabyBirthDateYearId).val()))
            removeErrorMsgAndLabelHighlight($('#' + drpBabyBirthDateDayId).parents('.fieldset-row'), $('#' + spnPersonalDetailsFeedbackId), "Please enter your baby's date of birth.")
        else
            isValid = false;
        
        if (getDate($('#' + drpBabyBirthDateDayId).val() + '/' + $('#' + drpBabyBirthDateMonthId).val() + '/' + $('#' + drpBabyBirthDateYearId).val()) <= getDate(minBabyDOB)) 
            removeErrorMsgAndLabelHighlight($('#' + drpBabyBirthDateDayId).parents('.fieldset-row'), $('#' + spnPersonalDetailsFeedbackId), 'Please enter a valid date of birth.')
        else
            isValid = false;
        
        if (getDate($('#' + drpBabyBirthDateDayId).val() + '/' + $('#' + drpBabyBirthDateMonthId).val() + '/' + $('#' + drpBabyBirthDateYearId).val()) >= getDate(maxBabyDOB)) 
            removeErrorMsgAndLabelHighlight($('#' + drpBabyBirthDateDayId).parents('.fieldset-row'), $('#' + spnPersonalDetailsFeedbackId), "We're sorry, but currently our baby club is only for babies in their first year.")
        else
            isValid = false;
            
        // if the full date of birth has been entered but it is invalid, display a message
        if ($('#' + drpBabyBirthDateDayId).val() != 0 && $('#' + drpBabyBirthDateMonthId).val() != 0 && $('#' + drpBabyBirthDateYearId).val() != 0)
        {
            if (getDate($('#' + drpBabyBirthDateDayId).val() + '/' + $('#' + drpBabyBirthDateMonthId).val() + '/' + $('#' + drpBabyBirthDateYearId).val()) > getDate(minBabyDOB)) 
                addErrorMsgAndLabelHighlight($('#' + drpBabyBirthDateDayId).parents('.fieldset-row'), $('#' + spnPersonalDetailsFeedbackId), 'Please enter a valid date of birth.', ['Please enter a valid date of birth.', "We're sorry, but currently our baby club is only for babies in their first year."]);
            
            if (getDate($('#' + drpBabyBirthDateDayId).val() + '/' + $('#' + drpBabyBirthDateMonthId).val() + '/' + $('#' + drpBabyBirthDateYearId).val()) < getDate(maxBabyDOB)) 
                addErrorMsgAndLabelHighlight($('#' + drpBabyBirthDateDayId).parents('.fieldset-row'), $('#' + spnPersonalDetailsFeedbackId), "We're sorry, but currently our baby club is only for babies in their first year.", ['Please enter a valid date of birth.', "We're sorry, but currently our baby club is only for babies in their first year."]);
        }
        
        if (isValid)
        {
            markValid(0);
            showRegSection(1);
        }
        else
            clearValid(0);
    }
    
    $('#you-and-your-baby-section :input').change(function() {
        validatePersonalDetailsSection();
    }).keyup(function() {
        $(this).trigger('change');
    });

    function validateAddressSection() {
        var isValid = true;

        if ($('#' + txtHouseNrId).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + txtHouseNrId).parents('.fieldset-row'), $('#' + spnAddressFeedbackId), 'Please enter your house/flat number.')
        else
            isValid = false;

        if ($('#' + txtAddress1Id).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + txtAddress1Id).parents('.fieldset-row'), $('#' + spnAddressFeedbackId), 'Please enter the first line of your address.')
        else
            isValid = false;

        if ($('#' + txtPostCodeId).val() != '' && $('#' + txtPostCodeId).val().length >= 5)
            removeErrorMsgAndLabelHighlight($('#' + txtPostCodeId).parents('.fieldset-row'), $('#' + spnAddressFeedbackId), 'Please enter your postcode.')
        else
            isValid = false;

        if (isValid)
        {
            markValid(1);
            showRegSection(2);
        }
        else
        {
            clearValid(1);
        }
    }
    
    $('#your-address-section :input').change(function() {
        validateAddressSection();
    }).keyup(function() {
        $(this).trigger('change');
    });

    function validateMembershipSection() {
        var isValid = true;

        if ($('#' + txtEmailId).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + txtEmailId).parents('.fieldset-row'), $('#' + spnMembershipFeedbackId), 'Please enter your email address.')
        else
            isValid = false;

        if ($('#' + txtEmailId).val().match(/^[a-zA-Z0-9'_]+([-+.][a-zA-Z0-9'_]+)*@[a-zA-Z0-9'_]+([-.][a-zA-Z0-9'_]+)*\.[a-zA-Z0-9'_]+([-.][a-zA-Z0-9'_]+)*$/))
            removeErrorMsgAndLabelHighlight($('#' + txtVerifyEmailId).parents('.fieldset-row'), $('#' + spnMembershipFeedbackId), 'Please enter a valid email address.')
        else
            isValid = false;

        if ($('#' + txtVerifyEmailId).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + txtVerifyEmailId).parents('.fieldset-row'), $('#' + spnMembershipFeedbackId), 'Please verify your email address.')
        else
            isValid = false;

        if ($('#' + txtEmailId).val() == $('#' + txtVerifyEmailId).val())
            removeErrorMsgAndLabelHighlight($('#' + txtVerifyEmailId).parents('.fieldset-row'), $('#' + spnMembershipFeedbackId), 'Please verify your email address and ensure that it is the same as the first email address.')
        else
            isValid = false;

        if ($('#' + txtPasswordId).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + txtPasswordId).parents('.fieldset-row'), $('#' + spnMembershipFeedbackId), 'Please enter your password.')
        else
            isValid = false;

        if ($('#' + drpReceivePacksEmailId).val() != '')
            removeErrorMsgAndLabelHighlight($('#' + drpReceivePacksEmailId).parents('.fieldset-row'), $('#' + spnMembershipFeedbackId), 'Please select if you would like to receive our free baby packs and email advice for you and your baby.')
        else
            isValid = false;

        if (isValid)
        {
            markValid(2);
            showRegSection(3);
        }
        else
            clearValid(2);
    }
    
    $('#your-membership-section :input').change(function() {
        validateMembershipSection();
    }).keyup(function() {
        $(this).trigger('change');
    });

    function validateRegisterSection() {
        var isValid = true;

        if ($('#' + chkPrivacyPolicyId + ':checked').length == 1)
            removeErrorMsgAndLabelHighlight($('#' + chkPrivacyPolicyId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the privacy policy.')
        else
            isValid = false;

        if ($('#' + chkTermsId + ':checked').length == 1)
        {
            removeErrorMsgAndLabelHighlight($('#' + chkTermsId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the <br />terms & conditions.')
            removeErrorMsgAndLabelHighlight($('#' + chkTermsId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the <br/>terms & conditions.')
            removeErrorMsgAndLabelHighlight($('#' + chkTermsId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the <br>terms & conditions.')
            removeErrorMsgAndLabelHighlight($('#' + chkTermsId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the <BR>terms & conditions.')
            removeErrorMsgAndLabelHighlight($('#' + chkTermsId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the <br />terms &amp; conditions.')
            removeErrorMsgAndLabelHighlight($('#' + chkTermsId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the <br/>terms &amp; conditions.')
            removeErrorMsgAndLabelHighlight($('#' + chkTermsId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the <br>terms &amp; conditions.')
            removeErrorMsgAndLabelHighlight($('#' + chkTermsId).parents('.reg-form-join-section-input').parent('div'), $('#' + spnJoinInFeedbackId), 'Please accept the <BR>terms &amp; conditions.')
        }
        else
            isValid = false;
    }
    
    $('#join-in-section :input').change(function() {
        validateRegisterSection();
    }).keyup(function() {
        $(this).trigger('change');
    });

    /* -------------------------------------------------- */

    /* -------------------------------------------------- */
    /* set up the date picker */

    $('#' + hidBabyBirthDateId).datepicker(
	{
	    prevText: '', nextText: '', buttonImage: '/images/cal-icon2.gif', buttonImageOnly: true, showOn: 'both',
	    minDate: '-1y', maxDate: '+9m',
	    buttonText: 'Calender',
	    onSelect: function(date) {
	        $('#' + drpBabyBirthDateDayId).val(new Date($('#' + hidBabyBirthDateId).val()).getDate());
	        $('#' + drpBabyBirthDateMonthId).val(new Date($('#' + hidBabyBirthDateId).val()).getMonth() + 1);
	        $('#' + drpBabyBirthDateYearId).val(new Date($('#' + hidBabyBirthDateId).val()).getFullYear());
	        validatePersonalDetailsSection();
	        ;
	    }
	});
    /* -------------------------------------------------- */

    /* -------------------------------------------------- */
    /* set up the password strength indicator */

    $('#' + txtPasswordId).bind('keyup', checkPassword);

    function isCommonPassword(strPassword)
    {
	var result = false;

	$.each(commonPasswords, function(index) { 
		if (strPassword.toUpperCase().indexOf(commonPasswords[index].toUpperCase()) != -1) {result = true;}
	});

	if (strPassword.toUpperCase().indexOf('aaaaaaaa'.toUpperCase()) != -1) {result = true;}
	return result;
    }

    function checkPassword()
    {
	// Get the password
	var strPassword = $('#' + txtPasswordId).val();
	var repeatChars = false;

	var lc = 0;
	var uc = 0;
	var num = 0;
	var sc = 0;
	var TotalStrength = 1;

	// Check to see if the password meets the minimum length
	if ((strPassword.length >= 8) && !isCommonPassword(strPassword))
	{
		// Cycle through and set each indicator to show if Upper, Lower, Numeric and Special charators are being used
		var charPassword = strPassword.split('');
	        for (i=0; i<charPassword.length; i++)
	        {
	            if (charPassword[i].match(/[a-z]/g)) {lc = 1;}
	            else if (charPassword[i].match(/[A-Z]/g)) {uc = 1;}
	            else if (charPassword[i].match(/[0-9]/g)) {num = 1;}
	            else {sc = 1;} 

		    if (i > 0 && charPassword[i] == charPassword[i-1]) {repeatChars = true;}
	        }

		// Get the total password strength
		TotalStrength = lc + uc + num + sc;

		// Adjust the strength depending upon the length and any repeat charactors
		//
		// Only check adjust length if more than two indicators are set
		// this stops passwords like @1111111111 being classed as recommended
		if (TotalStrength > 2)
		{
			// A length of 9 scores an extra one but greater than 9 scores an extra 2
			if (strPassword.length == 9) {TotalStrength++;}
			if (strPassword.length > 9) {TotalStrength = TotalStrength + 2;}
			if (repeatChars) {TotalStrength--;}
		}
	}
	else if (strPassword.length == 0)
	{
		TotalStrength = 0;
	}

        if (TotalStrength == 0)
        { 
            $('#password-strength-image').css('background-position', 'left 0px');
            $('#divPasswordStrengthCopy').html('');
        }
        else if (TotalStrength == 1)
        {
            $('#password-strength-image').css('background-position', 'left -20px');
            $('#divPasswordStrengthCopy').html('Weak');
        }
        else if (TotalStrength == 2)
        {
            $('#password-strength-image').css('background-position', 'left -40px');
            $('#divPasswordStrengthCopy').html('Average');
        }
        else if (TotalStrength == 3)
        {
            $('#password-strength-image').css('background-position', 'left -60px');
            $('#divPasswordStrengthCopy').html('Strong');
        }
        else if (TotalStrength == 4)
        {
            $('#password-strength-image').css('background-position', 'left -80px');
            $('#divPasswordStrengthCopy').html('Strong');
        }
        else if (TotalStrength == 5)
        {
            $('#password-strength-image').css('background-position', 'left -100px');
            $('#divPasswordStrengthCopy').html('Strong');
        }
        else if (TotalStrength == 6)
        {
            $('#password-strength-image').css('background-position', 'left -120px');
            $('#divPasswordStrengthCopy').html('Recommended');
        }

        //$('#divPasswordStrengthCopy').html('TotalStrength: ' + TotalStrength + '; lc=' + lc + '; uc=' + uc + ';num=' + num + '; sc=' + sc + '; repeatChars=' + repeatChars);

    }
    /* -------------------------------------------------- */

    /* -------------------------------------------------- */
    /* ajaxify the address finder */

    $('#divInterimAddress').hide();
    $('#divConfirmInterimAddress').hide();

    // trigger the find address event handler when the user hits enter when in the text field
    $('#' + txtPostcodeFinderId).bind('keypress', function(event) {
        if (event.keyCode == 13) {
            $('#' + btnFindAddressId).trigger('click'); 
        }
    });

    // the find address click event handler
    $('#' + btnFindAddressId).click(function(event) {
    
        $('#' + spnAddressFinderFeedbackId).html('');
        if ($('#' + txtPostcodeFinderId).val() == '')
        {
            $('#' + spnAddressFinderFeedbackId).html('<p class="highlight-message">Please enter a postcode.</p>');
            return false;
        }
    
        $('#babyclub-reg-address-finder .highlight-message').remove();
        $('#babyclub-reg-address-finder *').removeClass('highlight-label');

        $('#divInterimAddress').hide();
        $('#divConfirmInterimAddress').hide();
        
        $('#address-finder-loader').html('<img src="/images/ajax-loader2.gif" alt="Loading" />');
        $('#' + btnFindAddressId).hide();

        var str = $('form').serialize() + '&ajax=findaddress';

        $.ajax
        ({
            type: "POST",
            //url: "/baby-club/register.aspx?ajax=findaddress",
            data: str,

            // if ajax call succeeded...
            success: function(data, textStatus, XMLHttpRequest) {
                var jsonResponse = $.parseJSON(data);
                if (jsonResponse != null && jsonResponse['success'] != null && jsonResponse['success'] == 'false') 
                {
                    if (jsonResponse['invalid_fields'] != null) 
                    {
                        $.each(jsonResponse['invalid_fields'], function(item) {
                            $('#' + jsonResponse['invalid_fields'][item]).parents('.fieldset-row').addClass('highlight-label');
                        });
                    }
                    if (jsonResponse['messages'] != null) 
                    {
                        $.each(jsonResponse['messages'], function(item) {
                            $('#' + jsonResponse['messages'][item].control).html('<p class="highlight-message">' + jsonResponse['messages'][item].message + '</p>');
                        });
                    }
                }
                else if (jsonResponse != null && jsonResponse['success'] != null && jsonResponse['success'] == 'true' && jsonResponse['address_list'] != null) 
                {
                    $('#' + drpInterimAddressId + ' option').remove();
                    $.each(jsonResponse['address_list'], function(item) {
                        $('#' + drpInterimAddressId).append($('<option />').val(jsonResponse['address_list'][item].Key).text(jsonResponse['address_list'][item].Value));
                    });

                    $('#divInterimAddress').show();
                    $('#divConfirmInterimAddress').show();
                }
                else 
                {
                    $('#' + spnAddressFinderFeedbackId).html('<p class="highlight-message">Unexpected response.</p>');
                }
            },

            // ajax call failed...
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#' + btnFindAddressId).unbind('click'); // unbind the ajax call from the click
                $('#' + btnFindAddressId).trigger('click'); // trigger the click to post as usual because ajax failed (javascript works but the ajax call or response may be blocked)
            },

            // ajax call completed (succeeded or failed)
            complete: function(XMLHttpRequest, textStatus) {
                $('#address-finder-loader').html('');
                $('#' + btnFindAddressId).show();
            }
        });
        event.preventDefault();
    });

    // the confirm address click event handler
    $('#' + btnConfirmAddressId).click(function(event) {

        $('#babyclub-reg-address-finder .highlight-message').remove();
        $('#babyclub-reg-address-finder *').removeClass('highlight-label');

        $('#address-finder-loader').html('<img src="/images/ajax-loader2.gif" alt="Loading" />');
        $('#' + btnConfirmAddressId).hide();

        var str = $('form').serialize() + '&ajax=confirmaddress';

        $.ajax
        ({
            type: "POST",
            //url: "/baby-club/register.aspx?ajax=confirmaddress",
            data: str,

            // if ajax call succeeded...
            success: function(data, textStatus, XMLHttpRequest) {
                var jsonResponse = $.parseJSON(data);
                if (jsonResponse != null && jsonResponse['success'] != null && jsonResponse['success'] == 'false') 
                {
                    if (jsonResponse['invalid_fields'] != null) 
                    {
                        $.each(jsonResponse['invalid_fields'], function(item) {
                            $('#' + jsonResponse['invalid_fields'][item]).parents('.fieldset-row').addClass('highlight-label');
                        });
                    }
                    if (jsonResponse['messages'] != null) 
                    {
                        $.each(jsonResponse['messages'], function(item) {
                            $('#' + jsonResponse['messages'][item].control).html('<p class="highlight-message">' + jsonResponse['messages'][item].message + '</p>');
                        });
                    }
                }
                else if (jsonResponse != null && jsonResponse['success'] != null && jsonResponse['success'] == 'true' && jsonResponse['update_fields'] != null) 
                {
                    $.each(jsonResponse['update_fields'], function(item) {
                        $('#' + jsonResponse['update_fields'][item].control).val(jsonResponse['update_fields'][item].value);
                    });

                    validateAddressSection();
                }
                else 
                {
                    $('#' + spnAddressFinderFeedbackId).html('<p class="highlight-message">Unexpected response.</p>');
                }
            },

            // ajax call failed...
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#' + btnConfirmAddressId).unbind('click'); // unbind the ajax call from the click
                $('#' + btnConfirmAddressId).trigger('click'); // trigger the click to post as usual because ajax failed (javascript works but the ajax call or response may be blocked)
            },

            // ajax call completed (succeeded or failed)
            complete: function(XMLHttpRequest, textStatus) {
                $('#address-finder-loader').html('');
                $('#' + btnConfirmAddressId).show();
            }
        });
        event.preventDefault();
    });

    /* -------------------------------------------------- */

    /* -------------------------------------------------- */
    /* ajaxify the registration form */

    $('#' + btnSubmitId).click(function(event) {

        $('.highlight-message').remove();
        $('*').removeClass('highlight-label');
        
        $('#register-loader').html('<img src="/images/ajax-loader2.gif" alt="Loading" />');
        $('#' + btnSubmitId).hide();

        var str = $('form').serialize() + '&ajax=register';

        $.ajax
	    ({
            type: "POST",
            //url: "/baby-club/register.aspx?ajax=register",
            data: str,

            // if ajax call succeeded...
            success: function(data, textStatus, XMLHttpRequest) {
                var jsonResponse = $.parseJSON(data);
                if (jsonResponse != null && jsonResponse['success'] != null && jsonResponse['success'] == 'false') 
                {
                    if (jsonResponse['invalid_fields'] != null) 
                    {
                        $.each(jsonResponse['invalid_fields'], function(item) {
                            $('#' + jsonResponse['invalid_fields'][item]).parents('.fieldset-row').addClass('highlight-label');
                            $('#' + jsonResponse['invalid_fields'][item]).parent('.reg-form-join-section-input').parent('div').addClass('highlight-label');
                        });
                    }
                    if (jsonResponse['messages'] != null) 
                    {
                        $.each(jsonResponse['messages'], function(item) {
                            $('#' + jsonResponse['messages'][item].control).html('<p class="highlight-message">' + jsonResponse['messages'][item].message + '</p>');
                        });
                    }
                }
                else if (jsonResponse != null && jsonResponse['success'] != null && jsonResponse['success'] == 'true' && jsonResponse['redirect'] != null) 
                {
                    location.href = jsonResponse['redirect'];
                }
                else 
                {
                    $('#' + spnAddressFinderFeedbackId).html('<p class="highlight-message">Unexpected response.</p>');
                }
            },

            // ajax call failed...
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#' + btnSubmitId).unbind('click'); // unbind the ajax call from the click
                $('#' + btnSubmitId).trigger('click'); // trigger the click to post as usual because ajax failed (javascript works but the ajax call or response may be blocked)
            },

            // ajax call completed (succeeded or failed)
            complete: function(XMLHttpRequest, textStatus) {
                $('#register-loader').html('');
                $('#' + btnSubmitId).show();
            }
        });
        event.preventDefault();
    });
    /* -------------------------------------------------- */

});
