/*
 * @author philip.ward
 * 
 * November 2008: Script being re-written to use jQuery and jQuery UI.
 */
 
//	Global variables (values cached in memory)

var currentPopup = 0;	//	need to keep global...
var selectedRow;

// Allow a DIV overlay to occupy most of the screen:

jQuery.fn.largePopup = function() {
	this.css("width", $(window).width() - 200);
	this.css("height", $(window).height() - 200);
	return this;
}

jQuery.fn.fullscreen = function() {
	this.css("top", "0px");
	this.css("left", "0px");
	log("Window height: " + $(window).height() + "px");
	this.css("bottom", $(window).height() + "px");
	this.css("right", $(window).width() + "px");
}

jQuery.fn.playAudio = function(audioUrl) {
	
	// First, make a DIV to contain the audio elements:
	
	var audioDiv = document.createElement('div');
	document.body.appendChild(audioDiv);
	var adn = Math.random().toString().substring(2);
	adn = "audioDiv" + adn;
	audioDiv.id = adn;
	
	//	Get title information:
	
	var q = $(this).parents('tr').children();
	var s = "";
	var h="<h2>" + $(q[2]).html() + " (" + $(q[1]).html() + ")</h2><br>";
	
	//	Does browser support HTML5 <AUDIO> tag with MP3s?
	
	if (document.createElement('audio').canPlayType) {
		if (document.createElement('audio').canPlayType('audio/mpeg')) {
			h += "<audio id='mp3Audio' controls='controls'><source src='audio/37221.mp3' type='audio/mpeg'/><audio>";
		} else {
			h += "<embed src='audio/37221.mp3' width='300' height='20' autostart='false'></embed>"
		}
	} else {
		h += "<object width='300' height='20'><param name='src' value='audio/37221.mp3'><param name='autoplay' value='false'>";
		h += "<param name='controller' value='true'><param name='bgcolor' value='#000000'>";
		h += "<embed src='audio/37221.mp3' autostart='false' loop='false' width='300' height='20' controller='true' bgcolor='#000000'></embed></object>";
	}
	
	$(audioDiv).addClass("audio").draggable({
			handle: "h2"
		}).html(h).center().show().addClose();
		
}

jQuery.fn.removeAudio = function(someHtml) {
	
	$this.parent().html(s);
	
}

function hformat(someString) { // Substitute carriage returns and line feeds with <BR>:

	someString = escape(someString);

	var re = /%0D%0A/g;		//	Works for Internet Explorer
	someString = someString.replace(re, "<BR>");
	re = /%0A/g;			//	Works for Firefox
	someString = someString.replace(re, "<BR>");
	
	re = /%22/g;	//	Double quote marks
	someString = someString.replace(re, "&#34;");
	
//	alert(someString);
	
	//	Single quotes are not for some reason escaped by encodeURIComponent, so we do that here:
	
	re = /\'/g;
	someString = someString.replace(re, "&#39;");
	
	//	we also have some problems with plus signs:
	
	re = /\+/g;
	someString = someString.replace(re, "&#43;");
	
	//	Now replace percent signs by some string to fool http and perl that this is not an escaped string.
	
	re = /&#/g;
	someString = someString.replace(re, "QamphashQ");	
	
	//	Ditto with semicolons.
	
	re = /;/g;
	someString = someString.replace(re, "QsemicolonQ");	
	
	return someString;
		
}

function largeFont() {	// Increase the font size in the results table

	var f = $("#resultsTable").css('font-size');
	f = f.substr(0,2);
	f++;
	$("#resultsTable").css('font-size', f + 'px');
	
}

function littleFont() {	//	Decrease the font size in the results table
	
	var f = $("#resultsTable").css('font-size');
	f = f.substr(0,2);
	f--;
	$("#resultsTable").css('font-size', f + 'px');
	
}

