/* 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: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:District of Columbia|\
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:NH:New Hampshire|\
US:NJ:New Jersey|\
US:NM:New Mexico|\
US:NV:Nevada|\
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:MB:Manitoba|\
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|\
';

// 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='\
US:Estados Unidos|\
AL:Albania|\
DE:Alemania|\
AD:Andorra|\
AO:Angola|\
AI:Anguila|\
AG:Antigua y Barbuda|\
AN:Antillas Holandesas|\
SA:Arabia Saudí|\
DZ:Argelia|\
AR:Argentina|\
AM:Armenia|\
AW:Aruba|\
AU:Australia|\
AT:Austria|\
BS:Bahamas|\
BH:Bahréin|\
BB:Barbados|\
BE:Bélgica|\
BZ:Belice|\
BJ:Benín|\
BM:Bermudas|\
BT:Bhután|\
BO:Bolivia|\
BA:Bosnia y Herzegovina|\
BW:Botsuana|\
BR:Brasil|\
BN:Brunéi|\
BG:Bulgaria|\
BF:Burkina Faso|\
BI:Burundi|\
CV:Cabo Verde|\
KH:Camboya|\
CA:Canadá|\
TD:Chad|\
CL:Chile|\
C2:China|\
CY:Chipre|\
VA:Ciudad del Vaticano|\
CO:Colombia|\
KM:Comoras|\
KR:Corea del Sur|\
CR:Costa Rica|\
HR:Croacia|\
DK:Dinamarca|\
DM:Dominica|\
EC:Ecuador|\
SV:El Salvador|\
AE:Emiratos Árabes Unidos|\
ER:Eritrea|\
SK:Eslovaquia|\
SI:Eslovenia|\
ES:España|\
FM:Estados Federados de Micronesia|\
EE:Estonia|\
ET:Etiopía|\
PH:Filipinas|\
FI:Finlandia|\
FJ:Fiyi|\
FR:Francia|\
GM:Gambia|\
GI:Gibraltar|\
GD:Granada|\
GR:Grecia|\
GL:Groenlandia|\
GP:Guadalupe|\
GT:Guatemala|\
GF:Guayana Francesa|\
GN:Guinea|\
GW:Guinea-Bissau|\
GY:Guyana|\
HN:Honduras|\
HK:Hong Kong|\
HU:Hungría|\
IN:India|\
ID:Indonesia|\
IE:Irlanda|\
NF:Isla Norfolk|\
IS:Islandia|\
KY:Islas Caimán|\
CK:Islas Cook|\
FO:Islas Feroe|\
FK:Islas Malvinas|\
MH:Islas Marshall|\
PN:Islas Pitcairn|\
SB:Islas Salomón|\
TC:Islas Turcas y Caicos|\
VG:Islas Vírgenes Británicas|\
IL:Israel|\
IT:Italia|\
JM:Jamaica|\
JP:Japón|\
JO:Jordania|\
KZ:Kazajstán|\
KE:Kenia|\
KG:Kirguistán|\
KI:Kiribati|\
KW:Kuwait|\
LA:Laos|\
LS:Lesotho|\
LV:Letonia|\
LI:Liechtenstein|\
LT:Lituania|\
LU:Luxemburgo|\
MG:Madagascar|\
MY:Malasia|\
MW:Malawi|\
MV:Maldivas|\
ML:Malí|\
MT:Malta|\
MA:Marruecos|\
MQ:Martinica|\
MU:Mauricio|\
MR:Mauritania|\
YT:Mayotte|\
MX:México|\
MN:Mongolia|\
MS:Montserrat|\
MZ:Mozambique|\
NA:Namibia|\
NR:Nauru|\
NP:Nepal|\
NI:Nicaragua|\
NE:Níger|\
NU:Niue|\
NO:Noruega|\
NC:Nueva Caledonia|\
NZ:Nueva Zelanda|\
OM:Omán|\
NL:Países Bajos|\
PW:Palaos|\
PA:Panamá|\
PG:Papúa Nueva Guinea|\
PE:Perú|\
PF:Polinesia Francesa|\
PL:Polonia|\
PT:Portugal|\
QA:Qatar|\
GB:Reino Unido|\
CZ:República Checa|\
AZ:República de Azarbaiyán|\
GA:República de Gabón|\
CG:República del Congo|\
CD:República Democrática del Congo|\
DO:República Dominicana|\
RE:Reunión|\
RW:Ruanda|\
RO:Rumanía|\
RU:Rusia|\
WS:Samoa|\
KN:San Cristóbal y Nieves|\
SM:San Marino|\
PM:San Pedro y Miquelón|\
VC:San Vicente y las Granadinas|\
SH:Santa Elena|\
LC:Santa Lucía|\
ST:Santo Tomé y Príncipe|\
SN:Senegal|\
SC:Seychelles|\
SL:Sierra Leona|\
SG:Singapur|\
SO:Somalia|\
LK:Sri Lanka|\
SZ:Suazilandia|\
ZA:Sudáfrica|\
SE:Suecia|\
CH:Suiza|\
SR:Surinam|\
SJ:Svalbard y Jan Mayen|\
TH:Tailandia|\
TW:Taiwán|\
TZ:Tanzania|\
TJ:Tayikistán|\
TG:Togo|\
TO:Tonga|\
TT:Trinidad y Tobago|\
TN:Túnez|\
TM:Turkmenistán|\
TR:Turquía|\
TV:Tuvalu|\
UA:Ucrania|\
UG:Uganda|\
UY:Uruguay|\
VU:Vanuatu|\
VE:Venezuela|\
VN:Vietnam|\
WF:Wallis y Futuna|\
YE:Yemen|\
DJ:Yibuti|\
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(defaultCountry) {
  if ( postCountry != '' ) {
    defaultCountry = postCountry;
  }
  var countryLineArray = country.split('|');  // Split into lines
  var selObj = document.getElementById('countrySelect');
  selObj.options[0] = new Option('Seleccionar País','');
  selObj.selectedIndex = 0;
  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);
    }
    if ( defaultCountry == countryCode ) {
      selObj.selectedIndex = loop + 1;
    }
  }
}

function populateState() {
	var selObj = document.getElementById('stateSelect');
	var foundState = false;
	// 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('Seleccionar Estado','');
		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('countrySelect').value == countryCode && countryCode != '' ) {
			// If it's a input element, change it to a select
			if ( selObj.type == 'text' ) {
				parentObj = document.getElementById('stateSelect').parentNode;
				parentObj.removeChild(selObj);
				var inputSel = document.createElement("SELECT");
				inputSel.setAttribute("name","state");
				inputSel.setAttribute("id","stateSelect");
				parentObj.appendChild(inputSel) ;
				selObj = document.getElementById('stateSelect');
				selObj.options[0] = new Option('Seleccionar Estado','');
				selObj.selectedIndex = 0;
			}
			if ( stateCode != '' ) {
				selObj.options[optionCntr] = new Option(stateName, stateCode);
			}
			// See if it's selected from a previous post
			if ( stateCode == postState && countryCode == postCountry ) {
				selObj.selectedIndex = optionCntr;
			}
			foundState = true;
			optionCntr++
		}
	}
	// If the country has no states, change the select to a text box
	if ( ! foundState ) {
		parentObj = document.getElementById('stateSelect').parentNode;
		parentObj.removeChild(selObj);
		// Create the Input Field
		var inputEl = document.createElement("INPUT");
		inputEl.setAttribute("id", "stateSelect");
		inputEl.setAttribute("type", "text");
		inputEl.setAttribute("name", "state");
		inputEl.setAttribute("size", 20);
		inputEl.setAttribute("value", postState);
		parentObj.appendChild(inputEl);
	}
}

function initCountry(country) {
	populateCountry(country);
	populateState();
}

function initUSState() {
	var country = document.getElementById('countrySelect').value;
	if (country == 'US') {
		document.getElementById('stateSelect').selectedIndex = 45;
	}
}