/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Down Home Consulting :: http://downhomeconsulting.com */

/*
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.

*/

// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
var postState = '';
var postCountry = '';

// State table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:AL:Alabama|\
US:AK:Alaska|\
US:AS:American Samoa|\
US:AZ:Arizona|\
US:AR:Arkansas|\
US:CA:California|\
US:CO:Colorado|\
US:CT:Connecticut|\
US:DE:Delaware|\
US:DC:District Of Columbia|\
US:FM:Federated States Of Micronesia|\
US:FL:Florida|\
US:GA:Georgia|\
US:GU:Guam|\
US:HI:Hawaii|\
US:ID:Idaho|\
US:IL:Illinois|\
US:IN:Indiana|\
US:IA:Iowa|\
US:KS:Kansas|\
US:KY:Kentucky|\
US:LA:Louisiana|\
US:ME:Maine|\
US:MH:Marshall Islands|\
US:MD:Maryland|\
US:MA:Massachusetts|\
US:MI:Michigan|\
US:MN:Minnesota|\
US:MS:Mississippi|\
US:MO:Missouri|\
US:MT:Montana|\
US:NE:Nebraska|\
US:NV:Nevada|\
US:NH:New Hampshire|\
US:NJ:New Jersey|\
US:NM:New Mexico|\
US:NY:New York|\
US:NC:North Carolina|\
US:ND:North Dakota|\
US:MP:Northern Mariana Islands|\
US:OH:Ohio|\
US:OK:Oklahoma|\
US:OR:Oregon|\
US:PW:Palau|\
US:PA:Pennsylvania|\
US:PR:Puerto Rico|\
US:RI:Rhode Island|\
US:SC:South Carolina|\
US:SD:South Dakota|\
US:TN:Tennessee|\
US:TX:Texas|\
US:UT:Utah|\
US:VT:Vermont|\
US:VI:Virgin Islands|\
US:VA:Virginia|\
US:WA:Washington|\
US:WV:West Virginia|\
US:WI:Wisconsin|\
US:WY:Wyoming|\
US:AE:Armed Forces Africa|\
US:AA:Armed Forces Americas|\
US:AE:Armed Forces Canada|\
US:AE:Armed Forces Europe|\
US:AE:Armed Forces Middle East|\
US:AP:Armed Forces 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: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|\
EI:CO ANTRIM:County Antrim|\
EI:CO ARMAGH:County Armagh|\
EI:CO DERRY:County Londonderry|\
EI:CO DOWN:County Down|\
EI:CO FERMANAGH:County Fermanagh|\
EI:CO TYRONE:County Tyrone|\
IE:CO CARLOW:County Carlow|\
IE:CO CAVAN:County Cavan|\
IE:CO CLARE:County Clare|\
IE:CO CORK:County Cork|\
IE:CO DONEGAL:County Donegal|\
IE:CO DUBLIN:County Dublin|\
IE:CO GALWAY:County Galway|\
IE:CO KERRY:County Kerry|\
IE:CO KILDARE:County Kildare|\
IE:CO KILKENNY:County Kilkenny|\
IE:CO LAIOGHIS:County Laioghis|\
IE:CO LEITRIM:County Leitrim|\
IE:CO LIMERICK:County Limerick|\
IE:CO LONGFORD:County Longford|\
IE:CO LOUTH:County Louth|\
IE:CO MAYO:County Mayo|\
IE:CO MEATH:County Meath|\
IE:CO MONAGHAN:County Monaghan|\
IE:CO OFFALY:County Offaly|\
IE:CO ROSCOMMON:County Roscommon|\
IE:CO SLIGO:County Sligo|\
IE:CO TIPPERARY:County Tipperary|\
IE:CO WATERFORD:County Waterford|\
IE:CO WESTMEATH:County Westmeath|\
IE:CO WEXFORD:County Wexford|\
IE:CO WICKLOW:County Wicklow|\
MX:AG:Aguascalientes|\
MX:BA:Baja, California (North)|\
MX:BJ:Baja, California (South)|\
MX:CE:Campeche|\
MX:CI:Chiapas|\
MX:CH:Chihuahua|\
MX:CU:Coahuila de Zaragoza|\
MX:CL:Colima|\
MX:DF:Destrito Federal|\
MX:DO:Durango|\
MX:GX:Guanajuato|\
MX:GR:Guerrero|\
MX:HL:Hidalgo|\
MX:JL:Jalisco|\
MX:MX:Mexico, Estado de|\
MX:MC:Michoacande Ocampo|\
MX:MR:Morelos|\
MX:NA:Nayarit|\
MX:NN:Neuvo Leon|\
MX:OA:Oaxaca|\
MX:PB:Puebla|\
MX:QU:Queretaro de Arteaga|\
MX:QR:Quintana Roo|\
MX:SL:San Luis Potosi|\
MX:SI:Sinaloa|\
MX:SO:Sonora|\
MX:TB:Tabasco|\
MX:TA:Tamaulipas|\
MX:TL:Tlaxcala|\
MX:VC:Veracruz-Llave|\
MX:YU:Yucatan|\
MX:ZA:Zacatecas\
'; //ENDSTATE

