var map;
var transit;
var drivingRoute;
function initialize() {
    map = new BMap.Map('map');
    map.centerAndZoom(document.getElementById("txtCity").value, 13);
    map.enableScrollWheelZoom();
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.ScaleControl());
    map.addControl(new BMap.OverviewMapControl());
    map.addControl(new BMap.MapTypeControl());
    setTimeout(init(), 5000);
}

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('../../Themes/Default/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("../../Themes/Default/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("../../Themes/Default/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: 560,
        height: 310,
        enableCloseOnClick: true
    };
    $.get("/Common/JSONHandler.ashx", { Key: "GetCustomerById", id: khid })
    .done(function (result) {
        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/ShowCustomerView.aspx?CustomerId=" + khid + "'";

        $("#khcontent").find("td").each(function () {
            $(this).text("");
        });
        $name.text("");
        $tel.text("");
        $page.text("");
        $address.text("");
        $lastgd.text("");
        $xfje.text("");
        $lasthf.text("");
        $xfcs.text("");
        $lastts.text("");
        $tsnum.text("");

        if (typeof result != 'undefine' || result) {
            $name.text(result.Name);
            $tel.text(result.CompanyTel1);
            $page.text(result.Homepage);
            $address.text(result.CompanyAddress);
            $lastgd.text(result.FirstDocumentary);
            //$xfje.text("");
            $lasthf.text(result.LastVisit);
            //$xfcs.text("");
            $lastts.text(result.LastComplaint);
            $tsnum.text(result.ComplaintAllNum);
            $("#customerInfo").attr("onclick", link);
        }

        var infoWin = new BMap.InfoWindow($("#khcontent").html(), opt);
        infoWin.setTitle($("#khname").html());
        marker.openInfoWindow(infoWin);

    }).fail(function (relust) {
        alert("客户详情：网络繁忙，请稍后再试！");
    })
}

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) {
            var lng = poi.point.lng;
            var lat = poi.point.lat;
            $(html).append("<input type=\"button\" class=\"setPoint btn btn-primary\" ref=\"ok\" style=\"width:100px; height:22px;  padding:0px;\" value=\"确定\" />");
            //            $(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) {
    $(".setPoint").each(function () {
        $(this).click(function () {
            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();
        });
    });
}

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());
    this._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) {
    //修改图标
    //    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" class="common">地 址：</td>');
    html.push('      <td>' + objm.address + '</td>');
    html.push('  </tr>');
    html.push('  <tr>');
    html.push('      <td  align="left" class="common">电 话：</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 infoWin = new BMap.InfoWindow(html.join(""), opt); // 创建信息窗口对象    
    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.addEventListener("dragend", function () {
        if (!infoWin.isOpen()) {
            this.openInfoWindow(e.infoWin); // 打开信息窗口 
            setPoint(marker.getPosition().lng, marker.getPosition().lat);
        }
    });
    marker.addEventListener("click", function () {
        if (!infoWin.isOpen()) {
            this.openInfoWindow(infoWin);
            setPoint(marker.getPosition().lng, marker.getPosition().lat);
        }
    });
    var label = new BMap.Label(objm.name != "" ? objm.name : "拖拽确定打标定位。", { offset: new BMap.Size(20, -10) });
    marker.setLabel(label); // 创建标注标题到地图
    // 将标注添加到地图中 
    map.addOverlay(marker);
    map.setDefaultCursor(_preCursor);
    map.removeEventListener("mousedown", showInfo);
}

//将标注显示在地图
function addMarker2(name, lng, lat, address) {
    var opt = {
        width: 260, // 信息窗口宽度 
        height: 120, // 信息窗口高度    
        enableCloseOnClick: true,
        title: name
    };
    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>' + address + '</td>');
    html.push('  </tr>');
    html.push('  <tr>');
    html.push('      <td  align="left" class="common">电 话：</td>');
    html.push('      <td>123123</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 point = new BMap.Point(lng, lat);
    var marker = new BMap.Marker(point);
    //可托拽的标注
    marker.enableDragging();
    //监听标注事件
    marker.addEventListener("dragend", function () {
        if (!infoWin.isOpen()) {
            this.openInfoWindow(e.infoWin); // 打开信息窗口 
            setPoint(marker.getPosition().lng, marker.getPosition().lat);
        }
    });
    marker.addEventListener("click", function () {
        if (!infoWin.isOpen()) {
            this.openInfoWindow(infoWin);
            setPoint(marker.getPosition().lng, marker.getPosition().lat);
        }
    });

    marker.setTitle(name);
    var label = new BMap.Label(name, { position: point, offset: new BMap.Size(20, -10) });
    marker.setLabel(label);
    // 将标注添加到地图中 
    map.addOverlay(marker);
}

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() {
    map.clearOverlays();
}

function loadScript() {
    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 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 () {
    //单位信息
    $.ajax({ url: "/Common/JSONHandler.ashx",
        data: { Key: "GetCompanyInfo" },
        success: function (res) {
            if (res != null) {
                $("#txtCountry").val(res.CountryName);
                $("#txtProvince").val(res.ProvinceName);
                $("#txtCity").val(res.CityName);
                $("#txtArea").val(res.AreaName);
                $("#txtAddress").val(res.Address);
                $("#txtCompanyName").val(res.CompanyName);
                $("#txtTel").val(res.Tel400);
                $("#txtId").val(res.Id);
                $("#txtLng").val(res.Lng);
                $("#txtLat").val(res.Lat);
                $("#txt_start").val(res.Address);
            }
        },
        error: function (e)
        { alert("网络繁忙，请稍后再试！"); }
    });
})
//获取参数
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;
}