/**
 * システム名　　： 地図連動ライブラリ
 * モジュール名　：　All-in
 * モジュール説明： WMPで地図連動を行うのに必要なライブラリ。GMapのライブラリも必要。
 * ターゲット　　：GMapが動作するブラウザ(GBrowserIsCompatible()で返し値がtrue）
 * ファイル名　　：wmp_gmap_lib.js
 * 更新履歴　　　：2007.09.18 Ver.0.00 Mra
 * @version 0
 * @since 2007-09-18
 * @author Mra
 * エンコーディング:UTF-8
 */
var areastatus;
var mgr;
var gmaps;
var WMP;
var laststvmarkerLocation;
var panorama;
var stvmarker;
var client;
var overlayInstance = null;
 if(!WMP){
 	WMP = {};
}

if(!WMP.Widget){
	WMP.Widget = {};
}
/**
 * WMP.Widget.GMap
 * @param {String} menuId 地図連動のメニュー表示部分の属性ID
 * @param {String} mapId　　地図連動の地図表示部分の属性ID
 * @param {Number} comId 業者番号
 * @return {none}
 * 引数は全て必須項目です。
 * optionsについては仕様書で確認して下さい。
 */
WMP.Widget.GMap = function(menuId,mapId,options)
{
	var self = this;
	/* GMapが動作するブラウザか確認 */
	if(!GBrowserIsCompatible()){
		this.errorUnsuportedBrowser();
		return false;
	}
	window.onunload = GUnload;

	/* デバッグモードの設定 */
	if(options.debug){
		this.debug = true;
	}else{
		this.debug = false;
	}
	if(!menuId ||  !mapId || !options){
		this.errorSettingParameters();
		return false;
	}
	if(options.comId){
		this.zenkoku_no = options.comId;
	}else{
		this.errorAlert('comIdを指定して下さい。');
		return;
	}

	this.requestUrl = "../../../../tool_2/google_maps/searchConditionItems.php?z=";
	this.requestUrl += this.zenkoku_no;
this.requestUrl += "&tool=" + options.tool;

	if(options.form){
		this.form = eval('document.' + options.form);
	}else{
		this.errorAlert('formを指定して下さい。');
		return;
	}

	this.ajaxCustomParam = options.ajaxCustomParam || '';


	//オプションのチェック
	if(this.isZoomLevel(options.defaultZoomLevel)){
		this.defaultZoomLevel = options.defaultZoomLevel;
	}else{
		this.errorZoomLevel('初回表示の');
		return false;
	}

	if(this.isZoomLevel(options.maxZoomLevel)){
		this.maxZoomLevel = options.maxZoomLevel;
	}else{
		this.errorZoomLevel('最大');
		return false;
	}

	if(this.isZoomLevel(options.minZoomLevel)){
		this.minZoomLevel = options.minZoomLevel;
	}else{
		this.errorZoomLevel('最小');
		return false;
	}

	if(options.satellite){
		gmapTypeSatellite = true;
	}else{
		this.mapTypeSatellite = false;
	}

	if(options.streetview){
		this.mapTypeStreetView = true;
	}else{
		this.mapTypeStreetView = false;
	}


	if(options.dualMap){
		this.mapTypeDual = true;
	}else{
		this.mapTypeDual = false;
	}

	//独自マーカー作成
	this.iconDirectory = options.iconDirectory || '../../../../tool_2/google_maps/icon/chin/';
	this.ICON = [];
	for (var i = 1; i <= 9; i++) {
		this.ICON[i] = new GIcon();
		this.ICON[i].image = this.iconDirectory + i + '.gif';//gif or png
		this.ICON[i].iconSize = new GSize(36,36);
		this.ICON[i].iconAnchor = new GPoint(18,18);//アイコンのアンカー
		this.ICON[i].infoWindowAnchor = new GPoint(18,3);//情報ウィンドウのアンカー設定（オリジナルアイコンではこれを指定しないと、infowindowを開く際エラーが起きるので注意！）
//		this.ICON[i].shadow = this.iconDirectory + 'm_shadow.png';
		this.ICON[i].shadow = 'NULL';
	}

	this.menuId = menuId;
	try{
		this.menu = document.getElementById(this.menuId);
	}
	catch(e){
		this.errorAlert('メニュー欄の領域を確保できませんでした。\nIDが存在するか確認して下さい。');
		return;
	}
	if(!this.menu) {
			this.errorAlert('メニュー欄の領域を確保できませんでした。\nIDが存在するか確認して下さい。');
			return;
	}

	try{
		this.mapField = document.getElementById(mapId);
		gmaps = new GMap2(this.mapField);
this.display();
//gmaps.setCenter(new GLatLng(35.658587,139.745425),4);

//ダイアログのメソッド追加
WMP.Widget.GMap.prototype.dialogOpen = function(zoom_mes){
	$("#dialog").dialog({
		bgiframe  : true,
		title     : '注意事項',
		resizable : false,
		draggable : false,
		width     : 360,
		height    : 250,
		position  : ['right','top'],
		buttons   : {'閉じる' : this.dialogClose}
	});
	$('#dialog').html('<span style="font-size: 14px;">' + zoom_mes + '</span>');
	$('#dialog').dialog('open');
}
//ダイアログのメソッド追加
WMP.Widget.GMap.prototype.dialogClose = function(){
	$('#dialog').dialog('close');
}


//初期位置の設定
if(options.defaultIdo != "" && options.defaultKeido != ""){
	gmaps.setCenter(new GLatLng(options.defaultIdo , options.defaultKeido),this.defaultZoomLevel); //初期位置
	var point2 = new GLatLng(options.defaultIdo , options.defaultKeido);
	var marker2 = new GMarker(point2)
	gmaps.addOverlay(marker2);
	gmaps.openInfoWindow(point2, options.defaultHtml);
}else{
	gmaps.setCenter(new GLatLng(1000,1000),this.defaultZoomLevel); //何もない場所を表示
}

	}
	catch(e){
		this.errorAlert('地図欄の領域を確保できませんでした。\nIDが存在するか確認して下さい。');
		return;
	}
	if(!gmaps) {
			this.errorAlert('地図欄の領域を確保できませんでした。\nIDが存在するか確認して下さい。');
			return;
	}

	//ズームレベルの指定
	GEvent.addListener(gmaps,"moveend", function() {
		var zml = gmaps.getZoom();
		if( zml > self.maxZoomLevel ) gmaps.setZoom(self.maxZoomLevel);
		else if ( zml < self.minZoomLevel ) gmaps.setZoom(self.minZoomLevel);





// 地図表示座標の取得
var rectObj = gmaps.getBounds();
var mapAreaSW = rectObj.getSouthWest();
var mapAreaNE = rectObj.getNorthEast();


	requestUrl = self.requestUrlCache.replace(/&pg=(\d+)/) + "&swlng=" + mapAreaSW.lng() + "&swlat=" + mapAreaSW.lat() + "&nelng=" + mapAreaNE.lng() +"&nelat=" + mapAreaNE.lat() + "&fullbk=1";

	//zoomlevelが変更になったらinfoWindowを削除する。（現在のzoomlevelを小窓に渡させないといけない為）
	GEvent.addListener(gmaps, 'zoomend',function(oldZoomLevel, newZoomLevel) {
		if(oldZoomLevel != newZoomLevel){
			//infoWindowを削除する。
			gmaps.closeInfoWindow();
		}
	});
	if(self.maxZoomLevel < zml){
		zml = zml - 1;
	}

	//***** クイックBtoB対応 hirabaru 20091119 start *****


GDownloadUrl(requestUrl,function(responseText,status){
	if(status == 200){

		try{
			var bkInfo = eval('('+responseText+')');
			var zoom_mes = '';
			var bkInfoData = [];
			/* リストの生成 */
			document.getElementById("bkList").innerHTML = '';
			var eleParent = document.createElement('div');

			var setCount = 0;
			for(var i = 0; i < bkInfo.data.length; i++){
				if(bkInfo.data[i].max_zoom >= zml){
					bkInfoData[setCount] = bkInfo.data[i];
					setCount++;
				}else{
					zoom_mes = 'この縮尺度では表示されなくなった物件が御座います。非表示物件を確認なさりたい場合には、縮尺度を一段階小さくしてご確認下さい。詳細については<a href="/help/search_map.html">こちら</a>をご確認下さい。';
				}
			}
			for(var i = 0; i < bkInfoData.length; i++){
				//***** クイックBtoB対応 hirabaru 20091119 start *****
				self.createList(bkInfoData[i],eleParent,i+1);
				//***** クイックBtoB対応 hirabaru 20091119 end *******
			}
			if(zoom_mes){
				self.dialogOpen(zoom_mes);
			}else{
				self.dialogClose();
			}

			document.getElementById("bkList").appendChild(eleParent);
		}catch(e){
			document.getElementById("bkList").innerHTML = '&nbsp;表示範囲に該当する物件が見つかりませんでした。';
			self.hideLoadDiv();
			return;
		}
	}
});









	});

	/* 検索Bパターン */
	this.pattern = 'A';
	if( options.fromLegacy && options.fromLegacy.length > 0 ) {
		this.getQuery = options.fromLegacy
		this.pattern = 'B'
	}
	/* CSS系 */
	this.listMouseoverClassName = 'listHover';
	this.listActiveClassName    = 'listActive';
	this.activeListElement;

	/* ローディング処理系 */
	this.loadDivId = 'loadDiv';
	this.createLoadDiv();

	/* 左メニュー系 */
	this.layers = [];
	this.prefecuters = null;
	this.cities = null;
	this.towns = null;
	this.prefChangeFlag = true;
	this.cityChangeFlag = true;
	this.townChangeFlag = true;
	this.currentLayer = 0;
	this.layerCount = 0;
/*	this.list = document.getElementById('bkList'); */
	this.getLayers();
	this.showAndHideLayers();
	this.pageNumber = 0;//ページング処理用ページ番号
	this.requestUrlCache = '';//検索URLの一時保存（ページング処理で使用）
	this.addNextBtnFlag = false;//次へボタンを表示するしないフラグ
	this.addPrevBtnFlag = false;//前へ…
	this.page = ''; //　何件から何件目を表示しているという意味の文字列が入る

	/* 地図系 */
	this.bukken = [];
	this.bukken.data = [];
	this.bukken.list = [];
	this.gmapIsShown = false;//地図表示中フラグ
	this.getPrefectures();

	if(this.pattern == 'B') {
		this.bSearch();
		this.resizeMapAndMenu();
	}

	//ウィンドウいっぱいに地図を表示する
	GEvent.addDomListener(window,'resize',function(){self.adaptMapSize(self.menuId,self.mapField)});
	this.adaptMapSize(this.menuId, this.mapField);
}





