if (!WC) {
    var WC = function() {};
}

/**
 * Usage:
 * WC.postcodelookup.bindContainer('.address-fields');
 */
WC.postcodelookup = function(map, target_url) {
    var instance = this;
    
    this.map = {};
    this.addresses = [];
    this.postcode = '';
    this.target_url = '';
    
    if (map != undefined) {
        this.map = map;
    }
    
    if (target_url != undefined) {
        this.target_url = target_url;
    }
    
    /**
     * The following fields need to be bound using this function:
     * Note: fields can be CSS format (e.g. #myfield or .myfield), dom elements or jquery elements
     * find_button:    '', // the button to click to find addresses
     * find_postcode:  '', // the field which contains the entered postcode
     * find_container: '', // the surrounding container for address fields
     * find_list:      '', // the <select> element for address selections
     * addr_line1:     '', // the form element containing address line 1
     * addr_line2:     '', // the form element containing address line 2
     * addr_town:      '', // the form element containing address town
     * addr_county:    '', // the form element containing address county
     * addr_postcode:  ''  // the form element containing the postcode
     */
    this.bind = function(map, target_url) {
        this.map = map;
        this.target_url = target_url;
        $(this.map.find_button).bind('click', this.findPostcode);
        return this;
    }
    
    this.findPostcode = function() {
        if (instance.postcode == $(instance.map.find_postcode).val()) {
            return;
        }
        instance.postcode = $(instance.map.find_postcode).val();
        
        $(instance.map.find_container).show();
        $(instance.map.find_list).unbind('click');
        $(instance.map.find_list).html('<option>Finding addresses, please wait...</option>');

        $.ajax({
            url: instance.target_url,
            dataType: 'json',
            data: {'postcode': instance.postcode},
            success: instance.parseLookup,
            error: instance.lookupError
        });
    }
    
    this.parseLookup = function(response) {
        if ( response == null || ! response.data || $.isEmptyObject(response.data) || response.error) {
            $(instance.map.find_list).html('<option>No results, please enter your address manually.</option>');
            return;
        }
    
        //instance.addresses = data;
        
        var select = $(instance.map.find_list).get(0);
        select.options.length = 0;
        $.each(response.data, function(key, value) {
            select.options[select.options.length] = new Option(value, key);
        });

        $(instance.map.find_list).bind('click', instance.populateAddress);
    }
    
    this.lookupError = function(XMLHttpRequest, textStatus, errorThrown) {
        $(instance.map.find_list).html('<option>No results, please enter your address manually.</option>');
    }
    
    this.populateAddress = function() {
        var index = $(instance.map.find_list).val();
        if (index !== null){
            $.ajax({
                url: instance.target_url,
                dataType: 'json',
                data: {'adid': index},
                success: instance.parseAddress,
                error: instance.parseAddressError
            });
        }
    }
    
    this.parseAddress = function(response) {
        if (!response.data || $.isEmptyObject(response.data) || response.error) {
            alert('An error occured auto-completing the address, please complete manually.');
            return;
        }    
        var address = response.data[0]

        if(address.Line4!='') {
            address.Line1 = address.Line1 + ", " + address.Line2;
            address.Line2 = address.Line3 + ", " + address.Line4;
        } else if(address.Line3!='') {
            address.Line1 = address.Line1 + ", " + address.Line2;
            address.Line2 = address.Line3;
        }

        $(instance.map.addr_line1).val(address.Line1);
        $(instance.map.addr_line2).val(address.Line2);
        $(instance.map.addr_town).val(address.PostTown);
        $(instance.map.addr_county).val(address.County);
        $(instance.map.addr_postcode).val(address.Postcode);
    }
    
    this.parseAddressError = function(XMLHttpRequest, textStatus, errorThrown) {
        alert('An error occured auto-completing the address, please complete manually.');
    }    

}
WC.postcodelookup.bindContainer = function(css_class, target_url) {
    $(css_class).each(function(){
        var root = $(this);
        var map = {
            find_button:    root.find('.find_button:first'), // the button to click to find addresses
            find_postcode:  root.find('.find_postcode:first'), // the field which contains the entered postcode
            find_container: root.find('.find_container:first'), // the surrounding container for address fields
            find_list:      root.find('.find_list:first'), // the <select> element for address selections
            addr_line1:     root.find('.addr_line1:first'), // the form element containing address line 1
            addr_line2:     root.find('.addr_line2:first'), // the form element containing address line 2
            addr_town:      root.find('.addr_town:first'), // the form element containing address town
            addr_county:    root.find('.addr_county:first'), // the form element containing address county
            addr_postcode:  root.find('.addr_postcode:first')  // the form element containing the postcode
        };
        (new WC.postcodelookup).bind(map, target_url);
    });
}
