<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', '1');
require('protect.php');
require_once('settings.php');
require_once('db_connect.php');
require_once('gb_settings.php');

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

$mode = 'new';
$r = array('nobs' => 1);
if ($id > 0) {
	// Only gb_admins are allowed to change existing:
	if (!user_is_gb_admin()) exit('You are not allowed to do this!');
	$stmt = $db->prepare('SELECT * FROM gb_observations WHERE id=:id;');
	$stmt->bindValue(':id', $id, PDO::PARAM_INT);
	$stmt->execute();
	$r = $stmt->fetch();
	$stmt->closeCursor();
	if ($r !== false) {
		$mode = 'edit';
		$r['workgroup'] = explode(',', $r['workgroup']);
		if ($r['observer'] == 0)
			$r['observer'] = array();
		else
			$r['observer'] = explode(',', $r['observer']);
	}
}

if ($mode == 'edit') {
	$page_title = 'Ground-Based: Edit observation';
} else {
	$page_title = 'Ground-Based: Add new observation';
}

include('top.php');
include('gb_menu.php');
?>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
	$("#gb_edit_accordion").accordion({
		autoHeight: false
	});

	$("#kic").autocomplete({
		minLength: 2,
		source: function(request, response) {
			$.ajax({
				url: "../json_kic.php",
				type: "GET",
				dataType: "json",
				data: {"search": request.term},
				success: function(data) {
					response(data);
				}
			});
		},
	});

	var dates = $("#obtained_from, #obtained_to").datepicker({
		dateFormat: 'dd-mm-yy',
		changeMonth: true,
		changeYear: true,
		onSelect: function(selectedDate) {
			var option = (this.id == "obtained_from" ? "minDate" : "maxDate"),
				instance = $(this).data("datepicker"),
				date = $.datepicker.parseDate(
					instance.settings.dateFormat ||
					$.datepicker._defaults.dateFormat,
					selectedDate, instance.settings);
			dates.not(this).datepicker("option", option, date);
		},
		beforeShow: function(){
			var other = (this.id == "obtained_from" ? "#obtained_to" : "#obtained_from");
            var option = (this.id == "obtained_from" ? "maxDate" : "minDate");
            var selectedDate = $(other).datepicker('getDate');
            $(this).datepicker( "option", option, selectedDate);
		}
	}).change(function(){
        var other = (this.id == "obtained_from" ? "#obtained_to" : "#obtained_from");
        if ($("#obtained_from").datepicker('getDate') > $("#obtained_to").datepicker('getDate'))
            $(other).datepicker('setDate', $(this).datepicker('getDate') );
    });

	$("#instrument").change(function(){
		var val = $(this).val();
		if (val == "") {
			$("#instrument_info").hide();
		} else {
			$("#instrument_info").load("instrument.php?id=" + val + "&dialog=true").show();
		}
	}).trigger('change');

	$("#workgroup_0").change(function(){
		if ($(this).is(':checked')) {
			$('#real_workgroups').children().prop('disabled', true).prop('checked', false).addClass('ui-state-disabled');
		} else {
			$('#real_workgroups').children().prop('disabled', false).removeClass('ui-state-disabled');
		}
	}).trigger('change');

	$("#btn_cancel").click(function(){
		location.href = '/groundbased/';
	});

	$("#gb_edit_form").submit(function(e){
		var href = $(this).attr("action") + "?ajax=1";
		var data = $(this).serialize();
		$(this).find("div.update_callback").removeClass('ok error').addClass('loading').html('Updating...').show();
		$.ajax({
			url: href,
			type: 'POST',
			data: data,
			context: $(this),
			success: function(d) {
				if (d == '') {
					$(this).find("div.update_callback").addClass('ok').removeClass('error loading').html('Updated sucessfully!<br />As soon as your upload has been approved by an admin, your observation will be visible in the database.').show();
				} else {
					$(this).find("div.update_callback").addClass('error').removeClass('ok loading').html(d).show();
				}
			}
		});
		e.preventDefault();
		return false;
	});

	// Extract JSON list of observers from select-box:
	var data = [];
	$("#observer_select option").each(function(){
		var value = $(this).val();
		if (value != "") {
			data.push({id: value, name: $(this).text()});
		}
	});

	// Get list of selected observers:
	var selected_options = [
<?php
$observers = parse_observers($db, $r['observer']);
if (!empty($observers)) {
	$write_observer = array();
	foreach ($observers as $obs) {
		if (ctype_digit($obs['id'])) {
			$write_observer[] = "{id: \"" . $obs['id'] . "\", name: \"" . $obs['name'] . "\"}";
		} else {
			$write_observer[] = "{id: \"" . $obs['id'] . "\", name: \"" . $obs['name'] . " (<i>Non-KASC Member</i>)\"}";
		}
	}
	echo implode(",\n", $write_observer) . "\n";
}
?>
	];

	// Make the traditional select box go away:
	$("#observer_select").attr('name', 'observer_select_oldselect');
	$("#observer_select_container").hide();

	// Make the new "select-box" (jquery.tokeninput):
	var ny = $('<input name=\"observer_select\" type="text" />').appendTo("#replace_select");
	ny.tokenInput(data, {
		prePopulate: selected_options,
		processPrePopulate: true,
		preventDuplicates: true,
		tokenDelimiter: ',',
		propertyToSearch: 'name',
		hintText: 'Type in a name',
		allowCreation: true,
		createTokenText: '(<i>Non-KASC member</i>)',
		onAdd: function(){
			$("#observer_service").prop('checked', false);
		}
	});

	// Make the service button cooperate with the toneninput:
	$("#observer_service").change(function(){
		if ($(this).is(':checked')) {
			ny.tokenInput("clear");
			$("#replace_select").children("input").blur();
		}
	});
});
//]]>
</script>