/**
 * 地図のサイズをcontainerのwidthからmenuのwidth分引いたサイズに変更する
 * @param {String} メニュDivのID menuId
 * @param {Object] 地図 map
 */
WMP.Widget.GMap.prototype.adaptMapSize = function(menuId,map){
	var container = document.getElementById('container');
	var menu = document.getElementById(menuId);
	if ( !menu ) return;
	var style = menu.currentStyle || document.defaultView.getComputedStyle(menu, '');
	var menuWidth = style.width.replace(/px$/,'');
	var cStyle = container.currentStyle || document.defaultView.getComputedStyle(container,'');
	var cWidth = cStyle.width;
	if ( /%$/.test(cWidth) ) cWidth = document.documentElement.clientWidth;
	if ( /px$/.test(cWidth)) cWidth = cWidth.replace(/px$/,'');
	var computedWidth = cWidth - menuWidth - 32; // -32はカラム落ち対策
var computedHeight = document.documentElement.clientHeight - 116; // -116は検索結果が1行+結果クリア行が見えるように配置
	map.style.width = computedWidth + 'px';
map.style.height = computedHeight + 'px';
container.style.height = computedHeight + 'px';
}


/**
 * DOM要素のclass属性にスペースを空けてcss用のクラス名を追加する
 * @param {Object} ele
 * @param {Object} className
 * @return {none}
 * @see WMP.Widget.GMap.prototype.showMarkerAndList
 */
