﻿// 共用函式區
function GetWindowCurrentSize() { //取得目前視窗大小
    var bodyCW, bodyCH;
    if (window.innerWidth) {
        bodyCW = window.innerWidth;
        bodyCH = window.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientWidth) {
        bodyCW = document.documentElement.clientWidth;
        bodyCH = document.documentElement.clientHeight;
    }
    else if (document.body) {
        bodyCW = document.body.clientWidth;
        bodyCH = document.body.clientHeight;
    }
    return [bodyCW, bodyCH];
}

function GetPolyLineNode(obj) { // 取得GWPolyLine物件的所有節點坐標
    var a = new Array();
    var Pt = obj.StPoint;
    a.push([Pt.iX, Pt.iY]);
    while (1) {
        a.push([Pt.iX, Pt.iY]);
        if (Pt == obj.LtPoint)
            break;
        Pt = Pt.oNextPoint;
    }
    return a;
}

function GetMapCenterXY(map) {  // 取得目前地圖中心點坐標
    var a = new GWMapViewInfo();
    map.GetMapViewInfo(a);
    return [(a.iRTx + a.iLBx) / 2, (a.iRTy + a.iLBy) / 2, a.iScale];
}

function InitUI() {
    //ShowLoader(SYSMSG.POILISTLOADMSG, $('TabContent1'), 'POILISTLOADER');
    InitMapToolBar();
    InitTabBtn();
    setTimeout("TabControl(1);", 500);
    setTimeout("InitEditorUI();", 2000);
    //TabControl(1);
    document.title = SYSMSG.HTMLTITLE;
    $('CopyRight').innerHTML = SYSMSG.COPYRIGHT;
    $('MeasureDialog').innerHTML = SYSMSG.MEASUREDIALOG;
    $('SaveLinkDialog').innerHTML = SYSMSG.SAVELINKDIALOG;
    $('MapBookMarkDialog').innerHTML = SYSMSG.BOOKMARKDIALOG;
    $('MapBookMarks').innerHTML = SYSMSG.BOOKMARKDEMO;
    $('TabContent1').innerHTML = SYSMSG.WIKIGPS;
    $('TabContent5').innerHTML = SYSMSG.ROUTINGMSG;
    $('TabContent6').innerHTML = '<div style="padding:5px 5px 5px 5px;text-align:left;width:240px;cursor:pointer;"><span class="GrayText">以下為地圖Mashup範例：</span></div><br />';
    $('TabContent6').innerHTML += '<div style="text-align:center;"><img src="Images/Mashup01.gif" style="cursor:pointer;" title="媽祖遶境即時追蹤" onclick="GetMashup(1);" /><br /><br /><img src="Images/Mashup02.gif" style="cursor:pointer;" title="flickr.com" onclick="GetMashup(2);" /><br /><br /><img src="Images/Mashup03.gif" style="cursor:pointer;" title="flickr.com" onclick="GetMashup(3);" /></div>';
    //$('TabContent7').innerHTML = '<div style="padding:5px 5px 5px 5px;text-align:left;width:240px;cursor:pointer;"><span class="GrayText">以下為WiKiGPS範例：</span></div><br />';
    //$('TabContent7').innerHTML += '<div style="text-align:center;"><img src="Images/wikiGPS/7-11.png" style="cursor:pointer;" title="便利商店" onclick="SearchWikiPoiData(49,' + "'7-ELEVEN'" + ');" /><br /><br /><img src="Images/wikiGPS/Family.png" style="cursor:pointer;" title="便利商店" onclick="SearchWikiPoiData(49,' + "'全家'" + ');" /> <br /><br /></div>';
    //$('TabContent7').innerHTML = SYSMSG.WIKIGPS;
    $('TabContent7').innerHTML = SYSMSG.SPATIALANALYSIS;

    map.SwitchRCMenu(true);
    h = '<div id="RCMenu"><span class="GrayText">設為起點</span><br /><span class="GrayText" style="border-bottom:solid 1px #999999;padding-bottom:3px;">以下為WiKiGPS範例：</span><br /><span onclick="this.parentNode.parentNode.style.visibility=\'hidden\';">關閉選單</span></div>';
    map.SetRCMenuContent(h);

    UpdateStatusBar();
    map.SetCBFunction('MapMove', WikiPOIList);
    map.SetCBFunction('GetCursorXY', UpdateStatusBar);
    map.SetCBFunction('PlacardClickEvent', PlacardClickEvent);
    $('MeasureDialog').style.zIndex = '999';
    $('MapBookMarkDialog').style.zIndex = '999';
}

function InitTabBtn() {
    var s = '<table cellpadding="0" cellspacing="0"><tr>';
    for (var i = 1; i < SYSMSG.TABBTNNAME.length + 1; i++) {
        s += SYSMSG.TABBTNTEMPLATE.evaluate({ num: i, name: SYSMSG.TABBTNNAME[i - 1] });
    }
    s += '</tr></table>';
    $('TabBtnGroup').innerHTML = s;
}

function ClickEvent_Buffer(x, y, event) {
    var point;
    point = 'POINT(' + x + ' ' + y + ')';
    var mgmap1 = new GWMapIcon('Images/EditIcon_00.gif', 20, 20, 17, 17);
    //圖標點陰影樣式
    var mgmap2 = new GWMapIcon('', 30, 30, 15, 15);
    map.AddPlacard(1, mgmap1, mgmap2, 1, x, y, '', 0);
    map.ReflashPlacard();
    var aj = new Ajax.Request("PostGIS_Services.asmx/pgBuffer_asGeoJSON",
                      { postBody: "{KWT_String:'" + point + "',radius:" + $('Buffer').value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: BufferDone });

    map.SetCBFunction("ClickEvent", '');
}

function BufferDone(val) {
    var res = eval("[" + val.responseText + "]");
    var e = eval("[" + res[0].d + "]");

    var p1 = new GWPolyLine(new GWPoint(e[0].coordinates[0][0][0], e[0].coordinates[0][0][1]), 2, "rgba(255,0,0,0.5)", 2);
    for (var i = 1; i < e[0].coordinates[0].length; i++) {
        p1.AddPoint(new GWPoint(e[0].coordinates[0][i][0], e[0].coordinates[0][i][1]));
    }
    map.AddPolyLine(p1);
    map.ReflashPolyLine();
}