<?php
if ($mode == 'edit') {
	echo "<h2>Edit observation (Admin Only)</h2>\n";
	echo "<p>Please use the form below to edit the information about this observation.</p>\n";
} else {
	echo "<h2>Add new observation</h2>\n";
	echo "<p>Please use the form below to submit information about a new observation to the database.</p>\n";
}
?>

<div id="gb_edit_accordion">
	<h3><a href="#">Single observation</a></h3>
	<div style="font-size:10pt;padding-left:10px;padding-right:10px;">
		<div id="instrument_info" style="width:400px;float:right;border:1px solid gray;display:none;padding:4px;" class="ui-corner-all"></div>

<form id="gb_edit_form" action="gb_edit_submit.php" method="post">
<div>
<label for="kic">KIC/EPIC-number:</label>
<input type="text" name="kic" id="kic" value="<?php echo $r['Kepler_id']; ?>" /><br /><br />

<label>Date obtained:</label>
<div class="buttongroup">
	<input type="text" id="obtained_from" name="obtained_from" value="<?php echo (empty($r['obtained_from'])) ? '' : date('d-m-Y', strtotime($r['obtained_from'])); ?>" /><br />
	<input type="text" id="obtained_to" name="obtained_to" value="<?php echo (empty($r['obtained_to'])) ? '' : date('d-m-Y', strtotime($r['obtained_to'])); ?>" />
</div>
<div style="clear:none;padding-left:150px;font-size:8pt;width:270px;">
Please provide either the exact date the observation was done in the top field, or a range of dates where the observation was done.
</div><br />

<label for="instrument">Instrument:</label>
<select name="instrument" id="instrument">
	<option value="">-- Please select --</option>
<?php
echo gb_instrument_options($db, $r['instid']);
?>
</select><br />
<div style="clear:none;padding-left:150px;font-size:8pt;width:270px;">
If an instrument or instrument-configuration does not exist in the above list, please contact <a href="mailto:rasmush@phys.au.dk">Rasmus Handberg</a>.
</div><br />

<label>Ordered by:</label>
<div class="buttongroup">
<?php
echo "\t\t\t<input type=\"checkbox\" name=\"workgroup[]\" id=\"workgroup_0\" value=\"0\"";
if (is_null($r['workgroup'])) echo " checked=\"checked\"";
echo "/><label for=\"workgroup_0\" class=\"chkboxlabel\">None</label><br />\n";
echo "<div id=\"real_workgroups\">\n";
foreach ($arrWorkingGroups as $num => $wg) {
	echo "\t\t\t<input type=\"checkbox\" name=\"workgroup[]\" id=\"workgroup_{$num}\" value=\"{$num}\"";
	if (is_array($r['workgroup'])) {
		if (in_array($num, $r['workgroup'])) echo " checked=\"checked\"";
	} else {
		if ($r['workgroup'] == $num) echo " checked=\"checked\"";
	}
	echo "/><label for=\"workgroup_{$num}\" class=\"chkboxlabel\">{$num} - {$wg}</label><br />\n";
}
?>
</div></div><br /><br />

