//地图盒子的高度
var windheight=$(window).height();
var divheight=$('.y_maphead').height();
var navheight=$('.y_puicdh_c').height();

var windwidth=$(window).width();
var divwidth=$('.y_mapcenter_left').width();
$('.y_mapcenter').css({'height':(windheight-divheight-navheight)+'px'});
$('.y_mapcenter_main').css({'width':(windwidth-divwidth-20)+'px'}); 
// $('.y_mapcond_main .y_mapcond_right  span a').hide();
// 地图找房 区域效果
$(function(){
    $('.y_maptop_scr').keyup(function(event) {
        if(event.keyCode==13){                        
            $('.y_maptop_sub').click();
            console.log('提交');
            return false;
        }else{
            lplist();
        }
    });

    navMouseleave('#y_maptop_sel1','#y_maptop_sel1 .y_qysf');
    navMouseleave('#y_maptop_sel2','#y_maptop_sel2 .y_qysf');
    navMouseleave('#y_maptop_sel3','#y_maptop_sel3 .y_qysf');
    navMouseleave('#y_maptop_sel4','#y_maptop_sel4 .y_qysf');

    $('#y_maptop_sel1 .y_left a').on('mouseover',function(){
        var  cyit=$(this).attr('city');
        var sjtitle=$(this).text();
        $(this).css({'color':'#f00'}).siblings().css({'color':'#666'});
        $('#y_maptop_sel1 p.y_right').attr('sj-city',''+sjtitle+'')
        $.post('/js/navs.json',{cyit:cyit,csrf_token_f:111},function(data){
            var echodataUl = $('#y_maptop_sel1 p.y_right');
            echodataUl.html('');
            var data = data.data;
            var html = '';
            $.each(data,function(key,val){
                html ='<a data-city="'+val.id+'" href="javascript:;">';
                html+=''+val.title+'';
                html+='</a>';
                echodataUl.append(html);
            })
        })
    });

    $('#y_maptop_sel1 p.y_right').on('click','a',function(){
        var title=$('#y_maptop_sel1 p.y_right').attr('sj-city');
        var datacity=$(this).attr('data-city');
        var name_title=$(this).text();
        $('#y_maptop_sel1 p.y_city span').text(title);
        $('.y_mapcond_right span.quyu em').text(name_title);
        $('.y_mapcond_right span.quyu a').show();
        lplist();
    });
    y_leixing('y_maptop_sel2','a','yusuan');
    y_leixing('y_maptop_sel3','a','huxing');
    y_leixing('y_maptop_sel4','a','tese');

    fontext('quyu','#y_maptop_sel1 p.y_city span','区域');
    fontext('yusuan','#y_maptop_sel2 p.y_city span','预算');
    fontext('huxing','#y_maptop_sel3 p.y_city span','户型');
    fontext('tese','#y_maptop_sel4 p.y_city span','特色');

    $('.y_mapcond_left a').on('click',function(){
        $('.y_mapcond_right span em').html('');
        $('.y_mapcond_right span a').hide();
        $('#y_maptop_sel1 p.y_city span').text('区域');
        $('#y_maptop_sel2 p.y_city span').text('预算');
        $('#y_maptop_sel3 p.y_city span').text('户型');
        $('#y_maptop_sel4 p.y_city span').text('特色');
        lplist();
    })
})

function fontext(name1,name2,text){
    $('.y_mapcond_right').on('click','span.'+name1+' a',function(){
        $(this).siblings('em').html('');
        $(this).hide();
        $(name2).text(text);
        lplist();
    })
}

function  y_leixing(name1,name2,name3){
    $('#'+name1+' p.y_leixing').on('click',name2,function(){
        var title=$(this).text();
        var name_title=$(this).text();
        var name_title=$(this).text();
        $('#'+name1+' p.y_city span').text(title);
        $('.y_mapcond_right span.'+name3+' em').text(name_title);
        $('.y_mapcond_right span.'+name3+' a').show();
        lplist();
    });
}

function navMouseleave (id,id1){
    $(id).on({
        mouseover: function() {
           $(id1).show();
        },
        mouseleave: function() {
            $(id1).hide();
        }
    });
}

