var TABELOG = {
 "center": new GLatLng(35.703554, 139.749495),
 "map": new GMap2(document.getElementById("map")),
 "marker": [],
 "markerNum": 0,
 "enabledAppendMarker": false,
 "pageNum": [1, 1, 1, 1, 1],
 "maxPageNum": [1, 1, 1, 1, 1],
 "shopDetail": [[], [], [], [], []],
 "sortOrder": "totalscore",
 "list": [
  document.getElementById('list_0'),
  document.getElementById('list_1'),
  document.getElementById('list_2'),
  document.getElementById('list_3'),
  document.getElementById('list_4')
 ],
 "pager": [
  document.getElementById('pager_0'),
  document.getElementById('pager_1'),
  document.getElementById('pager_2'),
  document.getElementById('pager_3'),
  document.getElementById('pager_4')
 ],
 "icon": [
  "http://map.fkoji.com/tabelog/img/iconA.png",
  "http://map.fkoji.com/tabelog/img/iconB.png",
  "http://map.fkoji.com/tabelog/img/iconC.png",
  "http://map.fkoji.com/tabelog/img/iconD.png",
  "http://map.fkoji.com/tabelog/img/iconE.png"
 ],
 "shopMarker": [[],[],[],[],[]],
 "geocoder": new GClientGeocoder(),
 "pointIcon": new GIcon(),
 "shopInfo": undefined,
 "preTarget": undefined,
 "infoElement": document.createElement("div"),
 "start": 1,
 "centerInfo": undefined,
 "centerAddress": '',
 "allowGetAddress": true,
 "tab": [
  document.getElementById('tab_0'),
  document.getElementById('tab_1'),
  document.getElementById('tab_2'),
  document.getElementById('tab_3'),
  document.getElementById('tab_4')
 ],
 "barTotal": "http://map.fkoji.com/tabelog/img/bar-image-total.gif",
 "barTaste": "http://map.fkoji.com/tabelog/img/bar-image-taste.gif",
 "barMood": "http://map.fkoji.com/tabelog/img/bar-image-mood.gif",
 "barService": "http://map.fkoji.com/tabelog/img/bar-image-service.gif",
 "shopImage": []
};

TABELOG.onload = function() {
 this.map.setCenter(this.center, 13);
 this.map.addControl(new GSmallMapControl());
 this.map.addControl(new GMapTypeControl());
 this.pointIcon.image = 'http://map.fkoji.com/hotpepper/img/point.gif';
 this.pointIcon.iconSize = new GSize(8, 8);
 this.pointIcon.iconAnchor = new GPoint(4, 4);
 this.pointIcon.infoWindowAnchor = new GPoint(4, 4);
 if (location.href.match(/\?lat=([0-9\.]+)&lng=([0-9\.]+)$/)) {
  this.map.setCenter(new GLatLng(RegExp.$1, RegExp.$2), 13);
 }
 this.appendMarker();
 GEvent.addListener(this.marker[0], "dragstart", function() {
  TABELOG.map.closeInfoWindow();
 });
 this.message("<b>マーカーを好きな場所にドラッグしてみましょう。</b>");
 GEvent.addListener(this.map, "click", function(overlay, point) {
  if (!overlay) {
   TABELOG.allowGetAddress = true;
   if (TABELOG.enabledAppendMarker) {
    TABELOG.appendMarkerMain(point);
    document.getElementById("cancel-append-marker").disabled = true;
    TABELOG.enabledAppendMarker = false;
    TABELOG.requestTabelog(point);
    setTimeout(function(){
     if (TABELOG.marker.length > 1)
      TABELOG.message("<b>このマーカーもドラッグできます。マーカーは5個まで追加できます。</b>");
    }, 1000);
   }
  }
 });
 document.getElementById("sort").selectedIndex
  = (this.sortOrder == "totalscore") ? 0 :
    (this.sortOrder == "taste") ? 1 :
    (this.sortOrder == "service") ? 2 :
    (this.sortOrder == "mood") ? 3 :
    (this.sortOrder == "highprice") ? 4 :
    (this.sortOrder == "lowprice") ? 5 :
    6;
}

