// (c) 2009-2010 SystemK Corp. / layar.jp All Rights Reserved.
// Minna-no-Layar ver 3.03 (un!tan!)
// Programmed by @mak_oto
function we_go()
{
	var self = this;

	this.data = [];
	this.markerz = [];

	this.getboundsmarkerz_program = 'getboundsmarkerz_v2.php';
	this.recently_pois_program = 'recently_pois.php';
	this.getpoi_program = 'getpoi.php';
	this.setdoko_program = 'setdoko.php';

	this.loading_HTML = '<p style="text-align: left"><img src="./img/loading.gif" style="vertical-align: middle"> 読み込み中…</p>';

	this.user = null;
	this.zoomLevel = null;
	this.mapObject = null;

	this.nowTarget = null;
	this.nowTargetId = null;
	this.nowTargetObj = {
		name : null,
		url : null,
		attribution : null
	};

	this.editTarget = null;
	this.infoWindow = null;
	this.nowAddress = null;

	this.notLoadBounds = false;

	this.max_poi = 20;
	this.max_poi_mobile = 5;

	this.userAgent = navigator.userAgent;

	this.JAPAN_string = '日本, ';
	this.Image_File = null;
	this.default_lat = null;
	this.default_lon = null;
	this.default_poi = null;
	this.lat = null;
	this.lon = null;
	this.notfit = false;
	this.jgrowl_dontview = false;

	this.twitter = null;

	this.history = [];

	// preload images

	var img = [
		'gobutton2.gif', 'gobutton.gif'
	];
	$(img).each(function () {
		var i = new Image();
		i.src = './img/' + this;
	});

	this.init.apply(this, arguments);
}

