/**
 * This class provides functionality to dynamically retrieve and display state/province
 * names and -codes as HTML <option> tags, based on the given country code.
 *
 * @author Stefan T.
 * @copyright Godengo Inc., 2008
 *
 * DEPENDENCIES:
 *  prototype.js must be loaded prior to this
 **/

/* @global */
StateOptionsSwitcher = Class.create();

StateOptionsSwitcher.prototype = {

	initialize: function (countryId, stateId, stateContainer, config) {
		this.country = $(countryId);
		this.state = $(stateId);
		this.stateContainer = $(stateContainer);
		this.spinner = $(config.spinner) || null; //spinner image
		this.backendurl = config.backendurl || '/core/ajaxserver.php';
		this.isrequired = config.isrequired || false;
		this.blankoption = config.blankoption ||false;
		this.label = config.label || '';
		if(this.country) {
			this.country.onchange = this.onchange.bind(this);
		}
	},

	onchange: function() {
		var ajaxRequest = new Ajax.Updater(this.stateContainer, this.backendurl, {
    		method:       'get',
    		parameters:   {	'country' : (this.country.value || 'US'),
							'req':'getStates',
							'field':this.state.id,
							'isrequired':this.isrequired,
							'blankoption':this.blankoption,
							'label':this.label
						  },
    		asynchronous: true,
    		onLoading : this.showSpinner(this.spinner),
    		onComplete : this.hideSpinner(this.spinner)
  		});
	},
	showSpinner: function(spinner) {
		if(spinner)
			spinner.show();
	},
	hideSpinner : function(spinner) {
		if(spinner)
			spinner.hide();
	}
}