/**
 * @class KPIPane   Views the all KPI's in a spreadsheet format
 * 
 * @author ktyra (11/3/2008)
 */
 
isc.defineClass("OPINIATOR_KPIPane", isc.ListGrid);
OPINIATOR_KPIPane.addClassProperties({
		
    /**
     * Take the difference of the two tallies
     */
    diffTally: function ( t1, t2)
        {
        var diff = {
            value: OPINIATOR_KPIPane.diffValue(t1.value,  t2.value),
            ytd: OPINIATOR_KPIPane.diffValue(t1.ytd, t2.ytd), 
            mtarget: Math.abs(OPINIATOR_KPIPane.diffValue(t1.mtarget, t2.mtarget)), 
            ytarget: Math.abs(OPINIATOR_KPIPane.diffValue(t1.ytarget, t2.ytarget)),
            prev: {
                value: OPINIATOR_KPIPane.diffValue(t1.prev.value, t2.prev.value), 
                ytd: OPINIATOR_KPIPane.diffValue(t1.prev.ytd, t2.prev.ytd)
                },
            lastyear: 
                {
                value: OPINIATOR_KPIPane.diffValue(t1.lastyear.value, t2.lastyear.value), 
                ytd: OPINIATOR_KPIPane.diffValue(t1.lastyear.ytd, t2.lastyear.ytd)
                }
            };
        return diff;
        },

    /**
     * Return a tally that has its targets set as a percentage of 
     * another tallies targets 
     *
     * t1 - Contains Values and Targets which are a percentage 
     * t2 - Contains The targets to take a percentage of
     */
    percentOfTarget: function ( t1, t2)
        {
        var diff = {
            value: t1.value,
            ytd: t1.ytd,
            mtarget: OPINIATOR_KPIPane.percentOf(t2.mtarget, t1.mtarget), 
            ytarget: OPINIATOR_KPIPane.percentOf(t2.ytarget, t1.ytarget), 
            prev: {
                value: t1.prev.value,
                ytd: t1.prev.ytd
                },
            lastyear: 
                {
                value: t1.lastyear.value,
                ytd: t1.lastyear.ytd
                }
            };
        return diff;
        },

    diffValue: function ( v1, v2)
        {
        // Ensure the values are numbers
        v1 = new Number(v1);
        v2 = new Number(v2);
        return ( v1 == -1 ) ? (-1) : (v1 - v2);
        },


    percentOf: function ( v, p)
        {
        // Ensure the values are numbers
        v = new Number(v);
        p = new Number(p);
        return new Number(new Number(v*p/100).toFixed(0));
        },

    addTitleRecord: function ( records, title, styleProp )
        {
        var rec = { tally:null, title: "<font color='#DE107C'>"+title+"</font>" };
        //var rec = { tally:null, title: "<font color='#FFFFFF'>"+title+"</font>" };
        //var rec = { tally:null, title: "<font color='#002AFF'>"+title+"</font>" };
        rec[styleProp] = "kpiPaneRowSeparator";
        records.add(rec);
        },

    addTallyRecord: function( records, title, tally )
        {
        if ( isc.isAn.Object(tally) )
            { records.add({ tally:tally, title:title }); }
        },
    addSurveyTypeRecord: function( records, title, tally, countMonthTotal, countYearTotal, countLastYearTotal, countLastMonthOfYearTotal )
        {
        if ( isc.isAn.Object(tally) )
            { records.add({ tally:null, title:title, surveyTypeMonth:tally.surveyTypeMonth, surveyTypeYear:tally.surveyTypeYear 
			, countMonthTotal:countMonthTotal, countYearTotal:countYearTotal
			, surveyTypeLastYear:tally.surveyTypeLastYear, countLastYearTotal:countLastYearTotal
			, surveyTypeLastMonthOfYear:tally.surveyTypeLastMonthOfYear, countLastMonthOfYearTotal:countLastMonthOfYearTotal}); }
        },

    formatVariance: function(value, against, reverse)
        {
        value = new Number(value);
        against = new Number(against);

        if ( value == (-1) || against == (-1) )
            { return "--"; }
        
        var pv;
        if ( against == 0 )
            { pv = 100.0; }
        else
            { 
            if ( reverse == undefined )
                { pv = ((value-against)/against * 100); }
            else
                { pv = ((against-value)/against * 100); }
            }

        if ( pv <= -20.0 )
            { return "<font color='#FF0000'>"+OPINIATOR_KPIPane.formatValue(pv)+"</font>"; }
        else if ( pv <= -10.0 )
            { return "<font color='#FFFF00'>"+OPINIATOR_KPIPane.formatValue(pv)+"</font>"; }
        else if ( pv >= 20.0 )
            { return "<font color='#00FF00'>"+OPINIATOR_KPIPane.formatValue(pv)+"</font>"; }
        else if ( pv >= 10.0 )
            { return "<font color='#FFFF00'>"+OPINIATOR_KPIPane.formatValue(pv)+"</font>"; }

        return OPINIATOR_KPIPane.formatValue(pv);
        },

   formatKPI: function( value, kpi)
        {
        if ( value < 0 )
            { return OPINIATOR_KPIPane.formatValue(value); }
        else if ( value < kpi.MaxPoor )
            { return "<font color='#C61010'>"+OPINIATOR_KPIPane.formatValue(value)+"</font>"; }
        else if ( value < kpi.MaxOK )
            { return "<font color='#FDBF0B'>"+OPINIATOR_KPIPane.formatValue(value)+"</font>"; }
        return OPINIATOR_KPIPane.formatValue(value);
        },

    formatValue: function( value )
        {
        value = new Number(value);
        if ( value == (-1) )
            { return "--"; }
        return value.toFixed(1);
        },

    findTallyOfType: function( acats, type  )
        {
        var acat = acats.find("type", type);
        if ( isc.isAn.Object(acat) )
            { return acat.tally; }
        return null;
        }

    });