TABELOG.appendMarker = function() {
 if (this.marker.length == 0) {
  this.appendMarkerMain(this.map.getCenter());
  TABELOG.requestTabelog(this.map.getCenter());
 } else {
  this.message("<b>お店を探したい場所をクリックしてください。</b>");
  document.getElementById("append-marker").disabled = true;
  document.getElementById("cancel-append-marker").disabled = false;
  this.enabledAppendMarker = true;
 }
}

TABELOG.cancelAppendMarker = function() {
 document.getElementById("append-marker").disabled = false;
 document.getElementById("cancel-append-marker").disabled = true;
 this.enabledAppendMarker = false;
}

TABELOG.appendMarkerMain = function(point) {
 var i = this.marker.length;
 this.markerNum = i;
 var icon = new GIcon();
 icon.image = this.icon[i];
 icon.iconSize = new GSize(33, 64);
 icon.iconAnchor = new GPoint(16, 62);
 icon.infoWindowAnchor = new GPoint(22, 4);
 this.marker.push(new GMarker(point, {"draggable":true, "icon":icon}));
 GEvent.addListener(this.marker[i], "dragend", function() {
  TABELOG.pageNum[i] = 1;
  TABELOG.requestTabelog(TABELOG.marker[i].getPoint());
  setTimeout(function(){
   if (TABELOG.marker.length == 1)
    TABELOG.message("<b>[マーカーを追加]ボタンでマーカーを追加できます。</b>");
  }, 1000);
 });
 GEvent.addListener(this.marker[i], "dragstart", function() {
  TABELOG.markerNum = i;
  TABELOG.resetList(i);
 });
 GEvent.addListener(this.marker[i], "click", function() {
  TABELOG.map.closeInfoWindow();
  TABELOG.changeTab(i);
 });
 this.map.addOverlay(this.marker[i]);
 if (this.marker.length < 5) {
  document.getElementById("append-marker").disabled = false;
 }
}

TABELOG.requestTabelog = function(point) {
 var url = [
  'http://api.tabelog.com/Ver2.1/RestaurantSearch/?',
  'Key=431c629493cf0bb1104c7de263baaeeeb91541c0',
  'Latitude=' + point.y,
  'Longitude=' + point.x,
  'SearchRange=medium',
  'ResultSet=large',
  'SortOrder=' + this.sortOrder,
  'PageNum=' + this.pageNum[this.markerNum]
 ].join('&');
 this.xmlToJson(url, 'TABELOG.putMarker');
}

TABELOG.resetList = function(index) {
 this.map.closeInfoWindow();
 for (var i = 0; i < this.list.length; i++) {
  if (i != index) {
   this.list[i].style.display = 'none';
   this.pager[i].style.display = 'none';
   this.tab[i].className = '';
  } else {
   this.list[i].innerHTML = '';
   this.list[i].style.display = 'block';
   this.pager[i].innerHTML = '';
   this.pager[i].style.display = 'block';
   this.tab[i].className = 'on';
   for (var j = 0; j < this.shopMarker[i].length; j++) {
    this.map.removeOverlay(this.shopMarker[i][j]);
   }
  }
 }
 this.shopImage = [];
}

