$(document).ready(function(){
  // 初期化中は非表示
  $('.content_map .details').hide();

  // アコーディオンの設定
  $(".content_map .accordion").accordion();

  var c = $('#map_canvas');
  if (c != null) {
    // 地図を生成
    var map = new GMap2(c[0]);

    GEvent.addListener(map, "load", function(){
      $('.content_map .details .item').css({
        "display": "none",
        "position": "absolute"
      });

      $('.content_map .details').show();
    });

    map.setCenter(new GLatLng(43.0585, 141.347), 10);
    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());
    map.addControl(new GMapTypeControl());
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();

    var icon = new GIcon();
    icon.image = "http://oishii-shokuzai.jp/theme/img/marker.png";
    icon.iconSize = new GSize(24, 24);
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(16, 0);

    // アイテムの設定
    var list_block = $('.content_map .list_block')
    $.each($('.content_map .details .item'), function(idx, elm){
      var item = $(elm);

      // マーカーの設置
      var tmp = item.find('.latlng').text().split(' ', 2);
      var latlng = new GLatLng(tmp[0], tmp[1]);
      var marker = new GMarker(latlng, {"icon":icon});
      GEvent.addListener(marker, "click", function(){
        $.each(item.find('.image_block span'), function(idx, elm_span){
          $(elm_span).after($('<img class="photo" src="' + $(elm_span).text() + '">'));
          $(elm_span).remove();
        });
        item.show('clip');
      });
      map.addOverlay(marker);

      // リストの設置
      var name = item.find('h3').text();
      var address = item.find('.sentence_block .address').text();
      var thumbnail = item.find('.thumbnail').text();
      if (thumbnail == '') {
        thumbnail = 'http://oishii-shokuzai.jp/theme/img/no_image_2015.gif';
      }
      var term = $('<div class="item"><h3>' + name + '</h3><div class="address_block">' + address + '</div><div class="tag_block">くだもの狩り</div><img src="' + thumbnail + '" class="photo"></div>');
      list_block.append(term);
      term.click(function(){
        $.each(item.find('.image_block span'), function(idx, elm_span){
          $(elm_span).after($('<img class="photo" src="' + $(elm_span).text() + '">'));
          $(elm_span).remove();
        });
        item.show('clip');
      });

      // アイテムのクリックイベント
      item.click(function(){
        item.hide('clip');
      });
    });
    
    // 終了処理
    $(document).unload(function(){
      GUnload();
    });
  }
});

