var map, mapvmInput = avalon.vmodels.InputCustomer;
var transit;
var drivingRoute;
function initialize() {
    if (!mapvmInput) map = avalon.vmodels.InputCustomer;
    map = new BMap.Map('map');
    var city, address, lng, lat;
    //编辑或输入
    if (mapvmInput) {
        city = mapvmInput.customerEntity.CompanyCityDisplay;
        address = mapvmInput.customerEntity.CompanyAddress;
        lng = mapvmInput.customerEntity.Lng;
        lat = mapvmInput.customerEntity.Lat;
        if (!city || city == "") city = "南宁市";
        console.log(city + ":" + address);
        mapvmInput.addressKey = address;
        if (lng) {
            var p = new BMap.Point(lng, lat);
            map.centerAndZoom(p, 12);
            addMarker2(mapvmInput.customerEntity.Name, lng, lat, address);
        }
        else {
            if (address && address != "") seekLocal(city, address, false);
            map.centerAndZoom(city, 12);
        }
    } else {
        if ($("#txtCity").length>0) {
            city = $("#txtCity").val();
        } else {
            city = "南宁";
        }
        map.centerAndZoom(city, 12);
        setTimeout(init, 1000);
    }
    map.enableScrollWheelZoom();
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.ScaleControl());
    map.addControl(new BMap.OverviewMapControl());
    map.addControl(new BMap.MapTypeControl());
    
}

function init() {
    if ($("#ul_kh").children("li").length > 0) {
        add_marker();
    }
    else {
        //$("#btn_seek").click();
    }
    transit = new BMap.TransitRoute(map, { renderOptions: { map: map, panel: "divline", autoViewport: true } });
    drivingRoute = new BMap.DrivingRoute(map, { renderOptions: { map: map, panel: "divline", autoViewport: true } });
}

function myCityCallback(result) {
    var cityName = result.name;
    map.setCenter(cityName);
    map.setCurrentCity(cityName);
}
//将标注显示在地图
function addMarker(khid, name, lng, lat, indexM, address) {
    var icon = new BMap.Icon('/Content/Themes/Base/Images/pin.png', new BMap.Size(21, 32), {//图标大小 
        imageOffset: new BMap.Size(0 - indexM * 21, 0),   // 设置图片偏移 
        anchor: new BMap.Size(10, 30), //表示图片相对于所加的点的位置
        infoWindowAnchor: new BMap.Size(10, 0)//控制信息窗口开启的位置
    })
    var point = new BMap.Point(lng, lat);

    var marker = new BMap.Marker(point, { icon: icon });
    marker.setTitle(name);
    var label = new BMap.Label(name, { position: point, offset: new BMap.Size(20, -10) });
    marker.setLabel(label);
    marker.addEventListener("click", function () {
        document.getElementById("txt_start").value = document.getElementById("txtAddress").value;
        document.getElementById("txt_end").value = address;
        document.getElementById("txt_end").setAttribute("lng", lng);
        document.getElementById("txt_end").setAttribute("lat", lat);
        newInfoWindow(this, khid);
    });
    // 将标注添加到地图中 
    map.addOverlay(marker);
    //鼠标移到标注
    marker.addEventListener("mouseover", function () {
        this.setIcon(new BMap.Icon("/Content/Themes/Base/Images/pin.png", new BMap.Size(21, 32), {
            imageOffset: new BMap.Size(0 - indexM * 21, -34),   // 设置图片偏移 
            anchor: new BMap.Size(10, 30), //表示图片相对于所加的点的位置
            infoWindowAnchor: new BMap.Size(10, 0)//控制信息窗口开启的位置
        }));
    });
    //鼠标离开标注
    marker.addEventListener("onmouseout", function () {
        this.setIcon(new BMap.Icon("/Content/Themes/Base/Images/pin.png", new BMap.Size(21, 32), {
            imageOffset: new BMap.Size(0 - indexM * 21, 0),   // 设置图片偏移 
            anchor: new BMap.Size(10, 30), //表示图片相对于所加的点的位置
            infoWindowAnchor: new BMap.Size(10, 0)//控制信息窗口开启的位置
        }));
    });
}

