var currentLocation;

function init() {	
	unit[0].checked=true;
	System.Gadget.onSettingsClosing=SettingsClosing;
	var currentSetting=System.Gadget.Settings.read("units");
	if(currentSetting=="metric") {
		unit[1].checked=true;	
	}
	currentLocation=System.Gadget.Settings.read("Location");
	if (currentLocation!="")
		envVar.innerText=currentLocation;
}
function SettingsClosing(event) {
	if (event.closeAction==event.Action.commit) {
		variableName="english";
		if(unit[1].checked) {
			variableName="metric";		
		}
		System.Gadget.Settings.write("units", variableName);
		System.Gadget.Settings.write("Location", currentLocation);
	}
	event.cancel=false;
}

//load the xml data from the website
function loadData() {
	req = new ActiveXObject("Microsoft.XMLHTTP");
	if (req) {
		req.open("GET","http://vwidget.accuweather.com/widget/vista4/locate_city.asp?location=" + envVar.value,true);
		req.onreadystatechange=processData;
		req.send();
	}
}

//process data when its received
function processData() {
	if (req.readyState==4) {
		if (req.status==200) {
			parseData(req.responseXML.documentElement);
		}
	}
}

//parse the xml data and populate the table with data.
function parseData(xmlData) {
	tempNode=xmlData.getElementsByTagName("./citylist").item(0);
	tempNodes=tempNode.getElementsByTagName('location');
	deleteRows("LocationTable");
	for (count=0;count<tempNodes.length;count++) {
		cityNode=tempNodes[count];
		tempString="<a class=\"link\" href=\"#\" onClick=\"selectLocation('" + cityNode.getAttribute("location") + "'); return false;\">+</a>&nbsp;&nbsp;";
		tempString1="<a class=\"link\" href=\"#\" onClick=\"selectLocation('" + cityNode.getAttribute("location") + "'); return false;\">" + cityNode.getAttribute("city") + ", " + cityNode.getAttribute("state") + "</a>";
		addRow("LocationTable",tempString,tempString1);
	}
	if (tempNodes.length==0) {
		addRow("LocationTable","Location not found","");
	}
	with (scrollTableContainer.style) {
		display="block";
	}
}

//add a row programatically to a table
function addRow(id,value,text){
	var tbody=document.getElementById(id).getElementsByTagName("tbody")[0];
	var row=document.createElement("TR");
	var cell1=document.createElement("TD");
	cell1.innerHTML=value;
	cell1.style.whiteSpace="nowrap";
	var cell2=document.createElement("TD");
	cell2.innerHTML=text;
	cell2.style.whiteSpace="nowrap";
	row.appendChild(cell1);
	row.appendChild(cell2);
	tbody.appendChild(row);
}

//delete a row from a table
function deleteRows(id) {  
	var tbl=document.getElementById(id);
	totalRows=tbl.rows.length;
	for (count=0;count<totalRows;count++) {
		document.getElementById(id).deleteRow(0);
	}
}

//if a location is selected save it to the settings and close the flyout
function selectLocation(locationCode) {
	currentLocation=locationCode;	
	envVar.innerText=currentLocation;
	updated.innerText="Location Set";
}