isc.defineClass("OPINIATOR_FrequencySelector", isc.DynamicForm);
OPINIATOR_FrequencySelector.addProperties ({
    // Superclass properties
    //showShadow:false,
    //shadowOffset:9,
    //shadowSoftness:10,
    //styleName: "performanceContentFrame",
    styleName: "performanceContent",
    fixedColWidths:false,

    // The Items
    items: [
        {
        name:"range",
        title:"Select Time Span",
        titleAlign:"left",
        showTitle:false,
        align:"center",
        tabIndex:2,
        startRow:true,
        wrapTitle:false,
        type:"enum",
        valueMap: { 
            "DAY": "Today", 
            "WEEK": "This Week",
            "MONTH": "This Month", 
            "YEAR": "This Year"
            }, 
        width:130,
        height:25
        }],

    initWidget : function () 
        { 
        this.Super("initWidget", arguments); 
        this.setValue("range", "DAY");
        },

    destroy: function()
        { 
        delete this.target;
        this.Super("destroy", arguments); 
        },

    itemChange: function( item, newValue, oldValue )
        { this.target.changeRange(newValue); }
});


isc.defineClass("OPINIATOR_FrequencyChart", OPINIATOR_FusionChart);
OPINIATOR_FrequencyChart.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" ]
    });
OPINIATOR_FrequencyChart.addProperties ({
    // Private Properties
    _freqSets: null,
    _freqSetNo: 0,
	_hideDateRange: null,
    // Superclass Properties
    chart:"FusionCharts/Column3D.swf",
    attributes: 
        {
        //caption:"Rolling 12 Months",
        //xAxisName:Month",
        yAxisMinValue:0,
        yAxisMaxValue:100,
        numberPrefix:"",
        numberSuffix:"%",
        decimalPrecision:0,
        showhovercap:true,
        showNames:true,
        showValues:false,
        showChartLimits:false,
        rotateNames:false,
        showColumnShadow:false,
        showLineShadow:false,
        animation:true,
        showAlternateHGridColor:false,
        //AlternateHGridColor:"ff5904",
        //divLineColor:"ff5904",
        //divLineAlpha:20,
        numDivLines:3,
        divLineColor:"ffffff",
        divLineDecimalPrecision:0,
        showDivLineValue:true,
        hShowDivLineValue:false,
        //alternateHGridAlpha:5,
        canvasBgColor:"000000",
        canvasBorderColor:"000000",
        canvasBorderThickness:0,
        baseFontColor:"ffffff",
        lineThickness:2,
        limitsDecimalPrecision:0,
        //divLineDecimalPrecision:0,
        hoverCapBgColor:"000000",
        hoverCapBorderColor:"868586",
        baseFont:"Trebuchet MS, Helvetica, sans-serif",
        baseFontSize:"14",
        baseFontColor:"ffffff",
        outCnvBaseFont:"Trebuchet MS, Helvetica, sans-serif",
        outCnvBaseFontSize:"12",
        outCnvBaseFontColor:"c4c4c4",
        anchorBgAlpha:100,
        anchorBorderThickness:1,
        anchorBorderColor:"000000",
        anchorBgAlpha:100,
        lineColor:"ffffff",
        //bgColor:"525456"
        zeroPlaneColor:"272829",
        bgColor:"000000",
        exportEnabled:true,
		exportAtClient:false,
		exportAction:"download",
		exportHandler: location.href + "/FCExporter.jsp",
		exportFileName:'MyFileName'
        },
    //backgroundColor:"#525456",
    backgroundColor:"#000000",
    styleName:"performanceContent",

    initWidget : function () 
        { 
        this._hasAnimated = false;
        this.Super("initWidget", arguments); 
        },

    destroy: function()
        {
        delete this._tallies;
        this.Super("destroy", arguments);
        },

    changeRange: function( range )
        {
        this._freqSetNo = this._freqSets.findIndex("name", range);
        if ( this._freqSetNo < 0 )
            { this._freqSetNo = 0; }
        this.updateRangeLabel();
        },

    updateRangeLabel: function()
        {
        if (this._hideDateRange == null) 
		{
			if (this._freqSets !== null) {
				var set = this._freqSets[this._freqSetNo];
				var begin = new Date(set.begin);
				var end = new Date(set.end);
				
				switch (set.name) {
					case "DAY":
						this.attributes.xAxisName = end.dFormat("ddd d, mmm 'yy");
						break;
					case "WEEK":
						this.attributes.xAxisName = begin.dFormat("ddd d, mmm 'yy") + " - " + end.dFormat("ddd d, mmm 'yy");
						break;
					case "MONTH":
						this.attributes.xAxisName = begin.dFormat("ddd d") + " - " + end.dFormat("ddd d, mmm 'yy");
						break;
					case "YEAR":
						this.attributes.xAxisName = begin.dFormat("mmm") + " - " + end.dFormat("mmm 'yy");
						break;
					default:
						break;
				}
			}
		}
        this.refreshChart();
        },

    getDataset: function()
        { 
        var dataset = null;
        if ( this._freqSets !== null )
            {
            var set = this._freqSets[this._freqSetNo];
            var values = set.freqValues;
            if ( isc.isAn.Array(values) )
                { dataset = values; }
            else if ( isc.isAn.Object(values) )
                { dataset = [values]; }

            // Change the dataset to a percentage and make the hover the number 
            // counts
            if ( dataset !== null )
                {
                dataset = this.getPercentages(dataset);
                dataset.sortByProperty("value", false);
                }
            }

        return dataset === null ? [] : dataset;
        },

    getPercentages: function( dataset )
        {
        var total = 0;
        var len = dataset.getLength();
        for ( var i = 0; i < len; i++ )
            { total += dataset[i].value; }

        var ndataset = new Array();
        for ( i = 0; i < len; i++ )
            { 
            var datum  = dataset[i];
            var color;
            if ( i < OPINIATOR_FrequencyChart.colors.length )
                { color = OPINIATOR_FrequencyChart.colors[i]; }
            else
                { color = OPINIATOR.randomColor(); }
            var ndatum = { 
                name:datum.name, 
                value:0, 
                hoverText:"Total " + datum.value,
                color:OPINIATOR_FrequencyChart.colors[i]
                };
            if ( datum.value !== 0 )
                { ndatum.value = (datum.value/total)*100; }
            ndataset.push(ndatum);
            }

        return ndataset;
        },

    updateChart: function( freqSets )
        {
        this._freqSets = freqSets;
        this.updateRangeLabel();
        }

    });

