var sPatronID = '';
var sServerHashSeed = '';
var sLoginStatus = '';
var sFamilyRegistration = '';
var sPrintCert = '';
var sReviewSetting = '';
var sAnonymousReviewsSetting = '';
var sLoggedOutMessage = '';
var EvancedFlag = 0;

if (document.layers) {n=1;ie=0;n6=0}
if (document.all) {n=0;ie=1;n6=0}
if (document.getElementById&&!document.all) {n=0;ie=0;n6=1}

window.onload=function()
{
	loadContent();
	loadVars();
	displayComponents(sLoginStatus);
}

window.onunload=function()
{
	if (sPatronID != '')
	{
		var str = ServerPath + "readerwidget.asp?command=logout&programid=" + ProgramID + "&evancedflag=" + EvancedFlag;
		rescriptHomePage(str);
		
		doFBLogout();
		
		if (sLoggedOutMessage != '')
			window.alert(sLoggedOutMessage);
		else
			window.alert("You have been logged out.");
	}
}

function checkForEnter(e)
{
	var evtobj = window.event ? event : e;
			
	if (evtobj.keyCode == 13)
	{
		doLogin();
	}
}

//hides/shows components depending on login status
function displayComponents(loginStatus)
{
	hideDivs();
	
	if (loginStatus == 'Logged In')
	{
		// turn on components when user is logged in
		if (eval("document.getElementById('spnLoggedIn')"))
			document.getElementById('spnLoggedIn').style.display = 'block';
		
		if (eval("document.getElementById('spnResetPassword')"))
			document.getElementById('spnResetPassword').style.display = 'none';
		if (eval("document.getElementById('divResetPassword')"))
			document.getElementById('divResetPassword').innerHTML = '';
		
		if (eval("document.getElementById('divPrizeMessage')")) {
			if (document.getElementById('divPrizeMessage').innerHTML != '') {
				document.getElementById('divPrizeMessage').style.display = 'block';
			}
			try
			{
				document.getElementById('prizescroll').start();
			}
			catch(e) {}
		}
		
		if (eval("document.getElementById('divCertificateMessage')")) {
			if (document.getElementById('divCertificateMessage').innerHTML != '') {
				document.getElementById('divCertificateMessage').style.display = 'block';
			}
		}
		
		if (eval("document.getElementById('divFamilyRegistration')")) {
			if (sFamilyRegistration == '1') {
				document.getElementById('divFamilyRegistration').style.display = 'block';
			}
		}
		
		if (eval("document.getElementById('spnLoggedInReviews')")) {
			if (sReviewSetting == '2') {
				document.getElementById('spnLoggedInReviews').style.display = 'block';
			}
			else {
				if (eval("document.getElementById('spnLoggedOutReviews')")) {
					document.getElementById('spnLoggedOutReviews').style.display = 'block';
				}
			}
		}
	}
	else if (loginStatus == 'Password Reset')
	{
		// turn on components when user's password is reset
		if (eval("document.getElementById('spnResetPassword')"))
			document.getElementById('spnResetPassword').style.display = 'block';
	}
	else
	{
		// turn on components when user is logged out
		if (eval("document.getElementById('spnLoggedOut')"))
			document.getElementById('spnLoggedOut').style.display = 'block';
		
		if (eval("document.getElementById('spnLoggedOutReviews')")) {
			document.getElementById('spnLoggedOutReviews').style.display = 'block';
		}
		
		if (eval("document.getElementById('spnLoggedInReviews')")) {
			if ((sReviewSetting == '1' || sReviewSetting == '2') && sAnonymousReviewsSetting == '1') {
				document.getElementById('spnLoggedInReviews').style.display = 'block';
				if (eval("document.getElementById('spnLoggedOutReviews')")) {
					document.getElementById('spnLoggedOutReviews').style.display = 'none';
				}
			}
		}
		
		// clear out login fields
		if (eval("document.getElementById('username')"))
			document.getElementById('username').value = '';
		if (eval("document.getElementById('libcardno')"))
			document.getElementById('libcardno').value = '';
		if (eval("document.getElementById('password')"))
			document.getElementById('password').value = '';
		if (eval("document.getElementById('pinnumber')"))
			document.getElementById('pinnumber').value = '';
	}
	setLoginFocus();
}

