//地图盒子的高度
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();
var _height= windheight-300;

$('.y_mapcenter_list').css('height',_height)
$('.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();
// 地图找房 区域效果
var dataID={};
var dataTitle={};
$(function(){

    /*----------------------------------检索------------------------------------------------*/

    /* 搜索框检索 */
    var text;       //用于存放检索内容
    var _txt='';   //用于存放点击搜索之前的值  用意在于不能每点击或回车一次发送请求
    var dataTxt = {};
    $('.y_maptop_scr').keyup(function(event) {
        if(event.keyCode==13){
            fuInput();
        }
    });
    /* 点击搜索按钮 */
    $('.y_maptop_sub').click(function(){
        fuInput();
    });

    /* 获取input框的值 */
    function fuInput(){
        var txt = $('.y_maptop_scr').val().replace(/\s/g,"");          //获取input 内容并去掉所有的空格
        if(txt !== _txt){
            _txt=txt;
            dataTxt.content=_txt;
            $('.y_mapcond_right').html("");         //清空里面所有的标签
            getData(1,dataTxt,false);
            $('.y_mapcenter_list ul li').eq(0).click();
        }

    }

   

    /*----------------------------------筛选--------------------------------------------------*/

    // 区域、预算、户型、特色点击获取筛选条件

    $('.y_maptop_sel .y_leixing').on('click','a',function(){
        var _type = $(this).attr('data-type');
        var _thisID = $(this).attr('data-id');
        var _thisTitle = $(this).text();
        $(this).parents('.y_maptop_sel').find('.dataText').html(_thisTitle);
        switch(_type)
        {
            case "city":
                dataID.city=_thisID;
                dataTitle.city = _thisTitle;
                break;
            case "price":
                dataID.price=  _thisTitle;
                    // _thisID;
                dataTitle.price = _thisTitle;
                break;
            case "houseType":
                dataID.houseType=_thisID;
                dataTitle.houseType = _thisTitle;
                break;
            case "trait":
                dataID.trait=_thisID;
                dataTitle.trait = _thisTitle;
                break;
        }
        getData(1,dataID);           //选择筛选条件时候,把条件通过Ajax提交返回数据

        // console.log(dataID);
        //筛选条件的显示
        var _htm="";
        for(i in dataTitle){
            _htm +='<span class="yusuan"><em>'+ dataTitle[i] +'</em><a data-type="'+i+'" href="javascript:;"><img src="/map/image/ico_map4.png" alt=""></a></span>';
        }
        $('.y_mapcond_right').html("");
        $('.y_mapcond_right').append(_htm);             //插入前先进行清空再插入

    })

    // 显示筛选条件处的删除功能
    var module = {city:"区域",price:"价格",houseType:"户型",trait:"特色"};
    $('.y_mapcond_right').on('click','.yusuan a',function(){

        var property = $(this).attr('data-type');
        //删除对象中的数据
        delete dataID[property];
        delete dataTitle[property];

        // 实现删除当前标签时,对应的数据修改为默认值
        $('.dataText[data-id="'+property+'"]').html(module[property]);

        $(this).parent('.yusuan').remove();  //删除当前的标签内容

        getData(1,dataID);           //选择筛选条件时候,把条件通过Ajax提交返回数据


    })

    //清空条件
    $('.y_mapcond_left').on('click',function(){
        dataID={};          //清空对象
        dataTitle={};       //清空对象
        $('.y_mapcond_right').html("");         //清空里面所有的标签

        //把所有的筛选条件修改为默认值
        for(i in module){
            $('.dataText[data-id="'+i+'"]').html(module[i]);
        }

        getData(1,dataID);           //选择筛选条件时候,把条件通过Ajax提交返回数据

    })



    //区域 点击筛选
    $('#y_maptop_sel1 .y_left a').on('click',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('/map/pidcity',{id:cyit,'csrf_token_f':csrfToken},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-type="city" data-id="'+val.id+'" href="javascript:;">';
                html+=''+val.city_name+'';
                html+='</a>';
                echodataUl.append(html);
            })
        })
    });



    // 区域  预算  户型  特色 显示隐藏
    navMouseleave(".y_maptop_sel");
})



