var id;

var map;
var geocoder;
var address;
var gps;

var lat = 35.658587;
var lng = 139.745425;

var cnt = 0;

var maptypes = [
	G_NORMAL_MAP,
	G_SATELLITE_MAP,
	G_HYBRID_MAP
];

$(document).ready(function() {
	var latitude = $.cookie('latitude');
	var longtitude = $.cookie('longtitude');

	if (latitude != null && longtitude != null) {
		lat = latitude;
		lng = longtitude;
	}

	initGeoLocation();

	var hasParam = checkParam(window.location.search);
	var isDbConnect = checkDbConnect();

	$("body").attr("onload", initialize(hasParam, isDbConnect));
});

function initialize(hasParam, isDbConnect) {
	var zoom = $.cookie('zoom');

	map = new GMap2(document.getElementById("map_canvas"));
	map.setCenter(new GLatLng(lat, lng), (zoom != null && !isNaN(zoom)) ? Number(zoom) : 15);
	GEvent.addListener(map, "click",
		function(overlay, latlng) {
			onMapClick(latlng, isDbConnect);
		}
	);
	GEvent.addListener(map, "zoomend",
		function(oldLevel, newLevel) {
			$.cookie('zoom', newLevel, {expires:30, path:'/app/strayed/'});
		}
	);
	GEvent.addListener(map.getInfoWindow(), "closeclick",
		function() {
			closeInfoWindow(isDbConnect, true);
		}
	);

	var maptype = $.cookie('maptype');
	map.addControl(new GMapTypeControl(true));
	map.addControl(new GSmallZoomControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5, 34)));
	map.addControl(new HistoryControl());
	map.addControl(new NavigationControl());
	map.setMapType((maptype) ? maptypes[maptype] : G_NORMAL_MAP);
	GEvent.addListener(map, "maptypechanged",
		function() {
			for(i = 0; i < maptypes.length; i++) {
				if (map.getCurrentMapType() === maptypes[i]) {
					$.cookie('maptype', i, {expires:30, path:'/app/strayed/'});
					return;
				}
			}
		}
	);

	geocoder = new GClientGeocoder();

	if (hasParam) {
		getAddress(new GLatLng(lat, lng), hasParam, isDbConnect);
	}
	else {
		if (gps != null) {
			gps.getCurrentPosition(
				function(e) {
					getAddress(new GLatLng(e.coords.latitude, e.coords.longitude), hasParam, isDbConnect, true);
				},
				function(error) {
					alert(error.message);
					changeWatchLocation(true, isDbConnect);
				}
			);
		}
	}

	var adsManagerOptions = {
		maxAdsOnMap : 1,
		style: G_ADSMANAGER_STYLE_ADUNIT
	};

	adsManager = new GAdsManager(map, 'pub-0597307270877941', adsManagerOptions);
	adsManager.enable();
}

function initGeoLocation() {
	if (gps == null) {
		if (navigator != null && navigator.geolocation != null) {
			gps  = navigator.geolocation;
		}
		else {
			try {
				gps = google.gears.factory.create('beta.geolocation');
			}
			catch (error) {
				return false;
			}
		}
	}

	return true;
}

function changeWatchLocation(isWatch, isDbConnect) {
	if (gps != null) {
		if (isWatch) {
			id = gps.watchPosition(
				function(e) {
					onLocationChanged(e, isDbConnect);
				},
				function(error) {
					alert(error.message);
				}
			);
		}
		else {
			if (id != null) {
				id = gps.clearWatch(id);
			}
		}
	}
}

function onLocationChanged(e, isDbConnect) {
	var distance = getDistance(lat, lng, e.coords.latitude, e.coords.longitude);

	if (distance >= 30) {
		if (distance >= 50) {
			cnt++;
			
			if (cnt != 3) {
				return;
			}
		}

		cnt = 0;

		changeWatchLocation(false);
		getAddress(new GLatLng(e.coords.latitude, e.coords.longitude), false, isDbConnect, true);
	}
}

function onMapClick(latlng, isDbConnect) {
	getAddress(latlng, true, isDbConnect);
}

function getDistance(srclat, srclng, dstlat, dstlng) {
	var src = new GLatLng(srclat, srclng);
	var dst = new GLatLng(dstlat, dstlng);
	return dst.distanceFrom(src);
}

function getAddress(latlng, isClick, isDbConnect, isGPS) {
	if (latlng != null) {
		lat = latlng.lat();
		lng = latlng.lng();
		geocoder.getLocations(latlng, function(response) {
				showAddress(response, latlng, isClick, isDbConnect, isGPS);
			}
		);
	}
}

function showAddress(response, latlng, isClick, isDbConnect, isGPS) {
	if (response != null && response.Status.code == 200) {
		var dt = new Date();
		var month = dt.getMonth() + 1;
		var date = dt.getDate();
		var hour = dt.getHours();
		var min = dt.getMinutes();
		var sec = dt.getSeconds();
		var locale = dt.getFullYear() + "-" + 
			((month < 10) ? "0" + month : month) + "-" + 
			((date < 10) ? "0" + date : date) + " " + 
			((hour < 10) ? "0" + hour : hour) + ":" + 
			((min < 10) ? "0" + min : min) + ":" + 
			((sec < 10) ? "0" + sec : sec);

		map.clearOverlays();
		place = response.Placemark[0];
		var marker = new GMarker(latlng);
		map.addOverlay(marker);
		marker.openInfoWindowHtml(
			"<div class='info'><p class='address'>" + place.address + "</p>" +
			"<p class='datetime'>" + dt.toLocaleString() + "</p></div>" +
			"<div id='footer'>" + 
			((isGPS) ? "<img class='gps' src='../assets/gps.png' alt='GPSモード' />" : "") + 
			"<a class='mailto' href='mailto:?body=http://flashcast.jp/app/strayed/map/?latlng=" + latlng.lat() + ',' + latlng.lng() + "'></a>" + 
			"<a class='button' href='javascript:closeInfoWindow(" + isDbConnect + ", true);'>close</a>" + 
			((isDbConnect) ? "<a class='button' href='javascript:saveLocation(\"" + locale + "\");'>save</a>" : "") + "</div>");
		$.cookie('latitude', latlng.lat(), {expires:30, path:'/app/strayed/'});
		$.cookie('longtitude', latlng.lng(), {expires:30, path:'/app/strayed/'});
		address = response;

		if (address.__shared == undefined) {
			address.__shared = "";
		}
	}
	else {
		if (isClick) {
			alert("Sorry. Could not get the address info.");
		}
	}

	changeWatchLocation(!isClick, isDbConnect);
}

function saveLocation(locale) {
	if (!executeSql('INSERT INTO history(dat, locale) VALUES(?, ?)',
		[tonosamart.obj2Json(address), locale])) {
		alert("Sorry. Could not save the address info.");
	}

	closeInfoWindow(true, true);
}

function closeInfoWindow(isDbConnect, isClose) {
	map.clearOverlays();

	if (isClose) {
		if (!id) {
			changeWatchLocation(true, isDbConnect);
		}
	}
}

function checkParam(param) {
	var hasParam = false;

	if (param) {
		if (param.toLowerCase().indexOf('latlng=', 1) === 1) {
			var arr = param.substr(8).split(',');

			if (arr) {
				if (arr.length === 2) {
					if (!isNaN(arr[0]) && !isNaN(arr[1])) {
						lat = arr[0];
						lng = arr[1];
						hasParam = true;
					}
				}
			}
		}
	}

	return hasParam;
}