var map;
var submap;
var userlay;
var reporterlay;
var shapeLayer;

var rShopPoint = [];
var rReviewerPoint = [];
var rShopMarkers = [];
var rReviewerMarkers = [];
var rShopHtml = [];
var rReviewerHtml = [];
var REPORTER_OFFSET;

for (i = 0; i < 100; i++) {
	rShopPoint[i] = new ZdcPoint();
	rReviewerPoint[i] = new ZdcPoint();
	rShopMarkers[i] = new ZdcMarker();
	rReviewerMarkers[i] = new ZdcMarker();
}

var reporter;
var numSpots;
var isDynamicShow;
var myTimer;
var action_mode;

var zoomLevel = 4;

var REPORTER_IMG;
var reporter_icon;

var n = 0;
var NUM_SPLIT_MOVE = 20;


var geocoder = null;
var httpObj = null;
var side_bar_html;
var customDiv;

var cnt = 0;
var srcY;
var dstY;
var dy;
var scy;

var browser={type:0};
var ua = navigator.userAgent.toLowerCase();
if(ua.indexOf("opera")!=-1){browser.type = 4;}
else if(ua.indexOf("msie")!=-1&&document.all){browser.type = 1;}
else if(ua.indexOf("safari")!=-1){browser.type = 3}
else if(ua.indexOf("mozilla")!=-1){browser.type = 2}


// アイコンを定義
var icon = new ZdcIcon();
icon.size = new ZdcSize(22, 29);
icon.offset = new ZdcPixel(-11, -29);
icon.msgoffset = new ZdcPixel(0, -15);
icon.image = './img/marker.png';

// ---------------------------------------------------------
// ロード load()
// ---------------------------------------------------------
function load() {
		//地図を表示
		showMap();

		//データを初期化して開始
		var apiUrl = getApiUrl();
		dataInit(apiUrl);
}


// ---------------------------------------------------------
// APIに投げるURLを作る getApiUrl()
// ---------------------------------------------------------
function getApiUrl() {
	return '/api.php';
}

// ---------------------------------------------------------
// 地図を最大化 windowMaximize()
// ---------------------------------------------------------
function windowMaximize() {
	var wsize = map.getMapWindowSize();

	// サブマップ利用時は、サブマップの表示位置も変更する
	//submap.resizeMapWindow(document.body.clientHeight-150, document.body.clientWidth-200, 200, 150);

	// 地図の大きさをウィンドウに合わせて変更する
	map.resizeMapWindow(wsize.top, wsize.left, document.body.clientWidth-wsize.left, document.body.clientHeight-wsize.top);

}

