var Polymorphism = Class.create();
Polymorphism.prototype = {
    initialize: function(data, feature) {
        if(data) {
            Object.extend(this, data);
        }
        this.colors = ["00FF00", "0000FF", "FF8C00", "FF0000"]
        this.feature = feature;
    },

  warName: function(){
        var path=location.pathname;
        var a=path.split("/");
        return '/'+a[1];
    },

    popup: function() {
        var object_id=this.feature.object_id
        var m = new Control.Modal(false,{
            contents: function(){
                new Ajax.ULRequest(warName()+'/gene/reference/'+object_id,{
                    onLoading: function() {},
                    onComplete: function(request){
                        m.update(request.responseText);              
                    }.bind(this)
                });
                return 'loading';
            }
        });
        m.open();
    },
    
    //TODO this needs to be cleaned up badly....
    render: function(parent) {
        var myContainer = Builder.node('div');
        var reference_link = Builder.node('a', {href: '#'})
        reference_link.innerHTML = 'Display Literature References...'

        if(!parent) {
            if(this.feature!=null)
                myContainer.appendChild(Builder.node('a', {target:'_blank', href:this.warName()+'/gene/browse/' + this.feature.feature_id+'?newData=false'}, 'View Polymorphism...'))
            Builder._appendChild(myContainer, Builder.node('br', {}, " "));
        
            if(this.referenceId>0){
                Builder._appendChild(myContainer, Builder.node('a', {}, [reference_link]))
            }
      
            Event.observe(reference_link,
            "click",
            this.popup.bindAsEventListener(this))
            //container.appendChild(Builder.node('a', {href:'#',onclick:reference.popup()}, 'Display References'))
          
        }


        if(this.polyconfs && this.polyconfs.length > 0) {
            var heading = Builder.node('div', {style: 'padding-top: 20px;'}, [Builder.node('h3','Polymorphism Confirmations:')]);
            var ul = Builder.node('ul', {className:'polyconfs'})
            for(var i = 0; i<this.polyconfs.length; i++) {
                var polyconf = this.polyconfs[i]
                var li = Builder.node('li', {id: 'pc_' + polyconf.confirmation_id + "_" + polyconf.accession, className:'polyconf'}, polyconf.sequence + '(' + polyconf.orientation + ') ' + polyconf.accession)
                Builder._appendChild(ul, li);
            }
            Builder._appendChild(myContainer, heading);
            Builder._appendChild(myContainer, ul);
        }

        if(this.frequencies && this.frequencies.length > 0) {
            var heading = Builder.node('div', {style: 'padding-top: 20px;'}, [Builder.node('h3','Discovery Allele Frequencies:')]);

            var h_table = Builder.node('table', {className:'allele_header'});
            var h_tbody = Builder.node('tbody');
            h_table.appendChild(h_tbody);
            var h_row = Builder.node('tr');

            $H({'A': [1,0,0,0], 'C': [0,1,0,0], 'G': [0,0,1,0], 'T': [0,0,0,1]}).each(function (pair) {
                Builder._appendChild(h_row, Builder.node('td',{style: 'text-align:right;'} ,pair[0]));
                var canvas = Builder.node('div', {style:'position:relative;width:50px;height:13px;'});
                Builder._appendChild(h_row, Builder.node('td', {}, [canvas]));
                this.drawBar(canvas, pair[1]);
            }.bind(this));
            Builder._appendChild(h_tbody, h_row);

            var table = Builder.node('table', {className:'alleles'});
            var tbody = Builder.node('tbody');
            Builder._appendChild(table, tbody);
            var row = Builder.node('tr');

            row = Builder.node('tr', [Builder.node('td',{style: 'text-align:right;'}, 'Total')]);
            Builder._appendChild(tbody, row);
            var counts = [this.frequencies[0].a, this.frequencies[0].c, this.frequencies[0].g, this.frequencies[0].t]
            var canvas = Builder.node('div', {style:'position:relative;width:50px;height:13px;'})
            canvas.onmouseover=this.showTooltip.bind(counts);

            //row.appendChild(Builder.node('td', {colSpan:8},Builder.node("a",{href: this.warName()+'/genotype/genotypes/'+this.object_id, target:"_blank"}, [canvas])));

            Builder._appendChild(row, Builder.node('td', {colSpan:8},Builder.node("a",{href: this.warName()+'/genotype/genotypes/'+this.object_id+'?session_id='+this.session_id, target:"_blank"}, [canvas])));

            this.drawBar(canvas, counts);

            row = Builder.node('tr');
            for(var i = 1; i<this.frequencies.length; i++) {
                var polymorphism = this.frequencies[i];
                if(i%4 == 0) {
                    Builder._appendChild(tbody, row);
                    row = Builder.node('tr');
                }

                Builder._appendChild(row, Builder.node('td', {style: 'text-align:right;'},polymorphism.ethnicity));
                counts = [polymorphism.a, polymorphism.c, polymorphism.g, polymorphism.t]
                canvas = Builder.node('div', {style:'position:relative;width:50px;height:13px;'})
                canvas.onmouseover=this.showTooltip.bind(counts);
                var ethString=polymorphism.ethnicity.replace(/ /g,"+");
                ethString=ethString.replace(/&/g,"%26")

                //row.appendChild(Builder.node('td', {},Builder.node("a",{href:this.warName()+'/genotype/genotypes/'+this.object_id + "?ethnicity="+ethString, target:"_blank"}, [canvas])));

                Builder._appendChild(row, Builder.node('td', {},Builder.node("a",{href:this.warName()+'/genotype/genotypes/'+this.object_id + "?ethnicity="+ethString+'&session_id='+this.session_id, target:"_blank"}, [canvas])));

                this.drawBar(canvas, counts);
            }

            if((this.frequencies.length-1) % 4 != 0) {
                if(row.childNodes.length < 8) {
                    Builder._appendChild(row, Builder.node('td', {colSpan:(8-row.childNodes.length)}, ""));
                }
                Builder._appendChild(tbody, row);
            }

            Builder._appendChild(myContainer, heading);
            Builder._appendChild(myContainer, h_table);
            Builder._appendChild(myContainer, table);
        }

        if(this.hapFrequencies && this.hapFrequencies.length > 0) {
            var heading = Builder.node('div', {style: 'padding-top: 20px;'}, [Builder.node('h3','GenBank Allele Frequencies:')]);

            var h_table = Builder.node('table', {className:'allele_header'});
            var h_tbody = Builder.node('tbody');
            Builder._appendChild(h_table, h_tbody);
            var h_row = Builder.node('tr');

            $H({'A': [1,0,0,0], 'C': [0,1,0,0], 'G': [0,0,1,0], 'T': [0,0,0,1]}).each(function (pair) {
                Builder._appendChild(h_row, Builder.node('td',{style: 'text-align:right;'} ,pair[0]));
                var canvas = Builder.node('div', {style:'position:relative;width:50px;height:13px;'});
                Builder._appendChild(h_row, Builder.node('td', {}, [canvas]));
                this.drawBar(canvas, pair[1]);
            }.bind(this));
            
            Builder._appendChild(h_tbody, h_row);

            var table = Builder.node('table', {className:'alleles'});
            var tbody = Builder.node('tbody');
            Builder._appendChild(table, tbody);
            var row = Builder.node('tr');

            row = Builder.node('tr', [Builder.node('td',{style: 'text-align:right;'}, 'Total')]);
            Builder._appendChild(tbody, row);
            var counts = [this.hapFrequencies[0].a, this.hapFrequencies[0].c, this.hapFrequencies[0].g, this.hapFrequencies[0].t]
            var canvas = Builder.node('div', {style:'position:relative;width:50px;height:13px;'})
            canvas.onmouseover=this.showTooltip.bind(counts);
            Builder._appendChild(row, Builder.node('td', {colSpan:8}, [canvas]));
            this.drawBar(canvas, counts);
            
            row = Builder.node('tr');
            for(var i = 1; i<this.hapFrequencies.length; i++) {
                var polymorphism = this.hapFrequencies[i];
                if(i%4 == 0) {
                    Builder._appendChild(tbody, row);
                    row = Builder.node('tr');
                }

                Builder._appendChild(row, Builder.node('td', {style: 'text-align:right;'},polymorphism.ethnicity));
                counts = [polymorphism.a, polymorphism.c, polymorphism.g, polymorphism.t]
                canvas = Builder.node('div', {style:'position:relative;width:50px;height:13px;'})
                canvas.onmouseover=this.showTooltip.bind(counts);
                Builder._appendChild(row, Builder.node('td', {}, [canvas]));
                this.drawBar(canvas, counts);
            }

            if((this.hapFrequencies.length-1) % 4 != 0) {
                if(row.childNodes.length < 8) {
                    Builder._appendChild(row, Builder.node('td', {colSpan:(8-row.childNodes.length)}, ""));
                }
                Builder._appendChild(tbody, row);
            }

            Builder._appendChild(myContainer, heading);
            Builder._appendChild(myContainer, h_table);
            Builder._appendChild(myContainer, table);
        }
        
        var newRow
        
            if(!parent || parent.tagName == 'TBODY')
            {
                var column = Builder.node('td', {colSpan:this.feature.row().childNodes.length});
                newRow = Builder.node('tr', [column]);
                column.style.border = '1px solid #f4ce67';
                column.style.padding = '5px';
                Builder._appendChild(column, myContainer);
            }
            if(!parent) {
                newRow.style.display = 'none';
                if(this.feature.row().nextSibling) {
                    this.feature.row().parentNode.insertBefore(newRow, this.feature.row().nextSibling);
                }
                else {
                    Builder._appendChild(this.feature.row().parentNode, newRow);
                }
                new Effect.Appear(newRow);
            } else if(parent.tagName == 'TBODY') {
                Builder._appendChild(parent, newRow);      
            }
            else {
                Builder._appendChild(parent, myContainer);
            }

            //
            // Once the polyconfs are added to the parent, they are actually added to the DOM and we can set them draggable
            //
    
            $$('.polyconfs .polyconf').each(function(f){
                new Draggable(f.id, {revert:true, tag:'li', ghosting:true});
            })
       
      
    },

    drawBar: function(parent, intArray) {
        var jg = new jsGraphics(parent);
        var sum = intArray.inject(0, function(acc, n) { return acc + n; })
        var len=0;
        var offset = 0;
        for(var i=0; i<intArray.length; i++){
            len = Math.floor(50*intArray[i]/sum);
            if(intArray[i]!=0)
                len+=2;
            jg.setColor("#" + this.colors[i%4])
            jg.fillRect(offset, 6, len, 4);
            offset+=len;
        }
        jg.paint();
    },

    /*
    "this" is bound as the count (ugh)
     */
    showTooltip: function() {
        var colors = ["000000", "000000", "000000", "000000"]
        var background= ["00ff00","7b68ee","ff8c00","ff4500"]
        var tooltip = new Array()
        for(var i=0; i<4; i++) {
            tooltip.push("<span style='color: #" + colors[i] + ";background-color: #"+background[i]+"'>"+this[i]+"</span>")
        }
        Tip(tooltip.join(':'))
    }
}
