<?php
/**
 * exp.php
 * 2 Apr 2011
 * manipulate bed files for a particular experiment
 */
session_start();
require_once 'util.function.php';
require_once 'const.inc.php';
if(!$_SESSION['researcher_id']) {
    header('Location: login.php');
    exit;
} else if(!ctype_digit($_GET['id']) || !experiment_access_permission($_SESSION['researcher_id'], $_GET['id'])) {
     // experiments level
    exit;
}

$id = $_GET['id'];
$head_insert = '<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" id="theme">'."\n".
               '<link rel="stylesheet" href="css/jquery.fileupload-ui.css">';

$title = "Manage Files";
require_once 'header.inc.php';

require_once 'db.function.php';
require_once 'DBSelectForm.class.php';



// View ALL Bed files 
$db = getDB();
if($_GET['id'] == 0) {
    $exp = array('title' => 'Viewing all BED files from all experiments', 'keywords' => '', 'description' => 'ALL BED FILES');
    $exp_query = 'or 1 = 1';
    if(isset($_GET['search']) && count($_SESSION['last_search_result'])) {
        $exp_query = 'or bedfile_id in ('. join(',', $_SESSION['last_search_result']) . ')';
        $exp = array('title' => "Viewing results from your search for <span style=\"color:blue\">$_SESSION[last_search_q]</span>", 'keywords' => '', 'description' => 'SEARCH RESULTS');
    } else if(isset($_GET['search'])) {
        $exp_query = '';
        $exp = array('title' => "Viewing results from your search for <span style=\"color:blue\">$_SESSION[last_search_q]</span>", 'keywords' => '', 'description' => 'SEARCH RESULTS');
    }
    $disabled = 'disabled="disabled" style="background-color:white"';
    $descr_query = "concat(descr, ' <a href=\"exp.php\?id=', experiment_id, '\">From Experiment ', experiment_id, '</a>') as descr";
} else {
    $exp = $db->getRow("select title, trim(',' from keywords) as keywords, description from experiment where experiment_id = ?", array($_GET['id']));
    $exp_query = '';
    $disabled = '';
    $descr_query = 'descr';
}


// Reference button works
if($_SESSION['admin']) {
    $reference_button = "<button class=\"action reference\" title=\"Toggle reference file status\"><img src=\"img/reference.png\"> reference</button>";
} else {
    $reference_button = '';
}
$reference = $db->getAssoc("select bedfile_id, name from bedfile where is_reference = 1 order by name");

// Query and store bedfiles information, bedfiles belong to this experiment
$bed = $db->query("select bedfile_id as id, method_id, method.name as method, genome_id, genome.name as genome, bedfile.name, date_format(upload_date, '%c/%e/%y') as upload_date, date_format(expiration, '%c/%e/%y') as expiration, header, $descr_query from bedfile left join method using(method_id) left join genome using(genome_id) where experiment_id = ? $exp_query order by bedfile_id", $id);
if(PEAR::isError($bed)) {
    print_r($bed);
    die;
}

$fieldmap = array('Date' => 'upload_date', 'Name' => 'name', 'Genome' => 'genome', 'Method' => 'method', /*'Expires' => 'expiration',*/ 'Header' => 'header', 'Description' => 'descr');
?>

<a href="index.php">&laquo; Back to Home</a><br>
Experiment: <b><?php print "$exp[title]" ?></b><br>
Keywords: <b><?php print $exp['keywords']; ?></b><br>
Description: <b><?php print $exp['description']; ?></b><br><br>
<?php
if(isset($_GET['search']) && $bed->numRows() == 0) {
    print '<h3 id="nofiles">Your search for '.$_SESSION['last_search_q'] .' didn\'t match any BED files.</h3>';
} else if($bed->numRows() == 0) {
    print '<h3 id="nofiles">You don\'t have any BED files for this experiment.</h3>';
}
?>