TABELOG.putMarker = function(json) {
 document.getElementById("loading").style.display = 'none';
 this.shopInfo = eval(json);
 json = undefined;
 this.resetList(this.markerNum);
 if (!this.shopInfo.Item) {
  if (this.pageNum[this.markerNum] == 1) {
   this.list[this.markerNum].style.display = 'block';
   this.list[this.markerNum].innerHTML = '検索結果は 0 件です。';
  }
  return;
 }

 this.maxPageNum[this.markerNum] = Math.floor(this.shopInfo.NumOfResult / 20) + 1;
 this.pager[this.markerNum].innerHTML = '';
 var start = 0;
 var end = 0;
 if (this.pageNum[this.markerNum] <= 3) {
  start = 1;
  end = 5;
 } else {
  start = this.pageNum[this.markerNum] - 2;
  end = this.pageNum[this.markerNum] + 2;
 }
 for (var i = start; i <= end && i <= this.maxPageNum[this.markerNum]; i++) {
  var span = document.createElement("span");
  span.appendChild(document.createTextNode(i));
  var id = i - 1;
  span.id = 'page_' + id;
  if (i == this.pageNum[this.markerNum])
   span.className = 'here';
  this.pager[this.markerNum].appendChild(span);
 }

 if (!this.shopInfo.Item.length) {
  this.shopInfo.Item = [this.shopInfo.Item];
 }
 for (var i = 0; i < this.shopInfo.Item.length; i++) {
  var item = document.createElement('div');
  var num = [
   this.markerNum * 1 + 1,
   20 * (this.pageNum[this.markerNum] - 1) + (i + 1)
  ].join('.');
  var detail = {
   "name": this.shopInfo.Item[i].RestaurantName,
   "category": this.shopInfo.Item[i].Category,
   "url": this.shopInfo.Item[i].TabelogUrl,
   "total": this.shopInfo.Item[i].TotalScore,
   "taste": this.shopInfo.Item[i].TasteScore,
   "service": this.shopInfo.Item[i].ServiceScore,
   "mood": this.shopInfo.Item[i].MoodScore,
   "dinner": this.shopInfo.Item[i].DinnerPrice,
   "situation": this.shopInfo.Item[i].Situation
  };
  this.shopDetail[this.markerNum][i] = detail;
  var score = detail[this.sortOrder] || detail.total || 0;
  var tail = (this.sortOrder == "highprice" || this.sortOrder == "lowprice") ? detail.dinner : score + 'pt';
  item.appendChild(document.createTextNode(num + '. ' + detail.name + ' [' + detail.category + '] ' + tail));
  var bar1 = document.createElement("img");
  var bar2 = document.createElement("img");
  var bar3 = document.createElement("img");
  var bar4 = document.createElement("img");
  bar1.src = this.barTotal;
  bar2.src = this.barTaste;
  bar3.src = this.barService;
  bar4.src = this.barMood;
  bar1.width = Math.floor(300 * (detail.total / 5.0));
  bar2.width = Math.floor(300 * (detail.taste / 5.0));
  bar3.width = Math.floor(300 * (detail.service / 5.0));
  bar4.width = Math.floor(300 * (detail.mood / 5.0));
  bar1.height = 2;
  bar2.height = 2;
  bar3.height = 2;
  bar4.height = 2;
  var p = document.createElement("p");
  p.appendChild(bar1);
  p.appendChild(document.createElement("br"));
  p.appendChild(bar2);
  p.appendChild(document.createElement("br"));
  p.appendChild(bar3);
  p.appendChild(document.createElement("br"));
  p.appendChild(bar4);
  item.appendChild(p);
  item.className = 'item';
  item.id = 'shop_' + this.markerNum + '.' + i;
  this.list[this.markerNum].appendChild(item);
  this.shopMarker[this.markerNum][i] = this.createShopMarker(
   num,
   this.shopInfo.Item[i].Longitude,
   this.shopInfo.Item[i].Latitude,
   this.shopInfo.Item[i].RestaurantName,
   this.shopInfo.Item[i].Category,
   this.shopInfo.Item[i].Situation,
   this.shopInfo.Item[i].DinnerPrice,
   this.shopInfo.Item[i].TabelogUrl,
   i,
   this.markerNum
  );
  TABELOG.map.addOverlay(this.shopMarker[this.markerNum][i]);
 }
 this.list[this.markerNum].style.display = 'block';
 this.tab[this.markerNum].style.display = 'block';
 this.tab[this.markerNum].className = 'on';
}

TABELOG.createShopMarker = function(num, x, y, n, c, s, d, url, id, index) {
 var marker = new GMarker(new GPoint(x, y), {"icon":TABELOG.pointIcon});
 GEvent.addListener(marker, "click", function() {
  for (var i = 0; i < TABELOG.list.length; i++) {
   TABELOG.list[i].style.display = (i == index) ? 'block' : 'none';
   TABELOG.tab[i].className = (i == index) ? 'on' : '';
   TABELOG.pager[i].style.display = (i == index) ? 'block' : 'none';
   TABELOG.markerNum = index;
  }
  marker.openInfoWindowHtml(TABELOG.createInfo(num, url, n, c, s, d));
  for (var i = 0 ; i < 20; i++) {
   if (document.getElementById("shop_" + index + '.' + i)) {
    if (i == id)
     document.getElementById("shop_" + index + '.' + i).style.fontWeight = 'bold';
    else
     document.getElementById("shop_" + index + '.' + i).style.fontWeight = '';
   }
  }
 });
 return marker;
}

