﻿function OnCountryChanged(CountryId, StateListId, StateTextId) {
    ChangedCountry(CountryId, StateListId, StateTextId, false);
}

function ChangedCountry(CountryId, StateListId, StateTextId, keepOldState){
    var StateListControl = document.getElementById(StateListId);
    var StateTextControl = document.getElementById(StateTextId);
    var CountryControl = document.getElementById(CountryId);

    var selectedCountry = CountryControl.options[CountryControl.selectedIndex].text;

    var oldStateTextValue = StateTextControl.value
    if(!keepOldState)
        oldStateTextValue = '';
    
    if (selectedCountry == 'United States' || selectedCountry == 'United Kingdom')  {
        StateTextControl.style.display = 'none'
		
		switch(selectedCountry)
		{
		case 'United States':
		  FillPickList(StateListControl, StateTextControl, "/Portals/0/States/statesofus.xml", "state", oldStateTextValue);
		  break;
		case 'United Kingdom':
		  FillPickList(StateListControl, StateTextControl, "/Portals/0/States/statesofuk.xml", "state", oldStateTextValue);
		  break;
		}		
        StateListControl.style.display = ''
    }
    else {
        StateTextControl.style.display = ''
        StateTextControl.value = oldStateTextValue
        StateListControl.style.display = 'none'
    }
}

function OnStateChanged(StateListId, StateTextId) {
    var StateListControl = document.all(StateListId);
    var StateTextControl = document.all(StateTextId);
    var selectedState = StateListControl.options[StateListControl.selectedIndex].text;
    StateTextControl.value = selectedState
}

function FillPickList(picklist, stateTextControl, xmlPath, tagName, oldStateTextValue) {
	$.ajax({
        type: "GET",
		url: xmlPath,
		dataType: "xml",
		success: function(xml) {
			var picklistSelect = $(picklist);
			picklistSelect.find('option').remove().end().append('<option value=\'1\'> </option>');
			$(xml).find(tagName).each(function(){
				picklistSelect.append($("<option></option>").text($(this).text()));
			});
			
			if(oldStateTextValue == "")
			    oldStateTextValue = "abcdefghifkkliovcnoi";   //IE will select last one if using val('')
			    
			picklistSelect.val(oldStateTextValue);	
			
			if (picklistSelect.attr("selectedIndex") > 0)
                stateTextControl.value = oldStateTextValue;
            else
                stateTextControl.value = '';			
		} 
	});
}
