/*
Country State Drop Downs v1.0.
(c) Copyright 2005 Down Home Consulting, Inc.
www.DownHomeConsulting.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, itness for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

*/

// list of countries, keyed to unique country codes
var countries = {
   US : 'United States',
   CA : 'Canada',
   UK : 'United Kingdom',
   AU : 'Australia',
   ZZ : ' -------- ',
   AF: 'Afghanistan',
   AL: 'Albania',
   DZ: 'Algeria',
   AO: 'Angola',
   AR: 'Argentina',
   AM: 'Armenia',
   AW: 'Aruba',
   AU: 'Australia',
   AT: 'Austria',
   AZ: 'Azerbaijan',
   BS: 'Bahamas',
   BB: 'Barbados',
   BE: 'Belgium',
   BM: 'Bermuda',
   BO: 'Bolivia',
   XB: 'Bosnia-Herzegovina',
   BR: 'Brazil',
   BN: 'Brunei Darussalam',
   BG: 'Bulgaria',
   KH: 'Cambodia',
   CA: 'Canada',
   KY: 'Cayman Islands',
   CF: 'Central African Republic',
   CL: 'Chile',
   CN: 'China',
   CO: 'Colombia',
   CG: 'Congo',
   CR: 'Costa Rica',
   HR: 'Croatia',
   CU: 'Cuba',
   CY: 'Cyprus',
   CZ: 'Czech Republic',
   DK: 'Denmark',
   DO: 'Dominican Republic',
   EC: 'Ecuador',
   EG: 'Egypt',
   SV: 'El Salvador',
   ET: 'Ethiopia',
   FJ: 'Fiji',
   FI: 'Finland',
   FR: 'France',
   GE: 'Georgia',
   DE: 'Germany',
   GT: 'Guatemala',
   GY: 'Guyana',
   HT: 'Haiti',
   HN: 'Honduras',
   HK: 'Hong Kong',
   HU: 'Hungary',
   IS: 'Iceland',
   IN: 'India',
   ID: 'Indonesia',
   IR: 'Iran',
   IQ: 'Iraq',
   IE: 'Ireland',
   IL: 'Israel',
   IT: 'Italy',
   JM: 'Jamaica',
   JP: 'Japan',
   JO: 'Jordan',
   KZ: 'Kazakhstan',
   KE: 'Kenya',
   KP: 'Korea',
   KW: 'Kuwait',
   LA: 'Laos',
   LB: 'Lebanon',
   LR: 'Liberia',
   LY: 'Libya',
   LI: 'Liechtenstein',
   LT: 'Lithuania',
   LU: 'Luxembourg',
   MY: 'Malaysia',
   MT: 'Malta',
   MQ: 'Martinique',
   MX: 'Mexico',
   MC: 'Monaco',
   MN: 'Mongolia',
   MA: 'Morocco',
   MZ: 'Mozambique',
   MM: 'Myanmar (Burma)',
   NA: 'Namibia',
   NL: 'Netherlands',
   NZ: 'New Zealand',
   NI: 'Nicaragua',
   NG: 'Nigeria',
   'NO': 'Norway',
   PK: 'Pakistan',
   PS: 'Palestinian Territory',
   PA: 'Panama',
   PG: 'Papua New Guinea',
   PY: 'Paraguay',
   PE: 'Peru',
   PH: 'Philippines',
   PL: 'Poland',
   PT: 'Portugal',
   PR: 'Puerto Rico',
   QA: 'Qatar',
   RO: 'Romania',
   RU: 'Russian Federation',
   SA: 'Saudi Arabia',
   XS: 'Serbia-Montenegro',
   SL: 'Sierra Leone',
   SG: 'Singapore',
   SK: 'Slovak Republic',
   ZA: 'South Africa',
   KR: 'South Korea',
   ES: 'Spain',
   SE: 'Sweden',
   CH: 'Switzerland',
   SY: 'Syrian Arab Republic',
   TW: 'Taiwan',
   TZ: 'Tanzania',
   TH: 'Thailand',
   TN: 'Tunisia',
   TR: 'Turkey',
   UG: 'Uganda',
   UA: 'Ukraine',
   AE: 'United Arab Emirates',
   UK: 'United Kingdom',
   GB: 'Great Britain',
   US: 'United States',
   UY: 'Uruguay',
   VE: 'Venezuela',
   VN: 'Vietnam',
   YU: 'Yugoslavia',
   ZW: 'Zimbabwe'
 }