function MapActionCreate_Buffer(PID, GWPolyline) {
    var pt = GWPolyline.StPoint;
    var polygon, StPoint, polylineStr;
    polygon = 'POLYGON((';
    polylineStr = 'LINESTRING(';
    if (pt != null)
        StPoint = pt;
    while (pt != null) {
        polylineStr += pt.iX.toString() + ' ' + pt.iY.toString() + ',';
        polygon += pt.iX.toString() + ' ' + pt.iY.toString() + ',';
        pt = pt.oNextPoint;
    }
    polylineStr = polylineStr.substring(0, polylineStr.length - 1) + ")";
    polygon += GWPolyline.StPoint.iX + ' ' + GWPolyline.StPoint.iY + '))';
    map.SetMapAction(0);
    map.SetCBFunction("MapActionCreate", '');

    if (GWPolyline.iType == 2) {
        var aj = new Ajax.Request("PostGIS_Services.asmx/pgBuffer_asGeoJSON",
                  { postBody: "{KWT_String:'" + polygon + "',radius:" + $('Buffer').value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: BufferDone, onFailure: ReadPOIListFail });

    }
    else {
        var aj = new Ajax.Request("PostGIS_Services.asmx/pgBuffer_asGeoJSON",
                  { postBody: "{KWT_String:'" + polylineStr + "',radius:" + $('Buffer').value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: BufferDone, onFailure: ReadPOIListFail });

    }
}
var polylineStr_i;
function MapActionCreate_Interplate(PID, GWPolyline) {
    var pt = GWPolyline.StPoint;
    var StPoint;
    polylineStr_i = 'LINESTRING(';
    if (pt != null)
        StPoint = pt;
    while (pt != null) {
        polylineStr_i += pt.iX.toString() + ' ' + pt.iY.toString() + ',';
        pt = pt.oNextPoint;
    }
    polylineStr_i = polylineStr_i.substring(0, polylineStr_i.length - 1) + ")";
    map.SetMapAction(0);
    map.SetCBFunction("MapActionCreate", '');

}

function Generlization() {
    if ($('TownShape').options[$('TownShape').selectedIndex].value=="-1") return;
    var aj = new Ajax.Request("PostGIS_Services.asmx/pgGetGeneralizeByCityCode",
                          { postBody: "{CityCode:'" + $('TownShape').options[$('TownShape').selectedIndex].value + "',level:" + $("GeneralizeValue").value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: GenerlizationDone, onFailure: ReadPOIListFail }, true);

}
function GenerlizationDone(req) {
    map.RemoveAllPolyLine();
    var res = eval("[" + req.responseText + "]");
    var e = eval(res[0].d);

    var minX = 180, minY = 90, maxX = -180, maxY = -90;
    var cX = 0, cY = 0, n = 1;
    var p1 = new GWPolyLine(new GWPoint(e[0].coordinates[0][0][0], e[0].coordinates[0][0][1]), 5, "rgba(255,0,0,0.5)", 1);
    cX = e[0].coordinates[0][0][0];
    cY = e[0].coordinates[0][0][1];
    for (var i = 1; i < e[0].coordinates[0].length; i++) {
        if (minX > e[0].coordinates[0][i][0]) minX = e[0].coordinates[0][i][0];
        if (minY > e[0].coordinates[0][i][1]) minY = e[0].coordinates[0][i][1];
        if (maxX < e[0].coordinates[0][i][0]) maxX = e[0].coordinates[0][i][0];
        if (maxY < e[0].coordinates[0][i][1]) maxY = e[0].coordinates[0][i][1];
        cX += e[0].coordinates[0][i][0];
        cY += e[0].coordinates[0][i][1];
        n += 1;
        p1.AddPoint(new GWPoint(e[0].coordinates[0][i][0], e[0].coordinates[0][i][1]));
    }

    cX = cX / n;
    cY = cY / n;
    var zoom = true;
    var level = 3;
    var mvi = new GWMapViewInfo();
    var Lx, Ly, Rx, Ry;
    while (zoom && (level <= 10)) {
        map.MoveToRXY(cX, cY, level, false);
        map.GetMapViewInfo(mvi);
        //Rx:左上x,Ry:左上y,Lx:右下x,Ly:左下y
        Rx = mvi.iLBx;
        Ly = mvi.iLBy;
        Lx = mvi.iRTx;
        Ry = mvi.iRTy;

        if (Rx >= maxX && Lx <= minX && Ry >= maxY && Ly <= minY)
            zoom = false;

        level += 1;
    }
    map.AddPolyLine(p1);
    map.ReflashPolyLine();
}

function GetInterpolate() {
    var aj = new Ajax.Request("PostGIS_Services.asmx/pgLineInterpolate_asGeoJSON",
                  { postBody: "{KWT_String:'" + polylineStr_i + "',ratho:" + $('interplateValue').value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: DrawLineInterpolate });
}
function DrawLineInterpolate(val) {
    var res = eval("[" + val.responseText + "]");
    var xy = eval('[' + res[0].d + ']');
    // alert(res.coordinates);
    var x = xy[0].coordinates[0];
    var y = xy[0].coordinates[1];
    map.RemoveAllPlacard();
    var mgmap1 = new GWMapIcon('http://geoweb.tw/image/MIcon01.png', 43, 26, 1, 26);
    var mgmap2 = new GWMapIcon('', 43, 26, 21, 13);
    map.MoveTo(x, y, true);
    map.AddPlacard(1, mgmap1, mgmap2, 1, x, y, '', 1);
    map.ReflashPlacard();

}

function HighLight(e, type) {
    var s = (type == 1) ? '#9BDDFF' : '';
    e.style.backgroundColor = s;
}

function ShowLoader(msg, e, lid) {         //Show Loader
    var d = document.createElement('div');
    d.innerHTML = SYSMSG.LOADER.evaluate({ LoadID: lid, LoadMsg: msg });
    e.appendChild(d);
}

function GetMapCenter() {        // 取得目前地圖中心點及比例尺
    var mgMVI = new GWMapViewInfo();
    map.GetMapViewInfo(mgMVI);
    return [(mgMVI.iRTx + mgMVI.iLBx) / 2, (mgMVI.iRTy + mgMVI.iLBy) / 2, mgMVI.iScale];
}