//logs in patron
function doLogin()
{
	var str1 = ''; var str2 = ''; var str3 = ''; var str4 = '';
	sServerHashSeed = document.getElementById('ServerHashSeed').value;
	
	if (eval("document.getElementById('username')"))
	{
		if (EvancedFlag == 0)
			var str1 = document.getElementById('username').value;
		else
			var str1 = getAscii(endecrypt(document.getElementById('username').value, hex_md5(sServerHashSeed)));
	}
	if (eval("document.getElementById('libcardno')"))
	{
		if (EvancedFlag == 0)
			var str2 = document.getElementById('libcardno').value;
		else
			var str2 = getAscii(endecrypt(document.getElementById('libcardno').value, hex_md5(sServerHashSeed)));
	}
	if (eval("document.getElementById('password')"))
	{
		if (EvancedFlag == 0)
			var str3 = document.getElementById('password').value;
		else
			var str3 = getAscii(endecrypt(document.getElementById('password').value, hex_md5(sServerHashSeed)));
	}
	if (eval("document.getElementById('pinnumber')"))
	{
		if (EvancedFlag == 0)
			var str4 = document.getElementById('pinnumber').value;
		else
			var str4 = getAscii(endecrypt(document.getElementById('pinnumber').value, hex_md5(sServerHashSeed)));
	}
	
	if (str1 != '')
		str1 = '&str1=' + str1;
	if (str2 != '')
		str2 = '&str2=' + str2;
	if (str3 != '')
		str3 = '&str3=' + str3;
	if (str4 != '')
		str4 = '&str4=' + str4;
	
	var str = ServerPath + "readerwidget.asp?command=login&programid=" + ProgramID + str1 + str2 + str3 + str4 + "&evancedflag=" + EvancedFlag;
	rescriptHomePage(str);
}

//log out patron
function doLogOut()
{
	var str = ServerPath + "readerwidget.asp?command=logout&programid=" + ProgramID;
	rescriptHomePage(str);
	
	//redo language stuff
	rescriptHomePage(arrScriptBlocks[1]);
	
	doFBLogout();
	
	displayComponents('Logged Out');
	
	if (sLoggedOutMessage != '')
	{
		window.alert(sLoggedOutMessage);
		setLoginFocus();
	}
}

//resets patron's password
function doResetPassword()
{
	var str1 = ''; var str2 = '';
	
	if (eval("document.getElementById('newpassword')"))
	{
		if (EvancedFlag == 0)
			var str1 = document.getElementById('newpassword').value;
		else
			var str1 = getAscii(endecrypt(document.getElementById('newpassword').value, hex_md5(sServerHashSeed)));
	}
	if (eval("document.getElementById('confirmnewpassword')"))
	{
		if (EvancedFlag == 0)
			var str2 = document.getElementById('confirmnewpassword').value;
		else
			var str2 = getAscii(endecrypt(document.getElementById('confirmnewpassword').value, hex_md5(sServerHashSeed)));
	}
	
	if (str1 != '')
		str1 = '&str1=' + str1;
	if (str2 != '')
		str2 = '&str2=' + str2;
	
	var str = ServerPath + "readerwidget.asp?command=resetpassword&programid=" + ProgramID + str1 + str2 + "&evancedflag=" + EvancedFlag;
	rescriptHomePage(str);
}

function getAscii(str)
{
	var chr = ''; var chrcode = 0; var codestr = ''; var codefinalstr = '';
	for (var x = 0; x < str.length; x++)
	{
		chr = str.substr(x,1);
		chrcode = chr.charCodeAt(0);
		codestr = chrcode.toString();
		if (codestr.length == 1)
			codestr = '00' + codestr;
		else if (codestr.length == 2)
			codestr = '0' + codestr;
		codefinalstr = codefinalstr + codestr; 
	}
	return codefinalstr;
}