<!-- toolbar -->
<div class="buttons">
<button class="action download"><img src="img/download.png"> download</button>
<button class="action compare" <?php echo $disabled ?>><img src="img/compare.png"> compare</button>
<button class="action delete"><img src="img/delete.png"> delete</button>
<button class="action extract" <?php echo $disabled ?>><img src="img/split.png"> extract</button>
<button class="action ucsc"><img src="img/ucsc.png"> ucsc</button>
<button class="action edit"><img src="img/edit.png"> <span class="editbuttontext">edit</span></button>
<?php print "$reference_button\n"; ?>
</div>
<br>

<!-- table of bed files -->
<table id="bedfiletable" cellpadding=6 cellspacing=0>
<?php
// print the rows of bedfiles
print "<tr><th><input type=\"checkbox\" id=\"allnone\" title=\"Select all\"/></th><th>" . join("</th><th>", array_keys($fieldmap)) . "</th><th></th></tr>\n";
$i = 0;
while($r = $bed->fetchRow()) {
    $class = '';
    if($i % 2 == 1) {
       $class = ' class="oddrow"';
    }
    print "<tr$class bedid=\"$r[id]\"><td><input class=\"bchk\" type=\"checkbox\" id=\"bed_$r[id]\">";
    if(isset($reference[$r['id']])) {
        print "<img src=\"img/reference.png\" class=\"ref\" style=\"\" title=\"Reference file\"/>";
    }
    print "</td>";
    foreach($fieldmap as $f) {
        //print "<td id=\"${f}_$r[id]\">". htmlspecialchars($r[$f]) . "</td>";
        if($f == 'name') {
            $r[$f] = "<a href=\"bedinfo.php?id=$r[id]\">$r[$f]</a>";
			// link to the bedinfo
        }
        print "<td id=\"${f}_$r[id]\">$r[$f]</td>";
    }
    print "</tr>\n";
    $selectVals[$r['id']]['genome'] = $r['genome'];
    $selectVals[$r['id']]['method'] = $r['method'];
    $i++;
}
?>
</table>
<!-- toolbar -->
<div class="buttons">
<button class="action download"><img src="img/download.png"> download</button>
<button class="action compare" <?php echo $disabled ?>><img src="img/compare.png"> compare</button>
<button class="action delete"><img src="img/delete.png"> delete</button>
<button class="action extract" <?php echo $disabled ?>><img src="img/split.png"> extract</button>
<button class="action ucsc"><img src="img/ucsc.png"> ucsc</button>
<button class="action edit"><img src="img/edit.png"> <span class="editbuttontext">edit</span></button>
<?php print "$reference_button\n"; ?>
</div>
<br>
<?php if($_GET['id'] != 0): ?>
<b>Upload new</b>: Drag and drop BED files here or click to browse. zip/tar/gz/bz2 OK.<br>
<form id="file_upload" action="uploadsvc.php?id=<?= $_GET['id'] ?>" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" multiple>
    <button>Upload</button>
    <div>Upload files (max size: 500M)</div>
</form>
<table id="files"></table>
Copy a reference file:
<?php
//$refSelect = new DBSelectForm('bedfile', 'select bedfile_id, name from bedfile where bedfile_id in ('.REFERENCE_FILE_IDS.') order by name', array('id' => 'ref_bed_select'));
$refSelect = new DBSelectForm('bedfile', 'select bedfile_id, name from bedfile where is_reference = 1 order by name', array('id' => 'ref_bed_select'));
$refSelect->printSelect();
?>
<button id="copyref">ok</button>
<?php
endif;
?>

<!-- dialogs functionalities -->
<div id="compare_dialog" style="display:none" title="Compare BED files">
Base pair overlap: <input type="text" id="compare_bp_overlap" style="width:40px" value="1"/><br>

<?php
echo "Select destination: ";
//$refSelect = new DBSelectForm('bedfile', 'select bedfile_id, name from bedfile where bedfile_id in ('.REFERENCE_FILE_IDS.') order by name', array('id' => 'ref_bed_select'));
$destSelect = new DBSelectForm('experiment', 'select experiment_id,title from experiment where is_reference = 0');
$destSelect->printSelect();
?>
<br>