function showVideo(eventID, eventTitle, eventDate, eventPlace){ //	Show a YouTube or Vimeo video, or an MP4 on the site, in one of the popups

	// If there are more than one video for an event, list them and invite the user to choose:
	
	var h;
	
	if (eventID.indexOf(",") > 0) {
		h = "<DIV class=drag-video>";
		log("Video IDs: " + eventID);
		h += "<B>" + eventTitle + "</B><BR>" + eventDate + " " + eventPlace + "<BR>";
		var videos = new Array;
		videos = eventID.split(",");
		var vlen = videos.length;
		var c = ""
		
		for (var i=0;i<vlen;i++) {
			
			//	Check for descriptive title:
			
			var dt = "Video " + (i+1);
			var ix = videos[i].indexOf("§");
			
			if (ix > 0) {
				dt = videos[i].substr(ix+1);
			}
			
			h += "<input type='button' value='" + dt + "' onclick='showVideo(\"" + videos[i] + "\",\"" + eventTitle + "\",\"" + eventDate + "\",\"" + eventPlace + "\")'><BR>";
		}
//		h += "<BR><input class='press' type='button' value='Close' onclick='closeVideo()'></DIV>";
		h += "<BR></DIV>";
//		$("#opback").fadeTo(1,0.7).show();			
		$("#popup9").html(h).fadeIn("slow").addClass("video").draggable({
			handle: "div"
		}).center().addClose();
		return false;	
	}
	
	var r = new RegExp("[0-9]{7,}");
	
	//	Make sure video will fit in window:
	
	var wi = $(window).width();
	var ht = $(window).height();
	var h2 = 610;

	if (wi > 889) {
		wi = 800;
	} else {
		wi = wi * 0.9;
	}
	
	if (ht > 734) {
		ht = 661;		
	} else {
		ht = ht * 0.9;
		h2 = ht - 51;
	}
	
	log("Initial: " + wi + " " + ht);
	
	//	Adjust aspect ratio
	
	switch (wi/ht) {
		case 1.4-100: wi = ht * 5/4;
			break;
		case 0-1.2: ht = wi * 4/5;	
			h2 = ht - 51;
	}

	//	eventID may contain a short descriptive title:
	
	var ix = eventID.indexOf("§");
	var dt = "";
	
	if (ix > 0) {
		dt = "(" + eventID.substr(ix+1) + ")";	
		eventID = eventID.substr(0, ix);
	}

	log("Window " + wi + " x " + ht);
	
	// Special handling for audios? //

	h = "<iframe width='" + wi + "' height='" + h2 + "' ";
	log (h);
		
	if (r.test(eventID)) { //	Video is on Vimeo
		h += 'src="http://player.vimeo.com/video/' + eventID + '?title=0&amp;byline=0&amp;portrait=0" frameborder="0"></iframe>';
	}
	else {	
		if (eventID.length > 9) { //	Video is on YouTube
			h += "src='http://www.youtube.com/embed/" + eventID + "?showinfo=1&rel=0&modestbranding=1&hd=1' frameborder='0' allowfullscreen></iframe>";
		}
	}

//	h += "<br><table width=100%><tr><td span=2 align=left><b>" + eventTitle + "</b></td></tr><tr><td align=left>" + eventDate + ", " + eventPlace + " " + dt + "</td><td align=right><input class='press' type='button' value='Close' onclick='closeVideo()'></td></tr></table>";
	h += "<br><table width=100%><tr><td span=2 align=left><b>" + eventTitle + "</b></td></tr><tr><td align=left>" + eventDate + ", " + eventPlace + " " + 
		dt + "</td><td align=right></td></tr></table>";
	
	//	Add an opaque background to the screen:
	
	log("Opaquing display");
	
//	$("#opback").fadeTo(1,0.7).show();
	
	log("Showing video DIV");	
/*	
	$("#popup10").html(h).fadeIn("slow").addClass("video").draggable({
		handle: "div"
	});	//	since popup 10 is unlikely to be open...
*/	
	//	Set table DIV width to match movie container width:
	
	var w = $("#video").width();
	$("#headertable").width(w-8);
	
//	$("#popup10").width(wi).height(ht).center();
	$("#popup10").html(h).fadeIn("slow").addClass("video").width(wi).height(ht).center().addClose();
	
	log("Video should be ready to play");
}

function closeVideo() { // Close the video opened with showVideo

	var foo = "#popup10";
	
	if ($("#popup9").html() == "") {
		log("Hiding opaque");
		$("#opback").fadeTo(1,0).hide();
	} else {
		log("Popup 9 is visible");
		if ($(foo).html() == "") {
			log(foo + " is not visible");
			foo = "#popup9";
			$("#opback").fadeTo(1,0).hide();
		} else {
			log(foo + " is " + $(foo).attr("visibility"));
		}
	}

	log("Closing video...");
	$(foo).fadeOut("slow").html("").draggable({
		handle: "div",
		cursor: "default"
	}).removeProp("width").removeProp("height");
	
	$(".div").css('cursor','auto');	// Sometimes this doesn't happen automatically.

	log("Video popup closed");
	
}

