var map;
var centerId;
function onLoad(selLayer) {
  map = new GMap2( document.getElementById("map") );
  //所在地の座標設定 （美唄）
  var tempLon  = 141.85800075531006; // 経度(lng)
  var tempLat  = 43.3320768378829;  // 緯度(lat)
  var tempHomePoint = new GLatLng(tempLat,tempLon);
  map.setCenter(tempHomePoint , 15);// 数値部分を変えると詳細-広域に変更できます。0-17
  map.enableScrollWheelZoom();
  map.addControl(new GMapKitMapControls3d());
  map.addControl(new GMapTypeControl());

  // マーカーの一覧を取得(GET)
  GDownloadUrl( "/com/gmapOpenList.php?id=" + encodeURIComponent(selLayer), function(listdata){
    try {
      var markers = JSON.parse(listdata);
      if(markers) {
        // レイヤチェック初期設定
        if (selLayer instanceof Array) {
          for (var i=0 ; i<selLayer.length; i++){
            var layer = selLayer[i];
            var eSource = document.getElementById("LY[" + layer + "]");
            eSource.checked = true;
          }
        } else {
          var eSource = document.getElementById("LY[" + selLayer + "]");
          eSource.checked = true;
        }
        var conMapId = document.getElementById("conMapId").value;
        var conType = document.getElementById("contentsType").value;
          GDownloadUrl( "/com/gmapGetCenter.php?id=" + encodeURIComponent(conMapId), function(centerData){
          var center = JSON.parse(centerData);
          centerId = center.ＰＫマップキー ;
          var centerLat = center.緯度 ;  // 緯度(lat)
          var centerLon = center.経度 ;  // 経度(lng)
          // 中心点座標の設定
          var homePoint = new GLatLng(centerLat,centerLon);
          map.setCenter(homePoint , 15);// 数値部分を変えると詳細-広域に変更できます。0-17
        });
        for(var i=0; i<markers.length; ++i) { // それぞれについて…
          var markerID = markers[i];
          // マーカー情報を取得(GET)
          GDownloadUrl( "/com/gmapOpenRead.php?id=" + encodeURIComponent(markerID) + "&type=" + encodeURIComponent(conType), function(mkdata){
            // 地図にマーカーを追加
            var mk = JSON.parse(mkdata);
            //所在地の座標設定 
            var lat  = mk.lat ;  // 緯度(lat)
            var lon  = mk.lng ;  // 経度(lng)
            var mapId = mk.mapkey;
            var memberId = mk.memberkey;
            var reportId = mk.reportid;
            var markerId = mk.makey;
            var mapType = mk.maptype;

            if (markerId != 0) {
              var markerPath = '/marker/' + mk.icon;
            } else {
              var markerPath = undefined;
            }
            var textInfo = mk.info;
            var imageName = mk.imagename;
            if (imageName != "") {
              if (mapType == 1) {
                var $pAuth     = "";
                var $tblname   = "ict_i_reportupfile";
                var $fieldimg  = "ファイル";
                var $orgname   = imageName;
                var $pkkey     = reportId;
                var $thumbnail = "サムネール";
              } else {
                var $pAuth     = "";
                var $tblname   = "ict_migration_real_estate_img";
                var $fieldimg  = "イメージ";
                var $orgname   = imageName;
                var $pkkey     = reportId;
                var $thumbnail = "サムネイル詳細";
              }
              // 画像表示ＵＲＬ設定
              var $imgfull = "/com/imageNoSession.php";
              $imgfull = $imgfull + "?pAuth="  + encodeURI($pAuth);
              $imgfull = $imgfull +  "&pTName=" + encodeURI($tblname);
              $imgfull = $imgfull +  "&pFName=" + encodeURI($orgname);
              $imgfull = $imgfull +  "&pTItem=" + encodeURI($thumbnail); 
              if (mapType == 1) {
                  $imgfull = $imgfull +  "&pTW[1]=" + encodeURI($pkkey);
                  $imgfull = $imgfull +  "&pTW[2]=" + encodeURI(imageName);
              } else {
                  $imgfull = $imgfull +  "&pTW[2]=" + encodeURI($pkkey);
                  $imgfull = $imgfull +  "&pTW[4]=" + encodeURI(imageName);
              }

              var imageInfo = '<img src="' + $imgfull + '" width="100" align="left" />';
            } else {
              var imageInfo = '';
            }
            
            var linkName = mk.linkname;
            var linkUrl = mk.linkuri;
            if (linkName != "" && linkName != null && linkUrl != "" && linkUrl != null) {
              var linkInfo = '<a href="' + linkUrl + '" target="_blank">' + linkName + '</a>';
            } else {
              var linkInfo = '';
            }
            var allInfo = "";
            if (imageInfo != "" && imageInfo != null) {
              allInfo = allInfo + imageInfo;
              allInfo = allInfo + textInfo;
              allInfo = allInfo + '<br clear="left">';
            } else {
              allInfo = allInfo + textInfo + '<br />';
            }
            if (linkInfo != "") {
              allInfo = allInfo + linkInfo;
            }
            addInfoShowMarker( mapId, centerId, new GLatLng(lat, lon), textInfo, imageInfo, linkName, linkInfo, allInfo, markerPath );
          });
        }
      }
    } catch(e){}  
  });
}

