﻿
/****************************************************************************************/
/*  创建地图相关的数据                                                                  */
/*  创建图与层                                                                          */
/*  isNewStyle 是否新显示风格                                                           */
/*  fun_addToPlan 从外部传入，用于响应Marker的Infowindow中关于添加到行程的功能          */
/*  showMarker, 当地图中加入Marker时是否立即显示出来                                    */
/*  isNewStyle, 是否引用新的风格显示相关景点列表，此参数主要传入到下级的景点等层中      */
/*  pageSize, 分页显示相关景点，并且让地图中的Marker标记与当前页中的序号一致            */
/*  pageIndex, 当前页，从0开始                                                          */
/*  isLarge 是否使用大地图模式，大地图模式下操作按钮会不一样，地图风格也不一样          */
/*  isAutoFill 是否启动地图分格Load功能   下级                                              */
/*  selectedData 此层中需要默认选中的数据，结构为Json： ObjectType:ObjectID             */
/*  selectedMarkerType 显示选择中的景点的图标类型 0 ：不显示 1：选择中的 2：字母        */
/****************************************************************************************/
//objectID, objectType, map_centerLat, map_centerLng, map_level, showMarker, isNewStyle, pageSize, pageIndex,
// isLarge, isAutoFill, fun_addToPlan, selectedData, selectedMarkerType
/*var options = {"ObjectID":objectID,"ObjectType":objectType,
    "CenterLAT":map_centerLat,"CenterLNG":map_centerLng,"MAPLevel":map_level,
    "ShowMarker":showMarker,"IsNewStyle":isNewStyle,
    "PageSize":pageSize,"PageIndex":pageIndex,"IsLarge":isLarge,
    "IsAutoFill":isAutoFill,"AddToPlanFun":fun_addToPlan,
    "SelectMarkerType":selectedMarkerType
}*/
function HMap(options) {
    var _self = this;
    this.callbackFun = function(layerID) {
        _self.LayerCountShowing++;
        if (_self.LayerCountShowing >= _self.LayerCountVisible) {
            if (_self.Options.ShowCallbackFun != undefined && _self.Options.ShowCallbackFun != null) {
                _self.Options.ShowCallbackFun(layerID);
            }
            _self.LayerCountShowing = 0;
        }
    }
    //showchildren 是否只显示子对像
    this.DefaultOptions = {
        "ContainerID":"map_canvas",
        "CenterLAT": 34.524940, "CenterLNG": 108.916180, "MAPLevel": 4, "ShowMarker": true,"MapType":google.maps.MapTypeId.ROADMAP,
        "ObjectID": 0, "CObjectType": sceneObjectType,
        "PageIndex": 0, "PageSize": 10, "IsLarge": true,
        "SelectMarkerType": "scene", "ShowSelectMarker": 1, "SelectedData": null,
        "IsAutoFill": true, "IsNewStyle": true, "AddToPlanFun": null, "ShowUnSelectMarker": true,
        "LayerID": 0, "LayerType": sceneObjectType, "Visible": false, "ListenMapChanged": true,
        "ShowSelectedMarkerInList": true, "ShowCallbackFun": null, "ScrollWheelZoom": true,"ShowChildren":false,
        "MarkerClickFun":null,
        "LayerOptions": [
            { "LayerID": 0, "Visible": true,"ObjectType":sceneObjectType, "LayerType": sceneObjectType, "Icon": sceneIcon, "LayerTypeName": "scene", "ShowCallbackFun": this.callbackFun },
            { "LayerID": 1, "Visible": false, "ObjectType": hotelObjectType, "LayerType": hotelObjectType, "Icon": hotelIcon, "LayerTypeName": "hotel", "ShowCallbackFun": this.callbackFun },
            { "LayerID": 2, "Visible": false, "IsAutoFill": false,  "ObjectType": foodObjectType, "LayerType": foodObjectType, "Icon": foodIcon, "LayerTypeName": "food", "ShowCallbackFun": this.callbackFun },
            { "LayerID": 3, "Visible": false, "IsAutoFill": false, "ObjectType": tripObjectType, "LayerType": tripObjectType, "Icon": tripIcon, "LayerTypeName": "trip", "ShowCallbackFun": this.callbackFun },
            { "LayerID": 4, "Visible": false, "IsAutoFill": false, "ObjectType": tipsObjectType, "LayerType": tipsObjectType, "Icon": tipsIcon, "LayerTypeName": "tips", "ShowCallbackFun": this.callbackFun },
            { "LayerID": 5, "Visible": false, "IsAutoFill": false, "ObjectType": regionObjectType, "LayerType": regionObjectType, "Icon": regionIcon, "LayerTypeName": "region", "ShowCallbackFun": this.callbackFun },
            { "LayerID": 6, "Visible": false, "IsAutoFill": false, "ObjectType": 8, "LayerType": 8, "Icon": trainstationIcon, "LayerTypeName": "trainstation", "ShowCallbackFun": this.callbackFun },
            { "LayerID": 7, "Visible": false, "IsAutoFill": false, "ObjectType": 10, "LayerType": 10, "Icon": airportIcon, "LayerTypeName": "airport", "ShowCallbackFun": this.callbackFun }
         ]
    }
    this.LayerCountShowing = 0;
    this.LayerCountVisible = 0;
    
    this.Options = {};
    jQuery.extend(true,this.Options, this.DefaultOptions, options);
    
    this.map_hlayer = new Array();
    this.map_icon_zindex = 999;
    this.centerPoint = new google.maps.LatLng(_self.Options.CenterLAT, _self.Options.CenterLNG);
    this.map_lastRect;
    this.map = null;
    this.overlay = null;
    this._NeedReloadLayer = true;
    this.getLayerOptions = function(layerID) {
        if (layerID >= 0 && layerID < _self.Options.LayerOptions.length) {
            return _self.Options.LayerOptions[layerID];
        }
        return {};
    }
    this.release = function () {
        this.map_release();
    }
    this.map_release = function () {
        for (var k = 0; k < _self.map_hlayer.length; k++) {
            _self.map_hlayer[k].release();
            _self.map_hlayer[k] = null;
        }
        _self.map_hlayer.splice(0, _self.map_hlayer.length);
        _self.Options.ShowCallbackFun = null;
        _self.Options = null;
        _self.centerPoint = null;
        google.maps.event.clearListeners(_self.map, "zoom_changed");
        google.maps.event.clearListeners(_self.map, "dragstart");
        google.maps.event.clearListeners(_self.map, "dragend");
        google.maps.event.clearListeners(_self.map, "click");
        _self.map = null;
        //_self = null;
    }
    this.getMapLevel = function() { return _self.Options.MAPLevel; }
    this.getCenterPoint = function() { return this.centerPoint; }
    this.setRealodLayer = function(bLoad) {        this._NeedReloadLayer = bLoad == undefined ? true : bLoad;    }
    this.setShowSelectedMarker = function(bShow) {
        this._ShowSelectMarker = bShow == undefined ? 1 : bShow;
        for (var k = 0; /*k < 5 && */k < this.map_hlayer.length; k++) {            this.map_hlayer[k].setShowSelectedMarker(bShow);        }
    }
    
    this.getLayer = function(objectType) {
        var ret = null;
        for (var k = 0; k < this.map_hlayer.length; k++) {
            if (this.map_hlayer[k].ObjectType == objectType) {
                ret = this.map_hlayer[k];
                break;
            }
        }
        return ret;
    }
    this.getLayerByID = function (layerID) {
        if (layerID >= 0 && layerID < this.map_hlayer.length)
            return this.map_hlayer[layerID];
        else
            return nul;
    }
    this.map_initialize = function (objectID, objectType) {
        var myOptions = {
            zoom: this.Options.MAPLevel,
            center: new google.maps.LatLng(this.Options.CenterLAT, this.Options.CenterLNG),
            mapTypeId: this.Options.MapType,
            disableDoubleClickZoom: true,
            scrollwheel: _self.Options.ScrollWheelZoom
        }
        if (!_self.Options.IsLarge) {
            //disableDefaultUI: true,
            myOptions.mapTypeControl = true;
            myOptions.mapTypeControlOptions = { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU };
            myOptions.navigationControl = true;
            myOptions.navigationControlOptions = { style: google.maps.NavigationControlStyle.SMALL };
        }
        var canvasID = _self.Options.ContainerID;
        this.map = new google.maps.Map(document.getElementById(canvasID), myOptions);

        $('#map_controllist > li').addClass('controllist');
        $('#contentSelection > li').addClass('selections');
        $('#rmap').addClass('selections-selected');

        for (var kk = 0; kk < this.Options.LayerOptions.length; kk++) {
            var para = { overlay: this.overlay };
            jQuery.extend(para, this.Options, this.getLayerOptions(kk));
            if (para.MarkerClickFun == undefined || para.MarkerClickFun == null)
                para.MarkerClickFun = this.Options.MarkerClickFun;

            //如果只显示子景点，则不需自动填充
            if (para.ShowChildren == undefined)
                para.ShowChildren = this.option.ShowChildren || false;
            if (para.ShowChildren == true) {
                para.IsAutoFill = false;
            }
            para.SelectedData = this.Options.SelectedData;
            this.map_hlayer[kk] = new HLayer(this.map, para);  //景点
        }

        if (_self.Options.ShowMarker) {
            this.map_refreshLayers(_self.Options.MAPLevel);
        }
        else {
            this.map_getLayerData(0);
        }

        // === Create the MoreControl(), and do addControl() it ===
        //map.addControl(new MoreControl());

        if (_self.Options.ListenMapChanged) {
            google.maps.event.addListener(this.map, "zoom_changed", function (e) {
                gfCloseInfoWindow();
                _self.Options.MAPLevel = _self.map.getZoom();
                var cRect = _self.map.getBounds();
                _self.map_refreshLayers(_self.Options.MAPLevel, _self.map_lastRect, cRect);
                if (_self.map_lastRect == undefined || _self.map_lastRect == null) {
                    _self.map_lastRect = cRect;
                }
            });
            google.maps.event.addListener(this.map, "dragstart", function (e) {
                gfCloseInfoWindow();
            });
            google.maps.event.addListener(this.map, "dragend", function (e) {
                gfCloseInfoWindow();
                var cRect = _self.map.getBounds();
                _self.map_refreshLayers(_self.Options.MAPLevel, _self.map_lastRect, cRect);
                if (_self.map_lastRect == undefined || _self.map_lastRect == null) {
                    _self.map_lastRect = cRect;
                }
            });
        }
        google.maps.event.addListener(this.map, "click", function (overlay, latlng, overlaylatlng) {
            if (overlay == null)
                gfCloseInfoWindow();
        });
    }
    this.map_refreshLayers = function (level, rect0, rect1) {
        _self.LayerCountVisible = 0;
        _self.LayerCountShowing = 0;
        for (var k = 0; /*k < 5 && */k < _self.map_hlayer.length; k++) {
            if (!_self.map_hlayer[k].IsHidden()) {
                _self.LayerCountVisible++;
            }
        }
        if (!_self._NeedReloadLayer) return;
        if (!_self.map) {
            alert("not self map");
            return false;
        }


        var t1 = _self.map.getBounds();
        if (t1 == undefined) {
            setTimeout(function () {
                _self.map_refreshLayers(level, rect0, rect1);
            }, 1000);
            return false;
        }
        var sw = t1.getSouthWest();
        var ne = t1.getNorthEast();
        var paramap = { "pageSize": this.Options.PageSize, "pageIndex": this.Options.PageIndex, "rect0": sw, "rect1": ne, "currentSqure": 0, "layerID": 0, "level": level, "sn": Math.random() };
        var t = Async.chain().next(_self.resetLayer);
        for (var k = 0; k < _self.map_hlayer.length; k++) {
            var dd = _self.map_hlayer[k];
            dd.setShowSN(paramap.sn);

            if (dd.IsHidden()) {
                t = t.next(dd.completed);
            }
            else {
                t = t.next(dd.getData); //.next(dd.bindData);
                if (dd.Options.IsAutoFill) {
                    for (var j = 0; j < 9; j++) {
                        t = t.next(dd.fillMapRect).next(dd.incSqure);
                    }
                    //t = t.next(dd.bindData);
                }
                t = t.next(dd.bindData).next(dd.addMarkerToMap).next(dd.showMarkersAll);
            }
            t = t.next(_self.incLayer);
        }
        t.next(function (para) {
            var totalCount = 0;
            for (var j = 0; j < _self.map_hlayer.length; j++) {
                totalCount += _self.map_hlayer[j].dataCount();
            }
            $("#relatescenecount").text(totalCount);
            if (_self.Options.ShowCallbackFun) {
                _self.Options.ShowCallbackFun(-1, false); //当前层，是否要重画线路
            }
        }).go(paramap);
    }
    this.resetLayer = function(para) {
        para.layerID = 0;
        for (var k = para.layerID; k < _self.map_hlayer.length; k++) {
            //if (_self.map_hlayer[k].IsHidden() == false) {
                _self.map_hlayer[k].setNeedData(true);
                _self.map_hlayer[k].setLevelID(para.level);
            //}
        }
        return para;
    }
    this.incLayer = function(para) {
        para.layerID++;
        if (para.layerID < _self.map_hlayer.length) {
            _self.map_hlayer[para.layerID].setNeedData(true);
            _self.map_hlayer[para.layerID].setLevelID(para.level);
        }
        return para;
    }
    this.map_pagerLayer = function(layerID, pageIndex) {
        if (layerID >= this.map_hlayer.length) return;
        if (layerID < 0) return;
        this.map_hlayer[layerID].PagerData(pageIndex);
    }
    // ==== toggleLayer adds and removes the layers ====
    this.map_toggleLayer = function (i, isshow) {
        var layer = this.getLayerByID(i);
        if (layer == null || layer == undefined) return;
        
        if (isshow || isshow == undefined)
            layer.changeOptions({"Visible":false, "ShowUnSelectMarker": true });
        else
            layer.changeOptions({"ShowUnSelectMarker": false });

        if (isshow == undefined) {
            if (layer.dataCount() > 0 && layer.isAddedToMap() == false) {
                layer.showMarkers(true);
                return;
            }
            else {
                if (layer.dataCount() == 0) layer.setNeedData(true);
            }
            if (!layer.IsHidden() && layer.dataCount() > 0) {
                layer.hide();
            } else {
                var sw = this.map.getBounds().getSouthWest();
                var ne = this.map.getBounds().getNorthEast();
                layer.show(sw, ne);
            }
        }
        else if (isshow == false) {
            layer.hide();
        }
        else {
            if (layer.dataCount() > 0) {
                if (layer.isAddedToMap() == false) {
                    layer.showMarkers(true);
                    return;
                }
                else if (layer.IsHidden() == true) {
                    //this.map_hlayer[i].show();
                }
            }
            else {
                if (layer.dataCount() == 0) layer.setNeedData(true);
            }
            var sw = this.map.getBounds().getSouthWest();
            var ne = this.map.getBounds().getNorthEast();
            layer.show(sw, ne);
        }

    }
    this.map_getLayerData = function (i) {

        if (i >= this.map_hlayer.length) return;
        if (i < 0) return;
        if (this.map_hlayer[i].isNeedData()) {
            var sw = this.map.getBounds().getSouthWest();
            var ne = this.map.getBounds().getNorthEast();
            var paramap = { "pageSize": 10, "pageIndex": 0, "rect0": sw, "rect1": ne, "currentSqure": 0, "layerID": i, "level": _self.Options.MAPLevel, "sn": Math.random() };
            _self.map_hlayer[i].setShowSN(param.sn);
            var t = Async.go(paramap).next(_self.map_hlayer[i].getData);
            //this.map_hlayer[i].getData();
        }
    }
    this.map_MarkerClick = function (layerid, i, objectID, objectType) {

        if (layerid >= this.map_hlayer.length || i >= this.map_hlayer[layerid].mapMarkers.length) return;
        if (layerid < 0) {
            layerid = this.getLayerIDByObjectType(objectType);
            var data = this.map_hlayer[layerid]._Data;
            if (data != undefined && data != null) {
                var totalCount = data.length;
                for (var k = 0; k < totalCount; k++) {
                    if (data[k].ObjectID == objectID) {
                        i = k;
                        break;
                    }
                }
            }
        }
        this.map.setCenter(this.map_hlayer[layerid].mapMarkers[i].pointer);
        google.maps.event.trigger(this.map_hlayer[layerid].mapMarkers[i], "click");
    }

    this.map_ismapvisible = function() {
        var ishide = false;
        //$('.hide').
        return ishide;
    }
    //通过对分页标签的了解，看是否需要加载数据
    this.map_hasdata = function(sender) {
        var t = $('#' + sender + '-pager');
        if (t.length == 0)
            return false;
        else
            return true;
    }
    this.addMarker = function(layerid, data, bRefresh) {
        if (layerid >= this.map_hlayer.length || layerid < 0) layerid = 0;
        this.map_hlayer[layerid].addMarkerBySearch(data, bRefresh);
    }
    this.setCenter = function (lat, lng, maplevel, bForce) {
        if ((bForce == undefined || bForce == false)
                && (_self.Options.MAPLevel == undefined || maplevel == _self.Options.MAPLevel)
                && this.centerPoint.lat() == lat && this.centerPoint.lng() == lng) {
            return;
        }
        this.centerPoint = new google.maps.LatLng(lat, lng);
        if (maplevel == undefined || maplevel <= 0 || maplevel >= 19) {
            //_self.Options.MAPLevel = maplevel;
        }
        else {
            _self.Options.MAPLevel = maplevel;
        }
        this.map.setCenter(this.centerPoint);
        if(this.map.getZoom()!=_self.Options.MAPLevel)
            this.map.setZoom(_self.Options.MAPLevel);
    }
    this.getLayerIDByObjectType = function(objectType) {
        var lid = 0;
        for (var k = 0; k < this.map_hlayer.length; k++) {
            if (this.map_hlayer[k].getLayerType() == objectType) {
                lid = k;
                break;
            }
        }
        return lid;
    }
    this.getObjectTypeByLayer = function(layerid) {
        if (layerid >= 0 && layerid < this.map_hlayer.length) {
            return this.map_hlayer[layerid].getLayerType();
        }
        else
            return 0;
    }
    this.clearData = function () {
        for (var i = 0; i < this.map_hlayer.length; i++) {
            this.map_hlayer[i].clearData();
        }
    }
    this.removeSelectObjectID = function(objectType, objectID, bRefresh, fun_show) {
        var lid = this.getLayerIDByObjectType(objectType);
        this.map_hlayer[lid].removeSelectedObjectID(objectID, bRefresh);
        if (fun_show != undefined && fun_show != null) {
            fun_show(objectType, objectID);
        }
    }
    this.addSelectObjectID = function (objectType, objectID, bRefresh, fun_show, options) {
        var lid = this.getLayerIDByObjectType(objectType);
        var data = this.map_hlayer[lid]._Data;
        var currentData = null;
        if (data != undefined && data != null) {
            var totalCount = data.length;

            for (var k = 0; k < totalCount; k++) {
                if (data[k].ObjectID == objectID) {
                    currentData = data[k];
                }
            }
        }
        if (currentData == null) {
            this.ObjectID = objectID;
            _self.map_hlayer[lid].addSelectedObjectID(objectID, bRefresh, objectType, function () {
                if (fun_show != undefined && fun_show != null) {
                    fun_show(objectType, objectID);
                }
            }, options);
        }
        else {
            this.map_hlayer[lid].addSelectedObjectID(currentData.ObjectID, bRefresh, currentData.ObjectType, options);
            if (fun_show != undefined && fun_show != null) {
                fun_show(objectType, objectID);
            }
        }
    }
    this.setCenterByObject = function (objectType, objectID, fun_show) {
        var lid = this.getLayerIDByObjectType(objectType);
        var data = this.map_hlayer[lid]._Data;
        var currentData = null;
        if (data != undefined && data != null) {
            var totalCount = data.length;

            for (var k = 0; k < totalCount; k++) {
                if (data[k].ObjectID == objectID) {
                    currentData = data[k];
                    break;
                }
            }
        }
        if (currentData == null) {
            this.ObjectID = objectID;
            var u = window.ROOT + 'ajax/SearchActions.aspx';
            $.get(u,
            { 'act': 'search.get',
                'id': objectID,
                'objectType': objectType
            },
            function (json) {
                if (json.s == -1) {
                    alert(json.msg);
                    return;
                }
                if (json.datalist.length > 0) {
                    _self.map_hlayer[lid].addSelectedObjectID(json.datalist[0].ObjectID);
                    _self.setCenter(json.datalist[0].LAT, json.datalist[0].LNG);
                    if (fun_show != undefined && fun_show != null) {
                        fun_show(objectType, objectID);
                    }
                }
            }, "json");
        }
        else {
            this.map_hlayer[lid].addSelectedObjectID(currentData.ObjectID);
            this.setCenter(currentData.LAT, currentData.LNG);
            if (fun_show != undefined && fun_show != null) {
                fun_show(objectType, objectID);
            }
        }
    }
    this.CalculateMapLevel = function(idList, mapwidth, mapheight) {
        var u = window.ROOT + 'ajax/SearchActions.aspx';
        $.get(u,
            { 'act': 'search.getmaplevel',
                'idlist': idList,
                'width': mapwidth,
                'height': mapheight
            },
            function(json) {
                if (json.s == -1) {
                    alert(json.msg);
                    return;
                }
                var data = json.datalist[0];
                _self.setCenter(data.CenterLAT, data.CenterLNG, data.MapLevel);
            }, "json");
        };

        this.showIconTop = function (objectType, objectID) {
            var layer = _self.getLayer(objectType);
            if (layer != null && layer != undefined) {
                var index = -1;
                for (var k = 0; k < layer.mapMarkers.length; k++) {
                    if (layer.mapMarkers[k].ObjectID == objectID && layer.mapMarkers[k].ObjectType == objectType) {
                        index = k;
                        break;
                    }
                }
                if (index >= 0) {
                    layer.showIconTop2(index);
                }
            }
        }
        this.showIconBottom = function (objectType, objectID) {
            var layer = _self.getLayer(objectType);
            if (layer != null && layer != undefined) {
                var index = -1;
                for (var k = 0; k < layer.mapMarkers.length; k++) {
                    if (layer.mapMarkers[k].ObjectID == objectID && layer.mapMarkers[k].ObjectType == objectType) {
                        index = k;
                        break;
                    }
                }
                if (index >= 0) {
                    layer.showIconBottom(index);
                }
            }
        }
    //初始化地图
    this.map_initialize(this.Options.ObjectID, this.Options.ObjectType);
}

