var map = null;
var geocoder = null;
var current_point = null;
var searchControl = null;
var msg_show = null;

// ajaxによるメッセージ送信
function getMessage() {
  new Ajax.Request("./get_log.php", {method: "post", parameters:Form.serialize("messageForm"), onComplete: displayMessage });
}

function displayMessage(httpObj) {
  $("message_area").innerHTML = httpObj.responseText + "</br>";
}

// onload procedure
function OnLoad() {
  loadMap();
  
  // Create a search control
  searchControl = new GSearchControl();

  // Add in a full set of searchers
  var localSearch = new GlocalSearch();
  //searchControl.addSearcher(localSearch);
  searchControl.addSearcher(new GwebSearch());
  //searchControl.addSearcher(new GvideoSearch());
  searchControl.addSearcher(new GblogSearch());

  // Set the Local Search center point
  //localSearch.setCenterPoint("New York, NY");

  // Tell the searcher to draw itself and tell it where to attach
  searchControl.draw(document.getElementById("searchcontrol"));

  // Execute an inital search
  //searchControl.execute("Google");
}
  
// create map
function loadMap() {
  messages = [];
  messages[0] = 'こんにちは';
  messages[1] = 'こんばんは';
  messages[2] = 'おはようです';
  messages[3] = '頑張る！';
  messages[4] = '疲れた。。';
  messages[5] = 'どこなんだろう、ここ';
  messages[6] = 'いい景色ですねー';
  messages[7] = 'お腹空いたかも';
  messages[8] = '眠いです';
  messages[9] = 'この辺りに美味しいお店があったはず';
  messages[10] = 'ずいぶん歩いたのかな';
  messages[11] = 'こっちでいいのかな？';
  messages[12] = '今日はどこまで行こうかな';
  messages[13] = '歌でも歌いますか';
  messages[14] = 'らーららー、ふーふふー';
  messages[15] = 'どっちに行ったら良いのかな';
  messages[16] = 'ふわー、すごい！';
  messages[16] = 'ジュースでも買おうかな';
  messages[17] = '懐かしいなー';
  messages[18] = 'あの人どうしてるかな';
  messages[19] = 'あの人元気かな';
  messages[20] = 'ここに来るとあのときの事思い出します';
  messages[21] = 'ここに来るのは五年振りかな';
  messages[22] = 'いい天気';
  messages[23] = '雨降りそう…';
  messages[24] = '足がパンパン…';
  messages[25] = '今夜のビールは美味しいだろーなー';
  messages[26] = '休暇も明日でおしまいか…';
  messages[27] = '明日から頑張ろう';
  messages[28] = 'はりゃほりゃ';
  messages[29] = 'うがー';
  messages[30] = '温泉とかないのかなー';

  category = [];
  category[0] = '朝';
  category[1] = '夜';
  category[2] = '朝';
  category[3] = '頑張り';
  category[4] = '癒し';
  category[5] = '不安';
  category[6] = '景色';
  category[7] = '食事';
  category[8] = '眠い';
  category[9] = 'グルメ';
  category[10] = '歴史';
  category[11] = '不安';
  category[12] = '楽しい';
  category[13] = '音楽';
  category[14] = '音楽';
  category[15] = '放浪';
  category[16] = '驚き';
  category[16] = '酒';
  category[17] = '懐かしい';
  category[18] = '人';
  category[19] = '人';
  category[20] = '思い出';
  category[21] = '思い出';
  category[22] = '天気';
  category[23] = '雨';
  category[24] = '疲れ';
  category[25] = 'ビール';
  category[26] = '休暇';
  category[27] = '希望';
  category[28] = '不思議';
  category[29] = '珍しい';
  category[30] = '温泉';
  
  // create Google maps
  map = new GMap2(document.getElementById("map"));
  geocoder = new GClientGeocoder();

  // 初期位置設定
  // 初期座標
  x = 139.59;
  y = 35.48;
  // 初期倍率
  z = 4;


  initial_point = new GLatLng(y, x);
  initial_point_marker = new GPoint(x, y);
  //map.centerAndZoom(initial_point, z);
  map.setCenter(initial_point, 17-z);

  marker = new GMarker(initial_point_marker);

  // 以前の位置
  prev_point = initial_point;


  // 地図選択コントローラ
  map.addControl(new GMapTypeControl());
  // 大型コントローラ
  map.addControl(new GLargeMapControl());

  // 地図表示タイプ設定
  //map.setMapType(G_HYBRID_TYPE);
  map.setMapType(G_MAP_TYPE);


}