// list of provinces and states, keyed to country codes that match var coutries
var country_regions = {
  CA : {
       AB : 'Alberta',  
       MB : 'Manitoba',
       AB : 'Alberta',
       BC : 'British Columbia',
       MB : 'Manitoba',
       NB : 'New Brunswick',
       NL : 'Newfoundland and Labrador',
       NS : 'Nova Scotia',
       NT : 'Northwest Territories',
       NU : 'Nunavut',
       ON : 'Ontario',
       PE : 'Prince Edward Island',
       QC : 'Quebec',
       SK : 'Saskatchewan',
       YT : 'Yukon Territory'
  },
  US : {
       AK : 'Alaska',  
       AL : 'Alabama',
       AR : 'Arkansas',
       AS : 'American Samoa',
       AZ : 'Arizona',
       CA : 'California',
       CO : 'Colorado',
       CT : 'Connecticut',
       DC : 'D.C.',
       DE : 'Delaware',
       FL : 'Florida',
       FM : 'Micronesia',
       GA : 'Georgia',
       GU : 'Guam',
       HI : 'Hawaii',
       IA : 'Iowa',
       ID : 'Idaho',
       IL : 'Illinois',
       IN : 'Indiana',
       KS : 'Kansas',
       KY : 'Kentucky',
       LA : 'Louisiana',
       MA : 'Massachusetts',
       MD : 'Maryland',
       ME : 'Maine',
       MH : 'Marshall Islands',
       MI : 'Michigan',
       MN : 'Minnesota',
       MO : 'Missouri',
       MP : 'Marianas',
       MS : 'Mississippi',
       MT : 'Montana',
       NC : 'North Carolina',
       ND : 'North Dakota',
       NE : 'Nebraska',
       NH : 'New Hampshire',
       NJ : 'New Jersey',
       NM : 'New Mexico',
       NV : 'Nevada',
       NY : 'New York',
       OH : 'Ohio',
       OK : 'Oklahoma',
       OR : 'Oregon',
       PA : 'Pennsylvania',
       PR : 'Puerto Rico',
       PW : 'Palau',
       RI : 'Rhode Island',
       SC : 'South Carolina',
       SD : 'South Dakota',
       TN : 'Tennessee',
       TX : 'Texas',
       UT : 'Utah',
       VA : 'Virginia',
       VI : 'Virgin Islands',
       VT : 'Vermont',
       WA : 'Washington',
       WI : 'Wisconsin',
       WV : 'West Virginia',
       WY : 'Wyoming',
       AA : 'Military Americas',
       AE : 'Military Europe/ME/Canada',
       AP : 'Military Pacific'
  },
  AU : {
       AAT : 'Australian Antarctic Territory',  
       ACT : 'Australian Capital Territory',
       NT : 'Northern Territory',
       NSW : 'New South Wales',
       QLD : 'Queensland',
       SA : 'South Australia',
       TAS : 'Tasmania',
       VIC : 'Victoria',
       WA : 'Western Australia'
  },
  BR : {
       AC : 'Acre',  
       AL : 'Alagoas',
       AM : 'Amazonas',
       AP : 'Amapa',
       BA : 'Baia',
       CE : 'Ceara',
       DF : 'Distrito Federal',
       ES : 'Espirito Santo',
       FN : 'Fernando de Noronha',
       GO : 'Goias',
       MA : 'Maranhao',
       MG : 'Minas Gerais',
       MS : 'Mato Grosso do Sul',
       MT : 'Mato Grosso',
       PA : 'Para',
       PB : 'Paraiba',
       PE : 'Pernambuco',
       PI : 'Piaui',
       PR : 'Parana',
       RJ : 'Rio de Janeiro',
       RN : 'Rio Grande do Norte',
       RO : 'Rondonia',
       RR : 'Roraima',
       RS : 'Rio Grande do Sul',
       SC : 'Santa Catarina',
       SE : 'Sergipe',
       SP : 'Sao Paulo',
       TO : 'Tocatins'
  },
  NL : {
       DR : 'Drente',  
       FL : 'Flevoland',
       FR : 'Friesland',
       GL : 'Gelderland',
       GR : 'Groningen',
       LB : 'Limburg',
       NB : 'Noord Brabant',
       NH : 'Noord Holland',
       OV : 'Overijssel',
       UT : 'Utrecht',
       ZH : 'Zuid Holland',
       ZL : 'Zeeland'
  },
  UK : {
       AVON : 'Avon',  
       BEDS : 'Bedfordshire',
       BERKS : 'Berkshire',
       BUCKS : 'Buckinghamshire',
       CAMBS : 'Cambridgeshire',
       CHESH : 'Cheshire',
       CLEVE : 'Cleveland',
       CORN : 'Cornwall',
       CUMB : 'Cumbria',
       DERBY : 'Derbyshire',
       DEVON : 'Devon',
       DORSET : 'Dorset',
       DURHAM : 'Durham',
       ESSEX : 'Essex',
       GLOUS : 'Gloucestershire',
       GLONDON : 'Greater London',
       GMANCH : 'Greater Manchester',
       HANTS : 'Hampshire',
       HERWOR : 'Hereford & Worcestershire',
       HERTS : 'Hertfordshire',
       HUMBER : 'Humberside',
       IOM : 'Isle of Man',
       IOW : 'Isle of Wight',
       KENT : 'Kent',
       LANCS : 'Lancashire',
       LEICS : 'Leicestershire',
       LINCS : 'Lincolnshire',
       MERSEY : 'Merseyside',
       NORF : 'Norfolk',
       NHANTS : 'Northamptonshire',
       NTHUMB : 'Northumberland',
       NOTTS : 'Nottinghamshire',
       OXON : 'Oxfordshire',
       SHROPS : 'Shropshire',
       SOM : 'Somerset',
       STAFFS : 'Staffordshire',
       SUFF : 'Suffolk',
       SURREY : 'Surrey',
       SUSS : 'Sussex',
       WARKS : 'Warwickshire',
       WMID : 'West Midlands',
       WILTS : 'Wiltshire',
       YORK : 'Yorkshire'
  },
  EI : {
       'CO ANTRIM' : 'County Antrim',  
       'CO ARMAGH' : 'County Armagh',
       'CO DOWN' : 'County Down',
       'CO FERMANAGH' : 'County Fermanagh',
       'CO DERRY' : 'County Londonderry',
       'CO TYRONE' : 'County Tyrone',
       'CO CAVAN' : 'County Cavan',
       'CO DONEGAL' : 'County Donegal',
       'CO MONAGHAN' : 'County Monaghan',
       'CO DUBLIN' : 'County Dublin',
       'CO CARLOW' : 'County Carlow',
       'CO KILDARE' : 'County Kildare',
       'CO KILKENNY' : 'County Kilkenny',
       'CO LAOIS' : 'County Laois',
       'CO LONGFORD' : 'County Longford',
       'CO LOUTH' : 'County Louth',
       'CO MEATH' : 'County Meath',
       'CO OFFALY' : 'County Offaly',
       'CO WESTMEATH' : 'County Westmeath',
       'CO WEXFORD' : 'County Wexford',
       'CO WICKLOW' : 'County Wicklow',
       'CO GALWAY' : 'County Galway',
       'CO MAYO' : 'County Mayo',
       'CO LEITRIM' : 'County Leitrim',
       'CO ROSCOMMON' : 'County Roscommon',
       'CO SLIGO' : 'County Sligo',
       'CO CLARE' : 'County Clare',
       'CO CORK' : 'County Cork',
       'CO KERRY' : 'County Kerry',
       'CO LIMERICK' : 'County Limerick',
       'CO TIPPERARY' : 'County Tipperary',
       'CO WATERFORD' : 'County Waterford'
  }
}