// ---------------------------------------------------------
// 地図を表示 showMap()
// ---------------------------------------------------------
function showMap() {

	//地図を表示
	map = new ZdcMap(document.getElementById('map'));
	rakutenMapC_log.append(map);

	map.setMapType('4');

/*
	// サブマップ関連処理
	submap = new ZdcSubMap(document.getElementById("submap"));
	submap.setMapLocation(map.getMapLocation());
	var zoomopt = -5;
	var subzoomopt = 4;
	submap.setParentMap(map, zoomopt);
	map.setChildMap(submap, zoomopt, subzoomopt,15);
*/

	//サイズを最大化する
	windowMaximize();


	// 位置と縮尺を指定する
	map.setMapLocation(ZdcCommon.WGS2TKY(139.6953217 ,35.6862817), zoomLevel);

	// 中心点アイコンウィジットを追加する
	map.addMapCenter(new ZdcMapCenter(4));

	// スケールバーウィジットを追加する
	map.addMapScaleBar(new ZdcScaleBar());


	//-------------------------------------------------------------------------
	// コントロールのカスタマイズ(ユーザコントロール)
	//-------------------------------------------------------------------------
	var usrctl = new ZdcUserControl();

	// 画像をユーザコントロールに追加する
	usrctl.setImage('./img/control.png', new ZdcSize(60,60), './img/shadow.png', new ZdcSize(62,62)); 
	usrctl.setDocPosition(0,0,0,0);

	// アクションボタンを生成する
	usrctl.setAction(1,20,0,39,19);
	usrctl.setAction(2,0,20,19,39);
	usrctl.setAction(3,40,20,59,39);
	usrctl.setAction(4,20,40,39,59);
	usrctl.setAction(5,20,20,39,39);

	// イベントリスナを追加する
	ZdcEvent.addListener(usrctl, 'clickend', function(){
		switch(this.actionid){
			case 'none': break; 
			case 1: map.scrollMap(0,300);	break;
			case 2:map.scrollMap(300,0);	break;
			case 3:	map.scrollMap(-300,0);	break;
			case 4:	map.scrollMap(0,-300);	break;
			case 5:	map.restoreMapLocation();	break;
		}
	});

	//-------------------------------------------------------------------------
	// コントロールのカスタマイズ(ユーザズームコントロール)
	//-------------------------------------------------------------------------
	var zomctl = new ZdcUserZoomControl();

	// ユーザが作成した画像をセットする
	zomctl.setImage('./img/zoomcontrol.png', new ZdcSize(19,154), './img/grid.png', new ZdcSize(19,8), './img/zoomshadow.png', new ZdcSize(21,156));

	// 画像間の位置関係を調整する
	zomctl.setDocPosition(0, 0, 0, 0);
	zomctl.setDragType('2');

	// アクションボタンを生成する
	zomctl.setAction('zoomIn',0,0,19,19);
	zomctl.setAction('zoomOut',0,136,154,154);
	zomctl.setAction('slither',0,0,138,154,19);
	zomctl.setAction('setZoom',0,0,138,154);

	// アクションボタンにイベントハンドラを追加する
	ZdcEvent.addListener(zomctl,'clickend',function() {
		switch(this.actionid){
			case 'zoomIn':
				map.mapZoomIn();
				this.setSlitherPosition();
				break;
			case 'zoomOut': 
				map.mapZoomOut();
				this.setSlitherPosition();
				break;
			case 'setZoom': 
				var s = this.getZoom();
				map.setMapScale(s);
				this.setSlitherPosition();
				break;
		}
	});
	ZdcEvent.addListener(zomctl,'mousedowngrid',function(){
		if(this.actionid=='slither'){
			this.dragstart();
			return false;
		}
	});
	ZdcEvent.addListener(zomctl,'mouseup',function(){
		if(this.actionid=='slither'){
			this.dragend();
		}
	});


	//-------------------------------------------------------------------------
	// ユーザコントロール、ユーザズームコントロールを地図に追加する
	//-------------------------------------------------------------------------
	// 地図にユーザコントロール、ユーザズームコントロールを追加する
	map.addUserControl(usrctl, 5, 5);
	map.addUserZoomControl(zomctl, 71, 26);

	// ユーザズームコントロールのスライサーの初期位置を地図縮尺にあわせる
	zomctl.setSlitherPosition();


	//-------------------------------------------------------------------------
	// レイヤを作成
	//-------------------------------------------------------------------------

	//reporter用ユーザレイヤ
	reporterlay = new ZdcUserLayer();
	reporterlay.setLayerScale(1, 18); // 縮尺レベル1から18に対応
	reporterlay.setLayerType('auto');

	//tooltip用ユーザレイヤ
	userlay = new ZdcUserLayer();
	userlay.setLayerScale(1, 18); // 縮尺レベル1から18に対応
	userlay.setLayerType('auto');


}

// ---------------------------------------------------------
// 初期化 dataInit(functionName)
// ---------------------------------------------------------
function dataInit(functionName) {

	// tooltipsエレメントをappendChildする
	var element = document.createElement('div');
	element.id = "tooltips";
	document.getElementById("map").appendChild(element);

	reporter = document.createElement("div");
	document.getElementById("tooltips").appendChild(reporter);
	reporter.style.visibility="hidden";


	// Jsonpでデータロード
	var script = document.createElement('script');
	script.setAttribute('type', 'text/javascript');
	script.setAttribute('src', functionName);
	script.setAttribute('charset', 'UTF-8');
	document.getElementsByTagName('head').item(0).appendChild(script);
}


