﻿//地図制御
//
// prototype.js(1.4)が必要 

var DMap = new Object();
DMap.ExecuteQueue = Class.create();
DMap.ExecuteQueue.prototype = {
	objqueue:null,
	
	initialize:function(queueArray){
		if(queueArray){
			this.objqueue = queueArray;
		}
		else{
			this.objqueue = new Array();
		}
	},
	
	addObject:function(target){
		this.objqueue.push(target);
	},
	
	execute:function(zoomlevel,mesh){
		for(var i=0; i < this.objqueue.length ;i++){
			if(this.objqueue[i].isZoomrange(zoomlevel)){
				this.objqueue[i].getMeshData(mesh);
			}
		}
	},

	refreshMarker:function(){
		for(var i=0; i < this.objqueue.length ;i++){
			this.objqueue[i].markerman.refresh();
		}
	},
		
	
	clear:function(){
		for(var i=0; i < this.objqueue.length ;i++){
			this.objqueue[i].clear();
		}
	}
};

DMap.LargeMesh = Class.create();
DMap.LargeMesh.prototype = {
	x:0,
	y:0,
	initialize:function(glatlngvalue){
		if(glatlngvalue){
			this.x = Math.floor((glatlngvalue.lng() - 100));
			this.y = Math.floor((glatlngvalue.lat() * 1.5));
		}
	},
	
	meshcode:function(){
		return this.x.toString() + this.y.toString();
	}
};

DMap.Meshcode = Class.create();
DMap.Meshcode.prototype = {
	x:0,
	y:0,
	initialize:function(glatlngvalue){
		if(glatlngvalue){
			this.x = Math.floor((glatlngvalue.lng() - 100)*10);
			this.y = Math.floor((glatlngvalue.lat() * 1.5)*10);
		}
	},
	
	meshcode:function(){
		return this.x.toString() + this.y.toString();
	}
};


//MapManager
DMap.MapManager = Class.create();
DMap.MapManager.prototype = {
	
	map:null,
	maparea:null,
	execqueue:null,
	linkm:null,
	
	initialize:function(mapareadiv,linkarea){
		this.maparea = mapareadiv;		//マップ表示div
		this.map = new GMap2(this.maparea);
		this.execqueue = new DMap.ExecuteQueue();	//データ管理オブジェクトキュー格納用
		this.linkm = new DMap.LinkManager(this.map,linkarea);
	},
	
	clearMarker:function(){
		this.execqueue.clear();
		this.drawMarker();
	},
	
	addDataManager:function(dmobject){
		dmobject.setGMap(this.map);
		this.execqueue.addObject(dmobject);
		return dmobject;
	},
	
	show:function(lng,lat,zoom){
		this.map.addControl(new GLargeMapControl());
		this.map.addControl(new GMapTypeControl());
		this.map.addControl(new GScaleControl());
		this.map.addControl(new GOverviewMapControl(new GSize(200,150)));
		this.map.setCenter(new GLatLng(lng,lat),zoom);
		this.map.addMapType(G_PHYSICAL_MAP);
		GEvent.addListener(this.map,"moveend",this.drawMarker.bind(this));
		this.drawMarker();
		
	},
	
	drawMarker:function(isResize){
		if(isResize){
			this.map.checkResize();
		}
		var bounds = this.map.getBounds();
		var zoomlevel = this.map.getZoom();
		this.getData(zoomlevel,bounds.getNorthEast(),bounds.getSouthWest());
		this.linkm.drawlink();
	},
	
	getData:function(zoomlevel,llNorthEast,llSouthWest){
		var meshSW = new DMap.LargeMesh(llSouthWest);
		var meshNE = new DMap.LargeMesh(llNorthEast);
		var meshTarget = new DMap.LargeMesh();
		for(mx = meshSW.x;mx <= meshNE.x;mx++){
			for(my = meshSW.y;my <= meshNE.y;my++){
				meshTarget.x = mx;
				meshTarget.y = my;
				this.execqueue.execute(zoomlevel,meshTarget);
			}
		}
		this.execqueue.refreshMarker();
	}
};