function closeText() {
	
	$("#textDiv").fadeOut("slow").html("");
	$("#opback").fadeTo(1,0).hide();
	
}

function showTranscript(id, title, date, location) {
	
	var url = "http://talks.sahajayogaonline.com/cgi-bin/showText.pl";

	$.post(url, {i: id}, function(data) {
//		var h = "<div id=p10head><table width=100%><tr><td align=left style='margin:0px;'><h2 id='tsh1'>" + title + "</h2></td><td align=right><input class='press' type='button' value='Close' onclick='closeVideo()'></td></tr></table>";
		var h = "<div id=p10head><table width=100%><tr><td align=left style='margin:0px;'><h2 id='tsh1'>" + title + "</h2></td></tr></table>";
		h += date + ", " + location + "</div><div class='scrollable'>" + data + "</div>";
//		$("#opback").fadeTo(1,0.7).show();
		var wi = $(window).width() - 200;
		var hi = $(window).height() - 250;
		if (wi > 700) wi = 700;	// window should not be too large
		wi = wi + "px";
		hi = hi + "px";
		$("#popup10").width(wi).html(h).fadeIn("slow").addClass("audio").draggable({
			handle: "h2"
		}).addClose().height(hi).center();
		
		wi = $("#popup10").width()-25;
		hi = $("#popup10").height()-$("#tsh1").height()-60;
		wi = wi + "px";
		hi = hi + "px"; 
		$(".scrollable").width(wi).height(hi);
		
	});
	
}
function editText(id, user, session, someVal) {
	
	//	Display rich text window for entering and editing transcripts, using clEditor.
	
	var url = "http://talks.sahajayogaonline.com/cgi-bin/showText.pl";
	log("Parameters: " + id + " " + user + " " + session);
	
	
	log("Starting editText");
	$.post(url, {i: id}, function(data) {
		var h = "<h1>" + someVal + "</h1><textarea id='textEdit'>" + data + "</textarea>";
		h += "<table width=100%><tr><td align=left><input class='press' type='button' value='Save' onclick='saveText(" + id + ", \"" + user + "\", \"" + session + "\")'></td>";
		h += "<td align=right><input class='press' type='button' value='Close' onclick='closeText()'></td></tr></table></div>";
		$("#opback").fadeTo(1,0.7).show();
		$("#textDiv").html(h).fadeIn("slow").addClass("video").largePopup().center();
		log("Received: " + data);
		$("#textEdit").focus().width($("#textDiv").width()-20).height($("#textDiv").height()-125).center();
		var wi = $("#textDiv").width()-20;
		var ht = $("#textDiv").height()-125
		$("#textEdit").cleditor({
			width: wi,
			height: ht
		});
		log("Wrote data");
	});
	log("Finished editText");			
}

function saveText(id, user, session) {
	
	var url = "http://talks.sahajayogaonline.com/cgi-bin/saveText.pl";

	// Recover content of iframe body:
	var iframeRef = document.getElementsByTagName('iframe');	
	var t = $(iframeRef).contents().find('body').html();
	
	log("saveText: " + t);
	
	// Post content to server:
	$.post(url, {i: id, h: t, u: user, s: session}, function(data) {
		alert(data);	// data is just a thank-you message.
	})

	//	Update the results listing:
	url = "http://talks.sahajayogaonline.com/cgi-bin/SimpleFormLoad.pl";
	qry = "objId=" + id + "&user=" + user + "&session=" + session;
	xmlHttpPost(url, qry);
	
}

function wordCrunch(someText) {	//	Removes Word formatting from XML and HTML text

	var s = someText;
	s.replace(/<xml>.+<\/xml>/gi, "");	//	Remove any XML code
	s.replace(/<style>.+?<\/style>/gi, "");
	s.replace(/<object>.+?<\/object>/gi, "");
}