//设置线路搜索值
function getOneMapOverlay(khid, name, lng, lat) {
    var lays = map.getOverlays();
    for (var i = 0; i < lays.length; i++) {
        try {
            if (lays[i].getPosition() !== null) {
                var point = lays[i].getPosition();
                if (lng == point.lng && lat == point.lat) {
                    document.getElementById("txt_start").value = document.getElementById("txtAddress").value;
                    document.getElementById("txt_end").value = name;
                    document.getElementById("txt_end").setAttribute("lng", point.lng);
                    document.getElementById("txt_end").setAttribute("lat", point.lat);
                    newInfoWindow(lays[i], khid);
                }
            }
        }
        catch (e) { }
    }
}


function newInfoWindow(marker, khid) {
    var opt = {
        width: 365,
        height: 210,
        enableCloseOnClick: true
    };
    var obj = $("#" + khid);
    if (obj != undefined && obj != null) {
        var $name = $("#khname").children("span");
        var $tel = $("#tel");
        var $page = $("#page");
        var $address = $("#address");
        var $lastgd = $("#lastgd");
        var $xfje = $("#xfje");
        var $lasthf = $("#lasthf");
        var $xfcs = $("#xfcs");
        var $lastts = $("#lastts");
        var $tsnum = $("#tsnum");
        var link = "window.location.href='#/Customer/DetailCustomer/" + khid + "'";

        $("#khcontent").find("td").each(function () {
            $(this).text("");
        });
        $name.text(obj.attr("title"));
        $tel.text(obj.attr("tel"));
        $page.text(obj.attr("page"));
        $address.text(obj.attr("aes"));
        $lastgd.text(obj.attr("tlastgdel"));
        //$xfje.text("");
        $lasthf.text(obj.attr("lasthf"));
        //$xfcs.text("");
        $lastts.text(obj.attr("lastts"));
        $tsnum.text(obj.attr("tsnum"));
        $("#customerInfo").attr("onclick", link);
    }
    var infoWin = new BMap.InfoWindow($("#khcontent").html(), opt);
    infoWin.setTitle($("#khname").html());
    marker.openInfoWindow(infoWin);
}

function closeInfoWindow() {
    var lays = map.getOverlays();
    for (var i = 0; i < lays.length; i++) {
        try {
            if (lays[i].getPosition() !== null) {
                lays[i].closeInfoWindow();
            }
        }
        catch (e) { }
    }
}

//搜索
function seekLocal(city, address, sel) {
    var seek = 0;
    var local = new BMap.LocalSearch(city, {
        renderOptions: {
            map: map,
            autoViewport: true,
            selectFirstResult: sel,
            panel: "seekpanel"
        },
        onSearchComplete: function (results) {
            
        },
        onMarkersSet: function (pois) {
        },
        onInfoHtmlSet: function (poi, html) {
            $(html).append("<input type=\"button\" class=\"setPoint btn btn-primary\" ref=\"ok\" style=\"width:100px; height:22px;  padding:0px;margin-left:0px;margin-top:10px;\" value=\"确定\" />").click(function () {
                $("#lng").val(poi.point.lng + "," + poi.point.lat);
                setPoint(poi.lng, poi.lat, poi);
            });
            //$(html).append("<input type=\"button\" class=\"setPoint\" ref=\"ca\" style=\"width:100px; height:22px; margin-left:20px; padding:0px;\" value=\"取消\" />");
            //setPoint(lng, lat);
        }
    });
    local.search(address);
}


//确定保存
function setPoint(lng, lat,poi) {
    mapvmInput.customerEntity.Lng = lng;
    mapvmInput.customerEntity.Lat = lat;
    $("#lng").val(lng + "," + lat);
    console.log(poi);
    if (poi) {
        mapvmInput.customerEntity.CompanyAddress = poi.address;

    }
    if (mapvmInput) mapvmInput.$mapwin.close();
    /*
    $(".setPoint").each(function () {
        $(this).click(function () {
            //var ref = $(this).attr("ref");
            //if (ref == "ok") {
            $("#lng").val(lng + "," + lat);
            mapvmInput.customerEntity.Lng = lng;
            mapvmInput.customerEntity.Lat = lat;
            //if ($(window.parent.document).find("#ctl00_ContentPlaceHolder1_txtLng")) {
            //    $(window.parent.document).find("#ctl00_ContentPlaceHolder1_txtLng").attr("value", lng);
            //    $(window.parent.document).find("#ctl00_ContentPlaceHolder1_txtLat").attr("value", lat);
            //}
            //if ($(window.parent.document).find("#ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_txtLng")) {
            //    $(window.parent.document).find("#ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_txtLng").attr("value", lng);
            //    $(window.parent.document).find("#ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_txtLat").attr("value", lat);
            //}
            //}
            //$(window.parent.document).find("#ContentMessageBox2_btnHeaderCloseContentMessageBox").click();
            $(".aui_buttons button").click();
        });
    });
    */
}

