<?php
//error_reporting(E_ALL & ~E_NOTICE);
//ini_set('display_errors', '1');
require_once('utilities.php'); // Needed for kasoc_star_identifier - needs to be first for some reason
require('protect.php');
require_once('db_connect.php');
require_once('redirect.php');
require_once('pub_functions.inc.php');

$mode = isset($_GET['mode']) ? trim($_GET['mode']) : '';
$load_id = isset($_GET['starid']) ? intval($_GET['starid']) : 0;
if ($mode == 'search') {
	$object_name = isset($_POST['objectname']) ? trim($_POST['objectname']) : '';
	$kic = 0;
	if (!empty($object_name)) {
		// If the search is for KOI, broaden the search to the KOI table:
		if (preg_match('/^koi[-\s]+(\d+)$/i', $object_name, $matches)) {
			$stmt = $db->prepare("SELECT koi.Kepler_id FROM koi WHERE koi.koi_id=:koiid;");
			$stmt->bindValue(':koiid', $matches[1], PDO::PARAM_INT);
			$stmt->execute();
			$kic = intval($stmt->fetchColumn());
			$stmt->closeCursor();

		// If the search is for Kepler ids, simply search that KIC number:
		} elseif (preg_match('/^kic[-\s]+(\d+)$/i', $object_name, $matches)) {
			$kic = intval($matches[1]);

		// If the search is for K2 ids, broaden the search to include KIC-number:
		} elseif (preg_match('/^epic[-\s]+(\d+)$/i', $object_name, $matches)) {
			$kic = intval($matches[1]);

		// Search for Cat-nicknames:
		} elseif (preg_match('/^cat[-\s]+(\w+)$/i', $object_name, $matches)) {
			$stmt = $db->prepare("SELECT Kepler_id FROM nicknames WHERE nickname=:search;");
			$stmt->bindValue(':search', $matches[1], PDO::PARAM_STR);
			$stmt->execute();
			$kic = intval($stmt->fetchColumn());
			$stmt->closeCursor();

		// The KIC list of 2MASS ids is more complete than SIMBAD:
		} elseif (preg_match('/^2mass j(\d+\+\d+)$/i', $object_name, $matches)) {
			$stmt = $db->prepare("SELECT KIC.Kepler_id FROM KIC WHERE KIC.2MASS=:2mass;");
			$stmt->bindValue(':2mass', $matches[1], PDO::PARAM_STR);
			$stmt->execute();
			$kic = intval($stmt->fetchColumn());
			$stmt->closeCursor();

		} else {
			$stmt = $db->prepare("SELECT SIMBAD.Kepler_id FROM SIMBAD WHERE SIMBAD.preferred=:search1 OR SIMBAD.display_name=:search2 OR SIMBAD.ids REGEXP :search3 LIMIT 1;");
			$stmt->bindValue(':search1', $object_name, PDO::PARAM_STR);
			$stmt->bindValue(':search2', $object_name, PDO::PARAM_STR);
			$stmt->bindValue(':search3', '(/|^)(NAME )?(V* )?' . preg_quote($object_name) . '(/|$)', PDO::PARAM_STR);
			$stmt->execute();
			$row = $stmt->fetch();
			$stmt->closeCursor();
			if ($row !== false) {
				$kic = $row['Kepler_id'];
			} else {
				$stmt = $db->prepare("SELECT SIMBAD.Kepler_id FROM SIMBAD WHERE SIMBAD.preferred LIKE :search1 OR SIMBAD.display_name LIKE :search2 OR SIMBAD.ids LIKE :search3 LIMIT 1;");
				$stmt->bindValue(':search1', '%{$object_name}%', PDO::PARAM_STR);
				$stmt->bindValue(':search2', '%{$object_name}%', PDO::PARAM_STR);
				$stmt->bindValue(':search3', '%{$object_name}%', PDO::PARAM_STR);
				$stmt->execute();
				$row = $stmt->fetch();
				$stmt->closeCursor();
				if ($row !== false) {
					$kic = $row['Kepler_id'];
				}
			}
		}

	} else {
		$kic = isset($_POST['kic_id']) ? intval($_POST['kic_id']) : 0;
	}

	// Save the user input and redirect back to page with the star that was found:
	$_SESSION['internal_freqs_post'] = $_POST;
	if ($kic == 0) {
		redirect('/catalog/', 303);
	} else {
		redirect('/catalog/' . $kic, 303);
	}

} elseif ($load_id > 0) {
	$kic = intval($load_id);
	$p = $_SESSION['internal_freqs_post'];
	//$p['kic_id'] = $kic;

	// Check that the provided starid is not a custom aperture:
	$stmt = $db->prepare("SELECT real_kepler_id FROM cuap_targets_map WHERE cuap_kepler_id=:starid AND cuap_kepler_id != real_kepler_id;");
	$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
	$stmt->execute();
	$row = $stmt->fetch();
	$stmt->closeCursor();
	if ($row !== false) {
		$kic = $row['real_kepler_id'];
		redirect('/catalog/' . $kic, 303);
	}

} else {
	// The page was loaded without any input:
	$p = array();
	$kic = 0;
}