WMP.Widget.GMap.prototype.addClassName = function(ele, className)
{
	if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
		return;
	ele.className += (ele.className ? " " : "") + className;
};

/**
 * DOM要素のclass属性から指定したクラス名を取り除く
 * @param {Object} ele
 * @param {Object} className
 * @return {none}
 * @see WMP.Widget.GMap.prototype.showMarkerAndList
 */
WMP.Widget.GMap.prototype.removeClassName = function(ele, className)
{
	if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
		return;
	ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};

WMP.Widget.GMap.prototype.setClassName = function(ele,className){
	if(!ele || !className|| (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1)) return;
	else ele.className = className;
}

/**
 * マーカーを地図上に追加する
 * @param {GMarker} marker
 * @param {MraList} DOM li element
 * @return {Number} 地図上に置かれたマーカーの数
 */

WMP.Widget.GMap.prototype.addMarkerAndListByJSON = function(bkInfo)
{
	this.page = bkInfo.page;
	if(bkInfo.position >= 0 && areastatus != 'hold'){
		gmaps.setCenter(new GLatLng(bkInfo.data[bkInfo.position].latitude,bkInfo.data[bkInfo.position].longitude),this.defaultZoomLevel);
	} else if (areastatus != 'hold') {
		gmaps.setCenter(new GLatLng(bkInfo.jumpido,bkInfo.jumpkeido),this.defaultZoomLevel);
	}
//	this.display();
	gmaps.clearOverlays();
mgr = new MarkerManager(gmaps);
	this.bukken.data = [];
	this.bukken.list = [];
	/* マーカーの生成 */

	for(var i = 0; i < bkInfo.data.length; i++){
		this.bukken.data.push(bkInfo.data[i]);
		this.createMarkerAndList(this.bukken.data[i]);
	}
	delete(bkInfo);















if (this.mapTypeStreetView == true){

  client = new GStreetviewClient();

  var latlng = new GLatLng(bkInfo.data[bkInfo.position].latitude-0.001,bkInfo.data[bkInfo.position].longitude-0.001);


  var guyIcon = new GIcon(G_DEFAULT_ICON);
  guyIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
  guyIcon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
  guyIcon.imageMap = [
        26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
        16,20, 16,14, 19,13, 22,8
     ];
  guyIcon.iconSize = new GSize(49, 52);
  guyIcon.iconAnchor = new GPoint(25, 35);  // near base of guy's feet
  guyIcon.infoWindowAnchor = new GPoint(25, 5);  // top of guy's head

  stvmarker = new GMarker(latlng, {icon: guyIcon, draggable: true});



    // ストリートビューマーカー設定

    laststvmarkerLocation = latlng;
  GEvent.addListener(stvmarker, "dragend", self.onDragEnd);
  GEvent.addListener(stvmarker, "click", self.openPanoramaBubble);
    GEvent.addListener(gmaps, 'click', function(overlay, latlng) {
      if (!overlay) {
	    client.getNearestPanorama(latlng, self.onResponse);
      }
    });




gmaps.addOverlay(stvmarker);


}
















mgr.refresh();


	/* マーカーを表示する */
	this.hideLoadDiv();

if (this.mapTypeStreetView == true){
	overlayInstance = new GStreetviewOverlay();
	gmaps.addOverlay(overlayInstance);
}

};
















WMP.Widget.GMap.prototype.activeList = function(ele){
	if(this.activeListElement) this.removeClassName(this.activeListElement,this.listActiveClassName);
	this.addClassName(ele,this.listActiveClassName);
	this.activeListElement = ele;
}


