jQuery(function($) {
    // open in a new window
    $('.register label[for=id_privacy] a').click(function() {
        $(this).attr('target', '_blank');
    });
    if ($('.register #id_address_1').length > 0) {
        var cta = $('<div id="search_address" class="cta secondary"><button><span><span><span><span>Look up address</span></span></span></span></button></div>').insertAfter('.register #id_postcode');
        cta.find('button:first').click(function() {
            if (document.getElementById('paf_loading')) {
                return false;
            }
            // go to Ajax post code thingie and pre-fill address:
        
            // clean up after last time, if there was a last time.
            $('.postcode_not_found').remove();
            $('#l_auto_fill').remove();
            $('#id_auto_fill').remove();
        
            // to override set to_post as js var
            if (typeof(to_post) == 'undefined') {
                to_post = '../postcode-address-lookup/';
            }
            
            var newData = {
                'postcode':$('#id_postcode').val()
            };
            $('#search_address').after('<div id="paf_loading" />');
            $.ajax({'timeout':10000, 'url':to_post, 'data':newData, 'type':'POST', 'error' : function(XMLHttpRequest, textStatus, errorThrown) {
                    // error state, let them complete the form as usual
                    $('#paf_loading').remove();
                    $('#search_address').after("<p class=\"postcode_not_found\" role=\"alert\">We had a problem finding an address with that postcode. Please enter your details manually in the boxes below.</p>");
                    $('.register .other').each(function() {
                        $(this).removeClass('other');
                    });
                    $('#id_address_1').focus();
                }, 'success': function(data) {
                $('#paf_loading').remove();
                // this is the callback for the function
                if (data.addresses && data.addresses.length > 0) {
                    // we have some pre-filled addresses
                    var newSelect = $('<select id="id_auto_fill" name="auto_fill" />');
                    $('#search_address').after(newSelect);
                    newSelect.before($('<label for="auto_fill" id="l_auto_fill" role="alert">Select an exact address:</label>'));
                    newSelect.append($('<option value="">Please select your address</option>'));
                    for (var i=0, j=data.addresses.length; i<j; i++) {
                        var current = data.addresses[i];
                        var option = document.createElement('option');
                        option.value = current[0];
                        str = current[1];              
                        $(option).data('prefill', current);
                        $(option).text(str);
                        newSelect.append(option);
                    }

                    newSelect.change(function() {
                        var ident = $(this).find('option:selected').val();                      
                        var identData = {
                            'id': ident
                        };
                        $.ajax({'url':to_post, 'data':identData, 'type':'POST', 'dataType':'json', 'success': function(data2) {
                            
                            var toAdd = data2.addresses[0];
                            $('#id_address_1').val('').val(toAdd.address_1);
                            $('#id_town').val('').val(toAdd.town);
                            $('#id_county').val('').val(toAdd.county);
                            $('#id_address_2').val('');
                            if (toAdd.address_2) {
                                $('#id_address_2').val(toAdd.address_2);
                            }
                            $('#id_address_3').val('');
                            if (toAdd.address_3) {
                                $('#id_address_3').val(toAdd.address_3);
                            }
                            $('#id_address_1').focus();
                        }});
                    });
                }
                else {
                    // we don't have any pre-filled addresses
                    $('#search_address').after("<p class=\"postcode_not_found\" role=\"alert\">We can't find an address with that postcode. Please enter the details in the boxes below.</p>");
                    $('#id_address_1').focus();
                }
                $('.register .other').each(function() {
                    $(this).removeClass('other');
                });
            }, 'dataType' : 'json'});
            return false;
        });
    }
    // cause the form field with the error to be focused on click
    $('div.errors li a').click(function() {
        var id = $(this).attr('href').replace('#', '');
        $('#' + id).focus();
        return false;
    });
});

