isc.defineClass("OPINIATOR_VulnerabilityChart", OPINIATOR_FusionChart);
OPINIATOR_VulnerabilityChart.addProperties({

    // Public properties
    /**
     * Use Previous Months values instead of current month values?
     */
    usePrevMonth: false,

    // Private properties
    _pcats: null,

    // Superclass Properties
    chart:"FusionCharts/Bubble.swf",
    backgroundColor:"#272829",
    styleName:"performanceContentFrame",
    showShadow:true,
    shadowOffset:9,
    shadowSoftness:10,

    // Performance Labels X Axis
    categories: 
        {
        attributes: 
            { 
            verticalLineColor: "000000",
            verticalLineThickness: 1,
            verticalLineAlpha: 100
            },
        labels: 
            [
            { x:20, label:"20%" },
            { x:40, label:"40%" },
            { x:50, label:"", showVerticalLine:1 },
            { x:60, label:"60%" },
            { x:80, label:"80%" }
            ]
        },

     vertTrendlines: [{
         // 0 to 50%
         startValue: 0,
         endValue: 50,
         color: "C61010",
         showOnTop: false,
         isTrendZone: true,
         alpha: 60
         },
         {
         // 50% to 100%
         startValue: 50,
         endValue: 100,
         color: "00FF40",
         showOnTop: false,
         isTrendZone: true,
         alpha: 30
         }],

     horizTrendlines: [{
         startValue: 0,
         endValue: 50,
         displayValue: " ",
         color: "ffffff",
         showOnTop: false,
         isTrendZone: true,
         alpha: 30
         }],

     attributes: {
        caption:" ",
        numberPrefix:"",

        yAxisName:"Perceived Importance (%)",
        yAxisMinValue:0,
        yAxisMaxValue:100,

        xAxisName:"Performance",
        xAxisMinValue:0,
        xAxisMaxValue:100,

        showAlternateHGridColor:true,
        alternateHGridAlpha:100,
        alternateHGridAlpha:"ffffff",

        bubbleScale:0.5,
        showhovercap:true,
        showLegend:false,
        showNames:true,
        showValues:false,
        showLimits:true,
        showLabels:true,
        rotateLabels:false,
        animation:true,
        use3DLighting:true,
        numDivLines:1,
        adjustDiv:false,
        //divLineColor:"ff5904",
        divLineColor:"000000",
        divLineThickness:1,
        divLineAlpha:100,
        showYAxisValues:false,
        showDivLineValues:true,
        canvasBgColor:"272829",
        canvasBorderColor:"ffffff",
        canvasBorderThickness:0,
        chartTopMargin:40,
        hoverCapBgColor:"2E2F30",
        hoverCapBorderColor:"000000",
        baseFont:"Trebuchet MS, Helvetica, sans-serif",
        baseFontSize:"14",
        baseFontColor:"ffffff",
        outCnvBaseFont:"Trebuchet MS, Helvetica, sans-serif",
        outCnvBaseFontSize:"14",
        outCnvBaseFontColor:"ffffff",
        canvasBgColor:"6F6F6F",
        bgColor:"272829",
        bgAlpha:100,
        exportEnabled:true,
		exportAtClient:false,
		exportAction:"download",
		exportHandler: location.href + "/FCExporter.jsp",
		exportFileName:'MyFileName'
        },

    initWidget: function () 
        {
        this.Super("initWidget", arguments);
        this.attributes = isc.clone(this.attributes);
        this.attributes.caption = this.usePrevMonth ? "Previous Month" : "Current Month";
        },

    destroy: function()
        {
        this._pcats = null;
        this.Super("destroy", arguments);
        },

    setPerfCats: function ( newpcats )
        {
        this._pcats = newpcats;
        // Get the max and min values from the importance tallies in case they are 
        // different.
        //this.attributes.yAxisMinValue = this._getTallyMin(1)/10;
        //this.attributes.yAxisMaxValue = this._getTallyMax(1)/10;
        //this.refreshChart();
        },

    getSeries: function ()
        {
        //  Create the data set.  Skip the first Category because its the Net Promoter
        var dataset = [];
        var len = this._pcats.getLength();
        for ( var i = 0; i < len; i++ )
            {
            var pcat = this._pcats[i];
            var perf = pcat.tallies[0];
            var imp = pcat.tallies[1];
            var perf_value = this.usePrevMonth ? new Number(perf.prev.value) : new Number(perf.value);
            var imp_value = this.usePrevMonth ? new Number(imp.prev.value) : new Number(imp.value);

            // Skip if there are no values for this category
            if ( perf_value < 0 || imp_value < 0 )
                { continue; }

            var perf_min = new Number(perf.min);
            var perf_max = new Number(perf.max);

            var x = ((perf_value - perf_min)/(perf_max - perf_min))*100;
            var y = imp_value*20;

            dataset.add({
                x:x, y:y, z:20, 
                name:pcat.name, 
                color:pcat._vcolor, 
                alpha: pcat._vvisible ? 100 : 30
                });
            }

        return [{ attributes: { showValues:false }, dataset: dataset }];
        },

    _getTallyMin: function ( tallyno )
        {
        var len = this._pcats.getLength();
        var min = null;
        for ( var i = 0; i < len; i++ )
            {
            var pmin = new Number(this._pcats[i].tallies[tallyno].min);
            if ( min === null || pmin < min )                    
                { min = pmin; }
            }
        return isc.isA.Number(min) ? min : 0;
        },

    _getTallyMax: function ( tallyno )
        {
        var len = this._pcats.getLength();
        var max = null;
        for ( var i = 0; i < len; i++ )
            {
            var pmax = new Number(this._pcats[i].tallies[tallyno].max);
            if ( max === null || pmax > max )                    
                { max = pmax; }
            }

        return isc.isA.Number(max) ? max : 0;
        }

    });