// Get the name of the star:
$star_identifier = ($kic != 0) ? kasoc_star_identifier($db, $kic) : '';

if ($kic != 0) {
	$page_title = 'Star Catalog: ' . $star_identifier;
} else {
	$page_title = 'Star Catalog';
}
include('top.php');
?>
<h2>Star Catalog<?php
if ($kic != 0) {
	echo ": " . $star_identifier;
}
?></h2>

<form id="searchform" action="index.php?mode=search" method="post" style="clear:both;">
<div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabsdsfsd" style="font-size:10pt;">
	<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
		<li id="objectstoggle" class="ui-state-active ui-corner-top"><a href="#" class="ui-tabs-anchor">Object</a></li>
	</ul>
	<div id="target_type_form" style="padding:5px;margin-top:5px;" class="ui-tabs-panel ui-widget-content ui-corner-bottom">
		<label for="objectname">Star name:</label><input type="text" id="objectname" name="objectname" value="<?php echo isset($p['objectname']) ? $p['objectname'] : ''; ?>" /><br />
		<label for="kic_id">KIC/EPIC number:</label><input type="text" name="kic_id" id="kic_id" value="<?php echo isset($p['kic_id']) ? $p['kic_id'] : ''; ?>" />
	</div>
	<div style="text-align:center;width:350px;margin-bottom:5px;margin-top:5px;">
		<input type="submit" value="Search" class="ui-button ui-state-default button-icon-search ui-corner-all" />
	</div>
</div>
</form>