// what type of thing are the regions for each country
var region_names = {
    CA : 'Province',
    US : 'State'
}

//declaring the class
var AddressUpdater = Class.create();

//defining the rest of the class implmentation
AddressUpdater.prototype = {
  // TODO: should degrade to work without JS enabled (as regular text-inputs)
  initialize : function (address_name, country_value, region_value){
  
    // set initial values
    this.address_name  = address_name
    this.country_value = country_value
    this.region_value  = region_value
	if (address_name == 'global')
	{
		this.country_id = 'country'
		this.region_id = 'region'
		this.region_name = 'region'
	}
	else
	{
	    this.country_id    = address_name + '_country'   
	    this.region_id     = address_name + '_province'
	    this.region_name   = address_name + '[province]'
	}
    
    // populate the form elements with some values
    this.populateCountry()
    this.updateRegion()
    
    // when the country select is changed, update the region element
    $(this.country_id).onchange = this.updateRegion.bindAsEventListener(this); 
  },
    
  populateCountry : function(){
    
    if ( $(this.country_id).type == 'text' ) {                // If it's a text input,   
      this.replaceTextInputWithSelect(this.country_id)        // change it to a select   
    }

    countrySelect = $(this.country_id) 
    
    // dummy instruction entry
    countrySelect.options[0] = new Option('--------','')
    countrySelect.selectedIndex = 0
    
    this.addOptions(countrySelect, countries, this.country_value) // add the country options    
  }, 
  
  updateRegion : function() {
    this.populateRegion()
	if (this.address_name != 'global')
    {
		this.setRegionLabel()
	}
  },
  
  populateRegion : function (){
    regions  = country_regions[this.selectedCountryCode()]   // get the list of regions for the selected country 
  
    if(!regions){                                            // If the country has no regions,  
      this.replaceSelectWithTextInput()                      // change the select to a text input
                                                  
    } else {                                                 // otherwise there are regions to list, 
      regionElement = $(this.region_id)                      // so we have to populate a select
                            
      
      if ( regionElement.type == 'text' ) {                  // If it's an input element,
        this.replaceTextInputWithSelect(this.region_id)      // change it to a select
      } else if ( regionElement.type == 'select-one'  ) { 
        regionElement.options.length = 0                     // Otherwise, just empty the list
      } else {
        throw "Invalid element -- expected either 'text' or 'select-one' type element"
      }
      regionSelect = $(this.region_id)                       // grab a fresh version of regionSelect
      
      // dummy instruction entry
      regionSelect.options[0] = new Option('Select ' + this.regionType(), '')
      regionSelect.selectedIndex = 0    
      this.addOptions(regionSelect, regions, this.region_value) // add the regions for the chosen country      
    }
  },

  setRegionLabel : function(){   	
    	$( this.address_name + '_province_label').innerHTML = this.regionType(this.address_name) 
  },
  
  regionType : function(){
    countryCode = this.selectedCountryCode()
    return (countryCode && region_names[countryCode]) ? region_names[countryCode] : 'Region'
  },
  
  // utility functions 
  selectedCountryCode : function(){
  	if(this.address_name == 'global')
	{
		return $('country').options[$('country').selectedIndex].value
	}
	else
	{
    	return $(this.address_name + '_country').options[$(this.address_name + '_country').selectedIndex].value
	}
  },  
  replaceSelectWithTextInput : function (){
    selObj = $(this.region_id)
    parentObj = selObj.parentNode
    parentObj.removeChild(selObj)
    // Create the Input Field
    var inputEl = document.createElement("INPUT")
    inputEl.setAttribute("type",  "text")
    inputEl.setAttribute("id",    selObj.id)
    inputEl.setAttribute("name",  selObj.name)
    inputEl.setAttribute("size",  20)
    inputEl.setAttribute("value", this.region_value)
    parentObj.appendChild(inputEl)   
  },
  replaceTextInputWithSelect : function (element_id){
    inputObj = $(element_id)
    parentObj = inputObj.parentNode
    parentObj.removeChild(inputObj)
    var inputSel = document.createElement("SELECT")
    inputSel.setAttribute("id",   inputObj.id)
    inputSel.setAttribute("name", inputObj.name)
    parentObj.appendChild(inputSel) 
  },
  addOptions : function(select, options, selected_value){
    selectElement = $(select)
    for(option in options){                                                             // for each option in the list of options
      selectElement.options[selectElement.length] = new Option(options[option], option) // create a new option
    
      if ( option == selected_value) {                            // if the new option matches the selected value,
        selectElement.selectedIndex = selectElement.length - 1;   // select it
      }
    }
  }
}
