/**
 * Google MyMap EXPO 全般のグローバル変数
 *
 * plotEntries プロット数
 *
 * names マイマップ集の名前リスト
 *
 * first 最初のプロットかどうか
 *       index.htmlの初期プロット時のみ
 *       日本を中心に表示するために必要
 *
 * displayed 新着,おすすめ,ゲストリストを表示したかどうか
 *
 * worksheets 新着マイマップのリストの内、行データを取得していない
 *            ワークシートを日付順に格納した配列
 *
 * plotType プロットしたマイマップ集の種類
 *          新着, おすすめ, or ゲスト
 *
 * general 新着マイマップ用オブジェクト
 *  key 新着スプレッドシートのkey
 *  entiries 新着エントリ情報格納配列
 *  max 新着リストへの最大表示数
 *
 * recommend おすすめマイマップ用オブジェクト
 *  key おすすめスプレッドシートのkey
 *  entiries おすすめエントリ情報格納配列
 *  max おすすめリストへの最大表示数
 *
 * guest ゲストマイマップ用オブジェクト
 *  key ゲストスプレッドシートのkey
 *  entiries ゲストエントリ情報格納配列
 *  max ゲストリストへの最大表示数
 */
var gmymapexpo = new Object();

/**
 * index.html用の初期化関数。
 * 初期化後 ゲストワークーシートから順に
 * ワークシートの読み込みを開始する。
 */
function initTop() {
  initMap();

  var select =
      document.getElementById('items').getElementsByTagName('select')[0];
  gmymapexpo.plotEntries = select.value;
  gmymapexpo.names = {
    general: 'New My Maps',
    recommend: 'Best My Maps',
    guest: 'My Maps by guests'
  };

  gmymapexpo.general = new Object();
  gmymapexpo.general.key = 'pZJwZdcoBTuN43GhMpFUOXw';
  gmymapexpo.general.entries = new Array();
  gmymapexpo.general.max = 10;

  gmymapexpo.recommend = new Object();
  gmymapexpo.recommend.key = 'pZJwZdcoBTuMGrvxlsR6cTw';
  gmymapexpo.recommend.entries = new Array();
  gmymapexpo.recommend.max = 10;

  gmymapexpo.guest = new Object();
  gmymapexpo.guest.key = 'pZJwZdcoBTuMwhaCxQMSpDQ';
  gmymapexpo.guest.entries = new Array();
  gmymapexpo.guest.max = 4;

  gmymapexpo.first = true;
  gmymapexpo.displayed = false;

  loadGuestWorksheets();
}

/**
 * ゲストワークシートの読み込み
 */
function loadGuestWorksheets() {
  loadJson([
            'http://spreadsheets.google.com/feeds/worksheets/',
            gmymapexpo.guest.key,
            '/public/values',
            '?alt=json-in-script',
            '&callback=setGuestWorksheets'
            ].join(''));
}

/**
 * ゲストワークシートの読み込み後、シート名がguestのシートの
 * リストフィードURLを取得。
 * @param json ゲストワークシートフィードのjsonオブジェクト
 */
function setGuestWorksheets(json) {
  for (var i = 0; i < json.feed.entry.length; i++) {
    var entry = json.feed.entry[i];
    if (entry.title.$t == 'guest') {
      loadGuestList(entry.link[0].href);
      break;
    }
  }
}

/**
 * ゲストリストフィードを読み込む。
 * @param href ゲストリストフィードURL
 */
function loadGuestList(href) {
  loadJson([
            href,
            '?alt=json-in-script',
            '&callback=setGuestList',
            '&orderby=position',
            '&reverse=true'
            ].join(''));
}

/**
 * ゲストリストフィードから行データを読み込み
 * gmymapexpo.guest.entriesへ格納する。
 * @param json ゲストリストフィードのjsonオブジェクト
 */
function setGuestList(json) {
  var data = new Array();
  for (var i = 0; i < json.feed.entry.length; i++) {
    var entry = getRowData(json.feed.entry[i]);
    entry.type = 'guest';
    gmymapexpo.guest.entries.push(entry);
  }
  loadRecommendWorksheets();
}

/**
 * おすすめワークシートの読み込み
 */
function loadRecommendWorksheets() {
  loadJson([
            'http://spreadsheets.google.com/feeds/worksheets/',
            gmymapexpo.recommend.key,
            '/public/values',
            '?alt=json-in-script',
            '&callback=setRecommendWorksheets'
            ].join(''));
}

/**
 * おすすめワークシートの読み込み後、シート名がrecommendのシートの
 * リストフィードURLを取得。
 * @param json おすすめワークシートフィードのjsonオブジェクト
 */
function setRecommendWorksheets(json) {
  for (var i = 0; i < json.feed.entry.length; i++) {
    var entry = json.feed.entry[i];
    if (entry.title.$t == 'recommend') {
      loadRecommendList(entry.link[0].href);
      break;
    }
  }
}

/**
 * おすすめリストフィードを読み込む。
 * @param href おすすめリストフィードURL
 */
