/***********************************************************************
 * phppp.js - Javascript functions to go with the PHPPP_DB library	 *
 *                                                                     *
 * Author: Seth Davenport                                              *
 * Version 0.5.                                                        *
 * Date: 2003-05-20                                                    *
 * TODO  Rework g_checkState to support multiple DbStp's on one page.  *
 ***********************************************************************/

// The current state of the 'super checkbox':
// Determines whether it will check or uncheck all 
// other checkboxes in its DB_SortedTablePane.
var g_checkState = true;
 
/* 
 * Checks all checkboxes belonging to a DB_SortedTablePane object 
 * (also used by DB_TableSearchPane objects since they inherit from
 * the DB_SortedTablePane class).
 */
function DbStp_checkAll(DbStp_ID) {
	// Array containing all input controls on this page.
	var inputObjs = document.getElementsByTagName('input');
	if (!inputObjs) return false;
	
	for(var i=0; i<inputObjs.length; i++) {
		var elem = inputObjs[i];
		if ((elem.type == "checkbox") 
				&& (elem.name.substring(0, DbStp_ID.length) == DbStp_ID)) {
			elem.checked = g_checkState;
		}
	}
	g_checkState = (!g_checkState);
	
	return false;
}

/*
 * Changes the page start position as selected by the page selector
 * box.
 */
function DbStp_goToPage(DbStp_ID, targetURL) {
	var matchingElements = document.getElementsByName(DbStp_ID + "_pageSelect");
	if ((!matchingElements) || (matchingElements[0].type != 'select-one'))
		return false;
	var startPos = parseInt(matchingElements[0].value);
	// Ensure that startPos has a legal value.
	if (startPos < 0) {
		return reportError("you must select a non-negative integer for the start position.");
	}
	
	document.location = targetURL + "&" + DbStp_ID
			+ "_startPos=" + matchingElements[0].value;
	return false;
}

/*
 * Changes the number of rows displayed.  Also changes the start position
 * if pagination is turned off.
 */
function DbStp_toolBarBtnClick(DbStp_ID, targetURL, paginationOn) {
	// Check that paginationOn is in fact a boolean value.
	if ((paginationOn != true) && (paginationOn != false)) 
		return false;
		
	var matchingElements;
	var startClause = "";
	
	// If the browse buttons are active instead of the page selector,
	// we need to error check the start position field as well.
	if(!paginationOn) {
		matchingElements = document.getElementsByName(DbStp_ID + "_startPos");
		if ((!matchingElements) || (matchingElements[0].type != 'text'))
			return false;
		var startPos = parseInt(matchingElements[0].value);
		// Check that the new startPos is a positive integer.
		if ((isNaN(startPos)) || (startPos < 0)) {
			alert("Please enter an integer greater than zero as the starting position.");
			return false;
		}
		startClause = "&" + DbStp_ID + "_startPos=" + startPos;
	}
	
	// Get the new number of rows to display.
	matchingElements = document.getElementsByName(DbStp_ID + "_numRows");
	if ((!matchingElements) || (matchingElements[0].type != 'text'))
		return false;
	var numRows = parseInt(matchingElements[0].value);
	// Check that the new numRows is a positive integer.
	if ((isNaN(numRows)) || (numRows < 1)) {
		alert("Please enter an integer greater than zero as the number of rows.");
		return false;
	}
	// Refresh the page.
	document.location = targetURL + "&" + DbStp_ID
			+ "_numRows=" + matchingElements[0].value + startClause;
	return false;
}

/** 
 * Brings up a pop-up window allowing the user to edit a 'text'
 * type field in the DB_SortedTablePane.
 */