// 経度、緯度小数点以下6桁表示
function shortForm(x) {
  return Math.floor(x*1000000)/1000000;
}

// 住所から検索（ジオコーダー）
var geocoder = new GClientGeocoder();

function searchAddress(address){
    geocoder.getLatLng(address, showMap);
}

function layerSearch(layer){
  var obj = layer;
  if (obj.length !== undefined) {
    var sel = new Array();
    var num = 0;
    for(i=0;i<obj.length;i++){
      if(obj[i].checked){
        sel[num] = obj[i].value;
        num ++;
      }
    }
  } else {
    if (obj.checked === false) {
      var sel = "";
    } else {
      var sel = obj.value;
    }
  }
  onLoad(sel);
}

function showMap(latlng) {
  if (latlng){
      // マーカーの削除
      //map.clearOverlays();
      var marker = new GMarker(latlng);
      map.setCenter(latlng, 15);
      map.addOverlay(marker);
      
      document.getElementById("lng").value = latlng.lng();
      document.getElementById("lat").value = latlng.lat();
      //document.getElementById("latlngaddress").value = document.getElementById("address").value;
  } else {
      alert("住所から緯度経度に変換できません");
  }
}

function addInfoShowMarker(mapId, centerId, latlng, textInfo, imageInfo, linkName, linkInfo, allInfo, path) {
  if (path !== undefined) {
    var iconCheck = new GIcon();
    iconCheck.image = '/marker/check.gif';  //アイコン画像
    iconCheck.iconSize = new GSize(50, 50);    //アイコンサイズ
    //アンカーポイントと画像の左上角からの相対オフセット値
    iconCheck.iconAnchor = new GPoint(25,50);
    iconCheck.infoWindowAnchor = new GPoint(25, 1);

    var icon1 = new GIcon();
    icon1.image = path;  //アイコン画像
    icon1.iconSize = new GSize(50,50);    //アイコンサイズ
    //アンカーポイントと画像の左上角からの相対オフセット値
    icon1.iconAnchor = new GPoint(25,50);
    icon1.infoWindowAnchor = new GPoint(25, 1);
    if (mapId != centerId) {
      var mk = new GMarker(latlng,{
        draggable:true,
        clickable: true,
        icon: icon1,
        title: linkName
      });
    } else {
      var markCheck = new GMarker(latlng,{
        draggable:false,
        clickable: false,
        icon: iconCheck
      });
      map.addOverlay(markCheck);
      var mk = new GMarker(latlng,{
        draggable:false,
        clickable: true,
        icon: icon1,
        title: "本記事のマーカーです"
      });
    }
  } else {
    if (mapId != centerId) {
      var mk = new GMarker(latlng);
    } else {
      var mk = new GMarker(latlng,{
        clickable: true,
        title: "本記事のマーカーです"
      });
    }
  }

  map.addOverlay(mk);
  if (mapId == centerId) {
    // "表示" タブの内容
    var view = document.createElement("div");
    view.innerHTML = allInfo.replace(/(\n|\r)+/g,"<br>");
    var tab = new GInfoWindowTab( "表示", view );
    mk.openInfoWindowTabs( [tab], {"maxWidth":300} );
  }

  GEvent.addListener( mk, "click", function(){
    var tab1 = new GInfoWindowTab( "表示", view );
    mk.openInfoWindowTabs( [tab1], {"maxWidth":300} );
  });
  // "表示" タブの内容
  var view = document.createElement("div");
  view.innerHTML = allInfo.replace(/(\n|\r)+/g,"<br>");
}
onunload = GUnload;
