function terrierLoadPage()
	{
	//	Load up the HTML fragments for each item necessary

	$('.HTMLFragment').each(function(i){

		var fragmentID = $(this).attr('id');

		if (fragmentID.length > 0)
			{
			var curObj = $(this);

			getHTMLFragment(curObj, fragmentID);
							
			//	First, bind double-click to this element, for editing the html
			curObj.dblclick(function () { 
				setHTMLFragment(curObj, fragmentID); 
				});

			}
//			else
//				alert('fragment id attribute is invalid');
		});

//	var theLoggedInUser = getCookie('reView_Login');
//	if (isDefined(theLoggedInUser) && theLoggedInUser.length)
//		$('#footer p span a').html("Logged in as " + theLoggedInUser);
	}
function terrierLogin()
	{
	try {		
		//	Display dialog asking for subscriber info
			
		var ourDiv = 'loginDialog';
		if ($('#' + ourDiv).length == 0)
			$('#container').append("<div id=" + ourDiv + "></div>");

		var theDialogHTML = "<table width=480 cellspacing=0 cellpadding=2>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=50% class='alignRight'>User Name : </td>";
		theDialogHTML += "<td width=50%><input type='text' id='userEmail' value=''/></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=50% class='alignRight'>Password : </td>";
		theDialogHTML += "<td width=50%><input type='password' id='userPassword' value=''/></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=100% colspan=2></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=100% colspan=2><span id=helpMsg></span></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "</table>";
		$('#' + ourDiv).html(theDialogHTML);
	
		$('#' + ourDiv).dialog({
						autoOpen: false,
						modal: true,
						minHeight: 200,
						minWidth: 520,
						width: 520,
						position: ['center','top'],
						title: 'Login',
						resizable: true,
						open: function(Event, ui) {
							var previouslyLoggedInSubscriber = getCookie($('#theDomain').val() + '_Login');
							if (isDefined(previouslyLoggedInSubscriber) && 
								previouslyLoggedInSubscriber.length)
								{			
								$('#userEmail').val(previouslyLoggedInSubscriber);
								$('#userPassword').focus();
								}	

							$("#userPassword").bind("keydown", function(e){
								if (e.keyCode == 13)
									{
									var theDlgObj = $('#' + ourDiv);
									theDlgObj.dialog("option", "buttons")['Submit'].apply(theDlgObj);
									}
								});	
						
							} ,
						buttons: {
							"Submit": function() {

							$.ajax({
									type: "POST",
									url: "/code/php/_terrierLogin.php",
									data:  "user=" + $('#userEmail').val()  + "&pass=" + $('#userPassword').val() + "&site=" + "",
									dataType: "xml",
									success: function(xml) {
										var isAuthenticated = $(xml).find('authenticated').text();
										var theError = $(xml).find('error').text();
										if (isAuthenticated == 'Yes')
											{
											showHelpMsg('Welcome!', 'messageboxok', ourDiv);

											var domainName = $(xml).find('domain').text();
											var userName = $(xml).find('username').text();
											setCookie(domainName + '_Login', $('#userEmail').val());
											$('#theLoggedInName').val(userName);
											$('#theDomain').val(domainName);

											displayLoggedIn($('#userEmail').val());												
											}
										else
											showHelpMsg('Unable to login: ' + theError, 'messageboxerror');
										}
								});
							},
							"Cancel": function() { 
								$('#' + ourDiv).html("");
								$(this).dialog("close");
								$(this).remove();
							} 
						}
					});
						
		$('#' + ourDiv).dialog('open');
		}
	catch (e) {
		showException(e, "terrierLogin(): ");	
		}			
	}
function terrierLogout()
	{
	if (confirm("Are you sure you want to logout?"))
		{
//		deleteCookie('reView_Subscriber');

		$.ajax({
			type: "GET",
			url: "/code/php/_terrierLogout.php",
			data:  "brokercode=" + $('#theBroker').val() + "&user=" + getCookie($('#theDomain').val() + '_Login'),
			dataType: "xml",
			success: function(xml) {
				var theError = $(xml).find('error').text();
				//	Can't fail

				//	I think I need to reload the page to get the new PHP _Session vars

				window.location.reload(true);
												
//				setupSubscriberButtons($('#theBroker').val());
				}
		});
		
		}
	}
