﻿var updateDir = "http://widget.tallrice.com/hkforecast/version.txt";

function setWidgetDetails() {
	checkForUpdate();
	if(window.widget) {
	document.getElementById("WIDGETNAME").innerHTML = getKeyValue("Info.plist", "CFBundleDisplayName");
	document.getElementById("VERSION").innerHTML = 'v.' + getKeyValue("Info.plist", "CFBundleShortVersionString");
	document.getElementById("DEVELOPER").innerHTML = "t a l l r i c e";
	}
}

function checkForUpdate() {
//alert('checking update');
	var req = new XMLHttpRequest(); 
	req.onload = function(e) {compareVersion(e,req);};
	if (window.widget) req.setRequestHeader("Cache-Control", "no-cache");
	req.open("GET", updateDir, true); 
	req.send(null); 
}

function compareVersion(e, xml_request) {
	if (xml_request.responseText) {	
		if(window.widget) {
			if (parseFloat(xml_request.responseText) > parseFloat(getKeyValue("Info.plist", "CFBundleShortVersionString"))) {
				document.getElementById("DEVELOPER").innerHTML = 't a l l r i c e - v.' + xml_request.responseText + ' - Now Available ';
			}
		}
	}
}

function openURL(thisurl) {
	if(window.widget) { 
		widget.openURL(thisurl);
	} else {
		window.open(thisurl);
	}
}

function getKeyValue(plist, key) {
	var xml_http = new XMLHttpRequest();
	xml_http.open("GET", plist, false);
	xml_http.send(null); 
	var xml = xml_http.responseXML;
	var key_value = null;
	var nodes = xml.getElementsByTagName("dict")[0].childNodes; 
	for (var i=0; i < nodes.length; i++) {
		if (nodes[i].nodeType == 1 && nodes[i].tagName.toLowerCase()
		== "key" && nodes[i].firstChild.data == key) {
			if (nodes[i+2].tagName.toLowerCase() != "array") {
					key_value = nodes[i+2].firstChild.data;
			} else {
				key_value = new Array();
				var ar_nodes = nodes[i+2].childNodes;
				for (var j=0; j < ar_nodes.length; j++) {
					if (ar_nodes[j].nodeType == 1)
					key_value.push(ar_nodes[j].firstChild.data);
				}
			} 
			break;
		}
	} 
	return key_value;
} 

function addListEntry(id, value) {
	objList = document.getElementById(id);
	objListElement = document.createElement('li');
	objTextNode = document.createTextNode(value);
	objListElement.appendChild(objTextNode);
	objList.appendChild(objListElement);
}

function expandContractWidget(id, value, w, h, status) {
	if(window.widget) {
		window.resizeTo(w, h);
	}
	document.getElementById(id).style.display = value;
}

function ucfirst( str ) {
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1, str.length-1);
}

