﻿var provinceXml;

// 清空下拉菜单
function DropSelectOption(obj) {
	for (var i=obj.options.length-1; i>=0; i--) {obj.options[i].parentNode.removeChild(obj.options[i]);}
}

function LoadProvince(place) {
	var lp = new RequestAdapter();
	lp.handleXML = function(xml) {
		provinceXml = xml;
		TraversalProvince();
		if (place != null) {
			InitProvince(place);
		}
	}
	var req = new Request(lp);
	req.doGet('/Resource/Province.xml', false);
}

function InitProvince(place) {
	var node = document.getElementById('province');
	for (var i=0;i<node.options.length;i++) {
		var option = node.options[i];
		if (place.indexOf(option.text) >= 0) {
			option.selected = true;
			var city = node.nextSibling;
			while(city.nodeName != 'SELECT') {city = city.nextSibling;}
			BindCitySelect(city, option.value);
			InitCity(place);
			break;
		}
	}
}

function InitCity(place) {
	var node = document.getElementById('city');
	for (var i=0;i<node.options.length;i++) {
		var option = node.options[i];
		if (place.indexOf(option.text) >= 0) {
			option.selected = true;
			break;
		}
	}
}

function TraversalProvince() {
	var nodes = document.getElementsByTagName('select');
	var xpath = '//resource/node';
	for (var i=0;i<nodes.length;i++) {
		if (nodes[i].name == 'province') {
			BindProvinceSelect(nodes[i]);
		}
	}
}

function BindProvinceSelect(select) {
	DropSelectOption(select);
	var xpath = '//resource/node';
	var nodes = provinceXml.selectNodes(xpath);
	select.options.add(new Option('省　份', '0'));
	for (var i=0;i<nodes.length;i++) {
		select.options.add(new Option(nodes[i].getAttribute('name'), nodes[i].getAttribute('id')));
	}
}

function BindCitySelect(select, nodeid) {
	DropSelectOption(select);
	var xpath = '//node[@id="'+nodeid+'"]/node';
	var nodes = provinceXml.selectNodes(xpath);
	select.options.add(new Option('城　市', '0'));
	for (var i=0;i<nodes.length;i++) {
		select.options.add(new Option(nodes[i].getAttribute('name'), nodes[i].getAttribute('id')));
	}
}

function ProvinceChange(select) {
	var province = select;
	var city = province.nextSibling;
	while(city.nodeName != 'SELECT') {city = city.nextSibling;}
	var hidden = city.nextSibling;
	while(hidden.nodeName != 'INPUT') {hidden = hidden.nextSibling;}

	hidden.value = province.options[province.selectedIndex].text;
	BindCitySelect(city, province.value);
}

function CityChange(select) {
	var city = select;
	var province = city.previousSibling;
	while(province.nodeName != 'SELECT') {province = province.previousSibling;}
	var hidden = city.nextSibling;
	while(hidden.nodeName != 'INPUT') {hidden = hidden.nextSibling;}

	hidden.value = province.options[province.selectedIndex].text + ' ' + city.options[city.selectedIndex].text;
}