/**
 * マーカーと物件リストを生成する
 * @param {JSON} bkInfo 物件情報（値段や間取りなど）
 * @return {none}
 */

 WMP.Widget.GMap.prototype.createMarkerAndList = function(bkInfo)
 {
 	var self = this;
 	var marker;
 	var setInfoWindowURL = '';
 	var maxZoomLevel = '';
 	//***** ズームレベルの値設定 *****
 	maxZoomLevel = bkInfo.max_zoom;
 	marker = new GMarker(new GLatLng(bkInfo.latitude,bkInfo.longitude),self.ICON[bkInfo.c]);

 	GEvent.addListener(marker,'click',function(){
 		//***** クイックBtoB対応 hirabaru 20091119 start *****
 		setInfoWindowURL = '<iframe src="' + bkInfo.content + '&zml=' + gmaps.getZoom() + '" frameborder="0" style="border:none" width="220px"></iframe>';
 		marker.openInfoWindowHtml(setInfoWindowURL,{});
 		//***** クイックBtoB対応 hirabaru 20091119 end *****
 	});
 	if(self.maxZoomLevel > maxZoomLevel){
 		mgr.addMarker(marker,4,maxZoomLevel);
 	}else{
 		mgr.addMarker(marker,4);
 	}
 };



























/**
 * 物件リストを生成する
 * @param {JSON} bkInfo 物件情報（値段や間取りなど）
 * 		eleParent 親エレメント
 * 		ListNumber リスト番号
 * @return {none}
 */
WMP.Widget.GMap.prototype.createList = function(bkInfo,eleParent,ListNumber)
{
	var self = this;
	var eleList = document.createElement('div');
	var zml = gmaps.getZoom();
	var setInfoWindowURL = '';

	eleList.className = 'bkListLine';

	eleList.innerHTML =  '<span style="float:left;height:38px;margin-bottom:10px;">' + ListNumber + '. <img src="' + this.iconDirectory + bkInfo.c + '.gif" /></span><span class="listadd">' + bkInfo.address + '</span><br /><span class="listmadori">[' + bkInfo.madori_min + ']</span><span class="listmoney">' + '￥' + bkInfo.money_min + '</span>';
	var point = new GLatLng(bkInfo.latitude,bkInfo.longitude);

	GEvent.addDomListener(eleList,'click',function(){
		//***** クイックBtoB対応 hirabaru 20091119 start *****
		setInfoWindowURL = '<iframe src="' + bkInfo.content + '&zml=' + zml + '" frameborder="0" style="border:none" width="220px"></iframe>';
		gmaps.openInfoWindowHtml(point,setInfoWindowURL);
		//gmaps.openInfoWindowHtml(point,bkInfo.content);
		//***** クイックBtoB対応 hirabaru 20091119 end *****
	});

	GEvent.addDomListener(eleList,'mouseover',function(){self.addClassName(eleList,self.listMouseoverClassName);});
	GEvent.addDomListener(eleList,'mouseout',function(){self.removeClassName(eleList,self.listMouseoverClassName);});

	eleParent.appendChild(eleList);
};


























/**
 * 地図連動スタート！メソッド
 * @return {void} 何も返さない
 */
WMP.Widget.GMap.prototype.display = function()
{
	this.removeMapTypes();
	this.setAllControllers();
};

/**
 * WMP.Widget.GMap.prototype.isZoomLevel
 * 引数がGMapのズームレベルとして正しい値かチェックするメソッド
 * @param {Number} number ズームレベル
 * @return {Bool} 正当なズームレベルの場合に真を返す
 */
WMP.Widget.GMap.prototype.isZoomLevel = function(number)
{
	if((typeof number == 'number') && (number >=0 || number <= 19)){
		return true;
	}else{
		this.errorZoomLevel();
		return false;
	}
}

/**
 * WMP.Widget.GMap.prototype.errorAlert
 * debugモードの時にエラーの内容をアラートで表示します
 * @param {String} errorMessage
 * @return void
 */
WMP.Widget.GMap.prototype.errorAlert = function(errorMessage)
{
	if(this.debug){
		alert(errorMessage);
	}
	return;
};

/**
 * WMP.Widget.GMap.prototype.errorSettingParameters
 * WMP.Widget.GMapの引数を指定していない時に呼び出されるメソッド
 * @return void
 */
WMP.Widget.GMap.prototype.errorSettingParameters = function()
{
	this.errorAlert('初期値設定に誤りがあります。');
	return;
};

/**
 * WMP.Widget.GMap.prototype.errorUnsuportedBrowser
 * サポートされていないブラウザで閲覧した時に呼び出されるメソッド
 * @return void
 */

WMP.Widget.GMap.prototype.errorUnsuportedBrowser = function ()
{
	this.errorAlert('地図を表示できないブラウザを使用されています。');
	return;
};

/**
 * WMP.Widget.GMap.prototype.errorZoomLevel
 * 初期値設定の縮尺度が不正な場合に呼び出されるメソッド
 *
 */

WMP.Widget.GMap.prototype.errorZoomLevel = function(msg)
{
	if(msg) this.errorAlert(msg + '縮尺度数が不正です');
	else this.errorAlert('縮尺度数が不正です');
	return;
};



/**
 * プロパティを見て表示しないマップの種類を削除する（衛星写真・デュアル）
 * @return void
 */
WMP.Widget.GMap.prototype.removeMapTypes = function()
{
	if(this.mapTypeDual == false) gmaps.removeMapType(G_HYBRID_MAP);
	if(this.mapTypeSatellite == false) gmaps.removeMapType(G_SATELLITE_MAP);
	return;
}

/**
 * WMP.Widget.GMap.prototype.setAllControllers
 * GMapで使用するコントローラを表示する
 * @return void;
 */