$('#y_maptop_sel1 .y_left a').on('click',function(){
    $('#y_maptop_sel1 p.y_city span').text($(this).text());
    var post=$(this).attr('post')
    var _pointx = post.split(',')[0];
    var _pointy = post.split(',')[1];
    point=new BMap.Point(_pointx,_pointy);
    mp.centerAndZoom(point, 8);
    mp.enableScrollWheelZoom();
    lplist();
})

    var mp = new BMap.Map("allmap",{minZoom:5,maxZoom:16});
    mp.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件
    //    mp.addControl(new BMap.OverviewMapControl({isOpen:true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT})); //右下角,打开
    mp.addControl(new BMap.ScaleControl()); // 添加默认比例尺控件
    mp.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT})); // 左下
    mp.addControl(new BMap.NavigationControl()); //添加默认缩放平移控件
    mp.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_SMALL})); //右上角,仅包含平移和缩放按钮
    // point=new BMap.Point(110.483789,19.119914);
    point=new BMap.Point(106.367394,34.111821);
    mp.centerAndZoom(point, 5);
    mp.enableScrollWheelZoom();

    var geoc = new BMap.Geocoder();
    // console.log(geoc);
    

    // 复杂的自定义覆盖物
    function ComplexCustomOverlays(point, text, mouseoverText){
        this._point = point;
        this._text = text;
        this._overText = mouseoverText;
    }
    ComplexCustomOverlays.prototype = new BMap.Overlay();
    ComplexCustomOverlays.prototype.initialize = function(map){
      this._map = map;
      var div = this._div = document.createElement("div");
      div.style.position = "absolute";
      div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
      var span = this._span = document.createElement("span");
      var that = this;

 
      var arrows = this._arrows = document.createElement("div");
      arrows.style.background = "url(../map/image/ico_map9.png) no-repeat";
      arrows.style.position = "absolute";
      arrows.style.width = "24px";
      arrows.style.height = "28px";
      arrows.style.top = "10px";
      arrows.style.left = "0px";
      arrows.style.overflow = "hidden";
      arrows.style.cursor = "default";
      div.appendChild(arrows);

      div.onmouseover = function(){
        this.style.background = "url(../map/image/ico_map9.png) no-repeat";
        arrows.style.backgroundPosition = "0px -35px";
        this.style.zIndex = 999999;
        // this.style.cursor="pointer";
      }
 
      div.onmouseout = function(){
        this.style.background = "url(../map/image/ico_map9.png) no-repeat";
        arrows.style.backgroundPosition = "0px 0px";
        this.style.zIndex = 0;
      }

      mp.getPanes().labelPane.appendChild(div);
       
      return div;
    }

    
    ComplexCustomOverlays.prototype.draw = function(){
        var map = this._map;
        var pixel = map.pointToOverlayPixel(this._point);
        this._div.style.left = pixel.x - parseInt(this._arrows.style.left) - 8 + "px";
        this._div.style.top = pixel.y - 35+ "px";
    };

    ComplexCustomOverlays.prototype.addEventListener = function(event,fun){
        this._div['on'+event] = fun;
    };


    /*---------------------------------------新添加的省、区域-------------------------------------------------------------*/
    
   function labelFu(data){
        var datacenter = data;                          //数据重新赋值
        var rank = datacenter.rank;                     //获取级别
        var text = datacenter.city;                     //获取城市
        var count = datacenter.count;                   //获取城市楼盘数量
        var point = newPoint(datacenter.point);
        var _points = new BMap.Point(point[0],point[1]);    //经纬度处理     

         // 复杂的自定义覆盖物
         /*添加图标*/
        function ComplexCustomOverlay(point){
          this._point = point;
        }


        ComplexCustomOverlay.prototype = new BMap.Overlay();
        ComplexCustomOverlay.prototype.initialize = function(map){
          this._map = map;
          var div = this._div = document.createElement("div");
          div.style.position = "absolute";
          div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);//聚合功能?
          div.style.height = "45px";
          div.style.width="45px";
          div.style.cursor="pointer";
          div.style.zIndex = 0;
          div.setAttribute("pointX", this._point.lng);
          div.setAttribute("pointY", this._point.lat);
          div.setAttribute("rank", rank);
          // console.log(rank)

          var arrow = this._arrow = document.createElement("p");
          arrow.style.background = "url(/image/yuan.png) no-repeat 0px 0px/55px 110px";
          arrow.style.backgroundPosition = "0px 0x";
          arrow.style.width = "55px";
          arrow.style.height = "55px";
          arrow.style.lineHeight = "20px";
          arrow.style.textAlign = "center";
          arrow.style.top = "30px";
          arrow.style.padding = "10px 0";
          arrow.style.left = "30px";
          // arrow.innerHTML = text;

          var _ew = this.arow = document.createElement("em");
          _ew.innerHTML = text;

          var _arow = this.arow = document.createElement("span");
          _arow.style.display = " block";
          _arow.innerHTML = count;

          arrow.appendChild(_ew);
          div.appendChild(arrow);
          arrow.appendChild(_arow);
                   
         div.onmouseover = function(){
            arrow.style.background = "url(/image/yuan.png) no-repeat center/55px 110px";
            arrow.style.backgroundPosition = "0px -55px";
            this.style.zIndex = 99990;
          }
 
          div.onmouseout = function(){
            arrow.style.background = "url(/image/yuan.png) no-repeat center/55px 110px";
            arrow.style.backgroundPosition = "0px 0px";
            this.style.zIndex = 0;
          }

         /*
          *    给覆盖物添加点击事件
          */
         div.addEventListener("click", function () {
            /*获取当前的经纬度*/
            var _x = $(this).attr("pointX");
            var _y = $(this).attr("pointY");
            Apoint=new BMap.Point(_x,_y);

            /*获取级别*/
            var _rank = $(this).attr("rank");
            var mapRank = 14;
            if(_rank == 1){
                mapRank = 10;
                fuAjaxRegion();        // 把区域遍历
            }else if(_rank == 2){
                mapRank = 15;
                fuAjaxLabel();
            }
            // console.log(Apoint)
            mp.centerAndZoom(Apoint, mapRank);   // 点击当前覆盖物跳转到当前省份上,放大到10级

            mp.clearOverlays();     // 清除地图上所有的覆盖物

            // fuAjaxRegion();        // 把区域遍历

            // mp.clearOverlays();     // 清除地图上所有的覆盖物


            // 获取当省份
            var province = $(this).find('em').text();
            // console.log(province)


         });


          mp.getPanes().labelPane.appendChild(div);     //getPanes(),返回值:MapPane,返回地图覆盖物容器列表  labelPane呢???
          
          return div;
          
        }
        
        ComplexCustomOverlay.prototype.draw = function(){
          var map = this._map;
          var pixel = map.pointToOverlayPixel(this._point);
          this._div.style.left = pixel.x - parseInt(this._arrow.style.left) + "px";
          this._div.style.top  = pixel.y - 30 + "px";
        }


        var myCompOverlay = new ComplexCustomOverlay(_points);     //添加覆盖物的经纬度
        mp.addOverlay(myCompOverlay);                              //将标注添加到地图中

       
   }

    /*遍历所有省份*/
    function fuAjax(){
         $.ajax({
            url:"/map/js/ctiy.json",
            type:"GET",
            dataType:"json",
            success:function(data){
                if(data.code == 200){
                    // console.log(data.province)
                    $.each(data.province,function(key,val){
                        labelFu(val);
                    })
                    
                }
            },
            error:function(request){
                console.log('加载失败!');
            }
        })
    };
   
    fuAjax();

    /*遍历所有区域*/
    function fuAjaxRegion(){
         $.ajax({
            url:"/map/js/ctiy.json",
            type:"GET",
            dataType:"json",
            success:function(data){
                if(data.code == 200){
                    // console.log(data.region)
                    $.each(data.region,function(key,val){
                        labelFu(val);
                    })
                    
                }
            },
            error:function(request){
                console.log('加载失败!');
            }
        })
    };
   
    // fuAjaxRegion();

    /*
    *   新添加标注物
    */
    function fuAjaxLabel(){
        $.ajax({
            url:"/map/js/ctiy.json",
            type:"GET",
            dataType:"json",
            success:function(data){
                if(data.code == 200){
                    $.each(data.data,function(key,val){
                        var point = newPoint(val.point);        //把经纬度进行转化
                        var _points = new BMap.Point(point[0],point[1]);    //经纬度处理    
                        var txt = "",mouseoverTxt="";
                        var _iw = createInfoWindow(val);        //把当前的数据添加到标签中

                        var myCompOverlay = new ComplexCustomOverlays(_points,txt, mouseoverTxt); //将覆盖物存到变量,以便下面使用。
                        mp.addOverlay(myCompOverlay);       //把标签到地图上


                        myCompOverlay.addEventListener("click", function () {  //点击出现对应自定义覆盖物
                            mp.openInfoWindow(_iw, _points)   // 点击标签弹出标签                 
                         
                        });
                    })
                    
                }
            },
            error:function(request){
                console.log('加载失败!');
            }
        })
    }
    


     // 方法2:用于监听滚轮事件
     //firefox使用DOMMouseScroll,其他浏览器使用mousewheel
     $(document).bind('mousewheel DOMMouseScroll',fullscreenScroll);

     function fullscreenScroll(e){
         var delta = -e.originalEvent.wheelDelta || e.originalEvent.detail;//firefox使用detail:下3上-3,其他浏览器使用wheelDelta:下-120上120
         //下滚
         if(delta>0){
             e=e || window.event;
             var u = mp.getZoom();       // 定义地图缩放等级的变量
             // console.log(u)
             if(u <= 9){
                 mp.clearOverlays();     //清除地图上所有的覆盖物
                 fuAjax();
             }else if(u > 9 && u <= 11) {
                 fuAjaxRegion();
                 mp.clearOverlays();     //清除地图上所有的覆盖物
             }else{
                mp.clearOverlays();     //清除地图上所有的覆盖物
                fuAjaxLabel();
             }
         }
         //上滚
         if(delta<0){
             e=e || window.event;
             var u = mp.getZoom(); // 定义地图缩放等级的变量
             console.log(u)
             if(u >= 8 && u < 10){
                 mp.clearOverlays();     //清除地图上所有的覆盖物
                 fuAjaxRegion();
             }else if(u >= 10 && u <= 16){
                fuAjaxLabel();
                 mp.clearOverlays();     //清除地图上所有的覆盖物
             }else {
                 mp.clearOverlays();     //清除地图上所有的覆盖物
                 fuAjax();
             }
         }
     }



    /*--------------------------------------- 新添加的省、区域 END -------------------------------------------------------------*/
      




