var map;
var lastPrefCode;
var START_ZOOM = 9;
var ZOOMOUT_LIMIT = 8;

var openedInfoWindow;

// weather
var GET_WEATHER = 4;
var weatherPoint = new Array();
var weatherMarkers = null;

var movePrefControl;

/** ページ離脱時に読み出されるメソッド */
window.onunload = function() {
	map = null;
	lastPrefCode = null;
	weatherPoint = null;
	weatherMarkers = null;
}
/**
 * DOMの準備が完了したときに呼ばれるイベント
 */
window.addEvent('domready', function(){
	createMapApplication();

	// ツーリングスポットの書き換え
	getPoint();
	// 名産品の取得
	getLinkshare();
	// 天気予報の取得
	weatherCity();
	// 天気部分
	$('wheather-today').addEvent('click', function(){ weatherCity(true); });
	$('wheather-tommorow').addEvent('click', function(){ weatherCity(true); });
	if (new Date().getHours() < 12) {
		$('wheather-today').checked = true;
	} else {
		$('wheather-tommorow').checked = true;
	}
});
/**
 * 大きい地図の画面に移動するControl
 * @param controlDiv
 * @param map
 * @returns {MoveBigMap}
 */
function MoveBigMap(controlDiv, map) {
  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';

  // Set CSS for the control border
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '1px 2px 2px 1px';
  controlUI.style.borderColor = '#888888';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = '大きい地図のページに移動します';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('DIV');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.fontWeight = 'bold';
  controlText.style.padding = '3px 6px';
  controlText.innerHTML = '大きい地図で見る';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to
  // Chicago
  google.maps.event.addDomListener(controlUI, 'click', function() {
	// Cookie発行
	cookieSetLatLng(
		map.getCenter().lat().round(5),
		map.getCenter().lng().round(5),
		map.getZoom()
	);
	window.open('/map/', '_top');
  });
}

/**
 * 都道府県の画面に移動するControl
 * @param controlDiv
 * @param map
 * @returns {MoveBigMap}
 */
function MovePrefMap(controlDiv, map) {
	var movePrefUrl;

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';
  controlDiv.style.display = 'none';

  // Set CSS for the control border
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = '#F8F8F8';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '1px 2px 2px 1px';
  controlUI.style.borderColor = '#888888';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = '';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('DIV');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.fontWeight = 'bold';
  controlText.style.padding = '2px 6px';
  controlText.innerHTML = '';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to
  // Chicago
  google.maps.event.addDomListener(controlUI, 'click', function() {
	  if (movePrefUrl != null) {
			window.open(movePrefUrl, '_top');
	  }
  });

  this.setPref = function(prName, prUrl) {
	  movePrefName = prName;
	  movePrefUrl = prUrl;
	  if (prUrl != null) {
		  controlUI.title = prName + 'のページに移動します';
		  controlText.innerHTML = prName + 'のツーリング情報へ';
		  controlDiv.style.display = 'block';
	  } else {
		  controlDiv.style.display = 'none';
	  }
  }
}


/**
 * googleMapの生成。
 */
function createMapApplication() {
	// Mapの生成
	var lat = $('map-info-lat').innerHTML;
	var lng = $('map-info-lng').innerHTML;

    var latlng = new google.maps.LatLng(lat, lng);
    var mapOptions = {
      zoom: START_ZOOM,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.TERRAIN,

      disableDefaultUI: true,
      zoomControl: true,
      zoomControlOptions: {
          style: google.maps.ZoomControlStyle.SMALL,
          position: google.maps.ControlPosition.LEFT_TOP
      },
      mapTypeControl: true,
      mapTypeControlOptions: {
    	  style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
      },
      scaleControl: true,

      disableDoubleClickZoom: true,
      scrollwheel: false
    };
	map = new google.maps.Map($('google-map'), mapOptions);

	//カスタムコントロール
	var moveBigControlDiv = document.createElement('DIV');
	var moveBigControl = new MoveBigMap(moveBigControlDiv, map);
	moveBigControlDiv.index = 1;

	//カスタムコントロール
	var movePrefControlDiv = document.createElement('DIV');
	movePrefControl = new MovePrefMap(movePrefControlDiv, map);
	movePrefControlDiv.index = 2;

	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(moveBigControlDiv);
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(movePrefControlDiv);


	// center_changed イベント
	google.maps.event.addListener(map, "center_changed", function(mouseEvent) {
		// 逆ジオコーディング
		rgeocode(map.getCenter().lat(), map.getCenter().lng());
	});
	/*
	// moveend イベント
	GEvent.addListener(map, "moveend", function() {
	});
	*/
	// click イベント
	google.maps.event.addListener(map, "click", function(mouseEvent) {
		//移動する
		map.panTo(mouseEvent.latLng);
	});
	// zoom_changed イベント
	google.maps.event.addListener(map, "zoom_changed", function() {
		// zoom範囲の修正。これ以上広範囲は表示させない
		if (map.getZoom() < ZOOMOUT_LIMIT) {map.setZoom(ZOOMOUT_LIMIT);}
	});
	// map生成時に呼ばれる関数
	// 逆ジオコーディング
	rgeocode(map.getCenter().lat(), map.getCenter().lng());
}