WMP.Widget.GMap.prototype.setAllControllers = function()
{
	gmaps.addControl(new GSmallMapControl());
	gmaps.addControl(new GOverviewMapControl());
	gmaps.addControl(new GMapTypeControl());
	gmaps.addControl(new GScaleControl());












if (this.mapTypeStreetView == true){
//ストリートビューボタンを作成する
	gmaps.addControl(new TextualSVControl());
}





gmaps.addControl(new google.maps.LocalSearch(
{
searchFormHint : 'ここから住所や駅名等の入力で移動できます。「市区町村名　駅名」の複合検索も可能です。',
resultList : document.getElementById("lsresults")
}),
new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0,-30))
);





















gmaps.enableContinuousZoom();
gmaps.enableDoubleClickZoom();
	return;
}


 /**
 * this.menu内のDIVを取得する
 */

 WMP.Widget.GMap.prototype.getLayers = function()
{
	var menuDiv = this.menu.getElementsByTagName('DIV');
	var menuDivLen = menuDiv.length;
	for(var i = 0; i < menuDivLen; i++){
		var self = this;
		var child = menuDiv[i];
		if(child.nodeType == 1 && child.tagName == 'DIV' && child.className == 'layer'){
			this.layers.push(child);
		}
	}
	var layerCount = this.layers.length;
	this.layerCount = layerCount;
};

/**
 * レイヤーを表示・非表示
 *
 */
WMP.Widget.GMap.prototype.showAndHideLayers = function()
{
	if ( this.pattern == 'B' )  this.currentLayer = 4;
	for(var i = 0; i < this.layerCount; i++){
		if(i == this.currentLayer){
			this.layers[i].style.display = "block";
		}else{
			this.layers[i].style.display = "none";
		}
	}
};

/**
 * 県
 */
WMP.Widget.GMap.prototype.getPrefectures = function(){
	var requestUrl = this.requestUrl;
	requestUrl    += ( this.ajaxCustomParam ) ? '&' + this.ajaxCustomParam : '';
	requestUrl    += '&cmd=';
	requestUrl    += 'pref';
	requestUrl    += '&ac='; //anti-cache
	requestUrl    += (new Date).getTime();
	var self = this;
	GDownloadUrl(requestUrl,function(responseText,status){
		if(status == 200){
			var pref;
			try{
				pref = eval('('+ responseText +')');
				self.prefectures = pref;
				self.setPrefectures();
			}catch(e){
				self.errorAlert('県evalエラー:'+ e.message);
				pref = false;
				return;
			}
		}
	});

};

/**
 * 県選択フォームを表示する
 */
WMP.Widget.GMap.prototype.setPrefectures = function()
{
	if(this.prefectures){
		var i =0;
		var count = this.prefectures.length;
		var prefItem = document.getElementById('prefItem');
		var unorderList = document.createElement('ul');
		var li;
		var self = this;
		while(prefItem.hasChildNodes()){
			prefItem.removeChild(prefItem.firstChild);
		}
if (count < 1){
	prefItem.innerHTML = '<p style="color:red;">&nbsp;現在ご案内できる物件がありません。<p>';

} else if(count == 1){
	var radio = document.createElement('span');
	radio.innerHTML = '<input type="radio" name="pref" id="pref' + self.prefectures[0].num + '" value="' + self.prefectures[0].num + '" checked="checked">';

document.getElementById('prefItem').appendChild(radio);
	self.prefChangeFlag = true;
	self.currentLayer++;
self.showAndHideLayers();
self.getCities();

} else {
document.getElementById('prefMessage').innerHTML = '※表示させたい都道府県を選択してください';
		for(i = 0; i < count; i++){
			li = document.createElement('li');
var radio = document.createElement('span');
radio.innerHTML = '<input type="radio" name="pref" id="pref' + this.prefectures[i].num + '" value="' + this.prefectures[i].num + '">';
var text = document.createElement('span');
text.innerHTML = '<label for="pref' + this.prefectures[i].num + '">' + this.prefectures[i].name + '</label>';
			GEvent.addDomListener(radio,'click',function(){
self.prefChangeFlag = true;
if( self.getCities() == false) self.currentLayer--;
self.currentLayer++;
self.showAndHideLayers();
});
li.appendChild(radio);
li.appendChild(text);
			GEvent.addDomListener(li,'mouseover',function(){
				document.body.style.cursor = 'pointer';
			});
			GEvent.addDomListener(li,'mouseout',function(){
				document.body.style.cursor = 'default';
			});
			unorderList.appendChild(li);

		}
		prefItem.appendChild(unorderList);
}
	}
};

/**
 * 市
 */
WMP.Widget.GMap.prototype.getCities = function()
{
	this.showLoadDiv();
	if (!this.prefChangeFlag) {
		this.hideLoadDiv();
		return;
	}
	var self = this;
	var pref = this.form.getElementsByTagName('INPUT');
	var plen = pref.length;
	var kenV = [];
	var requestUrl = this.requestUrl;
	requestUrl    += ( this.ajaxCustomParam ) ? '&' + this.ajaxCustomParam : '';
	requestUrl    += '&cmd=';
	requestUrl    += 'city';
	requestUrl    += '&ac='; //anti-cache
	requestUrl    += (new Date).getTime();
	var checkedFlag = false;
	for(var i = 0; i < plen; i++){
		if(pref[i].checked && pref[i].name == 'pref'){
			requestUrl += '&pref[]=';
			requestUrl += pref[i].value;
			checkedFlag = true;
		}
	}
	if ( checkedFlag == false ) {
		alert('都道府県を選択してください。');
		this.hideLoadDiv();
		return false;
	}
	GDownloadUrl(requestUrl,function(responseText,status){
		if(status == 200){
			try{
				self.cities = eval(responseText);

			}catch(e){
				self.errorAlert('市evalエラー:'+ e.message);
				self.cities = null;
				return false;
			}
			self.setCities();
		}
	});

};