<label>Contact:</label>
<select name="contact" id="contact">
<?php
foreach ($db->query("SELECT * FROM users WHERE active=1 ORDER BY substring_index(name, ' ', -1) ASC;") as $row) {
	echo "<option value=\"{$row['userid']}\"";
	if (!empty($r['contact']) && $row['userid'] == $r['contact'] || (empty($r['contact']) && $row['userid']==$_SESSION['userid'])) echo " selected=\"selected\"";
	echo ">" . htmlentities($row['name']) . "</option>\n";
}
?>
</select><br />
<div style="clear:none;padding-left:150px;font-size:8pt;width:270px;">
The PI of the observation and the person which to be contacted.
</div><br />

<label>Observer(s):</label>
<div class="buttongroup">
	<input type="checkbox" id="observer_service" name="observer_service" value="on"<?php if (empty($r['observer'])) echo " checked=\"checked\""; ?> /><label for="observer_service" class="chkboxlabel">Service</label><br />
	<div id="observer_select_container">
	<select size="10" style="float:left;" name="observer_select[]" id="observer_select" multiple="multiple">
	<?php
	foreach ($db->query("SELECT * FROM users WHERE active=1 ORDER BY substring_index(name, ' ', -1) ASC;") as $row) {
		echo "<option value=\"{$row['userid']}\"";
		if (isset($r['observer'])) {
			if (is_array($r['observer'])) {
				if (in_array($row['userid'], $r['observer'])) echo " selected=\"selected\"";
			} else {
				if (ctype_digit($r['observer']) && $row['userid'] == $r['observer']) echo " selected=\"selected\"";
			}
		}
		echo ">" . htmlentities($row['name']) . "</option>\n";
	}
	?>
	</select>
	<div style="clear:both;font-size:8pt;width:270px;">
	To select multiple observers, hold down Ctrl (Windows) or Cmd (Mac) and click the above list.
	</div>
	</div>

	<div id="replace_select"></div>
</div>
<br style="clear:both;" /><br />

<label for="nobs">Number of observations:</label>
<input type="text" name="nobs" id="nobs" value="<?php echo $r['nobs']; ?>" /><br /><br />

<label for="remarks">Remarks:</label>
<textarea name="remarks" id="remarks" cols="10" rows="5"><?php echo $r['remarks']; ?></textarea>

</div>

<div style="padding-left:150px;padding-top:20px;">
	<input type="hidden" name="id" value="<?php echo $id; ?>" />
	<input type="submit" value="Submit" />
	<div class="error update_callback ui-corner-all" style="display:none;margin-left:0;margin-top:15px;"></div>
</div>
</form>
	</div>
<?php
if ($mode == 'new') {
?>
	<h3><a href="#">Multiple observations</a></h3>
	<div>
<p>In order to submit multiple targets at a time, you need to construct a comma-separated ASCII file with the following format, and send it to rasmush@phys.au.dk:
One observation per line, with the following fields separated by a comma (,). Each line should contain all nine fields, but they can (in some cases) be left blank.</p>
<ol>
	<li>KIC number</li>
	<li>Instrument ID (Find in on the KASOC website)</li>
	<li>Contact person</li>
	<li>Observer(s) *</li>
	<li>Number of observations</li>
	<li>Obtained_From (YYYY-MM-DD) **</li>
	<li>Obtained_To (YYYY-MM-DD) **</li>
	<li>Working Group(s) *</li>
    <li>Remarks</li>
</ol>

<p>Footnotes:<br />
*) Multiple values should be separated by ";".<br />
**) If exact observation date is known, please provide date in "Obtained_From" and leave "Obtained_To" blank. If range of dates should be provided, use both fields.
</p>

<p>In case of the contact person and observer, you can provide initials and then explain me who each initial correspond to. In the case of observers, you can also specify "service" if it was simple service-observations.</p>

An example would be:
<pre>
1160660,BCSPM,KU,service,1,2011-12-07,,1,Very nice target
11395018,FIES_HIGH,RH,KU,2,2012-01-01,2012-02-01,8,
11395018,ESPADONS,RH,service,2,2012-01-01,2012-02-01,10,This is cool
</pre>
	</div>
<?php
}
?>
</div>

<?php
include('bottom.php');
?>