/**
 * 逆ジオコーディング取得完了時に呼ばれるコールバック関数
 */
function callBackRgeocode(result){
	// 前回の住所表示をクリア
	$('map-info-pname').empty();
	$('map-info-mname').empty();
	if (result.status && result.result != null) {

		// 都道府県が変わったらページを切り替える
/*		var	newPref = result.result.prefecture.pcode;
	 	var pref = $('map-info-pcode').innerHTML;
		if (pref != newPref) {
			var url = '/pref/' + newPref + '/';
			window.open(url, '_top');
		}*/

		var prefecture = result.result.prefecture;
		var municipality = result.result.municipality;
		// 住所表示
		$('map-info-pname').set('text', prefecture.pname);
		$('map-info-mname').set('text', municipality.mname + ' 付近');

		// 前回の位置とことなる都道府県を表示しているときの処理
		if (lastPrefCode == null || lastPrefCode != prefecture.pcode) {
			// 都道府県別のページへのリンク
			if (prefecture.pcode == 1		// 北海道の例外処理
				|| prefecture.pcode == $('map-info-pcode').innerHTML) {
				// 新しい位置が、都道府県ページの県と同一
				movePrefControl.setPref(null, null);
			} else {
				// 都道府県別のページへのリンク
				var prUrl = '/pref/' + prefecture.pcode + '/';
				movePrefControl.setPref(prefecture.pname, prUrl);
			}
			lastPrefCode = prefecture.pcode;
		}
	} else {
		movePrefControl.setPref(null, null);
	}
}
/**
 * ツーリングスポットを取得する
 */
 function getPoint() {

	// requestするURLの生成
	var targetUrl = "/api-point.php"
		+ "?pref=" + $('map-info-pcode').innerHTML;

	new Request.JSON({	// mootools 1.2
			url: targetUrl,
			onComplete: callBackPoint}
	).get();
 }
/**
 * ツーリングスポット取得完了時に呼ばれる関数
 */
function callBackPoint(result){

	if (result.Items == null) {
	} else {
		var items = result.Items;
		items.each(function(item) {

			var type = item.type;
			var lat = Number.toFloat(item.lat);
			var lng = Number.toFloat(item.lng);
			var latlng = new google.maps.LatLng(lat, lng);


			var fukidashi;
			var markerOpt;

			var li;

			if (type == 'M') {
				// 道の駅タイプの処理
				markerOpt = michinoekiIcon();
				markerOpt.title = "道の駅 " + item.title;

				fukidashi = michinoekiFukidashi(item);

	 			// === リスト用の処理
	 			li = new Element('li', {
	 				'id':"michinoeki-" + item.id,
	 				'class':"michinoeki-li"
	 			}).appendText(item.title) ;

			} else if (type == 'S') {
				// スポットタイプの処理
				markerOpt = spotIcon();
				markerOpt.title = item.title;

				fukidashi = spotFukidashi(item);

	 			// === リスト用の処理
	 			li = new Element('li', {
	 				'id':"spot-" + item.id,
	 				'class':"spot-li"
	 			}).appendText(item.title) ;

			} else if (type == 'O') {
				// 温泉タイプの処理
				markerOpt = onsenIcon();
				markerOpt.title = item.title;

				fukidashi = onsenFukidashi(item);

	 			// === リスト用の処理
	 			li = new Element('li', {
	 				'id':"onsen-" + item.id,
	 				'class':"onsen-li"
	 			}).appendText(item.title) ;
			}

			if (markerOpt) {
				markerOpt.map = map;
				markerOpt.position = latlng;
				var marker = new google.maps.Marker(markerOpt);

				var infowindow = new google.maps.InfoWindow({
				    content: fukidashi
				});

				// click イベント
				google.maps.event.addListener(marker, "click", function() {
			 		// 情報ウィンドウを開く
			 		openInfoWindow(map, marker, infowindow);
				});

				if (li) {
					// リストにclickイベントを追加
					li.addEvent('click', function(e){
						new Event(e).stop();
				 		map.panTo(latlng);

				 		// 情報ウィンドウを開く
				 		openInfoWindow(map, marker, infowindow);
					});

					// リストに追加
 					li.setStyle('text-decoration', 'underline');
 					if (type == 'M') {
 	 	 				$('michinoeki-body-pref').adopt(li);
 	 	 	 			$('michinoeki-body-yet').setStyle('display', 'none');
 					} else if (type == 'S') {
 	 	 				$('spot-body-pref').adopt(li);
 	 	 	 			$('spot-body-yet').setStyle('display', 'none');
 					} else if (type == 'O') {
 	 	 				$('onsen-body-pref').adopt(li);
 	 	 	 			$('onsen-body-yet').setStyle('display', 'none');
 					}
				}
			}
		});
		items = null;
	}
	result = null;
	$$('.pref_ajax_loader').setStyle('display', 'none');
}
/**
 * 情報ウィンドウを開く
 */