// 歩数ストック
step_count = 0;
first_time = 1;
change_count = 3;

// 移動単位なんだけど、どのくらいなのやら
//step_width = 0.005;
step_width = 0.010;

// 移動アニメーション
function animation() {

  mesage_id = Math.floor(Math.random() * messages.length);

  if(first_time ==1) {
    x_dir = createDirection();
    y_dir = createDirection();
    first_time = 0;
    msg = messages[mesage_id];
    cat = category[mesage_id];
  }

  // 進路変更
  if(step_count > change_count) {

    x_dir = createDirection();
    y_dir = createDirection();


    change_count = Math.floor(Math.random() * 5);

    msg = messages[mesage_id];
    cat = category[mesage_id];

    step_count = 0;
  }
  
  x += step_width * x_dir;
  y += step_width * y_dir;
  
  //alert('x:' + x + ',y:' + y + ',x_dir:' + x_dir + ',y_dir' + y_dir);
  
  // 次の位置
  point = new GPoint(x, y);

  point = new GLatLng(y, x);
  point_marker = new GPoint(x, y);

  // 移動
  map.panTo(point);
  // マーカー表示
  //map.clearOverlays();
  map.removeOverlay(marker);
  marker = new GMarker(point_marker);
  map.addOverlay(marker);

  // 住所取得
  current_position_lat = map.getCenter().lat();
  current_position_lon = map.getCenter().lng();
  
  var url = 'getAddress.php?lat=' + current_position_lat + '&lon=' + current_position_lon;
  GDownloadUrl(url, function(response, status) { 

    current_address_list = document.getElementById('location').innerHTML;
   
    eval('var result=' + response);
	
	display_str_address = result.pref +  result.city +  result.town + '[' + cat + ']';
    search_str = result.pref +  result.city +  ' ' + cat;
	
	display_str =  '<div style="text-align:left"><a target="_blank" href="http://www.google.com/search?client=safari&rls=ja-jp&q=' + 
	                       search_str + '">' + display_str_address + 
	                       '</a></div><div style="text-align:right">' +  result.time + '</div>';
    
    msg_show = msg + '<br />' + display_str
	document.getElementById('location').innerHTML = msg_show + '<hr />' + current_address_list;

    // Execute an inital search
    searchControl.execute(search_str);

  });

  // 情報ウィンドウ表示
  //map.openInfoWindow(point, document.getElementById('msg'));
  marker.openInfoWindowHtml(msg_show);

  //map.showMapBlowup(point, 12, G_SATELLITE_TYPE);
  
  // 座標表示
  //document.getElementById('location').innerHTML = response;
  //document.getElementById('location').innerHTML = map.getCenterLatLng();
  
  // 線分を引く
  points = [];
  points[0] = prev_point;
  points[1] = point;
  map.addOverlay(new GPolyline(points, '#FF0000', 5, 0.7));
  
  step_count++;
  prev_point = point;
}

id_value = 1;
// 移動アニメーション
function animation2() {
 //alert(id_value);
  
  target = document.getElementById('id_data');
  target.value = id_value;

  id_value++;
  
  getMessage();
}

var timer = null;

// タイマースタート
function start_walk() {
  //alert('test');
  
  //interval = 1150;
  interval = 3500
  
  timer = setInterval("animation()", interval);

  latlng = map.getCenter();

  prev_point = latlng;
  x = latlng.lng();
  y = latlng.lat();
}

// タイマーストップ
function stop_walk() {
  clearInterval(timer);
}


// create random direction(tentative)
function createDirection() {
  return (Math.floor(Math.random() * 8) - 4) / 4;
}

function showAddress(address) {
  geocoder.getLatLng(address, showTheLatLng);
}

function showTheLatLng(latlng) {
  var address = document.getElementById("address").value;
  if(!latlng) {
    alert('not found');
  } else {
    map.setCenter(latlng, 13);
	
	prev_point = latlng;
	x = latlng.lng();
	y = latlng.lat();
  }
}
