// global variables
var _globalTally = null; // Performance
var _globalTallySecond = null; // Importance
var _isChange=null; //Flag is use for auto update performance chart

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

    // The Items
    items: 
        [
        {
        height:10,
        name:"spacer0",
        cellStyle:"performanceContentFrameValue",
        _constructor:"SpacerItem"
        },
        {
        name:"value",
        title:"MTD",
        defaultValue:0.0,
        width:40,
        cellStyle:"performanceContentFrameValue",
        titleStyle:"performanceContentFrameTitle",
        textBoxStyle:"performanceContentFrameValue",
        _constructor:"StaticTextItem"
        },
        {
        name:"ytd",
        title:"YTD",
        defaultValue:0.0,
        cellStyle:"performanceContentFrameValue",
        titleStyle:"performanceContentFrameTitle",
        textBoxStyle:"performanceContentFrameValue",
        width:40,
        _constructor:"StaticTextItem"
        }],

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

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

    updateView: function( tally )
        {
        var val = new Number(tally.value);
        var ytd = new Number(tally.ytd);

        this.setValue("value", val < 0 ? "n/a" : val);
        this.setValue("ytd", ytd < 0 ? "n/a" : ytd);
        }
    });


isc.defineClass("OPINIATOR_TallyTrendChart", OPINIATOR_FusionChart);
OPINIATOR_TallyTrendChart.addClassProperties({
        trendColors:[ "4930AE", "4930AE", "4930AE", "4930AE", "4930AE", "4930AE", 
                      "4930AE", "4930AE", "4930AE", "4930AE", "4930AE", "4930AE" ]
        });