/* 显示隐藏方法封装 */
function navMouseleave (oid){
    $(oid).on({
        mouseover: function() {
            $(this).find('.y_qysf').show();
        },
        mouseleave: function() {
            $(this).find('.y_qysf').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 _point = newPoint(post);
    point=new BMap.Point(_point[0],_point[1]);
    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 pid = datacenter.pid;                     //省份iD
        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);
          div.setAttribute("pid", pid);
          // 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 _pid = $(this).attr("pid");
            var mapRank = 14;
            if(_rank == 1){
                mapRank = 10;
                fuAjaxRegion(_pid);        // 把区域遍历
                // getData(1,_pid);           //选择筛选条件时候,把条件通过Ajax提交返回数据
            }else if(_rank == 2){
                mapRank = 15;
                fuAjaxLabel(_pid);
                // getData(1,_pid);           //选择筛选条件时候,把条件通过Ajax提交返回数据
            }
            // console.log(Apoint)
            mp.centerAndZoom(Apoint, mapRank);   // 点击当前覆盖物跳转到当前省份上,放大到10级

            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/province",
            type:"GET",
            dataType:"json",
            success:function(data){
                if(data.code == 200){
                    // console.log(data.data)
                    $.each(data.data,function(key,val){
                        labelFu(val);
                    })
                }
            },
            error:function(request){
                console.log('加载失败!');
            }
        })
    };
   
    fuAjax();

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

    /*
    *   新添加标注物
    */
    function fuAjaxLabel(pid =null){
        $.ajax({
            url:"/map/cityhouse",
            type:"GET",
            data:{pid:pid},
            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 o = scope(_points);
                        if(o != undefined){
                            var myCompOverlay = new ComplexCustomOverlays(o,txt, mouseoverTxt); //将覆盖物存到变量,以便下面使用。
                            mp.addOverlay(myCompOverlay);       //把标签到地图上

                             myCompOverlay.addEventListener("click", function () {  //点击出现对应自定义覆盖物
                                mp.openInfoWindow(_iw, _points)   // 点击标签弹出标签                 
                         
                            });
                        }
                    })
                    
                }
            },
            error:function(request){
                console.log('加载失败!');
            }
        })
    }
    /*监听地图移动事件*/
    mp.addEventListener("dragend", function(e){
        // var delta = -e.originalEvent.wheelDelta || e.originalEvent.detail;//firefox使用detail:下3上-3,其他浏览器使用wheelDelta:下-120上120
        // e=e || window.event;
        var u = mp.getZoom();       // 定义地图缩放等级的变量
        if(u>12){
            var center =mp.getCenter();

            mp.clearOverlays();     //清除地图上所有的覆盖物
            fuAjaxLabel();
        }
        
        
    })
    
    /*获取可视区域*/
    function scope(_point){
        var bs = mp.getBounds();   //获取可视区域
        var bssw = bs.getSouthWest();   //可视区域左下角
        var bsne = bs.getNorthEast();   //可视区域右上角   

        // console.log(1)

        if(_point.lng >= bssw.lng && _point.lng <= bsne.lng && _point.lat >= bssw.lat && _point.lat <= bsne.lat ){
            // console.log(_point)
            return _point
        }
        // console.log("当前地图可视范围是:" + bssw.lng + "," + bssw.lat + "到" + bsne.lng + "," + bsne.lat); 
    }
    




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

     function fullscreenScroll(e){
             var u = mp.getZoom();       // 定义地图缩放等级的变量
             console.log(u)
             if(u>6 && u <= 9){
                 mp.clearOverlays();     //清除地图上所有的覆盖物
                 fuAjax();
             }else if(u > 9 && u <= 11) {
                 fuAjaxRegion();
                 mp.clearOverlays();     //清除地图上所有的覆盖物
             }else if(u > 11){
                mp.clearOverlays();     //清除地图上所有的覆盖物
                fuAjaxLabel();
             }
         }
  


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



 // 遍历覆盖楼盘名称
function labal(obj){
    // console.log(obj)
    $.each(obj.data, function (i, obj) {
        var txt = obj.name;
        var mouseoverTxt = txt + '&nbsp;&nbsp;|&nbsp;&nbsp;' + obj.sale_price;
        var pintx = obj.longitude_latitude.split(',')[0];
        var pinty = obj.longitude_latitude.split(',')[1];
        var _points = new BMap.Point(pintx, pinty);

         var o = scope(_points);
         if(o != undefined){
             var myCompOverlay = new ComplexCustomOverlays(o,txt, mouseoverTxt); //将覆盖物存到变量,以便下面使用。
             mp.addOverlay(myCompOverlay);       //把标签到地图上
         }else{
            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);
        });
    });
}