TABELOG.changeTab = function(num) {
 this.markerNum = num;
 for (var i = 0; i < 5; i++) {
  if (i == num) {
   this.tab[i].className = 'on';
   this.list[i].style.display = 'block';
   this.pager[i].style.display = 'block';
  } else {
   this.tab[i].className = '';
   this.list[i].style.display = 'none';
   this.pager[i].style.display = 'none';
  }
 }
}

TABELOG.previous = function() {
 if (this.pageNum[this.markerNum] > 1) {
  this.pageNum[this.markerNum]--;
  this.requestTabelog(this.marker[this.markerNum].getPoint());
 }
}

TABELOG.next = function() {
 if (this.pageNum[this.markerNum] < this.maxPageNum[this.markerNum]) {
  this.pageNum[this.markerNum]++;
  this.requestTabelog(this.marker[this.markerNum].getPoint());
 }
}

TABELOG.page = function(page) {
 this.pageNum[this.markerNum] = page * 1 + 1;
 this.requestTabelog(this.marker[this.markerNum].getPoint());
}

TABELOG.xmlToJson = function(url, callback) {
 this.appendScript('http://api.fkoji.com/xml_to_json.php?url=' + encodeURIComponent(url) + '&callback=' + callback);
}

TABELOG.appendScript = function(url) {
 var script = document.createElement("script");
 script.src = url;
 script.type = 'text/javascript';
 script.charset = 'UTF-8';
 document.lastChild.appendChild(script);
}

TABELOG.openInfoWindow = function(index, num, target) {
 if (TABELOG.preTarget == target) {
  TABELOG.close();
  return;
 }
 if (this.preTarget) {
  this.preTarget.style.fontWeight = '';
 }
 this.shopMarker[index][num].openInfoWindowHtml(
  this.createInfo(
   [index * 1 + 1, num * 1 + (this.pageNum[index] - 1) * 20 + 1].join('.'),
   this.shopDetail[index][num].url,
   this.shopDetail[index][num].name,
   this.shopDetail[index][num].category,
   this.shopDetail[index][num].situation,
   this.shopDetail[index][num].dinner
  )
 );
 target.style.fontWeight = 'bold';
 this.preTarget = target;
}

TABELOG.createInfo = function(num, url, name, category, situation, dinner) {
 return '<p>' + num + '. <a href="' + url + '" target="_blank">' + name + '</a><br />[' + category + '] ' + situation + '<br />' + dinner + '</p><p><input type="button" id="zoom-in" value="ズームイン" onclick="TABELOG.map.setZoom(17);"/></p>'
}

TABELOG.clickObserver = function(event) {
 event = event || window.event;
 var target = event.target || event.srcElement;
 if (target.id.match(/^shop_([0-9])\.([0-9]+)$/)) {
  var index = RegExp.$1;
  var num = RegExp.$2;
  TABELOG.openInfoWindow(index, num, target);
 }
 else if (target.id.match(/^page_([0-9]+)$/)) {
  TABELOG.page(RegExp.$1);
 }
 else if (target.className == 'close') {
  TABELOG.close();
 }
}

TABELOG.search = function(q) {
 TABELOG.allowGetAddress = true;
 this.geocoder.getLatLng(q, function(point) {
  if (point) {
   TABELOG.map.setCenter(point);
  }
 });
 return false;
}

TABELOG.close = function() {
 TABELOG.preTarget.style.fontWeight = '';
 TABELOG.preTarget = undefined;
 TABELOG.map.closeInfoWindow();
}

TABELOG.selectSort = function(select) {
 this.sortOrder = select.options[select.selectedIndex].value;
 if (this.marker.length == 0) {
  this.requestTabelog(this.map.getCenter());
 } else {
  this.pageNum[this.markerNum] = 1;
  this.requestTabelog(this.marker[this.markerNum].getPoint());
 }
}

TABELOG.message = function(msg) {
 document.getElementById("tips-area").innerHTML = msg;
}

window.onload = function() {
 document.getElementsByTagName("html")[0].onclick = TABELOG.clickObserver;
 TABELOG.onload();
}
