BemsWebApplication.BoilerAnalysis = function(params, viewInfo) {
    "use strict";

    var initialized = false,
        shouldReload = false,
        datagrid = null,
        currentTabIndex = ko.observable(0),
        facilityViewModel = new BWA.CmFacilityViewModel(),
        dataSource;

    var m_Facility;

    var multiViewItems = [{
            template: 'mainCharts'
        }, {
            template: 'subCharts'
        }
    ];
    
    var facilityDataSource = BWA.db.createDataSource('CmFacility'),
        facilitiesForSearch = ko.observableArray(),

        facilityCodeForSearch = ko.observable(0),

        deferredForSearch = new $.Deferred();

    var  visiblePopup = ko.observable(false);

    var dataCalorie = ko.observableArray(),
        dataAtfw = ko.observableArray(),
        dataTemperatureCalorie = ko.observableArray(),
        dataTemperatureElectricity = ko.observableArray()
    ;

    var formulaGet = new BWA.Chart.FormulaGet(BWA.UserInfo.SiteId());

    //var timeBoxForSearch = BWA.SearchView.createDateTimeBox();
    // cyim 2016.08.22 : 성능분석 그래프의 경우 시간 데이타만 표시되어야 한다
    var timeBoxForSearch = BWA.SearchView.createDateTimeBox($G.TimeTypesForHourOnly, null, false);

    var chartEffi = BWA.Chart.Instance('chartEffiBO', 'dxChart'),
        chartAtfw = BWA.Chart.Instance('chartAtfwBO', 'dxChart'),
        chartCOP = BWA.Chart.Instance('chartCOPBO', 'dxChart'),
        chartFIRE = BWA.Chart.Instance('chartFIREBO', 'dxChart');

    var chartLayout = new BWA.ChartLayout({
        divs: [[{
            id: 'boilerDetail'
            }, {
                id: 'effi',
                chartId: 'chartEffiBO'
            }, {
                id: 'atfw',
                chartId: 'chartAtfwBO'
            }, {
                id: 'COP',
                chartId: 'chartCOPBO'
            }, {
                id: 'FIRE',
                chartId: 'chartFIREBO'
            }
        ]],
        multiViewOptions: {
            viewIndex: currentTabIndex,
            viewCount: 1
        }
    });

    var m = moment();
    dataCalorie([
        { DateTime: new Date(m.year(), m.month(), 1), Value: 50 },
        { DateTime: new Date(m.year(), m.month(), 2), Value: 50 },
        { DateTime: new Date(m.year(), m.month(), 3), Value: 60 },
        { DateTime: new Date(m.year(), m.month(), 4), Value: 80 },
        { DateTime: new Date(m.year(), m.month(), 5), Value: 100 },
        { DateTime: new Date(m.year(), m.month(), 6), Value: 40, },
        { DateTime: new Date(m.year(), m.month(), 7), Value: 120 },
        { DateTime: new Date(m.year(), m.month(), 31), Value: 120 }
    ]);

    // 추가 2015 04 20 hcLee ->
    var CODE = $Code,
    FuelType = CODE.FuelType,
    FT = CODE.FacilityType,
    FC = CODE.FacilityCode,
    F = CODE.Formula,
    TIT = CODE.TimeIntervalType;
    // 추가 2015 04 20 hcLee  <-

    //dataMonthForBar(dataDayForBar());

    //dataDayForPie([
    //    { FuelTypeName: '전기', Value: 320 },
    //    { FuelTypeName: '가스', Value: 350 },
    //    { FuelTypeName: '수도', Value: 360 },
    //]);
    //dataMonthForPie(dataDayForPie());

    function handleViewShown() {

        if (initialized === false) {

            var chartOption = BWA.ChartOptions.BoilerAnalysis;

            chartEffi = chartEffi(chartOption.getChartEffiOptions($Code.TimeType.HOUR));
            //chartAtfw = chartAtfw(chartOption.getChartAtfwOptions($Code.TimeType.HOUR));
            chartAtfw = chartAtfw(chartOption.getChart_2_Options($Code.TimeType.HOUR));
            //chartCOP = chartCOP(chartOption.getChartCOPOptions($Code.TimeType.HOUR));
            chartCOP = chartCOP(chartOption.getChart_3_Options($Code.TimeType.HOUR));
            //chartFIRE = chartFIRE(chartOption.getChartFIREOptions($Code.TimeType.HOUR));
            chartFIRE = chartFIRE(chartOption.getChart_4_Options($Code.TimeType.HOUR));

            initialized = true;
        }

        //hcLee 2016 07 12
        timeBoxForSearch.setDefaultDate();

        var eq = BWA.DataUtil.constructEqualFilter;
        facilityDataSource.filter([
            eq('SiteId', BWA.UserInfo.SiteId()),
            'and',
            eq('FacilityTypeId', $Code.FacilityType.BOILER),
            //'or',
            //eq('FacilityTypeId', 8),
        ]);
        facilityDataSource.load().done(function(facilities) {
            facilitiesForSearch(facilities);
            if (_.isEmpty(facilities) === false) {
                var f = facilities[0];
                handleSelectedFacilityInSearchView(f);
                handleSearchInSearchView();

                var datagrid = $('#boilerDataGridViewInSearchView').dxDataGrid('instance');
                if (_.has(datagrid, 'selectRows')) {
                    datagrid.selectRows(f);
                }
            }
        });
    }

    if (shouldReload) {
            //shouldReload = false;
            //dataSource.pageIndex(0);
            //dataSource.load();
    }

    function handleViewHidden() {
        //hideOverlay();
        //    var dataGrid = $('#gridContainer').dxDataGrid('instance');
        //    dataGrid.clearSelection();
        var paging = BWA.ChartLayout.Paging;
        paging.sideOverlayVisible(false);
        //paging.hideNextButton(true);
        //paging.hidePrevButton(true);
        $SearchView.visibleObservable(false); // hcLee 2015 03 23
        visiblePopup(false);

    }

    function handleViewShowing() {
    }

    function refreshList() {
        //dataSource.pageIndex(0);
        //dataSource.load();
    }

    var searchViewOptions = {
        searchViewItems: [
            { id: 'FacilityCode', ignoreValue: 0, defaultValue: 0, value: facilityCodeForSearch, dataSource: facilitiesForSearch },
        ],
        promiseDataInSearchView: deferredForSearch.promise()
    };

    function handleSelectedFacilityInSearchView(facility) {
        m_Facility = facility;
        return;
    }

    function handleSearchInSearchView(filter, searchViewItems) {
        //console.log(filter);
        //console.log(searchViewItems);
        if (m_Facility == null) return;

        visiblePopup(true);

        var f = m_Facility.toJS();
        facilityViewModel.fromJS(f);

        //var timeIntervalType = $Code.TimeIntervalType.QUARTERMIN;
        var timeIntervalType = timeBoxForSearch.type();

        var formula = $Code.Formula[$Code.FacilityType.BOILER];
        var formulaIds = _.values(formula);

        var date = timeBoxForSearch.getDate();

        //utils.toast.displayTime=1000000;
        //utils.toast.show('공조기 성능분석 중 입니다. 잠시만 기다려 주세요');
        /*
        timeBoxForSearch.type($Code.TimeIntervalType.DAY);
        timeIntervalType = $Code.TimeIntervalType.DAY;
        date.startDate = new Date(2015, 0, 1);
        date.endDate = new Date(2015, 11, 31);*/

        //        var startDate = moment().
        var promises = [];
        _.each(formulaIds, function (formulaId) {
            var p = formulaGet.apiGet({
                FacilityTypeId: f.FacilityTypeId,
                FacilityCode: f.FacilityCode,
                FormulaId: formulaId,

                TimeIntervalType: timeIntervalType,
                StartDate: date.startDate,
                EndDate: date.endDate

            });
            promises.push(p);
        });

    // 외기 온도와 습도를 위해 추가 hcLee 2015 04 20  ->
        var commonParameters = {
            TimeIntervalType: timeIntervalType,
            StartDate: date.startDate,
            EndDate: date.endDate
        };
        var temperatureParameters = {
            FacilityTypeId: FT.OUTDOOR,
            FacilityCode: FC.OUTDOOR,
            FormulaId: F[FT.OUTDOOR].TEMPERATURE,
        };
        var humidityParameters = _.extend({}, temperatureParameters, {
            FormulaId: F[FT.OUTDOOR].HUMIDITY,
        });

        promises.push(formulaGet.apiGet(_.extend(temperatureParameters, commonParameters)));
        promises.push(formulaGet.apiGet(_.extend(humidityParameters, commonParameters)));

        $.when.apply(this, promises)
        .done(function (kcal, fueluse, effi, fo2, eo2, airfact, elecuse, fire, COP,
            //2016 03 05 추가
            syseffi, load, pump_kw, pump_hz,
            OUTTemp, OutHumi) {

            kcal = kcal[0];
            fueluse = fueluse[0];
            effi = effi[0];
            fo2 = fo2[0];
            eo2 = eo2[0];
            airfact = airfact[0];
            elecuse = elecuse[0];
            fire = fire[0];
            COP = COP[0];

            // chart 1
            var EffiDataArray = [];
/*            _.each(kcal, function (x) { // 보일러능력
                EffiDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    kcal: x.Value
                });
            });  2016 03 07 다시 제외 */
            _.each(fueluse, function (x) { //보일러연료사용량
                EffiDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    m3: x.Value
                });
            });
            _.each(effi, function (x) { //보일러효율
                EffiDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    effi: x.Value
                });
            });
            _.each(syseffi[0], function (x) {// 시스템효율
                EffiDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    syseffi: x.Value
                });
            });
            _.each(elecuse, function (x) { // 보일러소비전력
                EffiDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    elecuse: x.Value
                });
            });
            _.each(pump_kw[0], function (x) { // 펌프소비전력
                EffiDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    pump_kw: x.Value
                });
            });

            var options = BWA.ChartOptions.BoilerAnalysis.getChartEffiOptions(timeBoxForSearch.type());
            options.dataSource = EffiDataArray;
            chartEffi().option(options);

            //chart2
            /*
            var AirDataArray = [];
            _.each(airfact, function (x) {
                AirDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    airfact: x.Value
                });
            });
            _.each(fo2, function (x) {
                AirDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    fo2: x.Value
                });
            });
            _.each(eo2, function (x) {
                AirDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    eo2: x.Value
                });
            }); 

            options = BWA.ChartOptions.BoilerAnalysis.getChartAtfwOptions(timeBoxForSearch.type());
            options.dataSource = AirDataArray;
            chartAtfw().option(options);*/

            var dataArray = BWA.Chart.getRelationDataArrayOnDateTime(effi, load[0], 'effi', 'load');
            options = BWA.ChartOptions.BoilerAnalysis.getChart_2_Options(timeBoxForSearch.type());
            options.dataSource = dataArray;
            chartAtfw().option(options);


            //chart3
            var COPDataArray = [];
            /*
            _.each(COP, function (x) {
                COPDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    COP: x.Value
                });
            });
            _.each(elecuse, function (x) {
                COPDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    elecuse: x.Value
                });
            });
            _.each(fueluse, function (x) {
                COPDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    m3: x.Value
                });
            });

            //chartCOP().option('dataSource', COPDataArray);
            options = BWA.ChartOptions.BoilerAnalysis.getChartCOPOptions(timeBoxForSearch.type());
            //chartCOP().option('argumentAxis', null); // 2015 05 21 결국 이 코드가 필요 함 (시간 축 에러 해결)
            options.dataSource = COPDataArray;
            chartCOP().option(options); */
            _.each(pump_kw[0], function (x) {
                COPDataArray.push({
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    pump_kw: x.Value
                });
            });
            _.each(pump_hz[0], function (x) {
                COPDataArray.push({
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    pump_hz: x.Value
                });
            });

            options = BWA.ChartOptions.BoilerAnalysis.getChart_3_Options(timeBoxForSearch.type());
            options.dataSource = COPDataArray;
            chartCOP().option(options);

            //chart4
            var FIREDataArray = [];/*
            _.each(fire, function (x) {
                FIREDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    fire: x.Value
                });
            });
            _.each(elecuse, function (x) {
                FIREDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    elecuse: x.Value
                });
            });
            _.each(fueluse, function (x) {
                FIREDataArray.push({
                    //DateTime: moment(x.DateTime).toDate(),
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
                    m3: x.Value
                });
            });

            //chartFIRE().option('dataSource', FIREDataArray);
            options = BWA.ChartOptions.BoilerAnalysis.getChartFIREOptions(timeBoxForSearch.type());
            //chartFIRE().option('argumentAxis', null); // 2015 05 21 결국 이 코드가 필요 함 (시간 축 에러 해결)
            options.dataSource = FIREDataArray;
            chartFIRE().option(options);
*/
            var maxValuecops = 0;
            _.each(load[0], function (x) {
                if (maxValuecops < x.Value) maxValuecops = x.Value;
            });

            FIREDataArray = BWA.Chart.mapNewWithConvertingDateTime(load[0], timeBoxForSearch.type());

            //_.each(OUTTemp[0], function (x) {
            //    FIREDataArray.push({
            //        DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
            //        Temperature: x.Value
            //    });
            //});

            //_.each(OutHumi[0], function (x) {
            //    FIREDataArray.push({
            //        DateTime: BWA.Chart.getCustermTimeArgumentAxisString(timeBoxForSearch.type(), moment(x.DateTime).toDate()),
            //        Humidity: x.Value
            //    });
            //});

            options = BWA.ChartOptions.BoilerAnalysis.getChart_4_Options(timeBoxForSearch.type());
            //options.valueAxis[0].tickInterval = Math.round(maxValuecops / 5) + 1;
            options.dataSource = FIREDataArray;
            chartFIRE().option(options);

            visiblePopup(false);
            /*            msgbox.
                        $("#large-indicator").dxLoadIndicator({
                            height: 60,
                            width: 60
                        });*/

            //chartTemperatureCalorie().option('dataSource', calories.concat(OUTtemperatures));
            //chartTemperatureElectricity2().option('dataSource', electricityDataArray.concat(OUTtemperatures));
        })
        .fail(function (error) {
            //alert(error);
            visiblePopup(false);
        });
    }


    var viewModel = $.extend(BWA.CommonView.create(
            params, viewInfo, searchViewOptions, ko.observable(null),
            handleViewShown, null, handleSearchInSearchView, undefined,
            chartLayout), {

//        facility: facilityViewModel,
        refreshList: refreshList,
        viewShowing: handleViewShowing,
        viewHidden: handleViewHidden, // hcLee 2015 06 19
        scrolling: { mode: 'infinite' },
        boilerDataGridOptions: {
            dataSource: facilitiesForSearch,
            columns: [
                { dataField: 'Name', caption: $G('facilityName'), width: '100%', alignment: 'left' }
            ],
            filterRow: {
                visible: true,
                showOperationChooser: false
            },
            selection: {
                mode: 'single'
            },
            rowClick: function(clickRow) {
                handleSelectedFacilityInSearchView(clickRow.data);
            }
        },
        contentReadyAction: function(e) {
            datagrid = e.component;
        }
    });

    viewModel.timeBoxForSearch = timeBoxForSearch;
    viewModel.currentTabIndex = currentTabIndex;
    viewModel.multiViewItems = [{
            facility: facilityViewModel,
            template: 'mainCharts'
        }, {
            template: 'subCharts'
        }
    ];

    $HourGlassPopup(viewModel, visiblePopup);
    return viewModel;
};