
/*******************/
/*  Control Panel  */
/*******************/

function valueChanged (inputID) {
	$("#" + inputID + "_changed").val(1);
}

function saveEntity (formID) {
	$("#formID").submit();
}

function scrollMenuLeft () {
	scrollMenu(300, -1200, 0);
}

function scrollMenuRight () {
	scrollMenu(-300, -100, 0);
}

function scrollMenu (amount, min, max) {
	var left = $("#menubar_carrier").css("left");
	left = left.substring(0, left.length-2);
	left = Number(left) + Number(amount);
	if (left < min || left > max)
		return;
	left = left + "px";
	$("#menubar_carrier").stop().animate({ left: left }, "slow");
}

/*********************/
/*  Update Database  */
/*********************/

function updateDatabase (tableName, entityID) {
	var i = 1;
	var params = "table_name=" + tableName;
	while (typeof($("#incompatible_field_name_" + i).val()) != "undefined") {
		params += "&field_name_" + i + "=" + $("#incompatible_field_name_" + i).val();
		i++;
	}
	$.post("schema/add_database_field.php", params, function (response) { updateDatabaseCallback(tableName, response); });
}

function updateDatabaseCallback (tableName, response) {
	$(".warning").slideUp();
	$("#" + tableName + "_notes").html(response).slideDown();
}

/************/
/*  Search  */
/************/

function search (tableName) {
	var searchIn = $("#search_in").val();
	var operator = $("#operator").val();
	var keywords = $("#keywords").val();
	if (keywords == "")
		return;

	window.location = "control_panel.php?table=" + tableName + "&search_in=" + searchIn + "&op=" + escape(operator) + "&search_for=" + escape(keywords);
}

/***************************/
/*  Copy Top-Level Record  */
/***************************/

function copyEntity (tableName) {
	var entityID = $("#" + tableName + "_ID").val();
	$("#" + tableName + "_ID").val("");		// Clear table ID to force re-insertion.
	$("#source_page").val("");			// Clear pre-defined return-to page.
	if (!window[tableName + "Validation"](""))	// Call Validation function reflectively. "": No table suffix
		$("#" + tableName + "_ID").val(entityID);	// Form validation failed. Reset table ID.
}

/*****************************/
/*  Delete Top-Level Record  */
/*****************************/

function deleteEntity (tableName, entityID, subrecordDivID) {
	var confirmation = confirm("Are you sure you want to delete this record? This operation cannot be undone.");
	if (!confirmation)
		return;
	else {
		$.post("schema/delete_entity.php", { table: tableName, entity_ID: entityID }, function () { deleteEntityCallback(tableName, subrecordDivID); });
	}
}

function deleteEntityCallback (tableName, subrecordDivID) {
	if (typeof(subrecordDivID) != "undefined") {
		$("#" + subrecordDivID).slideUp("slow", function () { $("#" + subrecordDivID).remove() });
	}
	else window.location = "control_panel.php?func=browse&table=" + tableName;
}

/**************************/
/*  Delete Uploaded File  */
/**************************/

function deleteUploadedFile (tableName, fieldName, entityID, filename) {
	var confirmation = confirm("Are you sure you want to delete this file? This operation cannot be undone.");
	if (!confirmation)
		return;
	else {
		$.post("schema/delete_uploaded_file.php", { table_name: tableName, field_name: fieldName, entity_ID: entityID, filename: filename }, function () { deleteUploadedFileCallback(fieldName); });
	}
}

function deleteUploadedFileCallback (fieldName) {
	$("#preview_" + fieldName).fadeOut("slow");
	$("#delete_" + fieldName).fadeOut("slow");
}

/*******************************/
/*  Manipulate Uploaded Image  */
/*******************************/

function manipulateImage (imageURL) {
	formatImage(imageURL, "", "");
}

function formatImage (imageURL, width, height) {
	var params = "max_width=750&image_URL=" + imageURL + "&width=" + width + "&height=" + height + "&output_image=" + imageURL;
	openInnerWindow("format_image", "schema/embedded_image_manipulator.php", 970, 550, "Crop Image", params);
}

/****************************/
/*  Preview Uploaded Image  */
/****************************/

