/*
 * PiAnoS (Picture Annotation System), A fingerprint examiner training tool Copyright (C) 2011-2012 University of Lausanne, Switzerland
 * https://ips-labs.unil.ch/pianos This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
 * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program
 * 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public
 * License along with this program. If not, see http://www.gnu.org/licenses/.
 */

/**
 * @constructor
 */
function Pianos4ToolLR( params )
{
    // ------------------------------
    // Constructor
    // ------------------------------
    
    // ------------------------------
    // Public methods
    // ------------------------------
    
    this.getName = function()
    {
        return 'SLR';
    }

    this.getLabel = function()
    {
        if( pianos.getParams().phase == "analysis" )
            return 'ESLR';
        else
            return 'SLR';
    }

    this.getIcon = function()
    {
        if( pianos.getParams().phase == "analysis" )
            return 'icons/tool_ESLR.png';
        else
            return 'icons/tool_LR.png';
    }

    this.bind = function( aView )
    {
        assert( !view );
        view = aView;
    }

    this.unbind = function()
    {
        assert( view );
        view = null;
    }

    this.activate = function()
    {
        needToCheckClusterState = true;
    }

    this.deactivate = function()
    {
        needToCheckClusterState = false;
    }

    this.onMouseDown = function( pos, target, event )
    {
    }

    this.onMouseMove = function( pos, target )
    {
    }

    this.onMouseUp = function( pos, target, event )
    {
    }

    this.cancel = function()
    {
    }

    this.getOptionsPanel = function()
    {
        if( !options )
        {
            panel = $( '<div />' ).addClass( 'pianos4_NIST_options' );
            
            var div = $( '<div />' );
            
            // Advance search
            var gpselect = $( '<a />' )
                .text( 'Advanced' )
                .attr( 'href', '#gp' )
                .bind( 'click', function( e )
                {
                    e.preventDefault();
                    lr_advanced_search();
                } );
            
            // sumbit
            var submitter = $( '<a />' )
                .text( 'Send' )
                .attr( 'href', '#lr' )
                .bind( 'click', function( e )
                {
                    e.preventDefault();
                    gpselectvalue = [];
                    
                    if( ! pianos.getParams().user.tutor )
                        xena_submit();
                    else
                        toastr.info( "Switch to a particular user to send the configuration in the calculator" );
                } );
            
            // Getter
            var getter = $( '<a />' )
                .text( 'Get' )
                .css( 'text-decoration', 'underline' )
                .css( 'cursor', 'pointer' )
                .on( 'click', function()
                {
                    onGetLRs();
                } ); 
                
            // Cluster status
            var statusdiv = $( '<div />' )
                .css( 'margin-top', '5px' )
                .css( 'display', 'grid' )
                .css( 'grid-template-columns', '30px auto' )
                .css( 'align-items', 'center' )
                .append(
                    $( '<div />' )
                        .text( 'State: ' )
                )
                .append(
                    $( '<div />' )
                        .attr( 'id', 'clusterstatus' )
                );
            
            // Composition
            div.append( submitter );
            div.append( '<br />' );
            div.append( getter );
            div.append( '<br />' );
            div.append( gpselect );
            div.append( '<br />' );
            div.append( statusdiv );
            
            // panel
            panel.append( div );
            
            options = panel;
        }
        
        return options;
    }
    
    this.afterLoaded = function()
    {
        $( '#clusterstatus' ).empty();
        
        var svgContainer = d3.select( '#clusterstatus' )
            .append( 'svg' )
            .attr( 'width', 32 )
            .attr( 'height', 16 );
        
        svgContainer.append( "circle" )
            .attr( 'id', 'clusterinput' )
            .attr( "cx", 8 )
            .attr( "cy", 8 )
            .attr( "r", 8 )
            .attr( 'fill', '#006DF0' );
        
        checkClusterState();
    }
    
    this.getHelp = function()
    {
        return Pianos4Help.compile( [
            ''
        ] );
    }

    // ------------------------------
    // Private variables
    // ------------------------------
    
    var self = this;
    var view = null;
    var options = null;
    
    var serverData = null;
    var serverDataIdx = null;
    
    var panel = null;
    var form = null;
    var downloadData = null;
    var exidData = null;
    
    var needToCheckClusterState = true;
    var currentClusterState = null;
    
    var gpselectvalue = [];
    var fingerselectvalue = [];
    var gpimpactvalue = false;
    var removecomparisonminutiae = false;
    var computealllrs = false;
    
    // ------------------------------
    // Private functions
    // ------------------------------
    
    var checkClusterState = function()
    {
        if( needToCheckClusterState )
        {
            $.ajax(
            {
                dataType: 'json',
                type: 'GET',
                url: pianos.getParams().Xena_api_state,
                success: function( d )
                {
                    var col = "";
                    if( d.data.Inputer === 'green' && d.data.Linux === 'green' && d.data.DMA === 'green' )
                    {
                        col = '#109618';
                        currentClusterState = "green";
                        
                    } else if( d.data.Inputer === 'red' || d.data.Linux === 'red' || d.data.DMA === 'red' ) {
                        col = '#dc3912';
                        currentClusterState = "red";
                        
                    } else {
                        col = '#ff9900';
                        currentClusterState = "orange";
                    }
                    
                    $( '#clusterinput' )
                        .css( 'fill', col );
                },
                error: function()
                {
                    $( '#clusterstatus > svg > circle' )
                        .css( 'fill', '#dc3912' );    
                }
            } );
            
            setTimeout( checkClusterState, 5000 );
        }
    }
    
    var returnData = function()
    {
        var data = pianos.getData();
        
        for( k in data )
        {
            if( k != "mark" & k != "print" )
            {
                delete data[ k ];
            } else {
                for( var j in data[ k ] )
                    if( j != "image" && j != "minutiae" )
                        delete data[ k ][ j ];
            }
        }

        return data;
    }
    
    var toJSON = function( data )
    {
        return JSON.stringify( data )
    }
    
    var checkData = function( data )
    {
        // Center
        hasCenter = false;
        
        for( m in data.print.minutiae )
        {
            if( data.print.minutiae[m].type == "center" )
            {
                hasCenter = true;
                break;
            }
        }

        // Number of paired minutiae above the minimum of the calculator
        paired = 0;
        
        for( m in data.print.minutiae )
        {
            if( data.print.minutiae[m].type != "center" & data.print.minutiae[m].type != "difference" & data.print.minutiae[m].pairing !== undefined )
                paired += 1;
        }
        
        minPaired = paired >= 4;
        
        // Post processing
        if( hasCenter == false )
        {
            if( pianos.getParams().phase == "analysis" )
                toastr.error( "You need to annotate the center on the mark" );
            else
                toastr.error( "You need to annotate the center on the print" );
            
            return false;
        } else if ( minPaired == false )
        {
            if( pianos.getParams().phase == "analysis" )
                toastr.error( "At least 4 minutiae have to be annotated" );
            else
                toastr.error( "At least 4 minutiae have to be paired" );
            return false;
        } else {
            return true;
        }
    }
    
    var lr_advanced_search = function()
    {
        var clear = function()
        {
            gpselectvalue = [];
            fingerselectvalue = [];
            gpimpactvalue = false;
            removecomparisonminutiae = false;
            computealllrs = false;
        }
        clear();
        
        var gpGetSel = function( label )
        {
            var items = [];
            gpbuttons.find( '.ui-state-highlight' ).each( function()
            {
                var data = $( this ).data( 'pianos4' );
                var t = label ? data.label : data.id;
                items.push( t );
            } );
            if( items.length == 4 )
                return [ 'All' ];
            else
                return items;
        }
        
        var gpUpdateSel = function()
        {
            var items = gpGetSel( true );
            var span = $( '#gpchoice' )
            if( items.length )
                span.text( items.join( ', ' ) );
            else
                span.text( 'All' );
        }
        
        var fingerGetSel = function( label )
        {
            var items = [];
            fingerbuttons.find( '.ui-state-highlight' ).each( function()
            {
                var data = $( this ).data( 'pianos4' );
                var t = label ? data.label : data.id;
                items.push( t );
            } );
            if( items.length == 10 )
                return [ 'All' ];
            else
                return items;
        }
        
        var fingerUpdateSel = function()
        {
            var items = fingerGetSel( true );
            var span = $( '#fingerchoice' )
            if( items.length )
                span.text( items.join( ', ' ) );
            else
                span.text( 'All' );
        }
        
        var get_gpimpact = function()
        {
            return $( '#gpimpact' )[ 0 ].checked;
        }
        
        var get_modified = function()
        {
            return $( '#modified' )[ 0 ].checked;
        }
        
        var get_alllrs = function()
        {
            return $( '#alllrs' )[ 0 ].checked;
        }
        
        var gplist = [
            {
                id: 'W',
                label: 'Whorl',
                url: 'css/general_patterns/whorl_h_1.jpg'
            },
            {
                id: 'L',
                label: 'Left loop',
                url: 'css/general_patterns/l_loop_h_1.jpg'
            },
            {
                id: 'R',
                label: 'Right loop',
                url: 'css/general_patterns/r_loop_h_1.jpg'
            },
            {
                id: 'A',
                label: 'Arch',
                url: 'css/general_patterns/arch_h_2.jpg'
            }
        ];
        
        var fingerlist = [
            {
                id: '1',
                label: 'Right thumb'
            },
            {
                id: '2',
                label: 'Right index'
            },
            {
                id: '3',
                label: 'Right middle'
            },
            {
                id: '4',
                label: 'Right ring'
            },
            {
                id: '5',
                label: 'Right little'
            },
            {
                id: '6',
                label: 'Left thumb'
            },
            {
                id: '7',
                label: 'Left index'
            },
            {
                id: '8',
                label: 'Left middle'
            },
            {
                id: '9',
                label: 'Left ring'
            },
            {
                id: '10',
                label: 'Left little'
            }
        ];
        
        var div = $( '<div />' );
        
        var gpheader = $( '<div />' )
            .css( 'margin-bottom', '1em' )
            .text( "Selection of the general pattern(s) to search against in the AFIS:" )
        
        var gpbuttons = $( '<div />' )
            .css( 'display', 'grid' )
            .css( 'grid-template-columns', 'repeat( 4, 1fr )' )
            .css( 'grid-gap', '5px' );
        
        var imgsize = 128;
        var frameheight = 150;
        
        for( var i in gplist )
        {
            var gp = gplist[ i ];
            
            var frame = $( '<span />' )
                .css( 'display', 'inline-block' )
                .width( imgsize )
                .height( frameheight );
            
            var image = $( '<img />' )
                .attr( 'src', gp.url )
                .width( imgsize )
                .height( imgsize );
            
            var label = $( '<span />' )
                .css( 'display', 'inline-block' )
                .width( imgsize )
                .css( 'text-align', 'center' );
            
            label.text( gp.label );
            
            frame.append( image );
            frame.append( label );
            
            var button = $( '<div >' )
                .css( 'display', 'inline-block' )
                .css( 'padding', '1em' )
                .addClass( 'ui-state-default ui-corner-all' )
                .css( 'cursor', 'pointer' )
                .hover(
                    function() { $( this ).addClass( 'ui-state-hover' ); },
                    function() { $( this ).removeClass( 'ui-state-hover' ); }
                )
                .click( function( e )
                {
                    $( this ).toggleClass( 'ui-state-highlight' );
                    gpUpdateSel();
                } );
            
            if( gpselectvalue.indexOf( gp.id ) >= 0 )
                button.addClass( 'ui-state-highlight' );
            
            button.append( frame );
            button.data( 'pianos4', gp );
            gpbuttons.append( button );
        }
        
        var fingerheader = $( '<div />' )
            .css( 'margin-top', '1em' )
            .css( 'margin-bottom', '1em' )
            .text( "Selection of the finger number(s) to search against in the AFIS:" );
        
        var fingerbuttons = $( '<div />' )
            .css( 'display', 'grid' )
            .css( 'grid-template-columns', 'repeat( 5, 1fr )' )
            .css( 'grid-gap', '5px' )
            .appendTo( div );
        
        for( var i in fingerlist )
        {
            var finger = fingerlist[ i ];
            
            var frame = $( '<span />' );
            
            var label = $( '<span />' )
                .css( 'text-align', 'center' );
            
            label.text( finger.label );
            
            frame.append( label );
            
            var button = $( '<div >' )
                .css( 'display', 'inline-block' )
                .css( 'padding', '1em' )
                .addClass( 'ui-state-default ui-corner-all' )
                .css( 'cursor', 'pointer' )
                .hover(
                    function() { $( this ).addClass( 'ui-state-hover' ); },
                    function() { $( this ).removeClass( 'ui-state-hover' ); }
                )
                .click( function( e )
                {
                    $( this ).toggleClass( 'ui-state-highlight' );
                    fingerUpdateSel( fingerbuttons );
                } );
            
            if( fingerselectvalue.indexOf( finger.id ) >= 0 )
                button.addClass( 'ui-state-highlight' );
            
            button.append( frame );
            button.data( 'pianos4', finger );
            fingerbuttons.append( button );
        }
        
        var gpimpact_header = $( '<div />' )
            .text( 'Show impact of the general pattern selection on the between variability in the PDF report' );
        
        var gpimpact_toggle = $( '<div />' )
            .append(
                $( '<input />' )
                    .attr( 'type', 'checkbox' )
                    .attr( 'id', 'gpimpact' )
                    .css( 'display', 'none' )
            )
            .append(
                $( '<label />' )
                    .attr( 'for', 'gpimpact' )
                    .attr( 'class', 'toggle' )
                    .append( $( '<span />' ) )
            );
        
        var togglesoptions = $( '<div />' )
            .css( 'margin-top', '1em' )
            .css( 'display', 'grid' )
            .css( 'grid-template-columns', 'auto 50px' )
            .append( gpimpact_header )
            .append( gpimpact_toggle );
        
        if( pianos.getParams().phase == "comparison" )
        {
            
            var modified_header = $( '<div />' )
                .text( 'Do not use the minutiae annotated/modified in the comparison phase' );
            
            var modified_toggle = $( '<div />' )
                .append(
                    $( '<input />' )
                        .attr( 'type', 'checkbox' )
                        .attr( 'id', 'modified' )
                        .css( 'display', 'none' )
                )
                .append(
                    $( '<label />' )
                        .attr( 'for', 'modified' )
                        .attr( 'class', 'toggle' )
                        .append( $( '<span />' ) )
                );
            
            togglesoptions
                .append( modified_header )
                .append( modified_toggle );
        }
        
        var alllrs_header = $( '<div />' )
            .text( 'Calculate all (E)SLRs for all General Pattern / Finger Number possibility' );
        
        var alllrs_toggle = $( '<div />' )
            .append(
                $( '<input />' )
                    .attr( 'type', 'checkbox' )
                    .attr( 'id', 'alllrs' )
                    .css( 'display', 'none' )
            )
            .append(
                $( '<label />' )
                    .attr( 'for', 'alllrs' )
                    .attr( 'class', 'toggle' )
                    .append( $( '<span />' ) )
            );
        
        togglesoptions
            .append( alllrs_header )
            .append( alllrs_toggle );
        
        var cursel = $( '<div />' )
            .css( 'margin-top', '1em' )
            .append(
                $( '<span />' )
                    .text( 'Your current general pattern choice(s):' )
                    .css( 'margin-right', '1em' )
            )
            .append(
                $( '<span />' )
                    .attr( 'id', 'gpchoice' )
                    .text( 'All' )
                    .css( 'font-style', 'italic' )
            )
            .append( $( '<br />' ) )
            .append(
                $( '<span />' )
                    .text( 'Your current finger number choice(s):' )
                    .css( 'margin-right', '1em' )
            )
            .append(
                $( '<span />' )
                    .attr( 'id', 'fingerchoice' )
                    .text( 'All' )
                    .css( 'font-style', 'italic' )
            );
        
        div.append( gpheader ).append( gpbuttons )
           .append( fingerheader ).append( fingerbuttons )
           .append( togglesoptions )
           .append( cursel );
        
        var dlgopts = {
            autoOpen : true,
            modal : true,
            width : 'auto',
            resizable: false,
            title : 'Advanced LR options',
            close : function()
            {
                clear();
                $( this ).remove();
            },
            buttons : {
                'Cancel / Clear' : function()
                {
                    clear();
                    $( this ).dialog( 'close' );
                },
                'Send and stay' : function()
                {
                    gpselectvalue = gpGetSel();
                    fingerselectvalue = fingerGetSel();
                    gpimpactvalue = get_gpimpact();
                    if( pianos.getParams().phase == "comparison" )
                        removecomparisonminutiae = get_modified();
                    
                    computealllrs = get_alllrs();
                    xena_submit();
                    
                    clear();
                },
                'Send and close' : function()
                {
                    gpselectvalue = gpGetSel();
                    fingerselectvalue = fingerGetSel();
                    gpimpactvalue = get_gpimpact();
                    if( pianos.getParams().phase == "comparison" )
                        removecomparisonminutiae = get_modified();
                    
                    computealllrs = get_alllrs();
                    xena_submit();
                    
                    clear();
                    $( this ).dialog( 'close' );
                }
            },
        };
        
        var dlg = $( '<div />' )
            .attr( 'id', 'pianos4_gpselect' )
            .addClass( 'pianos4_dialog' )
            .append( div );
        
        dlg.dialog( dlgopts );
    }
    
    onGetLRs = function()
    {
        var complete = function( data )
        {
            var dlgopts = {
                autoOpen : true,
                modal : true,
                width : '80%',
                title : 'All LRs',
                close : function()
                {
                    $( this ).remove();
                },
                open: function()
                {
                    $( ".ui-widget-overlay" ).bind( "click", function()
                    {
                        $( "#pianos4_getlr" ).dialog( "close" );
                        $( "#pianos4_getlr" ).remove();
                    } );
                },
                buttons : {
                    'Reload' : function()
                    {
                        $( this ).dialog( 'close' );
                        return onGetLRs();
                    },
                    
                    'Close' : function()
                    {
                        $( this ).dialog( 'close' );
                    }
                },
            };
            
            if( !data || data.error )
            {
                toastr.error( "Server error - no data returned" );
            } else {
                var div = $( '<div />' )
                    .attr( 'id', 'pianos4_lr_list' );
                
                var id_base = 'pianos4_resultdlg_opt_' + ( new Date().getTime() );
                
                var cols = [
                    {
                        title : 'Id',
                        render : function( data, i, j, cell )
                        {
                            cell.text( data[ i ].id );
                        }
                    }
                ];

                if( ! pianos.getParams().user.tutor || ( pianos.getParams().user.tutor && ! pianos.getParams().anonymous_review ) )
                {
                    cols.push.apply( cols, [
                        {
                            title : 'PDF',
                            render : function( data, i, j, cell )
                            {
                                cell.append( $( '<a />' ).text( 'PDF' ).attr( 'href', '?action=rpc&method=getlrpdf&id=' + data[ i ].id ) );
                            }
                        }
                    ] );
                }
                
                if( pianos.getParams().user.tutor && ! pianos.getParams().anonymous_review )
                {
                    cols.push.apply( cols, [
                        {
                            title : 'User',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].user );
                            }
                        }
                    ] );
                }
                
                cols.push.apply( cols, [
                    {
                        title : 'Time',
                        render : function( data, i, j, cell )
                        {
                            cell.text( data[ i ].time );
                        }
                    },
                    
                    {
                        title : 'Minutiae count',
                        render : function( data, i, j, cell )
                        {
                            cell.text( data[ i ].nb_min );
                        }
                    }
                ] );
                
                if( pianos.getParams().phase == "comparison" )
                {
                    cols.push.apply( cols, [
                        {
                            title : 'Bending Energy',
                            render : function( data, i, j, cell )
                            {
                                cell.text( data[ i ].be );
                            }
                        }
                    ] );
                }
                
                if( pianos.getParams().phase == "comparison" )
                {
                    cols.push.apply( cols, [
                        {
                            title : 'Score',
                            render : function( data, i, j, cell )
                            {
                                if( data[ i ].score !== null )
                                    cell.text( data[ i ].score );
                            }
                        },
                        
                        {
                            title : 'Rank',
                            render : function( data, i, j, cell )
                            {
                                if( data[ i ].rank !== null )
                                    cell.text( data[ i ].rank );
                            }
                        }
                    ] );
                }
                
                cols.push.apply( cols, [
                    {
                        title : 'DB size',
                        render : function( data, i, j, cell )
                        {
                            if( data[ i ].afis_db_size !== null )
                                cell.text( data[ i ].db_size );
                        }
                    },
                    
                    {
                        title : 'DB GP selection',
                        render : function( data, i, j, cell )
                        {
                            if( data[ i ].gpselect !== null )
                                cell.text( data[ i ].gpselect );
                        }
                    },
                    
                    {
                        title : 'DB finger selection',
                        render : function( data, i, j, cell )
                        {
                            if( data[ i ].fingerselect !== null )
                                cell.text( data[ i ].fingerselect );
                        }
                    }
                ] );
                
                if( pianos.getParams().phase == "comparison" )
                {
                    cols.push.apply( cols, [
                        {
                            title : 'δScore',
                            render : function( data, i, j, cell )
                            {
                                if( data[ i ].dev !== null )
                                    cell.text( data[ i ].dev );
                            }
                        }
                    ] );
                }
                
                cols.push.apply( cols, [
                    {
                        title : modeltype,
                        render : function( data, i, j, cell )
                        {
                            cell.text( data[ i ].LR );
                        }
                    },
                    
                    {
                        title : 'Log' + modeltype,
                        render : function( data, i, j, cell )
                        {
                            cell.text( data[ i ].log10_LR );
                        }
                    }
                ] );
                
                if( pianos.getParams().user.tutor && pianos.getParams().tutor_can_delete_lrs )
                {
                    cols.push(
                        {
                            title : 'Delete',
                            render : function( data, i, j, cell )
                            {
                                cell.append( $( '<img />' ).attr( 'src', 'css/icons/backend/Delete16.png' ).attr( 'alt', 'delete' ).css( 'cursor', 'pointer' ) ).click( function()
                                {
                                    $( '<div />' ).text( 'Do you really want to delete the LR report and data with the id ' + data[ i ].id + ' done by ' + data[ i ].user + ' ?' ).dialog( {
                                        title: "Confirm results deletion",
                                        width: 500,
                                        buttons: {
                                            'OK': function()
                                            {
                                                var dlg2 = $( this );
                                                pianos.ajax( {
                                                    pendingMessage: 'Deleting LR report',
                                                    type: 'post',
                                                    data: {
                                                        id: data[ i ].id
                                                    },
                                                    dataType: 'json',
                                                    url: '?action=rpc&method=deleteLR',
                                                    success: function( d )
                                                    {
                                                        if( ! d.error )
                                                        {
                                                            dlg2.dialog( 'close' );
                                                            dlg2.remove();
                                                            
                                                            dlg.dialog( 'close' );
                                                            dlg.remove();
                                                            
                                                            onGetLRs();
                                                        } else {
                                                            toastr.error( d.message );
                                                        }
                                                    },
                                                    error: function()
                                                    {
                                                        toastr.error( 'Network error' );
                                                    },
                                                } );
                                            },
                                            'Cancel': function()
                                            {
                                                $( this ).dialog( 'close' );
                                            },
                                        },
                                        close: function()
                                        {
                                            $( this ).remove();
                                        }
                                    } );
                                    
                                } );
                            }
                        }
                    );
                }
                
                div.qtable( {
                    data : processing( data.ret ),
                    columnMode : 'mapping',
                    columns : cols,
                } );
                
                var dlg = $( '<div />' )
                    .attr( 'id', 'pianos4_getlr' )
                    .addClass( 'pianos4_dialog' )
                    .css( 'max-height', $( window ).height() * 0.7 )
                    .append( div );
                
                dlg.dialog( dlgopts );
                
                $( '#pianos4_lr_list > table > thead' )
                    .css( 'cursor', 'n-resize' );
                
                $( '#pianos4_lr_list > table > tbody > tr' )
                    .removeClass( 'ui-qtable-row-odd ui-qtable-row-even' );
                
                $( '#pianos4_lr_list > table' )
                    .addClass( 'tablesorter' )
                    .addClass( 'tablesorter-default' )
                    .addClass( 'hover-highlight' )
                    .tablesorter({ 
                        widgets: [ 'zebra' ],
                    });
            }
        }

        var processing = function( data )
        {
            var ret = [];
            
            for( var i in data )
            {
                var d = data[ i ];
                
                ret.push( {
                    user : d.user,
                    id : d.id,
                    modeltype : d.modeltype,
                    time : d.time,
                    nb_min : parseInt( d.nb_min ),
                    be : parseFloat( d.Be ).toFixed( 4 ),
                    LR : parseFloat( d.LR ).toExponential( 4 ),
                    log10_LR : Math.log10( parseFloat( d.LR ) ).toFixed( 4 ),
                    rank : d.afis_rank,
                    score : d.afis_score,
                    dev : d.afis_dev,
                    db_size: d.afis_db_size,
                    gpselect: d.afis_db_gpselect,
                    fingerselect: d.afis_db_fingerselect
                } );
            }
            
            return ret;
        }
        
        $( '#pianos4_getlr' ).remove();
        
        var modeltype = pianos.getParams().phase == "analysis" ? "ESLR" : "LR";
        
        $.ajax( {
            pendingMessage : 'Loading LRs from database',
            url : '?action=rpc&method=getLRUsers&exid=' + pianos.getCaseID() + '&uid=' + pianos.getUser()[ 'id' ] + '&type=' + modeltype,
            dataType : 'json',
            success : function( data )
            {
                complete( data );
            },
            error : function()
            {
                toastr.error( "Network error" );
            }
        } );
    }
    
    xena_submit = function()
    {
        if( pianos.getParams().phase == "analysis" )
        {
            var tempData = $.extend( true, {}, returnData() );
            
            for( var i in tempData.mark.minutiae )
            {
                tempData.mark.minutiae[ i ].pairing = tempData.mark.minutiae[ i ].id;
            }
            tempData.print = tempData.mark;
            
        } else {
            var tempData = returnData();
        }
        
        if( removecomparisonminutiae )
        {
            var tempData2 = {
                mark: {
                    minutiae: {},
                    image: tempData.mark.image
                },
                print: {
                    minutiae: {},
                    image: tempData.print.image
                }
            };
            
            var updatedMinutiaeTimestamp = pianos.getParams().updatedMinutiaeTimestamp;
            updatedMinutiaeTimestamp = pgTimestamptzToDate( updatedMinutiaeTimestamp );
            
            for( var i in tempData.mark.minutiae )
            {
                if( tempData.mark.minutiae[ i ].modified <= updatedMinutiaeTimestamp )
                {
                    tempData2.mark.minutiae[ tempData.mark.minutiae[ i ].id ] = tempData.mark.minutiae[ i ];
                    
                    for( var j in tempData.print.minutiae )
                    {
                        if( tempData.print.minutiae[ j ].pairing == tempData.mark.minutiae[ i ].pairing )
                            tempData2.print.minutiae[ tempData.print.minutiae[ j ].id ] = tempData.print.minutiae[ j ];
                    }
                }
            }
            
            // Add centers
            for( var i in tempData.mark.minutiae )
            {
                if( tempData.mark.minutiae[ i ] === "center" )
                    tempData2.mark.minutiae[ tempData.mark.minutiae[ i ].id ] = tempData.mark.minutiae[ i ];
            }
            for( var i in tempData.print.minutiae )
            {
                if( tempData.print.minutiae[ i ] === "center" )
                    tempData2.print.minutiae[ tempData.print.minutiae[ i ].id ] = tempData.print.minutiae[ i ];
            }
            
            tempData = tempData2;
        }
        
        if( checkData( tempData ) == true )
        {
            var lrdata = {};
            
            lrdata.data = toJSON( tempData );
            lrdata.exid = getURLParameter( 'id' );
            lrdata.userId = pianos.getUser()[ 'id' ];
            lrdata.userName = pianos.getUser()[ 'name' ];
            lrdata.userEmail = pianos.getUser()[ 'email' ];
            lrdata.caseName = pianos.getCaseName();
            lrdata.markId = pianos.getMarkInformation()[ 'id' ];
            lrdata.printId = pianos.getPrintInformation()[ 'id' ];
            lrdata.phase = pianos.getParams().phase;
            
            if( gpselectvalue.length > 0 && gpselectvalue.length < 4 )
                lrdata.gpselect = gpselectvalue.join( ',' );
            else
                lrdata.gpselect = 'All';
            
            if( fingerselectvalue.length > 0 && fingerselectvalue.length < 10 )
                lrdata.fingerselect = fingerselectvalue.join( ',' );
            else
                lrdata.fingerselect = 'All';
            
            lrdata.gpimpact = gpimpactvalue;
            lrdata.alllrs = computealllrs;
            
            $.ajax(
            {
                dataType: 'json',
                type: 'POST',
                data: lrdata,
                url: '?action=rpc&method=lr',
                success: function( d )
                {
                    console.log( d );
                    
                    if( d.error == true )
                    {
                        toastr.error( d.message, "Xena error", { timeOut: 10000 } );
                        
                    } else if( d.ret.error == true ) {
                        toastr.error( d.ret.message, "Xena error", { timeOut: 10000 } );
                        
                    } else {
                        toastr.success( d.ret.id, "Data successfully sended to Xena", { timeOut: 10000 } );
                        
                        console.log( currentClusterState );
                        if( currentClusterState === "orange" )
                            toastr.info( "A very high load is visible on Xena. A delay may be present to retrieve the (E)SLR. Be patient", "Xena backlog", { timeOut: 20000 } );
                    }
                },
                error: function()
                {
                    toastr.error( "Network error" );    
                }
            } );
        }
        
        if( pianos.getParams().phase == "analysis" )
        {
            var tempData = returnData();
            
            for( var i in tempData.mark.minutiae )
                delete tempData.mark.minutiae[ i ].pairing;
        }
    }
}