<?php
if (!empty($kic) && $kic != 0) {
	// Load the KIC table data:
	$stmt = $db->prepare("SELECT
	KIC.Kepler_id as Kepler_id,
	KIC.RA as kic_ra,
	KIC.Decl as kic_decl,
	KIC.Teff AS kic_Teff,
	KIC.FeH AS kic_FeH,
	KIC.Log_G AS kic_logg,
	KIC.Radius AS kic_Radius,
	KIC.Kepler_Mag AS kic_mag,
	KIC.ebv AS kic_ebv,
	KIC.av AS kic_av,
	KIC.Contamination AS kic_contamination,
	KIC.umag AS kic_umag,
	KIC.gmag AS kic_gmag,
	KIC.imag AS kic_imag,
	KIC.zmag AS kic_zmag,
	KIC.gredmag AS kic_gredmag,
	KIC.d51mag AS kic_d51mag,
	KIC.jmag AS kic_jmag,
	KIC.hmag AS kic_hmag,
	KIC.kmag AS kic_kmag,
	KIC.parallax AS kic_parallax,
	KIC.2MASS as kic_2mass,
	KIC.Module_0 as kic_module_0,
	KIC.Module_1 as kic_module_1,
	KIC.Module_2 as kic_module_2,
	KIC.Module_3 as kic_module_3,
	KIC.Channel_0 as kic_channel_0,
	KIC.Channel_1 as kic_channel_1,
	KIC.Channel_2 as kic_channel_2,
	KIC.Channel_3 as kic_channel_3,
	KIC.Output_0 as kic_output_0,
	KIC.Output_1 as kic_output_1,
	KIC.Output_2 as kic_output_2,
	KIC.Output_3 as kic_output_3,
	KIC.Column_0 as kic_column_0,
	KIC.Column_1 as kic_column_1,
	KIC.Column_2 as kic_column_2,
	KIC.Column_3 as kic_column_3,
	KIC.Row_0 as kic_row_0,
	KIC.Row_1 as kic_row_1,
	KIC.Row_2 as kic_row_2,
	KIC.Row_3 as kic_row_3,
	KIC.fovflag as kic_fovflag
	FROM KIC WHERE KIC.Kepler_id=:starid;");
	$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
	$stmt->execute();
	$kicrow = $stmt->fetch();
	$stmt->closeCursor();
	if ($kicrow === false) $kicrow = array();

	// Get the row from the SIMBAD table:
	$stmt = $db->prepare("SELECT * FROM SIMBAD WHERE Kepler_id=:starid;");
	$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
	$stmt->execute();
	$row_simbad = $stmt->fetch();
	$stmt->closeCursor();

	// ------------- GROUND-BASED OBSERVATIONS -------------
	$stmt = $db->prepare("SELECT
gb_observations.id,
gb_observations.instid,
gb_observations.observer,
gb_observations.nobs,
gb_observations.obtained_from,
gb_observations.obtained_to,
gb_observations.workgroup,
gb_observations.remarks,
gb_instruments.type AS inst_type,
users.name as contact_name,
users.email as contact_email
FROM gb_observations
LEFT JOIN gb_instruments ON gb_observations.instid=gb_instruments.instid
LEFT JOIN users ON users.userid=gb_observations.contact
WHERE gb_observations.Kepler_id=:starid AND gb_observations.status=1
ORDER BY gb_observations.obtained_from DESC;");
	$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
	$stmt->execute();
	$results = $stmt->fetchAll();
	$stmt->closeCursor();

	echo "<h3>Ground-based observations</h3>\n";

	if ($results !== false && !empty($results)) {
		require('../groundbased/gb_settings.php');
		echo "<div style=\"padding-left:20px;padding-right:20px;\">\n";
		echo "<table class=\"tablesorter\">\n";
		echo "<thead>\n";
		echo "<tr>\n";
		echo "	<th style=\"width:16px;\">&nbsp;</th>\n";
		echo "	<th style=\"padding-right:15px;\">Instrument</th>\n";
		echo "	<th style=\"padding-right:15px;\">Obtained</th>\n";
		echo "	<th style=\"padding-right:15px;\">Number</th>\n";
		echo "	<th style=\"padding-right:15px;\">Observer</th>\n";
		echo "	<th style=\"padding-right:15px;\">Contact</th>\n";
		echo "	<th style=\"padding-right:15px;\">Remarks</th>\n";
		echo "</tr>\n";
		echo "</thead>";
		echo "<tbody>";
		foreach ($results as $row) {
			echo "<tr>\n";
			echo "	<td style=\"text-align:center;\">";
			switch($row['inst_type']) {
				case 'spectra':
					echo "<img src=\"/Images/rainbow_small.png\" width=\"16\" height=\"16\" alt=\"Spectroscopy\" title=\"Spectroscopy\" style=\"width:16px;vertical-align:middle;\" /> ";
					break;
				case 'photo':
					echo "<img src=\"/Images/lightbulb.png\" width=\"16\" height=\"16\" alt=\"Photometry\" title=\"Photometry\" style=\"width:16px;vertical-align:middle;\" /> ";
					break;
				case 'specpol':
					echo "<img src=\"/Images/specpol.png\" width=\"16\" height=\"16\" alt=\"Spectropolarimetry\" title=\"Spectropolarimetry\" style=\"width:16px;vertical-align:middle;\" /> ";
					break;
				case 'interfero':
					echo "<img src=\"/Images/interferometry.png\" width=\"16\" height=\"16\" alt=\"Interferometry\" title=\"Interferometry\" style=\"width:16px;vertical-align:middle;\" /> ";
					break;
			}
			echo "</td>\n";
			echo "	<td style=\"white-space:nowrap;\"><a href=\"/groundbased/instrument.php?id=" . urlencode($row['instid']) . "\" class=\"gb_inst_link\">" . htmlentities($row['instid']) . "</a></td>\n";
			echo "	<td style=\"text-align:right;white-space:nowrap;\">";
			echo (is_null($row['obtained_from']) || empty($row['obtained_from'])) ? '&nbsp;' : date('d-m-Y', strtotime($row['obtained_from']));
			echo "</td>\n";

			echo "	<td style=\"text-align:right;\">" . $row['nobs'] . "</td>\n";

			echo "	<td style=\"white-space:nowrap;\">";
			$arrObservers = parse_observers($db, $row['observer']);
			if (empty($arrObservers)) {
				echo 'Service';
			} else {
				foreach ($arrObservers as $observer) {
					echo htmlentities($observer['name']) . "<br />";
				}
			}
			echo "</td>\n";

			echo "	<td style=\"white-space:nowrap;\">" . format_email($row['contact_email'], $row['contact_name']) . "</td>\n";
			echo "	<td style=\"font-size:8pt;\">" . htmlentities($row['remarks']) . "</td>\n";
			echo "</tr>\n";
		}
		echo "</tbody>\n";
		echo "</table>\n";
		echo "</div>\n";
		echo "<div id=\"gb_inst_dialog\" style=\"display:none;text-align:left;\"></div>\n";
	} else {
		echo "<i>No ground-based observations listed.</i>";
	}

	// ------------- SIMBAD -------------
	echo "<h3>SIMBAD</h3>\n";

	$nearby_sources = array();
	$aladin_main_object_javascript = '';
	$aladin_nearby_objects_javascript = '';
	if (!is_null($kicrow['kic_ra']) && !is_null($kicrow['kic_decl'])) {

		$aladin_target = $kicrow['kic_ra'] . ' ' . $kicrow['kic_decl'];

		$search_radius = 8/60; // degrees
		$max_nearby_objects = 50; // maximal number of returned objects:

		$stmt = $db->prepare("SELECT KIC.Kepler_id,KIC.RA,KIC.Decl FROM KIC LEFT JOIN cuap_targets_map ON KIC.Kepler_ID=cuap_targets_map.cuap_kepler_id WHERE (real_kepler_id IS NULL OR KIC.Kepler_ID=real_kepler_id) AND KIC.RA BETWEEN :ra_low AND :ra_high AND KIC.Decl BETWEEN :dec_low AND :dec_high LIMIT $max_nearby_objects;");
		$stmt->bindValue(':ra_low', $kicrow['kic_ra']-$search_radius, PDO::PARAM_STR);
		$stmt->bindValue(':ra_high', $kicrow['kic_ra']+$search_radius, PDO::PARAM_STR);
		$stmt->bindValue(':dec_low', $kicrow['kic_decl']-$search_radius, PDO::PARAM_STR);
		$stmt->bindValue(':dec_high', $kicrow['kic_decl']+$search_radius, PDO::PARAM_STR);
		$stmt->execute();
		$nearby_objects = $stmt->fetchAll();
		$stmt->closeCursor();

		$aladin_main_object_javascript = sprintf("A.source(%f, %f, {starid: %d, name: '%s', is_main: true})", $kicrow['kic_ra'], $kicrow['kic_decl'], $kic, kasoc_star_identifier($db, $kic));

		$aladin_nearby_objects_javascript = array();
		foreach ($nearby_objects as $obj) {
			if ($obj['Kepler_ID'] != $kic) {
				$aladin_nearby_objects_javascript[] = sprintf("A.source(%f, %f, {starid: %d, name: '%s', is_main: false})", $obj['RA'], $obj['Decl'], $obj['Kepler_ID'], kasoc_star_identifier($db, $obj['Kepler_ID']));
			}
		}
		$aladin_nearby_objects_javascript = implode(",", $aladin_nearby_objects_javascript);
	}

	// SIMBAD finder image:
	echo "<div style=\"padding:10px;background-color:#dddddd;float:right;margin-right:25px;\" class=\"ui-corner-all\">\n";
	echo "	<div id=\"aladin-lite-div\" style=\"width:500px;height:400px;\"></div>\n";
	echo "</div>\n";

	if ($row_simbad === false) {
		echo "<i>Object not found in SIMBAD.</i>";

	} else {
		$identifiers = explode('/', $row_simbad['ids']);
		$identifiers = preg_replace('/^(name|v\*) /i', '', $identifiers);
		$main_identifier = $identifiers[0];
		$aladin_target = $row_simbad['RA'] . ' ' . $row_simbad['Decl'];

		echo "<table class=\"tablesorter\"  style=\"width:350px;margin-left:25px;\">\n";
		echo "<tbody>\n";

		echo "<tr>\n";
		echo "	<td style=\"width:110px;\">Names:</td>\n";
		echo "	<td style=\"white-space:nowrap;\">" . implode("<br />\n", $identifiers) . "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>Type:</td>\n";
		echo "	<td>" . htmlencode($row_simbad['otype']) . "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>Right Ascension:</td>\n";
		echo "	<td style=\"text-align:right;\">" . $row_simbad['RA'] . "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>Declination:</td>\n";
		echo "	<td style=\"text-align:right;\">" . $row_simbad['Decl'] . "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>Radial velocity (km/s):</td>\n";
		echo "	<td style=\"text-align:right;\">" . $row_simbad['rv'];
		echo is_null($row_simbad['rv_error']) ? '' : " &pm; {$row_simbad['rv_error']}";
		echo is_null($row_simbad['rv_bibcode']) ? '' : " <sup><a href=\"http://adsabs.harvard.edu/abs/{$row_simbad['rv_bibcode']}\" title=\"Radial velocity reference: {$row_simbad['rv_bibcode']}\" class=\"reference_tooltip\">(ref)</a></sup>";
		echo "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>Parallax (mas):</td>\n";
		echo "	<td style=\"text-align:right;\">" . $row_simbad['plx'];
		echo is_null($row_simbad['plx_error']) ? '' : " &pm; {$row_simbad['plx_error']}";
		echo is_null($row_simbad['plx_bibcode']) ? '' : " <sup><a href=\"http://adsabs.harvard.edu/abs/{$row_simbad['plx_bibcode']}\" title=\"Parallax reference: {$row_simbad['plx_bibcode']}\" class=\"reference_tooltip\">(ref)</a></sup>";
		echo "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>Spectral type:</td>\n";
		echo "	<td>" . $row_simbad['spectype'] . "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>U:</td>\n";
		echo "	<td style=\"text-align:right;\">";
		echo is_null($row_simbad['Umag']) ? '&nbsp;' : $row_simbad['Umag'];
		echo "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>B:</td>\n";
		echo "	<td style=\"text-align:right;\">";
		echo is_null($row_simbad['Bmag']) ? '&nbsp;' : $row_simbad['Bmag'];
		echo "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>V:</td>\n";
		echo "	<td style=\"text-align:right;\">";
		echo is_null($row_simbad['Vmag']) ? '&nbsp;' : $row_simbad['Vmag'];
		echo "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>R:</td>\n";
		echo "	<td style=\"text-align:right;\">";
		echo is_null($row_simbad['Rmag']) ? '&nbsp;' : $row_simbad['Rmag'];
		echo "</td>\n";
		echo "</tr>\n";

		echo "<tr>\n";
		echo "	<td>I:</td>\n";
		echo "	<td style=\"text-align:right;\">";
		echo is_null($row_simbad['Imag']) ? '&nbsp;' : $row_simbad['Imag'];
		echo "</td>\n";
		echo "</tr>\n";

		echo "</tbody>\n";
		echo "</table>\n";

		echo "<div class=\"ui-state-default ui-corner-all\" style=\"text-align:center;margin-top:0px;margin-left:25px;border:1px solid black;padding-top:10px;padding-bottom:10px;background-color:#eeeeee;width:350px;font-weight:normal;\">\n";
		echo "	<a href=\"http://simbad.u-strasbg.fr/simbad/sim-basic?Ident=" . urlencode($identifiers[0]) . "&amp;submit=submit+id\" target=\"_blank\">Open SIMBAD</a>\n";
		echo "</div>\n";

	}

	// JavaScript for Aladin Lite:
?>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
	// Aladin Lite applet:
	var aladin = $.aladin('#aladin-lite-div', {survey: "P/2MASS/color", zoom: 4/60, target: "<?php echo $aladin_target; ?>", showReticle: false});

	// Star currently active:
	var cat_main = A.catalog({name: 'Current object', shape: 'plus', color: 'rgb(178,50,178)', sourceSize: 30});
	aladin.addCatalog(cat_main);
	cat_main.addSources([<?php echo $aladin_main_object_javascript; ?>]);

	// Catalog of nearby objects:
	var cat = A.catalog({name: 'Nearby objects', shape: 'square', color: '#ff0000', sourceSize: 20});
	aladin.addCatalog(cat);
	cat.addSources([<?php echo $aladin_nearby_objects_javascript; ?>]);

	// define function triggered when  a source is hovered
	aladin.on('objectHovered', function(obj){
	    if (obj && !obj.data.is_main) {
	        var msg = 'You hovered object ' + obj.data.name + ' located at ' + obj.ra + ', ' + obj.dec;
	    }
	});

	// define function triggered when an object is clicked
	aladin.on('objectClicked', function(obj){
	    if (obj && !obj.data.is_main) {
			window.location.href = '/catalog/' + obj.data.starid;
	    }
	});
});
//]]>
</script>
<?php

	// ------------- CLASSIFICATIONS -------------
	echo "<h3>Classifications</h3>\n";
	echo "<a href=\"#\" id=\"input_classification\" style=\"display:block;width:160px;border:1px solid gray;float:right;text-align:center;margin-left:10px;padding-top:3px;padding-bottom:3px;\" class=\"ui-corner-all\"><div><img src=\"/Images/icon_classification.png\" width=\"70\" alt=\"\" /><br />Input Classification</div></a>\n";
	echo "<p style=\"font-size:8pt;margin-bottom:5px;\">The star has been classified to belong to the following classes. The classifications include both automatic classifications and &quot;manual&quot; classifications where the members of KASC has manually classified the stellar pulsations.</p>\n";
	echo "<ul style=\"\">\n";
	$stmt = $db->prepare("SELECT DISTINCT class,dist,source,source_publication FROM classification WHERE Kepler_id=:starid AND hide=0 ORDER BY dist;");
	$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
	$stmt->execute();
	$results = $stmt->fetchAll();
	$stmt->closeCursor();
	if ($results === false || empty($results)) {
		echo "\t<li><i>Star not classified.</i></li>\n";
	} else {
		foreach ($results as $row) {
			echo "\t<li>" . get_classification_name($row['class']) . ' (<span style="font-size:8pt;">';
			if ($row['dist'] == 0) {
				echo '<span title="' . htmlentities($row['source']) . '">manual</span>';
				if (!is_null($row['source_publication'])) {
					echo ": <a href=\"http://adsabs.harvard.edu/abs/" . urlencode($row['source_publication']) . "\" class=\"external\">" . htmlentities($row['source_publication']) . "</a>";
				}
			} else {
				echo $row['dist'];
			}
			echo "</span>)</li>\n";
		}
	}
	echo "</ul>\n";
	echo "<p style=\"font-size:8pt;\">If you would like to provide new classifications to this target, please use the &quot;Input Classification&quot; button to the right or feel free to <a href=\"mailto:rasmush@phys.au.dk\">contact us</a>.</p>\n";

	// ------------- PUBLICATIONS -------------
	echo "<h3 style=\"clear:both;\">Publications</h3>\n";
	$arr_kasoc_publications = array();
	$stmt = $db->prepare("SELECT DISTINCT Publications.pubid,title,status,authors,bibcode FROM Publications,pub_target_assoc WHERE pub_target_assoc.Kepler_id=:starid AND Publications.pubid=pub_target_assoc.pubid AND Publications.status IN ('published') ORDER BY find_in_set(status,'review,submission_rdy,submitted,accepted,published') asc, updated desc;");
	$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
	$stmt->execute();
	$results = $stmt->fetchAll();
	$stmt->closeCursor();
	if ($results === false || empty($results)) {
		echo "<i>No KASC publications found.</i>\n";
	} else {
		echo "<ul class=\"jqueryFileTree\" style=\"width:90%;margin-left:15px;\">\n";
		foreach ($results as $rs){
			if (!is_null($rs['bibcode'])) {
				$arr_kasoc_publications[] = $rs['bibcode'];
			}
			$arrauthors = explode(',', $rs['authors']);
			echo "\t<li class=\"file ext_pdf\"><a href=\"/publications/" . $rs['pubid'] . "\">" . render_author($arrauthors[0]) . ": " . render_title($rs['title']) . " (<span style=\"font-size:8pt;\">" . render_status($rs['status']) . "</span>)</a></li>\n";
		}
		echo "</ul>\n";
	}

	// ------------- SIMBAD PUBLICATIONS -------------
	if ($row_simbad !== false) {
		$refs = trim($row_simbad['refs']);
		$arrrefs = empty($refs) ? array(): explode(',', $refs);
		$arrrefs = array_diff($arrrefs, $arr_kasoc_publications);
		if (!empty($arrrefs)) {
			//$stmt_external = $db->prepare("SELECT pubid,title,authors FROM Publications WHERE status='external' AND bibcode=:bibcode LIMIT 1;");
			//$stmt_external->bindParam(':bibcode', $ref, PDO::PARAM_STR);

			echo "<h4 style=\"font-size:10pt;\">External references</h4>\n";
			echo "<ul id=\"external_publications\" class=\"jqueryFileTree\" style=\"margin-left:15px;\">\n";
			$k = 1;
			foreach ($arrrefs as $ref) {
				echo "\t<li class=\"file ext_html";
				if ($k > 5) {
					echo " hidden_publication";
				}
				echo "\" style=\"width:200px;\">";

				//$stmt_external->execute();
				//$r = $stmt_external->fetch();
				//if ($r === false) {
					echo "<a href=\"http://adsabs.harvard.edu/abs/" . urlencode($ref) . "\" class=\"external\">" . htmlentities($ref) . "</a>";
				//}
				//else {
				//	echo "<a href=\"/publications/{$r['pubid']}\">" . render_title($r['title']) . "</a>";
				//}
				echo "</li>\n";
				$k++;
			}
			echo "</ul>\n";
		}
	}

	// ------------- PROPOSALS -------------
	$stmt = $db->prepare("SELECT Proposals.Proposal_id,identifier,title FROM ProposalsAssoc LEFT JOIN Proposals ON ProposalsAssoc.Proposal_id=Proposals.Proposal_id WHERE ProposalsAssoc.Kepler_id=:starid ORDER BY abs(replace(Proposal_round,'Specific Targets Q','')) DESC,Proposal_round,identifier;");
	$stmt->bindValue(':starid', $kic, PDO::PARAM_INT);
	$stmt->execute();
	$results = $stmt->fetchAll();
	$stmt->closeCursor();
	if ($results !== false && !empty($results)) {
		echo "<h3>Kepler/K2 Proposals</h3>\n";
		echo "<ul class=\"jqueryFileTree\" style=\"width:90%;margin-left:15px;\">\n";
		foreach ($results as $row) {
			echo "\t<li class=\"file ext_pdf\"><a href=\"/proposals/" . $row['Proposal_id'] . "\">" . $row['identifier'] . ': ' . $row['title'] . "</a></li>\n";
		}
		echo "</ul>\n";
	}

	// ------------- KEPLER INPUT CATALOGUE -------------
	echo "<h3>" . kasoc_star_identifier_catalog($db, $kic) . "</h3>\n";
	if (!is_null($kicrow['kic_fovflag'])) {
		if ($kicrow['kic_fovflag'] == 0) {
			echo "<div class=\"error ui-corner-all\" style=\"margin-left:25px;\">Note: This target is not in the Kepler field of view or does not fall on a CCD.</div>";
		} elseif ($kicrow['kic_fovflag'] == 2) {
			echo "<div class=\"error ui-corner-all\" style=\"margin-left:25px;\">Note: This target is a composit target or a non-KIC object.</div>";
		}
	}
	echo "<table class=\"tablesorter\" style=\"width:350px;margin-left:25px;\">\n";
	echo "	<tbody>\n";
	echo "	<tr>\n";
	echo "		<td>" . render_latex('$Kp$') . "</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_mag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>Right Ascension:</td>\n";
	if (is_null($kicrow['kic_ra'])) {
		echo "		<td colspan=\"4\">&nbsp;</td>\n";
	} else {
		echo '		<td style="text-align:right;" colspan="4">' . deg_to_dms($kicrow['kic_ra']/15, 2, false) . "</td>\n";
	}
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>Declination:</td>\n";
	if (is_null($kicrow['kic_decl'])) {
		echo "		<td colspan=\"4\">&nbsp;</td>\n";
	} else {
		echo '		<td style="text-align:right;" colspan="4">' . deg_to_dms($kicrow['kic_decl'], 2, true) . "</td>\n";
	}
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td style=\"width:110px;\">" . render_latex('$T_\mathrm{eff} \, (\mathrm{K})$') . "</td>";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_Teff'] . "</td>";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>" . render_latex('$\log(g)$') . "</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_logg'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>" . render_latex('$[\mathrm{Fe}/\mathrm{H}]$') . "</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_FeH'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>" . render_latex('$R/R_\odot$') . "</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_Radius'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>" . render_latex('$E(B-V)$') . "</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_ebv'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>" . render_latex('$A(V)$') . "</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_av'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>Contamination</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_contamination'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>Parallax (mas):</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_parallax'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>u Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_umag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>g Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_gmag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>i Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_imag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>z Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_zmag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>gred Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_gredmag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>D51 Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_d51mag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>J Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_jmag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>H Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_hmag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>K Mag</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_kmag'] . "</td>\n";
	echo "	</tr>\n";
	echo "	<tr>\n";
	echo "		<td>2MASS</td>\n";
	echo "		<td style=\"text-align:right;\" colspan=\"4\">";
	if (!is_null($kicrow['kic_2mass'])) echo 'J' . $kicrow['kic_2mass'];
	echo "</td>\n";
	echo "	</tr>\n";
	if (kasoc_star_identifier_catalog($db, $kic, 'short') == 'EPIC') {

		echo "	<tr>\n";
		echo "		<td>CCD Module</td>\n";
		echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_module_0'] . "</td>\n";
		echo "	</tr>\n";
		echo "	<tr>\n";
		echo "		<td>CCD Channel</td>\n";
		echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_channel_0'] . "</td>\n";
		echo "	</tr>\n";
		echo "	<tr>\n";
		echo "		<td>CCD Output</td>\n";
		echo "		<td style=\"text-align:right;\" colspan=\"4\">" . $kicrow['kic_output_0'] . "</td>\n";
		echo "	</tr>\n";

	} else {

		function write_ccd_position($kicrow, $type, $season) {
			$dead_module = false;
			echo "		<td";
			if ($kicrow['kic_module_' . $season] == 3) {
				$dead_module = true;
				echo " style=\"text-align:center;background-image:url(/Images/diagonal_red.png);color:red;font-weight:bold;\" title=\"Target falls on broken module 3 in quarters >4.\"";
			} elseif ($kicrow['Kepler_id'] > 210000000 && $kicrow['kic_module_' . $season] == 7) {
				$dead_module = true;
				echo " style=\"text-align:center;background-image:url(/Images/diagonal_red.png);color:red;font-weight:bold;\" title=\"Target falls on broken module 7.\"";
			} else {
				echo " style=\"text-align:center;\"";
			}
			echo ">" . $kicrow['kic_' . $type . '_' . $season] . "</td>\n";
			return $dead_module;
		}

		echo "	<tr>\n";
		echo "		<td>CCD Modules</td>\n";
		$dead_module = false;
		$dead_module |= write_ccd_position($kicrow, 'module', 0);
		$dead_module |= write_ccd_position($kicrow, 'module', 1);
		$dead_module |= write_ccd_position($kicrow, 'module', 2);
		$dead_module |= write_ccd_position($kicrow, 'module', 3);
		echo "	</tr>\n";

		echo "	<tr>\n";
		echo "		<td>CCD Channels</td>\n";
		$dead_module |= write_ccd_position($kicrow, 'channel', 0);
		$dead_module |= write_ccd_position($kicrow, 'channel', 1);
		$dead_module |= write_ccd_position($kicrow, 'channel', 2);
		$dead_module |= write_ccd_position($kicrow, 'channel', 3);
		echo "	</tr>\n";

		echo "	<tr>\n";
		echo "		<td>CCD Outputs</td>\n";
		$dead_module |= write_ccd_position($kicrow, 'output', 0);
		$dead_module |= write_ccd_position($kicrow, 'output', 1);
		$dead_module |= write_ccd_position($kicrow, 'output', 2);
		$dead_module |= write_ccd_position($kicrow, 'output', 3);
		echo "	</tr>\n";

		echo "	<tr>\n";
		echo "		<td>CCD Columns</td>\n";
		$dead_module |= write_ccd_position($kicrow, 'column', 0);
		$dead_module |= write_ccd_position($kicrow, 'column', 1);
		$dead_module |=write_ccd_position($kicrow, 'column', 2);
		$dead_module |=write_ccd_position($kicrow, 'column', 3);
		echo "	</tr>\n";

		echo "	<tr>\n";
		echo "		<td>CCD Rows</td>\n";
		$dead_module |= write_ccd_position($kicrow, 'row', 0);
		$dead_module |= write_ccd_position($kicrow, 'row', 1);
		$dead_module |= write_ccd_position($kicrow, 'row', 2);
		$dead_module |= write_ccd_position($kicrow, 'row', 3);
		echo "	</tr>\n";
	}

	echo "	</tbody>\n";
	echo "</table>\n";

	// Explaination of the dead module:
	if ($dead_module) {
		echo "<div style=\"float:left;width:1.1em;height:1.1em;background-image:url(/Images/diagonal_red.png);border:1px solid gray;margin-right:5px;margin-left:25px;vartical-align:middle;\"></div>Target falls on dead CCD module";
	}
}
?>
<div style="display:none;text-align:left;" id="inputclass_dialog">
	<p>Please provide your manual classification of this target.<br />
	All provided classification should be beyond reasonable doubt.</p>
	<div>
		<label>Classification:</label>
		<select name="inpclass" id="inpclass">
			<option value=""></option>
<?php
	classwrite_select($arrClassificationClasses2, '');
?>
		</select><br />
		<label>Bibcode:</label><input type="text" name="inpbibcode" id="inpbibcode" maxlength="19" /><br />
		<label>Comment:</label><input type="text" name="inpcomment" id="inpcomment" /><br />
		<input type="hidden" name="inpkic" id="inpkic" value="<?php echo $kic; ?>" />
	</div>
	<div id="inputclass_dialog_error" class="error ui-corner-all" style="display:none;margin-top:10px;"></div>
</div>
<?php
include('bottom.php');
?>