<button id="compare_ok">ok</button>
<button id="compare_cancel">cancel</button>
</div>
<div id="extract_dialog" style="display:none" title="Extract parts of BED files">
<table>
<tr><td>Chromosome:</td><td><span id="extract_chrom"></span><input type="checkbox" id="extract_by_chrom"><label for="extract_by_chrom">Split by chromosome</label></td></tr>
<tr><td>Start position:</td><td><input type="text" id="extr_chrom_start"></td></tr>
<tr><td>End position:</td><td><input type="text" id="extr_chrom_end"></td></tr>
<tr><td>RGB value:</td><td><input type="text" id="extr_rgb" value="N,N,N" onfocus="if($(this).val() == 'N,N,N') $(this).val('');"></td></tr>
<!-- tr><td><input type="radio" id="save_dasr" name="extr_save"><label for="save_dasr">Save result to DASR</label></td><td><input type="radio" id="save_browser" name="extr_save"><label for="save_browser">Save to your computer</label></td></tr -->
</table>
<button id="extract_ok">ok</button>
<button id="extract_cancel">cancel</button>
</div>
<div id="download_dialog" style="display:none" title="Download BED files">
File suffix:<br>
<input type="radio" name="dl_suffix" id="dl_suffix_keep" value=""> <label for="dl_suffix_keep">Leave file names as is</label><br>
<input type="radio" name="dl_suffix" id="dl_suffix_xls" value="xls"><label for="dl_suffix_xls"> xls (MS Excel)</label><br>
<input type="radio" name="dl_suffix" id="dl_suffix_csv" value="csv"><label for="dl_suffix_csv"> csv (comma-separated values)</label><br>
<input type="radio" name="dl_suffix" id="dl_suffix_txt" value="txt"><label for="dl_suffix_txt"> txt (plain text)</label><br>
<input type="radio" name="dl_suffix" id="dl_suffix_custom" value="custom"><label for="dl_suffix_custom"> Custom:</label>
<input type="text" name="dl_suffix_custom_value" id="dl_suffix_custom_value"><br>
<button id="download_ok">ok</button>
<button id="download_cancel">cancel</button>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script>
<script>
var selects = Array();
var selectVals = Array();
<?php
// scroll down methods and genomes 
$genome = new DBSelectForm('genome', 'select name, name from genome');
$genome->insertElt('', 'none');
print "selects['genome'] = '". str_replace(array("'", "\n"), array("\'", ' '), $genome->getSelect()) . "';\n";
$method = new DBSelectForm('method', 'select name, name from method');
$method->insertElt('', 'none');
print "selects['method'] = '". str_replace(array("'", "\n"), array("\'", ' '), $method->getSelect()) . "';\n";
if($bed->numRows()) {
    print "selectVals = ". json_encode($selectVals) . ";\n";
} else {
    print "$('.buttons').hide(); $('#bedfiletable').hide();\n";
}
?>
var editMode = false;

<!-- edit -->