function terrierLoginSetup(LoginLabel)
	{
	try {					
		var ourDiv = 'LoginLabel';
		if ($('#' + ourDiv).length == 0)
			$('#hiddenFldsDiv').append("<div id=" + ourDiv + ">" + LoginLabel + "</div>");
		}
	catch (e) {
		showException(e, "terrierLoginSetup(): ");	
		}
	}	
function displayLoggedIn(loginName)
	{
	var loginMsg = "<span id=user_name_info class='floatRight'>You are logged in as&nbsp;<a id='terrierLoggedIn' href='#' class='floatRight' title='LoggedIn'><span class='bold'>" + loginName + "</span></a></span>";
	var logoutMsg = "<a id='terrierLogout' href='#' class='floatRight marginLeft14' title='Logout'><span>Logout</span></a>";
																
	$(".divLogin").each(function (i) {
		$(this).html(logoutMsg + loginMsg).css("font-size","10px");
	});
	
	$("#user_name_info").bind("click", function(){
		displayUserSettings();
		});
									
	$("#terrierLogout").bind("click", function(){
		terrierLogout();
		});
		
	$('.displayIfNotLoggedIn').hide(); 
	}
function displayLoggedOut()
	{
	var loginLabel = $("#LoginLabel").html();
	if (!isDefined(loginLabel) ||
		(isDefined(loginLabel) && loginLabel.length == 0) )
		loginLabel = "Login";
		
	var loginMsg = "<span id=user_login class='floatRight'>" + loginLabel + "</span></span>";
																
	$(".divLogin").each(function (i) {
		$(this).html(loginMsg).css("font-size","10px");
	});
      								
	$("#user_login").bind("click", function(){
		terrierLogin();
		});

    $("#user_login").hover(
		function () {
			$(this).css("cursor","pointer");
		}, 
		function () {
			$(this).css("cursor","default");
		}
    );
		
	$('.displayIfNotLoggedIn').show(); 
	}
function terrierPasswordChange()
	{
	try {		
		//	Display dialog asking for subscriber info
		
		var ourDiv = 'userPasswordChangeDialog';

		if ($('#' + ourDiv).length == 0)
			$('#container').append("<div id=" + ourDiv + "></div>");

		var theDialogHTML = "<table width=380 cellspacing=0 cellpadding=2>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=40% class='alignRight'>User Name : </td>";
		theDialogHTML += "<td width=60%><input type='text' id='userEmail' value=''/></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=40% class='alignRight'>Password : </td>";
		theDialogHTML += "<td width=60%><input type='password' id='userNewPassword1' value=''/></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=40% class='alignRight'>Password : </td>";
		theDialogHTML += "<td width=60%><input type='password' id='userNewPassword2' value=''/></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=100% colspan=2></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "<tr>";
		theDialogHTML += "<td width=100% colspan=2><span id=helpMsg></span></td>";
		theDialogHTML += "</tr>";
		theDialogHTML += "</table>";
		$('#' + ourDiv).html(theDialogHTML);
				
		$('#' + ourDiv).dialog({
						autoOpen: false,
						modal: true,
						height: 260,
						width: 400,
						position: ['center','top'],
						title: 'Change User Password',
						resizable: true,
						open: function(Event, ui) {
								$('#userEmail').val( $('#theLoggedInName').val() );
								
								$("#userNewPassword1").bind("keydown", function(e){
								if (e.keyCode == 13)
									{
									if ($('#userNewPassword2:hidden').length)
										{
										var theDlgObj = $('#' + ourDiv);
										theDlgObj.dialog("option", "buttons")['Submit'].apply(theDlgObj);
										}
									else	//	First password fld exists, just tab to the second.
										$('#' + ourDiv + ' #userNewPassword2').focus();
									}
								});	
							$("#userNewPassword2").bind("keydown", function(e){
								if (e.keyCode == 13)
									{
									var theDlgObj = $('#' + ourDiv);
									theDlgObj.dialog("option", "buttons")['Submit'].apply(theDlgObj);
									}
								});
						} ,
						buttons: {
							"Submit Password Change": function() {
								var doPasswordChange = true;
								var thePassword1 = $('#userNewPassword1').val();
								var thePasswordLength1 = $('#userNewPassword1').val().length;
								var thePassword2 = $('#userNewPassword2').val();
								var thePasswordLength2 = $('#userNewPassword2').val().length;
																
								if (thePasswordLength1 == 0)
									{
									$("#helpMsg").html('Please enter a password', 'messagebox');
									doPasswordChange = false;					
									}
								if (thePassword1 != thePassword2)
									{
									$("#helpMsg").html('Passwords do not match', 'messagebox');
									doPasswordChange = false;
									}
									
								if (doPasswordChange)
									{									
									if (confirm ("Are you sure you want to change your password?"))
										{
										var theUser = $('#theLoggedInName').val();
										
										$.ajax({
												type: "POST",
												url: "/code/php/_terrierChangePassword.php",
												data:  "user=" + theUser + "&pass=" + thePassword1,
												dataType: "xml",
												success: function(xml) {
													var theError = $(xml).find('error').text();
													if (theError == '0')
														{
														alert('Your password has been changed');
														
														var theDlgObj = $('#' + ourDiv);
														theDlgObj.dialog("option", "buttons")['Cancel'].apply(theDlgObj);
														}
													else
														$("#helpMsg").html('Unable to change your password: ' + theError);														
													}
											});
										}
									}
							},
							"Cancel": function() { 
								$('#' + ourDiv).html("");
								$(this).dialog("close");
								$(this).remove();
							}
						}
					});
						
		$('#' + ourDiv).dialog('open');	
			
		}
	catch (e) {
		showException(e, "terrierPasswordChange(): ");	
		}
	}