isc.defineClass("OPINIATOR_Legend", isc.DynamicForm);
OPINIATOR_Legend.addProperties({
    // Public Properties
    legendChange: null,

    // Private Properties 
    _pcats: null,

    // Superclass Properties
    items:[],
    numCols:2,
    showShadow:true,
    shadowOffset:9,
    shadowSoftness:10,
    styleName: "legendFrame",
    align:"left",
    colWidths:[16, "*"],

    initWidget: function () 
        { this.Super("initWidget", arguments); },

    destroy: function()
        {
        delete this._pcats;
        this.Super("destroy", arguments);
        },

    setPerfCats: function ( newpcats )
        {
        // If nothing changed since the last analytic set don't do anything
        if ( !OPINIATOR.listDiffer(this._pcats, newpcats, "id") ) 
            {
            //  Set so the old data set get's gc'd
            this._pcats = newpcats;
            return;
            }

        this._pcats = newpcats;

        var legendItems = [];
        var len = this._pcats.getLength();

        // Set the number columns based upon how many we'll show
        if ( (len-1) < 5 )       { this.numCols = 2; }
        else if ( (len-1) < 10 ) { this.numCols = 4; }
        else if ( (len-1) < 15 ) { this.numCols = 6; }
        else                     { this.numCols = 8; }

        for ( var i = 0; i < len; i++ )
            {
            var pcat = this._pcats[i];
            var bgcolor;

            if ( pcat._vvisible ) 
                { bgcolor = "#"+pcat._vcolor; }
            else
                { bgcolor = "#000000"; }

            legendItems.add({
                startRow:true,
                title:"",
                showTitle:false,
                cellStyle:"legendCell",
                editorType:"CanvasItem",
                canvasProperties:{backgroundColor:bgcolor, height:16, width:16 }
                });

            legendItems.add({
                pcatid:pcat.id,
                title:pcat.name,
                defaultValue:pcat._vvisible,
                type:"boolean",
                showTitle:false,
                startRow:false,
                valueMap:[false, true],
                align:"left",
                titleOrientation:"right", 
                titleWidth:0, 
                textAlign:"left",
                cellStyle:"legendCell",
                shouldSaveValue:false
                });
            }

        this.setItems(legendItems);
        },

    itemChange: function (item, newValue, oldValue)
        {
        // Change the how the category is displayed
        var pcat = this._pcats.find("id", item.pcatid);
        pcat._vvisible = newValue;

        if ( isc.isA.Function(this.legendChange) )
            { this.legendChange(); }
        }
    });


