$(function()
{

    // init loader
    var image = new Image();
    $(image).load(function(){$(this.hide);}).attr('src', 'images/ajax-loader.gif');
    $('.loader-aggregate').bind('start-loader', function()
    {
	$(this).after(image);
    });
    $('.loader-aggregate').bind('stop-loader', function()
    {
	$(this).parent().find('img').remove();
    });

    
    $.fn.changeSuggestions = function(context, ac_elements)
    {
	var $self = $(this);
	
	$self.trigger('start-loader');
	ac_elements.disable();

	$.get('user/geo-zip/get-suggestions.html',
            {
                state: $('#state option:selected', context).val(),
                format: 'json'
            },
            function(response)
            {
		ac_elements.setOptions('#city', context, {lookup: response.cities});
		if (1 == response.cities.length) {
		    $('#city', context).val(response.cities.shift());
		}

		ac_elements.setOptions('#zip', context, {lookup: response.zips});
		if (1 == response.zips.length) {
		    $('#zip', context).val(response.zips.shift());
		}

		ac_elements.enable();
		$self.trigger('stop-loader');
            }
        , 'json');
    }

    $.fn.changeSuggestionsZips = function(context, ac_elements)
    {
	var $self = $(this);
	
	$self.trigger('start-loader');
	ac_elements.disable();

	$.get('user/geo-zip/get-suggestions-zips.html',
	    {
		state: $('#state option:selected', context).val(),
		city: $(this).val(),
		format: 'json'
	    },
	    function(response)
	    {
		ac_elements.setOptions('#zip', context, {lookup: response.zips});
		if (1 == response.zips.length) {
		    $('#zip', context).val(response.zips.shift());
		}

		ac_elements.enable();
		$self.trigger('stop-loader');
	    }
	, 'json');
    }

    $.fn.changeSuggestionsCCZips = function(context, ac_elements)
    {
	var $self = $(this);

	$self.trigger('start-loader');
	ac_elements.disable();

	$.get('user/geo-zip/get-suggestions-zips.html',
	    {
		state: $('#cc_state option:selected', context).val(),
		format: 'json'
	    },
	    function(response)
	    {
		ac_elements.setOptions('#cc_zip_code', context, {lookup: response.zips});
		if (1 == response.zips.length) {
		    $('#cc_zip_code', context).val(response.zips.shift());
		}

		ac_elements.enable();
		$self.trigger('stop-loader');
	    }
	, 'json');
    }

    $.fn.changeSuggestionsCities = function(context, ac_elements)
    {
	var $self = $(this);

	$self.trigger('start-loader');
	ac_elements.disable();

	$.get('user/geo-zip/get-suggestions-cities.html',
	    {
		state: $('#state option:selected', context).val(),
		city: $(this).val(),
		format: 'json'
	    },
	    function(response)
	    {
		ac_elements.setOptions('#city', context, {lookup: response.cities});
		if (1 == response.cities.length) {
		    $('#city', context).val(response.cities.shift());
		}

		ac_elements.enable();
		$self.trigger('stop-loader');
	    }
	, 'json');
    }

});