function imagePreview (event, imageURL) {
	var x = event.clientX + 10;
	var y = event.clientY + 10;
	var imageHTML = "<IMG src='" + imageURL + "' style='width: 150px;'>";

	if ($("#image_preview").is("DIV"))
		$("#image_preview").stop().html(imageHTML).css("left", x + "px").css("top", y + "px").fadeIn();
	else $("<DIV id=\"image_preview\">" + imageHTML + "</DIV>").css("position", "absolute").css("left", x + "px").css("top", y + "px").appendTo("body");
	// $.post("ajax/preview_image.php", { image_URL: imageURL }, function (response) { imagePreviewCallback(response, x, y) });
}

function closeImagePreview () {
	$("#image_preview").stop().fadeOut();
	// $("body").remove($("#image_preview"));
}

/********************/
/*  Display Errors  */
/********************/

function registerErrors (errorDivID, errors) {
	var errorMessage = "The following errors occured when trying to submit:<UL>";
	for (var i in errors) {
		errorMessage += "<LI>" + errors[i];
	}
	errorMessage += "</UL>";
	$("#" + errorDivID).html(errorMessage).fadeIn("slow");
}

/***********************************/
/*  Sub-table Record Manipulation  */
/***********************************/

function showSubrecords (tableName, fieldName) {
	$("#show_" + tableName + "_" + fieldName).slideUp("slow");
	$("#" + tableName + "_" + fieldName + "_container").slideDown("slow");
}

function hideSubrecords (fieldName, tableName) {
}

function showSubrecordForm (tableName, fieldName, recordNum) {
	$("#" + tableName + "_" + fieldName + "_" + recordNum + "_form").slideDown("slow");
	$("#" + tableName + "_" + fieldName + "_" + recordNum + "_link").attr("href", "javascript: hideSubrecordForm('" + tableName + "', '" + fieldName + "', " + recordNum + ")");
}

function hideSubrecordForm (tableName, fieldName, recordNum) {
	$("#" + tableName + "_" + fieldName + "_" + recordNum + "_form").slideUp("slow");
	$("#" + tableName + "_" + fieldName + "_" + recordNum + "_link").attr("href", "javascript: showSubrecordForm('" + tableName + "', '" + fieldName + "', " + recordNum + ")");
}

function incrementNumSubtableRecords (fieldName) {
	return alterNumSubtableRecords(fieldName, 1);
}

function decrementNumSubtableRecords (fieldName) {
	/* Do not change the number of records - that way, if one is deleted from the middle, we know the range of
	   valid records to update. */
	return alterNumSubtableRecords(fieldName, 0); // -1);
}

function alterNumSubtableRecords (fieldName, delta) {
	var numRecords = $("#num_" + fieldName + "s").val();
	numRecords = Number(numRecords) + Number(delta);
	$("#num_" + fieldName + "s").val(numRecords);
	return numRecords;
}

function addExistingSubtableRecord (tableName, fieldName, recordID) {
	closeInnerWindow("subtable_records");
	addSubtableRecord(tableName, fieldName, recordID);
}

function loadExistingSubtableRecords (parentTable, fieldName) {
	var params = "table_name=" + parentTable + "&field_name=" + fieldName;
	openInnerWindow("subtable_records", "schema/load_subtable_records.php", 400, "", "Select Existing Record", params, "", "", 1);
}

function addSubtableRecord (tableName, fieldName, recordID) {
	showSubrecords(tableName, fieldName);
	if (typeof(recordID) == "undefined")
		recordID = "";
	var numRecords = incrementNumSubtableRecords(fieldName);
	$.getJSON("schema/add_subtable_record.php", { table_name: tableName, field_name: fieldName, record_num: numRecords, record_ID: recordID }, function (json) { addSubtableRecordCallback(fieldName, tableName, numRecords, json); });
}

function addSubtableRecordCallback (fieldName, tableName, numRecords, json) {
	var form = json.form;
	var script = json.script;
	$("#" + tableName + "_" + fieldName + "_container").append(form);
	$(script).appendTo("head");
}

function deleteSubtableRecord (fieldName, tableName, entityID, recordNum) {
	var confirmation = confirm("Are you sure you want to delete this record? This operation cannot be undone.");
	if (!confirmation)
		return;
	else {
		decrementNumSubtableRecords(fieldName);
		$.post("schema/delete_entity.php", { table: tableName, entity_ID: entityID }, function () { deleteSubtableRecordCallback(fieldName, tableName, recordNum); });
	}
}