/**
 * @class VulnerabilityPane  A Tab Pane Class that describes the 
 *        data as a 
 */
isc.defineClass("OPINIATOR_VulnerabilityPane", isc.VLayout);
OPINIATOR_VulnerabilityPane.addClassProperties({
    /**
     *  TODO: Colors should be changed to using a random color
     *  generator of which a function is is in this class.  However,
     *  we will have to change how we do the checkbox image in order
     *  to do that.
     */
    colors: [
        "FF8040", "0000FF", "00FFFF", "FF80FF", "300090", 
        "FFE71D", "FAD97F", "D67B7B", "624B85", "FFF32D",
        "BFDBFF", "D4AAFF", "FFAAFF", "000000", "0000000",
        "000000", "000000", "000000", "000000", "0000000",
        "000000", "000000", "000000", "000000", "0000000"
        ]
    });
OPINIATOR_VulnerabilityPane.addProperties({

    _pcats: null,
    _legend: null,
    _cchart: null,
    _pchart: null,

    // Super class properties
    styleName: "performanceContent",

    initWidget: function () 
        {
        this._legend = OPINIATOR_Legend.create({
                target:this,
                height:"10%",
                width:"75",
                legendChange : function ()
                    { this.target.refreshCharts(); }
                });

        this._cchart  = OPINIATOR_VulnerabilityChart.create({
                usePrevMonth:false,
                height:"100%",
                width:"100%"
                });

        this._pchart  = OPINIATOR_VulnerabilityChart.create({
                usePrevMonth:true,
                height:"100%",
                width:"100%"
                });

        // Space out the charts
        var chart_view = isc.HLayout.create({
            members:[OPINIATOR.hSpacer("6%"), this._cchart, OPINIATOR.hSpacer("6%"), this._pchart, OPINIATOR.hSpacer("6%")],
            height:"70%",
            width:"100%"
            });

        // Center the legend
        var legend_view = isc.HLayout.create({ 
            members:[OPINIATOR.hSpacer("*"), this._legend, OPINIATOR.hSpacer("*")],
            height:"*",
            width:"100%"
            });

        this.members = [ OPINIATOR.vSpacer(10), chart_view, legend_view ];
        this.Super("initWidget", arguments);
        },

    destroy: function()
        {
        this._pcats = null;
        this._cchart = null;
        this._pchart = null;
        this._legend.target = null;
        this._legend = null;
        this.Super("destroy", arguments);
        },

    setAnalytics: function ( analytics )
        {
        if ( !isc.isAn.Object(analytics) )
            {
            this._pcats = null;
            this._legend.setPerfCats(null);
            return;
            }

        var acats = analytics.list;
        this._pcats = acats.findAll("type", "PERFORMANCE");

        if ( !isc.isAn.Array(this._pcats) )
            { this._pcats = OPINIATOR.toArray(this._pcats); }

        // Set colors and default visibility
        var len =  this._pcats.getLength();
        for ( var i = 0; i < len; i++ )
            {
            var pcat = this._pcats[i];
            pcat._vvisible = true;
            pcat._vcolor = OPINIATOR_VulnerabilityPane.colors[i];
            }

        this._legend.setPerfCats(this._pcats);
        this._cchart.setPerfCats(this._pcats);
        this._pchart.setPerfCats(this._pcats);
        },

    refreshCharts: function () 
        {
        this._cchart.refreshChart();
        this._pchart.refreshChart();
        }
    });