// ===========================共用函式區 - 結束
// Mashup專區
function GetMashup(id) {

}
function PlacardClickEvent(PLID, status) {
    var placard = map.GetPlacardInfo(PLID);
    if (placard.iKind == 1) {
        map.MoveToRXY(placard.iLx, placard.iLy, ExtentZoom - 1, false);
    }
}
// 更新狀態列
function UpdateStatusBar(x, y, e) {
    //var pt = new GWLngLat(GetMapCenterXY(map)[0], GetMapCenterXY(map)[1]);
    var pt = new GWLngLat(x, y);
    var twd97 = pt.GetTWD97();
    $('MapStatusBar').innerHTML = SYSMSG.STATUSBAR + pt.DecToDeg()[0] + ',' + pt.DecToDeg()[1] + '&nbsp;&nbsp;' + SYSMSG.STATUSBAR_TWD97 + twd97[0].toFixed(2) + ',' + twd97[1].toFixed(2);
    //    var aj = new Ajax.Request("PostGIS_Services.asmx/pgCoordinateTransformation_asGeoJSON",
    //                      { postBody: "{WKT_Sring:'" + point_string + "'}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: CTDone});

}
function CTDone(val) {
    var res = eval("[" + val.responseText + "]");
    var xy = eval('[' + res[0].d + ']');
    var x = xy[0].coordinates[0];
    var y = xy[0].coordinates[1];
    var pt = new GWLngLat(GetMapCenterXY(map)[0], GetMapCenterXY(map)[1]);
    $('MapStatusBar').innerHTML = SYSMSG.STATUSBAR + pt.DecToDeg()[0] + ',' + pt.DecToDeg()[1] + '&nbsp;&nbsp;' + SYSMSG.STATUSBAR_TWD97 + x.toFixed(2) + ',' + y.toFixed(2);
}

// 載入繪製工具列
function InitEditorUI() {
    var s = '';
    for (var i = 0; i < SYSMSG.EDITBARNAME.length; i++) {
        var num = (i < 10) ? '0' + i : i;
        s += SYSMSG.EDITORBTNTEMPLATE.evaluate({ num: num, name: SYSMSG.EDITBARNAME[i], action: SYSVAR.EDITBARFUNC[i] });
    }
    s = SYSMSG.EDITORBARTEMPLATE.evaluate({ btn: s });
    $('TabContent4').innerHTML = s;
}

// 載入地圖工具列
function InitMapToolBar() {
    var s = '';
    for (var i = 0; i < SYSMSG.TOOLBARNAME.length; i++) {
        var num = (i < 10) ? '0' + i : i;
        s += SYSMSG.TOOLBARTEMPLATE.evaluate({ num: num, name: SYSMSG.TOOLBARNAME[i], action: SYSVAR.TOOLBARFUNC[i] });
    }
    $('MapToolBar').innerHTML = s;
}

// 載入POI清單
function LoadPOIList() {
    var aj = new Ajax.Request(SYSVAR.POILISTURL, { method: 'get', parameters: {}, onComplete: ReadPOIList, onFailure: ReadPOIListFail });
}

function ReadPOIList(req) {
    var h = '';
    var e;
    var ee;
    e = ISIE ? req.responseXML.childNodes[1] : req.responseXML.childNodes[0];
    h += SYSMSG.TABCONTENTTTITLEU + SYSMSG.POILISTMSG + SYSMSG.TABCONTENTTTITLED;
    h += '<table>';
    for (var i = 0; i < e.childNodes.length; i++) {
        ee = e.childNodes[i];

        if (ee.getAttribute('VISIBLE') == '1') { //判斷是否顯示
            var vis = (ee.getAttribute('VISIBLE') == '0') ? 'disabled' : '';
            h += SYSMSG.LISTPARENTTEMPLATE.evaluate({ NodeName: ee.getAttribute('NODENAME'), id: ee.getAttribute('ID'), fid: ee.getAttribute('ID'), disabled: vis });
            for (var j = 0; j < ee.childNodes.length; j++) {
                vis = (ee.childNodes[j].getAttribute('VISIBLE') == '0') ? 'disabled' : '';
                h += SYSMSG.LISTCHILDTEMPLATE.evaluate({ NodeName: ee.childNodes[j].getAttribute('NODENAME'), id: ee.childNodes[j].getAttribute('ID'), fid: ee.childNodes[j].getAttribute('FID'), disabled: vis });
            }
        }
    }
    h += '</table>';
    $('TabContent1').innerHTML = h;
}

function ReadPOIListFail() {
    $('TabContent1').innerHTML = '<br /><br /><span class="GrayText">' + SYSMSG.ERRORMSG01 + '</span>';
}

// Download Map
function DownloadMap() {
    var link = new Template('#{href}WMS.aspx?x=#{x}&y=#{y}&scale=#{r}&type=cycle&width=#{w}&height=#{h}');
    var x = GetMapCenterXY(map)[0];
    var y = GetMapCenterXY(map)[1];
    var r = GetMapCenterXY(map)[2];
    var w = $('Map').style.width.split('px')[0];
    var h = $('Map').style.height.split('px')[0];
    switch (r) {
        case 1:
            r = 5000;
            break;
        case 2:
            r = 10000;
            break;
        case 3:
            r = 25000;
            break;
        case 4:
            r = 50000;
            break;
        case 5:
            r = 100000;
            break;
        case 6:
            r = 250000;
            break;
        case 7:
            r = 500000;
            break;
        case 8:
            r = 1000000;
            break;
        case 9:
            r = 2500000;
            break;
        case 10:
            r = 5000000;
            break;
    }
    var option = 'height=' + (parseInt(h) + 30) + ',width=' + (parseInt(w) + 30) + ',status=no,toolbar=no,menubar=no,location=no';
    window.open(link.evaluate({ href: 'http://' + window.location.host + '/' + window.location.pathname.split("/")[1] + '/', x: x, y: y, r: r, w: w, h: h }), null, option);
}

// 地址搜尋
function SearchLoaction(key) {
    TabControl(2);
    var h = SYSMSG.TABCONTENTTTITLEU + SYSMSG.SEARCHLISTMSG01 + SYSMSG.TABCONTENTTTITLED;
    if (!key) {
        h += SYSMSG.SERACHLISTMSG03;
        $('TabContent2').innerHTML = h;
        return;
    }
    $('TabContent2').innerHTML = h;

    ShowLoader(SYSMSG.SEARCHLOADMSG, $('TabContent2'), 'SEARCHLISTLOADER');
    var aj = new Ajax.Request(SYSVAR.LOCATIONDATAURL, { method: 'post', parameters: { addinfo_string: key }, onComplete: ShowLocationList });
}

function ShowLocationList(req) {
    var h = SYSMSG.TABCONTENTTTITLEU + SYSMSG.SEARCHLISTMSG01 + SYSMSG.TABCONTENTTTITLED;
    eval(req.responseText);
    if (!Err) {
        h += '<table>';
        res.each(function(r) {
            h += SYSMSG.SEARCHLISTTEMPLATE.evaluate(r);
        });
        h += '</table>';
        $('TabContent2').innerHTML = h;

        ZoomToLocation(res[0].WGS_X, res[0].WGS_Y, res[0].Name);
    } else {
        h += SYSMSG.SERACHLISTMSG02;
        $('TabContent2').innerHTML = h;
    }
}