function addMoveMarkerIco(khid, city, name) {
    this._preCursor = this.map.getDefaultCursor(); //记录当前的鼠标cursor
    this.map.setDefaultCursor("url('http://api0.map.bdimg.com/images/marker_red_sprite.png'), default"); //设置鼠标样式  
}


var objm;
//打标
function addMoveMarker(models) {
    // map.setCenter(modelsss.city);
    objm = models;
    //var marker = new BMap.Marker(map.getCenter());
    if (!window._preCursor) window._preCursor = this.map.getDefaultCursor(); //记录当前的鼠标cursor
    this.map.setDefaultCursor("url('http://api0.map.bdimg.com/images/marker_red_sprite.png'), default"); //设置鼠标样式  
    map.addEventListener("mousedown", showInfo);
}
//打标
function showInfo(e) {
    //先设置鼠标默认状态并移除事件
    map.setDefaultCursor(window._preCursor);
    map.removeEventListener("mousedown",showInfo);
    //修改图标
    //    var icon = new BMap.Icon('pin.png', new BMap.Size(20, 32), {
    //        anchor: new BMap.Size(10, 30),
    //        infoWindowAnchor: new BMap.Size(10, 0)
    //    })
    var opt = {
        width: 260, // 信息窗口宽度 
        height: 120, // 信息窗口高度    
        enableCloseOnClick: true,
        title: objm.name
    };
    var html = [];
    html.push('<table border="0" cellpadding="1" cellspacing="1" width="100%" >');
    html.push('  <tr>');
    html.push('      <td align="left" style="width: 45px;">地 址：</td>');
    html.push('      <td class="setPointAddress">正在查询该坐标地址...</td>');
    html.push('  </tr>');
    //html.push('  <tr>');
    //html.push('      <td  align="left">电 话：</td>');
    //html.push('      <td>' + objm.tel + '</td>');
    //html.push('  </tr>');
    html.push('  <tr>');
    html.push('	     <td  align="center" colspan="2">');
    html.push('          <input type=\"button\" class=\"setPoint  btn btn-primary\" ref=\"ok\" style=\"width:150px; height:22px;  padding:0px;\" value=\"确定打标定位此处？\" />&nbsp;&nbsp;');
    //    html.push('		    <input type=\"button\" class=\"setPoint\" ref=\"ca\" style=\"width:100px; height:22px; margin-left:20px; padding:0px;\" value=\"取消\" />');
    html.push('	     </td>');
    html.push('  </tr>');
    html.push('</table>');
    var infoObj = $(html.join("")).appendTo(document.body);
    var infoWin = new BMap.InfoWindow(infoObj[0], opt); // 创建信息窗口对象 
    var warning;
    infoObj.find(".setPoint").click(function () {
        if (!marker.local) {
            warning = messageBox.warning("坐标地址正在查询中，请稍后。");
            return;
        }
        var point = marker.getPosition();
        setPoint(point.lng, point.lat, marker.local);
        infoObj.remove();
        map.removeOverlay(marker);
    });
    var pt = new BMap.Point(e.point.lng, e.point.lat);
    var marker = new BMap.Marker(pt, { offset: new BMap.Size(8, 26) });  // 创建标注
    //可托拽的标注
    marker.enableDragging();
    marker.local = null;
    var myGeo = new BMap.Geocoder();//坐标解析类
    _getLocal(e.point);
    //监听标注事件
    marker.addEventListener("dragend", function () {
        if (!infoWin.isOpen()) {
            this.openInfoWindow(infoWin); // 打开信息窗口
        }
        marker.local = null;
        _getLocal(marker.getPosition());
    });
    marker.addEventListener("click", function () {
        if (!infoWin.isOpen()) {
            this.openInfoWindow(infoWin);
        }
    });

    var label = new BMap.Label(objm.name != "" ? objm.name : "拖拽确定打标定位。", { offset: new BMap.Size(20, -10) });
    marker.setLabel(label); // 创建标注标题到地图
    // 将标注添加到地图中 
    map.addOverlay(marker);
    marker.openInfoWindow(infoWin);
    function _getLocal(point) {
        infoObj.find(".setPointAddress").text("正在查询该坐标地址...");
        myGeo.getLocation(point, function (d) {
            marker.local = d;
            infoObj.find(".setPointAddress").text(d.address);
            if (warning) warning.close();
        });
    }
}