// Country data table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var country = '\
AL:Albania|\
DZ:Algeria|\
AD:Andorra|\
AO:Angola|\
AI:Anguilla|\
AG:Antigua and Barbuda|\
AR:Argentina|\
AM:Armenia|\
AW:Aruba|\
AU:Australia|\
AT:Austria|\
AZ:Azerbaijan|\
BS:Bahamas|\
BH:Bahrain|\
BB:Barbados|\
BE:Belgium|\
BZ:Belize|\
BJ:Benin|\
BM:Bermuda|\
BT:Bhutan|\
BO:Bolivia|\
BA:Bosnia and Herzegovina|\
BW:Botswana|\
BR:Brazil|\
VG:British Virgin Islands|\
BN:Brunei Darussalam|\
BG:Bulgaria|\
BF:Burkina Faso|\
BI:Burundi|\
KH:Cambodia|\
CA:Canada|\
CV:Cape Verde|\
KY:Cayman Islands|\
TD:Chad|\
CL:Chile|\
CN:China|\
CO:Colombia|\
KM:Comoros|\
CD:Congo, Democratic Republic Of|\
CG:Congo|\
CK:Cook Islands|\
CR:Costa Rica|\
HR:Croatia|\
CY:Cyprus|\
CZ:Czech Republic|\
DK:Denmark|\
DJ:Djibouti|\
DM:Dominica|\
DO:Dominican Republic|\
EC:Ecuador|\
SV:El Salvador|\
ER:Eritrea|\
EE:Estonia|\
ET:Ethiopia|\
FK:Falkland Islands|\
FO:Faroe Islands|\
FJ:Fiji|\
FI:Finland|\
FR:France|\
GF:French Guiana|\
PF:French Polynesia|\
GA:Gabon|\
GM:Gambia|\
DE:Germany|\
GI:Gibraltar|\
GR:Greece|\
GL:Greenland|\
GD:Grenada|\
GP:Guadeloupe|\
GT:Guatemala|\
GN:Guinea|\
GW:Guinea-Bissau|\
GY:Guyana|\
VA:Holy See (Vatican)|\
HN:Honduras|\
HK:Hong Kong|\
HU:Hungary|\
IS:Iceland|\
IN:India|\
ID:Indonesia|\
IE:Ireland|\
IL:Israel|\
IT:Italy|\
JM:Jamaica|\
JP:Japan|\
JO:Jordan|\
KZ:Kazakhstan|\
KE:Kenya|\
KI:Kiribati|\
KW:Kuwait|\
KG:Kyrgyzstan|\
LA:Laos|\
LV:Latvia|\
LS:Lesotho|\
LI:Liechtenstein|\
LT:Lithuania|\
LU:Luxembourg|\
MG:Madagascar|\
MW:Malawi|\
MY:Malaysia|\
MV:Maldives|\
ML:Mali|\
MT:Malta|\
MQ:Martinique|\
MR:Mauritania|\
MU:Mauritius|\
YT:Mayotte|\
MX:Mexico|\
MN:Mongolia|\
MS:Montserrat|\
MA:Morocco|\
MZ:Mozambique|\
NA:Namibia|\
NR:Nauru|\
NP:Nepal|\
NL:Netherlands|\
AN:Netherlands Antilles|\
NC:New Caledonia|\
NZ:New Zealand|\
NI:Nicaragua|\
NE:Niger|\
NU:Niue|\
NF:Norfolk Island|\
NO:Norway|\
OM:Oman|\
PA:Panama|\
PG:Papua New Guinea|\
PE:Peru|\
PH:Philippines|\
PN:Pitcairn Islands|\
PL:Poland|\
PT:Portugal|\
QA:Qatar|\
RE:Reunion|\
RO:Romania|\
RU:Russia|\
RW:Rwanda|\
WS:Samoa|\
SM:San Marino|\
ST:Sao Tome and Principe|\
SA:Saudi Arabia|\
SN:Senegal|\
SC:Seychelles|\
SL:Sierra Leone|\
SG:Singapore|\
SK:Slovakia|\
SI:Slovenia|\
SB:Solomon Islands|\
SO:Somalia|\
ZA:South Africa|\
KR:South Korea|\
ES:Spain|\
LK:Sri Lanka|\
SH:St. Helena, Ascension & Tristan da Cunha|\
KN:St. Kitts and Nevis|\
LC:St. Lucia|\
PM:St. Pierre and Miquelon|\
VC:St. Vincent and the Grenadines|\
SR:Suriname|\
SJ:Svalbard & Jan Mayen Islands|\
SZ:Swaziland|\
SE:Sweden|\
CH:Switzerland|\
TW:Taiwan|\
TJ:Tajikistan|\
TZ:Tanzania|\
TH:Thailand|\
TG:Togo|\
TO:Tonga|\
TT:Trinidad and Tobago|\
TN:Tunisia|\
TR:Turkey|\
TM:Turkmenistan|\
TC:Turks and Caicos Islands|\
TV:Tuvalu|\
UG:Uganda|\
UA:Ukraine|\
AE:United Arab Emirates|\
GB:United Kingdom|\
US:United States|\
UY:Uruguay|\
VU:Vanuatu|\
VE:Venezuela|\
VN:Vietnam|\
WF:Wallis and Futuna|\
YE:Yemen|\
ZM:Zambia\
';