function deleteSubtableRecordCallback (tableName, fieldName, recordNum) {
	$("#" + tableName + "_" + fieldName + "_" + recordNum).slideUp("slow", function () { $("#" + fieldName + "_" + tableName + "_" + recordNum).remove(); });
}

function getExistingSubtableRecords (fieldName, fieldLabel, tableName) {
	$.post("schema/get_existing_subtable_records.php", { field_name: fieldName, field_label: fieldLabel, table_name: tableName }, function (response) { getExistingSubtableRecords(fieldName, fieldLabel, tableName, response); });
}

function getExistingSubtableRecordCallback (fieldName, fieldLabel, tableName, response) {
	openClientWindow("existing_" + tableName, response, 450, 500, "", "", "", 1);
}

function loadExistingSubtableRecord (recordID, fieldName, tableName) {
	closeClientInnerWindow("existing_" + tableName);
	var numRecords = incrementNumSubtableRecords(fieldName);
	$.getJSON("schema/add_subtable_record.php", { record_ID: recordID, record_num: numRecords, table_name: tableName }, function (json) { addSubtableRecordCallback(fieldName, tableName, numRecords, json); });
}

function unlinkSubrecord (tableName, fieldName, recordID, subrecordID, recordNum) {
	var confirmation = confirm("Are you sure you want to unlink this record? This will not actually delete the record, just disassociate it.");
	if (!confirmation)
		return;

	$.post("schema/unlink_subrecord.php", { table_name: tableName, field_name: fieldName, entity_ID: recordID, link_ID: subrecordID }, function () { deleteSubtableRecordCallback(tableName, fieldName, recordNum); });
}

/*****************************/
/*  Kernel / File Selection  */
/*****************************/

function browseFile (tableName, fieldName, directory, extensions) {
	if (!extensions)
		extensions = "";
	if (!directory)
		directory = "";

	openInnerWindow("file_browse_window", "schema/select_file.php", 800, "", "Select File", "table_name=" + tableName +"&field_name=" + fieldName + "&directory=" + directory + "&extensions=" + extensions, "", "", 1);
}

function chooseFile (event, browserName, filename, fileID) {
	var inputID = $("#browse_input").val();

	$("#" + inputID + "_changed").val(1);
	$("#" + inputID).val(filename.substring(3, filename.length));
	closeInnerWindow("file_browse_window");
}

/*********************/
/*  Manipulate Copy  */
/*********************/

function addCopy () {
	var copyName = "";
	while (copyName == "") {
		copyName = prompt("Please enter a name for this block of copy. No special characters please.");
		if (copyName == null)
			return;
		var validName = copyName.match(/^[a-zA-Z]+[a-zA-Z0-9( )]*$/);
		if (!validName) {
			copyName = "";
		}
	}
	$.post("schema/add_copy.php", { copy_name: copyName }, function () { window.location = window.location; });
}


/*************************/
/*  Manipulate Settings  */
/*************************/

function addSetting () {
	var settingName = "";
	while (settingName == "") {
		settingName = prompt("Please enter a name for this setting. No special characters please.");
		if (settingName == null)
			return;
		var validName = settingName.match(/^[a-zA-Z]+[a-zA-Z0-9( )]*$/);
		if (!validName) {
			settingName = "";
		}
	}
	$.post("schema/add_setting.php", { setting_name: settingName }, function () { window.location = window.location; });
}


/***********************/
/*  Manipulate Schema  */
/***********************/

function createDatabaseTable (tableName) {
	$.post("schema/create_database_table.php", { table_name: tableName }, function (response) { createDatabaseTableCallback(response, tableName); });
}

function createDatabaseTableCallback (response, tableName) {
	$(".warning").slideUp("slow");
}

function validateTableSchema () {
	var tableName = $("#table_label").val();
	if (tableName == "") {
		registerErrors("schema_error", new Array("Please specify a 'Table Label'"));
		return false;
	}

	var validName = tableName.match(/^[a-zA-Z]+[a-zA-Z0-9( )]*$/);
	if (!validName) {
		registerErrors("schema_error", new Array("Special characters are not permitted in 'Table Label'"));
		return false;
	}
	$("#schema_form").attr("action", "schema/save_database_table.php").submit();
	return true;
}

function editSchemaTableChanged () {
	window.location = "control_panel.php?func=schema&table=" + $("#table").val();
}