//県別リスト管理
DMap.PrefListManager = Class.create();
DMap.PrefListManager.prototype = {
	dataman:null,
	listarea:null,
	preflist:null,
	damlist:null,
	panelFlag:false,
	
	initialize:function(dataman,listarea,preflist,damlist){
		this.dataman = dataman;
		this.listarea = listarea;
		this.preflist = preflist;
		this.damlist = damlist;
		this.preflist.appendChild(this.createPreflist());
	},
	
	createPreflist:function(){
		var prefdata = [{prefno:1,prefname:'北海道'},
		{prefno:2,prefname:'青森'},
		{prefno:3,prefname:'岩手'},
		{prefno:4,prefname:'宮城'},
		{prefno:5,prefname:'秋田'},
		{prefno:6,prefname:'山形'},
		{prefno:7,prefname:'福島'},
		{prefno:8,prefname:'茨城'},
		{prefno:9,prefname:'栃木'},
		{prefno:10,prefname:'群馬'},
		{prefno:11,prefname:'埼玉'},
		{prefno:12,prefname:'千葉'},
		{prefno:13,prefname:'東京'},
		{prefno:14,prefname:'神奈川'},
		{prefno:15,prefname:'新潟'},
		{prefno:16,prefname:'富山'},
		{prefno:17,prefname:'石川'},
		{prefno:18,prefname:'福井'},
		{prefno:19,prefname:'山梨'},
		{prefno:20,prefname:'長野'},
		{prefno:21,prefname:'岐阜'},
		{prefno:22,prefname:'静岡'},
		{prefno:23,prefname:'愛知'},
		{prefno:24,prefname:'三重'},
		{prefno:25,prefname:'滋賀'},
		{prefno:26,prefname:'京都'},
		{prefno:27,prefname:'大阪'},
		{prefno:28,prefname:'兵庫'},
		{prefno:29,prefname:'奈良'},
		{prefno:30,prefname:'和歌山'},
		{prefno:31,prefname:'鳥取'},
		{prefno:32,prefname:'島根'},
		{prefno:33,prefname:'岡山'},
		{prefno:34,prefname:'広島'},
		{prefno:35,prefname:'山口'},
		{prefno:36,prefname:'徳島'},
		{prefno:37,prefname:'香川'},
		{prefno:38,prefname:'愛媛'},
		{prefno:39,prefname:'高知'},
		{prefno:40,prefname:'福岡'},
		{prefno:41,prefname:'佐賀'},
		{prefno:42,prefname:'長崎'},
		{prefno:43,prefname:'熊本'},
		{prefno:44,prefname:'大分'},
		{prefno:45,prefname:'宮崎'},
		{prefno:46,prefname:'鹿児島'},
		{prefno:47,prefname:'沖縄'}];

		var prefTable=document.createElement('TABLE');
		prefTable.setAttribute('border','0');
		var prefTableBody=document.createElement('TBODY');
		prefTable.appendChild(prefTableBody);
		for(var i=0;i < prefdata.length;i++){
			var preftr = document.createElement('TR');
			preftr.onmouseover = function(){
				this.style.backgroundColor="#cccccc";
			};
			preftr.onmouseout = function(){
				this.style.backgroundColor='transparent';
			};
			prefTableBody.appendChild(preftr);
			
			var preftd=document.createElement('TD');
			this.setDamdataRequestEvent(preftd,prefdata[i].prefno);
			preftr.appendChild(preftd);

			var preftext=document.createTextNode(prefdata[i].prefname.stripTags());
			preftd.appendChild(preftext);
			
		}
		return prefTable;
	},
	setDamdataRequestEvent:function(target,prefno){
		target.onclick = function(){
			this.setDamdataRequest(prefno);
		}.bind(this);
	},
	
	setDamdataRequest:function(prefno){
		this.damlist.innerHTML = "データ取得中です…";

		var url = "dws/mapdata.cgi"
		var opt = {
			onComplete:this.displayDamdataList.bind(this),
			method: 'get',
			parameters: "o=pref&n=" + prefno
		};
		
		new Ajax.Request(url,opt);
	},
	
	displayDamdataList:function(req){
	this.damlist.innerHTML = "";
		var helper = new MapData.Helper();
		var text = req.responseText;
		
		var response = eval("(" + helper.safariFilter(text) + ")");
		damdata = response.records;
		
		var damTable=document.createElement('TABLE');
		damTable.setAttribute('border','0');
		var damTableBody=document.createElement('TBODY');
		damTable.appendChild(damTableBody);

		for(var i=0;i < damdata.length;i++){
			var damtr = document.createElement('TR');
			damtr.onmouseover = function(){
				this.style.backgroundColor="#cccccc";
			};
			damtr.onmouseout = function(){
				this.style.backgroundColor='transparent';
			};

			damTableBody.appendChild(damtr);
			
			var damtd1=document.createElement('TD');
			damtr.appendChild(damtd1);
			var damtext=document.createTextNode(damdata[i].name.stripTags() + 
				"(" + damdata[i].kana.stripTags() + ")"
			);
			damtd1.appendChild(damtext);

			var damtd2=document.createElement('TD');
			damtr.appendChild(damtd2);
			
			var adr = damdata[i].address.stripTags();
			if(damdata[i].location){
				this.selectDamEvent(damtr,damdata[i]);
				if(damdata[i].location.confirmed != 1){
					adr += "(位置未確認)";
				}
			}
			else{
				adr += "(位置情報無し)";
			}
			var damtext=document.createTextNode(adr);
			damtd2.appendChild(damtext);
			
		}
		this.damlist.appendChild(damTable);
	},
	
	selectDamEvent:function(target,damdata){
		target.onclick = function(){
			this.setTargetDam(damdata);
		}.bind(this);
	},
	
	setTargetDam:function(damdata){
		this.dataman.setPopupKey(damdata.damno);
		this.dataman.map.setCenter(new GLatLng(damdata.location.y,damdata.location.x));
		this.dataman.tryPopup();
		this.switchPanel();
		
	},

	switchPanel:function(hideflag){
		if(hideflag){
			if(this.panelFlag){
				this.listarea.style.display = "none";
				this.panelFlag = false;
			}
			return;
		}
		
		if(this.panelFlag){
			this.listarea.style.display = "none";
			this.panelFlag = false;
		}
		else{
			this.listarea.style.display = "block";
			this.panelFlag = true;
		}
	}
};