//将标注显示在地图
function addMarker2(name, lng, lat, address) {
    var opt = {
        width: 260, // 信息窗口宽度 
        height: 120, // 信息窗口高度    
        enableCloseOnClick: true,
        title: name,
        tel: mapvmInput ? mapvmInput.customerEntity.CompanyTel1 : ""
    };
    var html = [];
    html.push('<table border="0" cellpadding="1" cellspacing="1" >');
    html.push('  <tr>');
    html.push('      <td align="left" class="common">地 址：</td>');
    html.push('      <td class="setPointAddress">' + address + '</td>');
    html.push('  </tr>');
    html.push('  <tr>');
    html.push('      <td  align="left" class="common">电 话：</td>');
    html.push('      <td>'+ opt.tel +'</td>');
    html.push('  </tr>');
    html.push('  <tr>');
    html.push('	     <td  align="center" colspan="2">');
    html.push('          <input type=\"button\" class=\"setPoint btn btn-primary\" ref=\"ok\" style=\"width:150px; height:22px;  padding:0px;\" value=\"确定打标定位此处？\" />&nbsp;&nbsp;');
    //    html.push('		    <input type=\"button\" class=\"setPoint\" ref=\"ca\" style=\"width:100px; height:22px; margin-left:20px; padding:0px;\" value=\"取消\" />');
    html.push('	     </td>');
    html.push('  </tr>');
    html.push('</table>');
    //var infoWin = new BMap.InfoWindow(html.join(""), opt); // 创建信息窗口对象
    var infoObj = $(html.join("")).appendTo(document.body);
    var infoWin = new BMap.InfoWindow(infoObj[0], opt); // 创建信息窗口对象 
    var warning;
    infoObj.find(".setPoint").click(function () {
        if (!marker.local) {
            warning = messageBox.warning("坐标地址正在查询中，请稍后。");
            return;
        }
        var point = marker.getPosition();
        setPoint(point.lng, point.lat, marker.local);
        infoObj.remove();
        map.removeOverlay(marker);
    });
    var myGeo = new BMap.Geocoder();
    var point = new BMap.Point(lng, lat);
    var marker = new BMap.Marker(point);
    marker.local = { address: address };
    //可托拽的标注
    marker.enableDragging();
    //监听标注事件
    marker.addEventListener("dragend", function () {
        if (!infoWin.isOpen()) {
            this.openInfoWindow(infoWin); // 打开信息窗口 
            //setPoint(marker.getPosition().lng, marker.getPosition().lat);
            _getLocal(marker.getPosition());
        }
    });
    marker.addEventListener("click", function () {
        if (!infoWin.isOpen()) {
            this.openInfoWindow(infoWin);
        }
    });
    marker.setTitle(name);
    var label = new BMap.Label(name, { position: point, offset: new BMap.Size(20, -10) });
    marker.setLabel(label);
    // 将标注添加到地图中 
    map.addOverlay(marker);
    function _getLocal(point) {
        infoObj.find(".setPointAddress").text("正在查询该坐标地址...");
        myGeo.getLocation(point, function (d) {
            marker.local = d;
            infoObj.find(".setPointAddress").text(d.address);
            if (warning) warning.close();
        });
    }
}

