/**
 * @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...

//function getFeedback (event_id, event_name, event_date, event_location) // Calls feedback screen

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 video, or an MP4 on the site, in one of the popups

	var h = "<DIV class=drag-video><TABLE id='headertable' width='100%'><TR><TD align=left><B>" + eventTitle + "</B></TD><TD align=right><input class='press' type='button' value='Close' onclick='closeVideo()'></TD></TR></TABLE></DIV>";
	
	if (eventID.length > 9) {		//	Video is on YouTube
		h += "<object id='video' width='425' height='344'>";
		h += "<param name='movie' value='http://www.youtube.com/v/" + eventID + "&hl=en&fs=1'></param>";
		h += "<param name='allowFullScreen' value='true'></param>";
		h += "<param name='allowscriptaccess' value='always'></param>";
		h += "<embed src='http://www.youtube.com/v/" + eventID + "&hl=en&fs=1' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed>";
		h += "</object>";		
	} else {	//	Video is on our server - we use JW FLV Player		
		h += "<span id='preview'>The player will show in this paragraph</span>";
		h += "<script type='text/javascript' src='video/swfobject.js'></script>";
		h += "<script type='text/javascript'>";
		h += "var s1 = new SWFObject('video/player.swf','player','480','360','9');"; 
		h += "s1.addParam('allowfullscreen','true');";
		h += "s1.addParam('allowscriptaccess','always');";
		h += "s1.addParam('flashvars','file=" + eventID + ".mp4');";
		h += "s1.write('preview');";
		h += "</script>";
	}

	h += "<br>" + eventDate + ", " + eventPlace;
	
	$("#popup10").html(h).fadeIn("slow").draggable({
		handle: "div",
	});	//	since popup 10 is unlikely to be open...
	
	//	Set DIV width to match movie container width:
	
	var w = $("#video").width();
	$("#headertable").width(w-8);
	
}

function closeVideo() { // Close the video opened with showVideo
	
	$("#popup10").fadeOut("slow").html("").draggable({
		handle: "div",
		cursor: "default"
	});
	
}

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("Updated 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 "Fedback": ackFeedback();	//	Acknowledge feedback
							break;
						case "Donkey:": eatGrass(resp1);	//	Vulgar obfuscation
							break;
						default: alert(resp1);						
					}
					report();
				}
			}
			log("Sending request...");
			self.xmlHttpReq.send(strDetails); 
		}

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 resizeWindow(newWidth,newHeight) { // Resize window
	window.resizeTo(newWidth,newHeight);
	return;	
}

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

	log("Request to close popup " + popupId + " with parent " + parentId);
	
	//	Hide and empty the current popup, make draggable:
	
	var objId = $("#object_" + popupId).val();
	var userId = $("#user_" + popupId).val();
	var sessionId = $("#session_" + popupId).val();
	
	$("#popup" + popupId).hide("normal").html("").draggable({handle: "div"});
	
	//	If the parent of this popup was another popup, fade it back in:
	
	log("Closing from " + popupId + " with ID " + objId + " to " + parentId);
	log ("User: " + userId + ", session: " + sessionId);
		
	if (parentId > 0) {
		$("#popup" + parentId).fadeTo("normal", 1);
	
		//	Refresh the parent popup contents:
	
		var toEdit = $("#type_" + parentId).val();
		var grandParent = $("#parent_" + parentId).val();
	    objId = $("#object_" + parentId).val();
			
		log("Type " + toEdit + " Grandparent " + grandParent + " object " + objId + " user " + userId + " session " + sessionId );
		
		loadPopup(toEdit, objId, userId, sessionId, grandParent, parentId);
	} else {
	
		//	Update the main listing:		
		
		url = location.href;
		log("URL: " + url);
		var qry = "objId=" + objId + "&user=" + userId + "&session=" + sessionId;
		log("URL: " + url + ", qry:" + qry);
		
		xmlHttpPost(url, qry);
		
	}
	
	$("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.
	
	for (var i=1; i<11; i++) {
		document.write( "<DIV id=popup" + i + " class='popup'></DIV>");
		var xpos = 20 * i;
		xpos = xpos + "px";
		
		var clr = '#AAEEEE'; // Vary the colors to make the DIVs more attractive
	
		switch(i) {
			case 2: clr = '#CCCCEE'; break;
			case 3: clr = '#EEAAEE'; break;	
			case 4: clr = '#EECCCC'; break;
			case 5: clr = '#EEEEAA'; break;
			case 6: clr = '#BBFFFF'; break;
			case 7: clr = '#DDDDFF'; break;
			case 8: clr = '#FFBBFF'; break;
			case 9: clr = '#FFDDDD'; break;
			case 10: clr = '#FFFFFF'; break;
		}
		
		//	Set the initial position and background colour for the popup:
		
		var myStyle = 'left:' + xpos + '; top:' + xpos + '; background:' + clr + ';';
		
		$("#popup" + i).attr({
			style: myStyle
		}).hide();
		
	}
	
	
	//	Make all popups draggable using the drag handle:
	
	$(".popup").draggable({
		handle: "div",
//		dragPrevention: "a,input,textarea,table",
		cursor: "move"
	});
	
}

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;
	
	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 {
		var 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 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 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 updatePopup (popupId) { // Updates the content of a popup

	//	First identify which of the several forms on screen is being used:
	
//	alert("Updating popup " + popupId);

	$("#popup" + popupId).fadeTo("fast", 1);
	
	for (var k=0;k<20;k++) {
//		alert(k + " " + document.forms[k].id);
		if (document.forms[k].id == "easyForm_" + popupId) {
			var 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 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("makeChanges: " + 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 = "";
	
	//	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 + "|";
	}
	
	var allInputs = $("#easyForm_" + popupId + " > :input");
	
	log("Found " + $(allInputs).length + " inputs");
		
	//	Run through the fields, one by one:
	
	var 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("defaultValue");
		}
		
		if (curVal != oldVal) {
			log(oldVal + " => " + curVal);
			if (commaWritten == 0) {
				commaWritten = 1;
				if (objectId != 0) {
					histText = histText + "Updated by " + currentUser + " " + document.lastModified;
				}
			}
			
			curVal = hformat(curVal);
			oldVal = hformat(oldVal);
			
			if (commaWritten == 1) {
				if (objectId != 0) {
					histText = histText + "<BR><B>" + fieldName + ":</B> " + oldVal + " -QamphashQ62QsemicolonQ " + curVal;							
				}
			}			
			
			//	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 + "|";
		}		
	})
		
	if (commaWritten==0) {
		alert("No changes made.");
		return;
	}
	
	qry = session + "|" + qry + "history=" + histText;
	
	log(qry);
	report();

	currentPopup = popupId;
	
//	alert("Current: " + currentPopup);
	
	//	Make the form look as though it has been disabled:
	
	$("#popup" + popupId).fadeTo("fast", 0.8);
	xmlHttpPost(url, "w=" + qry);
	
	return;
}

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 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});
		
}

var selectedRow;




