<?php
/**
 * index.php
 * 2 Apr 2011
 * main landing page for dasr application: view your experiments
 */

session_start();
if(!$_SESSION['researcher_id']) {
    header("Location: login.php");
    exit;
}
require_once 'db.function.php';

$db = getDB();
$exp = $db->query("select experiment_id, title, date_format(exp_date, '%c/%e/%y') as exp_date, ".
                  "trim(',' from keywords) as keywords, description, bedcount from experiment ".
                  "where experiment.researcher_id = ?", $_SESSION['researcher_id']);
				
				// individual experiments profile
				
	
// 			
function generateTable($exp, $fields) {
    $ret = "<table id=\"exptable\" cellpadding=6 cellspacing=0>\n<tr>";
    foreach(array_keys($fields) as $f) {
        $ret .= "<th>$f</th>";
    }
    $i = 0;
    while($r = $exp->fetchRow()) {
        $class = '';
        if($i % 2 == 1) {
            $class = ' class="oddrow"';
        }
        $ret .= "<tr$class>";
        foreach($fields as $k) {
            if($k == 'title' || $k == 'description') {
                $r[$k] = "<a href=\"exp.php?id=$r[experiment_id]\">$r[$k]</a>";   // link to exp.php, details for one experiment
            }
            $ret .= "<td>$r[$k]</td>";
        }
        
        $ret .= "</tr>\n";
        $i++;
    }
    $ret .= "</table>\n";
    return $ret;
}

$fields = array('Title' => 'title', 'Date' => 'exp_date', 'Keywords' => 'keywords', 'Description' => 'description', 'BED Files' => 'bedcount');
$title = "Home";
require_once 'header.inc.php';
?>

Welcome, <?= "$_SESSION[firstname]!" ?> [<a href="logout.php">Logout</a>]<br><br>
<p><img src="help.gif" alt="user manual" width="166" height="67" border="0" usemap="#Map" />
<map name="Map" id="Map"><area shape="rect" coords="6,0,166,64" href="help.php" target="_blank" alt="user manual" />
</map><br>  <br>
<?php
if($_SESSION['admin']):
require_once 'DBSelectForm.class.php';
$search_genome = new DBSelectForm('genome', 'select genome_id, name from genome', array('id' => 'search_genome'));
$search_genome->insertElt('', '[any]');
$search_method = new DBSelectForm('method', 'select method_id, name from method', array('id' => 'search_method'));
$search_method->insertElt('', '[any]');

?>
Search BED files: <input type="text" id="search_q"> <button id="search" onclick="window.location = 'search.php?' + jQuery.param({search_q:$('#search_q').val()})">ok</button>
<a href="javascript:;" onclick="$('#adv_search_div').show()" id="open_adv_search">Advanced search &raquo;</a><br><br>
<div id="adv_search_div" style="display:none">
<table>
<tr><td>Name:</td><td><input type="text" id="search_name"></td></tr>
<tr><td>Date:</td><td><input type="text" id="search_date"> (m/d/y; use - for a range)</td></tr>
<tr><td>Genome:</td><td><?php $search_genome->printSelect(); ?></td></tr>
<tr><td>Method:</td><td><?php $search_method->printSelect(); ?></td></tr>
<tr><td>Header:</td><td><input type="text" id="search_header"></td></tr>
<tr><td>Description:</td><td><input type="text" id="search_descr"></td></tr>
<tr>
<td><input type="radio" checked="true" name="bool_mode" id="match_all" value="and"><label for="match_all"> match ALL</label></td>
<td><input type="radio" name="bool_mode" id="match_any" value="or"><label for="match_any"> match ANY</label></td>
</tr>
</table>
<button id="search" onclick="window.location = 'search.php?' + jQuery.param({name:$('#search_name').val(),'date':$('#search_date').val(),genome:$('#search_genome').val(),method:$('#search_method').val(),descr:$('#search_descr').val(),header:$('#search_header').val(),
bool:$('input[name=bool_mode]:checked').val()})">ok</button>
<br>
</div>
<?php
endif;
?>


<?php

// displaying experiments

if(!$exp->numRows()) {
    print "<span id=\"noexp\">You have no existing experiments in the system.</span><br/>\n";
    print "<table id=\"exptable\" cellpadding=6 cellspacing=0>\n</table>";
} else {
    print "Experiments:<br/>\n";
    print generateTable($exp, $fields);
}

// admins can see whole experiments
if($_SESSION['admin']) {
    print "<br>Other people's experiments:<br>\n";
    $result = $db->query("select experiment_id, title, date_format(exp_date, '%c/%e/%y') as exp_date, ".
                  "trim(',' from keywords) as keywords, description, bedcount, concat(firstname,' ', lastname) as owner from experiment join researcher using(researcher_id) ".
                  "where experiment.researcher_id <> ?", $_SESSION['researcher_id']);   // show experiments not belong to mine
    $fields['Owner'] = 'owner';
    print generateTable($result, $fields);   // add 'owner' column
    print '<a href="exp.php?id=0">View all BED files at once &raquo;</a><br>';
}
?>