OPINIATOR_KPIPane.addProperties({
    // Super class Properties
    data:null,
    canPickFields:false,
    canResizeFields:true,
    canFreezeFields:false,
    canReorderFields:false,
    canGroupBy:false,
    canSort:false,
    canEdit:false,
    leaveScrollbarGap:false,
    showAllRecords:false,
    showHeader:true,
    showHeaderContext:true,
    alternateRecordStyles:false,
    border:"1px solid #000000",
    headerBaseStyle:"kpiPaneHeader",
    baseStyle:"kpiPaneCell",
    styleName:"kpiPaneBody",
    bodyStyleName:"kpiPaneBody",
    bodyBackgroundColor:null,
	
    // Private Properties
    _poorColor:"#C61010",
    _fairColor:"#FDBF0B",

    // Field Definitions for Tally objects
    fields: [ 
        { 
        name:"mVarFromLastYear", title:"% Var", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
			if(tally == null) return "--";
            if (isc.isAn.Object(tally) )
                { 
					if (isc.isAn.String(tally.subname)) {
						return "--";
					} else {
						return OPINIATOR_KPIPane.formatVariance(tally.lastyear.value, tally.value);	
					}
                }
            return " ";
            }
        },
        {
        name:"mLastYear", title:"Last Year", align:"center", cellAlign:"center",
        formatCellValue: 
        	function (value, record, rowNum, colNum, grid) {
	            var tally = record.tally;
	            if (isc.isAn.Object(tally) ) {
					if (isc.isAn.String(tally.subname)) {
						var label = tally.subname.split("::")[2];
						if (label != 'nodata') {
							return tally.subname.split("::")[2] + " - " + OPINIATOR_KPIPane.formatValue(tally.lastyear.value*100) + "%";	
						}
					}
					return OPINIATOR_KPIPane.formatValue(tally.lastyear.value);
				} else if(tally == null) {
					if (record.surveyTypeLastMonthOfYear != null && record.countLastMonthOfYearTotal != null && record.countLastMonthOfYearTotal != 0) {
						var lastMonthOfYearPercent = record.surveyTypeLastMonthOfYear/record.countLastMonthOfYearTotal;
						return OPINIATOR_KPIPane.formatValue(lastMonthOfYearPercent*100);
					}else{
						return "--";
					}
				}
	            return " ";	
        	}
        },
        {
        name:"mVarFromTarget", title:"% Var", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
			if(tally == null) return "--";
            if (isc.isAn.Object(tally) )
                {
                return OPINIATOR_KPIPane.formatVariance(tally.value, tally.mtarget, tally.reverseVar);
                }
            return " ";
            }
        },
        {
        name:"cTarget", title:"Target", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
			if(tally == null) return "--";
            if (isc.isAn.Object(tally) )
                { return OPINIATOR_KPIPane.formatValue(tally.mtarget); }
            return " ";
            }
        },
        {
        name:"mValue", title:"Month", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
            if (tally != null && isc.isAn.Object(tally) )
                {
					if (isc.isAn.String(tally.subname)) {
						var label = tally.subname.split("::")[0];
						if (label != 'nodata') {
							return tally.subname.split("::")[0] + " - " + OPINIATOR_KPIPane.formatValue(tally.value*100) + "%";	
						}
					} 
					return OPINIATOR_KPIPane.formatValue(tally.value);
				}
			else if(tally == null) {
				if (record.surveyTypeMonth != null && record.countMonthTotal != null && record.countMonthTotal != 0) {
					var monthPercent = record.surveyTypeMonth/record.countMonthTotal;
					return OPINIATOR_KPIPane.formatValue(monthPercent*100);
				}else{
					return "--";
				}
			}
            return " ";
            }
        },
        {
        name:"rtitle", title:"<font color='#DE107C'>Surveys</font>", align:"center", cellAlign:"center", width:"140",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var title = record.title;
            if (isc.isAn.String(title) )
                { return title; }
            return " ";
            }
        },
        {
        name:"ytdValue", title:"Year", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
            if (tally != null && isc.isAn.Object(tally) )
                {
					if (isc.isAn.String(tally.subname)) {
						var label = tally.subname.split("::")[1];
						if (label != 'nodata') {
							return tally.subname.split("::")[1] + " - " + OPINIATOR_KPIPane.formatValue(tally.ytd*100) + "%";	
						}
					}  
					return OPINIATOR_KPIPane.formatValue(tally.ytd);
				}
			else if(tally == null) {
				if (record.surveyTypeYear != null && record.countYearTotal != null && record.countYearTotal != 0) {
					var yearPercent = record.surveyTypeYear/record.countYearTotal;
					return OPINIATOR_KPIPane.formatValue(yearPercent*100);
				}else{
					return "--";
				}
			}
			return " ";
            }
        },
        {
        name:"yTarget", title:"Target", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
			if(tally == null) return "--";
            if (isc.isAn.Object(tally) )
                { return OPINIATOR_KPIPane.formatValue(tally.ytarget); }
            return " ";
            }
        },
        {
        name:"ytdVarFromTarget", title:"% Var", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
			if(tally == null) return "--";
            if (isc.isAn.Object(tally) )
                {
                return OPINIATOR_KPIPane.formatVariance(tally.ytd, tally.ytarget, tally.reverseVar);
                }
            return " ";
            }
        },
        {
        name:"ytdLastYear", title:"Last Year", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
            if (tally != null && isc.isAn.Object(tally) )
            {
				if (isc.isAn.String(tally.subname)) {
					var label = tally.subname.split("::")[3];
					if (label != 'nodata') {
						return tally.subname.split("::")[3] + " - " + OPINIATOR_KPIPane.formatValue(tally.lastyear.ytd*100) + "%";
					}
				}
				return OPINIATOR_KPIPane.formatValue(tally.lastyear.ytd);
			}
			else if(tally == null) {
				if (record.surveyTypeLastYear != null && record.countLastYearTotal != null && record.countLastYearTotal != 0) {
					var lastYearPercent = record.surveyTypeLastYear/record.countLastYearTotal;
					return OPINIATOR_KPIPane.formatValue(lastYearPercent*100);
				}else{
					return "--";
				}
			}
            return " ";
            }
        },
        {
        name:"yVarFromLastYear", title:"% Var", align:"center", cellAlign:"center",
        formatCellValue: function (value, record, rowNum, colNum, grid)
            {
            var tally = record.tally;
			if(tally == null) return "--";
            if (isc.isAn.Object(tally) )
                { return OPINIATOR_KPIPane.formatVariance(tally.ytd, tally.lastyear.ytd); }
            return " ";
            }
        }
        ],

    initWidget: function () 
        { this.Super("initWidget", arguments); },

    destroy: function()
        {
        this.setData(null);
        this.Super("destroy", arguments);
        },
	
	exportData: function() {			  
	      var url = exportURL + '?&kpi=1';		  		  	    
	      var params = {			
			_exportFields: null
	      };
	      
		 var allFields = this.getAllFields();
		 var visibleFields = [];
		 for(var i = 0; i < allFields.getLength(); i++) {
			var field = allFields.get(i);
			if(this.fieldIsVisible(field)) {					
				var title = field.title;
				if (title.indexOf("Survey") > 0) {
					title = "Survey";
				}
			    visibleFields.push(title);
			}
		}
		params._exportFields = visibleFields.join(',');
	     	

	    for(var key in params) { 
			url = url + '&' + encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
		}
		  
		return url;
	},
		
    setAnalytics: function ( analytics )
        {
		var type = analytics.type;	
		
        if ( !isc.isAn.Object(analytics) )
            {
            this.setData(null);
            return;
            }

        var records = [];
        var acats  = analytics.list;
		
		var sms = acats.find("surveyType", "SMS");
		var mobi = acats.find("surveyType", "MOBI");
		var web_survey = acats.find("surveyType", "WEB_SURVEY");
		var voice = acats.find("surveyType", "VOICE");		
		var countMonthTotal = 0;
		countMonthTotal = sms.surveyTypeMonth + mobi.surveyTypeMonth + web_survey.surveyTypeMonth + voice.surveyTypeMonth;
		var countYearTotal = 0;
		countYearTotal = sms.surveyTypeYear + mobi.surveyTypeYear + web_survey.surveyTypeYear + voice.surveyTypeYear;
		var countLastYearTotal = 0;
		countLastYearTotal = sms.surveyTypeLastYear + mobi.surveyTypeLastYear + web_survey.surveyTypeLastYear + voice.surveyTypeLastYear;
		var countLastMonthOfYearTotal = 0;
		countLastMonthOfYearTotal = sms.surveyTypeLastMonthOfYear + mobi.surveyTypeLastMonthOfYear + web_survey.surveyTypeLastMonthOfYear + voice.surveyTypeLastMonthOfYear;
        var welcome = acats.find("type", "WELCOME");
        var taken = welcome.tallies[0];
        var phones = welcome.tallies[1];
        // The Targets are a percentage of the Total
        var completed = OPINIATOR_KPIPane.findTallyOfType(acats, "THANKYOU");
        completed = OPINIATOR_KPIPane.percentOfTarget(completed, taken);
        var partial = OPINIATOR_KPIPane.diffTally(taken, completed);
        partial.reverseVar = true;

        //  Survey Talles (no hanging chads :-))
        OPINIATOR_KPIPane.addTallyRecord(records, "Total", taken);
        OPINIATOR_KPIPane.addTallyRecord(records, "Completed", completed);
        OPINIATOR_KPIPane.addTallyRecord(records, "Partial", partial);

        //  Net Promoter Scores
        OPINIATOR_KPIPane.addTitleRecord(records, "Overall", this.recordBaseStyleProperty);
        OPINIATOR_KPIPane.addTallyRecord(records, "Net Promoter", OPINIATOR_KPIPane.findTallyOfType(acats, "NETPROMOTER"));

        //  Consumer Results
        OPINIATOR_KPIPane.addTitleRecord(records, "Consumer Data", this.recordBaseStyleProperty);
        OPINIATOR_KPIPane.addTallyRecord(records, "Mobile No's", phones);
		
        OPINIATOR_KPIPane.addTallyRecord(records, "ZipCodes", OPINIATOR_KPIPane.findTallyOfType(acats, "ZIPCODE"));

		OPINIATOR_KPIPane.addSurveyTypeRecord(records, "SMS", sms, countMonthTotal, countYearTotal, countLastYearTotal, countLastMonthOfYearTotal);
		OPINIATOR_KPIPane.addSurveyTypeRecord(records, "Mobi", mobi, countMonthTotal, countYearTotal, countLastYearTotal, countLastMonthOfYearTotal);
		OPINIATOR_KPIPane.addSurveyTypeRecord(records, "Web Survey", web_survey, countMonthTotal, countYearTotal, countLastYearTotal, countLastMonthOfYearTotal);
		OPINIATOR_KPIPane.addSurveyTypeRecord(records, "Voice", voice, countMonthTotal, countYearTotal, countLastYearTotal, countLastMonthOfYearTotal);

        /*var pcats = acats.findAll("type", "PERFORMANCE");
        var ncats = acats.findAll("type", "NUMERIC");
		var ccats = acats.findAll("type", "CHOICE");*/
		
		var pcats = [];
		
		for (var i = 0 ; i < acats.length; i++) {
			if (acats[i].type == "PERFORMANCE" || acats[i].type == "NUMERIC" || acats[i].type == "CHOICE") { 
				pcats.add(acats[i]);
			}
		}

        /*if ( !isc.isAn.Array(pcats) )
            { pcats = []; }

        if ( isc.isAn.Array(ncats) )
            { pcats.addList(ncats); }

		if ( isc.isAn.Array(ccats)) {
			pcats.addList(ccats);
		}*/

		if (type == "ORG") {
			pcats.sortByProperty("name", true);
		}

        if ( isc.isAn.Array(pcats) )
            {
            // Importance
            var addtitle = true;
            var len = pcats.getLength();
            for ( var i = 0; i < len; i++ )
                { 
                if ( pcats[i].type == "PERFORMANCE" )
                    { 
	                //  Add the title if we found a performance type
                    if ( addtitle )
                        {
                        OPINIATOR_KPIPane.addTitleRecord(records, "What's Important", this.recordBaseStyleProperty);
                        addtitle = false;
                        }
                    OPINIATOR_KPIPane.addTallyRecord(records, pcats[i].name, pcats[i].tallies[1]); 
                    }
                }

            OPINIATOR_KPIPane.addTitleRecord(records, "How We Did", this.recordBaseStyleProperty);
            for ( i = 0; i < len; i++ )
                { 
                if ( pcats[i].type == "PERFORMANCE" )
                    { OPINIATOR_KPIPane.addTallyRecord(records, pcats[i].name, pcats[i].tallies[0]); }
                else
                    { OPINIATOR_KPIPane.addTallyRecord(records, pcats[i].name, pcats[i].tally); }
                }

            }

        this.setData(records);
       }

    });
	
	
