﻿dojo.require("dojo.io.script");

function StateProvinceControl(obj) {
	this.cList = dojo.byId(obj.countrySelect);
	this.sList = dojo.byId(obj.stateSelect);
	this.country = null;
	this.countries = {};
	this.waiting = false;
	dojo.connect(this.cList, 'onchange', dojo.hitch(this, this.update));
	dojo.connect(this.cList, 'onkeyup', dojo.hitch(this, this.update));
};

StateProvinceControl.prototype.update = function() {
	if(this.waiting === false) {
		this.country = this.cList[this.cList.selectedIndex].value;
				
		if(this.country != "") {
			if(typeof this.countries[this.country] == 'undefined') {		
					
				this.disableStates();
					
				this.countries[this.country] = null;
					
				this.waiting = true;
					
				dojo.xhrGet({
					url : TE_getHomePageURL() + "/_includes/scripts/TE_countrystate.asp?c=" + this.country,
					handleAs : 'json',
					preventCache : true,
					timeout : 10000,
					handle : dojo.hitch(this, function(response, ioArgs) {
						if(response.dojoType == 'timeout') {
							// timed out
						} else {
							this.countries[this.country] = response;
								
							if(this.count(this.countries[this.country]) !== 0) {
								this.addStates();
							}
								
							this.waiting = false;
						}
					})
				});
					
			} else {
				this.disableStates();
					
				if(this.count(this.countries[this.country]) !== 0) {
					this.addStates();
				}
			}
		} else {
			this.disableStates();
		}
	} else {
		setTimeout(dojo.hitch(this, this.update), 500);
	}
};
	
StateProvinceControl.prototype.count = function(obj) {
	var cnt = 0;
		
	for(var i in obj) {
		cnt++;
	}
		
	return cnt;
};

StateProvinceControl.prototype.addStates = function() {
	for(var i = this.sList.options.length - 1; i > 0; i--) {
		this.sList.removeChild(this.sList.options[i]);
	}
	
	for(var i = 1; i < this.countries[this.country].length; i++) {
		this.sList.appendChild(newNode('option', {'value':this.countries[this.country][i]['STATE_PROVINCE_CDE'], 'text':this.countries[this.country][i]['STATE_PROVINCE_NM']}));
	}
	
	this.sList.disabled = false;
};

StateProvinceControl.prototype.disableStates = function() {
	this.sList.selectedIndex = 0;
	this.sList.disabled = true;
};

function newNode(node, attr) {
	var x = document.createElement(node);
	for(var i in attr) {
		if(i == 'text') {
			x.appendChild(document.createTextNode(attr[i]));
		} else {
			x[i] = attr[i];
		}
	}
	return x;
}

dojo.addOnLoad(function() {
	// initialize the country/state select element behaviors
	new StateProvinceControl({
		'countrySelect' : 'cust_country',
		'stateSelect' : 'cust_state'
	});
	// append a hidden input field to the form
	// antennaRequestProcessor.asp looks for this field
	// helps prevent bots from spamming the form
	dojo.query('fieldset', dojo.byId('antennaRequestForm'))[0].appendChild(newNode('input', {'type':'hidden', 'name':'nobot', 'value':'not a bot'}));
});