suppressPackageStartupMessages({
  require(IMGTStatClonotype)
  require(shiny)
  require(reshape2)
  require(data.table)
  require(grid)
  require(ggplot2)
  library(plotly)
  require(gridExtra)
  require(shinyjs)
  require(DT)
  require(d3heatmap)
})
rlist=c("Nb_IMGT_clonotype_AA.set1","Proportion.set1","Normalized_proportion.set1",
        "Nb_IMGT_clonotype_AA.set2","Proportion.set2", "Normalized_proportion.set2", "Difference_proportion" , "z" ,
        "Lower_bound_IC_diff_prop","Upper_bound_IC_diff_prop", "rawp" ,"Bonferroni" ,
        "Holm" , "Hochberg" ,"SidakSS" , "SidakSD" ,"BH", "BY" ,"Test_interpretation" )

colorlist=c("Black"="#000000","DimGris"="#696969","Gray"="#808080","DarkGrey"="#A9A9A9","Graytout"="#BBACAC",
            "Silver"="#C0C0C0","LightGrey"="#D3D3D3","WhiteSmoke"="#F5F5F5","Morron"="#800000","FireBrick"="#B22222",
            "Brown"="#B15928","RosyBrown"="#BC8F8F","DarkRed"="#E41A1C","OrangeRed"="#FF4500","Orange"="#FF7F00",
            "Orange1"="#FDBF6F","Gold"="#FFD700","Yellow"="#FFFF00","LightYellow"="#FFFF99","LightPink"="#FFB6C1",
            "Rosy"="#FB9A99","HotPink"="#FF69B4","DeepPink"="#FF1493","Magenta"="#FF00FF","Pink2"="#C805FF",
            "DarkOrchid"="#9932CC", "Purple2"="#984EA3","Purple1"="#CAB2D6", "Blue1"="#A6CEE3","CadeBlue"="#559EA0",
            "Blue2"="#377eb8","RoyalBlue"="#4169E1","Blue"="#0000FF","DeepSkyBlue"="#00BFFF","Cyan"="#00FFFF",
            "YellowGreen"="#ADFF2F","LightGreen"="#90EE90","Lime"="#00FF00", "LimeGreen"="#32CD32","darkGreen"="#006400")