function openInfoWindow(map, marker, infowindow) {
	if (openedInfoWindow) {
		// 開いているフキダシがあれば閉じる
		openedInfoWindow.close();
	}
	// closeclick イベント
	google.maps.event.addListener(infowindow, "closeclick", function() {
		openedInfoWindow = null;
	});
	// フキダシを開く
	infowindow.open(map, marker);
	openedInfoWindow = infowindow;
}
/**
 * リンクシェアのアイテムを取得する
 */
function getLinkshare() {

	// requestするURLの生成
	var targetUrl = "/linkshare-proxy.php"
		+ "?keyword=" + encodeURIComponent($('map-info-shortname').innerHTML + " グルメ")
		+ "&max=" + 20;

	new Request.JSON({	// mootools 1.2
			url: targetUrl,
			onComplete: callBackLinkshare}
	).get();
 }


var LINKSHARE_MAX = 10000;
var LINKSHARE_MIN = 1000;
var LINKSHARE_LIMIT = 3;

/**
 * リンクシェア取得完了時に呼ばれる関数
 */
function callBackLinkshare(result){

	if (result == null || result.items == null) {
		//何もしない
	} else {
/*
		var titlebox1left = new Element('div', {'class': 'title-box1-left'});
		titlebox1left.adopt(new Element('h2', {
			'id': 'linkshare-title'
			,'text': $('map-info-shortname').innerHTML + 'の名産品'
		}));

		var titlebox1 = new Element('div', {'class': 'title-box1'});
		titlebox1.adopt(new Element('div', {'class': 'title-box1-right'}));
		titlebox1.adopt(titlebox1left);
*/
		var parent = $('linkshare-flame');
//		parent.adopt(titlebox1);

		var i = 0;
		var last_productname = "";
		var items = result.items;
		items.each(function(item) {

//			<a href="http://click.linksynergy.com/fs-bin/click?id=Kf*2zSIiIFs&offerid=83416.60059361&type=2&subid=0" >
//			<IMG border=0 src="http://www7.daiei.co.jp/item/image/item/0181-219-2.jpg" ></a>
//			<IMG border=0 width=1 height=1 src="http://ad.linksynergy.com/fs-bin/show?id=Kf*2zSIiIFs&bids=83416.60059361&type=2&subid=0" >

			// 価格がLINKSHARE_MAXを越えるときは処理しない
			if (item.price < LINKSHARE_MAX && item.price > LINKSHARE_MIN && i < LINKSHARE_LIMIT) {

				if (last_productname != item.productname) {
			// 商品画像
			var img = new Element('img', {
				'src': item.imageurl
				,'class': 'linkshare-pic'
				,'title': item.productname
			});
			// リンク先
			var a = new Element('a', {
				'href': item.linkurl
				,'target': '_blank'
				,'title': item.productname
			});
			var a2 = a.clone();
			var a3 = a.clone();

			// アフィリに必要な画像
			var param = item.linkurl.substring(item.linkurl.indexOf('?'));
			param = param.replace("offerid", "bids");
			var img2 = new Element('img', {
				'src': 'http://ad.linksynergy.com/fs-bin/show' + param
				,'border': 0
				,'width': 1
				,'height': 1
			});

			// 画像リンク
			var pic = new Element('div', {'class': 'pic'});
			pic.adopt(a2.adopt(img));
			pic.adopt(img2);

			var dt = new Element('dt');
			dt.adopt(a3.set('text', item.productname));

/*			// 会社名
			var merchantname = new Element('dd', {
				'class': 'item-merchantname'
				,'text': item.merchantname
			});
			// カテゴリ
			var category = new Element('dd', {
				'class': 'item-merchantname'
				,'text': item.category.primary
			});
			// 価格
			var price = new Element('dd', {
				'class': 'item-price'
				,'text': item.price + ' 円'
			});
*/
			var dl = new Element('dl', {'class': 'linkshare-item'});
			dl.adopt(dt);
//			dl.adopt(merchantname);
//			dl.adopt(category);
//			dl.adopt(price);

			var div = new Element('div', {'class': 'linkshare-div'});
			div.adopt(pic);
			div.adopt(dl);

			parent.adopt(div);

			i++;
					last_productname = item.productname;
				}
			}
		});
	}
	result = null;
}

