/*
	Country State Drop Downs v1.1.  

	(c) Copyright 2006 by 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.


	To install, add the following to the top of your page paste the html between the 
   form tags from demo2.html or demo.html into your page.

*/


// State table
// 
// To edit the list, just delete a line or add a line.  Order is important.  The order 
// displayed is the order it appears on the drop down.
//
var state = '\
US:AK:Alaska|\
US:AL:Alabama|\
US:AR:Arkansas|\
US:AS:American Samoa|\
US:AZ:Arizona|\
US:CA:California|\
US:CO:Colorado|\
US:CT:Connecticut|\
US:DC:D.C.|\
US:DE:Delaware|\
US:FL:Florida|\
US:FM:Micronesia|\
US:GA:Georgia|\
US:GU:Guam|\
US:HI:Hawaii|\
US:IA:Iowa|\
US:ID:Idaho|\
US:IL:Illinois|\
US:IN:Indiana|\
US:KS:Kansas|\
US:KY:Kentucky|\
US:LA:Louisiana|\
US:MA:Massachusetts|\
US:MD:Maryland|\
US:ME:Maine|\
US:MH:Marshall Islands|\
US:MI:Michigan|\
US:MN:Minnesota|\
US:MO:Missouri|\
US:MP:Marianas|\
US:MS:Mississippi|\
US:MT:Montana|\
US:NC:North Carolina|\
US:ND:North Dakota|\
US:NE:Nebraska|\
US:NV:Nevada|\
US:NH:New Hampshire|\
US:NJ:New Jersey|\
US:NM:New Mexico|\
US:NY:New York|\
US:OH:Ohio|\
US:OK:Oklahoma|\
US:OR:Oregon|\
US:PA:Pennsylvania|\
US:PR:Puerto Rico|\
US:PW:Palau|\
US:RI:Rhode Island|\
US:SC:South Carolina|\
US:SD:South Dakota|\
US:TN:Tennessee|\
US:TX:Texas|\
US:UT:Utah|\
US:VA:Virginia|\
US:VI:Virgin Islands|\
US:VT:Vermont|\
US:WA:Washington|\
US:WI:Wisconsin|\
US:WV:West Virginia|\
US:WY:Wyoming|\
US:AA:Military Americas|\
US:AE:Military Europe/ME/Canada|\
US:AP:Military Pacific|\
CA:AB:Alberta|\
CA:BC:British Columbia|\
CA:MB:Manitoba|\
CA:NB:New Brunswick|\
CA:NL:Newfoundland and Labrador|\
CA:NS:Nova Scotia|\
CA:NT:Northwest Territories|\
CA:NU:Nunavut|\
CA:ON:Ontario|\
CA:PE:Prince Edward Island|\
CA:QC:Quebec|\
CA:SK:Saskatchewan|\
CA:YT:Yukon Territory|\
AU:AAT:Australian Antarctic Territory|\
AU:ACT:Australian Capital Territory|\
AU:NT:Northern Territory|\
AU:NSW:New South Wales|\
AU:QLD:Queensland|\
AU:SA:South Australia|\
AU:TAS:Tasmania|\
AU:VIC:Victoria|\
AU:WA:Western Australia|\
BR:AC:Acre|\
BR:AL:Alagoas|\
BR:AM:Amazonas|\
BR:AP:Amapa|\
BR:BA:Baia|\
BR:CE:Ceara|\
BR:DF:Distrito Federal|\
BR:ES:Espirito Santo|\
BR:FN:Fernando de Noronha|\
BR:GO:Goias|\
BR:MA:Maranhao|\
BR:MG:Minas Gerais|\
BR:MS:Mato Grosso do Sul|\
BR:MT:Mato Grosso|\
BR:PA:Para|\
BR:PB:Paraiba|\
BR:PE:Pernambuco|\
BR:PI:Piaui|\
BR:PR:Parana|\
BR:RJ:Rio de Janeiro|\
BR:RN:Rio Grande do Norte|\
BR:RO:Rondonia|\
BR:RR:Roraima|\
BR:RS:Rio Grande do Sul|\
BR:SC:Santa Catarina|\
BR:SE:Sergipe|\
BR:SP:Sao Paulo|\
BR:TO:Tocatins|\
NL:DR:Drente|\
NL:FL:Flevoland|\
NL:FR:Friesland|\
NL:GL:Gelderland|\
NL:GR:Groningen|\
NL:LB:Limburg|\
NL:NB:Noord Brabant|\
NL:NH:Noord Holland|\
NL:OV:Overijssel|\
NL:UT:Utrecht|\
NL:ZH:Zuid Holland|\
NL:ZL:Zeeland|\
UK:EN:England|\
UK:NI:Northern Ireland|\
UK:SL:Scotland|\
UK:WA:Wales|\
IE:CO CAVAN:County Cavan|\
IE:CO DONEGAL:County Donegal|\
IE:CO MONAGHAN:County Monaghan|\
IE:CO DUBLIN:County Dublin|\
IE:CO CARLOW:County Carlow|\
IE:CO KILDARE:County Kildare|\
IE:CO KILKENNY:County Kilkenny|\
IE:CO LAOIS:County Laois|\
IE:CO LONGFORD:County Longford|\
IE:CO LOUTH:County Louth|\
IE:CO MEATH:County Meath|\
IE:CO OFFALY:County Offaly|\
IE:CO WESTMEATH:County Westmeath|\
IE:CO WEXFORD:County Wexford|\
IE:CO WICKLOW:County Wicklow|\
IE:CO GALWAY:County Galway|\
IE:CO MAYO:County Mayo|\
IE:CO LIETRIM:County Leitrim|\
IE:CO ROSCOMMON:County Roscommon|\
IE:CO SLIGO:County Sligo|\
IE:CO CLARE:County Clare|\
IE:CO CORK:County Cork|\
IE:CO KERRY:County Kerry|\
IE:CO LIMERICK:County Limerick|\
IE:CO TIPPERARY:County Tipperary|\
IE:CO WATERFORD:County Waterford';