/**
 * 市のチェックボックスを表示する
 */
WMP.Widget.GMap.prototype.setCities = function()
{
	if(this.cities){
		var i =0;
		var count = this.cities.length;
		var countCity;
		var checkbox;
		var text;
		var cityItem = document.getElementById('cityItem');
		var unorderList = document.createElement('ul');
		var unorderList2;
		var li;
		var pref = this.cities;
		var city;
		var self = this;
		var label;
		while(cityItem.hasChildNodes()){
			cityItem.removeChild(cityItem.firstChild);
		}
		for(i = 0; i < count; i++){
			city = pref[i].values;
			li = document.createElement('li');
			text = document.createTextNode(pref[i].name);
			li.appendChild(text);
			unorderList.appendChild(li);
			countCity = city.length;
			if(countCity > 0){
				unorderList2 = document.createElement('ul');
document.getElementById('cityMessage').innerHTML = '※表示させたい市区町村を選択してください';
				for(var j = 0; j < countCity; j++){
var radio2 = document.createElement('span');
radio2.innerHTML = '<input type="radio" name="c" id="city' + city[j].num + '" value="' + city[j].num + '">';
var text2 = document.createElement('span');
text2.innerHTML = '<label for="city' + city[j].num + '">' + city[j].name + '</label>';

					label = document.createElement('label');
					label.setAttribute('for', 'city' + city[j].num);
					li = document.createElement('li');
					checkbox = document.createElement('input');
					checkbox.setAttribute('id', 'city' + city[j].num);
					checkbox.type = 'radio';
					checkbox.name = 'c';
					checkbox.value = city[j].num;
					text = document.createTextNode(city[j].name);
					GEvent.addDomListener(radio2,'click',function(){
self.cityChangeFlag = true;
if( self.getTowns() == false) self.currentLayer--;
self.currentLayer++;








						self.showLoadDiv();
						if ( self.getAllFormValues() == false ){
							self.currentLayer--;
							self.hideLoadDiv();
							return;
						}
						self.resizeMapAndMenu(1);


var bkreloadButton = document.createElement('a');
var str = document.createTextNode("対象物件変更");
bkreloadButton.appendChild(str);
bkreloadButton.href = '#';
GEvent.addDomListener(bkreloadButton,'click',function(){
areastatus = 'hold';
	mgr.clearMarkers();
	self.getAllFormValues();
document.getElementById("bkList").innerHTML = '&nbsp;検索中です。しばらくお待ちください';



// 地図表示座標の取得
var rectObj = gmaps.getBounds();
var mapAreaSW = rectObj.getSouthWest();
var mapAreaNE = rectObj.getNorthEast();


	requestUrl = self.requestUrlCache.replace(/&pg=(\d+)/) + "&swlng=" + mapAreaSW.lng() + "&swlat=" + mapAreaSW.lat() + "&nelng=" + mapAreaNE.lng() +"&nelat=" + mapAreaNE.lat() + "&fullbk=1";



GDownloadUrl(requestUrl,function(responseText,status){
		if(status == 200){
			try{
				var bkInfo = eval('('+responseText+')');
	/* リストの生成 */

document.getElementById("bkList").innerHTML = '';

var eleParent = document.createElement('div');
for(var i = 0; i < bkInfo.data.length; i++){




		self.createList(bkInfo.data[i],eleParent,i+1);


}
document.getElementById("bkList").appendChild(eleParent);


			}catch(e){
document.getElementById("bkList").innerHTML = '&nbsp;表示範囲に該当する物件がありませんでした。';
				self.hideLoadDiv();
				return;
			}
		}
	});














}
);

document.getElementById("bkreload").innerHTML = '';
document.getElementById("bkreload").appendChild(bkreloadButton);














var areareselectButton = document.createElement('a');
var str = document.createTextNode("地域再選択");
areareselectButton.appendChild(str);
areareselectButton.href = '#';
GEvent.addDomListener(areareselectButton,'click',function(){
areastatus = '';
document.getElementById("bkList").innerHTML = '';
	self.currentLayer = 0;
self.showAndHideLayers();
	mgr.clearMarkers();
self.getPrefectures();
}
);

document.getElementById("areareselect").innerHTML = '';
document.getElementById("areareselect").appendChild(areareselectButton);











self.showAndHideLayers();

});
//					li.appendChild(checkbox);
//					label.appendChild(text);
//					li.appendChild(label);
li.appendChild(radio2);
li.appendChild(text2);
					unorderList2.appendChild(li);
				}
				li = document.createElement('li');
				li.appendChild(unorderList2);
				unorderList.appendChild(unorderList2);
			}else{
				unorderList2 = document.createElement('ul');
				li = document.createElement('li');
				text = document.createTextNode('なし');
				li.appendChild(text);
				unorderList2.appendChild(li);
				li = document.createElement('li');
				li.appendChild(unorderList2);
				unorderList.appendChild(unorderList2);
			}
		}
		cityItem.appendChild(unorderList);
	}
	this.hideLoadDiv();
	this.prefChangeFlag = false;
};