function ZoomToLocation(x, y, name) {
    SearchListLayer.SetMap(map);
    SearchListLayer.RemoveAllFeatures();
    SearchListLayer.AddFeature(new GWPointFeature(new GWLngLat(x, y), { Name: name }, '#{Name}'));
    SearchListLayer.OverlayFeature();
    map.MoveToRXY(x, y, 2, false);
}

// 切換POI圖層
function SwitchLayer(id, fid) {
    var checked = $('poi' + id).checked;
    if (id == fid) {
        var a = document.getElementsByName('poig' + id);
        $A(a).each(function(a) { a.checked = checked; });
    }
    LayerGroup.each(function(l) { l.RemoveAllFeatures(); });
    LayerGroup = new Array();
    UpdateLayerData();
}

function UpdateLayerData() {
    var a = document.getElementsByClassName("POIListChild");
    var s = '';
    a.each(function(a) {
        var b = a.childNodes[0].childNodes[0];
        if (b.checked) s += b.id.substring(3, b.id.length) + ",";
    });
    s = s.slice(0, -1);

    if (s != '') {
        map.SetCBFunction("", UpdateLayerData);

        ShowLoader(SYSMSG.POILOADMSG, $('TabContent1'), 'POILISTLOADER');

        var param = new Object();
        param.method = 'post';
        param.parameters = new Object();
        param.parameters.ID = s;
        param.parameters.X = GetMapCenterXY(map)[0];
        param.parameters.Y = GetMapCenterXY(map)[1];
        param.parameters.SCALE = GetMapCenterXY(map)[2];
        param.onComplete = LoadLayer;
        var aj = new Ajax.Request(SYSVAR.POIDATAURL, param);
    } else {
        map.RemoveAllPlacard();
    }
}

function LoadLayer(req) {
    res = req.responseText;
    eval(res);
    if (!Err) {
        res.each(function(l) {
            var lay = new GWPointLayer(l.LAYERNAME);
            lay.SetMap(map);
            $A(l.POI).each(function(f) {
                lay.AddFeature(new GWPointFeature(new GWLngLat(f.WGS_X, f.WGS_Y), f, l.ATEMPATE));
            });
            lay.OverlayFeature();
            LayerGroup.push(lay);
        });
    } else {

    }
    setTimeout("$('TabContent1').removeChild($('TabContent1').lastChild)", 500);
}

// 地圖工具列底線效果
function ToolBtnOver(e) {
    e.setAttribute('style', 'border-bottom:3px solid #3EA4DE');
}

function ToolBtnOut(e) {
    e.setAttribute('style', '');
}

// 地圖測量工具
var Mplid;

