// 2009 (c) SystemK Corp. / layar.jp All Rights Reserved.
function we_go()
{
	var self = this;
	new $.ajax(
	{
		async : false,
		url : 'getcategories.php',
		type : 'POST',
		data : {
			'dummy' : 'dummy'
		},
		dataType : 'json',
		success : function(data, dataType)
		{
			self.categories = data;
		},
		error : function(XMLHttpRequest, textStatus, errorThrown)
		{
			alert('error');
		},
		complete : function(XMLHttpRequest, textStatus)
		{
		}
	});

//	$('input#layar').click(function(e) {
//		e.preventDefault();
//		location.href = 'http://layar.jp/';
//		return false;
//	});

//	$('input#how_to_use').click(function(e) {
//		e.preventDefault();
//		location.href = '../how_to_use.html';
//		return false;
//	});

	this.init.apply(this, arguments);

	var search_button_click = function (e) {
		e.preventDefault();

		if ( $('#search-input').val() == '' )
		{
			$('#search-input').focus();
			return false;
		}

		var geocoder = new google.maps.Geocoder();

		var v = $('#search-input').val();
		var address = v.split(',');

	    geocoder.geocode(
			{
				'address' : $('#search-input').val(),
				'country' : ( address.length > 1 ) ? address[1].toLowerCase() : 'jp'
			},
		    function(results, status)
		    {
		    	if ( status == google.maps.GeocoderStatus.OK )
		    	{
					x.mapObject.setCenter(new google.maps.LatLng(
			    		results[0].geometry.location.lat(),
			    		results[0].geometry.location.lng())
			    	);
					x.mapObject.setZoom(17);
					if ( x.user != null )
					{
						x.setNewMarker(new google.maps.LatLng(
				    		results[0].geometry.location.lat(),
				    		results[0].geometry.location.lng())
				    	);
					}
					new $.ajax(
					{
						async : true,
						url : self.setdoko_program,
						type : 'POST',
						data : {
							'word' : $('#search-input').val()
						},
						dataType : 'text',
						success : function(data, dataType)
						{
						},
						error : function(XMLHttpRequest, textStatus, errorThrown)
						{
						},
						complete : function(XMLHttpRequest, textStatus)
						{
						}
					});
				}
				else
				{
					alert('見つかりませんでした。名称を変えて再検索してください');
					$('#search-input').focus();
				}
				return false;
			}
		);
		return false;
	};
	$('#search-button').click(search_button_click);

    $("#searchForm").submit(function(e){
        search_button_click(e);
        return false;
    });
}