function loadRecommendList(href) {
  loadJson([
            href,
            '?alt=json-in-script',
            '&callback=setRecommendList',
            '&orderby=position',
            '&reverse=true'
            ].join(''));
}

/**
 * おすすめリストフィードから行データを読み込み
 * gmymapexpo.recommend.entriesへ格納する。
 * @param json おすすめリストフィードのjsonオブジェクト
 */
function setRecommendList(json) {
  var data = new Array();
  if (json.feed.entry) {
    for (var i = 0; i < json.feed.entry.length; i++) {
      var entry = getRowData(json.feed.entry[i]);
      entry.type = 'recommend';
      gmymapexpo.recommend.entries.push(entry);
    }
  }
  loadGeneralWorksheets();
}

/**
 * おすすめワークシートの読み込み
 */
function loadGeneralWorksheets() {
  loadJson([
            'http://spreadsheets.google.com/feeds/worksheets/',
            gmymapexpo.general.key,
            '/public/values',
            '?alt=json-in-script',
            '&callback=setGeneralWorksheets'
            ].join(''));
}

/**
 * おすすめワークシートの読み込み後、シート名がgeneralのシートの
 * リストフィードURLを取得。
 * @param json おすすめワークシートフィードのjsonオブジェクト
 */
function setGeneralWorksheets(json) {
  for (var i = 0; i < json.feed.entry.length; i++) {
    var entry = json.feed.entry[i];
    if (entry.title.$t == 'recommend') {
      loadGeneralList(entry.link[0].href);
      break;
    }
  }
}

/**
 * おすすめリストフィードを読み込む。
 * @param href おすすめリストフィードURL
 */
function loadGeneralList(href) {
  loadJson([
            href,
            '?alt=json-in-script',
            '&callback=setGeneralList',
            '&orderby=position',
            '&reverse=true'
            ].join(''));
}

/**
 * おすすめリストフィードから行データを読み込み
 * gmymapexpo.general.entriesへ格納する。
 * @param json おすすめリストフィードのjsonオブジェクト
 */
function setGeneralList(json) {
  var data = new Array();
  if (json.feed.entry) {
    for (var i = 0; i < json.feed.entry.length; i++) {
      var entry = getRowData(json.feed.entry[i]);
      entry.type = 'general';
      gmymapexpo.general.entries.push(entry);
    }
  }
  //loadGeneralWorksheets();
  plotGeneral();
}  

/**
 * 新着リストを表示する
 * HTML処理
 */
function displayGeneralEntries() {
  var ol = document.getElementById('latest').getElementsByTagName('ol')[0];
  var str = [];
  var max = (gmymapexpo.general.entries.length < gmymapexpo.general.max)
    ? gmymapexpo.general.entries.length
    : gmymapexpo.general.max;
  for (var i = 0; i < max; ++i) {
    var entry = gmymapexpo.general.entries[i];
    var klass = (i%2 == 0)? 'odd': 'even';
    str.push('<li><a href="#mapTitle" onclick="openLatest(');
    str.push(i);
    str.push(');" class="img">');
    str.push('<img src="images/map-icon-');
    str.push(entry.icon);
    str.push('.gif" alt="');
    str.push(entry.icon);
    str.push('" /></a>');
    str.push('<span><a href="#mapTitle" onclick="openLatest(');
    str.push(i);
    str.push(');">');
    str.push(entry.title);
    str.push('</a><br />');
    str.push(entry.nick);
    str.push(' ');
    str.push(entry.date.getDate());
    str.push('/');
    str.push(entry.date.getMonth() + 1);
    str.push('/');
    str.push(entry.date.getFullYear());
    str.push('</span></li>');
  }
  ol.innerHTML = str.join("");
}

/**
 * おすすめリストを表示する
 * HTML処理
 */
function displayRecommendEntries() {
  var ol = document.getElementById('recommend').getElementsByTagName('ol')[0];
  var str = [];
  var max = (gmymapexpo.recommend.entries.length < gmymapexpo.recommend.max)
    ? gmymapexpo.recommend.entries.length
    : gmymapexpo.recommend.max;
  for (var i=0; i<max; i++) {
    var entry = gmymapexpo.recommend.entries[i];
    var klass = (i % 2 == 0) ? 'odd': 'even';
    str.push('<li><a href="#mapTitle" onclick="openRecommend(');
    str.push(i);
    str.push(');" class="img">');

    str.push('<img src="images/map-icon-');
    str.push(entry.icon);
    str.push('.gif" alt="');
    str.push(entry.icon);
    str.push('" /></a>');

    str.push('<span><a href="#mapTitle" onclick="openRecommend(');
    str.push(i);
    str.push(');">');
    str.push(entry.title);
    str.push('</a><br />');
    str.push(entry.nick);
    str.push(' ');
    str.push(entry.date.getDate());
    str.push('/');
    str.push(entry.date.getMonth() + 1);
    str.push('/');
    str.push(entry.date.getFullYear());
    str.push('</span></li>');
  }
  ol.innerHTML = str.join("");
}

