// random functions
function makeRegionPathElement(id) {
	var tmp = "00000" + String(id)
	return tmp.substr(tmp.length-5);
}

// - add trim() method to string object - strips leading and trailing whitespace
String.prototype.trim = function() {
	return this.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

// select functions
function clear_select(selectToClear) {
	while (selectToClear.length>0) {
		selectToClear.options[0] = null
	}
}

function disable_select(select, text) {
		select.options[0] = new Option(text, "");
		select.disabled = true;
}

function enable_select(select) {
		select.disabled = false;
}

function create_option(text, value) {
	var o;
	// do indent if first character is a dash
	if (text.charAt(0) == "-") {
		if (navigator.userAgent.toUpperCase().indexOf("FIREFOX")>0 || navigator.userAgent.toUpperCase().indexOf("NETSCAPE6")>0) {
			text = text.substr(1);
		} else if (navigator.userAgent.toUpperCase().indexOf("OPERA")>0) {
			text = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + text.substr(1);
		} else if (navigator.userAgent.toUpperCase().indexOf("MSIE")>0) {
			text = "     " + text.substr(1);
		} else {
			text = "     " + text.substr(1);
		}

		o = new Option(text, value);

		if (navigator.userAgent.toUpperCase().indexOf("FIREFOX")>0 || navigator.userAgent.toUpperCase().indexOf("NETSCAPE6")>0) {
			o.style.paddingLeft = "25px";
		}

	} else {
		o = new Option(text, value);
	}
	return o;
}

function populate_select(select, regions, selectedOption, allOption, editOrSearch) {
	var i = 0;
	var j = 0;
	var selectIndex = 0;
	// array for finding selected option
	var selectionCandidates = [];

	// All of ... option
	if (String(typeof(allOption))=="object" && allOption!=null && allOption.length==6) {
		select.options[i] = create_option(String(allOption[1]), String(allOption[2]));
		i++;
		select.options[i] = new Option(" ", String(allOption[2]));
		i++;
	}
	if (editOrSearch=="search") {

		// count number of regions
		for (r in regions) j++;

		// if there are more than 20, show the most popular 5 at the top. if there are more than 40, show the most popular 10 at the top. 
		if (j>20) {
			for (r in regions) {
				var selected = (regions[r][0] == selectedOption || regions[r][1] == selectedOption || String(selectedOption).indexOf(regions[r][2]) > -1)
				if ((Number(regions[r][5]) > 0 && Number(regions[r][5]) <= (j>40?10:5))
						&& ((editOrSearch=="search" && /[npca]/i.test(regions[r][3])) 
							|| (editOrSearch=="edit" && /[npca]/i.test(regions[r][4])))) {
					select.options[i] = create_option(String(regions[r][1]), String(regions[r][2]));
					if (selected) selectionCandidates[selectionCandidates.length] = [i, String(regions[r][2])];
					i++;
				}
			}
			select.options[i] = new Option(" ", (String(typeof(allOption))=="object" && allOption!=null && allOption.length==6?String(allOption[2]):""));
			i++;
		}
	}
		
	// show all of them
	for (r in regions) {
		var selected = (String(regions[r][0]) == String(selectedOption) || String(regions[r][1]) == String(selectedOption) || String(selectedOption).indexOf(regions[r][2])>-1)
		if ((editOrSearch=="search" && /[npca]/i.test(regions[r][3])) 
			|| (editOrSearch=="edit" && /[npca]/i.test(regions[r][4]))) {
			select.options[i] = create_option(String(regions[r][1]), String(regions[r][2]));
			if (selected) selectionCandidates[selectionCandidates.length] = [i, String(regions[r][2])];
			i++;
		}
	}

	// if there is an exact match among selectionCandidates, use it, otherwise get top one
	for (c in selectionCandidates) {
		if (selectionCandidates[c][1] == String(selectedOption)) {
			selectIndex = selectionCandidates[c][0];
		}
	}
	if (selectIndex == 0 && selectionCandidates.length>0) {
		selectIndex = selectionCandidates[c][0]
	}

	select.selectedIndex = selectIndex;
	return (selectIndex>0?true:false);
}


// data functions
function get_regions(dataArray) {
	var o = [];
	for (r in dataArray) {
		var rank = dataArray[r][0].charAt(0);
		if (rank=="A") rank = 10;
		else if (rank=="B") rank = 11;
		else if (rank=="C") rank = 12;
		else if (rank=="D") rank = 13;
		else if (rank=="E") rank = 14;
		else if (rank=="F") rank = 15;
		else if (rank=="G") rank = 16;
		//output array: region_id, region_name, region_path, search_type, edit_type, rank
		o[r] = [r, dataArray[r][0].substr(dataArray[r][0].indexOf("|")+1), dataArray[r][0].substring(3, dataArray[r][0].indexOf("|")), dataArray[r][0].charAt(1), dataArray[r][0].charAt(2), rank]
	}
	return o;
}

function get_countries() {
	return get_regions(d);
}

function get_provinces(countryId) {
	if (d[countryId].length > 1) {
		return get_regions(d[countryId][1]);
	} else {
		return new Array();
	}

}

function get_cities(countryId, provinceId) {
	if (d[countryId][1][provinceId].length > 1) {
		return get_regions(d[countryId][1][provinceId][1]);
	} else {
		return new Array();
	}

}

function get_areas(countryId, provinceId, cityId) {
	if (d[countryId][1][provinceId][1][cityId].length > 1) {
		return get_regions(d[countryId][1][provinceId][1][cityId][1]);
	} else {
		return new Array();
	}
}

function get_regions_by_regionpath(regionPath) {
	var countryId = 0, provinceId = 0, cityId = 0, areaId = 0;
	var countryName = "", provinceName = "", cityName = "", areaName = "";

	if (String(regionPath).length>0) {
		// loop through countries
		outer_loop: 
		for (n in d) {
			// check if we have found the region we are looking for
			if (String(d[n][0]).substring(3, String(d[n][0]).indexOf("|")) == regionPath) {
				countryId = n;
				countryName = String(d[n][0]).substr(String(d[n][0]).indexOf("|")+1);
				break outer_loop;
			}
			// loop through provinces in country
			if (d[n][1]) {
				for (p in d[n][1]) {
					// check if we have found the region we are looking for
					if (String(d[n][1][p][0]).substring(3, String(d[n][1][p][0]).indexOf("|")) == regionPath) {
						countryId = n;
						countryName = String(d[n][0]).substr(String(d[n][0]).indexOf("|")+1);
						provinceId = p;
						provinceName = String(d[n][1][p][0]).substr(String(d[n][1][p][0]).indexOf("|")+1);
						break outer_loop;
					}
					// loop through cities in province
					if (d[n][1][p][1]) {
						for (c in d[n][1][p][1]) {
							// check if we have found the region we are looking for
							if (String(d[n][1][p][1][c][0]).substring(3, String(d[n][1][p][1][c][0]).indexOf("|")) == regionPath) {
								countryId = n;
								countryName = String(d[n][0]).substr(String(d[n][0]).indexOf("|")+1);
								provinceId = p;
								provinceName = String(d[n][1][p][0]).substr(String(d[n][1][p][0]).indexOf("|")+1);
								cityId = c;
								cityName = String(d[n][1][p][1][c][0]).substr(String(d[n][1][p][1][c][0]).indexOf("|")+1);
								break outer_loop;
							}
							// loop through areas in province
							if (d[n][1][p][1][c][1]) {
								for (a in d[n][1][p][1][c][1]) {
									// check if we have found the region we are looking for
									if (String(d[n][1][p][1][c][1][a][0]).substring(3, String(d[n][1][p][1][c][1][a][0]).indexOf("|")) == regionPath) {
										countryId = n;
										countryName = String(d[n][0]).substr(String(d[n][0]).indexOf("|")+1);
										provinceId = p;
										provinceName = String(d[n][1][p][0]).substr(String(d[n][1][p][0]).indexOf("|")+1);
										cityId = c;
										cityName = String(d[n][1][p][1][c][0]).substr(String(d[n][1][p][1][c][0]).indexOf("|")+1);
										areaId = a;
										areaName = String(d[n][1][p][1][c][1][a][0]).substr(String(d[n][1][p][1][c][1][a][0]).indexOf("|")+1);
										break outer_loop;
									}
								}
							}
						}
					}
				}
			}
		}
	}
	return [
				[countryId, countryName],
				[provinceId, provinceName],
				[cityId, cityName],
				[areaId, areaName],
			];
}

// functions to populate select's
function populate_country_select(countrySelect, provinceSelect, citySelect, areaSelect, selectedOption, editOrSearch) {
	// populate provinces select
	var countries = get_countries();

	// if there are no provinces - exit
	if (countries.length==0) {
		clear_select(countrySelect);
		disable_select(countrySelect, "You're done"); //na
		if (provinceSelect!=null) {
			clear_select(provinceSelect);
			disable_select(provinceSelect, "You're done"); //na
		}
		if (citySelect!=null) {
			clear_select(citySelect);
			disable_select(citySelect, "You're done"); //na
		}
		if (areaSelect!=null) {
			clear_select(areaSelect);
			disable_select(areaSelect, "You're done"); //na
		}
		return true;
	}

	// clear countries select
	enable_select(countrySelect)
	clear_select(countrySelect);

	var arrAllOfArray = "";
	if (editOrSearch == "edit") {
		arrAllOfArray = [0, "Please select...", "", "N", "N", 0];
	}
	return populate_select(countrySelect, countries, selectedOption, arrAllOfArray, editOrSearch);
}

function populate_province_select(provinceSelect, citySelect, areaSelect, countryId, countryName, selectedOption, editOrSearch) {
	// populate provinces select
	var provinces = get_provinces(countryId);

	// if there are no provinces - exit
	if (provinces.length==0) {
		clear_select(provinceSelect);
		disable_select(provinceSelect, "You're done"); //na
		if (citySelect!=null) {
			clear_select(citySelect);
			disable_select(citySelect, "You're done"); //na
		}
		if (areaSelect!=null) {
			clear_select(areaSelect);
			disable_select(areaSelect, "You're done"); //na
		}
		return true;
	}

	// clear provinces select
	enable_select(provinceSelect)
	clear_select(provinceSelect);

	var arrAllOfArray = "";
	if (editOrSearch == "search") {
		arrAllOfArray = [countryId, "All of " + countryName, makeRegionPathElement(countryId), "P", "P", 0];
	} else {
		arrAllOfArray = [countryId, "Please select...", "", "P", "P", 0];
	}
	return populate_select(provinceSelect, provinces, selectedOption, arrAllOfArray, editOrSearch);
}

function populate_city_select(citySelect, areaSelect, countryId, provinceId, provinceName, selectedOption, editOrSearch) {
	// populate cities select
	var cities = get_cities(countryId, provinceId);

	// if there are no cities - exit
	if (cities.length==0) {
		clear_select(citySelect);
		disable_select(citySelect, "You're done"); //na
		if (areaSelect!=null) {
			clear_select(areaSelect);
			disable_select(areaSelect, "You're done"); //na
		}
		return true;
	}

	// clear cities select
	enable_select(citySelect)
	clear_select(citySelect)

	var arrAllOfArray = "";
	if (editOrSearch == "search") {
		arrAllOfArray = [provinceId, "All of " + provinceName, makeRegionPathElement(countryId) + "-" + makeRegionPathElement(provinceId), "C", "C", 0];
	} else {
		arrAllOfArray = [provinceId, "Please select...", "", "C", "C", 0];
	}
	citySelect.disabled = false;
	return populate_select(citySelect, cities, selectedOption, arrAllOfArray, editOrSearch);
}

function populate_area_select(areaSelect, countryId, provinceId, cityId, cityName, selectedOption, editOrSearch) {
	// populate areas select
	var areas = get_areas(countryId, provinceId, cityId);

	// if there are no areas - exit
	if (areas.length==0) {
		clear_select(areaSelect);
		disable_select(areaSelect, "You're done"); //na
		return true;
	}

	// clear cities select
	enable_select(areaSelect)
	clear_select(areaSelect)

	var arrAllOfArray = "";
	if (editOrSearch == "search") {
		arrAllOfArray = [cityId, "All of " + cityName, makeRegionPathElement(countryId) + "-" + makeRegionPathElement(provinceId) + "-" + makeRegionPathElement(cityId), "A", "A", 0];
	} else {
		arrAllOfArray = [cityId, "Please select... ", "", "A", "A", 0];
	}
	areaSelect.disabled = false;
	return populate_select(areaSelect, areas, selectedOption, arrAllOfArray, editOrSearch);
}




// event handlers
function dd_country_onchange(countrySelect, provinceSelect, citySelect, areaSelect, editOrSearch) {
	if (citySelect!=null) {
		clear_select(citySelect);
		disable_select(citySelect, " "); //please_select_above
	}

	if (areaSelect!=null) {
		clear_select(areaSelect);
		disable_select(areaSelect, " "); //please_select_above
	}

	var countryId = Number(countrySelect.options[countrySelect.selectedIndex].value);
	populate_province_select(provinceSelect, citySelect, areaSelect, countryId, countrySelect.options[countrySelect.selectedIndex].text.trim(), null, (editOrSearch=="edit"?"edit":"search"));
}

function dd_province_onchange(countrySelect, provinceSelect, citySelect, areaSelect, editOrSearch) {
	if (citySelect!=null) {
		clear_select(citySelect);
		disable_select(citySelect, " "); //please_select_above
	}

	if (areaSelect!=null) {
		clear_select(areaSelect);
		disable_select(areaSelect, " "); //please_select_above
	}

	if (String(typeof(countrySelect))=="object" && countrySelect!=null) {
		var countryId = Number(countrySelect.options[countrySelect.selectedIndex].value);
	} else if (String(typeof(countrySelect))=="string") {
		var countryId = Number(countrySelect.split("|")[0]);
	}

	var provinceSelectText = provinceSelect.options[provinceSelect.selectedIndex].text.trim();

	if (provinceSelectText.substring(0, 6) != "All of" 
			&& provinceSelectText.substring(0, 13) != "Please select"
			&& provinceSelectText != "") {
		var provinceDDValue = provinceSelect.options[provinceSelect.selectedIndex].value;
		var provinceId = Number(provinceDDValue.substr(provinceDDValue.lastIndexOf("-")+1));

		populate_city_select(citySelect, areaSelect, countryId, provinceId, provinceSelect.options[provinceSelect.selectedIndex].text.trim(), null, (editOrSearch=="edit"?"edit":"search"))
	} else {
		clear_select(citySelect);
		disable_select(citySelect, " "); //please_select_above
		if (areaSelect!=null) {
			clear_select(areaSelect);
			disable_select(areaSelect, " "); //please_select_above
		}
	}

}

function dd_city_onchange(countrySelect, provinceSelect, citySelect, areaSelect, editOrSearch) {
	if (areaSelect!=null) {
		clear_select(areaSelect);
		disable_select(areaSelect, " "); //please_select_above
	}

	var countryId, provinceId
	if (String(typeof(countrySelect))=="object" && countrySelect!=null) {
		var countryDDValue = countrySelect.options[countrySelect.selectedIndex].value;
		countryId = Number(countryDDValue.substr(countryDDValue.lastIndexOf("-")+1));
	} else if (String(typeof(countrySelect))=="string") {
		countryId = Number(countrySelect.split("|")[0]);
	}
	if (String(typeof(provinceSelect))=="object" && provinceSelect!=null) {
		var provinceDDValue = provinceSelect.options[provinceSelect.selectedIndex].value;
		provinceId = Number(provinceDDValue.substr(provinceDDValue.lastIndexOf("-")+1));
	} else if (String(typeof(provinceSelect))=="string") {
		provinceId = Number(provinceSelect.split("|")[0]);
	}
	
	var citySelectText = citySelect.options[citySelect.selectedIndex].text.trim();
	if (citySelectText.substring(0, 6) != "All of" 
			&& citySelectText.substring(0, 13) != "Please select"
			&& citySelectText != "") {
		var cityDDValue = citySelect.options[citySelect.selectedIndex].value;
		var cityId = Number(cityDDValue.substr(cityDDValue.lastIndexOf("-")+1));

		populate_area_select(areaSelect, countryId, provinceId, cityId, citySelect.options[citySelect.selectedIndex].text.trim(), null, (editOrSearch=="edit"?"edit":"search"))

	} else {
		clear_select(areaSelect);
		disable_select(areaSelect, " "); //please_select_above
	}

}

// main function
function display_dropdowns(countrySelect, provinceSelect, citySelect, areaSelect, regionPathToSelect, editOrSearch) {

if (f && f.p2) { f.p2.value='entered display_dropdowns'; }

	var countryId = 0, provinceId = 0, cityId = 0, areaId = 0;
	var countryName = "", provinceName = "", cityName = "", areaName = "";

	if (String(regionPathToSelect).length>0) {
		var a = get_regions_by_regionpath(regionPathToSelect);

		countryId = a[0][0];		countryName = a[0][1];
		provinceId = a[1][0];		provinceName = a[1][1];
		cityId = a[2][0];			cityName = a[2][1];
		areaId = a[3][0];			areaName = a[3][1];
	} 
	if (countryId == 0 && String(typeof(countrySelect))=="string" && countrySelect!=null) {
		countryId = Number(countrySelect.split("|")[0]);
		countryName = countrySelect.split("|")[1];

	}

/*
alert("countrySelect: " + countrySelect + ", provinceSelect: " + provinceSelect + ", citySelect: " + citySelect + ", areaSelect: " + areaSelect);
alert("country: " + countryId + ": " + countryName + String.fromCharCode(13, 10)
		+ "province: " + provinceId + ": " + provinceName + String.fromCharCode(13, 10)
		+ "city: " + cityId + ": " + cityName + String.fromCharCode(13, 10)
		+ "area: " + areaId + ": " + areaName + String.fromCharCode(13, 10));
*/

if (f && f.p2) { f.p2.value="country: " + countryId + ": " + countryName + String.fromCharCode(13, 10)
		+ "province: " + provinceId + ": " + provinceName + String.fromCharCode(13, 10)
		+ "city: " + cityId + ": " + cityName + String.fromCharCode(13, 10)
		+ "area: " + areaId + ": " + areaName + String.fromCharCode(13, 10); }

	// if country populates and province select exists, or country select doesn't exist
	if (String(typeof(countrySelect))!="object" || countrySelect==null || (populate_country_select(countrySelect, provinceSelect, citySelect, areaSelect, regionPathToSelect, editOrSearch) && String(typeof(citySelect))=="object" && provinceSelect!=null)) {
if (f && f.p2) { f.p2.value='country populated'; }
		// if province populates with select and city select exists
		if (populate_province_select(provinceSelect, citySelect, areaSelect, countryId, countryName, (countryId==0?"":regionPathToSelect), editOrSearch) && String(typeof(citySelect))=="object" && citySelect!=null) {
if (f && f.p2) { f.p2.value='province populated'; }
			// if province_id is 0
			if (provinceId <= 0) {
				// do nothing, lower dd's are already dealt with
if (f && f.p2) { f.p2.value='provinceId: '+provinceId; }
			// if city_id is 0
			} else if (cityId <= 0) {
				// pop city without regionToSelect
				populate_city_select(citySelect, areaSelect, countryId, provinceId, provinceName, "", editOrSearch);

				// clear area
				if (String(typeof(areaSelect))=="object" && areaSelect!=null) {
					clear_select(areaSelect);
					areaSelect.options[0] = new Option(" "); //please_select_above
					areaSelect.disabled = true;
				}
if (f && f.p2) { f.p2.value='cityId: '+cityId; }
			// if city_id > 0	
			} else {
				// pop city with regionToSelect
				if (populate_city_select(citySelect, areaSelect, countryId, provinceId, provinceName, regionPathToSelect, editOrSearch) && String(typeof(areaSelect))=="object" && areaSelect!=null) {
					populate_area_select(areaSelect, countryId, provinceId, cityId, cityName, (areaId==0?"":regionPathToSelect), editOrSearch);				

				} else if (String(typeof(areaSelect))=="object" && areaSelect!=null) {
					if (editOrSearch=="search") {
						if (String(typeof(areaSelect))=="object" && areaSelect!=null) {
							clear_select(areaSelect);
							areaSelect.options[0] = new Option(" "); //please_select_above
							areaSelect.disabled = true;
						}
					} else {
						populate_area_select(areaSelect, countryId, provinceId, cityId, cityName, (areaId==0?"":regionPathToSelect), editOrSearch);
					}					
				}
if (f && f.p2) { f.p2.value='cityId (else): '+cityId; }
			}

		// else if city select exists
		} else if (String(typeof(citySelect))=="object" && citySelect!=null) {
if (f && f.p2) { f.p2.value='clear city and area'; }
			// city
			clear_select(citySelect);
			citySelect.options[0] = new Option(" "); //please_select_above
			citySelect.disabled = true;

			// area
			if (String(typeof(areaSelect))=="object" && areaSelect!=null) {
				clear_select(areaSelect);
				areaSelect.options[0] = new Option(" "); //please_select_above
				areaSelect.disabled = true;
			}

		}

	// else if province select exists
	} else if (String(typeof(provinceSelect))=="object" && provinceSelect!=null) {
if (f && f.p2) { f.p2.value='clear province, city and area'; }
		// province
		clear_select(provinceSelect);
		provinceSelect.options[0] = new Option(" "); //please_select_above
		provinceSelect.disabled = true;

		// city
		if (String(typeof(citySelect))=="object" && citySelect!=null) {
			clear_select(citySelect);
			citySelect.options[0] = new Option(" "); //please_select_above
			citySelect.disabled = true;

			// area
			if (String(typeof(areaSelect))=="object" && areaSelect!=null) {
				clear_select(areaSelect);
				areaSelect.options[0] = new Option(" "); //please_select_above
				areaSelect.disabled = true;
			}
		}
	}

if (f && f.p2) { f.p2.value='exiting display_dropdowns'; }

}