/* Rather than use counties for the UK (as originally was the case),
I used provinces and constituent countries. Two-character codes
used may not be official codes. Irish addresses use counties
instead of provinces. I removed the 6 counties that belong to
Northern Ireland.

/* Counties in Northern Ireland. N Ireland is a province of the UK not a part of
the republic of Ireland, so these counties were removed. Northern Ireland no longer
uses counties as part of their address.

The correct country code for Ireland is IE, not EI. Changed EI to IE.

IE:CO ANTRIM:County Antrim|\
IE:CO ARMAGH:County Armagh|\
IE:CO DOWN:County Down|\
IE:CO FERMANAGH:County Fermanagh|\
IE:CO DERRY:County Londonderry|\
IE:CO TYRONE:County Tyrone|\

/* Provinces of the republic of Ireland. Apparently not used in addresses.
IE:CO:Connacht|\
IE:LE:Leinster|\
IE:MU:Munster|\
IE:UL:Ulster|\*/

// Country data table
//
// 
// To edit the list, just delete a line or add a line.  Order is important.  The order 
// displayed is the order it appears on the drop down.
//
var country = '\
AF:AFGHANISTAN|\
AL:ALBANIA|\
DZ:ALGERIA|\
AS:AMERICAN SAMOA|\
AD:ANDORRA|\
AO:ANGOLA|\
AI:ANGUILLA|\
AA:ANTARCTICA|\
AG:ANTIGUA|\
AR:ARGENTINA|\
AM:ARMENIA|\
AW:ARUBA|\
AU:AUSTRALIA|\
AT:AUSTRIA|\
AZ:AZERBAIJAN|\
BS:BAHAMAS, THE|\
BH:BAHRAIN|\
BD:BANGLADESH|\
BB:BARBADOS|\
BY:BELARUS|\
BE:BELGIUM|\
BZ:BELIZE|\
BJ:BENIN|\
BM:BERMUDA|\
BT:BHUTAN|\
BO:BOLIVIA|\
BA:BOSNIA-HERZEGOVINA|\
BW:BOTSWANA|\
BV:BOUVET ISLAND|\
BR:BRAZIL|\
IO:BRITISH INDIAN OCEAN|\
VG:BRITISH VIRGIN IS|\
BN:BRUNEI|\
BG:BULGARIA|\
BF:BURKINA FASO|\
MM:BURMA|\
BI:BURUNDI|\
KH:CAMBODIA|\
CM:CAMEROON|\
CA:CANADA|\
CE:CANAL ZONE|\
CV:CAPE VERDE, REPUBLIC|\
KY:CAYMAN ISLANDS|\
CF:CENTRAL AFRICAN EMP|\
TD:CHAD|\
CD:CHANNEL ISLANDS|\
CL:CHILE|\
CN:CHINA (PRC)|\
CX:CHRISTMAS ISLAND|\
CC:COCOS (KEELING) IS|\
CO:COLOMBIA|\
KM:COMOROS|\
CG:CONGO|\
CK:COOK ISLANDS|\
CR:COSTA RICA|\
HR:CROATIA|\
CU:CUBA|\
CY:CYPRUS|\
CZ:CZECH REPUBLIC|\
DK:DENMARK|\
DJ:DJIBOUTI|\
DM:DOMINICA|\
DO:DOMINICAN REPUBLIC|\
TP:EAST TIMOR|\
EC:ECUADOR|\
EG:EGYPT|\
SV:EL SALVADOR|\
GQ:EQUATORIAL GUINEA|\
ER:ERITREA|\
EE:ESTONIA|\
ET:ETHIOPIA|\
FK:FALKLAND ISLANDS|\
FO:FAROE ISLANDS|\
FJ:FIJI|\
FI:FINLAND|\
FR:FRANCE|\
GF:FRENCH GUIANA|\
PF:FRENCH POLYNESIA|\
TF:FRENCH SOUTHERN|\
GA:GABON|\
GM:GAMBIA, THE|\
GZ:GAZA STRIP|\
GE:GEORGIA|\
DE:GERMANY|\
GH:GHANA|\
GI:GIBRALTAR|\
GR:GREECE|\
GL:GREENLAND|\
GD:GRENADA|\
GP:GUADELOUPE|\
GU:GUAM|\
GT:GUATEMALA|\
GN:GUINEA|\
GW:GUINEA-BISSAU|\
GY:GUYANA|\
HT:HAITI|\
HM:HEARD & MCDONALD, IS|\
HN:HONDURAS|\
HK:HONG KONG|\
HU:HUNGARY|\
IS:ICELAND|\
IN:INDIA|\
ID:INDONESIA|\
IR:IRAN|\
IQ:IRAQ|\
IE:IRELAND|\
IL:ISRAEL|\
IT:ITALY|\
CI:IVORY COAST|\
JM:JAMAICA|\
JP:JAPAN|\
JA:JOHNSTON ATOLL|\
JO:JORDAN|\
KE:KENYA|\
KZ:KHAZAKSTAN|\
KI:KIRIBATI|\
KP:KOREA, P. DEM. REP.|\
KR:KOREA, REPUBLIC OF|\
KV:KOSOVO|\
KW:KUWAIT|\
KG:KYRGYZSTAN|\
LA:LAOS|\
LV:LATVIA|\
LB:LEBANON|\
LS:LESOTHO|\
LR:LIBERIA|\
LY:LIBYA|\
LI:LIECHTENSTEIN|\
LT:LITHUANIA|\
LU:LUXEMBOURG|\
MO:MACAO|\
MK:MACEDONIA|\
MG:MADAGASCAR|\
MW:MALAWI|\
MY:MALAYSIA|\
MV:MALDIVES|\
ML:MALI|\
MT:MALTA|\
MH:MARSHALL ISLANDS|\
MQ:MARTINIQUE|\
MR:MAURITANIA|\
MU:MAURITIUS|\
MX:MEXICO|\
FM:MICRONESIA, FEDERATED STATES|\
MI:MIDWAY ISLANDS|\
MD:MOLDOVA|\
MC:MONACO|\
MN:MONGOLIA|\
ME:MONTENEGRO|\
MS:MONTSERRAT|\
MA:MOROCCO|\
MZ:MOZAMBIQUE|\
MM:MYANMAR (BURMA)|\
NA:NAMIBIA|\
NR:NAURU|\
NV:NAVASSA ISLAND|\
NP:NEPAL|\
NL:NETHERLANDS|\
AN:NETHERLANDS ANTILLES|\
NC:NEW CALEDONIA|\
NZ:NEW ZEALAND|\
NI:NICARAGUA|\
NE:NIGER|\
NG:NIGERIA|\
NU:NIUE|\
NF:NORFOLK ISLAND|\
NM:NORTHERN MARIANA IS|\
NO:NORWAY|\
OM:OMAN|\
PK:PAKISTAN|\
PW:PALAU|\
PA:PANAMA|\
PG:PAPUA NEW GUINEA|\
PI:PARACEL ISLANDS|\
PY:PARAGUAY|\
PE:PERU|\
PH:PHILIPPINES|\
PN:PITCAIRN ISLANDS|\
PL:POLAND|\
PT:PORTUGAL|\
PR:PUERTO RICO|\
QA:QATAR|\
RE:REUNION|\
RO:ROMANIA|\
RU:RUSSIA|\
RW:RWANDA|\
SM:SAN MARINO|\
ST:SAO TOME & PRINCIPE|\
SA:SAUDI ARABIA|\
SN:SENEGAL|\
SS:SERBIA|\
SC:SEYCHELLES|\
SL:SIERRA LEONE|\
SG:SINGAPORE|\
SK:SLOVAK REPUBLIC|\
SI:SLOVENIA|\
SB:SOLOMON ISLANDS|\
SO:SOMALIA|\
ZA:SOUTH AFRICA|\
ES:SPAIN|\
SP:SPRATLY ISLANDS|\
LK:SRI LANKA|\
KN:ST CHRISTOPER-NEVIS|\
SH:ST HELENA|\
PM:ST PIERRE & MIQUELON|\
LC:ST. LUCIA|\
VC:ST. VINCENT|\
SD:SUDAN|\
SR:SURINAM|\
SJ:SVALBARD & JAN MAYEN|\
SZ:SWAZILAND|\
SE:SWEDEN|\
CH:SWITZERLAND|\
SY:SYRIA|\
TW:TAIWAN|\
TJ:TAJIKISTAN|\
TZ:TANZANIA, UNITED REP|\
TH:THAILAND|\
TG:TOGO|\
TK:TOKELAU|\
TO:TONGA|\
TT:TRINIDAD AND TOBAGO|\
PC:TRUST TERRITORY OF THE PACIFIC ISLANDS|\
TN:TUNISIA|\
TR:TURKEY|\
TM:TURKMENISTAN|\
TC:TURKS AND CAICOS IS|\
TV:TUVALU|\
UG:UGANDA|\
UA:UKRAINE|\
AE:UNITED ARAB EMIRATES|\
UK:UNITED KINGDOM|\
US:USA|\
UY:URUGUAY|\
UZ:UZBEKISTAN|\
VU:VANUATU|\
VA:VATICAN CITY|\
VE:VENEZUELA|\
VN:VIETNAM|\
VI:VIRGIN ISLANDS OF US|\
WA:WAKE ISLAND|\
WF:WALLIS AND FUTUNA|\
WE:WEST BANK|\
EH:WESTERN SAHARA|\
WS:WESTERN SAMOA|\
YE:YEMEN, P. DEM. REP.|\
YU:YUGOSLAVIA|\
ZM:ZAMBIA|\
ZW:ZIMBABWE';

