//miyakoFunc.js

	function toTop(){
		jQuery('#main-container').load("../miyako/top.jsp", null, toMapCB);
	}
	function toTopCB() {
		;
	}
	
	function toMap(){
		jQuery('#main-container').load("../miyako/map.jsp", null, toMapCB);
	}
	function toMapCB() {
		initIcon();
		initMap();
		initCenterMark();
	}
	var map;
	var mapMode = 1;
	var mapEventDate;
	var markerList = new Array();
	var iconList = new Array();
	var _lock = false;
	function initMap() {
   		if(GBrowserIsCompatible()) {
	    	var divMap = document.getElementById("map-area");
	   		map = new GMap2(divMap);
	   		map.setCenter(new GLatLng(36.5551132469, 139.88280594), 16);
	   		map.setMapType(G_NORMAL_MAP);
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GOverviewMapControl());
			map.addControl(new GScaleControl());
			
			GEvent.addListener(map, "moveend", function(){
				reloadMapContents();
				_lock = false;
			});
			initLayerList();
			mapEventDate = getCurrentDateStr();
		}
	}
	function initCenterMark() {
   		if(GBrowserIsCompatible()) {
			var mark = document.createElement("div");
			//var x = (695 - 42) / 2;
			//var y = (450 - 42) / 2;
			var x = (695 - 42) / 2 + 10;
			var y = (450 - 42) / 2 + 10;
			mark.style.position = "absolute";
			mark.style.top = y+"px";
			mark.style.left = x+"px";
			mark.style.backgroundImage = "url(../img/center.gif)";
			mark.style.width = "21px";
			mark.style.height = "21px";
			mark.style.opacity = 0.5;
			map.getContainer().appendChild(mark);
   		}
	}
	function initLayerList() {
 		AjMiyako.getFacilityKindList(getFacilityKindListCB);
	}
	function getFacilityKindListCB(facilityKindList) {
		var tbody = jQuery('#fackind_list_body');
		tbody.children().remove();
		tbody.append(createFacilityKindTrList(facilityKindList));
 		AjMiyako.getEventKindList(getEventKindListCB);
	}
	function createFacilityKindTrList(facilityKindList) {
		var s = "";
		s += '<tr>';
		var len = facilityKindList.length;
		for(var i = 0; i < len; i++) {
			var facilityKind = facilityKindList[i];
			var checked = (facilityKind[3] == 1)? " checked" : "";
			s += '<td width="33" align="left">'
				+'<img src="../img/' + facilityKind[2] + '" title="'+ facilityKind[1] + '"/>'
				+'<input type="checkbox" name="chk_layer_f" value="'
				+ facilityKind[0] + '" ' + checked  + ' />' 
				+'<td width="65" align="left">'
				+ facilityKind[1]
				+ '</td>';
			if((i+1) % 2 == 0 && i < len-1) {
				s += "</tr><tr>";
			}
		}
		s += "</tr>";
		return s;
	}
	function getEventKindListCB(eventKindList) {
		var tbody = jQuery('#eventkind_list_body');
		tbody.children().remove();
		tbody.append(createEventKindTrList(eventKindList));
		reloadMapContents();
	}
	function createEventKindTrList(eventKindList) {
		var s = "";
		var len = eventKindList.length;
		for(var i = 0; i < len; i++) {
			var eventKind = eventKindList[i];
			var checked = (eventKind[3] == "1")? " checked" : "";
			s += '<tr>';
			s += '<td width="190" align="left">'
				+'<img src="../img/' + eventKind[2] + '" title="'+ eventKind[1] + '"/>'
				+'<input type="checkbox" name="chk_layer_e" value="'
				+ eventKind[0] + '" ' + checked +' />' 
				+ eventKind[1]
				+ '</td>';
			s += "</tr>";
		}
		return s;
	}
	function td(s) {
		if(s == "") return "　";
		return s;
	}
	function initIcon() {
		createIcon(0, "../img/icon0000.png");
		createIcon(1, "../img/icon0001.png");
		createIcon(2, "../img/icon0002.png");
		createIcon(3, "../img/icon0003.png");
		createIcon(4, "../img/icon0004.png");
		createIcon(5, "../img/icon0005.png");
		createIcon(6, "../img/icon0006.png");
		createIcon(7, "../img/icon0007.png");
		createIcon(8, "../img/icon0008.png");
		createIcon(9, "../img/icon0009.png");
		createIcon(10, "../img/icon0010.png");
		createIcon(11, "../img/icon0011.png");
		createIcon(12, "../img/icon0012.png");
		createIcon(13, "../img/icon0013.png");
		createIcon(14, "../img/icon0014.png");
		createIcon(15, "../img/icon0015.png");
		createIcon(16, "../img/icon0016.png");
		createIcon(17, "../img/icon0017.png");
		createIcon(18, "../img/icon0018.png");
		createIcon(19, "../img/icon0019.png");
		createIcon(20, "../img/icon0020.png");
		createIcon(21, "../img/icon0021.png");
		createIcon(22, "../img/icon0022.png");
		createIcon(23, "../img/icon0023.png");
		createIcon(99, "../img/icon0099.png");
		createIcon(101, "../img/event0001.png");
		createIcon(102, "../img/event0002.png");
		createIcon(103, "../img/event0003.png");
		createIcon(104, "../img/event0004.png");
		createIcon(105, "../img/event0005.png");
		createIcon(106, "../img/event0006.png");
		createIcon(107, "../img/event0007.png");
		createIcon(108, "../img/event0008.png");
		createIcon(109, "../img/event0009.png");
		createIcon(110, "../img/event0010.png");
		createIcon(111, "../img/event0011.png");
		createIcon(112, "../img/event0012.png");
		createIcon(113, "../img/event0013.png");
		createIcon(114, "../img/event0014.png");
	}
	function createIcon(i, iconName) {
		iconList[i] = new GIcon();
		iconList[i].image = iconName;
		iconList[i].iconSize = new GSize(25, 25);
		//iconList[i].iconAnchor = new GPoint(25, 35);
		iconList[i].iconAnchor = new GPoint(12, 25);
		iconList[i].infoWindowAnchor = new GPoint(25, 5);
		iconList[i].shadow = "../img/shadow1.png";
	}
	function reloadMapContents() {
		if(_lock) return;
		jQuery('#map-area').block({
            message: 'データを取得しています...',
            css: { border: '1px solid #EC7810',	opacity: .9},
			overlayCSS: { backgroundColor: '#CCC', opacity: .5}
        });
		var rect = getMapRect();
		var layerDisp = getLayerDisp();
		var scale = map.getZoom();
 		AjMiyako.loadContents(reloadMapContentsCB, rect.x1, rect.y1, rect.x2, rect.y2, mapMode, mapEventDate, layerDisp, scale);
	}
	var Rect = function(x1, y1, x2, y2){
	    this.x1 = x1;
	    this.y1 = y1;
	    this.x2 = x2;
	    this.y2 = y2;
	};
	Rect.prototype = { x1:0, x2:0 ,y1:0, y2:0 };
	var markerList;
	function reloadMapContentsCB(contentsList) {
		map.clearOverlays();
		markerList = new Array();
		var len = contentsList.length;
		for(var i = 0; i < len; i++) {
			var contents = contentsList[i];
			makeMarker(contents);
		}
		reloadContentsTable(contentsList);
		getAddress(map.getCenter());
		jQuery('#map-area').unblock();
	}
	function makeMarker(contents) {
		var contentsId = contents[0];
		var contentsName = contents[1];
		var lng = contents[2];
		var lat = contents[3];
		var iconName = contents[4];
		markerList[contentsId] = new GMarker(new GLatLng(lat, lng),	{
			id: contentsId,
			icon: iconList[iconName],
			title: contentsName
		});
		GEvent.addListener(markerList[contentsId], "click", function() {
			map.closeInfoWindow();
			var dir;
			var detail = '';
			if(isFacilityMode()) {
				dir = "facility";
				if(contents[6] != '') {
					detail += '住所：' + contents[6] + '<br>';
				}
				if(contents[7] != '') {
					detail += '電話番号：' + contents[7] + '<br>';
				}
			} else {
				dir = "event";
				if(contents[6] != '') {
					if(contents[11] != '') {
						detail += '場所：<a href="../facility/detail.jsp?p='+contents[11]+'" target="_blank">' + contents[6] + '</a><br>';
					} else {
						detail += '場所：' + contents[6] + '<br>';
					}
				}
				if(contents[7] != '') {
					detail += '電話番号：' + contents[7] + '<br>';
				}
			}
			markerList[contentsId].openInfoWindowHtml('<div id="mapInfoWindow" class="mapInfoWindow">'+
					'<a href="../' + dir + '/detail.jsp?p='+contentsId+'" target="_blank">'+markerList[contentsId].getTitle()+'</a><br><br>' +
					detail + '</div>');
			
			_lock = true;
		});
		GEvent.addListener(markerList[contentsId], "infowindowclose", function() {
			_lock = false;
		});
		map.addOverlay(markerList[contentsId]);
	}
	function reloadContentsTable(contentsList) {
		var tbody = jQuery('#map_list_body');
		tbody.children().remove();
		tbody.append(createContentsTrList(contentsList));
		var len = contentsList.length;
		jQuery('#map-area-title').html(isFacilityMode()? '<h3>子育てマップ　施設モード</h3>'
					:'<h3>子育てマップ　イベントモード 　【'+ formatYMD(mapEventDate) + 'のイベントを表示中です】</h3>');
		
		jQuery('#map-list-title').html(isFacilityMode()? '<b>地図に表示されている施設リスト（中心地から近い'+len+'件）</b>　※距離は中心地点からの直線距離です'
														:'<b>地図に表示されているイベントリスト（'+len+'件）</b> <img src="../img/attention.gif" align="absMiddle"> イベントを行っていない日がありますので詳細をご確認ください');

		jQuery('#map-list-tbl-head').html(isFacilityMode()? '<table class="map-list-tbl">'+
														'<tr>'+
														  '<th width="290px">施設名称</th>'+
														  '<th width="30px">詳細</th>'+
														  '<th width="60px">距離</th>'+
														  '<th width="150px">住所</th>'+
														  '<th width="90px">電話番号</th>'+
														  '<th width="20px">HP</th>'+
														' </tr>'+
														'</table>'
														:'<table class="map-list-tbl">'+
														'<tr>'+
														  '<th width="270px">イベント名称</th>'+
														  '<th width="30px">MAP</th>'+
														  '<th width="150px">開催場所</th>'+
														  '<th width="100px">開催日時</th>'+
														  '<th width="90px">電話番号</th>'+
														' </tr>'+
														'</table>');
	}
	function createContentsTrList(contentsList) {
		var s = "";
		var len = contentsList.length;
		for(var i = 0; i < len; i++) {
			var row = contentsList[i];
			if(isFacilityMode()) {
				s += '<tr>';
				s += '<td width="290" align="left"><img src="../img/'+row[9]+'"><a href="#" onclick="moveMapTo(' + row[2] + ',' + row[3] + ')" title="地図を移動します">' + (i+1) + '.' + row[1] + '</a></td>';
				s += '<td width="30" align="center"><a href="../facility/detail.jsp?p='+row[0]+'" target="_blank"><img src="../img/facility_icon.gif" title="施設詳細ページを開きます"></a></td>';
				s += '<td width="60" align="center">' + td(row[5]) + '</td>';
				s += '<td width="150" align="left">' + td(row[6]) + '</td>';
				s += '<td width="90" align="center">' + td(row[7]) + '</td>';
				if(row[8] != null && row[8] != '') {
					s += '<td width="20" align="center"><a href="' + row[8] + '" target="_blank"><img src="../img/hp_icon.gif" title="施設のホームページを開きます"></a></td>';
				} else {
					s += '<td width="20" align="center">　</td>';
				}
				s += "</tr>";
			} else {
				s += '<tr>';
				s += '<td width="270" align="left"><img src="../img/'+row[9]+'"><a href="../event/detail.jsp?p='+row[0]+'" target="_blank" title="ｲﾍﾞﾝﾄ詳細ページを開きます">' + (i+1) + '.' + row[1] + '</a></td>';
				s += '<td width="30" align="center"><a href="#" onclick="moveMapTo(' + row[2] + ',' + row[3] + ')"><img src="../img/map_icon.gif" title="地図を移動します"></a></td>';
				if(row[11] != null && row[11] != '') {
					s += '<td width="150" align="left"><a href="../facility/detail.jsp?p=' + row[11] + '" target="_blank">' + row[6] + '</td>';
				} else {
					s += '<td width="150" align="left">' + td(row[6]) + '</td>';
				}
				if(row[10] == "1") {
					s += '<td width="100" align="center">' + row[5] + '<img src="../img/attention.gif" align="absMiddle" title="定例（期間）イベント"/></td>';
				} else {
					s += '<td width="100" align="center">' + td(row[5]) + '</td>';
				}
				s += '<td width="90" align="center">' + td(row[7]) + '</td>';
				s += "</tr>";
			}
		}
		return s;
	}
	function formatYMD(ymd) {
		var ymdstr = ymd.toString();
		return ymdstr.substring(0, 4) + "年" + ymdstr.substring(4, 6) + "月" + ymdstr.substring(6, 8) + "日";
	}
	function getCurrentDateStr() {
		var dt = new Date();
		var y = dt.getFullYear();
		var m = dt.getMonth() + 1;
		var d = dt.getDate();
		if(m < 10) m = "0" + m;
		if(d < 10) d = "0" + d;
		var s = y + m + d;
		return s;
	}
	function isFacilityMode() {
		return (mapMode == 1);
	}
	function getMapRect() {
		var bounds = map.getBounds(); 
		var southWest = bounds.getSouthWest(); 
		var northEast = bounds.getNorthEast(); 
		var rect = new Rect(southWest.lng(), southWest.lat(), northEast.lng(), northEast.lat());
		return rect;
	}
	function getLayerDisp() {
		var s = "";
		var chkList = document.getElementsByName(mapMode == 1? "chk_layer_f" : "chk_layer_e");
		var len = chkList.length;
		for(var i = 0; i < len; i++) {
			if(chkList[i].checked == true) {
				if(s != "") s += ",";
				s += "'";
				s += chkList[i].value;
				s += "'";
			}
		}
		return s;
	}
	function setLayerDisp(kind, b) {
		var chkList = document.getElementsByName(mapMode == 1? "chk_layer_f" : "chk_layer_e");
		var len = chkList.length;
		for(var i = 0; i < len; i++) {
			if(chkList[i].value == kind) {
				chkList[i].checked = b;
			}
		}
	}
	// レイヤすべてON/OFF
	function setAllLayerDisp(b) {
		var chkList = document.getElementsByName(mapMode == 1? "chk_layer_f" : "chk_layer_e");
		var len = chkList.length;
		for(var i = 0; i < len; i++) {
			chkList[i].checked = b;
		}
	}
	// レイヤチェック
	function chkLayer() {
		reloadMapContents();
	}
	// 表示モード変更
	function chgMapMode(mode) {
		mapMode = mode;
		reloadMapContents();
	}
	// 地図表示対象イベント日付変更
	function chgMapEventDate(dateStr) {
		mapEventDate = dateStr;
		reloadMapContents();
	}
	// 住所検索
	function moveToAddress(){
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(jQuery('#address').val(), function(p){ 
			if(p != null) {
				map.panTo(p);
			}
		});
	}
	// 住所検索(TOPから）
	function _moveToAddress(address){
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(address, function(p){ 
			map.panTo(p);
		});
	}
	// 住所取得（緯度経度から）
	function getAddress(latlng) {
		if (latlng != null){ 
			var geocoder = new GClientGeocoder();
			geocoder.getLocations(latlng, showAddress); 
		}
	}
	// 住所表示
	function showAddress(res) {
		if (!res || res.Status.code != 200) { 
			//alert("Status Code:" + response.Status.code); 
		} else {
			var address = res.Placemark[0].address;
			if(address.indexOf('日本,') == 0) {
				address = address.substring(3);
			}
			jQuery('#map-area-navi').html(isFacilityMode()? '【'+address+'】付近を中心に表示しています'
					:'【' + address + '】付近を中心に表示しています ');
		}
	}
	
	// イベントカレンダー更新(TOP)
	function updateCalendar(ym) {
		jQuery('#event-calendar').load("cm/calendar.jsp?ym="+ym, null, updateCalendarCB);
	}
	// イベントカレンダー更新(カレンダー用)
	function updateEventCalendar(ym) {
		jQuery.ajaxSetup({
			cache: false
		});
		jQuery('#event-calendar').load("../event/calendar.jsp?ym="+ym, null, updateCalendarCB);
	}
	function updateCalendarCB() {
		;
	}
	// 地図表示用イベントカレンダー更新
	function updateMapCalendar(ym) {
		jQuery('#map-event-calendar').load("../map/calendar.jsp?ym="+ym, null, updateMapCalendarCB);
	}
	function updateMapCalendarCB() {
		;
	}
	
	// 詳細画面地図表示
	function initDetailMap(title, kind, x, y) {
   		if(GBrowserIsCompatible()) {
	    	var divMap = document.getElementById("detail-map-area");
	   		map = new GMap2(divMap);
	   		map.setCenter(new GLatLng(y, x), 17);
	   		map.setMapType(G_NORMAL_MAP);
			//map.addControl(new GLargeMapControl3D());
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GOverviewMapControl());
			map.addControl(new GScaleControl());
			//map.enableScrollWheelZoom();
			var marker = new GMarker(new GLatLng(y, x),	{
				icon: iconList[kind],
				title: title
			});
			map.addOverlay(marker);
		}
	}
	// 施設検索
	function searchFacility() {
		var text = jQuery('#facility_search_text').val();
		if(text == '') return;
		searchMessage();
 		AjMiyako.searchFacility(searchFacilityCB, text);
	}
	// 施設検索（TOPから）
	function _searchFacility(facility) {
		var text = facility;
		searchMessage();
 		AjMiyako.searchFacility(searchFacilityCB, text);
	}
	function searchMessage() {
		jQuery('#facility-search').block({
            message: '検索中',
            css: { border: '1px solid #EC7810',	opacity: .9},
			overlayCSS: { backgroundColor: '#CCC', opacity: .6}
        });
	}
	// 施設検索コールバック
	function searchFacilityCB(facilityList) {
		var div = jQuery('#facility-result');
		div.children().remove();
		div.append(createSearchedFacilityList(facilityList));
		var len = facilityList.length;
		jQuery('#facility-result-title').html('検索結果（'+len+'件）');
		jQuery('#facility-search').unblock();
	}
	function createSearchedFacilityList(facilityList) {
		var s = "";
		var len = facilityList.length;
		for(var i = 0; i < len; i++) {
			var facility = facilityList[i];
			s += '<p class="p-result"><a href="../facility/detail.jsp?p='+facility[0]+'" target="_blank" ><img src="../img/facility_icon.gif" title="施設詳細ページを開きます"></a><img src="../img/'+facility[4]+'"><a href="#" onclick="setLayerDisp('+facility[5]+',true);moveMapTo(' + facility[2] + ',' + facility[3] + ')" title="地図を移動します">' + (i+1) + '.' + facility[1] + '</a></p>';
		}
		return s;
	}
	// 地図移動
	function moveMapTo(x, y) {
		if(map != null) {
			map.panTo(new GLatLng(y, x));
		}
	}
	
	function beforeQa() {
		var msg = "";
		var title = jQuery('#f_title').val();
		var namae = jQuery('#namae').val();
		var mail = jQuery('#mail').val();
		var mail2 = jQuery('#mail2').val();
		var naiyou = jQuery('#naiyou').val();
		if(title == null || title == "") {
			msg += "タイトルを入力してください。\n";
		}
		if(namae == null || namae == "") {
			msg += "お名前を入力してください。\n";
		}
		if(mail == null || mail == "") {
			msg += "メールアドレスを入力してください。\n";
		}
		if(mail2 == null || mail2 == "") {
			msg += "メールアドレス（確認用）を入力してください。\n";
		}
		if(mail != null && mail2 != null && mail != mail2) {
			msg += "メールアドレスとメールアドレス（確認用）に違う文字列が入力されています。\n";
		}
		if(naiyou == null || naiyou == "") {
			msg += "内容を入力してください。\n";
		}
		if(msg.length > 0) {
			alert(msg);
			return false;
		}
		if(confirm("メールを送信します。よろしいですか？")) {
			return true;
		}
		return false;
	}