// ---------------------------------------------------------
// データ読み込み dataLoad()
// ---------------------------------------------------------
function dataLoad(rSpotData) {
	// init
	side_bar_html = '';
	rShopPoint = [];
	rReviewerPoint = [];
	//rShopMarkers = [];
	//rReviewerMarkers = [];
	rShopHtml = [];
	rReviewerHtml = [];

	numSpots = rSpotData.spot.length;

	// マーカーを配置
	for (var i=0; i<rSpotData.spot.length; i++) {

		//alert('x:'+rSpotData.spot[i].shop_x+', y:'+rSpotData.spot[i].shop_y);

		rShopPoint[i] = ZdcCommon.WGS2TKY(rSpotData.spot[i].shop_x, rSpotData.spot[i].shop_y);
		rReviewerPoint[i] = ZdcCommon.WGS2TKY(rSpotData.spot[i].reviewer_x, rSpotData.spot[i].reviewer_y);

		//rShopMarkers[i] = new ZdcMarker(rShopPoint[i], icon);
		//rReviewerMarkers[i] = new ZdcMarker(rReviewerPoint[i], icon);

		rShopMarkers[i].setPoint(rShopPoint[i]);
		rShopMarkers[i].setIcon(icon);
		rReviewerMarkers[i].setPoint(rReviewerPoint[i]);
		rReviewerMarkers[i].setIcon(icon);


	var infowindow = document.createElement('div');
	infowindow.id = 'infowindow';

	//message
	var message = document.createElement('div');
	message.id = 'message';
	message.innerText   = '今から発送いたします！';
	message.textContent = '今から発送いたします！';

	//img
	var img_link = document.createElement('a');
	img_link.href = rSpotData.spot[i].item_url;

	var img_src = document.createElement('img');
	img_src.src = rSpotData.spot[i].item_img_url;
	img_src.border = 0;
	img_link.appendChild(img_src);

	var img = document.createElement('div');
	img.id = 'img';
	img.appendChild(img_link);


	//title
	var title_link = document.createElement('a');
	title_link.href = rSpotData.spot[i].item_url;

	var title_txt = document.createTextNode(rSpotData.spot[i].item_subject);
	title_link.appendChild(title_txt);

	var title = document.createElement('div');
	title.id = 'title';
	title.appendChild(title_link);

	//price
	var price = document.createElement('div');
	price.id = 'price';
	price.innerText   = '値段：'+ rSpotData.spot[i].item_price +'円';
	price.textContent = '値段：'+ rSpotData.spot[i].item_price +'円';

	//clearboth
	var clearboth = document.createElement('div');
	clearboth.id = 'clearboth';

	//body
	var body = document.createElement('div');
	body.id = 'body';
	body.innerText   = rSpotData.spot[i].item_body;
	body.textContent = rSpotData.spot[i].item_body;


	infowindow.appendChild(message);
	infowindow.appendChild(img);
	infowindow.appendChild(title);
	infowindow.appendChild(price);
	infowindow.appendChild(clearboth);
	infowindow.appendChild(body);


	rShopHtml[i] = infowindow;


	infowindow = document.createElement('div');
	infowindow.id = 'infowindow';

	//message
	message = document.createElement('div');
	message.id = 'message';
	message.innerText   = '到着しました！';
	message.textContent = '到着しました！';

/*
	//img
	img_link = document.createElement('a');
	img_link.href = 'http://plaza.rakuten.co.jp/' + rSpotData.spot[i].blog_base_url + '/recommend/';

	img_src = document.createElement('img');
	img_src.src = 'http://img.simpleapi.net/small/http://plaza.rakuten.co.jp/' + rSpotData.spot[i].item_img_url;
	img_src.border = 0;
	img_link.appendChild(img_src);

	img = document.createElement('div');
	img.id = 'img';
	img.appendChild(img_link);
*/


	//title
	title_link = document.createElement('a');
	title_link.href = 'http://plaza.rakuten.co.jp/' + rSpotData.spot[i].blog_base_url + '/recommend/';

	title_txt = document.createTextNode(rSpotData.spot[i].nickname + 'さん：');
	title_link.appendChild(title_txt);

	var title = document.createElement('div');
	title.id = 'title';
	title.appendChild(title_link);

	//body
	var comment_body = document.createElement('div');
	comment_body.id = 'body';
	comment_body.innerText   = rSpotData.spot[i].body;
	comment_body.textContent = rSpotData.spot[i].body;

	//clearboth
	clearboth = document.createElement('div');
	clearboth.id = 'clearboth';

	infowindow.appendChild(message);
	//infowindow.appendChild(img);
	infowindow.appendChild(title);
	infowindow.appendChild(comment_body);
	infowindow.appendChild(clearboth);


	rReviewerHtml[i] = infowindow;

	}

}


// ----------------------------------------------------------
// メッセージを表示する
// ----------------------------------------------------------
function showMessange(data) {
	// サイドバー書き出し
	document.getElementById("side_bar").innerHTML = data.msg;
}


// ----------------------------------------------------------
// 動的なマーカーを表示する
// ----------------------------------------------------------
function dynamicCreateMarker(data) {
	rSpotData = data;
	dataLoad(rSpotData);

	isDynamicShow = 1;
	action_mode = 'move_center';
	startDynamicShow(0);

}