//キーワード検索管理
DMap.KeywordSerchManager = Class.create();
DMap.KeywordSerchManager.prototype = {
	dataman:null,
	listarea:null,
	methodlist:null,
	damlist:null,
	keywordField:null,
	cookieman:null,
	panelFlag:false,
	
	initialize:function(dataman,listarea,methodlist,damlist,keywordField,cookieman){
		this.dataman = dataman;
		this.listarea = listarea;
		this.methodlist = methodlist;
		this.damlist = damlist;
		this.keywordField = keywordField;
		this.cookieman = cookieman;
		this.methodlist.appendChild(this.createSerchList());
	},
	
	createSerchList:function(){
		
		var keywordTable=document.createElement('TABLE');
		keywordTable.setAttribute('border','0');
		var keywordTableBody=document.createElement('TBODY');
		keywordTable.appendChild(keywordTableBody);
		
		var getKeywordTable = function(tablebody){
			var tr = document.createElement('TR');
			tr.onmouseover = function(){
				this.style.backgroundColor="#cccccc";
			};
			tr.onmouseout = function(){
				this.style.backgroundColor='transparent';
			};
			tablebody.appendChild(tr);
			return tr;
		}
		var keywordtr,keywordtd,keywordtext;
		
		//ダム名検索
		keywordtr = getKeywordTable(keywordTableBody);
		keywordtd=document.createElement('TD');
		this.setDamdataRequestEvent(keywordtd,"keyword");
		keywordtr.appendChild(keywordtd);
		
		keywordtext=document.createTextNode("ダム名・ふりがな");
		keywordtd.appendChild(keywordtext);	
		
		//河川名検索
		keywordtr = getKeywordTable(keywordTableBody);
		keywordtd=document.createElement('TD');
		this.setDamdataRequestEvent(keywordtd,"river");
		keywordtr.appendChild(keywordtd);
		
		keywordtext=document.createTextNode("水系・河川名");
		keywordtd.appendChild(keywordtext);	
		
		//地名検索
		keywordtr = getKeywordTable(keywordTableBody);
		keywordtd=document.createElement('TD');
		this.setAddressdataRequestEvent(keywordtd);
		keywordtr.appendChild(keywordtd);
		
		keywordtext=document.createTextNode("地名");
		keywordtd.appendChild(keywordtext);	
		
		return keywordTable;
	},
	setDamdataRequestEvent:function(target,operation){
		target.onclick = function(){
			this.cookieman.setCookie("searchoperation",operation);
			this.setDamdataRequest(operation);
		}.bind(this);
	},
	
	setDamdataRequest:function(operation){
		
		var keyword = this.keywordField.value;
		if(keyword == ""){
			return;
		}
		this.damlist.innerHTML = "ダムデータ取得中です…";
		
		var url = "dws/mapdata.cgi"
		var opt = {
			onComplete:this.displayDamdataList.bind(this),
			method: 'get',
			parameters: "o=" +operation  + "&q=" + keyword
		};
		
		new Ajax.Request(url,opt);
	},
	
	displayDamdataList:function(req){
		this.damlist.innerHTML = "";
		var helper = new MapData.Helper();
		var text = req.responseText;
		
		var response = eval("(" + helper.safariFilter(text) + ")");
		damdata = response.records;
		
		var damTable=document.createElement('TABLE');
		damTable.setAttribute('border','0');
		var damTableBody=document.createElement('TBODY');
		damTable.appendChild(damTableBody);
		
		if(damdata.length == 0){
			this.damlist.innerHTML = "該当するダムがありません";
			return;
		}
		
		for(var i=0;i < damdata.length;i++){
			var damtr = document.createElement('TR');
			damtr.onmouseover = function(){
				this.style.backgroundColor="#cccccc";
			};
			damtr.onmouseout = function(){
				this.style.backgroundColor='transparent';
			};

			damTableBody.appendChild(damtr);
			
			var damtd1=document.createElement('TD');
			damtr.appendChild(damtd1);
			var damtext=document.createTextNode(damdata[i].name.stripTags() + 
				"(" + damdata[i].kana.stripTags() + ")"
			);
			damtd1.appendChild(damtext);

			var damtd2=document.createElement('TD');
			damtr.appendChild(damtd2);
			
			var adr = damdata[i].address.stripTags();
			if(damdata[i].location){
				this.selectDamEvent(damtr,damdata[i]);
				if(damdata[i].location.confirmed != 1){
					adr += "(位置未確認)";
				}
			}
			else{
				adr += "(位置情報無し)";
			}
			var damtext=document.createTextNode(adr);
			damtd2.appendChild(damtext);
			
		}
		this.damlist.appendChild(damTable);
	},
	
	selectDamEvent:function(target,damdata){
		target.onclick = function(){
			this.setTargetDam(damdata);
		}.bind(this);
	},
	
	setTargetDam:function(damdata){
		this.dataman.setPopupKey(damdata.damno);
		this.dataman.map.setCenter(new GLatLng(damdata.location.y,damdata.location.x));
		this.dataman.tryPopup();
		this.switchPanel();
		
	},
	
	setAddressdataRequestEvent:function(target){
		target.onclick = function(){
			this.cookieman.setCookie("searchoperation","address");
			this.setAddressdataRequest();
		}.bind(this);
	},
	
	setAddressdataRequest:function(){
		var searchString = this.keywordField.value;
		
		if(searchString == ""){
			return;
		}
		

		this.damlist.innerHTML = "地名データ取得中です…";

		//ジオコーディングするためのオブジェクト作成
		var geo = new GClientGeocoder();
		geo.getLocations(searchString,this.onGeocoding.bind(this));
	},
	
	onGeocoding:function(result){
		this.damlist.innerHTML = "";
		
		var damTable=document.createElement('TABLE');
		damTable.setAttribute('border','0');
		var damTableBody=document.createElement('TBODY');
		damTable.appendChild(damTableBody);
		
		if (!result || result.Status.code != 200 || result.Placemark.length == 0) {
			
			this.damlist.innerHTML = "該当する地名を取得できません";
			
		} else {
			for(var i = 0; i< result.Placemark.length; i++){
				place = result.Placemark[i];
				
				address = place.AddressDetails.Country.AddressLine[0];
				
				point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
				map_bounds = new GLatLngBounds(point);

				var damtr = document.createElement('TR');
				damtr.onmouseover = function(){
					this.style.backgroundColor="#cccccc";
				};
				damtr.onmouseout = function(){
					this.style.backgroundColor='transparent';
				};

				damTableBody.appendChild(damtr);
				
				this.selectAddressEvent(damtr,point);

				var damtd1=document.createElement('TD');
				damtr.appendChild(damtd1);
				var damtext=document.createTextNode(address);
				damtd1.appendChild(damtext);


			}
		}
		this.damlist.appendChild(damTable);
	},
	
	selectAddressEvent:function(target,point){
		target.onclick = function(){
			this.setAddress(point);
		}.bind(this);
	},
	
	setAddress:function(point){
		this.dataman.map.setCenter(point);
		this.switchPanel();
	},
	
	switchPanel:function(hideflag){
		if(hideflag){
			if(this.panelFlag){
				this.listarea.style.display = "none";
				this.panelFlag = false;
			}
			return;
		}
		
		if(this.panelFlag){
			this.listarea.style.display = "none";
			this.panelFlag = false;
		}
		else{
			this.listarea.style.display = "block";
			this.panelFlag = true;
			switch(cookieman.getCookie("searchoperation")){
				case "keyword":
					this.setDamdataRequest("keyword");
				break;
				case "river":
					this.setDamdataRequest("river");
				break;
				case "address":
					this.setAddressdataRequest("address");
				break;
			}
		}
	}
};


