var map;
//var manager;
var allPos = [];
var new_marker;
var mode = 'new_book';
var disable_map_event = '';
var disable_new_marker_infowindowclose_event = '';
var prev_itemlist_length = 1;
var gmarkers = [];
var htmls = [];

function load() {
	
	map = new GMap2(document.getElementById("map"));
	// map.addControl(new GOverviewMapControl());
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(35.654,139.762), 13);
	//map.enableScrollWheelZoom();
	
	plotMarker();

	//$("#body_id").height(document.body.clientHeight);
}

function plotMarker(ean) {

	// 初期化
	map.clearOverlays();
	//manager = new GMarkerManager(map);
	
	gmarkers.length = 0;
	
	//map.setCenter(new GLatLng(38.21786,138.250451), 5);

	// Creates a marker whose info window displays the letter corresponding
	// to the given index.
	function createMarker(point, book_id, ean, quote,creator,title,around) {
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		var baseIcon = new GIcon();
		baseIcon.shadow="http://maps.google.co.jp/mapfiles/ms/icons/msmarker.shadow.png";
		baseIcon.iconSize=new GSize(32,32);
		baseIcon.shadowSize=new GSize(59,32);
		baseIcon.iconAnchor=new GPoint(16,32);
		baseIcon.infoWindowAnchor=new GPoint(16,0);

		// Create a lettered icon for this point using our icon class
		var icon = new GIcon(baseIcon);
		
		if (around == '1') {
			icon.image ="http://maps.google.co.jp/mapfiles/ms/icons/blue.png";
		} else {
			icon.image ="http://maps.google.co.jp/mapfiles/ms/icons/red-dot.png";
		}
		var marker = new GMarker(point,icon);
		var html = "<div id=\"baloon\">" + quote + "<br\>(" + creator + " <a href=\"javascript:void(0);\" onClick=\"change_ean_mode('" + ean + "')\">" + title + "</a>)</div>";
		
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html);
		});

		gmarkers[book_id] = marker;
		htmls[book_id] = html;
		
		return marker;
	}
	
	var successCallback = function (response)
	{
		var status = response.getElementsByTagName('status')[0].firstChild.nodeValue;
		var quote_count = response.getElementsByTagName('quote_count')[0].firstChild.nodeValue;
		var ean_count = response.getElementsByTagName('ean_count')[0].firstChild.nodeValue;
		var show_quote_count = response.getElementsByTagName('show_quote_count')[0].firstChild.nodeValue;
		var show_ean_count = response.getElementsByTagName('show_ean_count')[0].firstChild.nodeValue;

		if (status == 'success') {
			itemlist = response.getElementsByTagName('item');

			for (i = 0; i < itemlist.length; i++) {
				var book_id = itemlist[i].getElementsByTagName('book_id')[0].firstChild.nodeValue;
				if (i == 0) {
					var book_id_first = book_id
				}

				var ean = itemlist[i].getElementsByTagName('ean')[0].firstChild.nodeValue;
				var user_id = itemlist[i].getElementsByTagName('user_id')[0].firstChild.nodeValue;
				
				try {
					var title = itemlist[i].getElementsByTagName('title')[0].firstChild.nodeValue;
				} catch (e) {
					var title = "No Title";
				}

				try {
					var creator = itemlist[i].getElementsByTagName('creator')[0].firstChild.nodeValue;
				} catch (e) {
					var creator = "No Creator";
				}

				try {
					var label = itemlist[i].getElementsByTagName('label')[0].firstChild.nodeValue;
				} catch (e) {
					var label = "No Label";
				}

				try {
					var image = decodeURIComponent(itemlist[i].getElementsByTagName('image')[0].firstChild.nodeValue);
				} catch (e) {
					var image = "images/noimage.jpg";
				}

				try {
					var width = itemlist[i].getElementsByTagName('width')[0].firstChild.nodeValue;
				} catch (e) {
					var width = "120";
				}

				try {
					var height = itemlist[i].getElementsByTagName('height')[0].firstChild.nodeValue;
				} catch (e) {
					var height = "160";
				}

				var quote = itemlist[i].getElementsByTagName('quote')[0].firstChild.nodeValue;

				var lat = itemlist[i].getElementsByTagName('lat')[0].firstChild.nodeValue;
				var lon = itemlist[i].getElementsByTagName('lon')[0].firstChild.nodeValue;
				var around = itemlist[i].getElementsByTagName('around')[0].firstChild.nodeValue;
				
				var point = new GLatLng(lat, lon);
				//manager.addMarker(createMarker(point, book_id, ean),0);
				map.addOverlay(createMarker(point, book_id, ean,quote,creator,title,around));
				
			}

			$('#info').html("<img class='quotation first' src='assets/quotation_f.gif' alt='“'><img src='assets/bn_shi_index.gif' alt='新着10butai／'><!--新着<span class='numL'>10</span>butai<span class='numL slash'>/</span--><span class='numL'>" + ean_count + "</span><img src='assets/bn_honno_l.gif' alt='honno'><span class='numL'>" + quote_count + "</span><img src='assets/bn_butai_l.gif' alt='butai'><img class='quotation' src='assets/quotation_l.gif' alt='”'><p class=''>新着<span class='numL'>10</span>butai<span class='numL slash'>/</span><span class='numL'>" + ean_count + "</span>冊の本から<span class='numL'>" + quote_count + "</span>箇所の舞台が引用されています。</p>");

// mi //			$('#info').html("新着 " + show_quote_count + " butai / " + ean_count + " honno " + quote_count + "butai " + ean_count + "冊の本から" + quote_count + "箇所の舞台が引用されています");

			if (itemlist.length > 0) {
				gmarkers[book_id_first].openInfoWindowHtml(htmls[book_id_first]);
				initZoom();
			}	
		} else {
			alert(response.getElementsByTagName('message')[0].firstChild.nodeValue);
		}
	};
	var errorCallback = function (xml, status, e)
	{
		//  エラーハンドリングを書く。
		//  xml == XMLHttpRequest
		console.log("本データの読み込みエラー");
	};

	//  リクエストを投げる。
	url = "get_book.php";
	$.ajax({
		'type':     "POST",
		'url':      url,
		'data':     {'new' : '1'},
		'success':  successCallback,
		'error':    errorCallback
	});
}