/*--------------------------------- Ajax 分页功能 ----------------------------------------*/
var curPage = 1; //当前页码
var total,pageSize = 10,totalPage; //总记录数,每页显示数,总页数
//获取数据
function getData(page,arr = null,async){
    if(async == undefined){
        async= true;
    }
    $.ajax({
        type: 'post',
        url: "/map/houselist",
        data: {'page':page,'limit':pageSize,'csrf_token_f':csrfToken,'data':arr},
        dataType:'json',
        async:async,            //为了解决检索时,点击对应的楼盘
        beforeSend:function(){
            $(".y_mapcenter_list ul").append("<li id='loading'>loading...</li>");//显示加载动画
        },
        success:function(json){

            $(".y_mapcenter_list ul").html('');//清空数据区
            if(json.code == 200){
                total = json.count; //总记录数
                $('.housenum em').html(total);
                // pageSize = json.pageSize; //每页显示条数
                curPage = page; //当前页
                totalPage = parseInt((parseInt(total) + parseInt(pageSize) - 1) / pageSize); //总页数
                var html = '';
                var list = json.data;
                $.each(list,function(index,array){ //遍历json数据列
                    var jg=array.sale_price;
                    if (jg!=0) {
                        jg=array.sale_price+array.price_unit;
                    }else{
                        jg='待定';
                    };
                    html+=  '<li class="c" data-id="'+array.longitude_latitude+'">';
                    html+=  '<div class="y_tu"><a href="javascript:;"><img src="'+array.thumb+'" alt=""></a></div>';
                    html+=  '<div class="y_textmain">';
                    html+=  '<div class="y_text c">';
                    html+=  '<a href="javascript:;">'+(array.name.length > 6 ? array.name.slice(0,5)+'...' : array.name)+'</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">户型:'+array.main_units+'</div>';
                    html+=  '<div class="y_tese c">';
                    // console.log(array.characteristic);
                    if(array.characteristic != null){
                        $.each(array.characteristic,function (k,v) {
                            html+=  '<i>'+(v.length > 4 ? v.slice(0,3)+'...' : v)+'</i>';
                        })
                    }

                    html+=  '</div>';
                    html+=  '</div> ';
                    html+=  '</li>';
                });
                $(".y_mapcenter_list ul").append('<li id="loading"><img src="/map/image/load.gif" alt="" />数据加载中...</li>');//显示加载动画
                setTimeout(function(){
                    $(".y_mapcenter_list ul").html('');//清空数据区
                    $(".y_mapcenter_list ul").append(html);
                }, 300);
                
                $(".y_mapcenter_list ul").on('click','li',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();
                    // console.log(_i);
                    var _newhou = json.data[_i];
                    // console.log(_newhou)
                    var ih = createInfoWindow(_newhou);
                    mp.centerAndZoom(_points, 15);                  //对应的坐标及放大级别
                    labal(json);                                    //遍历所以有的点
                    mp.openInfoWindow(ih, _points)                  //当前覆盖添加并展示
                });
            }else{
                $(".y_mapcenter_list ul").append('<li id="loading">未找到符合条件的楼盘...</li>');//显示加载动画
                $('.housenum em').html(0);
                total = 0; //总记录数
            }
        },
        complete:function(){ //生成分页条
            getPageBar();
            fun();
        },
        error:function(){
            // alert("数据加载失败");
        }
    });
}
//获取分页条
function getPageBar(){
    //页码大于最大页数
    if(curPage>totalPage) curPage=totalPage;
    //页码小于1
    if(curPage<1) curPage=1;
    pageStr = '<div class="amount"><i>共'+total+'条</i><i>'+curPage+"/"+totalPage+'</i></div>';

    //如果是第一页
    if(curPage==1){
        pageStr += "<span>首页</span><span>上一页</span>";
        // alert("已经是首页!")
    }else{
        pageStr += "<span><a href='javascript:void(0)' rel='1'>首页</a></span><span><a href='javascript:void(0)' rel='"+(curPage-1)+"'>上一页</a></span>";
    }

    //如果是最后页
    if(curPage>=totalPage){
        pageStr += "<span>下一页</span><span>尾页</span>";
        // alert("已经最后一页!")
    }else{
        pageStr += "<span><a href='javascript:void(0)' rel='"+(parseInt(curPage)+1)+"'> 下一页</a></span><span><a href='javascript:void(0)' rel='"+totalPage+"'>尾页</a></span>";
    }
    $("#pagecount").html(pageStr);
}
$(function(){
    getData(1);

});
function fun(){
    $("#pagecount span a").on('click',function(){
        var rel = $(this).attr("rel");
        // alert(rel)
        if(rel){
            getData(rel,dataID);
        }
    });
}
/*-------------------------------------------------------------------------*/




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

/* 点击弹出对应信息 */
function  createInfoWindow(data){   //自定义覆盖物
    // console.log(data)
    var pri = '待定';
    if(data.sale_price != 0){
        pri = data.sale_price + data.price_unit;
    }
    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  target="_blank" href="/house/'+data.id+'/"><img src="'+data.thumb+'" alt="" width="100%" height="100%;"></a></p>'+
        '<p style="margin-top:8px;"><a style="font-size:16px; color:#333;" target="_blank"  href="/house/'+data.id+'/">'+data.name+'</a><span style="font-size:12px; color:#888; padding-left:8px;">['+data.city_name+']</span></p>'+
        '<p style="margin-top:5px;"><span><em style="font-size:18px; color:#f00; font-style:normal;">'+pri+'</em></span></p>'+
        '</div>'
    );
    return iw
}