function displayUserSettings()
	{
	var ourDiv = 'userSettingsDialog';
	if ($('#' + ourDiv).length == 0)
		$('#container').append("<div id=" + ourDiv + "></div>");

	var theDialogHTML = "<form id='userSettingsForm'>";
	theDialogHTML += "<a href='#' id='changePassword' class='floatRight' title='Password Change'><span class='blue noUnderline size85em'>Change Password</span></a>";
	theDialogHTML += "<div id=userSettingsDiv name=userSettingsDiv></div>";
	theDialogHTML += "<span id=helpMsg></span>";
	theDialogHTML += "</form>";
	$('#' + ourDiv).html(theDialogHTML);

	$('#' + ourDiv).dialog({
			autoOpen: false,
			modal: true,
			height: 525,
			width: 600,
			position: ['center','top'],
			resizable: true,
			open: function(Event, ui) {
					loadingImage = "http://t2review.com/hosting/code/images/loading.gif  height=16 width=16";
					$('#' + ourDiv).dialog('option', 'title', '<img src=' + loadingImage + ' /> Loading...');
					
					$("#changePassword").bind("click", function(){
						terrierPasswordChange();
						});	
			
					//	Capture Escape key to close the dialog
//					captureDialogEscapeAndClickX(closeSetHTMLFragmentDialog, ourDiv, editableContentID);
					
					$.ajax({
							type: "POST",
							url: "/code/php/get_xml_fragments.php",
							data:  "user=" + $('#theLoggedInName').val(),
							dataType: "html",
							success: function(textHTML) {
								$('#' + ourDiv).dialog('option', 'title', 'Settings for ' + $('#theLoggedInName').val());
								
								$("#userSettingsDiv").html( textHTML );								
								},
							error: function(httpReq, textStatus, errorThrown){
									alert(textStatus + " - " + errorThrown);
								}
							});								


				} ,		// open
			buttons: {
				"Submit": function() {
					
					alert( $("form").serialize() );
/*
					$.ajax({
							type: "POST",
							url: "code/php/set_xml_fragments.php",
							data:  "user=" + $('#theLoggedInName').val() + "&" + $("#userSettingsForm").serialize(),
							dataType: "xml",
							success: function(xml) {
								var theError = $(xml).find('error').text();
								if (theError == '0')
									{								
									alert("Saved!");
									
									var theDlgObj = $('#' + ourDiv);
									theDlgObj.dialog("option", "buttons")['Cancel'].apply(theDlgObj);
									}
								else
									$("#helpMsg").html('Unable to save settings: ' + theError);
								
								},
							error: function(httpReq, textStatus, errorThrown){
									alert(textStatus + " - " + errorThrown);
								}
							});	
*/
				},
				"Cancel": function() { 
					$('#' + ourDiv).empty();
					$('#' + ourDiv).dialog("destroy");
				}
			}		// buttons
		});
						
	$('#' + ourDiv).dialog('open');
	}
	