//hides all dynamic divs
function hideDivs()
{
	if (eval("document.getElementById('spnLoggedIn')"))
		document.getElementById('spnLoggedIn').style.display = 'none';
	if (eval("document.getElementById('spnLoggedOut')"))
		document.getElementById('spnLoggedOut').style.display = 'none';
	if (eval("document.getElementById('divPrizeMessage')"))
		document.getElementById('divPrizeMessage').style.display = 'none';
	if (eval("document.getElementById('divFamilyRegistration')"))
		document.getElementById('divFamilyRegistration').style.display = 'none';
	if (eval("document.getElementById('divCertificateMessage')"))
		document.getElementById('divCertificateMessage').style.display = 'none';
	if (eval("document.getElementById('spnLoggedInReviews')"))
		document.getElementById('spnLoggedInReviews').style.display = 'none';
	if (eval("document.getElementById('spnLoggedOutReviews')"))
		document.getElementById('spnLoggedOutReviews').style.display = 'none';
	if (eval("document.getElementById('spnResetPassword')"))
		document.getElementById('spnResetPassword').style.display = 'none';
}

function JSONscriptRequest(fullUrl) {
	// REST request path
	this.fullUrl = fullUrl; 
	// Keep IE from caching requests
	this.noCacheIE = "&noCacheIE=" + (new Date()).getTime();
	// Get the DOM location to put the script tag
	this.headLoc = document.getElementsByTagName("head").item(0);
	// Generate a unique script tag id
	this.scriptId = "YJscriptId" + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
JSONscriptRequest.prototype.buildScriptTag = function () {
	// Create the script tag
	this.scriptObj = document.createElement("script");

	// Add script object attributes
	this.scriptObj.setAttribute("type", "text/javascript");
	this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
	this.scriptObj.setAttribute("id", this.scriptId);
}

// removeScriptTag method
JSONscriptRequest.prototype.removeScriptTag = function () {
	// Destroy the script tag
	this.headLoc.removeChild(this.scriptObj); 
}

// addScriptTag method
JSONscriptRequest.prototype.addScriptTag = function () {
	// Create the script tag
	this.headLoc.appendChild(this.scriptObj);
}

//refreshes content with language-specific variables
function loadContent()
{
	for (var i = 0; i < arrScriptBlocks.length; i++)
	{
		rescriptHomePage(arrScriptBlocks[i]);
	}
}

// load global vars
function loadVars()
{
	sPatronID = document.getElementById("PatronID").value;
	sServerHashSeed = document.getElementById("ServerHashSeed").value;	
	sLoginStatus = document.getElementById("LoginStatus").value;
	try {
		sFamilyRegistration = document.getElementById("FamilyRegistration").value;
	}
	catch(e) {}
	sPrintCert = document.getElementById("PrintCert").value;
	sReviewSetting = document.getElementById("ReviewSetting").value;
	try {
		sAnonymousReviewsSetting = document.getElementById("AnonymousReviewsSetting").value;
	}
	catch(e) {}
}

//refreshes content with language-specific variables
function refreshContent(langID)
{
	PageLangID = langID;
	
	for (var i = 1; i < arrScriptBlocks.length; i++)
	{
		rescriptHomePage(arrScriptBlocks[i] + "&pagelangid=" + PageLangID);
	}
}

//reloads/refreshes the page's content
function refreshPage()
{
	var str = ServerPath + "readerwidget.asp?command=refresh&programid=" + ProgramID;
	rescriptHomePage(str);
	checkFBMessage();
}

// write out in-line script to "refresh" home page
function rescriptHomePage(request)
{
	// Create a new script object
	aObj = new JSONscriptRequest(request);
	// Build the script tag
	aObj.buildScriptTag();
	// Execute (add) the script tag
	aObj.addScriptTag();
}

// sets the focus to the first login field
function setLoginFocus()
{
	var bSetFocus = false;
	
	try {
		if (eval("document.getElementById('username')"))
		{
			document.getElementById('username').focus();
			bSetFocus = true;
		}
		if (eval("document.getElementById('libcardno')") && !bSetFocus)
		{
			document.getElementById('libcardno').focus();
			bSetFocus = true;
		}
		if (eval("document.getElementById('password')") && !bSetFocus)
		{
			document.getElementById('password').focus();
			bSetFocus = true;
		}
	}
	catch(e) {}
}


// set the mouse cursor
function setMouseCursor(obj)
{
	if (ie)
		obj.style.cursor = "hand";
	else
		obj.style.cursor = "pointer";
}

// loads program selection page for adding family members
function showAddMember()
{
	doFBLogout();
	var hWin = window.open(ServerPath + "patronprogramsel.asp?Ttype=family&ParentProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&Widget=Y", "MemberReg", "resizable=yes,scrollbars=yes");
}

// loads submit review page
function showLog()
{
	if (NewWindow == "Y")
		var hWin = window.open(ServerPath + "patronlogadd.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&NewWindow=Y", "PatronLog", "resizable=yes,scrollbars=yes");
	else
		location.href = ServerPath + "patronlogadd.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&Widget=Y&ReturnPage=" + ReturnPage + ";"
}

// loads patron home page for managing family members
function showManageMember(patronID)
{
	doFBLogout();
	var hWin = window.open(ServerPath + "homepage.asp?mm=1&ProgramID=" + ProgramID + "&PageLangID=" + PageLangID, "ManageMember", "resizable=yes,scrollbars=yes");
}

// loads patron certificate
function showPatronCert(patronID)
{
	if (patronID != '')
		var hWin = window.open(ServerPath + "patroncertificate.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&Widget=Y", "PatronCert", "menubar=yes,resizable=yes,scrollbars=yes");
}

// loads patron reviews
function showPatronReviews()
{
	if (NewWindow == "Y")
		var hWin = window.open(ServerPath + "patronreviewslist.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&NewWindow=Y", "PatronReviews", "resizable=yes,scrollbars=yes");
	else
		location.href = ServerPath + "patronreviewslist.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&Widget=Y&ReturnPage=" + ReturnPage + ";"
}

// loads patron reading list
function showReadingList()
{
	if (NewWindow == "Y")
		var hWin = window.open(ServerPath + "readinglist.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&NewWindow=Y", "ReadingList", "menubar=yes,resizable=yes,scrollbars=yes");
	else
		location.href = ServerPath + "readinglist.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&Widget=Y&ReturnPage=" + ReturnPage + ";"
}

// loads registration page
function showRegistration()
{
	if (NewWindow == "Y")
		var hWin = window.open(ServerPath + "programregmaint.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&Mode=New&NewWindow=Y", "ProgramReg", "resizable=yes,scrollbars=yes");
	else
		location.href = ServerPath + "programregmaint.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&Mode=New&Widget=Y&home=" + ReturnPage + "&away=" + ReturnPage;
}

// loads registration info page
function showRegInfo()
{
	if (NewWindow == "Y")
		var hWin = window.open(ServerPath + "programregmaint.asp?ProgramID=" + ProgramID + "&PatronID=" + sPatronID + "&PageLangID=" + PageLangID + "&Mode=Edit&NewWindow=Y", "PatronReg", "resizable=yes,scrollbars=yes");
	else
		location.href = ServerPath + "programregmaint.asp?ProgramID=" + ProgramID + "&PatronID=" + sPatronID + "&PageLangID=" + PageLangID + "&Mode=Edit&Widget=Y&home=" + ReturnPage + "&away=" + ReturnPage;
}

// loads RSS selection page
function showRSSSelection()
{
	var hWin = window.open(ServerPath + "rssselection.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID, "RSSSelection", "resizable=yes,scrollbars=yes");
}

// loads submit review page
function showSubmitReview()
{
	var hWin = window.open(ServerPath + "submitreview.asp?ProgramID=" + ProgramID + "&PatronID=" + sPatronID + "&PageLangID=" + PageLangID, "SubmitReview", "resizable=yes,scrollbars=yes");
}

// loads reviews page
function showViewReviews(ProgramID, Random, Limit)
{
	var hWin = window.open(ServerPath + "viewreviews.asp?ProgramID=" + ProgramID + "&PageLangID=" + PageLangID + "&Clear=Y&Random=" + Random + "&Limit=" + Limit, "ViewReviews", "resizable=yes,scrollbars=yes");
}

/*                           md5 routines                                   */
/* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/

/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}

/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;

var a =  1732584193;
var b = -271733879;
var c = -1732584194;
var d =  271733878;

for(var i = 0; i < x.length; i += 16)
{
	var olda = a;
	var oldb = b;
	var oldc = c;
	var oldd = d;

	a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
	d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
	c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
	b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
	a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
	d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
	c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
	b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
	a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
	d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
	c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
	b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
	a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
	d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
	c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
	b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

	a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
	d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
	c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
	b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
	a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
	d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
	c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
	b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
	a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
	d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
	c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
	b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
	a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
	d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
	c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
	b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

	a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
	d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
	c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
	b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
	a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
	d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
	c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
	b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
	a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
	d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
	c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
	b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
	a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
	d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
	c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
	b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

	a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
	d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
	c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
	b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
	a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
	d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
	c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
	b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
	a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
	d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
	c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
	b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
	a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
	d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
	c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
	b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

	a = safe_add(a, olda);
	b = safe_add(b, oldb);
	c = safe_add(c, oldc);
	d = safe_add(d, oldd);
}
return Array(a, b, c, d);

}

/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}

/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}

/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
	bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}

/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
	str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
		hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
}
return str;
}
/*                           md5 routines                                   */

/*							 rc4 routines									*/
var sbox = new Array(255); 
var key = new Array(255);

function endecrypt(val, pwd)
{
	var i = 0;
	var j = 0;
	var cipher = '';

	rc4_init(pwd);

	for (var a = 1; a <= val.length; a++)
	{
		var itmp = 0;
		
		i = (i + 1) % 256;
		j = (j + sbox[i]) % 256;
		itmp = sbox[i];
		sbox[i] = sbox[j];
		sbox[j] = itmp;
		
		var k = sbox[(sbox[i] + sbox[j]) % 256];
		var ctmp = val.substr(a - 1, 1);
		
		itmp = ctmp.charCodeAt(0);
		
		var cipherby = itmp ^ k;
		
		cipher += String.fromCharCode(cipherby);
	}
	return cipher;
}

function rc4_init(pwd)
{
	var iLength = pwd.length;
	
	for (var a = 0; a <= 255; a++)
	{
		var ctmp = pwd.substr((a % iLength),1);
		
		key[a] = ctmp.charCodeAt(0);
		sbox[a] = a;
	}
	
	var x = 0;

	for (var b = 0; b <= 255; b++)
	{
		x = (x + sbox[b] + key[b]) % 256;
		
		var tempSwap = sbox[b];
		
		sbox[b] = sbox[x];
		sbox[x] = tempSwap;
	}
}

//facebook functions
function checkFBMessage() {
	var zXml={useActiveX:(typeof ActiveXObject!="undefined"),useDom:document.implementation&&document.implementation.createDocument,useXmlHttp:(typeof XMLHttpRequest!="undefined")};zXml.ARR_XMLHTTP_VERS=["MSXML2.XmlHttp.6.0","MSXML2.XmlHttp.3.0"];zXml.ARR_DOM_VERS=["MSXML2.DOMDocument.6.0","MSXML2.DOMDocument.3.0"];function zXmlHttp(){}zXmlHttp.createRequest=function(){if(zXml.useXmlHttp){return new XMLHttpRequest();}else if(zXml.useActiveX){if(!zXml.XMLHTTP_VER){for(var i=0;i<zXml.ARR_XMLHTTP_VERS.length;i++){try{new ActiveXObject(zXml.ARR_XMLHTTP_VERS[i]);zXml.XMLHTTP_VER=zXml.ARR_XMLHTTP_VERS[i];break;}catch(oError){;}}}if(zXml.XMLHTTP_VER){return new ActiveXObject(zXml.XMLHTTP_VER);}else{throw new Error("Could not create XML HTTP Request.");}}else{throw new Error("Your browser doesn't support an XML HTTP Request.");}};zXmlHttp.isSupported=function(){return zXml.useXmlHttp||zXml.useActiveX;};function zXmlDom(){}zXmlDom.createDocument=function(){if(zXml.useDom){var oXmlDom=document.implementation.createDocument("","",null);oXmlDom.parseError={valueOf:function(){return this.errorCode;},toString:function(){return this.errorCode.toString()}};oXmlDom.__initError__();oXmlDom.addEventListener("load",function(){this.__checkForErrors__();this.__changeReadyState__(4);},false);return oXmlDom;;}else if(zXml.useActiveX){if(!zXml.DOM_VER){for(var i=0;i<zXml.ARR_DOM_VERS.length;i++){try{new ActiveXObject(zXml.ARR_DOM_VERS[i]);zXml.DOM_VER=zXml.ARR_DOM_VERS[i];break;}catch(oError){;}}}if(zXml.DOM_VER){return new ActiveXObject(zXml.DOM_VER);}else{throw new Error("Could not create XML DOM document.");}}else{throw new Error("Your browser doesn't support an XML DOM document.");}};zXmlDom.isSupported=function(){return zXml.useDom||zXml.useActiveX;};var oMozDocument=null;if(typeof XMLDocument!="undefined"){oMozDocument=XMLDocument;}else if(typeof Document!="undefined"){oMozDocument=Document;}if(oMozDocument&&!window.opera){oMozDocument.prototype.readyState=0;oMozDocument.prototype.onreadystatechange=null;oMozDocument.prototype.__changeReadyState__=function(iReadyState){this.readyState=iReadyState;if(typeof this.onreadystatechange=="function"){this.onreadystatechange();}};oMozDocument.prototype.__initError__=function(){this.parseError.errorCode=0;this.parseError.filepos=-1;this.parseError.line=-1;this.parseError.linepos=-1;this.parseError.reason=null;this.parseError.srcText=null;this.parseError.url=null;};oMozDocument.prototype.__checkForErrors__=function(){if(this.documentElement.tagName=="parsererror"){var reError=/>([\s\S]*?)Location:([\s\S]*?)Line Number(\d+),Column(\d+):<sourcetext>([\s\S]*?)(?:\-*\^)/;reError.test(this.xml);this.parseError.errorCode=-999999;this.parseError.reason=RegExp.$1;this.parseError.url=RegExp.$2;this.parseError.line=parseInt(RegExp.$3);this.parseError.linepos=parseInt(RegExp.$4);this.parseError.srcText=RegExp.$5;}};oMozDocument.prototype.loadXML=function(sXml){this.__initError__();this.__changeReadyState__(1);var oParser=new DOMParser();var oXmlDom=oParser.parseFromString(sXml,"text/xml");while(this.firstChild){this.removeChild(this.firstChild);}for(var i=0;i<oXmlDom.childNodes.length;i++){var oNewNode=this.importNode(oXmlDom.childNodes[i],true);this.appendChild(oNewNode);}this.__checkForErrors__();this.__changeReadyState__(4);};oMozDocument.prototype.__load__=oMozDocument.prototype.load;oMozDocument.prototype.load=function(sURL){this.__initError__();this.__changeReadyState__(1);this.__load__(sURL);};Node.prototype.__defineGetter__("xml",function(){var oSerializer=new XMLSerializer();return oSerializer.serializeToString(this,"text/xml");});Node.prototype.__defineGetter__("text",function(){var sText="";for(var i=0;i<this.childNodes.length;i++){if(this.childNodes[i].hasChildNodes()){sText+=this.childNodes[i].text;}else{sText+=this.childNodes[i].nodeValue;}}return sText;});}function zXslt(){}zXslt.transformToText=function(oXml,oXslt){if(typeof XSLTProcessor!="undefined"){var oProcessor=new XSLTProcessor();oProcessor.importStylesheet(oXslt);var oResultDom=oProcessor.transformToDocument(oXml);var sResult=oResultDom.xml;if(sResult.indexOf("<transformiix:result")>-1){sResult=sResult.substring(sResult.indexOf(">")+1,sResult.lastIndexOf("<"));}return sResult;;}else if(zXml.useActiveX){return oXml.transformNode(oXslt);}else{throw new Error("No XSLT engine found.");}};function zXPath(){}zXPath.selectNodes=function(oRefNode,sXPath,oXmlNs){if(typeof XPathEvaluator!="undefined"){oXmlNs=oXmlNs||{};var nsResolver=function(sPrefix){return oXmlNs[sPrefix];};var oEvaluator=new XPathEvaluator();var oResult=oEvaluator.evaluate(sXPath,oRefNode,nsResolver,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);var aNodes=new Array;if(oResult!=null){var oElement=oResult.iterateNext();while(oElement){aNodes.push(oElement);oElement=oResult.iterateNext();}}return aNodes;}else if(zXml.useActiveX){if(oXmlNs){var sXmlNs="";for(var sProp in oXmlNs){sXmlNs+="xmlns:"+sProp+"=\'"+oXmlNs[sProp]+"\' ";}oRefNode.ownerDocument.setProperty("SelectionNamespaces",sXmlNs);};return oRefNode.selectNodes(sXPath);}else{throw new Error("No XPath engine found.");}};zXPath.selectSingleNode=function(oRefNode,sXPath,oXmlNs){if(typeof XPathEvaluator!="undefined"){;oXmlNs=oXmlNs||{};var nsResolver=function(sPrefix){return oXmlNs[sPrefix];};var oEvaluator=new XPathEvaluator();var oResult=oEvaluator.evaluate(sXPath,oRefNode,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null);if(oResult!=null){return oResult.singleNodeValue;}else{return null;};}else if(zXml.useActiveX){if(oXmlNs){var sXmlNs="";for(var sProp in oXmlNs){sXmlNs+="xmlns:\'"+sProp+"="+oXmlNs[sProp]+"\' ";}oRefNode.ownerDocument.setProperty("SelectionNamespaces",sXmlNs);};return oRefNode.selectSingleNode(sXPath);}else{throw new Error("No XPath engine found.");}};function zXMLSerializer(){}zXMLSerializer.prototype.serializeToString=function(oNode){var sXml="";switch(oNode.nodeType){case 1:sXml="<"+oNode.tagName;for(var i=0;i<oNode.attributes.length;i++){sXml+=" "+oNode.attributes[i].name+"=\""+oNode.attributes[i].value+"\"";}sXml+=">";for(var i=0;i<oNode.childNodes.length;i++){sXml+=this.serializeToString(oNode.childNodes[i]);}sXml+="</"+oNode.tagName+">";break;case 3:sXml=oNode.nodeValue;break;case 4:sXml="<![CDATA["+oNode.nodeValue+"]]>";break;case 7:sXml="<?"+oNode.nodevalue+"?>";break;case 8:sXml="<!--"+oNode.nodevalue+"-->";break;case 9:for(var i=0;i<oNode.childNodes.length;i++){sXml+=this.serializeToString(oNode.childNodes[i]);}break;};return sXml;};
	var UrlPath = ServerPath + "readerwidget.asp?command=fbinfo&programid=" + ProgramID + "&ts=<%=now%>";
	var oXmlHttp = zXmlHttp.createRequest();
	
	oXmlHttp.open("get", UrlPath, true);
	oXmlHttp.onreadystatechange = function () {
		if (oXmlHttp.readyState == 4) {
			loadFBMessage(oXmlHttp, zXmlDom);
		}
	};
	oXmlHttp.send(null);
}

function doFBForceLogout() {
	try {
		window.open(FBAppPath + "fbprocessor.asp?MessageType=LogOut", "fbmessage", "modal=yes, height=1, width=1, resizable=no, scrollbars=no, status=no");
	}
	catch (e) {}
}

function doFBLogout() {
	try {
		if (document.getElementById("FBEnabled").value == '1') {
			window.open(FBAppPath + "fbprocessor.asp?MessageType=LogOut", "fbmessage", "modal=yes, height=1, width=1, resizable=no, scrollbars=no, status=no");
		}
	}
	catch (e) {}
}

function loadFBMessage(oXmlHttp, zXmlDom) {
	var oXmlDom = zXmlDom.createDocument();
	oXmlDom.loadXML(oXmlHttp.responseText);

	var oRoot = oXmlDom.documentElement;
	var aRow = oRoot.getElementsByTagName("fbinfo");
	
	var objptr = aRow[0].firstChild;
	do
	{
		try
		{
			switch(objptr.tagName)
			{
			case "status":
				document.getElementById("FBStatus").value = objptr.text;
				break;
			case "messageid":
				document.getElementById("FBMessageID").value = objptr.text;
				break;
			case "messagetype":
				document.getElementById("FBMessageType").value = objptr.text;
				break;
			case "programid":
				document.getElementById("FBProgramID").value = objptr.text;
				break;
			default:
				break;
			}
		}
		catch(e) {}
	} while (objptr = objptr.nextSibling);
	
	try
	{
		if (eval(document.getElementById("FBStatus").value) == '1') {
			window.open(FBAppPath + "fbprocessor.asp?MessageType=" + document.getElementById("FBMessageType").value + "&ProgramID=" + document.getElementById("FBProgramID").value + "&MessageID=" + document.getElementById("FBMessageID").value + "&Display=99&Site=" + ServerPath, "fbmessage", "modal=yes, top=100, left=100, height=500, width=650, resizable=yes, status=yes, scrollbars=yes");
			document.getElementById("FBStatus").value = '0';
		}
	}
	catch(e) {}
}