# Define UI for application that draws a histogram
shinyUI(fluidPage(
  useShinyjs(),
  headerPanel(list(
    tags$head(tags$style(".mybutton{background-color:#0082E0;color: #ffffff;}}")),
    tags$head(tags$style(".mybuttonExit{background-color:#0082E0;color: #ffffff;}}")),
    tags$style(HTML(".sidebar {height: 100%}
                    .dataTables_wrapper{ width:100%;overflow-x: scroll;overflow-y: hidden}
                    " )),
    tags$head(tags$title("IMGT/StatClonotype"),tags$link(rel="stylesheet", type="text/css", href="style.css"), tags$link(rel="icon",type="image/icon", href="favicon.png")),h2( a(img(src="imgt.png", height = 140, width = 175,style="border:0;float:right"),href="http://www.imgt.org/",target="_blank"),
                                                                                                                                                                                br(),
                                                                                                                                                                                span("WELCOME!",style="color:#272F87;font-family:times;font-weight:bold"),
                                                                                                                                                                                br(),
                                                                                                                                                                                span("to",style="color:#272F87;font-family:times;font-weight:bold"),
                                                                                                                                                                                a("IMGT/StatClonotype", style="font-family:times;font-weight:bold;text-decoration:underline",class="specialeffects",href = "http://www.imgt.org/StatClonotype/",target="_blank")
    ),
    h6(span("THE INTERNATIONAL IMMUNOGENETICS INFORMATION SYSTEM® ",style="color:#000000;font-family:Arial;font-weight:bold")),
    br())
    ),

  fluidRow(
    column(3,style = "background-color:#f4f9ff",

           conditionalPanel(condition="input.conditionedPanels==1 | input.conditionedPanels==2 | input.conditionedPanels==3| input.conditionedPanels==4| input.conditionedPanels==5 | input.conditionedPanels==6 | input.conditionedPanels==7| input.conditionedPanels==8",
                            br(),wellPanel(style = "background-color:#f4f9ff;",fileInput("files1", "Choose IMGT/HighV-QUEST set 1",accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
                                      fileInput("files2", "Choose IMGT/HighV-QUEST set 2",accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
                                      sliderInput("cdrlength",
                                                  "Select CDR3-IMGT length range",
                                                  min = 1,
                                                  max = 100,
                                                  value = c(4,45))
                            )                ),
           conditionalPanel(condition="input.conditionedPanels==3| input.conditionedPanels==4| input.conditionedPanels==5 | input.conditionedPanels==6 | input.conditionedPanels==7| input.conditionedPanels==8",
                            wellPanel(style = "background-color:#f4f9ff;",
                              radioButtons("TypeClono", label = strong("View IMGT clonotype (AA) "),choices= c("diversity", "expression"),inline = TRUE, selected = "diversity"))  ) ,

           conditionalPanel(condition="input.conditionedPanels==3| input.conditionedPanels==4| input.conditionedPanels==5",
                            wellPanel(style = "background-color:#f4f9ff;",radioButtons('Type_gene',label = strong('Show'), choices = c("Several genes","Single genes" ), selected = "Several genes",inline = TRUE),
                            radioButtons('Type_AnalysisGene',label = strong('Hide null or smallest gene occurrences'), choices = c("Yes" ,"No"), selected = "No",inline = TRUE)),
                            wellPanel(style = "background-color:#f4f9ff;",radioButtons('Type_allele',label = strong('Show'), choices = c("Several alleles","Single alleles" ), selected = "Single alleles",inline = TRUE),
                            radioButtons('Type_AnalysisAllele',label = strong('Hide null or smallest allele occurrences'), choices = c("Yes" ,"No"), selected = "No",inline = TRUE))),


           conditionalPanel(condition="input.conditionedPanels==3",
                            wellPanel(style = "background-color:#f4f9ff;",checkboxGroupInput('show_vars',strong('Columns to show'), choices = rlist ,
                                                                                             selected = rlist))),

           conditionalPanel(condition="input.conditionedPanels==4",
                            wellPanel(style = "background-color:#f4f9ff;",textInput("titleGphMTP", "Add graph title for genes (optional)", "\"Graph title\""), textInput("titleGphMTPallele", "Add graph title for alleles (optional) ", "\"Graph title\""))),


           conditionalPanel(condition="input.conditionedPanels==5",
                            wellPanel(style = "background-color:#f4f9ff;",radioButtons('Gene_Type',label = strong('Select gene type'), choices = c("V genes", "D genes" ,"J genes"), selected = "V genes",inline = TRUE)
                            ),
                            wellPanel(style = "background-color:#f4f9ff;",textInput("locus", "Add locus type to graph axis title: IGH, IGK, IGL, TRA, TRB, TRG or TRD (optional)", ""),
                                      textInput("titleGph", "Add graph title for genes (optional)", "\"Graph title\""),
                                      strong("Change bar colors for"),
                                      fluidRow(
                                        column(6,shinyjs::colourInput("barcolor1", "Normalized_proportion.set1", value = "#E41A1C", showColour ="background", palette = "limited",colorlist )),
                                        column(6,shinyjs::colourInput("barcolor2", "Normalized_proportion.set2", value = "#377eb8", showColour ="background", palette = "limited",colorlist ))),
                                      fluidRow(
                                        column(6, sliderInput("height",
                                                           "Select graph height for genes",
                                                           min = 5,
                                                           max = 30,
                                                           value = 25)),
                                        column(6, sliderInput("width",
                                                           "Select graph width for genes",
                                                           min = 5,
                                                           max = 30,
                                                           value = 20))
                                      )),
                            wellPanel(style = "background-color:#f4f9ff;",
                              fluidRow(
                                textInput("titleSynGphAllele", "Add graph title for alleles (optional)", "\"Graph title\""),
                              column(6, sliderInput("heightSynAllele",
                                                    "Select graph height for alleles",
                                                    min = 5,
                                                    max = 80,
                                                    value = 25,
                                                    step= 2)),
                              column(6, sliderInput("widthSynAllele",
                                                    "Select graph width for alleles",
                                                    min = 5,
                                                    max = 30,
                                                    value = 20))
                            ))) ,

           conditionalPanel(condition="input.conditionedPanels==6|input.conditionedPanels==7",
                             wellPanel(style = "background-color:#f4f9ff;",radioButtons("Type_CDR",label = strong('Choose CDR-IMGT'), choices = c("CDR1-IMGT","CDR2-IMGT" ,"CDR3-IMGT"), selected = "CDR3-IMGT",inline = TRUE),br(),uiOutput("selectCDRlength1"),uiOutput("selectCDRlength2") )),

           conditionalPanel(condition="input.conditionedPanels==6",
           checkboxInput("NormVal", "Normalized values",value = FALSE)),
           conditionalPanel(condition="input.conditionedPanels==7",
                            wellPanel(style = "background-color:#f4f9ff;",selectInput("IMGTAAclasses", "IMGT classes of the 20 common amino acids",
                                      choices = c("20 amino acids","Physicochemical" ,"Hydropathy","Volume","Chemical","Charge", "Hydrogen donor or acceptor atoms", "Polarity" ), selected = "20 amino acids"),
                                      radioButtons("AbsPercent",label = strong('Show results by'), choices = c("Absolute values" ,"Percentages"), selected = "Absolute values",inline = TRUE)),
                            fluidRow(
                              column(6, sliderInput("heightAApos",
                                                    "Select graphs height in cm",
                                                    min = 5,
                                                    max = 21,
                                                    value = 21)),
                              column(6, sliderInput("widthAApos",
                                                    "Select graphs width in cm",
                                                    min = 0,
                                                    max = 30,
                                                    value = 20))
                            )),


           conditionalPanel(condition="input.conditionedPanels==8",
                            wellPanel(style = "background-color:#f4f9ff;",radioButtons('Type_association',label = strong('Dendrogramm for'), choices = c("V- J gene associations","V- D gene associations" ,"D- J gene associations" ), selected = "V- J gene associations",inline = FALSE),
                            checkboxInput("clustering", "Results with clustering",value = TRUE)),
                            checkboxInput("NormValues", "Normalized values",value = FALSE),
                            selectInput("palette", "Color palettes", c("YlGnBu","YlOrRd", "Greens", "Blues","Reds"))
           ),
           div(actionButton("Quit", tags$span(img(src="exit.png"),HTML("Exit IMGT/StatClonotype") ),class="mybuttonExit")),br()

           ),

  column(9,
      #tags$style(type="text/css",
      #    ".shiny-output-error { visibility: hidden; }",
      #    ".shiny-output-error:before { visibility: hidden; }"),
      tabsetPanel(
        tabPanel(strong("IMGT/HighV-QUEST set 1"),
           wellPanel(h4(strong(helpText("IMGT clonotypes (AA)",style="color:#272F87"))),
                   dataTableOutput("filetable1Disp"),strong(uiOutput("Info1")),strong(uiOutput("NbClonoSet1")),strong(uiOutput("NbSeqSet1"))),
           wellPanel(h4(strong(helpText("Unselected IMGT clonotypes (AA) corresponding to CDR3-IMGT length outliers",style="color:#272F87"))),
                   dataTableOutput("filetable1RemSeqDisp"),strong(uiOutput("Info11")),strong(uiOutput("NbRemClonoSet1")),strong(uiOutput("NbRemSeqSet1"))),value = 1),

        tabPanel(strong("IMGT/HighV-QUEST set 2"),
           wellPanel(h4(strong(helpText("IMGT clonotypes (AA)",style="color:#272F87"))),
              dataTableOutput("filetable2Disp"),strong(uiOutput("Info2")),strong(uiOutput("NbClonoSet2")),strong(uiOutput("NbSeqSet2"))),
           wellPanel(h4(strong(helpText("Unselected IMGT clonotypes (AA) corresponding to CDR3-IMGT length outliers",style="color:#272F87"))),
                     dataTableOutput("filetable2RemSeqDisp"),strong(uiOutput("Info22")),strong(uiOutput("NbRemClonoSet2")),strong(uiOutput("NbRemSeqSet2"))), value = 2),

        tabPanel(strong("Statistical test results"),
                 h4(strong(helpText("Statistical test results for genes",style="color:#272F87"))),
                 dataTableOutput("testresults"),br(),
                 downloadButton('downloadData', 'Download', class= "mybutton"),br(),hr(),
                 h5(strong(helpText("List of genes with null or small occurrences",style="color:#272F87"))),
                 h6( helpText(img(src="circleorange.png"), "The list of genes with null or small occurrences is shown below. For this list the Fisher's exact test is used. Associated", tags$em("p"),"-values are displayed in \"rawp\" column of the \"Statistcal test results for genes\" table above", a("(see explanation)",href="http://www.imgt.org/StatClonotype/IMGTStatClonotypeDoc.html#STRGene",target="_blank"))),
                 actionButton("hide3", "Show/Hide Table", class= "mybutton"),
                 wellPanel(dataTableOutput("testresultsExcluded")),br(),
                 h4(strong(helpText("Statistical test results for alleles",style="color:#272F87"))),
                 h6(helpText(img(src="circleorange.png"),"Only alleles of genes having significant differences in proportions validated by all multiple testing procedures are analyzed.")),
                 dataTableOutput("testresultsallele"),br(),
                 downloadButton('downloadDataAllele', 'Download', class= "mybutton"),br(),br(),
                 h5(strong(helpText("List of alleles with null or small occurrences",style="color:#272F87"))),
                 h6( helpText(img(src="circleorange.png"), "The list of alleles with null or small occurrences is shown below. For this list the Fisher's exact test is used. Associated", tags$em("p"),"-values are displayed in \"rawp\" column of the \"Test results for alleles\" table above", a("(see explanation)",href="http://www.imgt.org/StatClonotype/IMGTStatClonotypeDoc.html#STRAllele",target="_blank"))),
                 actionButton("hide4", "Show/Hide Table", class= "mybutton"),
                 wellPanel(dataTableOutput("testresultsalleleExcluded")),
                 br(),hr(),value = 3),

        tabPanel(strong("Multiple testing procedures plots"),
                 h4(strong(helpText("Multiple testing procedures plots for genes",style="color:#272F87"))),
                 downloadButton('downloadMTPgraphPNG', 'PNG', class= "mybutton"),
                 downloadButton('downloadMTPgraphJPG', 'JPG', class= "mybutton"),
                 downloadButton('downloadMTPgraphPDF', 'PDF', class= "mybutton"),
                 h6(uiOutput("TitleGene"),style="font-size:150%;text-align:center"),
                 fluidRow(
                   column(6, plotlyOutput("LineGraphShinyDisplay",width = "100%", height = "300px") ),
                   column(6, plotlyOutput("ScatterPlotShinyDisplay",width = "100%", height = "300px"))),br(),br(),
                 dataTableOutput("MTPgphresults"),br(),
                 downloadButton('downloadDataLog', 'Download', class= "mybutton"),br(),hr(),
                 h4(strong(helpText("Multiple testing procedures plots for alleles",style="color:#272F87"))),
                 downloadButton('downloadMTPgraphAllelePNG', 'PNG', class= "mybutton"),
                 downloadButton('downloadMTPgraphAlleleJPG', 'JPG', class= "mybutton"),
                 downloadButton('downloadMTPgraphAllelePDF', 'PDF', class= "mybutton"),
                 h6(uiOutput("TitleAllele"),style="font-size:150%;text-align:center"),
                 fluidRow(
                   column(6, plotlyOutput("LineGraphShinyDisplayAllele",width = "100%", height = "300px") ),
                   column(6, plotlyOutput("ScatterPlotShinyDisplayAllele",width = "100%", height = "300px"))),br(),br(),
                 dataTableOutput("MTPgphresultsAllele"),br(),
                 downloadButton('downloadDataLogAllele', 'Download', class= "mybutton"),br(),hr(),
                 value = 4),

        tabPanel(strong("Synthesis graphs"),
                 h4(strong(helpText("Synthesis graph for genes",style="color:#272F87"))),br(),
                 downloadButton('downloadSyngraphPNG', 'PNG', class= "mybutton"),
                 downloadButton('downloadSyngraphJPG', 'JPG', class= "mybutton"),
                 downloadButton('downloadSyngraphPDF', 'PDF', class= "mybutton"),
                 plotOutput("SynthesisGph",width = "100%", height = "1075px"),strong(uiOutput("InfoSynGph1")),strong(uiOutput("NbClonoSet11SG")),br(),strong(uiOutput("InfoSynGph2")),strong(uiOutput("NbClonoSet22SG")),strong(uiOutput("NbClonoSet11ResDgene")),strong(uiOutput("NbClonoSet22ResDgene")),
                 wellPanel(h5(strong(helpText("Genes are ordered by their positions in the locus [1-3]. Not ordered genes are at the bottom of the gene list in the graph and listed in the table below",style="color:#272F87"))),
                          dataTableOutput("NonIdgeneOrders")),
                          h6(helpText("[1] Giudicelli V, Chaume D, Lefranc M-P. IMGT/GENE-DB: a comprehensive database for human and mouse immunoglobulin and T cell receptor genes. Nucleic Acids Res. 2005 Jan 1;33(Database issue):D256-61.")),
                          h6(helpText("[2] Lefranc M-P. and Lefranc G. The T cell receptor FactsBook. Academic Press, London, UK (398 pages), 2001.")),
                          h6(helpText("[3] Lefranc M-P. and Lefranc G. The Immunoglobulin FactsBook. Academic Press, London, UK (458 pages), 2001.")),hr(),br(),
                 h4(strong(helpText("Synthesis graph for alleles",style="color:#272F87"))),br(),
                 downloadButton('downloadSyngraphAllelePNG', 'PNG', class= "mybutton"),
                 downloadButton('downloadSyngraphAlleleJPG', 'JPG', class= "mybutton"),
                 downloadButton('downloadSyngraphAllelePDF', 'PDF', class= "mybutton"),
                 plotOutput("SynthesisGphAllele"),
                 br(),br(),value = 5),

        tabPanel(strong("CDR-IMGT lengths"),br(),
                 h4(strong(uiOutput("BargraphCDRlength"),style="color:#272F87")),
                fluidRow(
                    column(6, plotlyOutput("distPlotSet1CDR",width = "90%", height = "600px") ),
                    column(6, plotlyOutput("distPlotSet2CDR",width = "90%", height = "600px"))),
                h4(strong(helpText(uiOutput("List1perCDRlength"),style="color:#272F87"))),
                wellPanel(dataTableOutput('databaseperCDRlength1')),
                downloadButton('downloaddatabaseperCDRlength1', 'Download', class= "mybutton"),hr(),
                h4(strong(helpText(uiOutput("List2perCDRlength"),style="color:#272F87"))),
                wellPanel(dataTableOutput("databaseperCDRlength2")),
                downloadButton('downloaddatabasepergenelength2', 'Download', class= "mybutton"),br(),br(), value = 6),

        tabPanel(strong("CDR-IMGT AA properties"),
                h4(strong(uiOutput("IMGTclassesset1"),style="color:#272F87")),
                wellPanel(
                dataTableOutput("AAposset1"),br(),actionButton("hide1", "Show/Hide Table", class= "mybutton"),
                downloadButton("downloadAAposset1", 'Download', class= "mybutton")),
                h4(strong(uiOutput("IMGTclassesset1graph"),style="color:#272F87")),
                plotlyOutput("distPlotAAdivexp1",width="100%", height = "100%"),hr(),
                h4(strong(uiOutput("IMGTclassesset2"),style="color:#272F87")),
                wellPanel(
                dataTableOutput("AAposset2"),br(),actionButton("hide2", "Show/Hide Table", class= "mybutton"),
                downloadButton("downloadAAposset2", "Download", class= "mybutton")),
                h4(strong(uiOutput("IMGTclassesset2graph"),style="color:#272F87")),
                fluidRow(plotlyOutput("distPlotAAdivexp2",width="100%", height = "100%")),hr(),
                h4(strong(helpText("Variability indexes",style="color:#272F87"))),
                radioButtons("TypeIndex", label = strong(" "),choices= c("Shannon entropy","Wu-Kabat variability", "Simpson index"),inline = TRUE, selected = "Shannon entropy"),
                h5(strong(helpText("Variability plot (set 1)",style="color:#272F87"))),br(),
                plotlyOutput("Indexplot1",width = "100%", height = "100%"),br(),
                h5(strong(helpText("Variability plot (set 2)",style="color:#272F87"))),br(),
                plotlyOutput("Indexplot2",width = "100%", height = "100%"),br(),
                h5(strong(helpText("Index values (set 1)",style="color:#272F87"))),
                wellPanel(dataTableOutput("IndexTable1")),
                h5(strong(helpText("Index values (set 2)",style="color:#272F87"))),
                wellPanel(dataTableOutput("IndexTable2")),br(), value = 7),

        tabPanel(strong("V-D-J gene associations"),
                 fluidRow(
                   column(6,
                          h4(strong(uiOutput("GeneAssociationset1"),style="color:#272F87")),
                          downloadButton('heatmap1PDF', 'PDF', class= "mybutton"),
                          downloadButton('downloadheatmap1PNG', 'PNG', class= "mybutton"),
                          downloadButton('downloadheatmap1JPG', 'JPG', class= "mybutton"),br(),br(),br(),
                          d3heatmapOutput("HeatmapSet1",width ='100%', height = "900px")
                          ),
                   column(6,
                          h4(strong(uiOutput("GeneAssociationset2"),style="color:#272F87")),
                          downloadButton('heatmap2PDF', 'PDF', class= "mybutton"),
                          downloadButton('downloadheatmap2PNG', 'PNG', class= "mybutton"),
                          downloadButton('downloadheatmap2JPG', 'JPG', class= "mybutton"),br(),br(),br(),
                          d3heatmapOutput("HeatmapSet2",width ='100%', height = "900px"))),

                 br(),
                 h4(strong(uiOutput("heatmapset1table"),style="color:#272F87")),
                 wellPanel(dataTableOutput("DendroSet1table")),
                 downloadButton("downloadDendroSet1", "Download", class= "mybutton"),
                 br(),
                 h4(strong(uiOutput("heatmapset2table"),style="color:#272F87")),
                 wellPanel(dataTableOutput("DendroSet2table")),
                 downloadButton("downloadDendroSet2", "Download", class= "mybutton"),value = 8),id="conditionedPanels")

    )
  )
  ))