/**
 * 選択されている市からその市区町村を得る
 */
WMP.Widget.GMap.prototype.getTowns = function()
{
	this.showLoadDiv();
	if (!this.cityChangeFlag) {
		this.hideLoadDiv();
		return;
	}
	var self = this;
	var city = document.getElementById('cityItem');
	city = city.getElementsByTagName('input');
	var clen = city.length;
	var cVal = [];
	var requestUrl = this.requestUrl;
	requestUrl    += ( this.ajaxCustomParam ) ? '&' + this.ajaxCustomParam : '';
	requestUrl    += '&cmd=';
	requestUrl    += 'town';
	requestUrl    += '&ac='; //anti-cache
	requestUrl    += (new Date).getTime();
	var changedFlag = false;
	for(var i = 0; i < clen; i++){
		if(city[i].checked && city[i].name == 'c'){
			requestUrl += '&c[]=';
			requestUrl += city[i].value;
			changedFlag = true;
		}
	}
	if (changedFlag == false) {
		alert('市を選んでください');
		this.hideLoadDiv();
		return false;
	}
	GDownloadUrl(requestUrl,function(responseText,status){
		if(status == 200){
			try{
				self.towns = eval(responseText);

			}catch(e){
				self.errorAlert('市evalエラー:'+ e.message);
				self.cities = null;
				return;
			}
			self.setTowns();
		}
	});
};

/**
 * 市区町村をチェックボックスで表示する
 */
WMP.Widget.GMap.prototype.setTowns = function()
{
	if(this.towns){
		var townItem = document.getElementById('townItem');
		var self = this;
		var count = this.towns.length;
		if(count < 1) return;
		var countCity;
		var countTown;
		var towns = this.towns;
		var prefList;
		var cityList;
		var townList;
		var li;
		var text;
		var label;
		var checkbox;
		while(townItem.hasChildNodes()){
			townItem.removeChild(townItem.firstChild);
		}
		prefList = document.createElement('ul');
		for(var i = 0; i < count; i++){
			cityList = document.createElement('ul');
			countCity = towns[i][1].length;
			for(var j = 0; j < countCity; j++){
				countTown = towns[i][1][j].cho.length;
				townList = document.createElement('ul');
				li = document.createElement('li');
				text = document.createTextNode(towns[i][1][j].name);
				li.appendChild(text);
				li.appendChild(townList);
				cityList.appendChild(li);
			}
			li = document.createElement('li');
			text = document.createTextNode(towns[i][0]);
			li.appendChild(text);
			li.appendChild(cityList);
			prefList.appendChild(li);
		}
		townItem.appendChild(prefList);

	}
	this.hideLoadDiv();
	this.cityChangeFlag = false;
};

/**
 * メニュと地図をリサイズする
 * @param {Numeric} mode 0:デフォルト 1:物件リスト＆地図モード
 */
WMP.Widget.GMap.prototype.resizeMapAndMenu = function (mode)
{
	if(mode == 1){
		this.setClassName(this.menu,'menuResize');
	}else if(mode == 0){
		this.setClassName(this.menu,'menuDefaultSize');
		this.setClassName(this.mapField,'mapDefaultSize');
	}
	this.adaptMapSize();
	gmaps.checkResize();
}

/**
 * フォームの要素の値を抽出し、その条件にマッチするデータを取得する
 */
WMP.Widget.GMap.prototype.getAllFormValues = function()
{
	this.pageNumber = 0;
	var self = this;
	var all = this.form.elements;
	var text = '';
	var requestUrl = this.requestUrl;
	var bkInfo;
	requestUrl += ( this.ajaxCustomParam ) ? '&' + this.ajaxCustomParam : '';
	requestUrl += '&anticache=';
	requestUrl += (new Date).getTime();
	requestUrl += '&cmd=search';
	var len = all.length;
	for(var i = 0; i < len; i++){
		if(all[i].nodeName == 'INPUT'){
			if((all[i].type == 'radio' && all[i].checked)
			|| (all[i].type == 'checkbox' && all[i].checked))
			{
				text += '&';
				text += all[i].name;
				if(all[i].type == 'checkbox') text += '[]';
				text += '=';
				text += all[i].value;
			}

		}else if(all[i].nodeName == 'SELECT'){
			text += '&';
			text += all[i].name;
			text += '=';
			text += all[i].value;
		}
	}
	requestUrl += text;
	requestUrl +='&pg=0';
	this.requestUrlCache = requestUrl;

	this.getData(requestUrl);
};

/**
 * Bパターン検索
 */

WMP.Widget.GMap.prototype.bSearch = function()
{
	this.pageNumber = 0;
	var requestUrl = this.requestUrl;
	requestUrl += ( this.ajaxCustomParam ) ? '&' + this.ajaxCustomParam : '';
	requestUrl += this.getQuery;
	requestUrl += '&anticache=';
	requestUrl += (new Date).getTime();
	requestUrl += '&cmd=search';
	if ( /cn\[\]=/.test(requestUrl) == false ) {
		alert ('種別を選択してください');
		return false;
	}
	requestUrl +='&pg=0';

	this.requestUrlCache = requestUrl;

	this.showLoadDiv();
	this.getData(requestUrl);
};


/**
 * 処理中に表示するDivを作成する
 */
