<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2009-11-11
 * Modified    : 2010-04-27
 * For LOVD    : 2.0-26
 *
 * Access      : Curators and up.
 * Purpose     : Provide JavaScript for checking the submitted edit/create gene
 *               form.
 *
 * Copyright   : 2004-2010 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmer  : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 * Last edited : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 *
 *
 * This file is part of LOVD.
 *
 * LOVD is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * LOVD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LOVD; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *************/

define('ROOT_PATH', './');
// Here we are again with this weird solution. We can't directly connect to an outside URL using AJAX, and therefore we have to connect to ourselves with AJAX and connect outside using PHP.
if (!empty($_GET['check'])) {
    if (preg_match('/^(hg[0-9]{2}),(N[MR]_[0-9]{6,9}(\.[0-9]{1,2})?)$/', $_GET['check'], $aRegs)) {
        list(, $sBuild, $sRefSeq) = $aRegs;
        header('Content-type: text/plain; charset=ISO-8859-1');
        require ROOT_PATH . 'inc-init.php';
        $aOut = lovd_php_file('http://www.mutalyzer.nl/2.0/Variant_info?LOVD_ver=' . $_SETT['system']['version'] . '&build=' . $sBuild . '&acc=' . $sRefSeq);
        // 2010-01-07; 2.0-24; Make sure we're parsing an array to prevent errors.
        if (!is_array($aOut)) {
            die('Error while retrieving information on this reference sequence.');
        }
        foreach ($aOut as $key => $val) { $aOut[$key] = trim($val); } // To clean $aOut from the newlines at the end.
        if (count($aOut) == 1 && preg_match('/^Error \(Variant_info\): Reference sequence (version )?not found\.( Available: (.+))?$/', $aOut[0], $aRegs)) {
            // Reference sequence is not correct.
            if (empty($aRegs[1]) || empty($aRegs[3])) {
                // The whole reference sequence is not found.
                die('Unfortunately, we can\'t map the variants to the genome using the ' . $sRefSeq . ' reference sequence - no information was found on this transcript.');
            } else {
                $sRefSeqAcc = substr($sRefSeq, 0, strpos($sRefSeq, '.'));
                die('Unfortunately, we can\'t map the variants to the genome using this version of the ' . $sRefSeqAcc . ' reference sequence. However, please consider using ' . $aRegs[3] . ' in stead.');
            }
        } elseif (count($aOut) == 3 && is_numeric($aOut[0]) && is_numeric($aOut[1]) && is_numeric($aOut[2])) {
            // All good.
            $aResult = $aOut;
            // Now, we also need the genomic position of the start and end coordinates.
            $aOut = lovd_php_file('http://www.mutalyzer.nl/2.0/Variant_info?LOVD_ver=' . $_SETT['system']['version'] . '&build=' . $sBuild . '&acc=' . $sRefSeq . '&var=c.' . $aOut[0] . '_' . $aOut[1] . 'del');
            // 2010-01-07; 2.0-24; Make sure we're parsing an array to prevent errors.
            if (!is_array($aOut)) {
                $aOut = array();
            }
            foreach ($aOut as $key => $val) { $aOut[$key] = trim($val); } // To clean $aOut from the newlines at the end.
            if (count($aOut) == 7) {
                $aResult[] = $aOut[4]; // g_position_mrna_start
                $aResult[] = $aOut[5]; // g_position_mrna_end
            } else {
                // Whatever...
                $aResult[] = 0;
                $aResult[] = 0;
            }
            die('OK:' . implode(',', $aResult));
        } else {
            // OK, not sure what we're getting. Send it through.
            die(implode("\n", $aOut));
        }
    } else {
        // 2010-04-27; 2.0-26; Don\'t show an empty error when the format is not correct.
        die('Can\'t recognize the accession number for the transcript reference sequence; did you type it in correctly?');
    }
    exit;
}

require ROOT_PATH . 'inc-js-ajax.php';
?>

function lovd_checkSubmittedForm () {
    if (document.forms[0].genbank.value == 0 && document.forms[0].genbank_uri.value == '') {
        if (!window.confirm('Are you sure you don\'t want to select a GenBank file for this gene database? Without a reference sequence, submitters cannot check their submissions to your database and in case of multi-transcript genes, variants in your database cannot be interpreted properly. Press "Cancel" to return to the form to fill in a GenBank file, or "OK" to ignore this error.')) {
            scroll(0,0);
            return false;
        }
    } else if (document.forms[0].refseq_mrna.value != '' && document.forms[0].refseq_build.value != '----') {
        // Check specific transcript to see if we can align it.
        // 2010-01-28; 2.0-24; Need to access other file over same protocol; accessing http file from https page is not allowed by FireFox.
        // 2010-04-26; 2.0-26; Added .trim() for mRNA value, to remove additional spaces that makes the output return empty.
        objHTTP = lovd_HTTPRequest("<?php echo (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' && !empty($_SERVER['SSL_PROTOCOL'])? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']; ?>?check=" + escape(document.forms[0].refseq_build.value) + "%2C" + escape(document.forms[0].refseq_mrna.value.trim()));
        if (objHTTP) {
            if (objHTTP.status == 200 && objHTTP.responseText.substring(0,3) == "OK:") {
                aLocations = objHTTP.responseText.substr(3).split(',');
                document.forms[0].c_position_mrna_start.value = aLocations[0];
                document.forms[0].c_position_mrna_end.value = aLocations[1];
                document.forms[0].c_position_cds_end.value = aLocations[2];
                document.forms[0].g_position_mrna_start.value = aLocations[3];
                document.forms[0].g_position_mrna_end.value = aLocations[4];
                return true;
            } else {
                // Throw error. Just return whatever we got, and give the user the choice what to do.
                if (!window.confirm(objHTTP.responseText + '\nPress "Cancel" to return to the form, or "OK" to ignore this error.')) {
                    scroll(0,0);
                    return false;
                }
            }
        } // Not? Whatever. At least we tried.
    }

    return true;
}