function updateResults(someHtml, someObject) { // Updates content of a HTML object
	
	log("updateResults: " + someHtml.length);
	log("Object: " + someObject);
	
	//	This is necessary as the jQuery procedure apparently doesn't work with old IE versions.
		
//	if (window.ActiveXObject) { // We have some problems with old IE...
		var q = document.getElementById(someObject);
		q.innerHTML = someHtml;
/*	} else {
		$(someObject).html(resp1);
	}
*/	
	if (someHtml.indexOf("</TABLE>")>0) {
		$("#provFeedback").show();
	}
	
	log("Loaded HTML");
	
	report();
	
	return;
	
}

function loadPopup(toEdit, objId, userId, sessionId, parentId, popupId) { // Loads content of a popup window
	
	//	Determine the Ajax query:
	
	log("Running loadPopup for parent " +  parentId + ", child " + popupId + ", objId " + objId + ", type " + toEdit + ", user:" + userId + ", session: " + sessionId);
	
	var l = toEdit.length;
	
	if (toEdit.substr(l-3) === "_id") {
		toEdit = toEdit.substr(0, l-3) + "s";
	}
	
	if (toEdit === "citys") {	// Special case of plural
		toEdit = "cities";
	}
	
	//	Parameters to send to the server: type of object to edit, object ID, user ID, session ID, popup ID, parent ID.
	var qry = "?w=" + toEdit + "~~~" + objId + "~~~" + userId + "~~~" + sessionId + "~~~" + popupId + "~~~" + parentId;
	var url = "http://talks.sahajayogaonline.com/cgi-bin/easyEditNew.pl" + qry;
	
	//	Ajax query to database, returned content is loaded into popup window:
	
	$("#popup" + popupId).load(url);
	
	//	"reactivate" the buttons:
	
	$("dataentry input").attr("color", "#000000");


}

function updatePopup (popupId) { // Updates the content of a popup

	//	First identify which of the several forms on screen is being used:
	
	var myForm;
	var k;

//	alert("Updating popup " + popupId);

	$("#popup" + popupId).fadeTo("fast", 1);
	
	for (k=0;k<20;k++) {
//		alert(k + " " + document.forms[k].id);
		if (document.forms[k].id === "easyForm_" + popupId) {
			myForm = document.forms[k];
			k = 22;
		}
	}
	
	if (k < 22) {
		alert("Could not find form for easyForm_" + popupId);
		return;
	}
	
	var toEdit = myForm.type.value;
	var objId = myForm.object.value;
	var userId = myForm.user.value;
	var sessionId = myForm.session.value;
	var parentId = myForm.parent.value;
	
//	alert("Calling loadPopup for ID " + objId);
	
	loadPopup(toEdit, objId, userId, sessionId, parentId, popupId);
	
	return;		
	
}

function xmlHttpPost(strURL, strDetails) { // Make Ajax request, process response
	
	//	Pretty standard Ajax stuff; actually, not strictly Ajax as no XML involved.

			var xmlHttpReq = false;
			var self = this;
			
			// Decide which browser we are using:
			
			// Mozilla / Safari
			if (window.XMLHttpRequest) {
				self.xmlHttpReq = new XMLHttpRequest();

			//	Make sure content is returned as iso-8859-1 to avoid problems with accented characters:
			
				if (self.xmlHttpReq.overrideMimeType) {
            		self.xmlHttpReq.overrideMimeType('text/xml; charset=iso-8859-1');					
				}
				log("Detected Gecko browser");
			}
			// IE
			else if (window.ActiveXObject) {
				self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
				log("Detected IE");
			}
			
			log("Submitting " + strDetails);
			report();
			self.xmlHttpReq.open('POST', strURL, true);
			self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		 
			self.xmlHttpReq.onreadystatechange = function() {
				log("Ajax ready state " + self.xmlHttpReq.readyState);
				if (self.xmlHttpReq.readyState == 4) {
					var resp1 = self.xmlHttpReq.responseText;
					var resp2 = resp1.substr(0,7);
					log ("Received " + resp1);
					switch (resp2) {
						case "Display":
							updateRow(resp1.substr(7), "");
							break;
						case "Failed ":
							alert("Database operation failed: " + resp1);
							break;
						case "No Priv":
							alert("No privilege for requested operation.");
							break;
						case "Duplica":
							alert("Duplicate entry attempted.");
							break;
						case "No such":
							alert("No entry found with this ID.");
							break;
						case "Timeout":
							alert("Session timed out. Please log on again.");
							break;
						case "Illegal":
							alert(resp1);
							break;
						case "INSERT:":
							var objId = resp1.substr(7);
							$("#object_" + currentPopup).val(objId);
							log("Inserted " & objId & " from popup ID");
						case "Success":
							log("Current popup: " + currentPopup);
							updatePopup(currentPopup);
							break;
						case "Results":
							resp1 = resp1.substr(7);
							updateResults(resp1, 'results');
							break;
						case "Excel  ":
							resp1 = resp1.substr(7);
							$("body").html(resp1);
							break;
						case "UPDATE:": 
							break;
						case "Donkey:": eatGrass(resp1);	//	Vulgar obfuscation
							break;
						case "Woohoo!": alert(resp1.substr(7)); // to mislead criminals...
							break;
						case "Other":
							break;	
						default: alert(resp1);					
					}
					report();
				}
			};
			log("Sending request...");
			self.xmlHttpReq.send(strDetails); 
		}