we_go.prototype =
{
	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;
		}
		if ( arguments[2].poi != '' )
		{
			this.default_poi = arguments[2].poi;
		}

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

		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.twitter = new Twitter(this.mapObject);
			this.loadBoundsData(
			{'setToMap' : function()
				{
					var mapObject = self.mapObject;
					if ( self.default_poi != '' )
					{
						var data = self.data;
						var marker;
						for ( var i = 0, len = data.length; i < len; i++ )
						{
							if ( data[i].ID == self.default_poi )
							{
								marker = self.markerz[i];
								break;
							}
						}
						if ( marker )
						{
					    	self.closeInfoWindow();
							// バルーン表示
					        var infoWindow = new google.maps.InfoWindow();
					        infoWindow.open(mapObject, marker);
							self.infoWindow = infoWindow;

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

							self.getPoi(mapObject, data[i]);
						}
					}
				}
			});
		}
		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.twitter = new Twitter(self.mapObject);
					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.twitter = new Twitter(self.mapObject);
						self.loadBoundsData();
					},
					{enableHighAccuracy:true}
				);
			}
			else
			{
				// マップを作る
				this.zoomLevel = 5;
				this.createMap();
				this.mapObject.setCenter(new google.maps.LatLng(location.lat, location.lng));
				this.twitter = new Twitter(this.mapObject);
				this.loadBoundsData();
			}
		}

		if ( this.user == null )
		{
			parts.setLoginForm('#login');
		}
		else
		{
			$('#login').click(this.logout);
			$('.menu4 a').mouseover(function(e)
			{
				e.preventDefault();
				$('.menu4 a').css({'background-image' : 'url(./img/rogout2.gif)'});
				return false;
			}
			).mouseout(function(e)
			{
				e.preventDefault();
				$('.menu4 a').css({'background-image' : 'url(./img/rogout.gif)'});
			}
			);
			$('#usermenu-open').fancybox({
				'width'				: 480,
				'height'			: 480,
		        'autoScale'     	: false,
		        'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe'
			});
		}

		var d = document.createElement('div');
		var s = d.style;
		s.border = "1px solid #000000";
		s.padding = "3px";
		s.position = "absolute";
		s.top = "5px";
		s.right = "100px";
		s.backgroundColor = "#ffffff";
		s.fontWeight = "bold";
		s.fontSize = "12px";
		$(d).html('<img src="./img/icon_min.gif" style="vertical-align: middle"> : <span id="min-lay-count">0</span> <img src="./img/twitter_min.gif" style="vertical-align: middle"> : <span id="twitter-count">0</span>');
		document.getElementById('map').appendChild(d);

		setTimeout(
		function()
		{
			util.slideAnimation('#boundary-anchor');
		}, 500);
	} ,

	logout : function(e)
	{
		e.preventDefault();
		if ( confirm('ログアウトしますか？') )
		{
			location.href = './logout.php';
		}
		return false;
	} ,

	loginprocess : function(data)
	{
		$('#login').unbind('click.fb');
		$('#login').attr('href', '#');
		$('#login').click(this.logout);
		$('.menu4 a').css({'background-image' : 'url(./img/rogout.gif)'});
		$('.menu4 a').mouseover(function(e)
		{
			e.preventDefault();
			$('.menu4 a').css({'background-image' : 'url(./img/rogout2.gif)'});
			return false;
		}
		).mouseout(function(e)
		{
			e.preventDefault();
			$('.menu4 a').css({'background-image' : 'url(./img/rogout.gif)'});
		}
		);

		$('span#usermenu').html('<a href="./menu.php?popup" id="usermenu-open">' + data['results'][0]['NICKNAME'] + ' さんのメニュー</a>');
		this.user = data.results[0];
		this._setMapClickEvents();
		this.notfit = true;
		this.closeInfoWindow();
		this.allMarkerReget();
		$.fancybox.close();
		$('#usermenu-open').fancybox({
			'width'				: 480,
			'height'			: 480,
	        'autoScale'     	: false,
	        'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe'
		});
	} ,

	logoutprocess : function()
	{
	
	
	
	} ,

	loadRecentlyPois : function()
	{
		var self = this;
		new $.ajax(
		{
			async : true,
			url : self.recently_pois_program,
			type : 'POST',
			data : {
				'dummy' : 'dummy'
			},
			dataType : 'text',
			success : function(data, dataType)
			{
				$('#recently-poi').html(data);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown)
			{
				alert('error');
			},
			complete : function(XMLHttpRequest, textStatus)
			{
			}
		});
	} ,

	loadBoundaryPoiComments : function()
	{
		var self = this;
		var mapObject = this.mapObject;
		var bounds = mapObject.getBounds();
		var center = mapObject.getCenter();
		var northEast = bounds.getNorthEast();
		var southWest = bounds.getSouthWest();

		new $.ajax(
		{
			async : true,
			url : self.getboundsmarkerz_program,
			type : 'POST',
			data : {
				'center' : center.lat() + ',' + center.lng(),
				'northeast' : northEast.lat() + ',' + northEast.lng(), // north, east
				'southwest' : southWest.lat() + ',' + southWest.lng(), // south, west
				'pois' : self.max_poi,
				'type' : 'html'
			},
			dataType : 'text',
			success : function(data, dataType)
			{
				$('#recently-poi').html(data);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown)
			{
				alert('error');
			},
			complete : function(XMLHttpRequest, textStatus)
			{
			}
		});
	} ,

	createMap : function()
	{
		var self = this;

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

		// Zoom 調節のイベント
		google.maps.event.addListener(
			map, 'zoom_changed',
			function()
			{
				if ( self.notLoadBounds == false )
				{
					self.loadBoundsData();
				}
				if ( self.infoWindow )
				{
					var t = (self.editTarget != null) ? self.editTarget : self.nowTarget;
					map.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(map.getCenter());
				}
			}
		);

		this._setMapClickEvents();
	} ,

	init_markers : function()
	{
		for ( var i = this.markerz.length - 1; 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 - 1; i > -1; i-- )
		{
			this.data[i] = null;
			delete this.data[i];
		}
		this.data = [];
	} ,

	loadBoundsData : function(callback)
	{
		var self = this;

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

					new $.ajax(
					{
						async : true,
						url : self.getboundsmarkerz_program,
						type : 'POST',
						data : {
							'center' : lat + ',' + lng,
							'northeast' : northEast.lat() + ',' + northEast.lng(), // north, east
							'southwest' : southWest.lat() + ',' + southWest.lng(), // south, west
							'pois' : self.max_poi
						},
						dataType : 'json',
						success : function(data, dataType)
						{
							self.init_markers();
							self.init_data();
							self.data = data.data;
							if ( data.misc.cnt > self.max_poi )
							{
								if ( self.jgrowl_dontview == false )
								{
									$.jGrowl('表示件数 ' + data.misc.cnt + ' 件を ' + self.max_poi + ' 件までに制限しました<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) { }
									});
								}
							}

							$('#min-lay-count').text(data.data.length);

							if ( callback )
							{
								if ( callback['loadBoundsData'])
								{
									callback['loadBoundsData']();
								}
							}
							self.setToMap(false, callback);
							self.twitter.setToMap();

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

					setTimeout(
					function() {
					new $.ajax(
					{
						async : true,
						url : self.getboundsmarkerz_program,
						type : 'POST',
						data : {
							'center' : center.lat() + ',' + center.lng(),
							'northeast' : northEast.lat() + ',' + northEast.lng(), // north, east
							'southwest' : southWest.lat() + ',' + southWest.lng(), // south, west
							'pois' : self.max_poi,
							'type' : 'html'
						},
						dataType : 'text',
						success : function(data, dataType)
						{
							$('#boundary-poi').html(data);
						},
						error : function(XMLHttpRequest, textStatus, errorThrown)
						{
							alert('error');
						},
						complete : function(XMLHttpRequest, textStatus)
						{
						}
					});
					}, 50);
				}
			}, 100
		);
	} ,

	setToMap : function(bounds, callback)
	{
		var bounds = new google.maps.LatLngBounds();
		var mapObject = this.mapObject;
		var data = this.data;
		var fluster = this.fluster;
		var self = this;

		if ( data.length > 0 )
		{
			
			for ( var i = 0, len = data.length; i < len; i++ )
			{
				if ( data[i].ID != this.nowTargetId )
				{
					var shadowImage = new google.maps.MarkerImage("./img/kage.png");
					shadowImage.size = new google.maps.Size(79, 34);
					shadowImage.origin = new google.maps.Point(0, 0);
					shadowImage.anchor = new google.maps.Point(16, 34);
					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
				            ,icon : new google.maps.MarkerImage("./img/icon.gif")
				            ,shadow : shadowImage
				        });
					self.attachPOIEvent(mapObject, m, data[i]);
					bounds.extend(m.getPosition())
//					fluster.addMarker(m);
					self.markerz[this.markerz.length] = m;
				}
			}
			if ( bounds == true && this.notfit == false )
			{
				mapObject.fitBounds(bounds);
			}

			if ( callback )
			{
				if ( callback['setToMap'] )
				{
					callback['setToMap']();
				}
			}