function addDatabaseField (tableName) {
	var fieldName = "";
	while (fieldName == "") {
		fieldName = prompt("Please enter the name of the field. No spaces or special characters, please.");
		if (fieldName == null)
			return;

		// Check 'fieldName' with regexp
		if (!fieldName.match(/^[a-zA-Z]+[a-zA-Z0-9_]*$/))
			fieldName = "";
	}
	var fieldNum = $("#num_fields").val();
	fieldNum = Number(fieldNum) +1;
	$("#num_fields").val(fieldNum);
	$.post("schema/get_schema_field_row.php", { table_name: tableName, field_num: fieldNum, field_name: fieldName }, function (response) { addDatabaseFieldCallback(fieldName, response); });
}

function addDatabaseFieldCallback (fieldName, response) {
	$("#fields").append(response);
	$("#table_sort").append("<OPTION value='" + fieldName + "'>" + fieldName + "</OPTION>");
}

function addFieldModifier (fieldName) {
	
}

function dropDatabaseField (table, field) {
	var confirmation = confirm("Are you sure you want to delete this field? All data associated with this field will be permanently lost. This operation cannot be undone.");
	if (!confirmation)
		return;

	$.post("schema/delete_database_field.php", { table_name: table, field_name: field }, function () { dropDatabaseEntityCallback(field); });
}

function dropDatabaseEntityCallback (entityID) {
	$("#" + entityID).slideUp("fast", function() { $("#" + entityID).remove() });
}

function dropDatabaseFieldModifier (table, field, fieldNum, modifierNum) {

}


function dropDatabaseTable (tableName) {
	var failureMessage = "Verification mismatch. The table '" + tableName + "' will not be dropped.";
	var message = "You are about to drop the database table '" + tableName + "'. This operation will delete all data associated with the table and cannot be undone.";
	var success = function () { $.post("schema/drop_database_table.php", { table_name: tableName }, function () { window.location = "control_panel.php?func=schema" }) };
	verifyOperation(message, success, failureMessage);
}

function verifyOperation (message, verifiedCallback, failureMessage) {
	var alpha = "abcdefghijklmnopqrstuvwxyx1234567890";
	var verificationText = "";
	for (var i=0; i<6; i++) {
		var index = Math.floor(Math.random()*36);
		verificationText += alpha[index];
	}
	var userVerification = prompt(message + " Please enter the following verification text to proceed:\n\n" + verificationText);
	if (userVerification == null)
		return;

	else if (userVerification != verificationText) {
		if (typeof(failureMessage) != "undefined")
			alert(failureMessage);
		return;
	}
	else {
		verifiedCallback.call(this);
	}
}

/******************/
/*  Date Chooser  */
/******************/

function loadDateChooser (inputID, month, year, time) {
	// closeInnerWindow("date_chooser");
	if (typeof(month) == "undefined")
		month = "";

	if (typeof(year) == "undefined")
		year = "";

	if (typeof(time) == "undefined")
		time = 0;

	var params = "input_ID=" + inputID + "&month=" + month + "&year=" + year + "&time=" + time;
	closeScreen("date_chooser");
	openInnerWindow("date_chooser", "schema/load_date_chooser.php", 300, 350, "Date Chooser", params, "", "", 1, 1);
}

function chooseDate (calendarName, dayNum, dayEpoch) {
	var date = new Date();
	date.setTime(dayEpoch*1000);	// Convert to milis
	$("#chooser_month").val(date.getMonth()+1);	// getMonth returns 0-11
	$("#chooser_day").val(date.getDate());
	$("#chooser_year").val(date.getFullYear());
	$(".day").removeClass("selected_day");
	$("#" + calendarName + "_" + dayNum).addClass("selected_day");
}

function selectDate (inputID) {
	var month = $("#chooser_month").val();
	var day = $("#chooser_day").val();
	var year = $("#chooser_year").val();
	var hour = $("#chooser_hour").val();

	$("#" + inputID + "_changed").val(1);

	if (day == "") {
		$("#chooser_day").addClass("error_input");
		return;
	}

	var inputValue = month + "/" + day + "/" + year;
	if (typeof(hour) != "undefined") {
		var minute = $("#chooser_minute").val();
		var second = $("#chooser_second").val();
		var amPm = $("#chooser_am_pm").val();
		if (Number(hour) != 12)
			hour = Number(hour) + Number(amPm);
		inputValue += " " + hour + ":" + minute + ":" + second;
	}
	$("#" + inputID).val(inputValue);
	closeInnerWindow("date_chooser");
}