<%--
    Document   : searchResult
    Created on : May 28, 2013, 8:34:18 AM
    Author     : Joos Kiener <Joos.Kiener@gmail.com>
--%>

<jsp:include page="/WEB-INF/jsp/header.jsp"/>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<script type="text/javascript">
    var dataTable;
    // puts query string parameters in a object using Jquery bbq plugin
    // (https://github.com/cowboy/jquery-bbq)
    var urlParams = $.deparam.querystring();

    $(function() {

        $('#sdfDownloadLink a').attr('href','downloadHits?structure=' + urlParams['structure']
            + '&cas=' + urlParams['cas']+ '&compoundName=' + urlParams['compoundName']
            + '&compoundDescription=' + urlParams['compoundDescription']);

        $('#dataTable').delegate('td img', 'click', function() {
            alert($(this).attr('alt'));
        });

        var displayStart = 0;
        var displayLength = 4;

        var scrollY = "700";
        if (screen.height<=768){
            displayLength = 3;
            scrollY = "550";
        }

        if ($.bbq.getState('iDisplayStart')){
            displayStart = $.bbq.getState('iDisplayStart', true);
        }

        dataTable = $('#dataTable').dataTable( {
            //"sDom": 'l<"toolbar">rtip',
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": "/MDFSimpleWebApp/compound/search",
            "sAjaxDataProp": "aaData",
            "bLengthChange": false,
            "sScrollY": scrollY,
            "iDisplayLength": displayLength,
            "iDisplayStart": displayStart,
            "sPaginationType": "full_numbers",
            "bSort": false,
            "bFilter": false,
            "bAutoWidth": false,
            "aoColumns": [
                {
                    "sTitle" : "Structure",
                    "mData": "structure",
                    "bSearchable": false,
                    "bSortable": false,
                    "sWidth": "400px",
                    "fnRender": function ( oObj ) {
                        if (oObj.aData['id'] != ''){
                            var smiles = oObj.aData['smiles'];
                            var html;
                            if(urlParams['structure']){
                            html = '<img alt="' + smiles
                                + '" src="/MDFSimpleWebApp/compound/'
                                + oObj.aData['id'] + '/render/highlight/' + urlParams['structure'] +'"/>';
                            } else {
                                html = '<img alt="' + smiles
                                + '" src="/MDFSimpleWebApp/compound/'
                                + oObj.aData['id'] + '/render/"/>';
                            }
                            return html;
                        } else {
                            return '';
                        }
                    }
                },
                {
                    "sTitle" : "Compound Name",
                    "mDataProp": "compoundName",
                    "bSearchable": true,
                    "bSortable": true,
                    "sWidth": "200px",
                    "fnRender": function ( oObj ) {
                        if (oObj.aData['compoundName'] != ''){
                            var html = '<a href="/MDFSimpleWebApp/compound/'
                                + oObj.aData['id'] + '/">'
                                + oObj.aData['compoundName'] + '</a>';
                            return html;
                        } else {
                            return '';
                        }
                    }
                },
                {
                    "sTitle" : "CAS",
                    "mData": "cas", "bSearchable": true,
                    "bSortable": true,
                    "sWidth": "50px"
                }
            ],
            "fnServerData": function ( sSource, aoData, fnCallback ) {
                /* Add all request parameters to the AJAX call
                 * iDisplayStart and iDisplayLength are handeled by datatables
                 * -> do not forward them
                 */
                for (var key in urlParams){
                    if(key != "iDisplayStart" && key != "iDisplayLength"){
                        aoData.push( { "name": key, "value": urlParams[key] } );
                    }
                }

                $.ajax( {
                    "dataType": 'json',
                    "type": "GET",
                    "url": sSource,
                    "data": aoData,
                    "cache": true,
                    "success": function(data){
                        fnServerSideCallback(data);
                        fnCallback(data); // draw the table
                    },
                    "error": function(jqXHR, textStatus, errorThrown){
                        var errorText = errorThrown + ": " + jqXHR.responseText;
                        $('#footWide').before('<div class="error">' + errorText + '</div>');
                    }
                } );
            }
        } );
    } );

    function fnServerSideCallback(data) {
        $('#hitsFound').text("Hits Found: " + data.iTotalDisplayRecords);
        $('#totalRecords').text("Total Records: " + data.iTotalRecords);
        buildSmiles(data);
    }

    function buildSmiles(data) {
        var aaData = data.aaData;
        $.each(aaData, function(index, compound){
            var smiles = "";
            $.each(compound.compositions, function(index, composition){
                var chemicalStructure = composition.chemicalStructure;
                if (typeof chemicalStructure !== 'object' ){
                    chemicalStructure = resolveChemicalStructure(aaData, composition.chemicalStructure);
                }
                smiles += chemicalStructure.structureData + ".";
            });
             smiles =  smiles.substring(0,  smiles.length - 1);
            compound["smiles"] = smiles;
            compound["structure"] = "";
        });
        return true;
    }

    function resolveChemicalStructure(aaData, jsonId) {
        var result = null;
        $.each(aaData, function(index, compound){
            $.each(compound.compositions, function(index, composition) {
                var chemicalStructure = composition.chemicalStructure;
                if (typeof chemicalStructure === 'object' ){
                    if (chemicalStructure["@id"] == jsonId){
                        result = chemicalStructure;
                        return false;
                    }
                }
            });
        });
        return result;
    }
</script>
<div id="toolbar">
    <h1 id="hitsFound">Hits Found:</h1>
    <h1 id="totalRecords">Total Records:</h1>
    <div id="sdfDownloadLink"><a href="">Download Hits</a></div>
</div>
<table id="dataTable">
    <thead>
        <tr>
            <th>Structure</th>
            <th>Compound Name</th>
            <th>CAS</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<jsp:include page="/WEB-INF/jsp/footer.jsp"/>