isc.defineClass("OPINIATOR_FrequencyView", isc.HLayout);
OPINIATOR_FrequencyView.addProperties({

    // Private Properties
    _chart: null,

    //  Add the busy indictors
    showBusy: OPINIATOR_ShowBusy,
    destroyBusy: OPINIATOR_DestroyBusy,

    // Superclass  Propeties
    leaveScrollbarGap:true,
    showShadow: false, 
    width: "100%",
    height: 245,
    styleName:"performanceContent",
	chartFontSize: null,
	styleChartSelector: null,
	hideDateRange: null,
	chartBgColor:null,
	chartFont:null,
	showSelectorBottom:null,
    initWidget : function () 
        {
        this._chart = OPINIATOR_FrequencyChart.create({width:"100%", height:"*"});
		if (this.chartFontSize != null) {
			this._chart.attributes.outCnvBaseFontSize = this.chartFontSize;				
		}
		if (this.chartFont != null) {			
			this._chart.attributes.outCnvBaseFont=this.chartFont;	
		}		
		if(this.hideDateRange!=null){
			this._chart._hideDateRange=this.hideDateRange;			
		}	
		if(this.chartBgColor!=null){
			this._chart.attributes.canvasBgColor=this.chartBgColor;			
		}	
        this._selector = OPINIATOR_FrequencySelector.create({target:this._chart, width:"100%", height:20});
		if (this.styleChartSelector != null) {
			this._selector.className = this.styleChartSelector;	
		}
		
      // Center the Frequency Chart
		if(this.showSelectorBottom==null){
			var chart_view = isc.VLayout.create({
            members: [
                OPINIATOR.vSpacer(5), 
                this._chart, 
                OPINIATOR.vSpacer(5), 
                this._selector, 
                OPINIATOR.vSpacer(5)],
            showShadow: false, 
            width: "*",
            height: "100%",
            styleName:"performanceContent"
            });	
		}else{
			var chart_view = isc.VLayout.create({
            members: [
                OPINIATOR.vSpacer(5), 
                this._selector, 
                OPINIATOR.vSpacer(5), 
                this._chart, 
                OPINIATOR.vSpacer(5)],
            showShadow: false, 
            width: "*",
            height: "100%",
            styleName:"performanceContent"
            });
		}

        this.members = [OPINIATOR.hSpacer("10%"), chart_view, OPINIATOR.hSpacer("10%")];
        this.Super("initWidget", arguments);
        },

    destroy: function()
        {
        delete this._chart;
        delete this._selector;
        this.Super("destroy", arguments);
        },

    updateView: function( analytics, analytic )
        { 
        this.showBusy(true, OPINIATOR.BUSY_DELAY);

        // Create the set date ranges for the query
        var ranges = new Array();
        var end = new Date();

        ranges.push(this._getRange("DAY", end));
        ranges.push(this._getRange("WEEK", end));
        ranges.push(this._getRange("MONTH", end));
        ranges.push(this._getRange("YEAR", end));

        WebClientSvc.getFrequencySets(analytics.type, 
                                      analytics.id, 
                                      analytic.id, 
                                      {list:ranges},
                                      this.callback("_updateView"), 
                                      this.callback("error")); 
        },

    _getRange: function( rangename, end )
        {
        var begin = new Date();

        switch ( rangename )
            {
            case "DAY":
                break;
            case "WEEK":
                {
                var day = begin.getDay();
                if ( day === 0 ) 
                    { day = 7; }
                var days = 1 - day;
                var t = begin.getTime();
                t += days*24*60*60*1000;
                begin.setTime(t);
                }
                break;
            case "MONTH":
                begin.setDate(1);
                break;
            case "YEAR":
                begin.setMonth(0);
                begin.setDate(1);
                break;
            default:
                break;
            }

        begin.setHours(0); 
        begin.setMinutes(0); 
        begin.setSeconds(0);

        return {name:rangename, begin:begin, end:end };
        },

    _updateView: function( freqsets )
        { 
        this.showBusy(false);
        this._chart.updateChart(freqsets.sets); 
        },

    error: function (code, msg)
        {
        this.showBusy(false);
      /*  switch ( msg )
            {
            case "DeletedState":
                OPINIATOR.warn("This category has been deleted by another user.");
                break;

            default:
                OPINIATOR.warn(msg);
                break;
            }*/
        },

    callback: function (methodName)
        { return {target:this, methodName:methodName}; }
    });