WMP.Widget.GMap.prototype.createLoadDiv = function ()
{
	var loadDiv = document.createElement('div');
	loadDiv.id = this.loadDivId;
	loadDiv.style.display = 'none';
	if(window.outerWidth) loadDiv.width = window.outerWidth;
	if(window.outerHeight) loadDiv.height = window.outerHeight;

	var img = new Image();
	img.src = '/wmp/google_maps/loading.gif';
	img.width = '48';
	img.height = '48';

	var p = document.createElement('p');
	p.innerHTML = 'しばらくお待ち下さい';

	loadDiv.appendChild(img);
	loadDiv.appendChild(p);
	document.body.appendChild(loadDiv);
};

WMP.Widget.GMap.prototype.showLoadDiv = function()
{
	var loadDiv = document.getElementById(this.loadDivId);
	loadDiv.style.display = 'block';
}

WMP.Widget.GMap.prototype.hideLoadDiv = function()
{
	var loadDiv = document.getElementById(this.loadDivId);
	loadDiv.style.display = 'none';
}



/**
 * データを取得する
 * @param {String} r request url
 */
WMP.Widget.GMap.prototype.getData = function (r) {
	var self = this;
	if( r.length < 1024 ) {
		GDownloadUrl(r,function(responseText,status){
			if(status == 200){
				var bkInfo = eval('('+responseText+')');
				self.addMarkerAndListByJSON(bkInfo);;
			}
		});
	} else {
		var rr = r.split('?');
		GDownloadUrl(rr[0],function(responseText,status){
			if(status == 200){
				var bkInfo = eval('('+responseText+')');
				self.addMarkerAndListByJSON(bkInfo);
			}
		},rr[1]);

	}
}





































// ストリートビューウィンドウの表示
function openPanoramaBubble() {
  var contentNode = document.createElement('div');
  contentNode.style.textAlign = 'center';
  contentNode.style.width = '96%';
  contentNode.style.height = '76%';
  contentNode.innerHTML = 'Loading panorama';

  var smallNode = document.createElement('div');
  smallNode.style.width = '400px';
  smallNode.style.height = '200px';
  smallNode.id = 'pano';
  stvmarker.openInfoWindow(smallNode, {maxContent: contentNode});

  panorama = new GStreetviewPanorama(smallNode);
  panorama.setLocationAndPOV(stvmarker.getLatLng(), null);
  GEvent.addListener(panorama, "initialized", self.onNewLocation);
  GEvent.addListener(panorama, "yawchanged", self.onYawChange);

  var iw = gmaps.getInfoWindow();
  GEvent.addListener(iw, "maximizeend", function() {
    panorama.setContainer(contentNode);
    window.setTimeout("panorama.checkResize()", 10);
  });
}

function toggleOverlay() {
  if (!overlayInstance) {
    overlayInstance = new GStreetviewOverlay();
    gmaps.addOverlay(overlayInstance);
  } else {
    gmaps.removeOverlay(overlayInstance);
    overlayInstance = null;
  }
}

 // ストリートビューの向き変更に合わせてマーカーアイコンの向きを変更
function onYawChange(newYaw) {
  var GUY_NUM_ICONS = 16;
  var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
  if (newYaw < 0) {
    newYaw += 360;
  }
  guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
  guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
  stvmarker.setImage(guyImageUrl);
}

  // ストリートビューの移動時にマーカーも位置を合わせる
function onNewLocation(location) {
    stvmarker.setLatLng(location.latlng);
    laststvmarkerLocation = location.latlng;
}

function onDragEnd() {
  var latlng = stvmarker.getLatLng();
  if (panorama) {
    client.getNearestPanorama(latlng, self.onResponse);
  }
}

function onResponse(response) {
  if (response.code != 200) {
    stvmarker.setLatLng(lastMarkerLocation);
  } else {
    var latlng = new GLatLng(response.Location.lat, response.Location.lng);
    stvmarker.setLatLng(latlng);
    lastMarkerLocation = latlng;
    openPanoramaBubble();
  }
}





// 最初に関数を定義します
function TextualSVControl() {
}

// GControl を "subclass" にするには、prototype オブジェクトを
// GControl オブジェクトのインスタンスに設定します
TextualSVControl.prototype = new GControl();

// 各ボタンに対して1つの DIV を作成し、
// コントロール要素として返されるコンテナ DIV に格納します。そのコントロールを
// マップコンテナに追加し、マップクラスの要素を返して
// 適切な位置を指定します。
TextualSVControl.prototype.initialize = function(gmaps) {
  var container = document.createElement("div");

  var SVDiv = document.createElement("div");
  this.setButtonStyle_(SVDiv);
  container.appendChild(SVDiv);
  SVDiv.appendChild(document.createTextNode("ストリートビュー"));
  GEvent.addDomListener(SVDiv, "click", function() {
	self.toggleOverlay();
  });
  gmaps.getContainer().appendChild(container);
  return container;
}

TextualSVControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(8, 30));
}

// 指定されたボタン要素に対して適切な CSS を設定します。
TextualSVControl.prototype.setButtonStyle_ = function(button) {
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.fontSize = "11px";
  button.style.borderTop = "1px solid black";
  button.style.borderRight = "2px groove black";
  button.style.borderLeft = "1px solid black";
  button.style.borderBottom = "2px groove black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "80px";
  button.style.cursor = "pointer";
}