function showHelpMsg(msg, theClass, closeThisDialog)
	{
	var fadeInSpeed = 3000;
	var fadeOutSpeed = 1000;
	var msgObj;
	msgObj = $('#helpMsg');			//	If dialog is open
	
	if (isDefined(closeThisDialog) && closeThisDialog.length)
		{
		if ('loginDialog' == closeThisDialog)
			fadeInSpeed = 'fast';
		}
	
	msgObj.html(msg).addClass(theClass);
	msgObj.fadeIn(fadeInSpeed, function() { 
			msgObj.fadeOut(fadeOutSpeed);

			msgObj.removeClass(theClass);

			if (isDefined(closeThisDialog) && closeThisDialog.length)
				$('#' + closeThisDialog).dialog('close');
			});




//	$('#helpMsg').html(msg).addClass(theClass).fadeIn(2000,function() { 
//			$('#helpMsg').fadeOut(2000);
		
//			if (isDefined(closeThisDialog) && closeThisDialog.length)
//				$('#' + closeThisDialog).dialog('close');
//			});
	}
function getCookie(cookieName)
	{
	//	Because this is AJAX, cached the (hashed) cookies in 
	//	the page when they are set.  If they were set during
	//  this page life, we'll have it in the hidden field name.
	//  If not, we get it from the cookie.
	
	var hashedName = md5(cookieName);
	if ($('#'+hashedName).length > 0)
		{
		var retVal = $('#'+hashedName).val();
		if (retVal.length > 0)
			return retVal;
		}
	return $.cookie(cookieName);
	}
function setCookie(cookieName, newVal)
	{
	//	Because this is AJAX, cached the (hashed) cookies in 
	//	the page when they are set.  Set the document.cookie 
	//	AND also set the hashed field

	$.cookie(cookieName, newVal, { expires: 1 });	//	Expires in 1 days
	var hashedName = md5(cookieName);
	
	if ($('#'+hashedName).length == 0)
		{
		var inputFld = "<input type=hidden id='" + hashedName + "' />";
		$('.hidden').append(inputFld);
		}
	$('#'+hashedName).val(newVal);
	}
function deleteCookie(cookieName)
	{
	setCookie(cookieName, "");
	var hashedName = md5(cookieName);
	
	if ($('#'+hashedName).length > 0)
		{
		$('#'+hashedName).remove();
		}
	}
/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/
 
var md5 = function (string) {
 
	function RotateLeft(lValue, iShiftBits) {
		return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
	}
 
	function AddUnsigned(lX,lY) {
		var lX4,lY4,lX8,lY8,lResult;
		lX8 = (lX & 0x80000000);
		lY8 = (lY & 0x80000000);
		lX4 = (lX & 0x40000000);
		lY4 = (lY & 0x40000000);
		lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
		if (lX4 & lY4) {
			return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
		}
		if (lX4 | lY4) {
			if (lResult & 0x40000000) {
				return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
			} else {
				return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
			}
		} else {
			return (lResult ^ lX8 ^ lY8);
		}
 	}
 
 	function F(x,y,z) { return (x & y) | ((~x) & z); }
 	function G(x,y,z) { return (x & z) | (y & (~z)); }
 	function H(x,y,z) { return (x ^ y ^ z); }
	function I(x,y,z) { return (y ^ (x | (~z))); }
 
	function FF(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};
 
	function GG(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};
 
	function HH(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};
 
	function II(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};
 
	function ConvertToWordArray(string) {
		var lWordCount;
		var lMessageLength = string.length;
		var lNumberOfWords_temp1=lMessageLength + 8;
		var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
		var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
		var lWordArray=Array(lNumberOfWords-1);
		var lBytePosition = 0;
		var lByteCount = 0;
		while ( lByteCount < lMessageLength ) {
			lWordCount = (lByteCount-(lByteCount % 4))/4;
			lBytePosition = (lByteCount % 4)*8;
			lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
			lByteCount++;
		}
		lWordCount = (lByteCount-(lByteCount % 4))/4;
		lBytePosition = (lByteCount % 4)*8;
		lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
		lWordArray[lNumberOfWords-2] = lMessageLength<<3;
		lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
		return lWordArray;
	};
 
	function WordToHex(lValue) {
		var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
		for (lCount = 0;lCount<=3;lCount++) {
			lByte = (lValue>>>(lCount*8)) & 255;
			WordToHexValue_temp = "0" + lByte.toString(16);
			WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
		}
		return WordToHexValue;
	};
 
	function Utf8Encode(string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	};
 
	var x=Array();
	var k,AA,BB,CC,DD,a,b,c,d;
	var S11=7, S12=12, S13=17, S14=22;
	var S21=5, S22=9 , S23=14, S24=20;
	var S31=4, S32=11, S33=16, S34=23;
	var S41=6, S42=10, S43=15, S44=21;
 
	string = Utf8Encode(string);
 
	x = ConvertToWordArray(string);
 
	a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
 
	for (k=0;k<x.length;k+=16) {
		AA=a; BB=b; CC=c; DD=d;
		a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
		d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
		c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
		b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
		a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
		d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
		c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
		b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
		a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
		d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
		c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
		b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
		a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
		d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
		c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
		b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
		a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
		d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
		c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
		b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
		a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
		d=GG(d,a,b,c,x[k+10],S22,0x2441453);
		c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
		b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
		a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
		d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
		c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
		b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
		a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
		d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
		c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
		b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
		a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
		d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
		c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
		b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
		a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
		d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
		c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
		b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
		a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
		d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
		c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
		b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
		a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
		d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
		c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
		b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
		a=II(a,b,c,d,x[k+0], S41,0xF4292244);
		d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
		c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
		b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
		a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
		d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
		c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
		b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
		a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
		d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
		c=II(c,d,a,b,x[k+6], S43,0xA3014314);
		b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
		a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
		d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
		c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
		b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
		a=AddUnsigned(a,AA);
		b=AddUnsigned(b,BB);
		c=AddUnsigned(c,CC);
		d=AddUnsigned(d,DD);
	}
 
	var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
 
	return temp.toLowerCase();
}
function isDefined(variable)
	{
	return (!(!( variable||false )))
	}
