I am trying to convert the Javascript from a Klip Desktop Widget to be usuable in a html page. Unfortunately, I am rather weak at javascript and wondered if anybody could help me?

Here is what the widget does:

1) Logins in to Windows Live and set's it cookie
2) uses the cookie to login into Xbox Live and returns a Friends Lists dataset

Below I have posted the code. The top part includes various klip application information in XML format followed by the Javascript. The klip application saves the following preferences Windows Live Username, Windows Live password, refresh rate interval, and sortby criteria. These would need to be saved in a cookie, instead of the klip application.

I am envisioning presenting the user with a form to login with their username/password. Once logged in, the page could just refresh at intervals based on a dropdown lists. The Friends lists should also sort with online friends at the top.

Everything I have tried has turned into a muddy mess. Can somebody please help me pull out the javascript?

Here is the original file. The routine at the bottom sets everything in motion. I have added my comments here & there. I know that most of the klip needs to be stripped, I just need help pulling out the javascript in a working fashion.

Thanks in advance.

Code:
<klip>
	<identity>
		<title>
			Xbox Live Friends Monitor
		</title>
		<version>
			3.60m
		</version>
		<uniqueid>
			hmxboxlivefriends
		</uniqueid>
		<lastmodified>
			2006.12.04:1100
		</lastmodified>
		<description>
			Monitors your Xbox Live friends and notifies you about their online status.
		</description>
		<keywords>
			xbox live friends online
		</keywords>
	</identity>
	<locations>
		<defaultlink>
			http://www.xbox.com
		</defaultlink>
		<contentsource>
			http://live.xbox.com/profile/Friends.aspx
		</contentsource>
		<icon>
			http://www.moeller-mingers.de/klips/xboxlivefriends.png
		</icon>
		<banner>
			http://www.moeller-mingers.de/klips/xbl_banner.png
		</banner>
		<kliplocation>
			http://www.moeller-mingers.de/klips/XboxLiveFriends.klip
		</kliplocation>
	</locations>
	<setup>
		<refresh>
			15
		</refresh>
		<country>
			us
		</country>
		<language>
			en
		</language>
		<codepage> 
			65001
		</codepage>
		<report>
			true
		</report>
	</setup>
	<messages>
		<nodata>
			No friends list found.
		</nodata>
		<loading>
			Collecting data...
		</loading>
	</messages>
	<style>
		tbody
		{
			type: item;
			definition: 'tile,tag,link,scoreIcon,gamerScore,presenceIcon,presence,description,gamercard,serial';
		}
		td[class="XbcGamerTile"] img::attribute(src)
		{
			type: image;
			name: 'tile';
			itemcol: 2;
			noterow: 0;
			notelabel: false;
			wrap: false;
			height: 2;
			valign: top;
		}
		td[class="XbcGamerTag"] a
		{
			type: text;
			name: 'tag';
			itemcol: 3;
			noterow: 0;
			notelabel: false;
			key: override;
			valign: middle;
		}
		td[class="XbcGamerTag"] a::attribute(href)
		{
			type: link;
			name: 'link';
		}
		td[class="XbcGamerScore"] img::attribute(src)
		{
			type: image;
			name: 'scoreIcon';
			base: 'http://live.xbox.com';
			itemcol: 4;
			noterow: 0;
			valign: middle;
		}
		td[class="XbcGamerScore"] strong
		{
			type: text;
			name: 'gamerScore';
			align: right;
			itemcol: 5;
			noterow: 0;
			valign: middle;
		}
<!--
		td[class="XbcGamerPresenceIcon"] img::attribute(src)
		{
			type: image;
			name: 'presenceIcon';
			base: 'http://live.xbox.com';
			itemcol: 1;
			noterow: 0;
			notelabel: false;
			wrap: false;
			height: 2;
			valign: middle;
		}