/**
 * ゲストリストを表示する
 * HTML処理
 */
function displayGuestEntries() {
  var div = document.getElementById('guestList');
  var str = ['<div class="g-section g-tpl-50-50">'];
  var max = (gmymapexpo.guest.entries.length < gmymapexpo.guest.max)
    ? gmymapexpo.guest.entries.length
    : gmymapexpo.guest.max;
  for (var i=0; i<max; i++) {
    var entry = gmymapexpo.guest.entries[i];
    if (i%2 == 0) {
      str.push('<div class="g-unit g-first">');
    } else {
      str.push('<div class="g-unit">');
    }

    str.push('<ol><li><a href="#mapTitle" onclick="openGuest(');
    str.push(i);
    str.push(');" class="img">');
    str.push('<img src="images/guest-');
    str.push(entry.photo);
    str.push('.jpg" alt="');
    str.push(entry.nick);
    str.push('" /></a>');

    str.push('<span><a href="#mapTitle" onclick="openGuest(');
    str.push(i);
    str.push(');">');
    str.push(entry.nick);
    str.push('</a><br />');
    str.push(entry.title);
    str.push('</span></li></ol></div>');
  }
  str.push('</div>');
  div.innerHTML = str.join("");
}

/**
 * 新着リストのa.onlickにアタッチする関数。
 * 新着リストをプロットし、クリックされたエントリマーカの
 * インフォウィンドウを開く。
 * @param index gmymapexpo.general.entriesのインデックス
 * map.markersのインデックスと一致する
 */
function openLatest(index) {
  plotLatest();
  openMyMapInfo(index);
}

/**
 * おすすめリストのa.onlickにアタッチする関数。
 * おすすめリストをプロットし、クリックされたエントリマーカの
 * インフォウィンドウを開く。
 * @param index gmymapexpo.recommend.entriesのインデックス
 * map.markersのインデックスと一致する
 */
function openRecommend(index) {
  plotRecommend();
  openMyMapInfo(index);
}

/**
 * ゲストリストのa.onlickにアタッチする関数。
 * ゲストリストをプロットし、クリックされたエントリマーカの
 * インフォウィンドウを開く。
 * @param index gmymapexpo.guest.entriesのインデックス
 * map.markersのインデックスと一致する
 */
function openGuest(index) {
  plotGuest();
  openMyMapInfo(index);
}

/**
 * 新着リストをプロットする。
 * プロット数に足りない場合は、1つ古い日付のワークシートを読みにいく。
 * 初期プロットを担当。
 */
function plotGeneral() {
  if (gmymapexpo.plotType != 'general') {
    if ((gmymapexpo.plotEntries == 'all'
         || gmymapexpo.general.entries.length < gmymapexpo.plotEntries)
        && gmymapexpo.worksheets.length > 0) {
      loadGeneralList();
    } else {
      if (!gmymapexpo.displayed) {
        displayGuestEntries();
        displayGeneralEntries();
        displayRecommendEntries();
      }
      gmymapexpo.plotType = 'general';
      _plot();
      setMapListName();
    }
  }
}

/**
 * 現在は、名前をそろえる(latest)だけの意味のない関数
 */
function plotLatest() {
  plotGeneral();
}

/**
 * おすすめリストをプロットする。
 */
function plotRecommend() {
  if (gmymapexpo.plotType != 'recommend') {
    gmymapexpo.plotType = 'recommend';
    _plot();
    setMapListName();
  }
}

/**
 * ゲストリストをプロットする。
 */
function plotGuest() {
  if (gmymapexpo.plotType != 'guest') {
    gmymapexpo.plotType = 'guest';
    _plot();
    setMapListName();
  }
}

/**
 * プロット数に応じてプロットを実行する。
 * 初期プロット時のみresetZoomを実行しない。
 */
function _plot() {
  var entries = gmymapexpo[gmymapexpo.plotType].entries;
  if (gmymapexpo.plotEntries != 'all' &&
      entries.length > gmymapexpo.plotEntries) {
    entries = entries.concat().slice(0, gmymapexpo.plotEntries);
  }
  plotMarkers(entries);
  if (gmymapexpo.first) {
    gmymapexpo.first = false;
  } else {
    resetZoom();
  }
}

/**
 * マイマップリストの切り替えにともなう表示切り替え。
 * HTML処理
 */
function setMapListName() {
  var str = [
             ''
             ].join('');
  document.getElementById('mapListName').innerHTML = str;
}

/**
 * プロット数の変更。
 * select.onchangeにアタッチする関数。
 * プロットタイプ毎にプロット関数を切り替える。
 * @param number プロット数
 */
function changePlots(number) {
  gmymapexpo.plotEntries = number;
  var funcs = {
    general: plotGeneral,
    recommend: plotRecommend,
    guest: plotGuest
  };
  var func = funcs[gmymapexpo.plotType];
  gmymapexpo.plotType = null;
  func();
}

google.setOnLoadCallback(initTop);