function TrimString(sInString) 
{
  	if ( sInString ) 
	{
    		sInString = sInString.replace( /^\s+/g, "" );// strip leading
    		return sInString.replace( /\s+$/g, "" );// strip trailing
  	}
}

// Populates the country selected with the counties from the country list

function populateCountry(countryElementID, defaultCountry)
{
  	if ( postCountry != '' ) 
	{
    		defaultCountry = postCountry;
  	}

  	var countryLineArray = country.split('|');  // Split into lines
  	var selObj = document.getElementById(countryElementID);
  	var curValue = selObj.getAttribute("curvalue");

  	if ( curValue != null ) 
	{
    		defaultCountry = curValue;
  	}

  	selObj.options[0] = new Option('Select Country','');
  	selObj.selectedIndex = 0;
  	selObj.value = '';

  	for (var loop = 0; loop < countryLineArray.length; loop++) 
	{
    		lineArray = countryLineArray[loop].split(':');
    		countryCode  = TrimString(lineArray[0]);
    		countryName  = TrimString(lineArray[1]);

    		if ( countryCode != '' ) 
		{
      			// selObj.options[loop + 1] = new Option(countryName, countryCode);
      			selObj.options[loop + 1] = new Option(countryName, countryName);
			selObj.options[loop + 1].setAttribute("ctry_code", countryCode);
    		}

    		if ( defaultCountry == countryCode || defaultCountry == countryName ) 
		{
      			selObj.selectedIndex = loop + 1;

      			// selObj.value = countryCode;
      			selObj.value = countryName;

      			selObj.options[loop + 1].defaultSelected = true;
    		}
  	}
}

function populateState(countryElementID, stateElementID, stateElementName) 
{
  	var selObj = document.getElementById(stateElementID);
  	var curValue = selObj.getAttribute("curvalue");
  	var foundState = false;

   	if ( curValue == null ) 
	{
    		curValue = '';
  	}

 	// Empty options just in case new drop down is shorter

  	if ( selObj.type == 'select-one' ) 
	{
    		for (var i = 0; i < selObj.options.length; i++) 
		{
      			selObj.options[i] = null;
    		}

    		selObj.options.length=null;
    		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;

  	// var countryValue = document.getElementById(countryElementID).value;
  	var countrySel = document.getElementById(countryElementID);
  	var countryIdx = countrySel.selectedIndex;
  	var countryValue = countrySel.options[countryIdx].getAttribute("ctry_code");

	if ( countryValue != null && countryValue != '' )
	{
  		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 ( countryValue == countryCode && countryCode != '' ) 
			{
    				// If it's a input element, change it to a select

      				if ( selObj.type == 'text' ) 
				{
        				parentObj = selObj.parentNode;
        				// parentObj.removeChild(selObj);

        				var inputSel = document.createElement("SELECT");

        				inputSel.setAttribute("name", stateElementName);
        				inputSel.setAttribute("id", stateElementID);
      					inputSel.setAttribute("curvalue", curValue);

        				parentObj.replaceChild(inputSel, selObj) ;

        				selObj = document.getElementById(stateElementID);
        				selObj.options[0] = new Option('Select State','');
        				selObj.selectedIndex = 0;
      				}

      				if ( stateCode != '' ) 
				{
        				// selObj.options[optionCntr] = new Option(stateName, stateCode);
        				selObj.options[optionCntr] = new Option(stateName, stateName);
      				}

      				// See if it's selected from a previous post

      				// if ( ( stateCode == postState && countryCode == postCountry ) || ( stateCode == curValue ) )       		
				if ( curValue != null && ( stateCode == curValue || stateName == curValue ) ) 
				{
        				selObj.selectedIndex = optionCntr;

      					//selObj.value = stateCode;
      					selObj.value = stateName;

      					selObj.options[optionCntr].defaultSelected = true;
      				}

      				foundState = true;
      				optionCntr++
    			}
		}
  	}

  	// If the country has no states, change the select to a text box

  	if ( ! foundState ) 
	{
    		parentObj = selObj.parentNode;
    		// parentObj.removeChild(selObj);

  		// Create the Input Field

    		var inputEl = document.createElement("INPUT");

    		inputEl.setAttribute("id", stateElementID);
    		inputEl.setAttribute("type", "text");
    		inputEl.setAttribute("name", stateElementName);
    		inputEl.setAttribute("size", 30);
    		inputEl.setAttribute("value", curValue);
       		inputEl.setAttribute("curvalue", curValue);

    		parentObj.replaceChild(inputEl, selObj) ;
  	}
}

function initCountry(countryElementID, stateElementID, stateElementName, defaultCountry) 
{
  	populateCountry(countryElementID, defaultCountry);
  	populateState(countryElementID, stateElementID, stateElementName);
}