function DbStp_TextArea(DbStp_ID, colName, content, recordID, isRequired, targetURL) {
	// Check that isRequired is in fact a boolean value.
	if ((isRequired != true) && (isRequired != false)) 
		return false;
	
	// Create a pop-up window.
	var title = "Edit the '" + colName + "' field";
	var windowHandle = centerWindow("", DbStp_ID+"_"+colName+"_editor_recID"+recordID, 200,250);
	if (windowHandle.focus)
		windowHandle.focus();

	// Ensure that the child window has a reference to its parent.
	if(windowHandle.opener == null)
		windowHandle.opener = self;
		
	// Display the cell's edit form.	
	windowHandle.document.write('<html>\n<head>\n<title>'+title+'</title>\n</head>\n')
	windowHandle.document.write('<body>\n');
	windowHandle.document.write('<div align="center">\n');
	windowHandle.document.write('<p>'+title+'</p>\n');
	windowHandle.document.write('<textarea id="content" rows="7" cols="18">'+content+'</textarea>\n');
	windowHandle.document.write("<input type=\"hidden\" id=\"colName\" value=\""
			+colName+"\">\n");
	windowHandle.document.write("<input type=\"hidden\" id=\"targetURL\" value=\""
			+escape(targetURL)+"\">\n");
	windowHandle.document.write("<input type=\"hidden\" id=\"DbStp_ID\" value=\""
			+DbStp_ID+"\">\n");
	windowHandle.document.write("<input type=\"hidden\" id=\"recID\" value=\""
			+recordID+"\">\n");
	windowHandle.document.write("<input type=\"hidden\" id=\"isRequired\" value=\""
			+isRequired+"\">\n");
	windowHandle.document.write("<br><input type=\"button\" onClick=\"opener.DbStp_TextAreaSubmit(self"
		+");\" value=\"Submit Changes\">\n");
	windowHandle.document.write('</div>\n</body>\n</html>\n');
	
	return false; 
}

/**
 * Passes the changes registered in an text edit pop-up window
 * to the php script.  The windowHandle argument is a reference
 * to that pop-up window.
 */
function DbStp_TextAreaSubmit(windowHandle) {
	if (!windowHandle) return false;
	var content = windowHandle.document.getElementById('content').value;
	var colName = windowHandle.document.getElementById('colName').value;
	var DbStp_ID = windowHandle.document.getElementById('DbStp_ID').value;
	var recID = windowHandle.document.getElementById('recID').value;
	var isRequired = windowHandle.document.getElementById('isRequired').value;
	var targetURL = windowHandle.document.getElementById('targetURL').value;
	
	if ((isRequired != "true") && (isRequired != "false"))
		return reportError("Illegal value for variable isRequired: "+isRequired);
	if ((!content) && (isRequired == "true"))
		return reportError("This field is required!  Please enter some text.");
	if (!colName) 
		return reportError("colName is blank!  I don't know which field to update.");
	if (!DbStp_ID) 
		return reportError("DbStp_ID is blank! I don't know which table to update.");
	if (isNaN(recID)) 
		return reportError("recID is not a number! Cannot update table.");
	if (!targetURL) 
		return reportError("targetURL is blank! Cannot update table.");
		
	// Tell the php script to update the table and re-display it.
	window.location = unescape(targetURL)+DbStp_ID+"_recID="+recID+"&f0="+colName
			+"&v0="+escape(content)+"&r0="+isRequired;
	windowHandle.close();
	return false;
}

/**
 * Validates a modified record in a DB_SortedTablePane and tells 
 * the php script to save the changes.
 */