// Save the country & state field names
var countryFieldCfgArray = document.getElementById('cs_config_country_field').value.split(' ');
var stateFieldCfgArray   = document.getElementById('cs_config_state_field').value.split(' ');

// Save the names of the fields that hold the country & state default values
var countryDefaultCfgArray = document.getElementById('cs_config_country_default').value.split(' ');
var stateDefaultCfgArray   = document.getElementById('cs_config_state_default').value.split(' ');

var defaultState = false;
var defaultCountry = false;

var countriesArray = new Array();      // Changed. Inserted this line.

function TrimString(sInString) {
   
   if ( sInString ) {

      sInString = sInString.replace( /^\s+/g, "" );// strip leading
      return sInString.replace( /\s+$/g, "" );// strip trailing
   }
}
// Populates the country select with the counties from the country list
//
function populateCountry(idName) {

   var countryLineArray = country.split('|');      // Split into lines

   var selObj = document.getElementById( idName );

   selObj.options[0] = new Option('Select Country','');
   selObj.selectedIndex = 0;

   for (var loop = 0; loop < countryLineArray.length; loop++) {

      lineArray = countryLineArray[loop].split(':');

      countryCode  = TrimString(lineArray[0]);
      countryName  = TrimString(lineArray[1]);
	  countriesArray[countryCode] = countryName.toUpperCase(); // Changed. Inserted this line.
   
      if ( countryCode != '' ) {

         selObj.options[loop + 1] = new Option(countryName, countryName);// changed countryCode to countryName (2nd arg)
      }

      if ( defaultCountry == countryName.toUpperCase() ) {// changed countryCode to countryName.toUpperCase()

         selObj.selectedIndex = loop + 1;
      }
   }
}
function populateState( statestateIdName, countryIdName ) {

   var selObj = document.getElementById( stateIdName );
   var foundState = false;

   // Empty options just in case new drop down is shorter
   //
   if ( selObj.type == 'select-one' ) {

      selObj.options.length = 0;

      selObj.options[0] = new Option('Select State','');
      selObj.selectedIndex = 0;
   }
   // Populate the drop down with states from the selected country
   //
   var stateLineArray   = state.split("|");        // Split into lines

   var optionCntr = 1;

   for (var loop = 0; loop < stateLineArray.length; loop++) {

      lineArray = stateLineArray[loop].split(":");

      countryCode  = TrimString(lineArray[0]);
      stateCode    = TrimString(lineArray[1]);
      stateName    = TrimString(lineArray[2]);

      if ( document.getElementById( countryIdName ).value.toUpperCase() == countriesArray[countryCode] && countryCode != '' ) { //changed countryCode to countriesArray[countryCode] and document.getElementById( countryIdName ).value to document.getElementById( countryIdName ).value.toUpperCase()

         // If it's a input element, change it to a select
         //
         if ( selObj.type == 'text' ) {


            var inputSel = document.createElement("SELECT");
            inputSel.setAttribute("name", selObj.name); // changed "state" to selObj.name
            inputSel.setAttribute("id", stateIdName ); 

            parentObj = document.getElementById( stateIdName ).parentNode;// Moved down 6 lines.
            parentObj.removeChild(selObj);// Moved down 6 lines.
            parentObj.appendChild(inputSel) ;

            selObj = document.getElementById( stateIdName );
            selObj.options[0] = new Option('Select State','');
            selObj.selectedIndex = 0;
         }
   
         if ( stateCode != '' ) {

            selObj.options[optionCntr] = new Option(stateName, stateCode);// changed stateCode to stateName (2nd arg)
         }
         // See if it's selected from a previous post
         //
         if ( stateCode == defaultState.toUpperCase() && countriesArray[countryCode] == defaultCountry ) {// changed stateCode to stateName.toUpperCase() and defaultState to defaultState.toUpperCase() and countryCode to countriesArray[countryCode]

            selObj.selectedIndex = optionCntr;
         }
         foundState = true;
         optionCntr++
      }
   }
   // If the country has no states, change the select to a text box
   //
   if ( ! foundState ) {
 
      // Create the Input Field
      var inputEl = document.createElement("INPUT");

      inputEl.setAttribute("id",  stateIdName ); 
      inputEl.setAttribute("type", "text"); 
      inputEl.setAttribute("name", selObj.name); // changed "state" to selObj.name
      inputEl.setAttribute("size", 20); 
      inputEl.setAttribute("value", defaultState);  
      inputEl.setAttribute("maxlength", 255); // Changed. Inserted line

      parentObj = document.getElementById( stateIdName ).parentNode;// Moved down 11 lines
      parentObj.removeChild(selObj);// Moved down 11 lines
      parentObj.appendChild(inputEl) ;
   }
   
}
// Called when state drop down is changed
// 
function updateState( countryIdNameIn ) {

   for (var loop = 0; loop < countryFieldCfgArray.length; loop++) {
   
      countryIdName  = countryFieldCfgArray[loop];
      stateIdName    = stateFieldCfgArray[loop];

      // Read the default value hidden fields
      defaultCountry = document.getElementById( countryDefaultCfgArray[loop] ).value.toUpperCase(); // Changed. added .toUpperCase()
      defaultState   = document.getElementById( stateDefaultCfgArray[loop] ).value;

      if ( countryIdNameIn == countryIdName ) {

         populateState( stateIdName, countryIdName );
      }
   }
}
// Initialize the drop downs
// 
function initCountry() {

   for (var loop = 0; loop < countryFieldCfgArray.length; loop++) {
   
      countryIdName  = countryFieldCfgArray[loop];
      stateIdName    = stateFieldCfgArray[loop];

      // Read the default value hidden fields
      defaultCountry = document.getElementById( countryDefaultCfgArray[loop] ).value.toUpperCase(); // Changed. added .toUpperCase()
      defaultState   = document.getElementById( stateDefaultCfgArray[loop] ).value;

      populateCountry( countryIdName);
      populateState( stateIdName, countryIdName );
   }
}