function StartMeasure() {
    if ($('MeasureDialog').style.visibility == 'visible') return;
    $('MeasureDialog').style.visibility = 'visible';
    $('MeasureMsg').innerHTML = SYSMSG.MEASURE01;
    map.SetMapAction(MeasureMethod);
    map.SetCBFunction('MapActionCreate', ShowMeasureResult);
}
var MeasureMethod = 1;
function MeasureTypeChange() {
    if (!isNaN(Mplid)) map.RemovePolyLine(Mplid);
    Mplid = NaN;
    map.ReflashPolyLine();
    var rb = document.getElementsByName('FormatRadio');
    for (var i = 0; i < rb.length; i++) {
        if (rb[i].checked) {
            MeasureMethod = parseInt(rb[i].value);
            map.SetMapAction(MeasureMethod);
        }
    }
    map.SetCBFunction('MapActionCreate', ShowMeasureResult);
}
var plpoint;
function ShowMeasureResult(id, pl) {
    map.SetMapAction(0);
    Mplid = id;
    var pf = new GWPolyLineFeature();
    pf.SetGeometryByGWPolyLine(pl);
    pf.SetFid(id);
    var dist = pf.GetLength();
    switch (MeasureMethod) {
        case 1:
            var distt = (dist < 1000) ? dist.toFixed(2) + ' ' + SYSMSG.MEASUREUNIT02 : (dist / 1000).toFixed(3) + ' ' + SYSMSG.MEASUREUNIT01;
            var show = { Dist: distt, Points: pf.GetNodesCount() - 1 };
            $('MeasureMsg').innerHTML = SYSMSG.MEASURETEMPLATE01.evaluate(show);
            break;
        case 2:
            var pt = pl.StPoint;
            var polygon, StPoint;
            polygon = 'POLYGON((';
            if (pt != null)
                StPoint = pt;
            while (pt != null) {
                polygon += pt.iX.toString() + ' ' + pt.iY.toString() + ',';
                pt = pt.oNextPoint;
            }
            polygon += pl.StPoint.iX + ' ' + pl.StPoint.iY + '))';
            plpoint = pf.GetNodesCount() - 1;
            var aj = new Ajax.Request("PostGIS_Services.asmx/pgArea_KWT",
                      { postBody: "{KWT_String:'" + polygon + "'}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: CalcAreaDone });
            break;
    }
}

function CalcAreaDone(val) {
    var res = eval("[" + val.responseText + "]");
    var distt = (Math.sqrt(res[0].d) < 1000) ? res[0].d.toFixed(2) + ' ' + SYSMSG.MEASUREUNIT00 + SYSMSG.MEASUREUNIT02 : (res[0].d / 1000000).toFixed(3) + ' ' + SYSMSG.MEASUREUNIT00 + SYSMSG.MEASUREUNIT01;
    var show = { Dist: distt, Points: plpoint };
    $('MeasureMsg').innerHTML = SYSMSG.MEASURETEMPLATE02.evaluate(show);
}

function ReMeasure() {
    if (!isNaN(Mplid)) map.RemovePolyLine(Mplid);
    Mplid = NaN;
    map.ReflashPolyLine();
    $('MeasureMsg').innerHTML = SYSMSG.MEASURE01;
    map.SetMapAction(MeasureMethod);
}

function ClearMeasure() {
    if (!isNaN(Mplid)) map.RemovePolyLine(Mplid);
    Mplid = NaN;
    map.ReflashPolyLine();
    $('MeasureDialog').style.visibility = 'hidden';
    map.SetMapAction(0);
}

// 切換鷹眼圖及放大鏡
function SwitchEagleMap(e) {
    var m = true;
    e.style.visibility = 'hidden';
    var name = e.getAttribute('name');
    var d = (name.charAt(0) == 'M') ? -2 : 3;
    var s = (name.charAt(1) == '1') ? true : false;
    var type = (name.charAt(0) == 'M') ? 2 : 3;
    if ((name == 'E1') || (name == 'M1')) {
        $(name.charAt(0) + 'Closebtn').style.visibility = 'visible';
    } else {
        $(name.charAt(0) + 'Openbtn').style.visibility = 'visible';
    };
    map.ShowEagleEyeMap(type, s, SMW, SMH, d);
}

// 圖形編輯區 (線段)=================================================
function StratCreateFeature(type) {
    if (EditLayer && EditLayer.Attribute.EditType == type) {
        AddAnotherFeature(type);
        return;
    }
    $('FeatureList').style.display = 'none';
    if (EditLayer) EditLayer.RemoveAllFeatures();
    switch (type) {
        case 0:
            EditLayer = new GWPointLayer('EditPointLayer');
            map.SetCBFunction('ClickEvent', SavePoint);
            break;
        case 1:
            EditLayer = new GWPolyLineLayer('EditPolylineLayer', 0);
            map.SetMapAction(1);
            map.SetCBFunction('MapActionCreate', SaveLine);
            break;
        case 2:
            EditLayer = new GWPolyLineLayer('EditPolygonLayer', 2);
            map.SetMapAction(2);
            map.SetCBFunction('MapActionCreate', SaveLine);
            break;
        case 3:
            EditLayer = new GWPolyLineLayer('EditCircleLayer', 4);
            map.SetMapAction(1);
            map.SetCBFunction('MapActionCreate', SaveLine);
            break;
    }
    EditLayer.SetAttribute({ EditType: type });

    $('EditorStatus').style.display = '';
    $('EditorStatus').innerHTML = '<br />&nbsp;&nbsp;' + SYSMSG.EDITORMSG01 + '<br /><br />';
    EditLayer.SetMap(map);
}

function SavePoint(x, y, e) {
    TempFeature = new GWPointFeature(new GWLngLat(x, y));
    TempFeature.Fid = map.AddPlacard(1, TempFeature.Symbol.Icon, TempFeature.Symbol.Shad, 1, x, y, '', '', '');
    map.ReflashPlacard();
    map.SetPlacardDragDrog(true);
    map.SetCBFunction('ClickEvent', null);

    $('EditorStatus').style.display = 'none';
    $('FeatureList').style.display = 'none';

    var c = document.createElement('div');
    c.className = 'EditorInfoPanel';

    c.innerHTML = '<span>' + SYSMSG.COMMON04 + '</span><br /><input id="FeatureName" type="text" size="30" value="' + SYSMSG.EDITORMSGGROUP01[EditLayer.GetAttribute('EditType')] + (EditLayer.GetFeatureCount() + 1) + '" /><br /><span>' + SYSMSG.COMMON05 + '</span><br /><textarea id="FeatureDescript" rows="4" cols="27"></textarea><br />';
    c.innerHTML += '<input type="button" class="confirmbtn" value="' + SYSMSG.COMMON02 + '" onclick="ConfirmCreate(this.parentNode);"/>&nbsp;<input type="button" class="cancelbtn" value="' + SYSMSG.COMMON03 + '" onclick="CancelCreate(this.parentNode);">';
    $('TabContent4').appendChild(c);
    $('FeatureName').focus();
}

function SaveLine(id, obj) {
    TempFeature = new GWPolyLineFeature('', '', '', EditLayer.StereoType);
    TempFeature.SetGeometryByGWPolyLine(obj);
    TempFeature.RemoveFirstNode();
    TempFeature.SetFid(id);

    map.SetMapAction(0);

    $('EditorStatus').style.display = 'none';
    $('FeatureList').style.display = 'none';

    var c = document.createElement('div');
    c.className = 'EditorInfoPanel';

    c.innerHTML = '<span>' + SYSMSG.COMMON04 + '</span><br /><input id="FeatureName" type="text" size="30" value="' + SYSMSG.EDITORMSGGROUP01[EditLayer.GetAttribute('EditType')] + (EditLayer.GetFeatureCount() + 1) + '" /><br /><span>' + SYSMSG.COMMON05 + '</span><br /><textarea id="FeatureDescript" rows="4" cols="27"></textarea><br />';

    if (EditLayer.GetAttribute("EditType") == 1)
        c.innerHTML += SYSMSG.EDITORLINEWIDTH;
    c.innerHTML += SYSMSG.EDITORCOLORPANEL;

    c.innerHTML += '<input type="button" class="confirmbtn" value="' + SYSMSG.COMMON02 + '" onclick="ConfirmCreate(this.parentNode);"/>&nbsp;<input type="button" class="cancelbtn" value="' + SYSMSG.COMMON03 + '" onclick="CancelCreate(this.parentNode);">';

    $('TabContent4').appendChild(c);
    $('FeatureName').focus();
}

function ConfirmCreate(e) {
    TempFeature.Attribute = { Name: $('FeatureName').value, Descript: $('FeatureDescript').value };
    if (EditLayer.GetAttribute("EditType") > 0) {
        var w = (EditLayer.GetAttribute("EditType") == 1) ? parseFloat($('FeatureLineWidth').value) : 3;
        var c = new Object();
        c.r = $('FeatureRed').value;
        c.g = $('FeatureGreen').value;
        c.b = $('FeatureBlue').value;
        c.a = $('FeatureTrans').value;
        TempFeature.SetLineStyle(w, c);
        TempFeature.SetNodeStyle(3, c);
    } else {
        map.SetPlacardDragDrog(false);
        var pt = map.GetPlacardInfo(TempFeature.Fid);
        TempFeature.SetGeometry(new GWLngLat(pt.getXY()[0], pt.getXY()[1]));
        TempFeature.AttributeTemplate = new Template('<span class="BoldText">#{Name}</span><br /><br /><span class="GrayText">#{Descript}</span>');
    }
    EditLayer.AddFeature(TempFeature);
    EditLayer.OverlayFeature();
    ShowEditList(e);
}

function CancelCreate(e) {
    if (EditLayer.GetAttribute("EditType") > 0) {
        map.RemovePolyLine(TempFeature.Fid);
        map.ReflashPolyLine();
    } else {
        map.RemovePlacard(TempFeature.Fid);
        map.ReflashPlacard();
    }
    ShowEditList(e);
}

function CancelEdit() {
    //ShowEditList(e);
}

function ShowEditList(e) {
    if (e) $('TabContent4').removeChild(e);
    $('FeatureList').style.display = '';
    var h = '<table width="100%">';
    EditLayer.FeatureMembers.each(function(f, ind) {
        var t = new Template('<tr style="cursor:pointer;" onclick="EditFeature(#{ind});" onmouseover="HighLight(this,1);" onmouseout="HighLight(this,0);"><td style="width:35px"><img src="Images/EditIcon_0#{EditType}.gif"></td><td><span class="BoldText">#{Name}</span><br /><span class="GrayText">#{Descript}</span></td></tr>');
        var c = { ind: ind, Name: f.GetAttribute('Name'), Descript: f.GetAttribute('Descript'), EditType: EditLayer.GetAttribute('EditType') };
        h += t.evaluate(c);
    });
    h += '</table>';
    h += '<br /><input type="button" class="confirmbtn" value="' + SYSMSG.COMMON06 + '" onclick="AddAnotherFeature(' + EditLayer.GetAttribute('EditType') + ')"> <input type="button" value="' + SYSMSG.COMMON07 + '" class="confirmbtn" onclick="ExportKML();"/>'
    $('FeatureList').innerHTML = h;
}

function EditFeature(ind) {
    //$('EditorStatus').style.display = '';
    //$('EditorStatus').innerHTML = '<br />&nbsp;&nbsp;' + SYSMSG.EDITORMSG03 + '<br /><br />';
    $('FeatureList').style.display = 'none';
    if (EditLayer.GetAttribute('EditType') == 0) {
        var c = document.createElement('div');
        c.className = 'EditorInfoPanel';
        c.innerHTML = '<span>' + SYSMSG.COMMON04 + '</span><br /><input id="FeatureName" type="text" size="30" value="' + EditLayer.FeatureMembers[ind].GetAttribute('Name') + '" /><br /><span>' + SYSMSG.COMMON05 + '</span><br /><textarea id="FeatureDescript" rows="4" cols="27" value="">' + EditLayer.FeatureMembers[ind].GetAttribute('Descript') + '</textarea><br />';
        c.innerHTML += '<br /><input type="button" class="confirmbtn" value="' + SYSMSG.COMMON02 + '" onclick="SaveEditPoint(this.parentNode,' + ind + ');"/>&nbsp;<input type="button" class="cancelbtn" value="' + SYSMSG.COMMON03 + '" onclick="CancelEdit();">';
        $('TabContent4').appendChild(c);
        map.SetPlacardDragDrog(true);
    } else {
        EditIconLayer.SetMap(map);
        StartEditLine(ind);

        var c = document.createElement('div');
        c.className = 'EditorInfoPanel';

        c.innerHTML = '<span>' + SYSMSG.COMMON04 + '</span><br /><input id="FeatureName" type="text" size="30" value="' + EditLayer.FeatureMembers[ind].GetAttribute('Name') + '" /><br /><span>' + SYSMSG.COMMON05 + '</span><br /><textarea id="FeatureDescript" rows="4" cols="27" value="">' + EditLayer.FeatureMembers[ind].GetAttribute('Descript') + '</textarea><br />';

        if (EditLayer.GetAttribute("EditType") == 1)
            c.innerHTML += SYSMSG.EDITORLINEWIDTH;
        c.innerHTML += SYSMSG.EDITORCOLORPANEL;
        c.innerHTML += '<br /><input type="button" class="confirmbtn" value="' + SYSMSG.COMMON02 + '" onclick="SaveEditLine(this.parentNode,' + ind + ');"/>&nbsp;<input type="button" class="cancelbtn" value="' + SYSMSG.COMMON03 + '" onclick="CancelEdit();">';

        $('TabContent4').appendChild(c);

        var s = EditLayer.FeatureMembers[ind].LineStyle;
        if ($('FeatureLineWidth')) $('FeatureLineWidth').value = s.Width;
        $('FeatureRed').value = s.Color.r;
        $('FeatureGreen').value = s.Color.g;
        $('FeatureBlue').value = s.Color.b;
        $('FeatureTrans').value = s.Color.a;
    }
    //$('FeatureDescript').value = EditLayer.FeatureMembers[ind].GetAttribute('Descript');
    $('FeatureName').focus();

}

function StartEditLine(id) {
    $('EditorStatus').style.display = 'none';
    var i = new Array();

    var n = EditLayer.FeatureMembers[id].GetGeometry();
    n.each(function(a) { EditIconLayer.AddFeature(new GWPointFeature(a, { id: id }, '', EditIconLayer.BtnType, EditorIconStyle)); });

    EditIconLayer.OverlayFeature();
    map.SetCBFunction('PLDragOver', UpdateEditingLine);
    map.SetPlacardDragDrog(true);
}

function UpdateEditingLine(id) {
    var mpt = map.GetPlacardInfo(id);

    var i = EditIconLayer.GetIndexByFid(id);
    EditIconLayer.FeatureMembers[i].SetGeometry(new GWLngLat(mpt.getXY()[0], mpt.getXY()[1]));
    var p = EditIconLayer.FeatureMembers[i].GetGeometry()[0];

    EditLayer.FeatureMembers[parseInt(mpt.getCID())].EditNode(i, p);
    EditLayer.OverlayFeature();
}

function SaveEditPoint(e, ind) {
    map.SetPlacardDragDrog(false);
    EditLayer.FeatureMembers[ind].Attribute = { Name: $('FeatureName').value, Descript: $('FeatureDescript').value };
    var pt = map.GetPlacardInfo(EditLayer.FeatureMembers[ind].Fid);
    EditLayer.FeatureMembers[ind].SetGeometry(new GWLngLat(pt.getXY()[0], pt.getXY()[1]));
    EditLayer.OverlayFeature();
    ShowEditList(e);
}

function SaveEditLine(e, ind) {
    EditLayer.FeatureMembers[ind].Attribute = { Name: $('FeatureName').value, Descript: $('FeatureDescript').value };

    var w = (EditLayer.GetAttribute("EditType") == 1) ? parseFloat($('FeatureLineWidth').value) : 3;
    var c = new Object();
    c.r = $('FeatureRed').value;
    c.g = $('FeatureGreen').value;
    c.b = $('FeatureBlue').value;
    c.a = $('FeatureTrans').value;
    EditLayer.FeatureMembers[ind].SetLineStyle(w, c);
    EditLayer.FeatureMembers[ind].SetNodeStyle(3, c);
    EditLayer.OverlayFeature();

    map.SetPlacardDragDrog(false);
    EditIconLayer.RemoveAllFeatures();

    ShowEditList(e);
}

function AddAnotherFeature(type) {
    switch (type) {
        case 0:
            map.SetCBFunction('ClickEvent', SavePoint);
            break;
        case 1:
            map.SetMapAction(1);
            map.SetCBFunction('MapActionCreate', SaveLine);
            break;
        case 2:
            map.SetMapAction(2);
            map.SetCBFunction('MapActionCreate', SaveLine);
            break;
        case 3:
            map.SetMapAction(1);
            map.SetCBFunction('MapActionCreate', SaveLine);
            break;
    }
    $('EditorStatus').style.display = '';
    $('EditorStatus').innerHTML = '<br />&nbsp;&nbsp;' + SYSMSG.EDITORMSG01 + '<br /><br />';
    EditLayer.SetMap(map);
}

// 功能頁籤控制區
function TabControl(index) {
    var id;
    for (var i = 1; i < TotalTab + 1; i++) {
        id = "TabBtn" + i;
        $(id).childNodes[0].className = 'TabBtn';

        id = "TabContent" + i;
        $(id).style.visibility = 'hidden';
    }
    id = "TabBtn" + index;
    $(id).childNodes[0].className = 'TabBtnSelected';
    id = "TabContent" + index;
    $(id).style.visibility = 'visible';

    map.RemoveAllPolyLine();
    map.ReflashPolyLine();
    map.RemoveAllPlacard();
    map.ReflashPlacard();
    
    switch (index) {
        case 1:
            WikiPOITypeChange();
            break;
        case 5:
            break;
    }
}

// 重新計算地圖大小
function ResizeMap() {
    var bodyCW, bodyCH, a;
    a = GetWindowCurrentSize();
    bodyCW = a[0];
    bodyCH = a[1];

    // Resize Div
    var inH = bodyCH - 90 - 25;
    var mapW = bodyCW - 250 - 70;
    $('MapBookMarks').style.height = $('Map').style.height = $('TabContentGroup').style.height = inH + 'px';
    var a = $('TabContentGroup').childNodes;
    for (var i = 0; i < a.length; i++) a[i].style.height = inH + 'px';
    $('Map').style.width = mapW + 'px';
}

// 地圖快取標籤區
function ShowBookMarkDialog() {
    $('BookMarkName').value = '';
    $('MapStatusString').value = map.GetMapStatus();
    $('MapBookMarkDialog').style.visibility = 'visible';
    $('BookMarkName').focus();
}

function AddBookMark(Name, MS) {
    var a = document.createElement("div");
    if (!Name) Name = SYSMSG.BOOKMARKDEFAULT;
    a.innerHTML = '<table onclick="map.SetMapStatus(\'' + MS + '\');" class="MapBookMark' + Math.ceil(Math.random() * 4) + '" cellpadding="0" cellspacing="0"><tr><td><span>' + Name + '</span></td></tr></table>&nbsp;<img src="Images/BookMarkShadow.gif" />';
    $('MapBookMarks').appendChild(a);
}

function CancelBookMark(a) {
    a.style.visibility = 'hidden';
}

function ClearBookMark() {
    $('MapBookMarks').innerHTML = '';
}

// Cookies        
function SaveCookies() {
    setCookie('l', map.GetMapStatus(), 14);
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
    ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString())
}

// 傳送地圖 
function OpenSaveLink() {
    $('SaveLinkDialog').style.visibility = 'visible';
    $('SaveLinkText').value = window.location + '?l=' + map.GetMapStatus();
    $('SaveLinkText').select();
}

function CloseSaveLink() {
    $('SaveLinkDialog').style.visibility = 'hidden';
}

function SearchWikiPoiData(id, keyword) {
    var mvi = new GWMapViewInfo();
    map.GetMapViewInfo(mvi);
    var boundry = mvi.iRTx + "," + mvi.iLBy + "," + mvi.iLBx + "," + mvi.iRTy;
    var aj = new Ajax.Request(SYSVAR.WIKIDATAURL, { method: 'get', parameters: 'id=' + id + '&keyword=' + keyword + '&boundry=' + boundry, onComplete: ReadWikiPOIList, onFailure: function() { alert('取得資料錯誤'); } });
}

function ReadWikiPOIList(req) {
    var ResObject = TryEval(req.responseText);
    if (ResObject == false) {
        alert('Return Data False');
        return;
    }
    map.RemoveAllPlacard();
    var pois = ResObject.PoiData;
    var mapicon = new GWMapIcon('images/wikiGPS/7-11.png', 47, 49, 23, 24);
    switch (pois[0].POI_NAME) {
        case "7-ELEVEN便利商店":
            mapicon = new GWMapIcon('images/wikiGPS/7-11.png', 47, 49, 23, 24);
            break;
        case "全家便利商店":
            mapicon = new GWMapIcon('images/wikiGPS/family.png', 153, 42, 76, 21);
            break;
    }
    for (var i = 0; i < pois.length; i++) {
        map.AddPlacard(0, mapicon, mapicon, 1, pois[i].POI_X, pois[i].POI_Y, pois[i].POI_NAME + ":" + pois[i].POI_BRANCH, '', '');
    }
    map.ReflashPlacard();
}
function TryEval(tmp) {
    try {
        var ResObject = eval("(" + tmp + ")");
        return ResObject;
    }
    catch (e) {
        return false;
    }
}

function ExportKML() {
    var geometry = '';
    switch (EditLayer.Attribute.EditType) {
        case 0:
            EditLayer.FeatureMembers.each(function(f, ind) {
                geometry += 'POINT(' + f.Geometry[0].Lng + ' ' + f.Geometry[0].Lat + ')' + '|';
            });
            break;
        case 1:
            EditLayer.FeatureMembers.each(function(f, ind) {
                geometry += 'LINESTRING(';
                for (var i = 0; i < f.Geometry.length; i++) {
                    geometry += f.Geometry[i].Lng + ' ' + f.Geometry[i].Lat + ',';
                }
                geometry = geometry.substring(0, geometry.length - 1) + ')|';
            });
            break;
        case 2:
            EditLayer.FeatureMembers.each(function(f, ind) {
                geometry += 'POLYGON((';
                for (var i = 0; i < f.Geometry.length; i++) {
                    geometry += f.Geometry[i].Lng + ' ' + f.Geometry[i].Lat + ',';
                }
                geometry += f.Geometry[0].Lng + ' ' + f.Geometry[0].Lat + '))|';
            });
            break;
        case 3:
            alert(SYSMSG.COMMON21);
            break;
    }

    geometry = geometry.substring(0, geometry.length - 1);
    var aj = new Ajax.Request("PostGIS_Services.asmx/pgFormatConvert",
                      { postBody: "{WKTString:'" + geometry + "'}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: FormatConvertDone, onFailure: ReadPOIListFail });
}

function FormatConvertDone(val) {
    var KML_String = '';

    KML_String = '<?xml version="1.0" encoding="UTF-8"?>\n';
    KML_String += '<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">\n';
    KML_String += '<Document>\n';
    KML_String += '<name>ConvertToKML.kml</name>\n';

    var res = eval("[" + val.responseText + "]");
    var point = res[0].d.split('|');
    var i = 0;
    EditLayer.FeatureMembers.each(function(f, ind) {
        KML_String += '<Placemark>\n';
        KML_String += '<name>' + f.GetAttribute('Name') + '</name>\n';
        KML_String += '<description>' + f.GetAttribute('Descript') + '</description>\n';
        KML_String += point[i];
        KML_String += '\n</Placemark>\n';
        i += 1;
    });


    KML_String += '</Document>\n';
    KML_String += '</kml>';

    window.open("Function/ExportKML.aspx?KML=" + KML_String, "KML");

}
// 載入POI清單
var ExtentLx = 0, ExtentLy = 0, ExtentRx = 0, ExtentRy = 0, ExtentZoom = -1;
function WikiPOIList() {
    if ($('TabContent1').style.visibility != 'visible') return;
    if ($('PlaceClass').selectedIndex == 0) return;
    var mvi = new GWMapViewInfo();
    map.GetMapViewInfo(mvi);
    //Rx:左上x,Ry:左上y,Lx:右下x,Ly:左下y

    var Lx, Ly, Rx, Ry, Scale;
    Lx = mvi.iLBx;
    Ly = mvi.iLBy;
    Rx = mvi.iRTx;
    Ry = mvi.iRTy;
    Scale = mvi.iScale;

    if (ExtentLx > Lx || ExtentLy > Ly || ExtentRx < Rx || ExtentRy < Ry || ExtentZoom != Scale) {
        ExtentLx = Rx - (Lx - Rx) / 3;
        ExtentRx = Lx + (Lx - Rx) / 3;
        ExtentLy = Ly - (Ry - Ly) / 3;
        ExtentRy = Ry + (Ry - Ly) / 3;
        ExtentZoom = Scale;

        if (Scale == 1) {
            var aj = new Ajax.Request("PostGIS_Services.asmx/pgGetPOIbyExtent_Level01",
                      { postBody: "{xmin:" + ExtentLx.toString() + ",ymin:" + ExtentLy.toString() + ",xmax:" + ExtentRx.toString() + ",ymax:" + ExtentRy.toString() + ",classType:" + $('PlaceClass').options[$('PlaceClass').selectedIndex].value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: ReadWikiPOIList }, true);

        }
        else {
            var aj = new Ajax.Request("PostGIS_Services.asmx/pgGetPOIbyExtent",
                      { postBody: "{xmin:" + ExtentLx.toString() + ",ymin:" + ExtentLy.toString() + ",xmax:" + ExtentRx.toString() + ",ymax:" + ExtentRy.toString() + ",classType:" + $('PlaceClass').options[$('PlaceClass').selectedIndex].value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: ReadWikiPOIList }, true);
        }
    }
}
function WikiPOITypeChange() {
    var mvi = new GWMapViewInfo();
    map.GetMapViewInfo(mvi);
    //Rx:左上x,Ry:左上y,Lx:右下x,Ly:左下y
    var Lx, Ly, Rx, Ry, Scale;
    Lx = mvi.iLBx;
    Ly = mvi.iLBy;
    Rx = mvi.iRTx;
    Ry = mvi.iRTy;
    Scale = mvi.iScale;

    ExtentLx = Rx - (Lx - Rx) / 3;
    ExtentRx = Lx + (Lx - Rx) / 3;
    ExtentLy = Ly - (Ry - Ly) / 3;
    ExtentRy = Ry + (Ry - Ly) / 3;
    ExtentZoom = Scale;

    if ($('PlaceClass').selectedIndex != 0) {
        if (Scale == 1) {
            var aj = new Ajax.Request("PostGIS_Services.asmx/pgGetPOIbyExtent_Level01",
                      { postBody: "{xmin:" + ExtentLx.toString() + ",ymin:" + ExtentLy.toString() + ",xmax:" + ExtentRx.toString() + ",ymax:" + ExtentRy.toString() + ",classType:" + $('PlaceClass').options[$('PlaceClass').selectedIndex ].value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: ReadWikiPOIList }, true);

        }
        else {
            var aj = new Ajax.Request("PostGIS_Services.asmx/pgGetPOIbyExtent",
                      { postBody: "{xmin:" + ExtentLx.toString() + ",ymin:" + ExtentLy.toString() + ",xmax:" + ExtentRx.toString() + ",ymax:" + ExtentRy.toString() + ",classType:" + $('PlaceClass').options[$('PlaceClass').selectedIndex ].value + "}", method: 'post', contentType: 'application/json; charset=utf-8', onSuccess: ReadWikiPOIList }, true);
        }
    }
    else
    {
        map.RemoveAllPlacard();
        map.ReflashPlacard();
        $('WikiPOIList').innerHTML = '';
    }
    
}
function ReadWikiPOIList(req) {
    map.RemoveAllPlacard();
    var h = '';
    var e, res;
    res = eval("[" + req.responseText + "]");
    e = eval(res[0].d);

    h = '<table>';
    var mgmap1 = new GWMapIcon('Images/MIcon01.png', 43, 26, 21, 13);
    //圖標點陰影樣式
    var mgmap2 = new GWMapIcon('Images/MIcon02.png', 43, 26, 21, 13);
    var mgmap3 = new GWMapIcon('Images/marker.png', 20, 34, 20, 34);
    var r = new Object();
    for (var i = 0; i < e.length; i++) {
        if (e[i].Cnt == 1) {
            r.Name = e[i].Name;
            r.WGS_X = e[i].X;
            r.WGS_Y = e[i].Y;
            r.City = e[i].Town;
            r.Id = map.AddPlacard(0, mgmap1, mgmap2, 1, e[i].X, e[i].Y, e[i].Name+'<br/>'+e[i].Info, 1);
            h += SYSMSG.SEARCHLISTTEMPLATE.evaluate(r);

        } else {
            map.AddPlacard(1, mgmap3, mgmap2, 1, e[i].X, e[i].Y, '', 1);
            map.AddPlacard(2, mgmap3, mgmap2, 1, e[i].X, e[i].Y, '<a style=" background:#FFFFCC; border:1px solid #000000">' + e[i].Cnt + '</a>', 2);
        }
    }
    h += '</table>';
    if (e.length == 0)
        h += '<span class="GrayText">' + SYSMSG.SERACHLISTMSG02 + '</span>';
    $('WikiPOIList').innerHTML = h;
    map.ReflashPlacard();
}