-->
		td[class="XbcGamerPresence"] h4
		{
			type: text;
			name: 'presence';
			itemcol: 0;
			noterow: 4;
			notelabel: false;
			wrap: false;
			valign: middle;
		}
		td[class="XbcGamerDescription"] p
		{
			type: text;
			name: 'description';
			itemcol: 0;
			noterow: 5;
			notelabel: false;
		}
		presenceIcon
		{
			type: image;
			itemcol: 1;
			noterow: 0;
			notelabel: false;
			wrap: false;
			height: 2;
			valign: middle;
		}
		gamercard
		{
			type: image;
			itemcol: 0;
			noterow: 2;
			notelabel: false;
			wrap: false;
		}
		serial
		{
			type: text;
			itemcol: 0;
			noterow: 0;
		}
		p[class="XbcFloatLeft"]
		{
			type: scratch;
			name: 'summary';
			content: cdata;
		}
	</style>
   <klipscript><![CDATA[

// ------------------------------
// Preferences Setup
// ------------------------------

var int_val_arr = new Array("1","5","15","30","60","120","240","360","720","1440");
var int_str_arr = new Array("1 minute","5 minutes","15 minutes","30 minutes","1 hour","2 hours","4 hours","6 hours","12 hours","once a day");

var cUsername, cPassword, c_interval, c_sortby;
var showAlerts = false;

var onlineCount = 0;

var tracing = false;

function t(message1, message2)
{
	if (tracing)
	{
		trace(message1 + "\r\n");
		if (message2 && message2.length)
		{
			trace(message2 + "\r\n");
		}
	}
}

function setRefreshrate(rr_str)
{
	Prefs.refreshrate = rr_str - 0;
}

function onLoad()
{
	if (KlipFolio.build < 5840)
	{
		alert("Xbox Live Friends Monitor:\r\n\r\nThis Klip requires KlipFolio Version 3.0 or newer!\r\n");
		return false;
	}
   
	var tab = Setup.addTab('Windows Live Account');

	tab.addText("Username (Email address):");
	cUsername = tab.addTextField();
	
	tab.addText("Password:");
	cPassword = tab.addTextField("", true);
	
	tab.addText("Refresh:");
	c_interval = tab.addComboBox();
	c_interval.onChange = changeInterval;
	
	tab.addText("Sort by:");
	c_sortby = tab.addComboBox("Name", "Score");
	c_sortby.onChange = changeSortOrder;

	Setup.onClose = closeSetup;
	
	loadPrefs();
	initIntervals();
	Items.autoremove = false;
	
	result = true;
}

function initIntervals()
{
	for (var i = 0; i < int_str_arr.length; i++)
	{
		c_interval.addItem(int_str_arr[i]);
		if (Prefs.refreshrate == int_val_arr[i])
		{
			c_interval.selected = i;
		}
	}
}

function changeInterval()
{
	setRefreshrate(int_val_arr[c_interval.selected]);
}

function changeSortOrder()
{
	Items.sort(sortFriends);
}

function loadPrefs()
{
	cUsername.value = Prefs.getPref("username");
	cPassword.value = Klip.ungarble(Prefs.getPref("password"));
	c_sortby.selected = parseInt(Prefs.getPref("sortOrder"));
	setRefreshrate(Prefs.getPref("userInterval"));
}

function savePrefs()
{
	Prefs.setPref("username", cUsername.value);
	Prefs.setPref("password", Klip.garble(cPassword.value));
	Prefs.setPref("userInterval", int_val_arr[c_interval.selected]);
	Prefs.setPref("sortOrder", c_sortby.selected);
	prefsValid()
}

function prefsValid()
{
	if (!cUsername || !cPassword) return false;
	if ((cUsername.value.length == 0) || (cPassword.value.length == 0))
	{
		Prefs.nodata = "You have to set your Windows Live username and password in the Klip setup dialog.\r\n" +
		               "If you don't have such an account, yet, just create one on www.xbox.com.\r\n" +
		               "You also have to link your Gamertag to you Windows Live account on www.xbox.com.";
		return false;
	}
	else
		Prefs.nodata = "No friends list found.";
		return true;
}
   
function closeSetup()
{
	savePrefs();
}

// ------------------------------
// Utility Methods
// ------------------------------

function addHeader(request, header)
{
	if (!request.headers)
		request.headers = header;
	else
		request.headers += "\n" + header;
}

function getURI(url, referer, cookie, header, preventredirect)
{
	var httpRequest = Engines.HTTP.newRequest(url);
	if (referer) httpRequest.referer = referer;
	if (cookie) httpRequest.cookie = cookie;
	if (header) addHeader(httpRequest, header);
	httpRequest.autoredirect = (!preventredirect);

 	//trace("--- Sending request ---\r\n");
	//trace("   URL: " + httpRequest.url + "\r\n");
	//trace("   Method: " + httpRequest.method + "\r\n");
	//trace("   Referer: " + httpRequest.referer + "\r\n");
	//trace("   Cookie: " + httpRequest.cookie + "\r\n");
	//trace("   PostData: " + httpRequest.postdata + "\r\n");
	//trace("   Headers: " + httpRequest.headers + "\r\n");
	//trace("   Redirect: " + httpRequest.autoredirect + "\r\n");
	//trace("--- Sending request ---\r\n");
	
	Engines.HTTP.clear304cache();
	if (httpRequest.send())
	{
		//trace("RESULT: " + httpRequest.response.status + "\r\n");
		return httpRequest.response;
	}
	else
	{
		if (showAlerts)
		alert("Xbox Live Friends Monitor:\r\n\r\nERROR: request for \"" + httpRequest.url + "\" failed [" + httpRequest.response.status + "]!\r\n");
		return null;
	}
}

function getMatch(data, re, index)
{
	var match = data.match(re);
	if (match && !index && (match.length > 0))
	{
		return match;
	}
	else if (match && (index >= 0) && (index < match.length))
	{
		return match[index];
	}
	else
	{
		if (showAlerts)
		alert("Xbox Live Friends Monitor:\r\n\r\nERROR: match not found for /" + re.source + "/!\r\n");
		return null;
	}
}

function encodeUrl(url)
{
	var result = url;
	result = result.replace(/\$/g, "%24");
	result = result.replace(/\&/g, "%26");
	result = result.replace(/\+/g, "%2B");
	result = result.replace(/\,/g, "%2C");
	result = result.replace(/\//g, "%2F");
	result = result.replace(/\:/g, "%3A");
	result = result.replace(/\;/g, "%3B");
	result = result.replace(/\=/g, "%3D");
	result = result.replace(/\?/g, "%3F");
	result = result.replace(/\@/g, "%40");
	return result;
}

// ------------------------------
// Login Procedure
// ------------------------------

function login(user, password)
{
	//
	// Step 1 - Send a request to Xbox Live
	//
	// Klip.progressmessage = "Connecting to Windows Live Service...";

	var req = Engines.HTTP.newRequest (Prefs.contentsource);
	if (!req.send ()) 
	{ 
		t("Error - could not connect");
		// Klip.progressmessage = "Error - could not connect";
		return false; 
	}

	//
	// Step 2 - Follow the trail of redirects to the Windows Live server
	// The redirects lead to http://login.live.com/
	// Make a POST request to log in
	//

	req.referer = req.response.url;
	req.method = "POST";
	req.autoredirect = false;
	req.cookie = req.response.cookies.replace (/version=1/, "").replace(/ +; /g,"");

	var now = new Date ();
	var now_time = now.getTime();
	req.cookie += "; CkTst" + "=G" + now_time;

	var login_re = new RegExp('action="(.*?)"[^]*?name="PPSX"[^]*?value="(.*?)"[^]*?name="PPFT"[^]*?value="(.*?)"');
	var login_match = login_re.exec(req.response.data);
	
	// Construct the POST data to be used in the login request
	req.url = login_match[1];
	req.postdata = "PPSX=" + login_match[2] + "&PwdPad=";
	var pad_value = "IfYouAreReadingThisYouHaveTooMuchFreeTime";
	req.postdata += pad_value.substring (0, pad_value.length - password.length);
	req.postdata += "&login=" + escape(user).replace(/@/g, '%40') + "&passwd=" + password + "&LoginOptions=2&PPFT=" + login_match[3];

	// Send the login request	
	if (!req.send()) 
	{
		t("Error - could not authenticate");
		// Klip.progressmessage = "Error - could not authenticate";
		return false;
	}
	
	//	
	// Step 3 - Follow the redirects from the login request
	//

	// Get the next URL from the response to the POST above
	var postback_re = new RegExp('action="(.*?)"[^]*?<input[^]*?\\s+name="(.*?)"[^]*?\\s+value="(.*?)"');
	var postback_match = postback_re.exec(req.response.data);

	if(!postback_match)
	{
		t("Error - incorrect username or password");
		// Klip.progressmessage = "Error - incorrect username or password";
		return false;
	}
	
	var postbackReq = Engines.HTTP.newRequest(postback_match[1]);
	postbackReq.method = "POST";
	postbackReq.autoredirect = false;
	postbackReq.referer = req.url;
	postbackReq.postdata = postback_match[2] + "=" + encodeUrl(postback_match[3]);
	if (!postbackReq.send())
	{
		t("ERROR - could not send postback request");
		Klip.progressmessage = "ERROR - could not connect";
		return false;
	}
	
	// Klip.progressmessage = "Login complete";
	
	return postbackReq.response.cookies;
}

// ------------------------------
// onRefresh()
// ------------------------------

function sortFriends(item1, item2)
{
	var off1 = /Offline/.test(item1.getData("presence"));
	var off2 = /Offline/.test(item2.getData("presence"));

	if (off1 == off2)
	{
		switch (c_sortby.selected)
		{
			case 0:
				var name1 = item1.getData("tag").toLowerCase();
				var name2 = item2.getData("tag").toLowerCase();
				if (name1 == name2)
					return 0;
				else if (name1 > name2)
					return 1;
				else
					return -1;
				break;
			case 1:
				var score1 = parseInt(item1.getData("gamerScore"));
				var score2 = parseInt(item2.getData("gamerScore"));
				if (score1 == score2)
					return 0;
				else if (score1 > score2)
					return -1;
				else
					return 1;
				break;
		}
	}
	else if (off1 > off2)
		return 1;
	else 
		return -1;
}

function formatDescription(desc)
{
	desc = desc.replace(/<br \/><\/p>/, "");
	desc = Klip.stripTags(desc.replace(/<br \/>/, " - "));
	return desc;
}

function checkItem(item)
{
	var presence;
	var isOnline;
	
	presence = item.getData("presence");
	isOnline = (presence == "Online");
	item.setData("gamercard", "http://card.mygamercard.net/" + item.getData("tag") + ".jpg" + "?" + item.getData("serial"));
	item.setData("presenceIcon", "http://www.moeller-mingers.de/klips/xbl_" + (isOnline?"online":"offline")+".png");
	if (isOnline) 
	{
		onlineCount++;
	}
	item.candelete = false;
	item.canvisit = false;
	return true;
}

function updateItem(current_item, parameters)
{
	current_item.alerting = (current_item.alerting || (current_item.getData("presence") != parameters.getData("presence")));
	parameters.setData("serial", current_item.getData("serial"));
	if (parameters.getData("presence") != "Offline")
	{
		var newSerial = parseInt(parameters.getData("serial"));
		newSerial++;
		parameters.setData("serial", ""+newSerial);
	}
	return checkItem(parameters);
}

function createItem(new_item)
{
	new_item.alerting = (new_item.getData("presence") != "Offline");
	new_item.setData("serial", "0");
	return checkItem(new_item);
}

function getSummary()
{
	var summary = Engines.KlipFood.getScratch("summary");
	summary = summary.replace(/<br [^>]*?>/, "\r\n");
	summary = Klip.stripTags(summary);
//	trace("Summary: " + summary + "\r\n");
	return summary;
}

function fetchFile(URL)
{
	var fn;
	var file;
	var data;
	
	fn = URL.match(/^file:\/*([^]*?)$/)[1].replace(/\//g, "\\");
	file = Engines.File.open(fn);
	data = file.read(file.size);
	return data;
}

function onRefresh()
{
	var success = false;
	var cookie;
	var contentsource="http://live.xbox.com/profile/Friends.aspx";

	// Call Routine to verify our prefences Username;Password;Refresh Interval;Sortby
	//if (!prefsValid())
	//	return false;
	
	// Call Routine to Login to Windows Live and return it's cookie
	// Xbox Live cookie must be set before we can retrieve our Friends Data
	cookie = login(cUsername.value, cPassword.value);
	
	if (cookie)
	{
		// Update application status bar
		// Klip.progressmessage = "Loading data...";
		
		// Call Routine to retrieve Friends List Data from Xbox Live Account
		var httpResponse = getURI(contentsource, null, cookie);
		if (httpResponse)
		{
			Items.purge(True);
			onlineCount = 0;
			Engines.KlipFood.onUpdate = updateItem;
			Engines.KlipFood.onCreate = createItem;
			success = Engines.KlipFood.process(httpResponse.data);
			Items.sort(sortFriends);
			Items.status = "" + onlineCount;
			Items.statusAlt = getSummary();
		}
	}
	return success;
}

]]></klipscript>
</klip>