var map;

var markers;

var selectedId;
var openWindowId;

var eventHandler_dragEnd;
var eventHandler_zoom;

var isLoaded;

var m = {
  hotspots : [],
  spotPointer : new SpotPointerOverlay(),
  services : [
    'freespot',
    'bbmobile',
    'hotspot',
    'livedoor_wireless',
    'mzone'
  ],
  business_conditions : [
    '',
    ['netcafe', 'ネットカフェ']
  ],
  resize : function() {
    var width = (window.document.body.clientWidth - 250);
    document.getElementById('map').style.width = width + "px";
  },
  getSpot : function(id) {
    for (var i = 0; i < m.hotspots.length; i++) {
      if (m.hotspots[i][0] == id) {
        return m.hotspots[i];
      }
    }
    return false;
  }
}

function load() {

  markers = {};
  
  window.onresize = function() {
    m.resize();
  };

  isLoaded = false;

  if (GBrowserIsCompatible()) {
    
    map = new GMap2($('map'));

    var lat = document.getElementById('lat').value;
    var lng = document.getElementById('lng').value;

    var homeId = getCookie('home_id');
    var homeLat = getCookie('home_lat');
    var homeLng = getCookie('home_lng');

    if (lat == '{$lat}'){
      lat = (homeLat == '') ? 35.68023708247605 : homeLat;
      $('lat').value = lat;
    }
    if (lng == '{$lng}'){
      lng = (homeLng == '') ? 139.76720809936523 : homeLng;
      $('lng').value = lng;
    }

    map.setCenter(new GLatLng(lat, lng), 14);

    // 色々と有効にする
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();

    //コントロール追加
    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());

    // 画面スクロール対策
    GEvent.addDomListener(document.getElementById("map"), "DOMMouseScroll", CancelEvent); // Firefox
    GEvent.addDomListener(document.getElementById("map"), "mousewheel",     CancelEvent); // IE
    
    eventHandler_dragEnd = GEvent.addListener(map, 'dragend', onDragEnd);
    eventHandler_zoom = GEvent.addListener(map, 'zoomend', onDragEnd);
    
    onDragEnd();
    
    GEvent.addListener(map, 'moveend', function(){onMoveEnd();});
    
    map.addOverlay(m.spotPointer);
    
  }
}

function setCenterFromAddress_Areamap(address, zoom){
  map.setZoom(zoom);
  $('address').value = address;
  setCenterFromAddress(address);
}

function setCenterFromAddress(address){
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(address,
    function(latlng){
      //alert(latlng.lat() + ", " + latlng.lng());
      map.setCenter(latlng);
      search(latlng.lat(), latlng.lng());
    }
  );
}

function search(lat, lng){
  
  var limit = $('limit').value;
  var word = $('shopname') ? $('shopname').value : '';
  
  if (map.getZoom() < 9){
    return;
  }
  
  var bounds = map.getBounds();
  var northeast = bounds.getNorthEast();
  var southwest = bounds.getSouthWest();
  var height = northeast.lat() - southwest.lat();
  var width = northeast.lng() - southwest.lng();
  var hankei = (width > height ? width : height) / 2;

  var url = 
    "search_spot.php"
    + "?lat=" + lat
    + "&lng=" + lng
    + "&n=" + northeast.lat()
    + "&s=" + southwest.lat()
    + "&e=" + northeast.lng()
    + "&w=" + southwest.lng()
    + "&hankei=" + hankei
    + "&lim=" + limit
    + (word != '' ? "&word=" + word : '')
  ;
  var services = document.getElementsByName('services');
  for (var i = 0; i < services.length; i++) {
    if (services[i].checked) {
      url += "&ss[]=" + services[i].value;
    }
  }

  var business_conditions = document.getElementsByName('bc');
  for (var i = 0; i < business_conditions.length; i++) {
    if (business_conditions[i].checked) {
      url += "&bc[]=" + business_conditions[i].value;
    }
  }

  if (document.getElementById('power_supply').checked) {
    url += "&ps=1";
  }
  
  if ($('searchUrl')) {
    $('searchUrl').value = url;
  }
  
  GDownloadUrl(url, onSearchComplete);
}

function onMoveEnd(){
  var a = $('currentLocation');
  if (a) {
    var latlng = map.getCenter();
    a.href = 'index.php?lat=' + latlng.lat() + '&lng=' + latlng.lng();
  }
}

function addMarker(id, lat, lng, letter, service_id){
  var tablename = m.services[service_id];
  var icon = new GIcon();
  icon.iconSize = new GSize(31,27);
  icon.iconAnchor = new GPoint(0,26);
  icon.image = "img/" + tablename + ".png";
  var options = new Object();
  options.icon = icon;
  var marker = new GMarker(new GLatLng(lat, lng), options);
  map.addOverlay(marker);

  GEvent.addListener(marker, "mouseover", function(){m.spotPointer.changeInfo(id);});
  GEvent.addListener(marker, "click", function(){window.open('detail.php?id=' + id);});
  markers['' + id] = marker;
}

function onDragStart(){
}

function research(){
  var lat = map.getCenter().lat();
  var lng = map.getCenter().lng();
  document.getElementById('lat').value = lat;
  document.getElementById('lng').value = lng;
  search(lat, lng);
}

function onDragEnd(){
  research();
  $('zoom').value = map.getZoom();
}