we_go.prototype =
{
	data : [],
	markerz : [],

	user : null,
	categories : null,
	zoomLevel : null,
	mapObject : null,
	nowTarget : null,
	editTarget : null,
	infoWindow : null,
	nowAddress : null,

	userAgent : navigator.userAgent,
	expired_select_list : [
		{
			key : '3',
			title : 'ずっと'
		},
		{
			key : '1',
			title : '1日'
		},
		{
			key : '2',
			title : '2日'
		}
	],

	JAPAN_string : '日本, ',
	Image_File : null,
	default_lat : null,
	default_lon : null,
	lat : null,
	lon : null,
	notfit : false,
	jgrowl_dontview : false,

	Image_File_short : null,
	Image_File_middle : null,
	Image_File_long : null,
	Image_File_3d : null,

	rel_select_list : [
		{
			key : '1',
			title : 'ユーザの向きに合わせて表示する'
		},
		{
			key : '0',
			title : '南を前面にして表示する'
		}
	],

	rel : null,
	angle : null,

	getMapObject : function(){ return this.mapObject } ,

	init : function()
	{
		if ( arguments[0] != '' && typeof(arguments[0]) != undefined &&
			 arguments[1] != '' && typeof(arguments[1]) != undefined )
		{
			this.user = { ID: arguments[0], NICKNAME: arguments[1] };
		}
		if ( arguments[2].lat != '' && arguments[2].lon != '' )
		{
			this.default_lat = arguments[2].lat;
			this.default_lon = arguments[2].lon;
		}

		var self = this;
		var location = {lat: 37.799212, lng: 139.683442}; // default location

//		var resize = function()
//		{
//			var h;
//			if ( self.isIE() )
//			{
//				if (document.all && document.getElementById && (document.compatMode=='CSS1Compat'))
//				{
//				    h = document.documentElement.clientHeight;
//				}
//				// その他のIE。
//				else {
//				    h = document.body.clientHeight;
//				}
//			}
//			else
//			{
//				h = window.innerHeight;
//			}
//			$('#map_canvas').css('height', h +'px');
//		};
//		resize();
//		$(window).resize(resize);

		if ( this.default_lat != null && this.default_lon != null )
		{
			// パラメータとして位置情報を与えられていた場合
			location.lat = this.default_lat;
			location.lng = this.default_lon;
			// マップを作る
			this.zoomLevel = 17;
			this.createMap();
			this.mapObject.setCenter(new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng)));
			this.loadBoundsData();
		}
		else
		{
			// GPS対応端末の場合
			if(geo_position_js.init())
			{
				var show_position = function(p)
				{
					// マップを作る
					self.zoomLevel = 17;
					self.createMap();
					self.mapObject.setCenter(new google.maps.LatLng(p.coords.latitude, p.coords.longitude));
					self.loadBoundsData();
				};

				geo_position_js.getCurrentPosition(
					show_position,
					function(){
						// マップを作る
						self.zoomLevel = 5;
						self.createMap();
						self.mapObject.setCenter(new google.maps.LatLng(location.lat, location.lng));
						self.loadBoundsData();
					},
					{enableHighAccuracy:true}
				);
				return;
			}
			else
			{
				// マップを作る
				this.zoomLevel = 5;
				this.createMap();
				this.mapObject.setCenter(new google.maps.LatLng(location.lat, location.lng));
				this.loadBoundsData();
			}
		}
	} ,

	createMap : function()
	{
		var self = this;

	    var opt = {
	            zoom             : this.zoomLevel,
	            scaleControl     : false,
	            mapTypeId        : google.maps.MapTypeId.HYBRID ,
	            mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
	            navigationControlOptions: {style: (this.isMobile()) ? google.maps.NavigationControlStyle.ANDROID : google.maps.NavigationControlStyle.DEFAULT}
	    };
	    var map = new google.maps.Map(document.getElementById("map_canvas"), opt);
	    this.mapObject = map;

		// Zoom 調節のイベント
		google.maps.event.addListener(
			map, 'zoom_changed',
			function()
			{
				self.loadBoundsData();
				if ( self.infoWindow )
				{
					var t = (self.editTarget != null) ? self.editTarget : self.nowTarget;
					self.mapObject.setCenter(t.getPosition());
				}
			}
		);

		// マップドラッグのイベント
		google.maps.event.addListener(
			map, 'dragend',
			function()
			{
				self.loadBoundsData();
				if ( self.nowTarget && self.infoWindow == null )
				{
					self.nowTarget.setPosition(null);
					self.nowTarget.setPosition(self.mapObject.getCenter());
				}
			}
		);

		this._setMapClickEvents();
	} ,

	init_markers : function()
	{
		for ( var i = this.markerz.length; i > -1; i-- )
		{
			if ( this.markerz[i] != null )
			{
				google.maps.event.clearInstanceListeners(this.markerz[i]);
				this.markerz[i].setMap(null);
				this.markerz[i] = null;
				delete this.markerz[i];
			}
		}
		this.markerz = [];
	} ,

	init_data : function()
	{
		for ( var i = this.data.length; i > -1; i-- )
		{
			this.data[i] = null;
			delete this.data[i];
		}
		this.data = [];
	} ,

	loadAllData : function(bounds)
	{
		var self = this;

		new $.ajax({
			async : true,
			url : 'getallmarkerz.php',
			type : 'POST',
			data : {
				dummy : 'dummy'
			},
			dataType : 'json',
			success : function(data, dataType)
			{
				self.init_markers();
				self.init_data();
				self.data = data;

				return self.setToMap(bounds)
			},
			error : function(XMLHttpRequest, textStatus, errorThrown)
			{
				alert('error');
			},
			complete : function(XMLHttpRequest, textStatus)
			{
			}
		});
	} ,

	loadBoundsData : function()
	{
		var self = this;

		var id = setInterval(
			function()
			{
				if ( self.mapObject.getBounds() != undefined )
				{
					clearInterval(id);
					var bounds = self.mapObject.getBounds();
					var center = self.mapObject.getCenter();
					var northEast = bounds.getNorthEast();
					var southWest =  bounds.getSouthWest();

					new $.ajax(
					{
						async : true,
						url : 'getboundsmarkerz.php',
						type : 'POST',
						data : {
							'center' : center.lat() + ',' + center.lng(),
							'northeast' : northEast.lat() + ',' + northEast.lng(), // north, east
							'southwest' : southWest.lat() + ',' + southWest.lng()  // south, west
						},
						dataType : 'json',
						success : function(data, dataType)
						{
							self.init_markers();
							self.init_data();
							self.data = data.data;
							if ( data.misc.cnt > 50 )
							{
								if ( self.jgrowl_dontview == false )
								{
									$.jGrowl('表示件数 ' + data.misc.cnt + ' 件を 50 件までに制限しました<br><span style="vertical-align: middle"><input type="checkbox" value="1" id="dontview" name="dontview" style="vertical-align: middle" checked="checked"> このメッセージを表示しない</span>',
									{
										beforeClose : function(e,m,o) {
											self.jgrowl_dontview = ($("input[name='dontview']:checked").val()) ?
												true : false;
										} ,
										close : function(e,m,o) {



										}
									});
								}
							}
							return self.setToMap(false)
						},
						error : function(XMLHttpRequest, textStatus, errorThrown)
						{
							alert('error');
						},
						complete : function(XMLHttpRequest, textStatus)
						{
						}
					});
				}
			}, 100
		);

	} ,

	setToMap : function(bounds)
	{
		var bounds = new google.maps.LatLngBounds();
		var mapObject = this.getMapObject();
		var data = this.data;

		if ( data.length > 0 )
		{
			for ( var i = 0, len = data.length; i < len; i++ )
			{
				var m =
					new google.maps.Marker({
			            position: new google.maps.LatLng(data[i].Lat / 1000000, data[i].Lon / 1000000),
			            map     : mapObject,
			            draggable : false,
			            title : data[i].Title
			        });
				this.attachPOIEvent(mapObject, m, data[i].Title, data[i].Line3, data[i].Address2, data[i].Line2, data[i].Radio_List_Name, data[i].Lat, data[i].Lon, data[i].NICKNAME, data[i].Add_Date, data[i].Add_Time, data[i].Image_URL, data[i].ID, data[i].User_ID, data[i].img_width, data[i].img_height, data[i].Actions1, data[i].File_Name_3D, data[i].Rel, data[i].Angle, data[i].Alt, data[i].Relative_Alt, data[i].Scale, data[i].Size, data[i].Line4, data[i].Attribution);
				bounds.extend(m.getPosition())
				this.markerz[this.markerz.length] = m;
			}
			if ( bounds == true && this.notfit == false )
			{
				mapObject.fitBounds(bounds);
			}
		}
	} ,

	registered_baloon_node : function(obj)
	{
		var d = document.createElement('div');
		d.id = 'baloon-contents';

		var html = [];

		html[html.length] = '<form id="baloon" name="baloon">';
		html[html.length] = '<ul>';

		// 画像
		if ( obj.image != '' && obj.image != null && typeof(obj.image) != undefined )
		{
			html[html.length] = '<li><img height="75" src="' + obj.image + '"></li>';
		}
		else
		{
			if ( obj.file_3d != null )
			{
				html[html.length] = '<li><img src="./img/3d.png" width="' + obj.img_width + '" height="' + obj.img_height + '"></li>';
			}
		}

		// タイトル
		html[html.length] = '<li><strong style="105%;">' + this.esc(obj.title) + '</strong></li>';

		// コメント
		html[html.length] = '<li class="comment">';
		html[html.length] = '<p class="comment">' + this.esc(obj.comment) + '</p>';
		html[html.length] = '</li>';

		// 住所
		if ( obj.address != '' && obj.address != null && typeof(obj.address) != undefined )
		{
			html[html.length] = '<li id="address">' + this.esc(obj.address) + '</li>';
		}
		// line4
		if ( obj.line4 != '' && obj.line4 != null && typeof(obj.line4) != undefined )
		{
			html[html.length] = '<li id="line4">' + this.esc(obj.line4) + '</li>';
		}
		// attributte
		if ( obj.attribution != '' && obj.attribution != null && typeof(obj.attribution) != undefined )
		{
			html[html.length] = '<li id="attribution">' + this.esc(obj.attribution) + '</li>';
		}


		// リンク先URL
		if ( obj.url != null )
		{
			html[html.length] = '<li><a href="' + obj.url + '" target="_blank">' + obj.url + '</a></li>';
		}

		html[html.length] = '</ul>';


		html[html.length] = '<ul>';

		// 登録日時
		var date = obj.date.substr(0, 4) * 1 + '/' + obj.date.substr(4, 2) * 1 + '/' + obj.date.substr(6, 2);
		for ( var i = 6 - (new String(obj.time)).length; i > 0; i-- )
		{
			obj.time = '0' + obj.time;
		}
		var time = obj.time.substr(0, 2) + ':' + obj.time.substr(2, 2) + ':' + obj.time.substr(4, 2);
		html[html.length] = '<li style="text-align: right">' + date + ' ' + time;

		// ユーザー
		var user = (obj.user == null) ? 'admin' : this.esc(obj.user);
		html[html.length] = ' by ' + user + '</li>';

		if ( this.user == null )
		{
			//html[html.length] = '<li>キャラクターを登録したい場合はログインしてください</li>';
		}
		else if ( obj.user != null && this.user.NICKNAME == obj.user )
		{
			html[html.length] = '<li id="submit">';

			html[html.length] = '<input type="button" value="編集" name="edit" id="edit" onclick="return x.markerEdit(' + obj.id + ',' + obj.user_id + ')"';
			if ( this.isMobile() )
			{
				html[html.length] = ' style="font-size: 14px"';
			}
			html[html.length] = '> ';

			html[html.length] = '<input type="button" value="削除" name="delete" id="delete" onclick="return x.markerDelete(' + obj.id + ',' + obj.user_id + ')"';
			if ( this.isMobile() )
			{
				html[html.length] = ' style="font-size: 14px"';
			}

			html[html.length] = '></li>';
		}

		html[html.length] = '</ul>';
		html[html.length] = '</form>';
		html[html.length] = '<br>';

		d.innerHTML = html.join('');

		return d;
	} ,

	attachPOIEvent : function(mapObject, m, title, address, address2, comment, category, lat, lon, user, add_date, add_time, image_url, id, user_id, img_width, img_height, url, file_3d, rel, angle, alt, relative_alt, scale, size, line4, attribution)
	{
		var self = this;

		// マーカーのクリックイベントの定義
		google.maps.event.addListener(
			m, 'click',
			function()
			{
	        	self.closeInfoWindow();

				// バルーン表示
		        var infoWindow = new google.maps.InfoWindow({
					content : self.registered_baloon_node({
						title : title,
						address : address, // line3
						address2 : address2,
						comment: comment, //line2
						category : category,
						lat : lat,
						lon : lon,
						user : user,
						location :  new google.maps.LatLng(lat / 1000000, lon / 1000000),
						date : add_date,
						time : add_time,
						image : image_url,
						img_width : 75,
						img_height : 75,
						id : id,
						user_id : user_id,
						url : url,
						file_3d : file_3d,
						rel : rel,
						angle : angle,
						alt : alt,
						relative_alt : relative_alt,
						scale : scale,
						size : size,
						line4: line4,
						attribution: attribution
					})
		        });

		        infoWindow.open(mapObject, m);
				self.infoWindow = infoWindow;

				// バルーンの閉じるイベント
				google.maps.event.addListener(
					infoWindow, 'closeclick',
					function()
					{
						self.infoWindow = null;
						self.initEditTarget();
					}
				);
				self.editTarget = m;
			}
		);

	} ,

	allMarkerReget : function()
	{
		this.loadBoundsData(false);
	},

	markerEdit : function(id, user_id)
	{
		this.clearNowTarget();
		this.nowTarget = this.editTarget;

		var self = this;
		var data = {
			id : id,
			user : user_id
		};
		new $.ajax(
		{
			url : 'getpoint.php',
			type : 'POST',
			data : data,
			dataType : 'json',
			success : function(data, dataType)
			{
				if ( data.error == 0 )
				{
					self.closeInfoWindow();
					self.nowTarget.setDraggable(true);
					self.Image_File = data.data[0].File_Name;
					self.Image_File_short = data.data[0].File_Name_short;
					self.Image_File_middle = data.data[0].File_Name_middle;
					self.Image_File_long = data.data[0].File_Name_long;
					self.Image_File_3d = data.data[0].File_Name_3d;
					self.address = data.data[0].Line3;

					// バルーン表示
			        var infoWindow = new google.maps.InfoWindow();
			        infoWindow.open(self.mapObject, self.nowTarget);

					// バルーンの閉じるイベント
					google.maps.event.addListener(
						infoWindow, 'closeclick',
						function()
						{
							self.editCancel();
						}
					);

					google.maps.event.addListener(
						infoWindow, 'content_changed',
						function()
						{
						}
					);

					infoWindow.setContent(
						self.edit_baloon_node({
							title : data.data[0].Title,
							address : data.data[0].Line3,
							comment : data.data[0].Line2,
							category : data.data[0].Radio_List_ID,
							expired : data.data[0].Expired_Date,
							filename : data.data[0].File_Name,
							id : id,
							user_id : user_id,
							url : data.data[0].Actions1,
							rel : data.data[0].Rel,
							angle : data.data[0].Angle,
							alt : data.data[0].Alt,
							relative_alt : data.data[0].Relative_Alt,
							scale : data.data[0].Scale,
							size : data.data[0].Size
						}));

					self.infoWindow = infoWindow;

					var timeID = setInterval(function()
					{
						if ( document.getElementById('submit-button') )
						{
							clearInterval(timeID);
							// イベントの定義
							$('#name').focus();
						}
					}, 100);

					// マーカーのドラッグイベントの定義
				    google.maps.event.addListener(
				    	self.nowTarget, 'dragend',
				    	function()
				    	{
				            self._getTargetPosition(self.nowTarget);

				            if ( self.infoWindow )
				            {
								var geocoder = new google.maps.Geocoder();
							    geocoder.geocode(
						    	{'latLng': self.location},
							    function(results, status)
							    {
									var address = self._getGeocodingResults(results, status);
									self.address = address;

									$('#address').html('<span>住所</span><br>' + address);
								});
							}
							return false;
			            }
				    );
				}
			},
			error : function(XMLHttpRequest, textStatus, errorThrown)
			{
				alert('error');
			},
			complete : function(XMLHttpRequest, textStatus)
			{
			}
		});
	} ,

	markerDelete : function(id, user_id)
	{
		var self = this;
		if ( confirm('削除しますか？') )
		{
			var data = {
				id : id,
				user : user_id
			};
			new $.ajax(
			{
				url : 'markerdelete.php',
				type : 'POST',
				data : data,
				dataType : 'json',
				success : function(data, dataType)
				{
					if ( data.error == 0 )
					{
			        	self.closeInfoWindow();
						self.editTarget.setMap(null);
						self.initEditTarget();
						self.Image_File = null;
						self.Image_File_short = null;
						self.Image_File_middle = null;
						self.Image_File_long = null;
						self.Image_File_3d = null;
						alert('削除しました');
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown)
				{
					alert('error');
				},
				complete : function(XMLHttpRequest, textStatus)
				{
				}
			});
		}

		return false;
	} ,

	targetClear : function()
	{
		google.maps.event.removeListener(
			this.mapClickEvent
	    );
		if ( this.isMobile() )
		{
			if ( confirm('キャンセルしますか？') )
			{
	        	this.closeInfoWindow();
				this.clearNowTarget();
				this.initEditTarget();
				this.Image_File = null;
				this.Image_File_short = null;
				this.Image_File_middle = null;
				this.Image_File_long = null;
				this.Image_File_3d = null;
			}
		}
		else
		{
        	this.closeInfoWindow();
			this.clearNowTarget();
			this.initEditTarget();
			this.Image_File = null;
			this.Image_File_short = null;
			this.Image_File_middle = null;
			this.Image_File_long = null;
			this.Image_File_3d = null;
		}

		this._setMapClickEvents();
		return false;
	} ,

	targetRegister : function()
	{
		var l = this.nowTarget.getPosition();

		if ( this.isMobile() )
		{
			location.href = './index_m.php?lat=' + l.lat() + '&lng=' + l.lng();
		}
		else
		{
			if ( $('#name').val() == '' )
			{
				alert('タイトルを入力してください');
				return false;
			}
			if ( $('#comment').val() == '' )
			{
				alert('コメントを入力してください');
				return false;
			}
			if ( $('#url').val() != '' )
			{
				if ( $('#url').val().match('^http:\/\/') == null &&
					 $('#url').val().match('^https:\/\/') == null )
				{
					alert('リンク先URLが不正です。http:// か https:// から入力してください');
					return;
				}
			}
			if ( this.address == '' )
			{
				alert('地図上に住所がない場所では登録できません。');
				return false;
			}
			if (( this.Image_File == null ) && (this.Image_File_3d == null) )
			{
				alert('画像をアップロードしてください');3
				return false;
			}

			var data = {
					title : $('#name').val(),
					line2 : $('#comment').val(),
					line3 : this.address,
					attribution : null,
					lat : l.lat(),
					lon : l.lng(),
					actions1 : $('#url').val()
			};
			if ( this.Image_File != null )
			{
				data['file'] = this.Image_File;
			}
			data['rel'] = $('#rel').val();
			data['radio'] =  $('#category').val();
			data['expired'] = $('#expired').val();

			if ( this.Image_File_short != null)
			{
				data['Image_File_short'] = this.Image_File_short;
			}
			if ( this.Image_File_middle != null)
			{
				data['Image_File_middle'] = this.Image_File_middle;
			}
			if ( this.Image_File_long != null)
			{
				data['Image_File_long'] = this.Image_File_long;
			}
			if ( this.Image_File_3d != null)
			{
				data['Image_File_3d'] = this.Image_File_3d;
			}
			data['angle'] = $('#angle').val();;
			data['alt'] = $('#alt').val();;
			data['relative_alt'] = $('#relative_alt').val();;
			data['scale'] = $('#scale').val();;
			data['size'] = $('#size').val();;

			var self = this;
			new $.ajax(
			{
				url : 'register.php',
				type : 'POST',
				data : data,
				dataType : 'json',
				success : function(data, dataType)
				{
					if ( data.error == 0 )
					{
						alert('登録しました');
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown)
				{
					alert('error');
				},
				complete : function(XMLHttpRequest, textStatus)
				{
					self.initEditTarget();
					self._getTargetPosition(self.nowTarget);
					self.clearNowTarget();
		        	self.closeInfoWindow();
					self.notfit = true;
					self.loadBoundsData();
					self.mapObject.setCenter(self.location);
				}
			});
		}

		return false;
	} ,

	targetUpdate : function(id, user_id)
	{
		var l = this.nowTarget.getPosition();

		if ( this.isMobile() )
		{
			location.href = './index_m.php?lat=' + l.lat() + '&lng=' + l.lng() + '&id=' + id;
		}
		else
		{
			if ( $('#name').val() == '' )
			{
				alert('タイトルを入力してください');
				return false;
			}
			if ( $('#comment').val() == '' )
			{
				alert('コメントを入力してください');
				return false;
			}
			if ( $('#url').val() != '' )
			{
				if ( $('#url').val().match('^http:\/\/') == null &&
					 $('#url').val().match('^https:\/\/') == null )
				{
					alert('リンク先URLが不正です。http:// か https:// から入力してください');
					return;
				}
			}
			if (( this.Image_File == null ) && (this.Image_File_3d == null) )
			{
				alert('画像をアップロードしてください');
				return false;
			}

			var l = this.nowTarget.getPosition();
			var data = {
					id : id,
					user : user_id,
					title : $('#name').val(),
					line2 : $('#comment').val(),
					line3 : this.address,
					attribution : null,
					lat : l.lat(),
					lon : l.lng(),
					actions1 : $('#url').val()
			};
			if ( this.Image_File != null )
			{
				data['file'] = this.Image_File;
			}
			data['rel'] = $('#rel').val();
			data['radio'] = $('#category').val();
			data['expired'] = $('#expired').val();

			if ( this.Image_File_short != null)
			{
				data['Image_File_short'] = this.Image_File_short;
			}
			if ( this.Image_File_middle != null)
			{
				data['Image_File_middle'] = this.Image_File_middle;
			}
			if ( this.Image_File_long != null)
			{
				data['Image_File_long'] = this.Image_File_long;
			}
			if ( this.Image_File_3d != null)
			{
				data['Image_File_3d'] = this.Image_File_3d;
			}
			data['angle'] = $('#angle').val();;
			data['alt'] = $('#alt').val();;
			data['relative_alt'] = $('#relative_alt').val();;
			data['scale'] = $('#scale').val();;
			data['size'] = $('#size').val();;

			var self = this;
			new $.ajax(
			{
				url : 'update.php',
				type : 'POST',
				data : data,
				dataType : 'json',
				success : function(data, dataType)
				{
					if ( data.error == 0 )
					{
						alert('更新しました');
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown)
				{
					alert('error');
				},
				complete : function(XMLHttpRequest, textStatus)
				{
					self.initEditTarget();
					self._getTargetPosition(self.nowTarget);
					self.clearNowTarget();
		        	self.closeInfoWindow();
					self.notfit = true;
					self.loadBoundsData();
					self.mapObject.setCenter(self.location);
				}
			});
		}

		return false;
	} ,

	setNewMarker : function(_location)
	{
	    if ( this.nowTarget )
	    {
			this.clearNowTarget();
	    }
        if ( this.infoWindow )
        {
        	this.closeInfoWindow();
        }

        this.nowTarget = new google.maps.Marker({
            position: _location,
            map     : this.mapObject,
            draggable : true
        });
		this.editTarget = null;

		this.setNewMarkerEvents(_location);
	} ,

	setNewMarkerEvents : function(_location)
	{
		var self = this;

		var geocoder = new google.maps.Geocoder();
	    geocoder.geocode(
	    	{'latLng': _location},
		    function(results, status)
		    {
				var address = self._getGeocodingResults(results, status);
				self.address = address;
				// バルーン表示
		        var infoWindow = new google.maps.InfoWindow();

		        infoWindow.open(self.mapObject, self.nowTarget);

				// バルーンの閉じるイベント
				google.maps.event.addListener(
					infoWindow, 'closeclick',
					function()
					{
						self.closeInfoWindow();
					}
				);

				google.maps.event.addListener(
					infoWindow, 'content_changed',
					function()
					{
					}
				);

				infoWindow.setContent(
					self.baloon_node({
						address : address,
						location : _location
					}));

				self.infoWindow = infoWindow;
				self.Image_File = null;
				self.Image_File_short = null;
				self.Image_File_middle = null;
				self.Image_File_long = null;
				self.Image_File_3d = null;

				var timeID = setInterval(function()
				{
					if ( document.getElementById('submit-button') )
					{
						clearInterval(timeID);
						// イベントの定義
						$('#name').focus();
					}
				}, 100);
			}
		);

		// マーカーのドラッグイベントの定義
	    google.maps.event.addListener(
	    	this.nowTarget, 'dragend',
	    	function()
	    	{
	            self._getTargetPosition(self.nowTarget);

	            if ( self.infoWindow )
	            {
					var geocoder = new google.maps.Geocoder();
				    geocoder.geocode(
			    	{'latLng': self.location},
				    function(results, status)
				    {
						var address = self._getGeocodingResults(results, status);
						self.address = address;

						$('#address').html('<span>住所</span><br>' + address);
					});
				}
				return false;
            }
	    );

		// マーカーのクリックイベントの定義
		google.maps.event.addListener(
			this.nowTarget, 'click',
			function()
			{
	        	self.closeInfoWindow();

	            self._getTargetPosition(self.nowTarget);
				self.initEditTarget();

				var geocoder = new google.maps.Geocoder();
			    geocoder.geocode(
			    	{'latLng': self.location},
				    function(results, status)
				    {
						self.closeInfoWindow();

						var address = self._getGeocodingResults(results, status);

						// バルーン表示
				        var infoWindow = new google.maps.InfoWindow({
								content : self.baloon_node({
									address : address,
									location : _location
								})
				        });

				        infoWindow.open(self.mapObject, self.nowTarget);

						// バルーンの閉じるイベント
						google.maps.event.addListener(
							infoWindow, 'closeclick',
							function()
							{
								self.closeInfoWindow();
							}
						);
						self.infoWindow = infoWindow;
						self.Image_File = null;
						self.Image_File_short = null;
						self.Image_File_middle = null;
						self.Image_File_long = null;
						self.Image_File_3d = null;
					}
				);
			}
		);
	},

	baloon_node : function(obj)
	{
		var html = [];
		html[html.length] = '<form id="baloon" name="baloon" onsubmit="return false;">';

		html[html.length] = '<ul>';

		var d = document.createElement('div');
		d.id = 'baloon-contents';
		if ( this.isMobile() )
		{
			d.style.fontSize = 'small';
			html[html.length] = '<li class="attention">モバイル版登録ページに移動します</li>';
			html[html.length] = '<li id="submit">';
			html[html.length] = '<input type="button" id="cancel-button" name="cancel-button" value="キャンセル" onclick="return x.targetClear()" class="text"> ';
			html[html.length] = '<input type="button" id="submit-button" name="submit-button" value="移動" onclick="return x.targetRegister()" class="text">';
			html[html.length] = '</li>';
		}
		else
		{
			html[html.length] = '<li><label class="spn_title">タイトル<font color="red">*</font></label>';
			html[html.length] = '&nbsp;<input type="text" id="name" name="name" value="" size="100" maxlength="100" style="width:230px">';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#poi_title" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li id="address"><span class="spn_title">住所</span>';
			html[html.length] = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			html[html.length] = obj.address + '</li>';

			html[html.length] = '<li><span class="spn_title">コメント<font color="red">*</font></span>';
			html[html.length] = '&nbsp;&nbsp;<input type="text" id="comment" name="comment" value="" size="100" maxlength="100" style="width:230px">';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#poi_comment" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li><span class="spn_title">URL</span>';
			html[html.length] = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			html[html.length] = '<input type="text" id="url" name="url" value="" size="100" maxlength="100" style="width:230px">';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#poi_url" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li><iframe src="./file_upload_form.php" id="upload" name="upload" style="height: 16px; width: 230px;" frameborder="0" scrolling="no"></iframe>';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#2.3" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li><span class="spn_title">作品の向き</span>';
			html[html.length] = '&nbsp;';
			html[html.length] = '<select id="rel" name="rel">';
			var r = this.rel_select_list;
			for ( var i = 0, len = r.length; i < len; i++ )
			{
				html[html.length] = '<option value="' + r[i].key + '">';
				html[html.length] = r[i].title;
				html[html.length] = '</option>';
			}
			html[html.length] = '</select>';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#2.6" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li><span class="spn_title">回転(角度)</span>';
			html[html.length] = '&nbsp;';
			html[html.length] = '<input type="text" id="angle" name="angle" value="0" size="5" maxlength="3" style="width:70px">';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#2.6" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li><span class="spn_title">大きさ</span>';
			html[html.length] = '&nbsp;';
			html[html.length] = '<input type="text" id="scale" name="scale" value="1.0" maxlength="4" style="width:70px">';

			html[html.length] = '<li><span class="spn_title">高さ</span>';
			html[html.length] = '&nbsp;';
			html[html.length] = '<input type="text" id="relative_alt" name="relative_alt" value="0" maxlength="5" style="width:70px">(マイナス可能)';

			html[html.length] = '<li id="submit">';
			html[html.length] = '<input type="button" id="submit-button" name="submit-button" value="登録" onclick="return x.targetRegister()">';
			html[html.length] = '<input type="button" id="cancel-button" name="cancel-button" value="キャンセル" onclick="return x.targetClear()"> ';
			html[html.length] = '</li>';


		}

		html[html.length] = '</ul>';

		if ( !this.isMobile() )
		{
			// カテゴリと有効期限は非表示にして、初期選択の値で登録する
			var c = this.categories;
			html[html.length] = '<input type="hidden" name="category" value="0">';
			var e = this.expired_select_list;
			html[html.length] = '<input type="hidden" name="expired" value="3">';
			html[html.length] = '<input type="hidden" id="size"" name="size" value="5">';
			html[html.length] = '<input type="hidden" id="alt" name="alt" value="0">';
		}

		html[html.length] = '</form>';

		d.innerHTML = html.join('');

		return d;
	} ,

	edit_baloon_node : function(obj)
	{
		var d = document.createElement('div');
		d.id = 'baloon-contents';

		var html = [];
		html[html.length] = '<form id="baloon" name="baloon" onsubmit="return false;">';

		html[html.length] = '<ul>';

		if ( this.isMobile() )
		{
			d.style.fontSize = 'small';
			html[html.length] = '<li class="attention">モバイル版登録ページに移動します</li>';
			html[html.length] = '<li id="submit">';
			html[html.length] = '<input type="button" id="cancel-button" name="cancel-button" value="キャンセル" onclick="return x.editCancel()" class="text"> ';
			html[html.length] = '<input type="button" id="submit-button" name="submit-button" value="移動" onclick="return x.targetUpdate(' + obj.id + ',' + obj.user_id + ')" class="text">';
			html[html.length] = '</li>';
		}
		else
		{

			html[html.length] = '<li><label class="spn_title">タイトル<font color="red">*</font></label>';
			html[html.length] = '&nbsp;<input type="text" id="name" name="name" value="' + this.esc(obj.title) + '" size="100" maxlength="100" style="width:230px">';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#poi_title" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li id="address"><span class="spn_title">住所</span>';
			html[html.length] = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			html[html.length] = obj.address + '</li>';

			html[html.length] = '<li><span class="spn_title">コメント<font color="red">*</font></span>';
			html[html.length] = '&nbsp;&nbsp;<input type="text" id="comment" name="comment" value="' + this.esc(obj.comment) + '" size="100" maxlength="100" style="width:230px">';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#poi_comment" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			if ( obj.url == null )
			{
				obj.url = '';
			}
			html[html.length] = '<li><span class="spn_title">URL</span>';
			html[html.length] = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			html[html.length] = '<input type="text" id="url" name="url" value="' + obj.url + '" size="100" maxlength="100" style="width:230px">';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#poi_url" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li><iframe src="./file_upload_form.php" id="upload" name="upload" style="height: 16px; width: 230px;" frameborder="0" scrolling="no"></iframe>';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#2.3" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			// カテゴリと有効期限は非表示にして、初期選択の値で登録する
			var c = this.categories;
			html[html.length] = '<input type=hidden name="category" value="' + obj.category + '">';
			var e = this.expired_select_list;
			html[html.length] = '<input type=hidden name="expired" value="' + obj.expired + '">';

			html[html.length] = '<li><span class="spn_title">作品の向き</span>';
			html[html.length] = '&nbsp;';
			html[html.length] = '<select id="rel" name="rel">';
			var r = this.rel_select_list;
			for ( var i = 0, len = r.length; i < len; i++ )
			{
				html[html.length] = '<option value="' + r[i].key + '" ';
				if ( r[i].key == obj.rel )
				{
					html[html.length] = 'selected = "selected"';
				}
				html[html.length] = '>';
				html[html.length] = r[i].title;
				html[html.length] = '</option>';
			}
			html[html.length] = '</select>';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#2.6" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li><span class="spn_title">回転(角度)</span>';
			html[html.length] = '&nbsp;';
			html[html.length] = '<input type="text" id="angle" name="angle" value="' + obj.angle + '" size="5" maxlength="3" style="width:70px">';
			html[html.length] = '&nbsp;&nbsp;<a href="./how_to_use.html#2.6" target="layar_help"><img src="./img/info.png" alt="info" width="19" height="20" align="absmiddle"></a></li>';

			html[html.length] = '<li><span class="spn_title">大きさ</span>';
			html[html.length] = '&nbsp;';
			html[html.length] = '<input type="text" id="scale" name="scale" value="' + obj.scale + '" maxlength="4" style="width:70px">';

			html[html.length] = '<li><span class="spn_title">高さ</span>';
			html[html.length] = '&nbsp;';
			html[html.length] = '<input type="text" id="relative_alt" name="relative_alt" value="' + obj.relative_alt + '" maxlength="5" style="width:70px">';

			// その他3Dに関する部分もhiddenで送る
			html[html.length] = '<input type="hidden" id="size"" name="size" value="' + obj.size + '">';
			html[html.length] = '<input type="hidden" id="alt" name="alt" value="' + obj.alt + '">';


			html[html.length] = '<li id="submit">';

			html[html.length] = '<input type="button" id="submit-button" name="submit-button" value="更新" onclick="return x.targetUpdate(' + obj.id + ',' + obj.user_id + ')">';
			html[html.length] = '<input type="button" id="cancel-button" name="cancel-button" value="キャンセル" onclick="return x.editCancel()"> ';


			html[html.length] = '</li>';
		}

		html[html.length] = '</ul>';
		html[html.length] = '</form>';

		d.innerHTML = html.join('');

		return d;
	} ,

	editCancel : function()
	{
		this.initEditTarget();
		this.clearNowTarget();
    	this.closeInfoWindow();
		this.notfit = true;
		this.loadBoundsData();
	} ,

	closeInfoWindow : function()
	{
		var f = $('#upload')[0];
		if ( f )
		{
			var h = f.contentWindow.document.getElementsByTagName('body')[0];
			if ( h )
			{
				h.innerHTML = '';
			}
		}
		if ( this.infoWindow )
		{
			this.infoWindow.close();
			delete this.infoWindow;
			this.infoWindow = null;
		}
	} ,

	clearNowTarget : function()
	{
		if ( this.nowTarget )
		{
			google.maps.event.clearListeners(this.nowTarget, 'dragend');
			google.maps.event.clearListeners(this.nowTarget, 'click');
			this.nowTarget.setMap(null);
			delete this.nowTarget;
			this.nowTarget = null;
		}
	} ,

	initEditTarget : function()
	{
		if ( this.editTarget )
		{
			delete this.editTarget;
			this.editTarget = null;
		}
	} ,

	latlngOptimization : function(value)
	{
		var s = new String(value);
		return s.slice(0, s.indexOf('.') + 7);
	} ,

	_getTargetPosition : function(_target)
	{
		this.location = _target.getPosition();

		return false;
	} ,

	_getGeocodingResults : function(_results, _status)
	{
		var s = '';
		if ( _status == google.maps.GeocoderStatus.OK )
		{
			var japan = this.JAPAN_string;
			var r =  _results;

			for(var i=0, len = r.length; i < len; i++){
				var ra = r[i];
				var rtypes = ra.types;
				var rformatted = ra.formatted_address;

				if (rtypes.length >= 2
						&& (rtypes[0].search("sublocality_level") != -1
						&& rtypes[1] == "sublocality")
						|| rtypes[1] == "political") {
			        if( rformatted.indexOf(japan) != -1 )
			        {
			            s = rformatted.substring(4);
			        }
			        else
			        {
			            s = rformatted;
			        }
			        break;
			    }
			}
        }
		else
		{
			s = "";
		}

		return s;
	},

	_setMapClickEvents : function()
	{
		var self = this;
		if ( this.user != null )
		{
			setTimeout(function()
			{
				var map = self.getMapObject();
			    self.mapClickEvent = google.maps.event.addListener(
			    	map, 'click',
			    	function(event)
			    	{
		            	self.setNewMarker(event.latLng);
			    	}
			    );
			}, 200);
		}
	} ,

	esc : function(str)
	{
		if (str) {
			str.replace("\\", "\\\\");
			str.replace('"', '\"');
			str.replace("'", "\'");
			str.replace('/', '\/');
			str.replace('<', '\x3c');
			str.replace('>', '\x3e');
			str.replace("\x0d", "\r");
			str.replace("\x0a", "\n");
		} else {
			str = "";
		}

		return str;
	},

	isMobile : function()
	{
		var agent = this.userAgent;
		if ( agent.search(/iPhone/) != -1 )
		{
			return true;
		}
		else if ( agent.search(/Android/) != -1 )
		{
			return true;
		}
		else
		{
			return false;
		}
	} ,

	isIE : function()
	{
		return (document.documentElement.getAttribute("style") == document.documentElement.style) ?
			true : false;
	}
};