$('.edit').click(
function(evt) {
    if($('.bchk:checked').length == 0) {
        return;
    }
    var fields = ['name', 'header', 'descr', 'genome', 'method'];
    if(!editMode) {
        editMode = true;
        $('.action').attr('disabled', true);
        $('.action').css('background-color', 'white');
        $('.bchk,#allnone').attr('disabled', true);
        $('.edit').attr('disabled', false).css('background-color', '');
        $('.editbuttontext').html('done editing');
        $('.bchk:checked').each(
        function(i, val) {
            var bedid = $(val).attr('id').replace('bed_', '');
            openEdit('name', bedid);
            openEdit('header', bedid);
            openEdit('descr', bedid);
            openSelect('genome', bedid);
            openSelect('method', bedid);
        });
    } else {
        // save new values and return to normal viewing mode
        editMode =  false;
        $('.action').attr('disabled', false).css('background-color', '');
        $('.bchk,#allnone').attr('disabled', false);
        $('.editbuttontext').html('edit');
        var vals = {}; //Array();
        // we make one request to the upd.php script for each row
        $('.bchk:checked').each(
        function(i, elt) {
            var bedid = $(elt).attr('id').replace('bed_', '');
            var bKey = $(elt).attr('id');
            vals[bKey] = Array();
            for(var f in fields) {
                var fld = fields[f];
                vals[bKey].push({field:fld,val:$('#' + fld + '_' + bedid + '_txt').val()});
            }
            if(i == $('.bchk:checked').length - 1) {
                $.getJSON('upd.php', {vals: vals, table:'bedfile'},
                function(resp) {
                    if(resp['err'] == '') {
                        var e;
                        for(var k in vals) {
                            var bedid;
                            for(var j in vals[k]) {
                                bedid = k.replace('bed_', '');
                                e = vals[k][j];
                                $('#' + e.field + '_' + bedid).text(e.val);
                                if(e.field == 'genome' || e.field == 'method') {
                                    selectVals[bedid][e.field] = e.val;
                                } else if(e.field == 'name') {
                                    $('#' + e.field + '_' + bedid).html('<a href="bedinfo.php?id='+bedid+'">'+e.val+'</a>');
                                }
                            }
                        }
                    } else
                        alert(resp['err']);
                });
            }
        });
    }
});
function openEdit(fld, rowid) {
    var sel = '#'+fld+'_'+rowid;
    var currHtml = $(sel).html();
    var currVal = $.trim($(sel).text());
    $(sel).html('<input style="width:200px" type="text" value="'+currVal.replace(/"/g, '&quot;')+'" id="'+fld+'_'+rowid+'_txt">');
}
function openSelect(fld, rowid) {
    var sel = '#'+fld+'_'+rowid;
    $(sel).html(selects[fld]);
    $('#'+fld+'_id').attr('id', fld + '_' + rowid + '_txt');
    if(selectVals[rowid]) {
        $('#'+fld + '_' + rowid + '_txt').val(selectVals[rowid][fld]);
    }
}

<!-- delete -->
$('.delete').click(
function(evt) {
    var chosen = $('.bchk:checked');
    if(chosen.length == 0) {
        alert('Select at least one BED file to delete.');
        return;
    }
    var article = (chosen.length > 1 ? 'these' : 'this');
    var plural = (chosen.length > 1 ? 's' : '');
    if(confirm('Are you sure? You will permanently delete ' + article + ' bedfile'+plural+'. This cannot be undone.')) {
        var idsToDel = Array();
        chosen.each(
        function(i, elt) {
            idsToDel.push($(elt).attr('id').replace('bed_', ''));
            if(i == chosen.length - 1) {
                $.getJSON("del.php", {ids:idsToDel,experiment_id:<?= $_GET['id'] ?>},
                function(resp) {
                    if(resp['err']) {
                        alert(resp['err']);
                    }
                    for(j in resp['ids']) { // hide deleted guys
                        $('tr[bedid='+idsToDel[j]+']').css('text-decoration', 'line-through');
                        $('#bed_'+idsToDel[j]).remove();
                    }
                });
            }
        });
    }
});

<!-- UCSU -->
$('.ucsc').click(
function(evt) {
    var chosen = $('.bchk:checked');
    var idsToView = Array();
    chosen.each(
    function(i, elt) {
        idsToView.push($(elt).attr('id').replace('bed_', ''));
        if(i == chosen.length - 1) {
            $.getJSON("ucsc.php", {ids:idsToView},
            function(resp) {
                if(resp['err']) {
                    alert(resp['err']); // for example, if you've chosen a bedfile without a genome assigned
                } else {
                    var formHtml = '<form id="ucscview" method="post" action="<?php echo UCSC_VIEW_URL ?>" target="_blank"><input type="hidden" name="org" value="'+resp['org']+'">'+
                                   '<input type="hidden" name="clade" value="'+resp['clade']+'"><input type="hidden" name="db" value="'+resp['db']+'">'+
                                   '<input type="hidden" name="hgsid" value="192769869">'+
                                   '<input type="hidden" name="hgct_customText" value="'+resp['urls']+'"></form>';
                    $('#ucscview').remove();   // remove previous just in case
                    $('body').append(formHtml);
                    $('#ucscview').submit();
                }
            });
        }
    });
});

<!-- DOWNLOAD-->
$('#download_dialog').dialog({autoOpen:false, width:500, close:function(evt, ui) { $('#chosen_to_download').remove();} });
$('.download').click(
function(evt) {
    var chosen = $('.bchk:checked');
    var dlgContent = '<ul id="chosen_to_download">';
    chosen.each(
    function(i, elt) {
        if(i == 7) {
            dlgContent += "<li>...</li>";
        } else if(i < 7) {
            var bed_id = $(elt).attr('id').replace('bed_', '');
            dlgContent += "<li>" + $('#name_' + bed_id).text() + "</li>";
        }
        if(i == chosen.length - 1) {
            dlgContent += '</ul>';
        }
    });
    $('#download_dialog').prepend(dlgContent);
    $('#dl_suffix_keep').attr('checked', 'true');
    $('#download_dialog').dialog('open');
});
$('#download_ok').click(
function(evt) {
    var chosen = $('.bchk:checked');
    var idsToDL = Array();
    chosen.each(
    function(i, elt) {
        idsToDL.push($(elt).attr('id').replace('bed_', ''));
        if(i == chosen.length - 1) {
            var d = new Date();
            var mo = d.getMonth() + 1;
            var day = d.getDate();
            var yr = d.getYear() + 1900;
            var suffix = $('input[name=dl_suffix]:checked').val();
            if(suffix == 'custom') {
                suffix = $('#dl_suffix_custom_value').val();
            }
            console.log(suffix);
            window.location = "download.php?archive_name=dasr_download_" + mo + '-' + day + '-' + yr + '&' +jQuery.param({ids:idsToDL,suffix:suffix});
        }
    });
    $('#download_dialog').dialog('close');
});
$('#download_cancel').click(
function(evt) {
    $('#download_dialog').dialog('close');
});
$('#copyref').click(
function(evt) {
    $.getJSON('copy.php', {experiment_id:<?php echo $_GET['id'] ?>, ref_ids:[$('#ref_bed_select').val()]}, addNewFileRows);
    //function(resp) {
    //    
    //});
});
<?php
$newrow = '';
foreach($fieldmap as $f) {
    if($f == 'name') {
        $newrow .= "<td id=\"${f}_'+file.id+'\"><a href=\"bedinfo.php?id='+file.id+'\">'+file.$f+'</a></td>";
    } else {
        $newrow .= "<td id=\"${f}_'+file.id+'\">'+file.$f+'</td>";
    }
}
?>
<!-- addNewFileRows -->
function addNewFileRows(filelist) {
    if(filelist.length == 0) {
        return;
    }
    var newrows = '';
    for(i in filelist) {
        file = filelist[i];
        newrows += '<tr bedid="'+file.id+'" style="background-color:#7bc7ec"><td><input class="bchk" type="checkbox" checked="true" id="bed_'+file.id+'"/></td><?php echo $newrow ?>';
    }
    selectVals[file.id] = Array();
    selectVals[file.id]['genome'] = file.genome;
    selectVals[file.id]['method'] = file.method;
    $('#bedfiletable').append(newrows);
    if(!$('#bedfiletable').is(':visible')) {
        $('#bedfiletable').show();
        $('#nofiles').hide();
        //$('.action').attr('disabled', false);
        $('.buttons').show();
    }
    $.getJSON("updbedcount.php", {experiment_id:<?php echo $_GET['id']; ?>});
    //return $('<tr><td><img src="img/chk.png"><\/td><td>' + file.name + '<\/td><\/tr>');
}
var compBedIds = Array();

<!-- Compare -->
$('.compare').click(
function(evt) {
    var chosen = $('.bchk:checked');
    if(chosen.length != 2) {
        alert('Select two BED files to compare.');
        return;
    }
    var dlgContent = '<ul id="chosen_to_compare">';
    chosen.each(
    function(i, elt) {
        var bed_id = $(elt).attr('id').replace('bed_', '');
        compBedIds[i] = bed_id;
        dlgContent += "<li>" + $('#name_' + bed_id).text() + "</li>";
        if(i == 1) {
            dlgContent += '</ul>';
        }
    });
    $('#compare_dialog').prepend(dlgContent);
    $('#compare_dialog').dialog('open');
});
$('#compare_dialog').dialog({autoOpen:false, width:500});
$('#compare_cancel').click(
function(evt) {
    $('#compare_dialog').dialog('close');
    $('#chosen_to_compare').remove();
});
$('#compare_ok').live('click',
function(evt) {
    $.getJSON('compsvc.php', {bed_id1:compBedIds[0], bed_id2:compBedIds[1], experiment_id:<?php echo $_GET['id'] ?>, bp_overlap:$('#compare_bp_overlap').val()}, 
    function(filelist) {
        $('.compare img').attr('src', 'img/compare.png');
        addNewFileRows(filelist);
    });
    $('#compare_dialog').dialog('close');
    $('#chosen_to_compare').remove();
    $('.compare img').attr('src', 'img/spinner.gif');
});
var extrBedIds = Array();

<!-- EXTRACT -->
$('.extract').click(
function(evt) {
    var chosen = $('.bchk:checked');
    if(chosen.length != 1) {
        alert('Select one BED file from which to extract.');
        return;
    }
    extrBedIds[0] = $(chosen[0]).attr('id').replace('bed_', '');
    $.getJSON("getchroms.php", {bed_id:extrBedIds[0]}, 
    function(resp) {
        $('#extract_chrom').html(resp['sel']);
    });
    $('#extract_by_chrom').attr('checked', false);
    $('#extract_dialog').dialog('open');
});
$('#extract_dialog').dialog({autoOpen:false, width:500});
$('#extract_cancel').click(
function(evt) {
    $('#extract_dialog').dialog('close');
});
$('#extract_ok').click(
function(evt) {
    //save_dasr:$('#save_dasr').is(':checked')},
    $.getJSON('extrsvc.php', {bed_ids:extrBedIds, experiment_id:<?php echo $_GET['id'] ?>, chrom:$('#extr_chrom_select').val(), start:$('#extr_chrom_start').val(), end:$('#extr_chrom_end').val(), rgb:$('#extr_rgb').val(), split:$('#extract_by_chrom').is(':checked')},
    function(resp) {
        $('.extract img').attr('src', 'img/split.png');
        if(resp['err']) {
            alert(resp['err']);
        } else {
            addNewFileRows(resp['filelist']);
        }
    });
    $('#extract_dialog').dialog('close');
    $('.extract img').attr('src', 'img/spinner.gif');
});
$('#extract_by_chrom').change(
function(evt) {
    if($('#extract_by_chrom').is(':checked')) {
        $('#extr_chrom_select').attr('disabled', 'disabled');
    } else {
        $('#extr_chrom_select').attr('disabled', false);
    }
});

<!-- Reference -->
$('.reference').click(
function(evt) {
    var chosen = $('.bchk:checked');
    var refBedIds = jQuery.map(chosen, function(elt, i) { return $(elt).attr('id').replace('bed_', ''); });
    $.getJSON('refsvc.php', {ids:refBedIds},
    function(resp) {
        //jQuery.each(refBedIds, function(i, elt) { $('tr[bedid='+elt+'] img.ref').toggle(); });
        window.location = 'exp.php?id=<?php echo $_GET['id'] ?>'; // lazy
    });
});
</script>

<?php
$foot_insert = <<<EOT
<script src="js/jquery.fileupload.js"></script>
<script src="js/jquery.fileupload-ui.js"></script>
<script>
$('#allnone').change(
function(evt) {
    if($(evt.target).attr('checked')) {
        $('.bchk').attr('checked', 'checked');
        $(evt.target).attr('title', 'Select none');
    } else {
        $('.bchk').attr('checked', false);
        $(evt.target).attr('title', 'Select all');
    }
});
/*global $ */
$(function () {
    $('#file_upload').fileUploadUI({
        uploadTable: $('#files'),
        downloadTable: $('#files'),
        buildUploadRow: function (files, index) {
            return $('<tr><td>' + files[index].name + '<\/td>' +
                    '<td class="file_upload_progress"><div><\/div><\/td>' +
                    '<td class="file_upload_cancel">' +
                    '<button class="ui-state-default ui-corner-all" title="Cancel">' +
                    '<span class="ui-icon ui-icon-cancel">Cancel<\/span>' +
                    '<\/button><\/td><\/tr>');
        },
        buildDownloadRow: addNewFileRows
		
    });
});
</script>
EOT;
require_once 'footer.inc.php';
?>
