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

    var BUILDING_DEPTH = 1,
        FLOOR_DEPTH = 2,
        ZONE_DEPTH = 3;

    var CODE = $Code;

    var visiblePopup = ko.observable(false);

    //var timer;

    var initialized = false,
        dataSource;

    var buildingDataSource = BemsWebApplication.db.createDataSource('CmBuilding', [('SiteId', '=', BWA.UserInfo.SiteId())]),
        floorDataSource = BemsWebApplication.db.createDataSource('CmFloor'),

        buildings = ko.observableArray(),
        floorsForSearch = ko.observableArray(),

        buildingIdForSearch = ko.observable(),
        buildingNameForSearch = ko.observable(),

        floorIdForSearch = ko.observable(),
        floorNameForSearch = ko.observable(),

        deferredForSearch = new $.Deferred(),
        deferredForImageLoading = new $.Deferred();

    var deferredForLoadData = new $.Deferred();

    var locationEnableForSearch = ko.observable(true);


    var imageArray_prev = new Array();
    var BemsFloorStatusDataSource = BemsWebApplication.db.createDataSource('BemsFloorStatus');
    var BemsFloorPlanDataSource = BemsWebApplication.db.createDataSource('BemsFloorPlan');
    var imagefileUrl = ko.observable();


    function handleSearchViewInitializeUpdate() {
        //alert('handleSearchViewInitializeUpdate');
        $('#locationTreeViewInSearchView8').cwTreeView({
            width: '40%',
            height: '100%',
            maxDepth: 2,
            onClickTreeItem: handleClickTreeItem,
            delegateDataSource: BWA.DataUtil.getLocationDataSourceDelegateForTreeView(buildingDataSource, floorDataSource)
        });
    }

    function handleClickTreeItem(element, data) {

        var eq = BWA.DataUtil.constructEqualFilter;
        var depth = data.depth;
        //data = data.data;

        switch (depth) {

            case BUILDING_DEPTH: // building
                data = data.data;

                (data.BuildingId());
                buildingNameForSearch(data.Name());

                floorIdForSearch(null);
                floorNameForSearch('');
                break;

            case FLOOR_DEPTH: // floor
                buildingNameForSearch(data.parentData.data.Name());
                //alert(buildingIdForSearch());
                data = data.data;
                buildingIdForSearch(data.BuildingId());
                floorIdForSearch(data.FloorId());
                floorNameForSearch(data.Name());
                break;
        }
    }

    function handleViewShown() {
        if (initialized === false) {
            floorNameForSearch('');
            initialized = true;
        }
        /*
        timer = setInterval(function () {
            var now = new Date();
            if ((now.getMinutes() % 15 == 0) && (now.getSeconds() == 58)) {
                handleSearchInSearchView();
            }
        }, 1000);*/
    }

    function handleViewHidden() {
        $SearchView.visibleObservable(false); // hcLee 2015 03 23
        visiblePopup(false);
        //        clearInterval(timer); // hcLee 2015 06 12
    }

    function handleViewShowing() {
        //$.when(buildingDataSource.load(), floorDataSource.load()).done(function (dbBuildings, dbFloors) {

        //    deferredForSearch.resolve();
        //    dbBuildings = dbBuildings[0];
        //    dbFloors = dbFloors[0];

        //    if (_.isEmpty(dbBuildings) === false) {
        //        buildingIdForSearch(dbBuildings[0].BuildingId());
        //        buildingNameForSearch(dbBuildings[0].Name());
        //        floorIdForSearch(dbFloors[0].FloorId());
        //        floorNameForSearch(dbFloors[0].Name());
        //        handleSearchInSearchView();
        //    }
        //});
    }

    function refreshList() {
    }

    var searchViewOptions = {
        searchViewItems: [
            {}
        ],
        promiseDataInSearchView: deferredForSearch.promise()
    };
    var mapType = {
        coordinate: { font: "fill: black; font-weight: bold; font-size: 15px;", fixed: 1 },
        temperature: { font: "fill: red; font-weight: bold; font-size: 20px;", fixed: 1 },
        humidity: { font: "fill: blue; font-weight: bold; font-size: 20px;", fixed: 0 },
        carboneDioxide: { font: "fill: green ; font-weight: bold; font-size: 20px;", fixed: 1 },
        concentration: { font: "fill: darkgreen; font-weight: bold; font-size: 20px;", fixed: 1 },
        ozone: { font: "fill: purple ; font-weight: bold; font-size: 20px;", fixed: 2 },
        dust: { font: "fill: orangered ; font-weight: bold; font-size: 20px;", fixed: 0 }
    };

    function setTextInSVG(values) {

        $('#imageContext').find('text').remove();

        // image 기존 이모티콘 지우기
        for (var i = 0; i < imageArray_prev.length; i++) {
            imageArray_prev[i].parentNode.removeChild(imageArray_prev[i]);
        }
        imageArray_prev = new Array();


        var floorTextLocationInfo = new Array();
        var cnt = 0;
        BemsFloorStatusDataSource.filter([
                ["SiteId", "=", BWA.UserInfo.SiteId()],
                "and",
                ["FloorId", "=", floorIdForSearch()]
        ]);
        BemsFloorStatusDataSource.load()
       .done(function (result) {
           for (var i = 0; i < result.length; i++) {
               floorTextLocationInfo[i] = {
                   "floorId": 0,
                   "x": 0,
                   "y": 0,
                   "type": "",
                   "property": 0
               };
               floorTextLocationInfo[i].floorId = result[i].FloorId();
               floorTextLocationInfo[i].x = result[i].Xvalue();
               floorTextLocationInfo[i].y = result[i].Yvalue();
               floorTextLocationInfo[i].property = result[i].PropertyId();

               if (result[i].ServiceTypeId() == 100)
                   floorTextLocationInfo[i].type = 'temperature';
               else if (result[i].ServiceTypeId() == 110)
                   floorTextLocationInfo[i].type = 'humidity';
               else if (result[i].ServiceTypeId() == 130)
                   floorTextLocationInfo[i].type = 'carboneDioxide';
               else if (result[i].ServiceTypeId() == 140)
                   floorTextLocationInfo[i].type = 'concentration';
               else if (result[i].ServiceTypeId() == 150)
                   floorTextLocationInfo[i].type = 'ozone';
               else if (result[i].ServiceTypeId() == 160)
                   floorTextLocationInfo[i].type = 'dust';
               cnt++;
           }

           for (var i = 0; i < cnt; i++) {
               var locationInfo = floorTextLocationInfo[i];
               var type = mapType[locationInfo.type];
               var value = values[i].toFixed(type.fixed);
               if (value != -9999) addText(locationInfo.x, locationInfo.y, value, type.font, locationInfo.type);
           }
       });
    }

    function handleSearchInSearchView() {
        //$('#st').text('층계별 도면' + "  :  " + buildingNameForSearch() + " - " +

        if (floorIdForSearch() == null) {
            utils.toast.show('층을 선택해야 합니다.');
            return;
        }
        BemsFloorPlanDataSource.filter([
                ["SiteId", "=", BWA.UserInfo.SiteId()]
        ]);
        BemsFloorPlanDataSource.load()
        .done(function (result) {
            var idx = 0;
            for (var i = 0; i < result.length; i++) {
                if (result[i].FloorId() == floorIdForSearch() && result[i].ImageFileId() != null) {
                    idx++;
                    var imageFileId = result[i].ImageFileId();
                }
            }

            $('#st').text(buildingNameForSearch() + " - " +
                        floorNameForSearch());

            if (idx == 0) {
                imagefileUrl('');
                loadImage(imagefileUrl());
                utils.toast.show('해당 층의 평면도가 없습니다.','error');
            }
            else {
                imagefileUrl('{0}/CmFile(SiteId={1},FileId={2})/$value'.formati(BWA.db._url, BWA.UserInfo.SiteId(), imageFileId));
                loadImage(imagefileUrl());
            }

            var promises = [];
            promises.push(BemsWebApplication.api.get('BemsMonitoringPointHistory/FloorEachPointValue', {
                SiteId: BWA.UserInfo.SiteId(),
                FloorId: floorIdForSearch(),
            }));
            $.when.apply(this, promises).done(function (values) {
                setTextInSVG(values);
            }).fail(function (error) {
                visiblePopup(false);
            });
        });
    }


    function loadImage(imageUrl) {

        $('#imageContext').find('text').remove();

        //var imageUrl = url;//'/Images/Blueprint/' + viewModel.dataModel.FloorId() + '.jpg';

        var image = document.getElementById("image");

        var newImage = new Image();
        newImage.onload = function () {
            var imageSize = getImageSize(newImage.width, newImage.height);
            $('#imageContext').css('width', imageSize.width).css('height', imageSize.height);
            $('#image').attr('width', imageSize.width).attr('height', imageSize.height); // 2016 05 30 추가,  IE 문제해결,  종화
        }
        newImage.src = imageUrl;
        image.setAttributeNS('http://www.w3.org/1999/xlink', 'href', imageUrl);
    }


    function getImageSize(width, height) {
        var viewIndoor = $('#viewIndoor');
        var maxWidth = parseFloat(viewIndoor.css('width')), maxHeight = parseFloat(viewIndoor.css('height'));
        var widthRatio = width / maxWidth;
        var heightRatio = height / maxHeight;
        var maxRatio = max(widthRatio, heightRatio);
        if (maxRatio > 1) {
            return { width: width / maxRatio, height: height / maxRatio }
        }
        return { width: width, height: height }
    }

    function max(x, y) {
        if (x > y) return x;
        return y;
    }

    function addText(x, y, text, style, type) {

        if (type == 'temperature')
            var imageUrl = '/Images/Blueprint/object_1.png';
        else if (type == 'concentration')
            var imageUrl = '/Images/Blueprint/object_2.png';
        else if (type == 'carboneDioxide')
            var imageUrl = '/Images/Blueprint/object_3.png';
        else if (type == 'humidity')
            var imageUrl = '/Images/Blueprint/object_4.png';
        else if (type == 'dust')
            var imageUrl = '/Images/Blueprint/object_5.png';
        else if (type == 'ozone')
            var imageUrl = '/Images/Blueprint/object_6.png';


        var image = document.createElementNS("http://www.w3.org/2000/svg", "image");

        image.setAttributeNS(null, 'x', x);
        image.setAttributeNS(null, 'y', y);
        image.setAttributeNS('http://www.w3.org/1999/xlink', 'href', imageUrl);
        $('#imageContext').append(image);
        imageArray_prev.push(image);
        //************************

        var image = document.createElementNS("http://www.w3.org/2000/svg", "text");
        image.textContent = text;
        image.setAttributeNS(null, 'x', x + 45);
        image.setAttributeNS(null, 'y', y + 23);
        if (style) {
            image.setAttributeNS(null, 'style', style);
        }
        $('#imageContext').append(image);

    }

    function handleMenuItemClick(e) {

        var chartIntance = chart();
        var chartOptions = chartIntance._options;
        var series = chartIntance.getAllSeries();

        var table = [];
        var columns = [chartOptions.argumentAxis.title];
        var values = {};
        _.each(chartOptions.valueAxis, function (a) {
            columns.push(a.title.text);
        });
        _.each(series, function (s, i) {
            _.each(s.pointsByArgument, function (point, argument) {
                var array = values[argument];
                if (_.isArray(array) === false) {
                    array = values[argument] = [];
                }
                array[i] = point.value;
            });
        });
        var csvRows = [columns.join(',')];
        _.each(values, function (values, argument) {
            csvRows.push([$G.dateTime(moment(Number(argument))), values.join(',')].join(','));
        });

        var csvContent = csvRows.join("\r\n");

        var agent = navigator.userAgent.toLowerCase();
        if (window.navigator.msSaveOrOpenBlob) {

            var fileData = ['\uFEFF' + csvContent];
            var blobObject = new Blob(fileData);
            window.navigator.msSaveOrOpenBlob(blobObject, 'export.csv');
        }
        else {

            var csvString = 'data:text/csv;utf-8,\uFEFF' + encodeURI(csvContent);
            var a = $('#csvExporter');
            a.attr({
                'href': csvString,
                'target': '_blank',
                'download': 'export.csv'
            });
            //        a.trigger('click');
            var aa = document.getElementById('csvExporter');
            aa.click();
        }
    }

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

                refreshList: refreshList,
                viewShowing: handleViewShowing,
                viewHidden: handleViewHidden, // hcLee 2015 03 23
                //viewDisposing: handleViewHidden, // hcLee 2015 03 23
                locationEnableForSearch: locationEnableForSearch,

                handleMenuItemClick: handleMenuItemClick,
                menuItems: [{
                    text: '엑셀(csv) 내보내기'
                }]
            });

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