/*
			fluster.styles = {
				// This style will be used for clusters with more than 0 markers
				0: {
					image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m1.png',
					textColor: '#FFFFFF',
					width: 53,
					height: 52
				},
				// This style will be used for clusters with more than 10 markers
				10: {
					image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m2.png',
					textColor: '#FFFFFF',
					width: 56,
					height: 55
				},
				20: {
					image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m3.png',
					textColor: '#FFFFFF',
					width: 66,
					height: 65
				}
			};
			
			// Initialize Fluster
			// This will set event handlers on the map and calculate clusters the first time.
			fluster.initialize();
*/
		}
	} ,

	attachPOIEvent : function(mapObject, m, data)
	{
		var self = this;

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

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

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

				self.getPoi(mapObject, data);
			}
		);

	} ,

	getPoi : function(mapObject, data)
	{
		var self = this;
		var d = data;

		var i = setTimeout(
		function() {
			if ( self.infoWindow )
			{
				self.infoWindow.setContent(self.loading_HTML);
			}
		}, 500);

		new $.ajax(
		{
			async : true,
			url : self.getpoi_program,
			type : 'POST',
			data : {
				'id' : data.ID
			},
			dataType : 'text',
			success : function(data, dataType)
			{
				clearTimeout(i);
				self.infoWindow.setContent(data);

				var interval = setInterval(
				function() {
					if ( $('#poi-display-complete').val() != undefined )
					{
						clearInterval(interval);

						parts.setLoginForm('#baloon-login');

						$("#getcomment").fancybox({
							'width'				: 300,
							'height'			: 460,
					        'autoScale'     	: false,
					        'transitionIn'		: 'none',
							'transitionOut'		: 'none',
							'type'				: 'iframe'
						});
					}
				}, 1);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown)
			{
				alert('error');
			},
			complete : function(XMLHttpRequest, textStatus)
			{
			}
		});
	} ,

	getEditForm : function(mapObject, data)
	{
		var self = this;
		var d = data;

		var i = setTimeout(
		function() {
			if ( self.infoWindow )
			{
				self.infoWindow.setContent(self.loading_HTML);
			}
		}, 500);

		new $.ajax(
		{
			async : true,
			url : self.getpoi_program,
			type : 'POST',
			data : {
				'id' : data.ID
			},
			dataType : 'text',
			success : function(data, dataType)
			{
				clearTimeout(i);
				self.infoWindow.setContent(data);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown)
			{
				alert('error');
			},
			complete : function(XMLHttpRequest, textStatus)
			{
			}
		});
	} ,

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

	// 既存マーカーの修正
	markerEdit : function(id, user_id)
	{
		this.clearNowTarget();

		var shadowImage = new google.maps.MarkerImage("./img/kage.png");
		shadowImage.size = new google.maps.Size(79, 34);
		shadowImage.origin = new google.maps.Point(0, 0);
		shadowImage.anchor = new google.maps.Point(16, 34);

        this.nowTarget = new google.maps.Marker({
            position: this.editTarget.getPosition(),
            map     : this.mapObject,
            draggable : true,
            title : this.editTarget.getTitle()
            ,icon : new google.maps.MarkerImage("./img/icon.gif")
            ,shadow : shadowImage
        });
		this.nowTargetId = id;
		this.editTarget.setMap(null);

		var mapObject = this.mapObject;

		var self = this;
		var data = {
			id : id,
			user : user_id
		};
		new $.ajax(
		{
			url : 'markeredit.php',
			type : 'POST',
			data : data,
			dataType : 'text',
			success : function(data, dataType)
			{
				self.closeInfoWindow();
				self.nowTarget.setDraggable(true);

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

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

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

				infoWindow.setContent(data);

				self.infoWindow = infoWindow;

				var timeID = setInterval(function()
				{
					if ( document.getElementById('submit-button') )
					{
						clearInterval(timeID);
						self.Image_File = $('#poi-file-name').val();
						self.address = $('#poi-address').val();
					}
				}, 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;

								var address = ( address != '' && address != undefined  ) ? address : '検知できませんでした';
								var html = [];
								html[html.length] = address;

								$('#address').html(html.join(''));
							});
						}
						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;
						alert('削除しました');
						self.loadBoundsData();
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown)
				{
					alert('error');
				},
				complete : function(XMLHttpRequest, textStatus)
				{
				}
			});
		}

		return false;
	} ,

	targetClear : function()
	{
		var self = this;

		google.maps.event.removeListener(
			this.mapClickEvent
	    );

    	this.closeInfoWindow();
		this.clearNowTarget();
		this.initEditTarget();
		this.Image_File = null;

		this._setMapClickEvents();

		return false;
	} ,

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

		if ( this.nowTargetObj['name'] == null || $('#name').val() == '' )
		{
			alert('タイトルを入力してください');
			return false;
		}
		if ( this.nowTargetObj['attribution'] == null || $('#attribution').val() == '' )
		{
			alert('コメントを入力してください');
			return false;
		}
		if ( this.nowTargetObj['url'] != null && $('#url').val() != '' )
		{
			if ( $('#url').val().match('^http:\/\/') == null &&
				 $('#url').val().match('^https:\/\/') == null )
			{
				alert('リンク先URLが不正です。http:// か https:// から入力してください');
				return;
			}
		}

		var data = {
				title : $('#name').val(),
				line2 : this.address,
				attribution : $('#attribution').val(),
				lat : l.lat(),
				lon : l.lng(),
				actions1 : ( this.nowTargetObj['url'] == null ) ? '' : $('#url').val()
		};
		if ( this.Image_File != null && $('#poi-image-delete').attr('checked') == false )
		{
			data['file'] = this.Image_File;
		}

		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 ( $('#name').val() == '' )
		{
			alert('タイトルを入力してください');
			return false;
		}
		if ( $('#attribution').val() == '' )
		{
			alert('コメントを入力してください');
			return false;
		}
		if ( $('#url').val() != '' )
		{
			if ( $('#url').val().match('^http:\/\/') == null &&
				 $('#url').val().match('^https:\/\/') == null )
			{
				alert('リンク先URLが不正です。http:// か https:// から入力してください');
				return;
			}
		}

		var data = {
				id : id,
				user : user_id,
				title : $('#name').val(),
				line2 : this.address,
				attribution : $('#attribution').val(),
				lat : l.lat(),
				lon : l.lng(),
				actions1 : $('#url').val()
		};
		if ( this.Image_File != null && $('#poi-image-delete').attr('checked') == false )
		{
			data['file'] = this.Image_File;
		}

		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)
	{
		var self = this;

		this.clearNowTarget();
       	this.closeInfoWindow();

		var input_click = function(e)
		{
			e.preventDefault();
			$(this).unbind('click', input_click);
			$(this).unbind('focus', input_click);
			$(this).css('color', '#333333');
			$(this).val('');
			self.nowTargetObj[this.id] = '';
			return false;
		};

		var shadowImage = new google.maps.MarkerImage("./img/kage.png");
		shadowImage.size = new google.maps.Size(79, 34);
		shadowImage.origin = new google.maps.Point(0, 0);
		shadowImage.anchor = new google.maps.Point(16, 34);

        this.nowTarget = new google.maps.Marker({
            position: _location,
            map     : this.mapObject,
            draggable : true,
            zIndex : 100,
            icon : new google.maps.MarkerImage("./img/add_icon.gif")
			,shadow : shadowImage
        });
		this.editTarget = null;
		this.Image_File = null;

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

		// バルーンの閉じるイベント
		google.maps.event.addListener(
			infoWindow, 'closeclick',
			function()
			{
				if ( self.nowTargetObj['name'] != null  )
				{
					self.nowTargetObj['name'] = $('#name').val();
				}
				if ( self.nowTargetObj['url'] != null  )
				{
					self.nowTargetObj['url'] = $('#url').val();
				}
				if ( self.nowTargetObj['attribution'] != null  )
				{
					self.nowTargetObj['attribution'] = $('#attribution').val();
				}
				self.closeInfoWindow();
			}
		);

		// マーカーのドラッグイベントの定義
	    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;

						var address = ( address != '' && address != undefined  ) ? address : '検知できませんでした';
						var html = [];
						html[html.length] = address;

						$('#address').html(html.join(''));
					});
				}
				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.nowTarget.getPosition() },
				    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()
							{
								if ( self.nowTargetObj['name'] != null  )
								{
									self.nowTargetObj['name'] = $('#name').val();
								}
								if ( self.nowTargetObj['url'] != null  )
								{
									self.nowTargetObj['url'] = $('#url').val();
								}
								if ( self.nowTargetObj['attribution'] != null  )
								{
									self.nowTargetObj['attribution'] = $('#attribution').val();
								}
								self.closeInfoWindow();
							}
						);
						self.infoWindow = infoWindow;

						var timeID = setInterval(function()
						{
							if ( document.getElementById('submit-button') )
							{
								clearInterval(timeID);
								if ( self.nowTargetObj['name'] == null )
								{
									$('#name').bind('click', input_click);
									$('#name').bind('focus', input_click);
								}
								else
								{
									$('#name').val(self.nowTargetObj['name']);
									$('#name').css('color', '#333333');
								}
								if ( self.nowTargetObj['url'] == null )
								{
									$('#url').bind('click', input_click);
									$('#url').bind('focus', input_click);
								}
								else
								{
									$('#url').val(self.nowTargetObj['url']);
									$('#url').css('color', '#333333');
								}
								if ( self.nowTargetObj['attribution'] == null )
								{
									$('#attribution').bind('click', input_click);
									$('#attribution').bind('focus', input_click);
								}
								else
								{
									$('#attribution').val(self.nowTargetObj['attribution']);
									$('#attribution').css('color', '#333333');
								}
								if ( self.Image_File != null && self.Image_File != '' )
								{
									self.changeImage(self.Image_File);
								}
							}
						}, 100);
					}
				);
			}
		);

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

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

				var timeID = setInterval(function()
				{
					if ( document.getElementById('submit-button') )
					{
						clearInterval(timeID);
						$('#name').bind('click', input_click);
						$('#name').bind('focus', input_click);
						$('#url').bind('click', input_click);
						$('#url').bind('focus', input_click);
						$('#attribution').bind('click', input_click);
						$('#attribution').bind('focus', input_click);
					}
				}, 100);
			}
		);

	},

	baloon_node : function(obj)
	{
		var html = [];
		var d = document.createElement('div');
		d.id = 'baloon-contents';
		html[html.length] = '<form id="baloon" name="baloon" onsubmit="return false"><table><tr><td><div id="baloon-summary"><ul><li><input type="text" id="name" name="name" value="タイトル" style="color: #aaaaaa; font-size: large; width: 230px;" size="20" autocomplete="off" title="地点のタイトルを入力してください"></li><li id="address" style="word-break:break-all">';
		var address = ( obj.address != '' && obj.address != undefined  ) ? obj.address : '検知できませんでした';
		html[html.length] = address + '</li>';
		html[html.length] = '<li style="word-break:break-all"><input type="text" id="url" name="url" value="リンク先URL" size="20" maxlength="100" autocomplete="off" style="color: #aaaaaa; width:230px" title="地点からリンクしたいURLを入力してください"></li></ul>';
		html[html.length] = '<div class="comment"><p class="comment"><textarea id="attribution" name="attribution" cols="20" rows="2" style="color: #aaaaaa; width:230px;" autocomplete="off" title="地点についてのコメントを入力してください">コメント</textarea></p></div>';
		html[html.length] = '<li id="submit"><input type="button" id="submit-button" name="submit-button" value="登録" onclick="return main.targetRegister()"><input type="button" id="cancel-button" name="cancel-button" value="キャンセル" onclick="return main.targetClear()"></li></ul></div></td>';
		html[html.length] = '<td class="image"><div id="image"></div><p id="image-delete"></p><p><iframe src="./file_upload_form.php" id="upload" name="upload" style="height: 16px; width: 100px;" frameborder="0" scrolling="no"></iframe></p></td></tr></table></form>';
		d.innerHTML = html.join('');
		return d;
	} ,

	changeImage : function(image_name)
	{
		this.Image_File = image_name;

		$('#image').html('<img src="/uploaded/' + this.Image_File  + '">');
		$('#image-delete').html('<input type="checkbox" value="1" name="poi-image-delete" id="poi-image-delete" title="チェックを入れるとアップロードした写真は保存されません"><label for="poi-image-delete">写真を削除</label>');
	} ,

	editCancel : function()
	{
		var self = this;

		google.maps.event.removeListener(
			this.mapClickEvent
	    );
		this.initEditTarget();
		this.clearNowTarget();
    	this.closeInfoWindow();
		this.notfit = true;
		this.loadBoundsData();

		this._setMapClickEvents();
	} ,

	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;
			this.nowTargetId = null;
			this.nowTargetObj = {
				name : null,
				url : null,
				attribution : 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" )
			    {
			        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()
			{
			    self.mapClickEvent = google.maps.event.addListener(
			    	self.mapObject, 'click',
			    	function(event)
			    	{
		            	self.setNewMarker(event.latLng);
			    	}
			    );
			}, 200);
		}
	}

};