function DbStp_set(DbStp_ID, recID, editableFields, targetURL) {
	var typeObj;
	var valueObj;
	var requiredObj;
	var value;
	var urlExt = "";
	
	if (!editableFields) return reportError("editableFields param is null!");
	
	// Input validation
	for(var i=0; i<editableFields.length; i++) {
		typeObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_type");
		if (!typeObj) return reportError("Missing type info for "+editableFields[i]
				+".  stopping script.");
		requiredObj = document.getElementById(DbStp_ID+"_"+editableFields[i]
				+"_required");
		if (!requiredObj) return reportError("Missing 'required' info for "+editableFields[i]
				+".  stopping script.");
		
		// Ensure that the user has entered appropriate data in the fields.
		switch (typeObj.value) {
			case "int":
				valueObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID);
				if(!valueObj) return reportError("Missing value field for "+editableFields[i]
						+".  stopping script.");
				value = parseInt(valueObj.value);
				if (isNaN(value)) return reportError("Please enter an integer for the "
						+editableFields[i]+" field.");
				break;
			case "varchar":
			case "enum":
			case "set":
				valueObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID);
				if(!valueObj) return reportError("Missing value field for "+editableFields[i]
						+".  stopping script.");
				value = valueObj.value;
				break;
			case "date":
				var yearObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID+"_year");
				var monthObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID+"_month");
				var dayObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID+"_day");
				if (!yearObj) 
					return reportError("Stopping script: "+editableFields[i]+"_year field missing.");
				if (!monthObj) 
					return reportError("Stopping script: "+editableFields[i]+"_month field missing.");
				if (!dayObj) 
					return reportError("Stopping script: "+editableFields[i]+"_day field missing.");
				if (isNaN(yearObj.value))
					return reportError("Please enter a number in the "+editableFields[i]+" year field.");
				value = yearObj.value+"/"+monthObj.value+"/"+dayObj.value;
				break;
			case "time":
				var hourObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID+"_hour");
				var minuteObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID+"_minute");
				var secondObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID+"_second");
				if (!hourObj) 
					return reportError("Stopping script: "+editableFields[i]+"_hour field missing.");
				if (!minuteObj) 
					return reportError("Stopping script: "+editableFields[i]+"_minute field missing.");
				if (!secondObj) 
					return reportError("Stopping script: "+editableFields[i]+"_second field missing.");
				value = hourObj.value+":"+minuteObj.value+":"+secondObj.value;
				break;
			case "bool":
				valueObj = document.getElementById(DbStp_ID+"_"+editableFields[i]+"_"
						+recID);
				if(!valueObj) return reportError("Missing value field for "
						+editableFields[i]+".  stopping script.");
				value = parseInt(valueObj.value);
				if ((value != 0) && (value != 1)) 
					return reportError("Please enter either 1 or 0 for the "
						+editableFields[i]+" field.");
				break;
			default:
				continue;
		}
		
		// Ensure that required fields are filled out.
		if ((requiredObj.value == "true") && (value == null))
			reportError(editableFields[i]+" is a required field.  Please enter a value.");
		
		// Construct the URL which will update the table.
		urlExt += ("f"+i+"="+editableFields[i]+"&"
				+"v"+i+"="+escape(value)+"&r"+i+"="+requiredObj.value+"&");
	}
	
	// Update the table.
	window.location = unescape(targetURL)+DbStp_ID+"_recID="+recID+"&"+urlExt;
	return false;
}

/** 
 * Performs the operation 'op' on an item in a Db_ListWidget.
 */
function DbLw_operItem(widgetName, targetURL, op) {
	var radioObjs = document.getElementsByName(widgetName+"_sel");
	if (radioObjs == false) {
		alert("Error: invalid select element specified.");
		return false;
	}
	else {
		var itemID = false;
		
		for (var i=0; i<radioObjs.length; i++) {
			if (radioObjs[i].checked) {
				itemID = radioObjs[i].value;
				break;
			}
		}
		
		if (!itemID) {
			alert("You did not select anything!");
			return false;
		}
		if (parseInt(itemID) < 0) {
			alert("You made an invalid selection!");
			return false;
		}
		
		// Send the requested change to the server side script.
		window.location = unescape(targetURL)+widgetName+'_aID='+op+'&'
				+'id='+itemID;
		return true;
	}
}

/**
 * Opens a centred pop-up window and returns its windowHandle.
 * Modified by Seth Davenport from Martin Webb's original source
 * found at http://tech.irt.org/articles/js128/index.htm#2.2
 */
function centerWindow(location, title, width, height) {
    if (document.all)
        var xMax = screen.width, yMax = screen.height;
    else
        if (document.layers)
            var xMax = window.outerWidth, yMax = window.outerHeight;
        else
            var xMax = 640, yMax=480;
    var xOffset = (xMax - 200)/2, yOffset = (yMax - 200)/2;
    return window.open(location,title, 'width='+width+',height='+height+
	 		',screenX='+xOffset+',screenY='+yOffset+',top='+yOffset+
			',left='+xOffset+'');
}

/**
 * Displays a pop-up informing the user that an error has occurred.
 */
function reportError(message) {
	alert("An error has occurred in this script: "+message);
	return false;
}