function resizeWindow(newWidth,newHeight) { // Resize window
	window.resizeTo(newWidth,newHeight);
	return;	
}

function closeConfirm(popupId, parentId) { // Close a popup, focus parent popup (if any)

	//	Hide and empty the current popup, make draggable:
	
	$("#popup" + popupId).hide("normal").html("").draggable({handle: "div"});
	
	//	If the parent of this popup was another popup, fade it back in:
	
	if (parentId > 0) {
		$("#popup" + parentId).fadeTo("normal", 1);
	}
	
	$("WzTtDiV").hide();	//	In case any ToolTips still open.
	
	$(selectedRow).removeClass("selectedRow");
	
	if (currentPopup == popupId) {
		currentPopup = 0;
	}
	
	report();

	return;
}

function makeDivs() { // Creates 10 invisible DIVs which can then be used for popup windows, sets different background colors and cascades them.

	//	Make all popups draggable using the drag handle, and hide them:
	
	$(".popup").hide().draggable({
		handle: ".drag-handle",
		dragPrevention: "a,input,textarea,table,.multiSelectOptions",
		cursor: "move"
	});
	
	//	Add an opaque background DIV for the lightbox simulation, hide it for now:
	
	$("#opback").addClass("opaqueBackground").hide();
	$("#textDiv").addClass("textDivStyle").hide();
	$("#audioDiv").hide();
}

function toggleDrag(popup) { // Removes draggable attribute from a popup, allowing text selection
	
	$("#popup" + popup).draggable("destroy");
	
}

function submitForm() { // Submits a form
	document.form.submit();
}

function openPopup(toEdit, objId, userId, sessionId, parentId){ // Opens a popup for data editing 

	// Find a popup we can use:
	
	var i = 0;
	var j = 0;
	var p;

	for (i = 1; i < 11; i++) {
		if ($("#popup" + i).html() === "") {
			j = i;
			i = 11;
		}
	}
	
	if (j == 0) {
		alert("Too many popup windows open. Please close at least one.");
		return;
	}
	else {
		p = "#popup" + j;
	}
	
	//	Make the popup visible:
	
	$(p).show().html("<H1>Loading data...</H1>");
	
	//	Fade the parent popup, if there is one:
	
	if (parentId > 0) {
		$("WzTtDiV").hide(); //	In case any ToolTips still open.
		$("#popup" + parentId).fadeTo("normal", 0.6);
	}
	
	//	Populate the popup:
	
	loadPopup(toEdit, objId, userId, sessionId, parentId, j);
	currentPopup = j;
	return j;
}

function removeLink(table, user, col1, val1, col2, val2, popupId) {	//	Removes an entry in a many-to-many link table by creating a Ajax request and passing it to a M2M script on the server.
	
	/* Arguments: CGI script to run
	 * 			
	 * 
	 * Typical arguments to Perl CGI script:
	 * 
	 * w=tracks+add+Phil+event_id+213+tape_id+1234
			
	 */
	
	var url = "http://talks.sahajayogaonline.com/cgi-bin/mtm.pl";
	var par = "w=" + table + "+remove+" + user + "+" + col1 + "+" + val1 + "+" + col2 + "+" + val2;

	if (confirm("Do you really want to de-link?")) {
	
		xmlHttpPost(url, par);
		
	}
	
	updatePopup(popupId);
	
	return;
	
}