// ----------------------------------------------------------
// 動的にToolTipを表示開始する
// ----------------------------------------------------------
function startDynamicShow(id) {
	if(isDynamicShow == 1){
		//最後のIDまでいったら、ゼロに戻す。
		if(id == numSpots - 1){
			var apiUrl = getApiUrl();
			dataInit(apiUrl);
		}


		else{
			//(0)action_modeがmove_centerなら中心に動くを表示。
			if(action_mode == 'move_center'){


				var center_x = (parseFloat(rShopPoint[id].lon) + parseFloat(rReviewerPoint[id].lon)) / 2;
				var center_y = (parseFloat(rShopPoint[id].lat) + parseFloat(rReviewerPoint[id].lat)) / 2;

				map.setMapLocation(new ZdcPoint(center_x ,center_y), zoomLevel);

				// 座標によって車の向きを変える
				if(parseFloat(rShopPoint[id].lon) > parseFloat(rReviewerPoint[id].lon)){
					REPORTER_IMG = './img/track_r2l.png';
					REPORTER_OFFSET = new ZdcPixel(-30, -75);
				}else{
					REPORTER_IMG = './img/track_l2r.png';
					REPORTER_OFFSET = new ZdcPixel(-119, -35);
				}
				reporter_icon = new ZdcIcon();
				reporter_icon.image = REPORTER_IMG;
				reporter_icon.offset = REPORTER_OFFSET;

				action_mode = 'shop';

				myTimer = setTimeout( function () {
					startDynamicShow(id);
				}, 4000);

			}

			//(1)action_modeがshopならshopを表示。
			else if(action_mode == 'shop'){

				// データをマーカにセット
				userlay.addMarker(rShopMarkers[id]);

				// 地図にユーザレイヤを追加する
				map.addUserLayer(userlay);

				//tooptipを表示（openUserMsgWindow）
				//rShopMarkers[id].openUserMsgWindow(new ZdcUserMsgWindow(), rShopPoint[id], rShopHtml[id], 1);
				map.openUserMsgWindow(new ZdcUserMsgWindow(), rShopPoint[id], rShopHtml[id], new ZdcPixel(0,0), 2);

				action_mode = 'move';

				myTimer = setTimeout( function () {
					startDynamicShow(id);
				}, 4000);
			}

			//(2)action_modeがmoveならmoveする。
			else if(action_mode == 'move'){
				//startとstopのx,yを特定
				var startx = rShopPoint[id].lon;
				var starty = rShopPoint[id].lat;
				var stopx = rReviewerPoint[id].lon;
				var stopy = rReviewerPoint[id].lat;

				var x = parseFloat(startx) + parseFloat((stopx - startx)/NUM_SPLIT_MOVE * n);
				var y = parseFloat(starty) + parseFloat((stopy - starty)/NUM_SPLIT_MOVE * n);

				//reporterレイヤーを削除
				map.removeUserLayer(reporterlay);

				//reporterの座標を決める
				var temp = new ZdcPoint(x, y);
				var pos = temp;
				reporter.innerHTML = REPORTER_IMG;

				//reporterのマーカーを表示
				var reporter_marker = new ZdcMarker(pos, reporter_icon);
				reporterlay.addMarker(reporter_marker);
				map.addUserLayer(reporterlay);


				if(n == NUM_SPLIT_MOVE){
					n = 0;
					action_mode = 'reviewer';

					myTimer = setTimeout( function () {
						//地図からユーザレイヤを削除する
						map.closeUserMsgWindow();
						startDynamicShow(id);
					}, 2000);

				}else{
					myTimer = setTimeout('startDynamicShow('+id+')' , 10);
					n++;
				}
			}

			//(3)action_modeがreviewerならreviewerを表示。
			else if(action_mode == 'reviewer'){
				reporter.style.visibility = "hidden";

				// データをマーカにセット
				userlay.addMarker(rReviewerMarkers[id]);

				// 地図にユーザレイヤを追加する
				map.addUserLayer(userlay);

				//tooptipを表示（openMsgWindow）
				map.openUserMsgWindow(new ZdcUserMsgWindow(), rReviewerPoint[id], rReviewerHtml[id], new ZdcPixel(0,0), 2);

				action_mode = 'move_center';

				var idplus = id + 1;

				myTimer = setTimeout( function () {
					//地図からユーザレイヤを削除する
					map.closeUserMsgWindow();
					startDynamicShow(idplus);
				}, 5000);
			}

		}

	}
}


