var gpsmarker = L.marker(marumap.getCenter()).addTo(marumap);
gpsmarker.bindPopup("startで補足開始").openPopup();

var maxTrial = 0           //GPSの取得回数 →そんなものはなか\った
var watchId = null;// 最初はnullにしておく
var all = document.getElementById('all')
var array_latLing = []; //配列を作成
var array_name = [];
var array_desc = [];
var array_vie = [];
var array_layer = [];
    var maruike = L.geoJson(null, {	
        onEachFeature: function(f,layer) {
	    let p = f.properties;
	    let geo = f.geometry;
	    if (p) {			
    		let name = p.name, desc = p.description , viewer = p.viewer;
		let lati= geo.coordinates ;
		array_latLing.push(lati[1]);//末尾に入れる
		array_latLing.push(lati[0]);
		array_name.push(name);
		array_desc.push(desc);
		array_vie.push(viewer);
		array_layer.push(layer)
		let popup = "<h3>" + name + "</h3>";
		layer.bindPopup(popup);	
	    }
        }
    });

//2回目のやつ読みこみ
var array_latLing2 = []; //配列を作成
var array_name2 = [];
var array_desc2 = [];
var array_vie2 = [];
var array_layer2 = [];
var maruike2 = L.geoJson(null, {	
        onEachFeature: function(f,layer) {
	    let p = f.properties;
	    let geo = f.geometry;
	    if (p) {			
    		let name = p.name, desc = p.description , viewer = p.viewer;
		let lati= geo.coordinates ;
		array_latLing2.push(lati[1]);//末尾に入れる
		array_latLing2.push(lati[0]);
		array_name2.push(name);
		array_desc2.push(desc);
		array_vie2.push(viewer);
		array_layer2.push(layer)
		let popup = "<h3>" + name + "</h3>";
		layer.bindPopup(popup);	
	    }
        }
    });
//3回目のやつ読みこみ
var array_latLing3 = []; //配列を作成
var array_name3 = [];
var array_desc3 = [];
var array_vie3 = [];
var array_layer3 = [];
var maruike3 = L.geoJson(null, {	
        onEachFeature: function(f,layer) {
	    let p = f.properties;
	    let geo = f.geometry;
	    if (p) {			
    		let name = p.name, desc = p.description , viewer = p.viewer;
		let lati= geo.coordinates ;
		array_latLing3.push(lati[1]);//末尾に入れる
		array_latLing3.push(lati[0]);
		array_name3.push(name);
		array_desc3.push(desc);
		array_vie3.push(viewer);
		array_layer3.push(layer)
		let popup = "<h3>" + name + "</h3>";
		layer.bindPopup(popup);	
	    }
        }
    });

var gjl = omnivore.geojson("yuza2.geojson", null, maruike);
    gjl.addTo(marumap);

var gjl2 = omnivore.geojson("yuza.geojson", null, maruike2);
//gjl2.addTo(marumap);

var gjl3 = omnivore.geojson("yuza.geojson", null, maruike3);
//gjl2.addTo(marumap);

L.control.layers(null, {"maruike": gjl}).addTo(marumap);


function start() {
    if (tag.value == '') {
	alert('名前を埋めて')
    }else {
	gpsmarker.closePopup()
	all.textContent = "5秒後に取得開始"
	setTimeout(tryWatchGPS, 5000);
    }
}