function addLink(table, user, col1, val1, col2) { // adds a many-to-many link between data objects from a popup
	
	//	The opposite of removeLink...
		
	var url = "http://talks.sahajayogaonline.com/cgi-bin/mtm.pl";
	var tableName = col2.substr(0, col2.indexOf("_id"));
	var val2 = prompt("Please enter the ID of the " + tableName + " that you want to link to.");
	
	if (val2 !== "") {
		var par = "w=" + table + "+add+" + user + "+" + col1 + "+" + val1 + "+" + col2 + "+" + val2;
		xmlHttpPost(url, par);		
	} else {
		alert("No " + tableName + " ID specified.");
	}
	
	var toEdit = myForm.type.value;
	var objId = myForm.object.value;
	var userId = myForm.user.value;
	var sessionId = myForm.session.value;
	var parentId = myForm.parent.value;
	
	updatePopup(popupId);

	return;
}

function easyChanges(sqlQry) { // Pass a query to a host script for execution.
	 
	var url = "http://talks.sahajayogaonline.com/cgi-bin/easyUpdate.pl";
	
	var qry = escape(sqlQry);
	xmlHttpPost(url, qry);
	
	return;
	
}

function makeChanges(someId, tableName, session, popupId) {	// From popup, updates the database for the object of given ID and type (table name).
	
	//	First identify which of the several forms on screen is being used:
	
	log("parameters: " + someId + " " + tableName + " " + session + " " + popupId);
	
	var myForm = $("#easyForm_" + popupId);
	var currentUser = $("#user_" + popupId).attr('value');	
	
	//	Go through the form and identify changeable fields:
	
	var qry;
	var values = "";
	var commaWritten = 0;
	var i;	
	var histText;
	var url = "http://talks.sahajayogaonline.com/cgi-bin/udb.pl";
	var curVal = "";
	var oldVal = "";
	var fieldName = "";
	
	//	Identify the parent:
	
	var parent = $("#parent_" + popupId).val();
	
	//	The object ID is contained within the form as a hidden value, so it's not
	//	necessary to get it from the function arguments.
	
	var objectId = $("#object_" + popupId).val();
	
	if (objectId == "0") {	//	New object creation
		qry = "INSERT|" + tableName + "|";
		histText = "Created by " + currentUser + " " + document.lastModified;
	} else {
		qry = "UPDATE|" + tableName + "|" + objectId + "|";
		histText = "Updated by " + currentUser + " " + document.lastModified;
	}
	
	var allInputs = $("#easyForm_" + popupId + " > .updatable");
	
	//	Run through the fields, one by one:
	
	commaWritten = 0;
	
	$(allInputs).each(function() {
		
		curVal = $(this).val();
		fieldName = $(this).attr('name');
		
		if ($(this).attr("type") == "select-one") {
			oldVal = $(this).attr('default');
		} else {
			oldVal = $(this).attr("origVal");
		}
		
		if (curVal != oldVal) {

			if (commaWritten == 0) {
				commaWritten = 1;
			}
			
			histText = histText + "<BR><B>" + fieldName + ":</B> " + oldVal + " -QamphashQ62QsemicolonQ " + curVal;							

			curVal = hformat(curVal);
			oldVal = hformat(oldVal);
						
			//	Special treatment for duration fields:
			if ($(this).hasClass("duration") == true) {
				var z = curVal.indexOf("( ");
					
				if (z>0) {
					curVal = curVal.substr(z+2);
					z = curVal.indexOf(" sec");
					curVal = curVal.substr(0, z-1);					
				}				
			}			
			qry = qry + fieldName + "=" + curVal + "|";
		}		
	});
	
	//	Repeat the process for any multiSelect inputs:
	
	$(".popup .multiSelect > span").each(function() {
		curVal = $(this).html();
		log("curVal: " + curVal);
		fieldName = $(this).parent().attr('id');
		log("fieldName: " + fieldName);
		
		//	Default values from hidden input:
		
		oldVal = $("#default" + fieldName).val();
		log("oldVal: " + oldVal);
		
		if (curVal != oldVal) {
			fieldName = $("#default" + fieldName).attr('name');
			log(">> fieldName: " + fieldName);

			if (commaWritten == 0) {
				commaWritten = 1;
			}
			
			histText = histText + "<BR><B>" + fieldName + ":</B> " + oldVal + " -QamphashQ62QsemicolonQ " + curVal;							

			curVal = hformat(curVal);
			oldVal = hformat(oldVal);
						
			qry = qry + fieldName + "=" + curVal + "|";
			
		}
	});
		
	if (commaWritten==0) {
		alert("No changes made.");
		return;
	}
	
	qry = "w=" + session + "|" + qry + "history=" + histText;
	
	report();

	var currentPopup = popupId;

	//	Update the parent popup or window:
	
	//	Make the form look as though it has been disabled:
	
	$("#popup" + popupId).fadeTo("fast", 0.8);

	url = url + "?" + qry;

	var objId = $("#object_" + popupId).val();

	var x = $.get(url, function(data) {
		
		if (data.substr(0,6) == "INSERT") {
			objId = parseInt(data.substr(7), 10);
			$("#object_" + popupId).val(objId);
		}
		
		//	Update the current popup
		updatePopup(currentPopup);
		
		if (parent == 0) {
			url = location.href;
			
			var sf = url.indexOf("SimpleForm.pl");
			if (sf > -1) {
				url = url.substring(0, sf) + "SimpleFormLoad.pl";
			}
			
			//	Update the results listing:
			qry = "objId=" + objectId + "&user=" + currentUser + "&session=" + session;
			xmlHttpPost(url, qry);
		} else {
			url="http://talks.sahajayogaonline.com/cgi-bin/easyEditNew.pl";
			//	Update the calling dropdown list in the parent popup:
			qry = "x=" + $("#type_" + popupId).val() + "&objId=" + objId + "&user=" + currentUser + "&session=" + session;
			url += "?" + qry;
			
			$.get(url, function(data) {
				var category = singular(tableName) + "_id_" + parent;
				$("#" + category).html(data);
			});
		}
	});
	
	return false;
}