isc.defineClass("OPINIATOR_KPIPeriod", isc.DynamicForm);
OPINIATOR_KPIPeriod.addProperties({
	
	// private properties
	_parentPane: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: { 
		            "CAL_YEAR": "Calendar Year",
					"LAST_12_MONTH": "Rolling Year"
		            }, 
				defaultValue: "CAL_YEAR",
		        width:120,
		        height:25
        	}
        ],

    initWidget : function () 
        { 
			this.Super("initWidget", arguments);
		},

    destroy: function()
        { this.Super("destroy", arguments); },
	
	itemChange: function (item, newValue, oldValue) {
		if (sId != null) {
			WebClientSvc.getKPIAnalytics(sId, orgId, newValue, this.callback("changeKPI"), this.callback("error"));	
		} else {
			WebClientSvc.getKPIAnalytics(sId, orgId, newValue, this.callback("changeKPI"), this.callback("error"));
		}	
		periodKPI = newValue;
	},
	
	changeKPI:function( analytics) {
		var records = this._parentPane.data;
		records.removeList(records);
		this._parentPane.setAnalytics(analytics);
	},
	
	callback: function (methodName)
        { return {target:this, methodName:methodName}; },
		
	error: function (code, msg) {
        switch ( msg ) {
            default:
                OPINIATOR.warn(msg);
                break;
		}
	}
	
});