function SpotPointerOverlay() { 
  this.prototype = new GOverlay();
  this.container = document.createElement('div');
  this.spotId = false;
  this.changeCaption = function (caption, id) {
    this.caption = caption;
    if (this.container.textNode) {
      this.container.removeChild(this.container.textNode);
    }
    if (caption) {
      var html = caption + "<p><a href='detail.php?id=" + id + "'>詳しい情報を見る</a></p>"
      this.container.textNode = this.container.appendChild(document.createElement('p'));
      var style = this.container.textNode.style;
      style.padding = '0px 5px 0px 0px';
      this.container.textNode.appendChild(document.createTextNode(caption));
      this.container.linkNodeP = this.container.textNode.appendChild(document.createElement('p'));
      this.container.linkNodeA = this.container.linkNodeP.appendChild(document.createElement('a'));
      this.container.linkNodeA.appendChild(document.createTextNode("詳しい情報を見る"));
      this.container.linkNodeA.href = 'detail.php?id=' + id;
    }
  }
  this.changeInfo = function (id) {
    this.spotId = id;
    var spot = m.getSpot(id);
    if (spot) {
      var marker = markers['' + id];
      this.show();
      this.changeCaption(spot[3], id);
      
      var c = map.fromLatLngToDivPixel(marker.getLatLng());
      this.container.style.left = (c.x + 33) + "px";
      this.container.style.top = String(c.y - 52) + "px";
    } else {
      this.hide();
    }
    
  }
  this.refleshInfo = function() {
    var spot = m.getSpot(this.spotId);
    if (spot) {
      var c = map.fromLatLngToDivPixel(new GLatLng(spot[1], spot[2]));
      this.container.style.left = (c.x + 33) + "px";
      this.container.style.top = String(c.y - 52) + "px";
      this.show();
    } else {
      this.hide();
    }
  }
  this.show = function () {
    this.container.style.display = 'block';
  }
  this.hide = function () {
    this.container.style.display = 'none';
  }
}
SpotPointerOverlay.prototype.initialize = function(map) {
  this.changeCaption('');
  
  map.getPane(G_MAP_FLOAT_PANE ).appendChild(this.container);
  
  if (this.spotId) {
    this.changeInfo(this.spotId);
  }
  
  s = this.container.style;
  s.backgroundImage = "url('hukidasi.png')";
  s.width = '240px';
  s.height = '80px';
  s.position = 'absolute';
  s.backgroundRepeat = 'no-repeat';
  s.padding = "5px 0px 0px 12px";
  s.textAlign = "left";
}
SpotPointerOverlay.prototype.redraw = function(){
}

function onSearchComplete(txt, stat){
  
  for (var marker in markers) {
    map.removeOverlay(markers['' + marker]);
  }
  markers = {};
  
  eval("var hotspots = " + txt + ";");
  m.hotspots = hotspots;
  
  var h;
  var infos = '';
  var power_supply = 0;
  for (var i = 0; i < m.hotspots.length; i++) {
    h = m.hotspots[i];
    addMarker(h[0], h[1], h[2], h[3], h[4]);
    power_supply = (h[5] == 1 ? "[電源] " : "");
    infos += "<a href='detail.php?id=" + h[0] + "' target='_blank' onmouseover='m.spotPointer.changeInfo(\"" + h[0] + "\"); return false;'>" + (i+1) + " . " + power_supply + h[3] + "</a><br>";
  }
  var divInfo = document.getElementById('info');
  Element.update(divInfo, infos);
  
  if (!isLoaded){
    isLoaded = true;

    var mode = $('mode').value;
    var id = $('barid').value;
    var lat = $('lat').value;
    var lng = $('lng').value;

    switch(mode){
      case 'bar':
        moveAndOpen(id);
        break;
    }
    
    

  }
  
  m.spotPointer.refleshInfo();
}

function addMarkers () {
  var h;
  for (var i = 0; i < m.hotspots.length; i++) {
    h = m.hotspots[i];
    addMarker(h[0], h[1], h[2], h[3], h[4]);
  }
}

function addInfos () {
  var divInfo = document.getElementById('info');
  
}

function showSmallInfoWindow (id) {
  var spot = m.getSpot(id);
  if (spot == false) {
    return;
  }
  
  var opt = new Object();
  map.openInfoWindow(markers[id].getLatLng(), spot[3], opt);

  openWindowId = id;
}

function setCookie(key, value, expireDays){
  var d = new Date();
    d.setTime(d.getTime() + 24*60*60*1000*expireDays); //24時間後
    expire = d.toGMTString();
  document.cookie = key + '=' + value + ';expires=' + expire;
}

function getCookie(item) {
    var i, index, arr;
    arr = document.cookie.split(";");
    for(i = 0; i < arr.length; i++) {
        index = arr[i].indexOf("=");
        //2番目は頭がスペースのとき
        if(arr[i].substring(0, index) == item || 
                arr[i].substring(0, index) == " " + item)
            return arr[i].substring(index + 1);
    }
    return "";
}

function setHome(){
  var latlng = map.getCenter();
  setCookie('home_id', '', 1);
  setCookie('home_lat', latlng.lat(), 365);
  setCookie('home_lng', latlng.lng(), 365);
  alert('現在地をホームにセットしました！');
}

function setHomeBar(id, lat, lng){
  setCookie('home_id', id, 365);
  setCookie('home_lat', lat, 365);
  setCookie('home_lng', lng, 365);
  alert('この店をホームにセットしました！');
}

function loadHomeBar(){
  alert(getCookie('home_id'));
}

function clearHome(){
  setCookie('home_id', '', 1);
  setCookie('home_lat', '', 1);
  setCookie('home_lng', '', 1);
  setCookie('id', '', 1);
  setCookie('lat', '', 1);
  setCookie('lng', '', 1);
  alert('ホームをクリアしました！');
}