function showSize () // Returns the size of the current window.

{
	var x = window.innerWidth;
	var y = window.innerHeight;
	var f;
	var q;
	
//	Number of forms in the page: //	
	var n = document.getElementById('feedcount');
	n = n.value;
	
	for (var i=0;i<n;i++) {
		f = 'feed' + i;
		q = document.getElementById(f);
//		alert (q.name + " " + i + " " + n); //
		q.cols = Math.round((x/8)-50);
		q.rows = Math.round(y/250);
	 }
	 
	 x = (x-200)/2;
	 
	 n = document.getElementById('who');
	 n.width = x;	
	 n = document.getElementById('email');
	 n.width = x;
	 
}
 
function showStats (someUser) {
	
		var url = "http://talks.sahajayogaonline.com/cgi-bin/Stats.pl";
		var typeOfStats = 'Feedback'; // may parametrize this later
		
		$("#statsDiv").load(url, { user: someUser, statsType: typeOfStats});
		
}

function sendCreds() {
	//	Send user ID and password in a somewhat obfuscated form to the server.
	
	var uid=$("#cred1").val();
	var cpw=$("#cred2").val();
	var rst=$("#randomSpan").attr("random");
	var rnn=parseInt($("#randomSpan").attr("randint"));
	
	if (1 == 1) {
		var url = "http://talks.sahajayogaonline.com/cgi-bin/SimpleForm.pl?user=" + uid + "&passwd=" + cpw;
		window.location.href = url;
		return 1;
	}	
	
	//	Cover our tracks a bit:
	
	$("#randomSpan").remove();
	$("#Login").removeAttr("onclick");
	
	var toS;
	var toT = "";
	var s;
	
	var foo="_1749063825QAYXSWEDCVFRTGBNHZUJMKIOLPpoilkjmnbuzthgfvcrewdsaxyq";
	
	switch (rnn) {
		case 0-30: toS = uid+rst+cpw;
		default: toS = cpw+rst+uid;
	}
	
	log("Unencrypted: " + toS);
	
	var l = toS.length;
	var i;
	
	for (i=0;i<l;i++) {
		s = parseInt(foo.indexOf(toS.substr(i,1)))+rnn+2*i;
		if (s>62) s -= 63;
		if (s>62) s -= 63;
		toT += foo.substr(s,1); 		
	}
	
	log("Encrypted: " + toT);
	
	var url = "http://talks.sahajayogaonline.com/cgi-bin/SimpleForm.pl?creds=" + toT;
	window.location.href=url;
	
}



				