lplist();
function lplist(){
    $(".y_mapcenter_list ul").html('')
    var html = '';
    $.ajax({
        url: "/map/js/ctiy.json",
        type: "GET",
        dataType: "json",
        success: function(data) {//请求成功完成后要执行的方法
            // console.log(data)
            if(data.code == 200){
                $.each(data.data, function (i, data) {    //左边楼盘列表
                    var jg=data.content.pic;
                    if (jg!='') {
                        jg=data.content.pic;
                    }else{
                        jg='待定';
                    };
                    html+=  '<li class="c" data-id="'+data.point+'">';
                    html+=  '<div class="y_tu"><a href="javascript:;"><img src="'+data.content.img+'" alt=""></a></div>';
                    html+=  '<div class="y_textmain">';
                    html+=  '<div class="y_text c">';
                    html+=  '<a href="javascript:;">'+data.title+'</a>';
                    html+=  '<span><em>'+jg+'</em></span>';
                    html+=  '</div>';
                    html+=  '<div class="y_qixian">(有效期:2017年2月11日-2018年2月11日)</div>';
                    html+=  '<div class="y_hx">户型:'+data.content.add+'</div>';
                    html+=  '<div class="y_tese c">';
                    html+=  '<i>旅游地产</i><i>旅游地产</i><i>旅游地产</i>';
                    html+=  '</div>';
                    html+=  '</div> ';
                    html+=  '</li>';

                });
                $(".y_mapcenter_list ul").append(html);
            }
            

            // 遍历覆盖楼盘名称
            function labal(obj){
                // console.log(obj)
                $.each(obj.data, function (i, obj) {
                    var txt = obj.title;
                    var mouseoverTxt = txt + '&nbsp;&nbsp;|&nbsp;&nbsp;' + obj.content.pic;
                    var pintx = obj.point.split('|')[0];
                    var pinty = obj.point.split('|')[1];

                    var myCompOverlay = new ComplexCustomOverlays(new BMap.Point(pintx, pinty), txt, mouseoverTxt); //将覆盖物存到变量,以便下面使用。
                    mp.addOverlay(myCompOverlay);
                    var point = new BMap.Point(pintx, pinty);
                    var _iw = createInfoWindow(obj);
                    var _marker = myCompOverlay; //当初存的覆盖物变量

                    _marker.addEventListener("click", function () {  //点击出现对应自定义覆盖物
                         mp.openInfoWindow(_iw, point);
                    });

                });
            }


            $(".y_mapcenter_list ul li").click(function(){  //点击列表对应自定义覆盖物
                var _point =  $(this).attr('data-id');
                var _pointx = _point.split('|')[0];
                var _pointy = _point.split('|')[1];
                var _points = new BMap.Point(_pointx, _pointy);
                var _i = $(this).index();
                var _newhou = data.data[_i];
                var ih = createInfoWindow(_newhou);
                mp.centerAndZoom(_points, 15);                  //对应的坐标及放大级别
                labal(data);                                    //遍历所以有的点
                mp.openInfoWindow(ih, _points)                  //当前覆盖添加并展示

            });


        

        }
    });
}

// 处理经纬坐标
function newPoint(_point){
    var pointArr = [];
    var _pointx = _point.split('|')[0];
    var _pointy = _point.split('|')[1];
    pointArr.push(_pointx,_pointy);
    return pointArr;
}  

function  createInfoWindow(data){   //自定义覆盖物
    console.log(data)
    var iw= new BMap.InfoWindow(
        '<div class="map_id" style="width:260px; height:auto; position:absolute; left:0px; top:0px;">'+
        '<p style="width:100%; height:155px; margin-top:10px;"><a href="'+data.content.href+'"><img src="'+data.content.img+'" alt="" width="100%" height="100%;"></a></p>'+
        '<p style="margin-top:8px;"><a style="font-size:16px; color:#333;" href="'+data.content.href+'">'+data.title+'</a><span style="font-size:12px; color:#888; padding-left:8px;">'+data.dq+'</span></p>'+
        '<p style="margin-top:5px;"><span><em style="font-size:18px; color:#f00; font-style:normal;">'+data.content.pic+'</em></span></p>'+
        '</div>'
    );
    return iw
}