
	var state_selected = null;

	function state_country_check(myform)
	{
		// Ensure the event is there
//		$$('select[name=country_id]').addEvent('change', state_country_check(this.form));
//		$$('select[name=country]').addEvent('change', state_country_check(this.form));
		
		// Get the country_id, state_id and state_description elements
		var form_selector = '';
		if (myform)
			form_selector = 'form[id=' + myform.get('id') + '] ';
		var country_id = $$(form_selector + 'select[name=country_id]');
		if (!country_id.length)
			country_id = $$(form_selector + 'select[name=country]');
		var state_id = $$(form_selector + 'select[name=state_id]');
		var state_description = $$(form_selector + 'input[name=state_description]');
		
		if (!country_id.length || !state_id.length || !state_description.length)
			return;
		
		country_id = country_id[0];
		state_description = state_description[0];
		state_id = state_id[0];
		
		// Get the current value for state_id
		if (state_selected == null)
		{
			state_selected = state_id.getSelected();
			state_selected = state_selected[0].get('value');
		}

		// Remove the label for state_description
		$$('label[for='+state_description.get('id')+']').destroy();
		
		// Hide/show logic
		if (country_id.get('value') != 'CA' && country_id.get('value') != 'US')
		{
			state_id.set('value', '');
			state_id.hide();
			state_description.show();
		}
		else
		{
			// Load up the list of options
			state_id.set('html', '');
			
		    var request = new Request.JSON({
		        url:'/api/get_states/'+country_id.get('value'),
		  			method: 'get',
		        onSuccess: function(response){
		  	        	if(!response.error)
		  	        	{
		  	        		state_id.set('html', response.options);
		  	        		
		  	        		if (response.state_id == '')
		  	        			// Use the selected element
		  	        			state_id.set('value', state_selected);
		  	        			
		  	        		state_id.show();
		  	        		state_description.hide();
		  	        	}
		  			},
		        onFailure: function(response){
		  					
		  				}
		        }).send();
		}
	}
	
	window.addEvent('domready', function() {
		$$('select[name=country_id]').addEvent('change', function(){
			state_country_check(this.form);
		});
		$$('select[name=country]').addEvent('change', function(){
			state_country_check(this.form);
		});
		
		// Initial firing of the event for each form
		$$('form').each(function(f){
			state_country_check(f);
		});
	});
	