function wikiRepl(ss) {
    return ss.replace(/{{(.*)\|([0-9][0-9]*)}}/g,
		     '<img class="popup" src="$1" width="$2">').
	replace(/{{(.*)}}/g, '<img class="popup" src="$1">').
	replace(/\[\[(.*)\|(.*)\]\]/g, '<a href="$1">$2</a>').
	replace(/\[\[(.*)\]\]/g, '<a href="$1">$1</a>').
	replace(/^### (.*)/, '<h4>$1</h4>').
	replace(/^## (.*)/, '<h3>$1</h4>').
	replace(/^# (.*)/, '<h2>$1</h4>');
}

function tryWatchGPS() { //start button 押すとGPS取得開始\
    all.textContent = "GPS取得開始";
    if (watchId) {
	watchId = null;
    }    
    watchId = navigator.geolocation.watchPosition(
	onSuccess, onError, {
	    maximumAge: 0, timeout: 2000, enableHighAccuracy: true
	});
    
}

 
///// チート用
function cheat() {
    all.textContent = "GPS取得完了";
    tryWatchGPSstop();
    latlng = L.latLng([39.01874,139.909706]);//かどっこの湧水付近
    // latlng = L.latLng([38.8933,139.8192]); //大学付近
    marumap.panTo(latlng);
//    gpsmarker.setPopupContent(
//	"ここは "+latlng+"です.(チート)"
//    ).openPopup().setLatLng(latlng);
    gpsmarker.setLatLng(latlng);
    dist()    
  }
document.getElementById('cheat').addEventListener('click', cheat);
 

function onSuccess(pos) {
    all.textContent = "GPS取得完了";
    latlng = L.latLng([pos.coords.latitude, pos.coords.longitude]);
    marumap.panTo(latlng);
   gpsmarker.setPopupContent(
	"ここは "+latlng+"です."
   ).openPopup().setLatLng(latlng);
//    gpsmarker.setLatLng(latlng);
    dist();//距離計算
    //navigator.geolocation.clearWatch(watchId);
    restart();
}

function onError(err) {
    all.textContent = "GPS取得失敗";    
    restN =(++maxTrial)+"回目目試行します。";
    gpsmarker.setPopupContent("捕捉失敗:"+restN).openPopup();
  //  setTimeout(tryWatchGPS,5000);
  //  navigator.geolocation.clearWatch(watchId);
    restart();
}

function restart(){
navigator.geolocation.clearWatch(watchId);
    start();
}

function tryWatchGPSstop() { //stop button押すとGPS取得やめるよ
    navigator.geolocation.clearWatch(watchId);
    all.textContent = "GPS取得終了";    
    gpsmarker.setPopupContent("取得を止めました").openPopup();
}

/////距離計算とpopup
var maruike = 0
function dist() {
    var distance = 10; //単位はm
    var ido = 1;
    var keido =  0;
    // alert(array_desc.length)
    for( i = 0; i <= array_desc.length - 1; ++i){
	var array_idokedo = new L.latLng(array_latLing[keido] , array_latLing[ido]);	
	//alert(array_idokedo)
	keido = keido + 2;
	ido = ido + 2;
	//var latlng = L.latLng([39.016904,139.908115]);//距離計算デバック用latlng
	var dist3 = array_idokedo.distanceTo(latlng); //距離計算
	if (dist3 <= distance){
	    i2 = 100+i;    
	    d = array_desc[i]
	    if(localStorage.getItem(i2)){
		three();
	    } else if(localStorage.getItem(i)){
		two();
		localStorage.setItem(i2 , true);
	    }else{		
		array_layer[i].setPopupContent("<h3>" + array_name[i] + "</h3>" +"<p>"+wikiRepl(d)+"</p>\n<dl>"  ).openPopup();	
		localStorage.setItem(i,true);	
	    }
	}
	// all.textContent = "5秒後に取得開始";
	// setTimeout(tryWatchGPS, 5000);
    }
}
document.getElementById('dist').addEventListener('click', dist);
///ここまで 

function two(){
    if(localStorage.getItem(i)){
	array_layer[i].setPopupContent("<h3>" + array_name[i] + "</h3>" +"<h3>" + "2回目だよー" + "</h3>").openPopup();	    
    }
}

function three(){
    if(localStorage.getItem(i2)){
	array_layer[i].setPopupContent("<h3>" + array_name[i] + "</h3>" + "<h3>" + "3回目だよー" + "</h3>").openPopup();
    }
}

function locolreset(){
    localStorage.clear();
    all.textContent = "locol reset";
}
 
//ajax的cgiの処理 一回封印する
function dbAccess() {
//cgiからデータ受け取りのやつを書く
    function respond(){
	array_layer[0].setPopupContent("cgiからデータきたよ。書いてないけどね").openPopup();

    }
    function submit() {		// 「AJAX送信」ボタンを押したときの処
	var val = document.forms[0].elements['tag'];
	var tag = document.getElementById('tag');
	// 後で変える CGIに送るデータや送り先
	if (val) {
	    var conn = new XMLHttpRequest();
	    conn.open('POST', './maruike.cgi');

	    conn.setRequestHeader(		// 送信ヘッダを定義
		'Content-Type', 'application/x-www-form-urlencoded');
	    conn.send('tag='+encodeURIComponent(tag.value));
	    conn.onreadystatechange = respond;	// イベントリスナ登録
	}	
    }
    document.getElementById('db').addEventListener('click', submit); 
}



document.addEventListener('DOMContentLoaded', dbAccess)
document.getElementById('send').addEventListener('click', start);
document.getElementById('stop').addEventListener('click', tryWatchGPSstop);
document.getElementById('locol').addEventListener('click', locolreset);
 