function codeAddress(city, address) {

    var myGeo = new BMap.Geocoder();
    myGeo.getPoint(address, function (point) {
        if (point) {
            addMarker(point);
        }
    }, city);

}
//公车线路查询-ip定位查询
//城市（起），经度（起），纬度（起），经度（终），纬度（终）
function seekBusLine(city, lng1, lat1, lng2, lat2) {
    map.clearOverlays(); //清除地图上所有的覆盖物  
    transit.setLocation(city);
    transit.setSearchCompleteCallback(function (results) {
        if (transit.getStatus() == 5) {
            $("#v_msg").html("请选择准确的起点、途经点或终点");
        } else if (transit.getStatus() == 3) {
            $("#v_msg").html("导航结果未知");
        } else if (transit.getStatus() == BMAP_STATUS_SUCCESS) {

        }
    });
    var point1 = new BMap.Point(lng1, lat1);
    var point2 = new BMap.Point(lng2, lat2);
    $("#v_msg").html("");
    transit.search(point1, point2);
}
//公车线路查询-地址查询
//城市，起始地址，终点地址
function seekBusLineAddress(city, state, end) {
    map.clearOverlays(); //清除地图上所有的覆盖物  
    transit.setLocation(city);
    transit.setSearchCompleteCallback(function (results) {
        if (transit.getStatus() == 5) {
            $("#v_msg").html("请选择准确的起点、途经点或终点");
        } else if (transit.getStatus() == 3) {
            $("#v_msg").html("导航结果未知");
        } else if (transit.getStatus() == BMAP_STATUS_SUCCESS) {

        }
    });
    $("#v_msg").html("");
    transit.search(state, end);
}

//驾车线路查询-ip定位查询
//地址（起），经度（起），纬度（起），经度（终），纬度（终）
function seekCarLine(city, lng1, lat1, lng2, lat2) {
    map.clearOverlays(); //清除地图上所有的覆盖物  
    var point1 = new BMap.Point(lng1, lat1);
    var point2 = new BMap.Point(lng2, lat2);
    drivingRoute.search(point1, point2);
    $("#v_msg").html("");
}
//驾车线路查询-地址查询
//地址（起），经度（起），纬度（起），经度（终），纬度（终）
function seekCarLineAddress(state, end) {
    map.clearOverlays(); //清除地图上所有的覆盖物  
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 12);
    var transit = new BMap.DrivingRoute(map, {
        renderOptions: {
            map: map,
            panel: "divline",
            enableDragging: true //起终点可进行拖拽
        }
    })
    transit.search(state, end);
    $("#v_msg").html("");
}

function clearMarker() {
    if (map) map.clearOverlays();
}

function loadScript() {
    /*
    if (window.BMap) {
        initialize();
        return;
    }
    */
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://api.map.baidu.com/api?v=1.5&ak=225ec0d19b6a2e29301640397eab4e50&callback=initialize"; //此为v1.5版本的引用方式
    //script.src = "http://api.map.baidu.com/api?v=2.0&ak=225ec0d19b6a2e29301640397eab4e50&callback=initialize"; //此为v2.0版本的引用方式
    document.body.appendChild(script);
}

//IP定位获取当前城市
function myCity() {
    // 百度地图API功能
    var map = new BMap.Map("map");
    var point = new BMap.Point(116.331398, 39.897445);
    map.centerAndZoom(point, 12);

    function myFun(result) {
        var cityName = result.name;
        map.setCenter(cityName);
        alert("当前所在城市：" + cityName);
    }
    var myCity = new BMap.LocalCity();
    myCity.get(myFun);
}

function MyIp() {
    // 百度地图API功能
    var point = new BMap.Point(116.331398, 39.897445);
    map.centerAndZoom(point, 12);
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            var mk = new BMap.Marker(r.point);
            map.addOverlay(mk);
            map.panTo(r.point);
            alert('您的位置：' + r.point.lng + ',' + r.point.lat);
        }
        else {
            alert('failed' + this.getStatus());
        }
    }, { enableHighAccuracy: true })
}
//地址解析
function addOverlay(city, address) {
    // 百度地图API功能
    var map = new BMap.Map("map");
    var point = new BMap.Point(116.331398, 39.897445);
    map.centerAndZoom(point, 12);
    // 创建地址解析器实例
    var myGeo = new BMap.Geocoder();
    // 将地址解析结果显示在地图上,并调整地图视野
    myGeo.getPoint(address, function (point) {
        if (point) {
            map.centerAndZoom(point, 16);
            //map.addOverlay(new BMap.Marker(point));//定标
        }
    }, city);
}

//获取参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return decodeURI(r[2]);
    return
    null;
}