function clearArray(arr) 
{
	var newArr = new Array();
	var c = 0;
	for (i = 0; i < arr.length; i++) 
	{
		if (arr[i]) newArr[c++] = arr[i];
	}
	return newArr;
}


HkCountryState = function(formId, fieldCountry, fieldState, countries, states)
{
	this.version = 'polimaster';

	this.formId = formId;
	this.fieldCountry = fieldCountry;
	this.fieldState = fieldState;

	this.countries = clearArray(countries);
	this.states = clearArray(states);
}


HkCountryState.prototype.InitForm = function(currentCountryId, currentStateId)
{
	var form = jQuery('#'+this.formId).get(0);
	var c = form.elements[this.fieldCountry];
	var a = form.elements[this.fieldState];

	if (!c || !a) return;

	c.hkcs = this;

	c.onchange = function() 
	{
		var c = form.elements[this.hkcs.fieldCountry];
		var a = form.elements[this.hkcs.fieldState];
		var cid = 0;
		var aid = 0;
		cid = aid = -1;
		if (c.options.selectedIndex>-1) cid = c.options[c.options.selectedIndex].value;
		this.hkcs.AdjustStates(cid);
		if (a.options.selectedIndex != -1) 
		{
			aid = a.options[a.options.selectedIndex].value;
		}
	};

	//c.options[0] = new Option(' -- select --', 0); /*added by ahk, why*/

	for (i = 0; i < this.countries.length; i++) 
	{
		c.options[i] = new Option(this.countries[i].name, this.countries[i].id);
	}

	for (i = 0; i < c.options.length; i++) 
	{
		if(c.options[i].value == currentCountryId) 
		{
			c.options.selectedIndex = i;
			break;
		}
	}

	c.onchange();

	for (i = 0; i < a.options.length; i++) 
	{
		if (a.options[i].value == currentStateId) 
		{
			a.options.selectedIndex = i;
			break;
		}
	}
}


HkCountryState.prototype.AdjustStates = function(countryId)
{
	var form = jQuery('#'+this.formId).get(0);
	var a = form.elements[this.fieldState];

	a.options.length = 1;
	counter = 1;
	for (i = 0; i < this.states.length; i++) 
	{
		if(this.states[i].refId == countryId) 
		{
			a.options[counter] = new Option(this.states[i].name, this.states[i].id);
			counter++;
		}
	}

	if (a.options.length == 1)
	{
		a.options[0].text = 'N/A';
		a.options[0].value = -1;
		a.disabled = true;
	} 
	else 
	{
		a.options[0].text = '-- select --';
		a.options[0].value = 0;
		a.disabled = false;
	}
}