<?php

// Data functions (insert, update, delete, form) for table courses

// This script and data application were generated by AppGini 5.76
// Download AppGini for free from https://bigprof.com/appgini/download/

function courses_insert(){
	global $Translation;

	// mm: can member insert record?
	$arrPerm=getTablePermissions('courses');
	if(!$arrPerm[1]){
		return false;
	}

	$data['course_name'] = makeSafe($_REQUEST['course_name']);
		if($data['course_name'] == empty_lookup_value){ $data['course_name'] = ''; }
	$data['description'] = makeSafe($_REQUEST['course_name']);
		if($data['description'] == empty_lookup_value){ $data['description'] = ''; }
	$data['instructor_id'] = makeSafe($_REQUEST['instructor_id']);
		if($data['instructor_id'] == empty_lookup_value){ $data['instructor_id'] = ''; }
	$data['lab_id'] = makeSafe($_REQUEST['lab_id']);
		if($data['lab_id'] == empty_lookup_value){ $data['lab_id'] = ''; }
	$data['start_date'] = intval($_REQUEST['start_dateYear']) . '-' . intval($_REQUEST['start_dateMonth']) . '-' . intval($_REQUEST['start_dateDay']);
	$data['start_date'] = parseMySQLDate($data['start_date'], '');
	$data['end_date'] = intval($_REQUEST['end_dateYear']) . '-' . intval($_REQUEST['end_dateMonth']) . '-' . intval($_REQUEST['end_dateDay']);
	$data['end_date'] = parseMySQLDate($data['end_date'], '');
	$data['start_time'] = makeSafe($_REQUEST['start_time']);
		if($data['start_time'] == empty_lookup_value){ $data['start_time'] = ''; }
	$data['start_time'] = time24($data['start_time']);
	$data['end_time'] = makeSafe($_REQUEST['end_time']);
		if($data['end_time'] == empty_lookup_value){ $data['end_time'] = ''; }
	$data['end_time'] = time24($data['end_time']);
	$data['mon'] = makeSafe($_REQUEST['mon']);
		if($data['mon'] == empty_lookup_value){ $data['mon'] = ''; }
	$data['tue'] = makeSafe($_REQUEST['tue']);
		if($data['tue'] == empty_lookup_value){ $data['tue'] = ''; }
	$data['wed'] = makeSafe($_REQUEST['wed']);
		if($data['wed'] == empty_lookup_value){ $data['wed'] = ''; }
	$data['thu'] = makeSafe($_REQUEST['thu']);
		if($data['thu'] == empty_lookup_value){ $data['thu'] = ''; }
	$data['fri'] = makeSafe($_REQUEST['fri']);
		if($data['fri'] == empty_lookup_value){ $data['fri'] = ''; }
	$data['sat'] = makeSafe($_REQUEST['sat']);
		if($data['sat'] == empty_lookup_value){ $data['sat'] = ''; }
	$data['sun'] = makeSafe($_REQUEST['sun']);
		if($data['sun'] == empty_lookup_value){ $data['sun'] = ''; }
	$data['fees'] = makeSafe($_REQUEST['fees']);
		if($data['fees'] == empty_lookup_value){ $data['fees'] = ''; }

	// hook: courses_before_insert
	if(function_exists('courses_before_insert')){
		$args=array();
		if(!courses_before_insert($data, getMemberInfo(), $args)){ return false; }
	}

	$o = array('silentErrors' => true);
	sql('insert into `courses` set       `course_name`=' . (($data['course_name'] !== '' && $data['course_name'] !== NULL) ? "'{$data['course_name']}'" : 'NULL') . ', `description`=' . (($data['description'] !== '' && $data['description'] !== NULL) ? "'{$data['description']}'" : 'NULL') . ', `instructor_id`=' . (($data['instructor_id'] !== '' && $data['instructor_id'] !== NULL) ? "'{$data['instructor_id']}'" : 'NULL') . ', `lab_id`=' . (($data['lab_id'] !== '' && $data['lab_id'] !== NULL) ? "'{$data['lab_id']}'" : 'NULL') . ', `start_date`=' . (($data['start_date'] !== '' && $data['start_date'] !== NULL) ? "'{$data['start_date']}'" : 'NULL') . ', `end_date`=' . (($data['end_date'] !== '' && $data['end_date'] !== NULL) ? "'{$data['end_date']}'" : 'NULL') . ', `start_time`=' . (($data['start_time'] !== '' && $data['start_time'] !== NULL) ? "'{$data['start_time']}'" : 'NULL') . ', `end_time`=' . (($data['end_time'] !== '' && $data['end_time'] !== NULL) ? "'{$data['end_time']}'" : 'NULL') . ', `mon`=' . (($data['mon'] !== '' && $data['mon'] !== NULL) ? "'{$data['mon']}'" : 'NULL') . ', `tue`=' . (($data['tue'] !== '' && $data['tue'] !== NULL) ? "'{$data['tue']}'" : 'NULL') . ', `wed`=' . (($data['wed'] !== '' && $data['wed'] !== NULL) ? "'{$data['wed']}'" : 'NULL') . ', `thu`=' . (($data['thu'] !== '' && $data['thu'] !== NULL) ? "'{$data['thu']}'" : 'NULL') . ', `fri`=' . (($data['fri'] !== '' && $data['fri'] !== NULL) ? "'{$data['fri']}'" : 'NULL') . ', `sat`=' . (($data['sat'] !== '' && $data['sat'] !== NULL) ? "'{$data['sat']}'" : 'NULL') . ', `sun`=' . (($data['sun'] !== '' && $data['sun'] !== NULL) ? "'{$data['sun']}'" : 'NULL') . ', `fees`=' . (($data['fees'] !== '' && $data['fees'] !== NULL) ? "'{$data['fees']}'" : 'NULL'), $o);
	if($o['error']!=''){
		echo $o['error'];
		echo "<a href=\"courses_view.php?addNew_x=1\">{$Translation['< back']}</a>";
		exit;
	}

	$recID = db_insert_id(db_link());

	// hook: courses_after_insert
	if(function_exists('courses_after_insert')){
		$res = sql("select * from `courses` where `course_id`='" . makeSafe($recID, false) . "' limit 1", $eo);
		if($row = db_fetch_assoc($res)){
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = makeSafe($recID, false);
		$args=array();
		if(!courses_after_insert($data, getMemberInfo(), $args)){ return $recID; }
	}

	// mm: save ownership data
	set_record_owner('courses', $recID, getLoggedMemberID());

	return $recID;
}

function courses_delete($selected_id, $AllowDeleteOfParents=false, $skipChecks=false){
	// insure referential integrity ...
	global $Translation;
	$selected_id=makeSafe($selected_id);

	// mm: can member delete record?
	$arrPerm=getTablePermissions('courses');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='courses' and pkValue='$selected_id'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='courses' and pkValue='$selected_id'");
	if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3){ // allow delete?
		// delete allowed, so continue ...
	}else{
		return $Translation['You don\'t have enough permissions to delete this record'];
	}

	// hook: courses_before_delete
	if(function_exists('courses_before_delete')){
		$args=array();
		if(!courses_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'];
	}

	// child table: enrollment
	$res = sql("select `course_id` from `courses` where `course_id`='$selected_id'", $eo);
	$course_id = db_fetch_row($res);
	$rires = sql("select count(1) from `enrollment` where `course_id`='".addslashes($course_id[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "enrollment", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "enrollment", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='courses_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='courses_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	sql("delete from `courses` where `course_id`='$selected_id'", $eo);

	// hook: courses_after_delete
	if(function_exists('courses_after_delete')){
		$args=array();
		courses_after_delete($selected_id, getMemberInfo(), $args);
	}

	// mm: delete ownership data
	sql("delete from membership_userrecords where tableName='courses' and pkValue='$selected_id'", $eo);
}

function courses_update($selected_id){
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('courses');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='courses' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='courses' and pkValue='".makeSafe($selected_id)."'");
	if(($arrPerm[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3){ // allow update?
		// update allowed, so continue ...
	}else{
		return false;
	}

	$data['course_name'] = makeSafe($_REQUEST['course_name']);
		if($data['course_name'] == empty_lookup_value){ $data['course_name'] = ''; }
	$data['description'] = makeSafe($_REQUEST['course_name']);
		if($data['description'] == empty_lookup_value){ $data['description'] = ''; }
	$data['instructor_id'] = makeSafe($_REQUEST['instructor_id']);
		if($data['instructor_id'] == empty_lookup_value){ $data['instructor_id'] = ''; }
	$data['lab_id'] = makeSafe($_REQUEST['lab_id']);
		if($data['lab_id'] == empty_lookup_value){ $data['lab_id'] = ''; }
	$data['start_date'] = intval($_REQUEST['start_dateYear']) . '-' . intval($_REQUEST['start_dateMonth']) . '-' . intval($_REQUEST['start_dateDay']);
	$data['start_date'] = parseMySQLDate($data['start_date'], '');
	$data['end_date'] = intval($_REQUEST['end_dateYear']) . '-' . intval($_REQUEST['end_dateMonth']) . '-' . intval($_REQUEST['end_dateDay']);
	$data['end_date'] = parseMySQLDate($data['end_date'], '');
	$data['start_time'] = makeSafe($_REQUEST['start_time']);
		if($data['start_time'] == empty_lookup_value){ $data['start_time'] = ''; }
	$data['start_time'] = time24($data['start_time']);
	$data['end_time'] = makeSafe($_REQUEST['end_time']);
		if($data['end_time'] == empty_lookup_value){ $data['end_time'] = ''; }
	$data['end_time'] = time24($data['end_time']);
	$data['mon'] = makeSafe($_REQUEST['mon']);
		if($data['mon'] == empty_lookup_value){ $data['mon'] = ''; }
	$data['tue'] = makeSafe($_REQUEST['tue']);
		if($data['tue'] == empty_lookup_value){ $data['tue'] = ''; }
	$data['wed'] = makeSafe($_REQUEST['wed']);
		if($data['wed'] == empty_lookup_value){ $data['wed'] = ''; }
	$data['thu'] = makeSafe($_REQUEST['thu']);
		if($data['thu'] == empty_lookup_value){ $data['thu'] = ''; }
	$data['fri'] = makeSafe($_REQUEST['fri']);
		if($data['fri'] == empty_lookup_value){ $data['fri'] = ''; }
	$data['sat'] = makeSafe($_REQUEST['sat']);
		if($data['sat'] == empty_lookup_value){ $data['sat'] = ''; }
	$data['sun'] = makeSafe($_REQUEST['sun']);
		if($data['sun'] == empty_lookup_value){ $data['sun'] = ''; }
	$data['fees'] = makeSafe($_REQUEST['fees']);
		if($data['fees'] == empty_lookup_value){ $data['fees'] = ''; }
	$data['selectedID']=makeSafe($selected_id);

	// hook: courses_before_update
	if(function_exists('courses_before_update')){
		$args=array();
		if(!courses_before_update($data, getMemberInfo(), $args)){ return false; }
	}

	$o=array('silentErrors' => true);
	sql('update `courses` set       `course_name`=' . (($data['course_name'] !== '' && $data['course_name'] !== NULL) ? "'{$data['course_name']}'" : 'NULL') . ', `description`=' . (($data['description'] !== '' && $data['description'] !== NULL) ? "'{$data['description']}'" : 'NULL') . ', `instructor_id`=' . (($data['instructor_id'] !== '' && $data['instructor_id'] !== NULL) ? "'{$data['instructor_id']}'" : 'NULL') . ', `lab_id`=' . (($data['lab_id'] !== '' && $data['lab_id'] !== NULL) ? "'{$data['lab_id']}'" : 'NULL') . ', `start_date`=' . (($data['start_date'] !== '' && $data['start_date'] !== NULL) ? "'{$data['start_date']}'" : 'NULL') . ', `end_date`=' . (($data['end_date'] !== '' && $data['end_date'] !== NULL) ? "'{$data['end_date']}'" : 'NULL') . ', `start_time`=' . (($data['start_time'] !== '' && $data['start_time'] !== NULL) ? "'{$data['start_time']}'" : 'NULL') . ', `end_time`=' . (($data['end_time'] !== '' && $data['end_time'] !== NULL) ? "'{$data['end_time']}'" : 'NULL') . ', `mon`=' . (($data['mon'] !== '' && $data['mon'] !== NULL) ? "'{$data['mon']}'" : 'NULL') . ', `tue`=' . (($data['tue'] !== '' && $data['tue'] !== NULL) ? "'{$data['tue']}'" : 'NULL') . ', `wed`=' . (($data['wed'] !== '' && $data['wed'] !== NULL) ? "'{$data['wed']}'" : 'NULL') . ', `thu`=' . (($data['thu'] !== '' && $data['thu'] !== NULL) ? "'{$data['thu']}'" : 'NULL') . ', `fri`=' . (($data['fri'] !== '' && $data['fri'] !== NULL) ? "'{$data['fri']}'" : 'NULL') . ', `sat`=' . (($data['sat'] !== '' && $data['sat'] !== NULL) ? "'{$data['sat']}'" : 'NULL') . ', `sun`=' . (($data['sun'] !== '' && $data['sun'] !== NULL) ? "'{$data['sun']}'" : 'NULL') . ', `fees`=' . (($data['fees'] !== '' && $data['fees'] !== NULL) ? "'{$data['fees']}'" : 'NULL') . " where `course_id`='".makeSafe($selected_id)."'", $o);
	if($o['error']!=''){
		echo $o['error'];
		echo '<a href="courses_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


	// hook: courses_after_update
	if(function_exists('courses_after_update')){
		$res = sql("SELECT * FROM `courses` WHERE `course_id`='{$data['selectedID']}' LIMIT 1", $eo);
		if($row = db_fetch_assoc($res)){
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = $data['course_id'];
		$args = array();
		if(!courses_after_update($data, getMemberInfo(), $args)){ return; }
	}

	// mm: update ownership data
	sql("update membership_userrecords set dateUpdated='".time()."' where tableName='courses' and pkValue='".makeSafe($selected_id)."'", $eo);

}

function courses_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0, $TemplateDV = '', $TemplateDVP = ''){
	// function to return an editable form for a table records
	// and fill it with data of record whose ID is $selected_id. If $selected_id
	// is empty, an empty form is shown, with only an 'Add New'
	// button displayed.

	global $Translation;

	// mm: get table permissions
	$arrPerm=getTablePermissions('courses');
	if(!$arrPerm[1] && $selected_id==''){ return ''; }
	$AllowInsert = ($arrPerm[1] ? true : false);
	// print preview?
	$dvprint = false;
	if($selected_id && $_REQUEST['dvprint_x'] != ''){
		$dvprint = true;
	}

	$filterer_course_name = thisOr(undo_magic_quotes($_REQUEST['filterer_course_name']), '');
	$filterer_instructor_id = thisOr(undo_magic_quotes($_REQUEST['filterer_instructor_id']), '');
	$filterer_lab_id = thisOr(undo_magic_quotes($_REQUEST['filterer_lab_id']), '');

	// populate filterers, starting from children to grand-parents

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: course_name
	$combo_course_name = new DataCombo;
	// combobox: instructor_id
	$combo_instructor_id = new DataCombo;
	// combobox: lab_id
	$combo_lab_id = new DataCombo;
	// combobox: start_date
	$combo_start_date = new DateCombo;
	$combo_start_date->DateFormat = "dmy";
	$combo_start_date->MinYear = 1900;
	$combo_start_date->MaxYear = 2100;
	$combo_start_date->DefaultDate = parseMySQLDate('', '');
	$combo_start_date->MonthNames = $Translation['month names'];
	$combo_start_date->NamePrefix = 'start_date';
	// combobox: end_date
	$combo_end_date = new DateCombo;
	$combo_end_date->DateFormat = "dmy";
	$combo_end_date->MinYear = 1900;
	$combo_end_date->MaxYear = 2100;
	$combo_end_date->DefaultDate = parseMySQLDate('', '');
	$combo_end_date->MonthNames = $Translation['month names'];
	$combo_end_date->NamePrefix = 'end_date';

	if($selected_id){
		// mm: check member permissions
		if(!$arrPerm[2]){
			return "";
		}
		// mm: who is the owner?
		$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='courses' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='courses' and pkValue='".makeSafe($selected_id)."'");
		if($arrPerm[2]==1 && getLoggedMemberID()!=$ownerMemberID){
			return "";
		}
		if($arrPerm[2]==2 && getLoggedGroupID()!=$ownerGroupID){
			return "";
		}

		// can edit?
		if(($arrPerm[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3){
			$AllowUpdate=1;
		}else{
			$AllowUpdate=0;
		}

		$res = sql("select * from `courses` where `course_id`='".makeSafe($selected_id)."'", $eo);
		if(!($row = db_fetch_array($res))){
			return error_message($Translation['No records found'], 'courses_view.php', false);
		}
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
		$combo_course_name->SelectedData = $row['course_name'];
		$combo_instructor_id->SelectedData = $row['instructor_id'];
		$combo_lab_id->SelectedData = $row['lab_id'];
		$combo_start_date->DefaultDate = $row['start_date'];
		$combo_end_date->DefaultDate = $row['end_date'];
	}else{
		$combo_course_name->SelectedData = $filterer_course_name;
		$combo_instructor_id->SelectedData = $filterer_instructor_id;
		$combo_lab_id->SelectedData = $filterer_lab_id;
	}
	$combo_course_name->HTML = '<span id="course_name-container' . $rnd1 . '"></span><input type="hidden" name="course_name" id="course_name' . $rnd1 . '" value="' . html_attr($combo_course_name->SelectedData) . '">';
	$combo_course_name->MatchText = '<span id="course_name-container-readonly' . $rnd1 . '"></span><input type="hidden" name="course_name" id="course_name' . $rnd1 . '" value="' . html_attr($combo_course_name->SelectedData) . '">';
	$combo_instructor_id->HTML = '<span id="instructor_id-container' . $rnd1 . '"></span><input type="hidden" name="instructor_id" id="instructor_id' . $rnd1 . '" value="' . html_attr($combo_instructor_id->SelectedData) . '">';
	$combo_instructor_id->MatchText = '<span id="instructor_id-container-readonly' . $rnd1 . '"></span><input type="hidden" name="instructor_id" id="instructor_id' . $rnd1 . '" value="' . html_attr($combo_instructor_id->SelectedData) . '">';
	$combo_lab_id->HTML = '<span id="lab_id-container' . $rnd1 . '"></span><input type="hidden" name="lab_id" id="lab_id' . $rnd1 . '" value="' . html_attr($combo_lab_id->SelectedData) . '">';
	$combo_lab_id->MatchText = '<span id="lab_id-container-readonly' . $rnd1 . '"></span><input type="hidden" name="lab_id" id="lab_id' . $rnd1 . '" value="' . html_attr($combo_lab_id->SelectedData) . '">';

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_course_name__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['course_name'] : $filterer_course_name); ?>"};
		AppGini.current_instructor_id__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['instructor_id'] : $filterer_instructor_id); ?>"};
		AppGini.current_lab_id__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['lab_id'] : $filterer_lab_id); ?>"};

		jQuery(function() {
			setTimeout(function(){
				if(typeof(course_name_reload__RAND__) == 'function') course_name_reload__RAND__();
				if(typeof(instructor_id_reload__RAND__) == 'function') instructor_id_reload__RAND__();
				if(typeof(lab_id_reload__RAND__) == 'function') lab_id_reload__RAND__();
			}, 10); /* we need to slightly delay client-side execution of the above code to allow AppGini.ajaxCache to work */
		});
		function course_name_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#course_name-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_course_name__RAND__.value, t: 'courses', f: 'course_name' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="course_name"]').val(resp.results[0].id);
							$j('[id=course_name-container-readonly__RAND__]').html('<span id="course_name-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=courses_catalog_view_parent]').hide(); }else{ $j('.btn[id=courses_catalog_view_parent]').show(); }


							if(typeof(course_name_update_autofills__RAND__) == 'function') course_name_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ /* */ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 5,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ /* */ return { s: term, p: page, t: 'courses', f: 'course_name' }; },
					results: function(resp, page){ /* */ return resp; }
				},
				escapeMarkup: function(str){ /* */ return str; }
			}).on('change', function(e){
				AppGini.current_course_name__RAND__.value = e.added.id;
				AppGini.current_course_name__RAND__.text = e.added.text;
				$j('[name="course_name"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=courses_catalog_view_parent]').hide(); }else{ $j('.btn[id=courses_catalog_view_parent]').show(); }


				if(typeof(course_name_update_autofills__RAND__) == 'function') course_name_update_autofills__RAND__();
			});

			if(!$j("#course_name-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_course_name__RAND__.value, t: 'courses', f: 'course_name' },
					success: function(resp){
						$j('[name="course_name"]').val(resp.results[0].id);
						$j('[id=course_name-container-readonly__RAND__]').html('<span id="course_name-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=courses_catalog_view_parent]').hide(); }else{ $j('.btn[id=courses_catalog_view_parent]').show(); }

						if(typeof(course_name_update_autofills__RAND__) == 'function') course_name_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_course_name__RAND__.value, t: 'courses', f: 'course_name' },
				success: function(resp){
					$j('[id=course_name-container__RAND__], [id=course_name-container-readonly__RAND__]').html('<span id="course_name-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=courses_catalog_view_parent]').hide(); }else{ $j('.btn[id=courses_catalog_view_parent]').show(); }

					if(typeof(course_name_update_autofills__RAND__) == 'function') course_name_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function instructor_id_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#instructor_id-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_instructor_id__RAND__.value, t: 'courses', f: 'instructor_id' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="instructor_id"]').val(resp.results[0].id);
							$j('[id=instructor_id-container-readonly__RAND__]').html('<span id="instructor_id-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=instructors_view_parent]').hide(); }else{ $j('.btn[id=instructors_view_parent]').show(); }


							if(typeof(instructor_id_update_autofills__RAND__) == 'function') instructor_id_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ /* */ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 5,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ /* */ return { s: term, p: page, t: 'courses', f: 'instructor_id' }; },
					results: function(resp, page){ /* */ return resp; }
				},
				escapeMarkup: function(str){ /* */ return str; }
			}).on('change', function(e){
				AppGini.current_instructor_id__RAND__.value = e.added.id;
				AppGini.current_instructor_id__RAND__.text = e.added.text;
				$j('[name="instructor_id"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=instructors_view_parent]').hide(); }else{ $j('.btn[id=instructors_view_parent]').show(); }


				if(typeof(instructor_id_update_autofills__RAND__) == 'function') instructor_id_update_autofills__RAND__();
			});

			if(!$j("#instructor_id-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_instructor_id__RAND__.value, t: 'courses', f: 'instructor_id' },
					success: function(resp){
						$j('[name="instructor_id"]').val(resp.results[0].id);
						$j('[id=instructor_id-container-readonly__RAND__]').html('<span id="instructor_id-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=instructors_view_parent]').hide(); }else{ $j('.btn[id=instructors_view_parent]').show(); }

						if(typeof(instructor_id_update_autofills__RAND__) == 'function') instructor_id_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_instructor_id__RAND__.value, t: 'courses', f: 'instructor_id' },
				success: function(resp){
					$j('[id=instructor_id-container__RAND__], [id=instructor_id-container-readonly__RAND__]').html('<span id="instructor_id-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=instructors_view_parent]').hide(); }else{ $j('.btn[id=instructors_view_parent]').show(); }

					if(typeof(instructor_id_update_autofills__RAND__) == 'function') instructor_id_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function lab_id_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#lab_id-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_lab_id__RAND__.value, t: 'courses', f: 'lab_id' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="lab_id"]').val(resp.results[0].id);
							$j('[id=lab_id-container-readonly__RAND__]').html('<span id="lab_id-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=labs_view_parent]').hide(); }else{ $j('.btn[id=labs_view_parent]').show(); }


							if(typeof(lab_id_update_autofills__RAND__) == 'function') lab_id_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ /* */ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 5,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ /* */ return { s: term, p: page, t: 'courses', f: 'lab_id' }; },
					results: function(resp, page){ /* */ return resp; }
				},
				escapeMarkup: function(str){ /* */ return str; }
			}).on('change', function(e){
				AppGini.current_lab_id__RAND__.value = e.added.id;
				AppGini.current_lab_id__RAND__.text = e.added.text;
				$j('[name="lab_id"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=labs_view_parent]').hide(); }else{ $j('.btn[id=labs_view_parent]').show(); }


				if(typeof(lab_id_update_autofills__RAND__) == 'function') lab_id_update_autofills__RAND__();
			});

			if(!$j("#lab_id-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_lab_id__RAND__.value, t: 'courses', f: 'lab_id' },
					success: function(resp){
						$j('[name="lab_id"]').val(resp.results[0].id);
						$j('[id=lab_id-container-readonly__RAND__]').html('<span id="lab_id-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=labs_view_parent]').hide(); }else{ $j('.btn[id=labs_view_parent]').show(); }

						if(typeof(lab_id_update_autofills__RAND__) == 'function') lab_id_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_lab_id__RAND__.value, t: 'courses', f: 'lab_id' },
				success: function(resp){
					$j('[id=lab_id-container__RAND__], [id=lab_id-container-readonly__RAND__]').html('<span id="lab_id-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=labs_view_parent]').hide(); }else{ $j('.btn[id=labs_view_parent]').show(); }

					if(typeof(lab_id_update_autofills__RAND__) == 'function') lab_id_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
	</script>
	<?php

	$lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
	ob_end_clean();


	// code for template based detail view forms

	// open the detail view template
	if($dvprint){
		$template_file = is_file("./{$TemplateDVP}") ? "./{$TemplateDVP}" : './templates/courses_templateDVP.html';
		$templateCode = @file_get_contents($template_file);
	}else{
		$template_file = is_file("./{$TemplateDV}") ? "./{$TemplateDV}" : './templates/courses_templateDV.html';
		$templateCode = @file_get_contents($template_file);
	}

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Detail View', $templateCode);
	$templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
	$templateCode = str_replace('<%%EMBEDDED%%>', ($_REQUEST['Embedded'] ? 'Embedded=1' : ''), $templateCode);
	// process buttons
	if($AllowInsert){
		if(!$selected_id) $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return courses_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return courses_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
	}

	// 'Back' button action
	if($_REQUEST['Embedded']){
		$backAction = 'AppGini.closeParentModal(); return false;';
	}else{
		$backAction = '$j(\'form\').eq(0).attr(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
	}

	if($selected_id){
		if(!$_REQUEST['Embedded']) $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$j(\'form\').eq(0).prop(\'novalidate\', true); document.myform.reset(); return true;" title="' . html_attr($Translation['Print Preview']) . '"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
		if($AllowUpdate){
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return courses_validateData();" title="' . html_attr($Translation['Save Changes']) . '"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		}
		if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3){ // allow delete?
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');" title="' . html_attr($Translation['Delete']) . '"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		}
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', ($ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : ''), $templateCode);
	}

	// set records to read only if user can't insert new records and can't edit current record
	if(($selected_id && !$AllowUpdate && !$AllowInsert) || (!$selected_id && !$AllowInsert)){
		$jsReadOnly .= "\tjQuery('#course_name').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#course_name_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#instructor_id').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#instructor_id_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#lab_id').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#lab_id_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#start_date').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#start_dateDay, #start_dateMonth, #start_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#end_date').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#end_dateDay, #end_dateMonth, #end_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#start_time').replaceWith('<div class=\"form-control-static\" id=\"start_time\">' + (jQuery('#start_time').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#end_time').replaceWith('<div class=\"form-control-static\" id=\"end_time\">' + (jQuery('#end_time').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#mon').prop('disabled', true);\n";
		$jsReadOnly .= "\tjQuery('#tue').prop('disabled', true);\n";
		$jsReadOnly .= "\tjQuery('#wed').prop('disabled', true);\n";
		$jsReadOnly .= "\tjQuery('#thu').prop('disabled', true);\n";
		$jsReadOnly .= "\tjQuery('#fri').prop('disabled', true);\n";
		$jsReadOnly .= "\tjQuery('#sat').prop('disabled', true);\n";
		$jsReadOnly .= "\tjQuery('#sun').prop('disabled', true);\n";
		$jsReadOnly .= "\tjQuery('#fees').replaceWith('<div class=\"form-control-static\" id=\"fees\">' + (jQuery('#fees').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('.select2-container').hide();\n";

		$noUploads = true;
	}elseif($AllowInsert){
		$jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);"; // temporarily disable form change handler
		$jsEditable .= "\tjQuery('#start_time').addClass('always_shown').timepicker({ defaultTime: false, showSeconds: true, showMeridian: true, showInputs: false, disableFocus: true, minuteStep: 5 });";
		$jsEditable .= "\tjQuery('#end_time').addClass('always_shown').timepicker({ defaultTime: false, showSeconds: true, showMeridian: true, showInputs: false, disableFocus: true, minuteStep: 5 });";
			$jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);"; // re-enable form change handler
	}

	// process combos
	$templateCode = str_replace('<%%COMBO(course_name)%%>', $combo_course_name->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(course_name)%%>', $combo_course_name->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(course_name)%%>', urlencode($combo_course_name->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(instructor_id)%%>', $combo_instructor_id->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(instructor_id)%%>', $combo_instructor_id->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(instructor_id)%%>', urlencode($combo_instructor_id->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(lab_id)%%>', $combo_lab_id->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(lab_id)%%>', $combo_lab_id->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(lab_id)%%>', urlencode($combo_lab_id->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(start_date)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_start_date->GetHTML(true) . '</div>' : $combo_start_date->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(start_date)%%>', $combo_start_date->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(end_date)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_end_date->GetHTML(true) . '</div>' : $combo_end_date->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(end_date)%%>', $combo_end_date->GetHTML(true), $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array(  'course_name' => array('courses_catalog', 'Course'), 'instructor_id' => array('instructors', 'Instructor'), 'lab_id' => array('labs', 'Class'));
	foreach($lookup_fields as $luf => $ptfc){
		$pt_perm = getTablePermissions($ptfc[0]);

		// process foreign key links
		if($pt_perm['view'] || $pt_perm['edit']){
			$templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-md" id="' . $ptfc[0] . '_view_parent" title="' . html_attr($Translation['View'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
		}

		// if user has insert permission to parent table of a lookup field, put an add new button
		if($pt_perm['insert'] && !$_REQUEST['Embedded']){
			$templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent hspacer-md" id="' . $ptfc[0] . '_add_new" title="' . html_attr($Translation['Add New'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
		}
	}

	// process images
	$templateCode = str_replace('<%%UPLOADFILE(course_id)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(course_name)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(instructor_id)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(lab_id)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(start_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(end_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(start_time)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(end_time)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(mon)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(tue)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(wed)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(thu)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(fri)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(sat)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(sun)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(fees)%%>', '', $templateCode);

	// process values
	if($selected_id){
		if( $dvprint) $templateCode = str_replace('<%%VALUE(course_id)%%>', safe_html($urow['course_id']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(course_id)%%>', html_attr($row['course_id']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(course_id)%%>', urlencode($urow['course_id']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(course_name)%%>', safe_html($urow['course_name']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(course_name)%%>', html_attr($row['course_name']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(course_name)%%>', urlencode($urow['course_name']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(instructor_id)%%>', safe_html($urow['instructor_id']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(instructor_id)%%>', html_attr($row['instructor_id']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(instructor_id)%%>', urlencode($urow['instructor_id']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(lab_id)%%>', safe_html($urow['lab_id']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(lab_id)%%>', html_attr($row['lab_id']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(lab_id)%%>', urlencode($urow['lab_id']), $templateCode);
		$templateCode = str_replace('<%%VALUE(start_date)%%>', @date('d.m.Y', @strtotime(html_attr($row['start_date']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode(@date('d.m.Y', @strtotime(html_attr($urow['start_date'])))), $templateCode);
		$templateCode = str_replace('<%%VALUE(end_date)%%>', @date('d.m.Y', @strtotime(html_attr($row['end_date']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode(@date('d.m.Y', @strtotime(html_attr($urow['end_date'])))), $templateCode);
		$templateCode = str_replace('<%%VALUE(start_time)%%>', time12(html_attr($row['start_time'])), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(start_time)%%>', urlencode(time12($urow['start_time'])), $templateCode);
		$templateCode = str_replace('<%%VALUE(end_time)%%>', time12(html_attr($row['end_time'])), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(end_time)%%>', urlencode(time12($urow['end_time'])), $templateCode);
		$templateCode = str_replace('<%%CHECKED(mon)%%>', ($row['mon'] ? "checked" : ""), $templateCode);
		$templateCode = str_replace('<%%CHECKED(tue)%%>', ($row['tue'] ? "checked" : ""), $templateCode);
		$templateCode = str_replace('<%%CHECKED(wed)%%>', ($row['wed'] ? "checked" : ""), $templateCode);
		$templateCode = str_replace('<%%CHECKED(thu)%%>', ($row['thu'] ? "checked" : ""), $templateCode);
		$templateCode = str_replace('<%%CHECKED(fri)%%>', ($row['fri'] ? "checked" : ""), $templateCode);
		$templateCode = str_replace('<%%CHECKED(sat)%%>', ($row['sat'] ? "checked" : ""), $templateCode);
		$templateCode = str_replace('<%%CHECKED(sun)%%>', ($row['sun'] ? "checked" : ""), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(fees)%%>', safe_html($urow['fees']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(fees)%%>', html_attr($row['fees']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(fees)%%>', urlencode($urow['fees']), $templateCode);
	}else{
		$templateCode = str_replace('<%%VALUE(course_id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(course_id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(course_name)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(course_name)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(instructor_id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(instructor_id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(lab_id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(lab_id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(start_date)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(end_date)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(start_time)%%>', time12(''), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(start_time)%%>', urlencode(time12('')), $templateCode);
		$templateCode = str_replace('<%%VALUE(end_time)%%>', time12(''), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(end_time)%%>', urlencode(time12('')), $templateCode);
		$templateCode = str_replace('<%%CHECKED(mon)%%>', '', $templateCode);
		$templateCode = str_replace('<%%CHECKED(tue)%%>', '', $templateCode);
		$templateCode = str_replace('<%%CHECKED(wed)%%>', '', $templateCode);
		$templateCode = str_replace('<%%CHECKED(thu)%%>', '', $templateCode);
		$templateCode = str_replace('<%%CHECKED(fri)%%>', '', $templateCode);
		$templateCode = str_replace('<%%CHECKED(sat)%%>', '', $templateCode);
		$templateCode = str_replace('<%%CHECKED(sun)%%>', '', $templateCode);
		$templateCode = str_replace('<%%VALUE(fees)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(fees)%%>', urlencode(''), $templateCode);
	}

	// process translations
	foreach($Translation as $symbol=>$trans){
		$templateCode = str_replace("<%%TRANSLATION($symbol)%%>", $trans, $templateCode);
	}

	// clear scrap
	$templateCode = str_replace('<%%', '<!-- ', $templateCode);
	$templateCode = str_replace('%%>', ' -->', $templateCode);

	// hide links to inaccessible tables
	if($_REQUEST['dvprint_x'] == ''){
		$templateCode .= "\n\n<script>\$j(function(){\n";
		$arrTables = getTableList();
		foreach($arrTables as $name => $caption){
			$templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
			$templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
		}

		$templateCode .= $jsReadOnly;
		$templateCode .= $jsEditable;

		if(!$selected_id){
		}

		$templateCode.="\n});</script>\n";
	}

	// ajaxed auto-fill fields
	$templateCode .= '<script>';
	$templateCode .= '$j(function() {';

	$templateCode .= "\tcourse_name_update_autofills$rnd1 = function(){\n";
	$templateCode .= "\t\t\$j.ajax({\n";
	if($dvprint) {
		$templateCode .= "\t\t\turl: 'courses_autofill.php?rnd1=$rnd1&mfk=course_name&id=' + encodeURIComponent('".addslashes($row['course_name'])."'),\n";
		$templateCode .= "\t\t\tcontentType: 'application/x-www-form-urlencoded; charset=" . datalist_db_encoding . "',\n";
		$templateCode .= "\t\t\ttype: 'GET'\n";
	} else {
		$templateCode .= "\t\t\turl: 'courses_autofill.php?rnd1=$rnd1&mfk=course_name&id=' + encodeURIComponent(AppGini.current_course_name{$rnd1}.value),\n";
		$templateCode .= "\t\t\tcontentType: 'application/x-www-form-urlencoded; charset=" . datalist_db_encoding . "',\n";
		$templateCode .= "\t\t\ttype: 'GET',\n";
		$templateCode .= "\t\t\tbeforeSend: function() { \$j('#course_name$rnd1').prop('disabled', true); \$j('#course_nameLoading').html('<img src=loading.gif align=top>'); },\n";
		$templateCode .= "\t\t\tcomplete: function() { " . (($arrPerm[1] || (($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID()) || ($arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID()) || $arrPerm[3] == 3)) ? "\$j('#course_name$rnd1').prop('disabled', false); " : "\$j('#course_name$rnd1').prop('disabled', true); ")."\$j('#course_nameLoading').html(''); \$j(window).resize(); }\n";
	}
	$templateCode .= "\t\t});\n";
	$templateCode .= "\t};\n";
	if(!$dvprint) $templateCode .= "\tif(\$j('#course_name_caption').length) \$j('#course_name_caption').click(function(){ /* */ course_name_update_autofills$rnd1(); });\n";


	$templateCode.="});";
	$templateCode.="</script>";
	$templateCode .= $lookups;

	// handle enforced parent values for read-only lookup fields

	// don't include blank images in lightbox gallery
	$templateCode = preg_replace('/blank.gif" data-lightbox=".*?"/', 'blank.gif"', $templateCode);

	// don't display empty email links
	$templateCode=preg_replace('/<a .*?href="mailto:".*?<\/a>/', '', $templateCode);

	/* default field values */
	$rdata = $jdata = get_defaults('courses');
	if($selected_id){
		$jdata = get_joined_record('courses', $selected_id);
		if($jdata === false) $jdata = get_defaults('courses');
		$rdata = $row;
	}
	$templateCode .= loadView('courses-ajax-cache', array('rdata' => $rdata, 'jdata' => $jdata));

	// hook: courses_dv
	if(function_exists('courses_dv')){
		$args=array();
		courses_dv(($selected_id ? $selected_id : FALSE), getMemberInfo(), $templateCode, $args);
	}

	return $templateCode;
}
?>