function change_ean_mode(ean) {
	document.location = "book.php?isbn=" + ean;
}

function add_place_popup(back){
	
	if (back) {
		new_marker.enableDragging();
	} else {
		var gmarkeroptions = new Object();
		gmarkeroptions.draggable = true;
		new_marker = new GMarker(map.getCenter(), gmarkeroptions);
		
		map.addOverlay(new_marker);
	}
	
	html = ' \
	<div id="add_book" style="width:500px;"> \
	<input type="text" id="new_book_place" value="舞台を入力" style="width:300px" onKeyPress="if(keyPressFilter(event)) add_place_search();"><a href="javascript:void(0);" onClick="add_place_search();">場所を探す</a> <a href="javascript:void(0);" onClick="add_book();">確定</a> \
	<input type="checkbox" id="add_book_aroundHere" checked>この辺 \
	<div id="add_place_search_result"> \
	</div> \
	</div>';

	disable_new_marker_infowindowclose_event = '1';
	new_marker.openInfoWindowHtml(html);

	// dragエンド
	GEvent.addListener(new_marker, "dragend", function() {
		var book_place = $("#new_book_place").get(0).value;
		var tmp = $("#add_place_search_result").html();
		var aroundHere = $("#add_book_aroundHere").get(0).checked;

		disable_new_marker_infowindowclose_event = '1';
		new_marker.openInfoWindowHtml(html);
		$("#new_book_place").get(0).value = book_place;
		$("#add_place_search_result").html(tmp);
		$("#add_book_aroundHere").get(0).checked = aroundHere;
	});

	GEvent.addListener(new_marker, "infowindowopen", function() {
		mode = 'add_book';
		map.checkResize();
		disable_new_marker_infowindowclose_event = '';
	});

	GEvent.addListener(new_marker, "infowindowclose", function() {
		if (!disable_new_marker_infowindowclose_event) {
			
			map.removeOverlay(new_marker);
			mode = 'new_book';
			map.checkResize();
		}
	});

}