var CountryStateForm = new Class({
	initialize: function(countries, countryText) {
		this.countries = countries;
		this.countryText = countryText;
		try{
			this.initializeStateCountrySelects('billingCountry', 'sltBillingCountry', 'sltBillingState');
			this.initializeStateCountrySelects('shippingCountry', 'sltShippingCountry', 'sltShippingState');
			$('countrySelectEnabled').value = true;
		} catch(e){}

	},
	
	initializeStateCountrySelects: function(div, sltCountry, sltState) {
		var select = new Element('select', {id: sltCountry});
		select.onchange = this.callSetStateSelect(sltCountry, sltState).bindAsEventListener(this);
		
		var option = new Element('option', {
			value: '-1'
		});
		option.appendText(' ');
		select.appendChild(option);
		
		var selectedState = $(sltState).value;	
		
		for(countryId in countries) {
			option = new Element('option', {
				value: countryId
			});
			option.appendText(countries[countryId].name);
			
			select.appendChild(option);
			
			if(selectedState && selectedState != -1 && countries[countryId].states[selectedState]) {
				select.selectedIndex = select.length - 1;
			}
		}
		
		var label = new Element('label');
		label.appendText(this.countryText);
		var span = new Element('span');
		span.addClass('required');
		span.appendText('*');
		label.appendChild(span);
		
		var billingCountry = $(div);
		//billingCountry.appendChild(label);
		billingCountry.appendChild(select);
		
		this.setStateSelect(sltCountry, sltState, selectedState);
	},
	
	callSetStateSelect: function(sltCountryId, sltStateId) {
		var me = this;
		return function() {
			me.setStateSelect(sltCountryId, sltStateId);
		}
	},
	
	setStateSelect: function(sltCountryId, sltStateId, selectedState) {
		var select = $(sltStateId);
		var children = select.getChildren();
		
		for(var i = children.length - 1; i >=0; i--) {
			children[i].remove();
		}
		
		// removed the blank space option
		// in order to accomodate for countries with no province

		
		var countryId = $(sltCountryId).value;		
		if(this.countries[countryId]) {
			var states = this.countries[countryId].states;
			
			for(stateId in states) {
				option = new Element('option', {
					value: stateId
				});
				option.appendText(states[stateId]);
				
				select.appendChild(option);
				
				if(selectedState && selectedState != -1 && selectedState == stateId) {
					select.selectedIndex = select.length - 1;
				}
			}
		}
		else{
			// select default -1 option when country is also -1
			select.appendChild(new Element('option', -1));
			select.selectedIndex = 0;
		}
	}
});