function showException(e, eModule)
	{
	if (e instanceof TypeError)
		eStr = "Variable type problem, check your variable definitions!";
	else if (e instanceof RangeError)
		eStr = "Number out of range!";
	else if (e instanceof SyntaxError)
		eStr = "Syntax error in code!";
	else
		eStr = "An unspecified error occurred!";

	alert(eModule + "\r\n" +  eStr + "\r\n" +  e.message);
	}
function getHTMLFragment(curObj, fragmentID)
	{
	try {
//console.log("Safari: in getHTMLFragment");
		//	Load the scripts that non-admins don't care about, and only cause slowdowns

		$.getScript("http://themontgomeryfinancialgroup.com/code/js/jquery.cookie.js", function(){
			
			loadingImage = "http://themontgomeryfinancialgroup.com/code/images/loading.gif  height=16 width=16";
			curObj.html("<img src=" + loadingImage + " /> Loading...");
	
			//	Fetch the contents from mySQL and populate the field    
			$.ajax({
					type: "GET",
					url: "/code/php/get_html_fragments.php",
					data:  "id=" + fragmentID,
					cache: false,
					dataType: "text",
					success: function(textHTML) {
						curObj.html(textHTML);
						$('.HTMLFragment').html(textHTML);
						
						var loginName = $('#theLoggedInName').val();
						var sessionIsAlive = (loginName.search("SESSION") == -1) ? true : false;
						if (loginName == null || loginName == 0 || sessionIsAlive == false)
							{
							displayLoggedOut();
							}
						else
							{
							displayLoggedIn(loginName);
							}
						},
					error: function(httpReq, textStatus, errorThrown){

							curObj.html(textStatus + " - " + errorThrown);
							curObj.css({
									"background":"#F7CBCA",
									"color":"#CC0000"
									});
						}
				});
		});		//getScript
		}

	catch (e) {
		showException(e, "getHTMLFragment(): ");	
		}
	}
