$(document).ready(function() {
	var _fieldname = findCountryField();	
	
	$(_fieldname).change(function(){
		updateStateSelection($(_fieldname).val());			
	});	
	updateStateSelection($(_fieldname).val());	
});

function findCountryField() {
	
	// find country field in form
	if($('#selectCountry').val() != undefined) return '#selectCountry';
	if($('#country').val() != undefined) return '#country';
	if($('#idcountry').val() != undefined) return '#idcountry';	
	return '#selectCountry';
}

function findStateField() {	
	// find country field in form
	if($('#stateField').val() != undefined) return '#stateField';
	if($('#statename').val() != undefined) return '#statename';	
	return '#stateField';
}

function updateStateSelection(countryid) {
	var stateFieldID = findStateField();
	if(countries[countryid].states.length > 0) {
		for(i=0,entry=1;i<countries[countryid].states.length;i++) 
		{
			if (entry >= $(stateFieldID+' option').length) {
				// we add the option
				$(stateFieldID).append('<option value="' + countries[countryid].states[i].id + '">' + countries[countryid].states[i].name + '</option>');
			}
			else {
				// we override the option
				$(stateFieldID+' option:eq(' + (entry) + ')').replaceWith('<option value="' + countries[countryid].states[i].id + '">' + countries[countryid].states[i].name + '</option>');
			}
          	entry++;				
		}
		$('#stateSelection').parent().show();
	}
	else {
		// no states for the country, so hide the state field and set to empty
		$('#stateSelection').parent().hide();
		$(stateFieldID).val("");
	}	
}


function country(){		
  this.states= null;	// list of states in the country
  this.cc = "";			// Countrycode
  this.id= 0;			// CountryID
  this.name="";			// CountryName  
}

function state(_id,_name){		
  this.id= _id;		// StateID
  this.name=_name;	// Name  
}