/* */
function U()
{
	this.init.apply(this, arguments);
}
U.prototype.init = function(){
};
U.prototype.esc = function(str)
{
	str.replace("\\", "\\\\");
	str.replace('"', '\"');
	str.replace("'", "\'");
	str.replace('/', '\/');
	str.replace('<', '\x3c');
	str.replace('>', '\x3e');
	str.replace("\x0d", "\r");
	str.replace("\x0a", "\n");

	return str;
};
U.prototype.isIE = function()
{
	return (document.documentElement.getAttribute("style") == document.documentElement.style) ?
	true : false;
}
U.prototype.slideAnimation = function(obj)
{
	var params = {height:"toggle", opacity:"toggle"};
	$(obj).next().animate(params).parent().siblings()
		.children("ul:visible").animate(params, 'normal');
	return false;
}

/* */
function P()
{
	this.init.apply(this, arguments);
}
P.prototype.init = function()
{
	this.setSearchButton();
	this.setPhotoClick();
	this.setBoundaryClick();
	this.setRecentlyClick();
	this.setRecentlyCommentsClick();
	this.setSlideMenu();
};
P.prototype.setSlideMenu = function()
{
	$("#slidemenu").each(function(){
		$("li > a", this).each(function(index){
			var $this = $(this);

			if(index > 0) $this.next().hide();

			$this.click(function(){
				var params = {height:"toggle", opacity:"toggle"};
				if ( $(this).next().css('display') == 'none' )
				{
					$(this).next().animate(params).parent().siblings()
						.children("ul:visible").animate(params, 'normal');
				}
				return false;
			});
		});
	});
};
P.prototype.setSearchButton = function()
{
	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 )
		    	{
					main.closeInfoWindow();

					main.mapObject.setCenter(new google.maps.LatLng(
			    		results[0].geometry.location.lat(),
			    		results[0].geometry.location.lng())
			    	);
					main.mapObject.setZoom(17);
					new $.ajax(
					{
						async : true,
						url : main.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;
	};
	var search_input_click = function(e)
	{
		e.preventDefault();
		$('#search-input').unbind('click', search_input_click);
		$('#search-input').css('color', '#333333');
		$('#search-input').val('');
		return false;
	};

	$('#search-input').bind('click', search_input_click);
	$('#search-input').keypress(function(e) {
		if(e.which == 13) {
			// 検索結果表示処理
			$('#search-button').focus();
			search_button_click(e);
		}
	});
	$('#jump-form').bind('submit', function(e)
	{
		e.preventDefault();
		return false;
	});

	$('#search-button').mouseover(function(e)
	{
		e.preventDefault();
		$(this).attr('src', './img/gobutton2.gif');
	}).mouseout(function(e)
	{
		e.preventDefault();
		$(this).attr('src', './img/gobutton.gif');
	}).click(search_button_click);;

};
P.prototype.setLoginForm = function(obj)
{
	$(obj).fancybox({
		'width'				: 260,
		'height'			: 260,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
}
P.prototype.setPhotoClick = function()
{
	var photo = function (e)
	{
		e.preventDefault();

		var mapObject = main.mapObject;

		var t = e.target;
		var parent;
		switch (t.nodeName.toLowerCase())
		{
			case 'a':
				parent = t;
			break;
			case 'img':
				parent = t.parentNode;
			break;
		}

		if ( parent )
		{
			main.closeInfoWindow();
			var id = parent.id.split('-');
			mapObject.setCenter(new google.maps.LatLng(parseFloat(id[2]), parseFloat(id[3])));
			main.notLoadBounds = true;
			mapObject.setZoom(17);
			main.notLoadBounds = false;
			main.loadBoundsData({'setToMap' : function()
			{
				var data = main.data;
				var marker;
				for ( var i = 0, len = data.length; i < len; i++ )
				{
					if ( data[i].ID == id[1] )
					{
						marker = main.markerz[i];
						break;
					}
				}
				if ( marker )
				{
			    	main.closeInfoWindow();
					// バルーン表示
			        var infoWindow = new google.maps.InfoWindow();
			        infoWindow.open(mapObject, marker);
					main.infoWindow = infoWindow;

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

					main.getPoi(mapObject, data[i]);
				}
			}});
		}
		return false;
	};

	$('#photo').bind('click', photo);

	$('#photo-load').click(function (e)
	{
		e.preventDefault();

		new $.ajax(
		{
			async : true,
			url : 'recently_photos.php',
			type : 'POST',
			data : {
			},
			dataType : 'text',
			success : function(data, dataType)
			{
				$('#photo').unbind('click', photo);
				$('#photo-container').html(data);
				$('#photo').bind('click', photo);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown)
			{
			},
			complete : function(XMLHttpRequest, textStatus)
			{
			}
		});

		return false;
	});
};
P.prototype.setBoundaryClick = function()
{
	$('#boundary-poi').click(function (e) {
		e.preventDefault();

		var mapObject = main.mapObject;

		var t = e.target;
		var parent;
		switch(t.nodeName.toLowerCase())
		{
			case 'h3':
				parent = t.parentNode.parentNode.parentNode;
			break;
			case 'a':
				parent = t.parentNode.parentNode;
			break;
			case 'p':
				parent = t.parentNode.parentNode;
			break;
			case 'div':
				if ( $(t).attr('class') == 'boundary-summary' )
				{
					parent = t.parentNode;
				}
				else if ( t.id.indexOf("boundary-",0) != -1 )
				{
					parent = t;
				}
				else
				{
					return false;
				}
			break;
			default:
				return false;
			break;
		}
		var id = parent.id.split('-');
		if ( id.length != 4 )
		{
			return false;
		}
		main.closeInfoWindow();
		mapObject.setCenter(new google.maps.LatLng(parseFloat(id[2]  / 1000000), parseFloat(id[3] / 1000000)));
		main.notLoadBounds = true;
		mapObject.setZoom(17);
		main.notLoadBounds = false;
		main.loadBoundsData({'setToMap' : function()
		{
			var data = main.data;
			var marker;
			for ( var i = 0, len = data.length; i < len; i++ )
			{
				if ( data[i].ID == id[1] )
				{
					marker = main.markerz[i];
					break;
				}
			}
			if ( marker )
			{
		    	main.closeInfoWindow();
				// バルーン表示
		        var infoWindow = new google.maps.InfoWindow();
		        infoWindow.open(mapObject, marker);
				main.infoWindow = infoWindow;

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

				main.getPoi(mapObject, data[i]);
			}
			return false;
		}});
		return false;
	});
};
P.prototype.setRecentlyClick = function()
{
	$('#recently-poi').click(function (e) {
		e.preventDefault();

		var mapObject = main.mapObject;

		var t = e.target;
		var parent;
		switch(t.nodeName.toLowerCase())
		{
			case 'h3':
				parent = t.parentNode.parentNode.parentNode;
			break;
			case 'a':
				parent = t.parentNode.parentNode;
			break;
			case 'p':
				parent = t.parentNode.parentNode;
			break;
			case 'div':
				if ( $(t).attr('class') == 'boundary-summary' )
				{
					parent = t.parentNode;
				}
				else if ( t.id.indexOf("boundary-",0) != -1 )
				{
					parent = t;
				}
				else
				{
					return false;
				}
			break;
			default:
				return false;
			break;
		}
		var id = parent.id.split('-');
		if ( id.length != 4 )
		{
			return false;
		}
		main.closeInfoWindow();
		mapObject.setCenter(new google.maps.LatLng(parseFloat(id[2] / 1000000), parseFloat(id[3] / 1000000)));
		main.notLoadBounds = true;
		mapObject.setZoom(17);
		main.notLoadBounds = false;
		main.loadBoundsData({'setToMap' : function()
		{
			var data = main.data;
			var marker;
			for ( var i = 0, len = data.length; i < len; i++ )
			{
				if ( data[i].ID == id[1] )
				{
					marker = main.markerz[i];
					break;
				}
			}
			if ( marker )
			{
		    	main.closeInfoWindow();
				// バルーン表示
		        var infoWindow = new google.maps.InfoWindow();
		        infoWindow.open(mapObject, marker);
				main.infoWindow = infoWindow;

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

				main.getPoi(mapObject, data[i]);
			}
		}});
	});
};
P.prototype.setRecentlyCommentsClick = function()
{
	$('#comments-list').click(function (e) {
		e.preventDefault();

		var mapObject = main.mapObject;

		var t = e.target;
		var parent;
		switch(t.nodeName.toLowerCase())
		{
			case 'a':
				parent = t;
			break;
			default:
				return false;
			break;
		}
		var id = parent.id.split('-');
		if ( id.length != 4 )
		{
			return false;
		}
		main.closeInfoWindow();
		mapObject.setCenter(new google.maps.LatLng(parseFloat(id[2] / 1000000), parseFloat(id[3] / 1000000)));
		main.notLoadBounds = true;
		mapObject.setZoom(17);
		main.notLoadBounds = false;
		main.loadBoundsData({'setToMap' : function()
		{
			var data = main.data;
			var marker;
			for ( var i = 0, len = data.length; i < len; i++ )
			{
				if ( data[i].ID == id[1] )
				{
					marker = main.markerz[i];
					break;
				}
			}
			if ( marker )
			{
		    	main.closeInfoWindow();
				// バルーン表示
		        var infoWindow = new google.maps.InfoWindow();
		        infoWindow.open(mapObject, marker);
				main.infoWindow = infoWindow;

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

				main.getPoi(mapObject, data[i]);
			}
		}});
	});
};