<!--Create a new experiment --> 
<h3><a href="javascript:;" id="shownew">Create a new experiment &raquo;</a></h3>
<div id="newexp" style="display:none">
<table>
<?php
$fieldnames = array_flip($fields);
$formfields = array('title' => '<input type="text" style="width:200px" id="title">', 'exp_date' => '<input type="text" style="width:80px" id="exp_date">',
                    'keywords' => '<input type="text" style="width:300px" id="keywords">', 'description' => '<textarea id="description" rows="4" cols="40"></textarea>');
foreach($formfields as $k => $v) {
    print "<tr><td style=\"text-align:right\">$fieldnames[$k]</td><td>$v</td></tr>\n";
}
?>
</table>
<button id="createnew">create new</button>
</div>

<!--Create a new genome --> 
<h3 id="genome_banner"><a href="javascript:;" id="shownewgenome">Add a new genome &raquo;</a></h3>
<div id="newgenome" style="display:none">
<table>
<tr><td>Name:</td><td><input type="text" id="genome_name"> e.g. Human hg19</td></tr>
<tr><td>Clade:</td><td><input type="text" id="genome_clade"> e.g. mammal</td></tr>
<tr><td>Organism:</td><td><input type="text" id="genome_org"> e.g. Human</td></tr>
<tr><td>DB:</td><td><input type="text" id="genome_db"> e.g. hg19</td></tr>
<tr><td colspan="2">For Clade, Organism, and DB, please match the UCSC Genome Browser values.</td></tr>
<tr><td>Chromosomes<br>(paste list, each row is chrom length, e.g. chr1   249250621):</td><td><textarea id="genome_chroms" rows=4 cols=40></textarea></td></tr>
</table>
<button id="createnewgenome">add genome</button>
</div>

<!--Create a new menthod --> 
<h3 id="method_banner"><a href="javascript:;" id="shownewmethod">Add a new method &raquo;</a></h3>
<div id="newmethod" style="display:none">
<table>
<tr><td>Name of Method:</td><td><input type="text" id="method_name"> e.g. ChIP-Seq</td></tr>
</table>
<button id="createnewmethod">add method</button>
</div>

<!--Deal with the information you entered and send it to newexp.php --> 
<script>
$('#shownew').click(
function(evt) {
    $('#newexp').show();
});
$('#createnew').click(
function(evt) {
    var vals = {title:$('#title').val(), exp_date:$('#exp_date').val(),keywords:$('#keywords').val(),description:$('#description').val()};
    if(!jQuery.trim(vals.title)) {
        alert('Please specify a title.');
        $('#title').focus();
        return;
    }
    //var fields = <?php print "'#" . join(",", array_keys($formfields)) . "'"; ?>;
    $.getJSON('newexp.php', vals,
	
// Resp add one new row in my exp profile
    function(resp) {
        if(resp['err']) {
        } else {
            $('#exptable').append('<tr><td><a href="exp.php?id='+resp['id']+'">'+resp.title+'</a></td><td>'+resp.exp_date+'</td><td>'+resp.keywords+'</td><td><a href="exp.php?id='+resp['id']+'">'+resp.description+'</a></td><td>0</td></tr>');
            $('#newexp').hide();
            $('#noexp').hide();
        }
    });
});
$('#shownewgenome').click(
function(evt) {
    $('#newgenome').show();
});
// execute when user clicks add genome button
$('#createnewgenome').click(
function(evt) {
    // collect submitted values
    var vals = {name:$('#genome_name').val(),clade:$('#genome_clade').val(), org:$('#genome_org').val(), db:$('#genome_db').val(), chrom_length:$('#genome_chroms').val()};
    $.getJSON('newgenome.php', vals,
    function(resp) {
        if(resp['err']) {
            //alert(resp['err']);
        } else {
            $('#newgenome').hide();
            $('#genome_banner').append(' Thanks, the new genome was added.');
        }
    });
});
$('#shownewmethod').click(
function(evt) {
    $('#newmethod').show();
});
// execute when user clicks add genome button
$('#createnewmethod').click(
function(evt) {
    // collect submitted values
    var vals = {name:$('#method_name').val()};
    $.getJSON('newmethod.php', vals,
    function(resp) {
        if(resp['err']) {
            //alert(resp['err']);
        } else {
            $('#newmethod').hide();
            $('#method_banner').append(' Thanks, the new method was added.');
        }
    });
});
</script>
    
<?php
require_once 'footer.inc.php';
?>