//地図関係リンク管理
DMap.LinkManager = Class.create();
DMap.LinkManager.prototype = {
	divlink:null,
	map:null,
	initialize:function(gmap2,divlink){
		this.divlink = divlink;
		this.map = gmap2;
	},

	drawlink:function(){
		var centerpoint = this.map.getCenter();
		var bounds = this.map.getBounds();
		var zoom = this.map.getZoom();
		var pointj = this.wtoj(centerpoint.lng(),centerpoint.lat());
		var wlat = this.hourTohms(centerpoint.lat());
		var wlng = this.hourTohms(centerpoint.lng());
		
		var h = "<a href='?ll=" + centerpoint.toUrlValue() + "&z=" + zoom + "'>地図の中心位置のリンク</a><br>";
		h += "<a href='s/?a=" + bounds.getSouthWest().toUrlValue() + "," + bounds.getNorthEast().toUrlValue() + "' target='_blank'>地図上にあるダムの諸元表を開く</a><br>";
		h += "<a href='al/?a=" + bounds.getSouthWest().toUrlValue() + "," + bounds.getNorthEast().toUrlValue() + "' target='_blank'>地図帳を開く</a>-Powered by <a href='http://www.alpslab.jp/'>ALPSLAB</a><br>";
		h += "この位置を地図サービスで開く ";
		h += "<a href='http://maps.google.co.jp/maps?ll=" + centerpoint.toUrlValue() + "&z=" + zoom + "' target='_blank'>GM</a>";
		h += " <a href='http://map.livedoor.com/map/?ZM=10&MAP=E" + pointj.x.h + "."  + pointj.x.m + "." + pointj.x.s + "N" + pointj.y.h + "."  + pointj.y.m + "." + pointj.y.s  + "' target='_blank'>LD</a>";
		h += " <a href='http://map.yahoo.co.jp/pl?nl=" + pointj.y.h + "."  + pointj.y.m + "." + pointj.y.s + "&el=" + pointj.x.h + "."  + pointj.x.m + "." + pointj.x.s  + "&sc=4' target='_blank'>Y!</a>";
		h += " <a href='http://base.alpslab.jp/?s=250000;p=" + pointj.y.h + "/"  + pointj.y.m + "/" + pointj.y.s + "," + pointj.x.h + "/"  + pointj.x.m + "/" + pointj.x.s  + "' target='_blank'>AB</a><br>";
		h += "<a href='http://tikajya.x0.com/?y=" + centerpoint.lat() + "&x=" + centerpoint.lng() + "' target='_blank'>近くのホテル・旅館を検索(TiKaJYa!)</a><br>";
/******
 川の防災情報リニューアルに付きリンク中止
		h += "<a href='http://www.river.go.jp/jsp/mapFrame/MapD200.jsp?longitude=" + this.numToNN(pointj.x.h) + "." + this.numToNN(pointj.x.m) + "." + this.numToNN(pointj.x.s) + "&latitude=" + this.numToNN(pointj.y.h) + "." + this.numToNN(pointj.y.m) + "." + this.numToNN(pointj.y.s) + "&scale=3&time=&position=D200&telemeter=1' target='_blank'>テレメータ水位図(川の防災情報)</a><br>";
******/
		this.divlink.innerHTML = h;
		$("centerlat").innerHTML = wlat.h + "°" + wlat.m + "′" + wlat.s + "″";
		$("centerlng").innerHTML =  wlng.h + "°" + wlng.m + "′" + wlng.s + "″";
		
	},
	
	hourTohms:function(hour){
		var h = Math.floor(hour);
		var m = Math.floor((hour - h) * 60);
		var s = Math.floor((hour - h - m * (1/60)) * 3600 * 10) / 10;
		if(Math.floor(s) == s){
			s = s + ".0";
		}
		return {"hour":hour,
				"h":h,
				"m":m,
				"s":s};
	},
	
	wtoj:function(x,y){
		var jy = y + 0.00010696 * y - 0.000017467 * x - 0.0046020;
		var jx = x + 0.000046047 * y + 0.000083049 * x - 0.010041;
		
		var yhms = this.hourTohms(jy);
		var xhms = this.hourTohms(jx);
		
		return {"y":yhms,"x":xhms};
	},
	
	numToNN:function(numvalue){
		var intnum = Math.floor(numvalue)
		if(intnum < 10){
			return "0" + intnum.toString();
		}
		else{
			return intnum;
		}
	}
};