OPINIATOR_TallyTrendChart.addProperties ({

    // Private Properties
    _trend: null,
	
	categories: null,	
	
	_target: null,
	
	showTarget: false,
	
    // Superclass Properties
    chart:"FusionCharts/MSLine.swf",
    attributes: 
        {
        //caption:"Rolling 12 Months",
        //xAxisName:Month",
        yAxisMinValue:1,
        yAxisMaxValue:5,
        numberPrefix:"",
        showhovercap:true,
        showNames:true,
        showValues:false,
        showChartLimits:true,
        rotateNames:true,
        showColumnShadow:false,
        showLineShadow:false,
        animation:true,
        showAlternateHGridColor:true,
        AlternateHGridColor:"ff5904",
        divLineColor:"ff5904",
        divLineAlpha:20,
        showDivLineValue:true,
        hShowDivLineValue:true,
        alternateHGridAlpha:5,
        canvasBorderColor:"000000",
        canvasBorderThickness:0,
        baseFontColor:"ffffff",
        lineThickness:2,
        limitsDecimalPrecision:0,
        divLineDecimalPrecision:0,
        numDivLines:3,
        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"
        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()
        {
        this._trend = null;
		this.categories = null,
        this.Super("destroy", arguments);
        },

    getDataset: function()
        { return this._trend; },

	getSeries: function() {
		return [{attributes:{}, dataset:this._target}, {attributes:{}, dataset:this._trend}];
	},
	
	getCategories: function() {
		var obj = {attributes:{}, labels:this.categories};
		return obj;
	},
	
    updateView: function( tally )
        {
        this._trend = isc.isAn.Array(tally.trend) ? tally.trend : [];

		this._target = [];
		this.categories = [];
		var len = this._trend.getLength();
		
		for (var i = 0; i < len; i++) {
			if (this.showTarget) {
				var obj = {
					name: this._trend[i].name,
					value: tally.ytarget,
					color:"#FF0000"
				};
				this._target.add(obj);	
			}
			
			this.categories.add({
				label: this._trend[i].name
			});
		}
		
        // Colorize the trend chart
        for ( var i = 0; i < len; i++ )
            { this._trend[i].color = OPINIATOR_TallyTrendChart.trendColors[i]; }

        var attributes = isc.clone(this.attributes);
        if ( this._hasAnimated )
            { attributes.animation = false; }

        attributes.yAxisMinValue = tally.min;
        attributes.yAxisMaxValue = tally.max;
        this.setAttributes(attributes);

        this._hasAnimated = true;
        this.refreshChart();
        },
		
	setTarget :function(target) {
		this._target = target;
	},

	setShowTarget: function( value ) {
		this.showTarget = value;
	}

    });


isc.defineClass("OPINIATOR_TallyBulletChart", OPINIATOR_FusionWidget);
OPINIATOR_TallyBulletChart.addProperties ({
     chart:"FusionCharts/HBullet.swf",
     backgroundColor:"#000000",
     styleName:"performanceContent",

     colorRange: [
        {
        // Red Zone
        minValue: 0,
        maxValue: 0,
        code: "CF0032"
        },
        {
        // Yellow Zone
        minValue: 0,
        maxValue: 0,
        code: "FFF32D"
        },
        {
        // Green Zone
        minValue: 0,
        maxValue: 0,
        code: "50BC4C"
        }
        ],

     attributes: 
        {
        // Functions
        animation: true,
        defaultAnimiation: true,
        pallete: 2,

        // Chart Axis
        lowerLimit:1,
        upperLimit:5,
        adaptiveYMin:true,

        // Chart Caption
        caption:"",
        subCaption:"",

        // Number Formatting
        numberPrefix:"",
        decimals:1,
        forceDecimals:true,

        // Plot Properties
        showValue:false,
        plotAsDot:false,
        plotFillPercent:50,
        plotFillAlpha:80,
        targetFillPercent:80,
        plotFillColor:"000000",
        showPlotBorder:false,
        targetColor:"000000",
        targetThickness:4,

        // ColorRange
        colorRangeFillMix: "{light-50},{dark-30},{color}", 
        //colorRangeFillRatio: "5,10,85", 
        showColorRangeBorder:true,
        colorRangeBorderColor:"000000",
        colorRangeBorderThickness:1,
        showShadow:false,
        roundRadius:true,

        // TickMarks
        showTickMarks:true,
        showTickValues:true,
        showLimits:true,
        ticksBelowGraph:true,
        majorTMColor:"c4c4c4",
        adjustTM:true,

        // Tooltip
        showToolTip:true,
        toolTipBgColor:"000000",
        toolTipBorderColor:"868586",

        // Font Properties
        baseFont:"Trebuchet MS, Helvetica, sans-serif",
        baseFontSize:"14",
        baseFontColor:"c4c4c4",

        // Background
        bgColor:"000000",
        showBorder:false,

        // Chart Paddings & Margins
        chartRightMargin:30,
        
        exportEnabled:true,
		exportAtClient:false,
		exportAction:"download",
		exportHandler: location.href + "/FCExporter.jsp",
		exportFileName:'MyFileName'
        },

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

    destroy: function()
        {
        this._tally = null;
        this.Super("destroy", arguments);
        },

    updateView: function( tally )
        {
        this._tally = tally;

        var attributes = isc.clone(this.attributes);
        if ( this._hasAnimated )
            { attributes.animation = false; }
        attributes.lowerLimit = tally.min;
        attributes.upperLimit = tally.max;
        this.setAttributes(attributes);

        var colorRange = isc.clone(this.colorRange);

        colorRange[0].minValue = tally.min;
        colorRange[0].maxValue = tally.maxPoor;

        colorRange[1].minValue = tally.maxPoor;
        colorRange[1].maxValue = tally.maxFair;

        colorRange[2].minValue = tally.maxFair;
        colorRange[2].maxValue = tally.max;

        this.setColorRange(colorRange);

        // Don't let tally's be less then there minimum value.  This may be the case
        // when the tally has no data.
        var val = new Number(tally.value);
        if ( val < tally.min )
            { val = tally.min; }
        this.setValue(val);
        this.setTarget(tally.mtarget);

        this._hasAnimated = true;
        this.refreshChart();
        }
    });

isc.defineClass("OPINIATOR_PerformanceTallyView", isc.HLayout);
OPINIATOR_PerformanceTallyView.addProperties({
    // Contructor properties
    tallyName: null,
    tallyNo: null,
	
	_tally : null,

    // Private Properties
    _headerImage: null,
    _valuesForm: null,
    _trendChart: null,
    _bulletChart: null,
	
    // Superclass  Propeties
    leaveScrollbarGap:true,
    showShadow: false, 
    width: "100%",
    height: 145,
    styleName:"performanceContent",
	
    initWidget : function () 
        {
        this._headerImage = isc.Img.create({
            src: OPINIATOR_PerformanceSection.getStatusImage(null),
            imageType: "center",
            showTitle: false,
            title: "RYG",
            align:"right",
            imageType:"center",
            layoutAlign:"right",
            width:26
            });

        var header_label =  isc.Label.create ({
            contents: this.tallyName,
            height: 30,
            align: "left",
            valign: "left",
            defaultValue: " ",
            wrap: false,
            showEdges: false,
            baseStyle: "performanceContentFrameHeader",
            width:"*"
            });

        var header = isc.HLayout.create({
            members:[ header_label, this._headerImage],
            height:"30",
            width:"100%",
            styleName: "performanceContentFrameHeader"
            });

        this._valuesForm = OPINIATOR_TallyValueView.create({width:"100%", height:"100%"});
        this._trendChart = OPINIATOR_TallyTrendChart.create({width:"40%", height:"100%"});
        this._bulletChart = OPINIATOR_TallyBulletChart.create({width:"100%", height:70});

        var values_view = isc.VLayout.create({
            members: [header, this._valuesForm, OPINIATOR.vSpacer(20)],
            width:"20%"
            });

        // Center the Bullet Chart
        var bullet_view = isc.VLayout.create({
            members: [OPINIATOR.vSpacer("*"), this._bulletChart, OPINIATOR.vSpacer("*")],
            showShadow: false, 
            width: "40%",
            height: "100%",
            styleName:"performanceContent"
            });
		
		
        this.members = [OPINIATOR.hSpacer(10), values_view, this._trendChart, OPINIATOR.hSpacer(10), bullet_view];
        this.Super("initWidget", arguments);
        },

	getTrendChart: function() {
		return this._trendChart;
	},

    destroy: function()
        {
            this._headerImage = null;
        this._valuesForm = null;
        this._trendChart = null;
        this._bulletChart = null;
        this.Super("destroy", arguments);
        },

    updateView: function( analytics, analytic )
        {
        this._headerImage.setSrc(OPINIATOR_PerformanceSection.getStatusImage(tally));
        // Get view the tally based upon which tally no was set a creation time.
        var tally = ( this.tallyNo === null ) ? analytic.tally : analytic.tallies[this.tallyNo];
		if (autoUpdate) {
			this._valuesForm.updateView(tally);
        	this._trendChart.updateView(tally);
        	this._bulletChart.updateView(tally);	
		}
        }
	
});



/**
 * @class PerformanceSection    Class is used to create 
 * collapsable StackSections for the PerformancePane.  The class
 * can create and destory its contents on the fly.
 * 
 * @author ktyra (10/21/2008)
 *  
 */
isc.defineClass("OPINIATOR_PerformanceSection", isc.SectionHeader);
OPINIATOR_PerformanceSection.addClassProperties({
    /**
     * Returns the the RYG status indicator
     * 0 - Red, 1 - Yellow, 2 - Green
     */
    getRYG: function ( tally )
        {
        if ( isc.isAn.Object(tally) )
            {
            var val = new Number(tally.value);
            var maxPoor = new Number(tally.maxPoor);
            var maxFair = new Number(tally.maxFair);
            if (  val < 0 )      { return -1; }
            if (  val < maxPoor )      { return 0; }
            else if (  val < maxFair ) { return 1; }
            else { return 2; }
            }
        return -1;
        },

    /**
     * Returns an image name suitable to describe the ryg indicator
     * status.
     */
    getStatusImage: function ( tally )
        {
        switch ( OPINIATOR_PerformanceSection.getRYG(tally) )
            {
            case 0:  return "redball.png";
            case 1:  return "yellowball.png";
            case 2:  return "greenball.png";
            default: return "blank.gif";
            }
        },

    /**
     * Returns the header opener image name for the opener/closer 
     * icon based upon the ryg status of the dataset
     */
    getOpenerImage: function ( tally )
        {
        switch ( OPINIATOR_PerformanceSection.getRYG(tally) )
            {
            case 0: return  "red.png";
            case 1:  return "yellow.png";
            case 2:  return "green.png";
            default: return "na.png";
            }
        }
    });

OPINIATOR_PerformanceSection.addProperties({
	
    // Private Properties
	_tally: null,	
	_tallySecond:null,
    _contents:null,
    _views:null,
	_analytic:null,
	_ytarget:null,
	_ytargetSecond:null,

    // Superclass Properties
    /**
     *  Expand/Collapse icon properties 
     */
    iconWidth:24,
    iconHeight:24,
    skinImgDir:isc.Page.getAppDir()+"/images/skin/",
    baseStyle:"performanceSection",
    icon:"[SKIN]PerformanceSection/green.png",

    // Used for the initWidget to the status icon after that it is no longer used 
    initProps: {analytics:null, analytic:null},
    initWidget : function () 
        { 
        this.Super("initWidget", arguments); 
        this.updateViewPort(this.initProps.analytics, this.initProps.analytic);
        // These are no longer needed
        delete this.initProps;
        },

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

     /**
      * Destroys the sections contents
      */
    destroyViewPort: function () 
        {
        if ( isc.isAn.Object(this._contents) )
            { 
            delete this._views;
            isc.Log.logInfo("Destroying Section Contents: " + this.title + "(" + this.ID + ")");
            this._contents.destroy(); 
            delete this._contents;
            }
        },

    createViewPort: function ( type, name , catid )
        {	 	
        // Destroy and preexisting contents
        this.destroyViewPort();
	
        if ( type == "NETPROMOTER" )
            {
            this._views = [OPINIATOR_PerformanceTallyView.create({tallyName:"Net Promoter", height:150, tallyNo:null})];
			var trendChart = this._views[0].getTrendChart();
			var period = OPINIATOR_TrendChartPeriod.create({width: 214,
															trendChart:trendChart,
															analytic:this._analytic,
															ytarget:this._ytarget});
			
			var checkbox = OPINIATOR_DisplayTargetLine.create({ 
							padding: "0 0 0 2",
							trendChart: trendChart,
							catId: catid,
							styleName:"targetLineStyle"
							});

			var hLayout = isc.HLayout.create({ members: [period, checkbox]});
			
			this._contents = isc.VLayout.create({members: [this._views[0], hLayout], height:160});
										
            //this._contents = this._views[0];
            }
        else if ( type == "NUMERIC" )
            {
            this._views = [OPINIATOR_PerformanceTallyView.create({tallyName:name, height:150, tallyNo:null})];
			var trendChart = this._views[0].getTrendChart();
			
			var period = OPINIATOR_TrendChartPeriod.create({width: 214,
															trendChart:trendChart,
															analytic:this._analytic,
															ytarget:this._ytarget});
			
			var checkbox = OPINIATOR_DisplayTargetLine.create({ 
							padding: "0 0 0 2",
							trendChart: trendChart,
							catId: catid,
							styleName:"targetLineStyle"
							});
			
			var hLayout = isc.HLayout.create({ members: [period, checkbox]});
			
			this._contents = isc.VLayout.create({members: [this._views[0], hLayout], height:160});
			
            //this._contents = this._views[0];
            }
        else if ( type == "CHOICE" )
            {
            this._views = [OPINIATOR_FrequencyView.create({height:250})];
            this._contents = this._views[0];
            }
        else if ( type == "ZIPCODE" )
            {
            this._views = [OPINIATOR_FrequencyView.create({height:250})];
            this._contents = this._views[0];
            }
        else
            {
            var perf = OPINIATOR_PerformanceTallyView.create({tallyName:"Performance", height:"160", tallyNo:0});
            var imp  = OPINIATOR_PerformanceTallyView.create({tallyName:"Importance", height:"160", tallyNo:1});
            this._views = [perf, imp];
			
			var period = OPINIATOR_TrendChartPeriod.create({width: 214,
														    trendChartPerformance:perf.getTrendChart(),
															trendChartImportance:imp.getTrendChart(),
															analytic:this._analytic,
															ytarget:this._ytarget,
															ytargetSecond:this._ytargetSecond});
			
			var checkbox = OPINIATOR_DisplayTargetLine.create({ 
							padding: "0 0 0 2",
							trendChart: perf.getTrendChart(),
							trendChartSecond: imp.getTrendChart(),
							catId: catid,
							styleName:"targetLineStyle"
							});
			
			var hLayout = isc.HLayout.create({ members: [period, checkbox]});
										
            this._contents = isc.VLayout.create({members: [this._views[0], this._views[1], hLayout], height:300});
            }

        return this._contents;
        },

    getViewPort: function ()
        { return this._contents; },

    updateViewPort: function ( analytics, analytic )
        {

        // Update the _contents views if such a view exists and therefore is open
        // and visible.
        if ( isc.isAn.Array(this._views) )
            {
            var len = this._views.getLength();
            for ( var i = 0; i < len; i++ )
                {
                var view = this._views[i];
                this._views[i].updateView(analytics, analytic);
                }
            }

		// save analytic 
		this._analytic = analytic;
		if (isc.isA.Object(analytic.tally)) {
			this._ytarget = analytic.tally.ytarget;	
		} else if (isc.isAn.Array(analytic.tallies)) {
			this._ytarget = analytic.tallies[0].ytarget;
			this._ytargetSecond = analytic.tallies[1].ytarget;
		}
		

        // Set the image of the expand collapse based upon the status of the tally against its KPI
        var status_tally = null;
        if ( isc.isAn.Object(analytic.tally) ){ 
			status_tally = analytic.tally;
			_globalTally = analytic.tally; 
		}
        else if ( isc.isAn.Array(analytic.tallies) ) { 
			status_tally = analytic.tallies[0];
			_globalTally = analytic.tallies[0];
			_globalTallySecond = analytic.tallies[1]; 
		}

        if ( status_tally === null )
            {
            // No tally for determining the performance just use green
            this.setIcon("[SKIN]PerformanceSection/green.png");
            }
        else
            {
            this.setIcon("[SKIN]PerformanceSection/"+
                         OPINIATOR_PerformanceSection.getOpenerImage(status_tally));
            }
        }
		
    });

isc.defineClass("OPINIATOR_PerformancePane", isc.SectionStack);
OPINIATOR_PerformancePane.addProperties({

    // Private properties
    _panalytics: null,
    _analytics: null,
	_catId : null, // category type in section
		
	/// Super Class Properties
    leaveScrollbarGap:true,
    overflow:"auto",
    //  Only one section should be open at a time.  Memory consumption and performance become
    //  strained when more then one section open.  Potentially due to the number flash 
    //  objects opened.
    visibilityMode:"mutex", 
    sectionHeaderClass:"OPINIATOR_PerformanceSection",
    headerHeight:40,
    animateSections:OPINIATOR.STACK_ANIMATE,
    animateMemberTime:OPINIATOR.STACK_ANIMATE_TIME,
    styleName: "performancePane",

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

    destroy: function( )
        {
        delete this._analytics;
        delete this._panalytics;
        delete this._prevSection;
        this.Super("destroy", arguments);
        },

    setAnalytics: function ( analytics )
        {
		
		 new_panalytics = [];
		 var panalytics = analytics.list;
		 for (var i = 0; i < panalytics.length; i++) {			
			 if (panalytics[i].type != "WELCOME" && panalytics[i].type != "THANKYOU" && panalytics[i].type != "TEXT"
			 && panalytics[i].surveyType == null) {
				 new_panalytics.add(panalytics[i]);
			 };			
		 }

        var old_panalytics = this._panalytics;
        this._panalytics = new_panalytics;
        this._analytics = analytics;

        // Check for same structure.  If the structure is different then we need to rebuild
        // the sections list.  Otherwise, we'll just force the sections to update themselves
        if (OPINIATOR.listDiffer(old_panalytics, new_panalytics, "id") || OPINIATOR.listDiffer(old_panalytics, new_panalytics,	"name")) {
			this._createSections();
		} else {
			this._updateSections();
		}
		},

    _updateSections: function ()
        {
        var ids = this.getSections();
        if ( isc.isA.List(ids) )
            {
            var len = ids.getLength();
            for (  var i = 0; i < len; i++  )
                { 
                var sec = this.getSectionHeader(ids[i]);
                if ( isc.isAn.Object(sec) )
                    { sec.updateViewPort(this._analytics, this._panalytics[sec.analyticIndex]); }
                }
            }
        },

    /**
     * Create the properties for Performance sections for data in 
     * the dataset properties 
     */
    _createSections: function ()
        {
        var sections = this.getSections();
        for ( var i = sections.getLength() - 1; i >= 0; i-- )
            { this.removeSection(i); }

        // Create a section for each category and place the sections in a stack widget.
        sections = new Array(len); 
        var len = this._panalytics.getLength();
        for ( i = 0;  i < len; i++ )
            { 
            var analytic = this._panalytics[i];
            sections[i] = {
                ID:i, 
                title:analytic.name, 
                analyticIndex:i,
                initProps:{analytics:this.analytics, analytic:analytic}, 
                expanded:false
                }; 
            }

        this.addSections(sections);
        },

    /**
     *  Overrides the section expansion in order to create the
     *  contents of the section just before expansion.
     *  
     *  @param section  The section to be expanded supposedly can be
     *                  either a Section Object, Section Id, or
     *                  Section Name.  Currently we only support
     *                  object.
     *
     *  @param callback Method to be called once the expansion has
     *                  completed. So far does not appear to work.
     */
    expandSection: function ( section, callback )
        {
        var analytic = this._panalytics[section.analyticIndex];
        var viewport = section.createViewPort(analytic.type, analytic.name, analytic.id);		
        section.updateViewPort(this._analytics, analytic);
        this.addItem(section, viewport, 0);
		autoUpdate = true;
        this.Super("expandSection", arguments);
        },

    _sectionCollapsed: function( section )
        {
        if ( section )
            {
            this.removeItem(section, section.getViewPort()); 
            section.destroyViewPort();
            }
        },

    _sectionExpanded: function( section )
        { this._prevSection = section; },


    /**
     *  The default behaviour of a Mutex SectionStack is not to
     *  collapse the Section if its openned.  In other words, unless
     *  we are openning another section the default behavour won't
     *  allow the current one to collapse.  We are overriding that
     *  behaviour here.
     * 
     */
    sectionHeaderClick: function ( section )
        {
        // If Expand and Collapsing the same section then just collapse or expand.  This is different
        // the the standard SmartClient Mutex logic
        if ( this._prevSection && (this._prevSection.ID == section.ID) )
            {
            if ( this.sectionIsExpanded(section) )
                { this.collapseSection(section, this.ID+"._sectionCollapsed("+this._prevSection.ID+")"); }
            else
                { this.expandSection(section); }
            }
        else
            {
            //  This is the standard SmartClient mutex logic except we are destroying the conents
            //  of the collapsed section after the animation as we do above. Because too many open
            //  flash charts chew up memory.
            if ( this._prevSection && this.sectionIsExpanded(this._prevSection) )
                { this.collapseSection(this._prevSection, this.ID+"._sectionCollapsed("+this._prevSection.ID+")"); }

            this.expandSection(section); 
            this._prevSection = section;
            }
        }

    });
	
	
isc.defineClass("OPINIATOR_DisplayTargetLine", isc.DynamicForm);
OPINIATOR_DisplayTargetLine.addProperties({
    
	trendChart: null,
	trendChartSecond: null,
	catId: null,
	sequencedCategory: null,
	
	// Superclass Properties
    showBusy:OPINIATOR_ShowBusy,
    destroyBusy:OPINIATOR_DestroyBusy,

    // Superclass Properties
    minColWidth:10,
    cellPadding:2,
    numCols:2,
    fixedColWidths:false,
    titleWidths:80,
    cellBorder:0,
    showResizeBar:false,
    layoutAlign:"left",
    itemHoverDelay:3000,
    selectOnFocus:true,
	
	items:[
		{
	        name:"target_line",
	        title:"Show target line",
	        type:"boolean",
	        startRow:true,
	        height:25
        }
	],
	
	initWidget: function ()	
    { 
		this.Super("initWidget", arguments);
		
		// get category to save enable target line attribute
		if (sId != null && isc.isA.Number(this.catId) && this.catId != null) {
			WebClientSvc.getSequencedCategory(this.catId, sId, this.callback("_catloaded"), this.callback("error"));				
		} else {
			this.getItem("target_line").hide();
		}
		
	},
	
	destroy: function () {               
        this.Super("destroy", arguments);
    },
	
	itemChange: function (item, newValue, oldValue) {
		var iname = item.getFieldName();
		switch (iname) {
			case "target_line":
				if (isc.isA.Object(this.sequencedCategory)) {
					this.sequencedCategory.enableTargetLine = newValue;
					WebClientSvc.saveTargetLine(this.sequencedCategory.catref.id, sId, newValue, this.callback("_saveDone"), this.callback("error"));	
				}
				break;
			default:
				break;
		}
	},
	
	_saveDone: function( sequencedCategory ) {
		if (_globalTally != null) {
			this.updateChart( this.trendChart, _globalTally );	
		}
		
		if (_globalTallySecond != null) {
			this.updateChart( this.trendChartSecond, _globalTallySecond);
		}
		
		this.sequencedCategory = sequencedCategory;
	},
	
	_catloaded: function( sequencedCategory ) {
		this.sequencedCategory = sequencedCategory;
		this.getItem("target_line").setValue(sequencedCategory.enableTargetLine);	
		
		if (_globalTally != null) {
			this.updateChart( this.trendChart, _globalTally );	
		}
		
		if (_globalTallySecond != null) {
			this.updateChart( this.trendChartSecond, _globalTallySecond );
		}
	},
		
	callback: function (methodName)
        { return {target:this, methodName:methodName}; },
	
	error: function (code, msg) {
        switch ( msg ) {
            default:
                OPINIATOR.warn(msg);
                break;
		}
	},
	
	updateChart: function( chart , tally ) {
		if (chart != null) {
			chart.setShowTarget(this.sequencedCategory.enableTargetLine);
			chart.updateView(tally);
		}
	}
	
});


isc.defineClass("OPINIATOR_TrendChartPeriod", isc.DynamicForm);
OPINIATOR_TrendChartPeriod.addProperties({
    
	trendChart:null,
	analytic:null,
	ytarget:null,
	trendChartPerformance:null,
	trendChartImportance:null,	
	ytargetSecond:null,
	
	// Superclass properties
    showShadow:true,
    shadowOffset:9,
    shadowSoftness:10,    
    fixedColWidths:false,
	numCols:2,
    // The Items
    items: 
        [
			{
		        name:"chartPeriod",
		        title:"Period",
		        titleAlign:"right",
		        align:"left",
		        startRow:true,
		        type:"enum",
		        valueMap: { 
		            "ALL_TIME": "All time", 
		            "LAST_YEAR": "Last Year",
		            "LAST_MONTH": "Last Month",
		            "LAST_WEEK": "Last Week",
		            "LAST_24H": "Last 24 hours",
					"CUSTOM": "Custom"
		            }, 
				defaultValue: "LAST_YEAR",
		        width:120,
		        height:25
        	},
			
			{ height:10, startRow:true, _constructor:"RowSpacerItem" },
			
			{
		        ID:"PeriodStartTimeID",
		        title:"Start",
		        name:"start",
		        startRow:true,
		        height:30,
		        type:"canvas",
		        showTitle:true,
		        showFocused:true,
		        showFocusedAsOver:false,
		        titleAlign:"right",
		        titleOrientation:"left",
		        align:"left",
		        textAlign:"left",
		        canvasConstructor:"OPINIATOR_DatePicker",
		        canvasProperties:{ID:"PeriodStartTimePickerID"}
     	   },	  
			
		   //  End Time
        	{
		        ID:"PeriodEndTimeID",
		        title:"End",
		        name:"end",
		        startRow:true,
		        height:30,
		        showTitle:true,
		        showFocused:true,
		        showFocusedAsOver:false,
		        titleAlign:"right",
		        titleOrientation:"left",
		        align:"left",
		        textAlign:"left",
		        type:"canvas",
		        canvasConstructor:"OPINIATOR_DatePicker",
		        canvasProperties:{ID:"PeriodEndTimePickerID"}
    	    },			
			{
				ID:"PeriodToolBarRecipientID",
				name: "period_toolbar_button",
				title: "",
		        startRow:true,
		        height:30,			
		        type:"canvas",
		        showTitle:true,
		        showFocused:true,
		        showFocusedAsOver:false,
		        titleAlign:"left",
		        titleOrientation:"left",
		        align:"left",
		        textAlign:"left",
		        canvasConstructor:"OPINIATOR_ButtonBar",
		        canvasProperties: {
					ID: "ToolBarPeriod",
					align: "left",
					layoutAlign: "center",
					canFocus: false,
					defaultWidth: 80,
					height: 30,
					width: 290,
					target: this,
					buttons: [
						{
			                ID: "filter_custom",
			                title: "Apply",
							target: this,
			                visibility:"visible",
			                tabIndex:1,
			                //icon: "icons/16/category.png",
			                click: function () {																				
								this.parentElement.parentElement.getSurveyForCustom();				
								return true;
							}
	                	}
					]
				}
			} 
			
        ],

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

    destroy: function()
        { this.Super("destroy", arguments); },
	
	itemChange: function (item, newValue, oldValue) {
		var iname = item.getFieldName();
		
		if (newValue == "CUSTOM") {
			this.showCustomPeriod(true);
		} else {
			this.showCustomPeriod(false);
		}
				
		this.updateWhenItemChange(newValue);
				
		this.autoUpdateData(newValue);
		
		autoUpdate = false;
	},
	
	autoUpdateData:function(newValue){				
		var inter=this._inter;
		clearInterval(inter);	
		objTmp=this;			
		this._inter=setInterval(
			function(){		
				if(_isChange){
					objTmp.updateWhenItemChange(newValue);	
					_isChange = false;
				}				 	
			}
		,5000,objTmp,newValue);
		
	},		
	
	updateWhenItemChange:function(newValue){
		
		if(newValue=="CUSTOM"){			
			this.getSurveyForCustom();	
		}else{
				if (!isc.isA.Array(this.analytic.questions)) {
				WebClientSvc.getSurveyAnalyticsByPeriod(this.analytic.questions.id, sId, orgId, newValue,null, null,
														this.callback("updateChart"), this.callback("error"));		
			} else {
				var perfId = this.analytic.questions[0].id; 
				
				WebClientSvc.getSurveyAnalyticsByPeriod(perfId, sId, orgId, newValue,null,null,
														this.callback("updateChartPerformance"), this.callback("error"));
				
				var impId = this.analytic.questions[1].id;
				
				WebClientSvc.getSurveyAnalyticsByPeriod(impId, sId, orgId, newValue,null,null,
														this.callback("updateChartImportance"), this.callback("error"));
			}	
		}
			
	},
	
	updateChart:function( tally ) {
		_globalTally = tally;
		tally.ytarget = this.ytarget;
		var period = this.getValue("chartPeriod");
		
		this.trendChart.updateView(tally);
		
	},
	
	updateChartPerformance:function ( tally ) {
		_globalTally = tally;
		tally.ytarget = this.ytarget;
		this.trendChartPerformance.updateView(tally);
	},
	
	updateChartImportance:function( tally ) {
		_globalTallySecond = tally;
		tally.ytarget = this.ytargetSecond;
		this.trendChartImportance.updateView(tally);
	},
	
	callback: function (methodName)
        { return {target:this, methodName:methodName}; },
		
	error: function (code, msg) {
        switch ( msg ) {
            default:
                OPINIATOR.warn(msg);
                break;
		}
	},
	
	showCustomPeriod:function( flag ) {
		if (flag) {
			PeriodStartTimeID.show();
			PeriodStartTimePickerID.setDateTime(null);
			PeriodEndTimeID.show();
			PeriodEndTimePickerID.setDateTime(null);
			PeriodToolBarRecipientID.show();
		} else {
			PeriodStartTimeID.hide();
			PeriodEndTimeID.hide();
			PeriodToolBarRecipientID.hide();
		}
		
	},
	
	getSurveyForCustom: function() {	
	
		var startTime=PeriodStartTimePickerID.getDateTime();
		var endTime=PeriodEndTimePickerID.getDateTime();		
		var d1=new Date(startTime.getFullYear(),startTime.getMonth(),startTime.getDate());
		var d2=new Date(endTime.getFullYear(),endTime.getMonth(),endTime.getDate());	
		if (d1 > d2) {
			OPINIATOR.warn("Please input Start date < End date");			
		}
		else {	
		
			if (!isc.isA.Array(this.analytic.questions)) {
				WebClientSvc.getSurveyAnalyticsByPeriod(this.analytic.questions.id, sId, orgId, "CUSTOM", PeriodStartTimePickerID.getDateTime(), PeriodEndTimePickerID.getDateTime(), this.callback("updateChart"), this.callback("error"));
			}
			else {
				var perfId = this.analytic.questions[0].id;
				
				WebClientSvc.getSurveyAnalyticsByPeriod(perfId, sId, orgId, "CUSTOM", PeriodStartTimePickerID.getDateTime(), PeriodEndTimePickerID.getDateTime(), this.callback("updateChartPerformance"), this.callback("error"));
				
				var impId = this.analytic.questions[1].id;
				
				WebClientSvc.getSurveyAnalyticsByPeriod(impId, sId, orgId, "CUSTOM", PeriodStartTimePickerID.getDateTime(), PeriodEndTimePickerID.getDateTime(), this.callback("updateChartImportance"), this.callback("error"));
			}
		}
	}
	
  
});