function setHTMLFragment(curObj, fragmentID)
	{
	try {
		var loginName = "";
		loginName = $('#theLoggedInName').val()
		if (loginName != null && loginName.length > 0)	//	If logged in
			{	
			//	Use getScript to load the script now, instead of on page load.
			//	Saves lots of time.
			
	//		$.getScript("http://themontgomeryfinancialgroup.com/code/js/tiny_mce.js", function(){
				
				var ourDiv = 'fragmentDialog';
				var editableContentID = 'editableContent' + fragmentID;
				if ($('#' + ourDiv).length == 0)
					$('#container').append("<div id=" + ourDiv + "></div>");
		
				var defaultDialogTitle = 'Change contents of this field';
				var theVal = curObj.html();
				var theDialogHTML = "<form id='editorForm'>";
				theDialogHTML += "<textarea class='tinymce' id=" + editableContentID + " name=" + editableContentID + " cols='80' rows='30' >" + theVal + "</textarea>";
				theDialogHTML += "<span id=helpMsg></span>";
				theDialogHTML += "</form>";
				$('#' + ourDiv).html(theDialogHTML);
			
				$('#' + ourDiv).dialog({
						autoOpen: false,
						modal: true,
						height: 500,
						width: 750,
						position: ['center','top'],
						title: defaultDialogTitle,
						resizable: true,
						open: function(Event, ui) {
								loadingImage = "http://themontgomeryfinancialgroup.com/code/images/loading.gif  height=16 width=16";
								$('#' + ourDiv).dialog('option', 'title', '<img src=' + loadingImage + ' /> Loading...');

								//	Capture Escape key to close the dialog
								captureDialogEscapeAndClickX(closeSetHTMLFragmentDialog, ourDiv, editableContentID);
							
								tinyMCE.init({
									mode : "none",
									theme : "advanced",
									height : "360",
									width : "710",
////									plugins : "imagemanager"
//									plugins : "safari,spellchecker",
									plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,searchreplace,print,paste,directionality,fullscreen",
									theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,insertimage",
									theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,forecolor,backcolor",
									theme_advanced_buttons3 : "",
									theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen"
//									theme_advanced_buttons4 : "styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
//									theme_advanced_toolbar_location : "top",
//									theme_advanced_toolbar_align : "center",
		//							theme_advanced_statusbar_location : "bottom",
//									theme_advanced_resizing : true
									});
			
								$('#' + ourDiv).dialog('option', 'title', defaultDialogTitle);
							} ,		// open
						buttons: {
							"Submit": function() {
								tinyMCE.triggerSave();
								var doIt = false;
								var theVal = $('.tinymce').val();
																						
								if (theVal == "")
									{
									if (confirm("Are you sure you want empty the contents of this field?"))
										doIt = true;
									}
								else
									doIt = true;
									
								if (doIt == true)
									{
									$.ajax({
										type: "POST",
										url: "/code/php/set_html_fragments.php",
										data:  "id=" + fragmentID + "&user=" + loginName + "&" + $("#editorForm").serialize(),
										dataType: "xml",
										success: function(xml) {
											var theError = $(xml).find('error').text();
	
											if (theError == '0')
												{
												curObj.html(theVal);
												$('#' + ourDiv).dialog("close");
												}
											else
												alert(textResponse);
											},
										error: function(httpReq, textStatus, errorThrown){
												alert(textStatus + " - " + errorThrown);
											}
									});
									}
							},
							"Cancel": function() { 
								closeSetHTMLFragmentDialog(ourDiv, editableContentID);
							}
						}		// buttons
					});
									
				$('#' + ourDiv).dialog('open');
				
				tinyMCE.execCommand('mceAddControl', false, editableContentID);
				
				//	End 'Busy' title
				$('#' + ourDiv).dialog('option', 'title', defaultDialogTitle);
				
	//			});		//	getScript
			}
		}		//	Try

	catch (e) {
		showException(e, "setHTMLFragment(): ");	
		}
	}
function captureDialogEscapeAndClickX(theFunctionToExecute, divParameter, functionParameter)
	{
	$(document).bind("keydown", function(e){
		if (e.keyCode == 27)
			theFunctionToExecute(divParameter, functionParameter);
		});
	$(".ui-icon-closethick").bind("click", function(e){
		theFunctionToExecute(divParameter, functionParameter);
		});
	}
function closeSetHTMLFragmentDialog(ourDiv, editableContentID)
	{
	tinyMCE.execCommand('mceRemoveControl', false, editableContentID);
								
	$('#' + ourDiv).empty();
	$('#' + ourDiv).dialog("destroy");
	}
function displayHelpMsg(msg, theClass, closeThisDialog)
	{
	$('#helpMsg').html(msg).addClass(theClass).fadeIn(2000,function() { 
			$('#helpMsg').fadeOut(2000);
			
			if (isDefined(closeThisDialog) && closeThisDialog.length)
				$('#' + closeThisDialog).dialog('close');
			});
	}