/**
 * 天気を得られる周辺都市の緯度経度を取得する
 */
 function weatherCity() {
	// 「取得中」表示に切り替え
	var d1 = new Element('div', {'class': 'weather-box0-left'});
	var d0 = new Element('div', {'class': 'weather-box0'}).adopt(
		new Element('div', {'class': 'weather-box0-right'}));
	d0.adopt(d1);
	setLoading(d1, '天気予報データ取得中');
	$('weather-body').empty().adopt(d0);

	// requestするURLの生成
	var targetUrl = weatherCityCache(
		+ $('map-info-lat').innerHTML,
		+ $('map-info-lng').innerHTML,
		+ GET_WEATHER);

	//jsonの取得
	new Request.JSON({	// mootools 1.2
			url: targetUrl,
			onComplete: callBackWeatherCity}
	).get();
 }
/**
 * 天気を得られる周辺都市の緯度経度を取得完了時に呼ばれる関数
 */
function callBackWeatherCity(result){
	var weatherFrame = $('weather-body');
	weatherFrame.empty();

	if (result == null || result.Result == null) {
		weatherFrame.set('text', '該当データはありません。');
		return;
	}
	// 周辺都市が得られた
		var items = result.Result;

		var i = 0;
		weatherMarkers = new Array();

		items.each(function(item) {
			item.Link.match(/.*city=(\d+)/);
			var key = RegExp.$1;

			// 今日の天気か明日の天気か
			if ($('wheather-today').checked) { 	key += "A";	}
			 else {								key += "B";	}

			// 緯度経度は少しずらして表示
			var lat = Number.toFloat(item.Lat) + 0.01;
			var lng = Number.toFloat(item.Lng) + 0.02;
			var latlng = new google.maps.LatLng(lat, lng);
			weatherPoint[key] = latlng;

			// ネットから天気予報取得
			var targetUrl =item.Link;
			if ($('wheather-today').checked) { 	targetUrl += "&day=today";	}
			 else {								targetUrl += "&day=tomorrow";	}

			//jsonの取得
			new Request.JSON({	// moolools 1.2
					url: weatherCache(targetUrl),
					onComplete: function (yohou) {
						setWeatherIcon(yohou);
						yohou = null;
					}
			}).get();
		});
		items = null;
	result = null;
}

/**
 * 天気アイコンと情報を設置する
 */
function setWeatherIcon(yohou){
	if (yohou == null || !yohou.link) return;

	// IDの生成
	yohou.link.match(/\/(\d+)\.html/);
	var key = RegExp.$1;
	if (yohou.title.indexOf('今日の天気') > 0) { key +="A"; }
	 else {										key +="B"; }
	var id = 'weather' + key;

	//情報BOX作成
	var box = makeWeatherBox(id, yohou);
	$('weather-body').adopt(box);

	// アイコン
	var latlng = weatherPoint[key];
	if (latlng != null) {
		var yohouOpt = wheatherIcon(yohou);
		yohouOpt.map = map;
		yohouOpt.position = latlng;
		var marker = new google.maps.Marker(yohouOpt);

		// 天気2吹き出し用Element
		var div2 = makeWeatherFukidashi(id, yohou);
		var weather = new Element('div', {'class': 'wheather'}).adopt(div2);
		var infowindow = new google.maps.InfoWindow({
		    content: weather
		});

		// click イベント
		google.maps.event.addListener(marker, "click", function() {
	 		// 情報ウィンドウを開く
	 		openInfoWindow(map, marker, infowindow);
		});

		// 天気情報にclickイベントを追加
		box.addEvent('click', function(e){
			new Event(e).stop();
			map.panTo(latlng);

	 		// 情報ウィンドウを開く
	 		openInfoWindow(map, marker, infowindow);
		});
		weatherMarkers[weatherMarkers.length] = marker;
	}
	yohou = null;
}

