var $ = function(id) {
    return document.getElementById(id);
}

var HOTPEPPER = {
    baseUrl: "http://map.fkoji.com/hotpepper/",
    baseApiUrl: "http://api.hotpepper.jp/GourmetSearch/V110/?key=guest",
    center: new GLatLng(35.690616, 139.706271),
    map: new GMap2($("map")),
    geocoder: new GClientGeocoder(),
    pointIcon: [new GIcon(), new GIcon(), new GIcon(), new GIcon(), new GIcon()],
    shopInfo: undefined,
    preTarget: undefined,
    infoElement: document.createElement("div"),
    start: 1,
    centerInfo: undefined,
    centerAddress: '',
    allowGetAddress: true,
    list: [$('list_0'), $('list_1'), $('list_2'), $('list_3'), $('list_4')],
    tab: [$('tab_0'), $('tab_1'), $('tab_2'), $('tab_3'), $('tab_4')],
    navi: [$('pre'), $('next')],
    shopImage: [],
    marker: []
};

HOTPEPPER.init = function() {
    var iconFile = [
        this.baseUrl + "img/point-red.gif",
        this.baseUrl + "img/point-orange.gif",
        this.baseUrl + "img/point-green.gif",
        this.baseUrl + "img/point-blue.gif",
        this.baseUrl + "img/point-purple.gif",
    ];
    this.map.setCenter(this.center, 16);
    this.map.addControl(new GSmallMapControl());
    this.map.addControl(new GMapTypeControl());
    for (var i = 0; i < this.pointIcon.length; i++) {
	    this.pointIcon[i].image = iconFile[i];
 	    this.pointIcon[i].iconSize = new GSize(8, 8);
 	    this.pointIcon[i].iconAnchor = new GPoint(4, 4);
 	    this.pointIcon[i].infoWindowAnchor = new GPoint(4, 4);
    }

    var adsManager = new GAdsManager(this.map, 'partner-pub-3040571398200955', {
        maxAdsOnMap : 10,
        style: G_ADSMANAGER_STYLE_ADUNIT,
        channel: '1181035489',
        position: new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 24))
    });
    adsManager.enable();
}

HOTPEPPER.onload = function() {
    this.init();
    /* 店舗ID指定 */
    if (location.href.match(/(J[0-9]+)$/)) {
        this.getShopInfoById(RegExp.$1);
    }
    /* 緯度・経度指定 */
    else if (location.href.match(/\?lat=([0-9\.]+)&lng=([0-9\.]+)$/)) {
        this.map.setCenter(new GLatLng(RegExp.$1, RegExp.$2), 14);
        this.getCenterAddress();
    } else {
        /* 通常 */
        this.getCenterAddress();
    }
    GEvent.addListener(this.map, "click", function(overlay, point) {
        if (!overlay) {
            HOTPEPPER.allowGetAddress = true;
        }
    });
    GEvent.addListener(this.map, "moveend", function() {
        if (HOTPEPPER.allowGetAddress) {
            HOTPEPPER.map.clearOverlays();
            HOTPEPPER.preTarget = undefined;
            HOTPEPPER.start = 1;
            HOTPEPPER.getCenterAddress();
        }
    });
}

HOTPEPPER.getShopInfoById = function(id) {
    var hpUrl = [
        this.baseApiUrl,
        'ShopIdFront='+id,
    ].join('&');
    this.xmlToJson(hpUrl, 'HOTPEPPER.putMarker');
}

HOTPEPPER.getCenterAddress = function() {
    var center = this.map.getCenter();
    var invGeocoderUrl = [
        'http://nishioka.sakura.ne.jp/google/ws.php?',
        'lon='+center.x,
        'lat='+center.y,
        'format=simple'
    ].join('&');
    //this.xmlToJson(invGeocoderUrl, 'HOTPEPPER.requestHotpepper');
    HOTPEPPER.requestHotpepper({});
}

HOTPEPPER.requestHotpepper = function(json) {
    $("loading").style.display = 'block';
    this.centerInfo = eval(json);
    json = undefined;
    //this.centerAddress = this.centerInfo.point.pref + this.centerInfo.point.city + this.centerInfo.point.town;
    //$('address').innerHTML = this.centerAddress;
    var center = this.map.getCenter();
    var zoom = this.map.getZoom();
    var range = (zoom >= 16) ? 1 : (zoom >= 15) ? 2 : (zoom >= 14) ? 3 : (zoom >= 13) ? 4 : 5;
    var hpUrl = [
        this.baseApiUrl,
        'Latitude='+center.y,
        'Longitude='+center.x,
        'Range='+range,
        'Start='+this.start,
        'Count=100'
    ].join('&');
    this.xmlToJson(hpUrl, 'HOTPEPPER.putMarker');
    var geocoder = new GClientGeocoder();
    geocoder.getLocations(center, function(addresses) {
        if (addresses.Status.code == 200) {
            var result = addresses.Placemark[0];
            $('address').innerHTML = result.address;
        }
    });
}

HOTPEPPER.resetList = function() {
    for (var i = 0; i < this.list.length; i++) {
        this.list[i].innerHTML = '';
        this.list[i].style.display = 'none';
        this.tab[i].style.fontWeight = '';
        this.tab[i].style.display = 'none';
    }
    this.navi[0].style.display = 'none';
    this.navi[1].style.display = 'none';
    this.shopImage = [];
}

HOTPEPPER.putMarker = function(json) {
    this.shopInfo = eval(json);
    json = undefined;
    this.resetList();
    if (!this.shopInfo.Shop) {
        this.list[0].style.display = 'block';
        this.list[0].innerHTML = '検索結果は 0 件です。';
        $("loading").style.display = 'none';
        return;
    }
    if (this.start >= 101) {
        this.navi[0].style.display = 'block';
    }
    if (this.shopInfo.NumberOfResults - this.start >= 100) {
        this.navi[1].style.display = 'block';
    }
    if (!this.shopInfo.Shop.length) {
        this.shopInfo.Shop = [this.shopInfo.Shop];
    }
    var j = -1;
    for (var i = 0; i < this.shopInfo.Shop.length; i++) {
        if (i % 20 == 0) {
            j++;
            this.tab[j].style.display = 'block';
        }
        var item = this.createItem(i, j);
        this.list[j].appendChild(item);
        this.createMarker(i, j);
        this.map.addOverlay(this.marker[i]);
        this.shopImage[i] = document.createElement("img");
        this.shopImage[i].src = this.shopInfo.Shop[i].PictureUrl.PcSmallImg;
        this.shopImage[i].id = 'shopimage_' + i;
        this.shopImage[i].title = '地図に表示';
    }
    this.list[0].style.display = 'block';
    this.tab[0].style.fontWeight = 'bold';
    if (this.shopInfo.Shop.length == 1) {
        this.openInfoWindow(0, item);
    }
    $("loading").style.display = 'none';
}

HOTPEPPER.createItem = function(i, j) {
    var item = document.createElement('div');
    var num = i + 1;
    item.appendChild(document.createTextNode(num+'. '+this.shopInfo.Shop[i].ShopName));
    item.className = 'item';
    item.id = 'shop_' + i;
    return item;
}

HOTPEPPER.createMarker = function(i, j) {
    this.marker[i] = new GMarker(new GLatLng(this.shopInfo.Shop[i].Latitude, this.shopInfo.Shop[i].Longitude), this.pointIcon[j]);
    GEvent.addListener(this.marker[i], "click", function() {
        var target = $("shop_" + i);
        HOTPEPPER.openInfoWindow(i, target);
    });
}

HOTPEPPER.page = function(num) {
    for (var i = 0; i < 5; i++) {
        if (i == num) {
            $('tab_' + i).style.fontWeight = 'bold';
            $('list_' + i).style.display = 'block';
        } else {
            $('tab_' + i).style.fontWeight = '';
            $('list_' + i).style.display = 'none';
        }
    }
    var j = 0;
}

HOTPEPPER.previous = function() {
    this.map.clearOverlays();
    this.preTarget = undefined;
    this.start -= 100;
    this.requestHotpepper(this.centerInfo);
}

HOTPEPPER.next = function() {
    this.map.clearOverlays();
    this.preTarget = undefined;
    this.start += 100;
    this.requestHotpepper(this.centerInfo);
}

HOTPEPPER.xmlToJson = function(url, callback) {
    this.appendScript('http://api.fkoji.com/xml_to_json.php?url=' + encodeURIComponent(url) + '&callback=' + callback);
}

HOTPEPPER.appendScript = function(url) {
    var script = document.createElement("script");
    script.src = url;
    script.type = 'text/javascript';
    script.charset = 'UTF-8';
    document.lastChild.appendChild(script);
}

HOTPEPPER.openInfoWindowUp = function() {
    if (!HOTPEPPER.preTarget) {
        for (var i = 0; i < 5; i++) {
            if ($("list_" + i).style.display == "block") {
                var id = i * 20;
                HOTPEPPER.openInfoWindow(id, $("shop_" + id));
                break;
            }
        }
    } else {
        HOTPEPPER.preTarget.id.match(/^shop_([0-9]+)$/);
        var id = RegExp.$1 - 1;
        if (id >= 0) {
            HOTPEPPER.openInfoWindow(id, $("shop_" + id));
        }
    }
}

HOTPEPPER.openInfoWindowDown = function() {
    if (!HOTPEPPER.preTarget) {
        for (var i = 0; i < 5; i++) {
            if ($("list_" + i).style.display == "block") {
                var id = i * 20;
                HOTPEPPER.openInfoWindow(id, $("shop_" + id));
                break;
            }
        }
    } else {
        HOTPEPPER.preTarget.id.match(/^shop_([0-9]+)$/);
        var id = RegExp.$1 * 1 + 1;
        if ($("shop_" + id)) {
            HOTPEPPER.openInfoWindow(id, $("shop_" + id));
        }
    }
}

HOTPEPPER.openInfoWindow = function(id, target) {
    if (HOTPEPPER.preTarget == target) {
        HOTPEPPER.close();
        return;
    }
    var i = id;
    var shop = (HOTPEPPER.shopInfo.Shop.length) ? HOTPEPPER.shopInfo.Shop[i] : HOTPEPPER.shopInfo.Shop;

    var title = document.createElement("div");
    title.className = 'detail-title';
    var a = document.createElement("a");
    var vc_url = 'http://www.hotpepper.jp/A_20100/str' + shop.ShopIdFront + '.html';
    a.href = 'http://ck.jp.ap.valuecommerce.com/servlet/referral?sid=2348214&pid=875020768&vc_url=' + encodeURIComponent(vc_url);
    a.target = '_blank';
    a.title = 'ホットペッパーのページへ';
    a.appendChild(document.createTextNode(target.firstChild.nodeValue));
    title.appendChild(a);

    var shopCatch = document.createElement("div");
    shopCatch.appendChild(document.createTextNode(shop.ShopCatch));

    var img = document.createElement("img");
    img.src = shop.PictureUrl.PcMiddleImg;
    img.border = 0;
    var img_link = document.createElement("a");
    img_link.href = a.href;
    img_link.target = '_blank';
    img_link.title = target.firstChild.nodeValue;
    img_link.appendChild(img);

    var img_af = document.createElement("img");
    img_af.src = 'http://ad.jp.ap.valuecommerce.com/servlet/gifbanner?sid=2348214&pid=87502076';
    img_af.height = '1';
    img_af.width = '1';
    img_af.border = '0';

    var qr = document.createElement("img");
    qr.src = shop.KtaiQRUrl;
    qr.width = '120';
    qr.height = '120';

    var div = document.createElement("div");
    div.appendChild(document.createTextNode("写真提供：ホットペッパー.jp"));

    var thisUrl = document.createElement("div");
    var thisUrlLink = document.createElement("a");
    thisUrlLink.href = 'http://map.fkoji.com/hotpepper/' + shop.ShopIdFront;
    thisUrlLink.target = '_blank';
    thisUrlLink.appendChild(document.createTextNode("this page URL"));
    thisUrl.appendChild(thisUrlLink);

    var close = document.createElement("div");
    close.appendChild(document.createTextNode("[close]"));
    close.className = 'close';

    HOTPEPPER.infoElement.innerHTML = '';
    HOTPEPPER.infoElement.appendChild(title);
    HOTPEPPER.infoElement.appendChild(shopCatch);
    HOTPEPPER.infoElement.appendChild(img_link);
    HOTPEPPER.infoElement.appendChild(qr);
    HOTPEPPER.infoElement.appendChild(div);
    HOTPEPPER.infoElement.appendChild(thisUrl);
    if (HOTPEPPER.preTarget != undefined) {
        HOTPEPPER.preTarget.style.fontWeight = '';
    }
    target.style.fontWeight = 'bold';
    HOTPEPPER.preTarget = target;
    HOTPEPPER.allowGetAddress = false;
    HOTPEPPER.changeDisplay(i);
    HOTPEPPER.marker[i].openInfoWindow(HOTPEPPER.infoElement);
}

HOTPEPPER.changeDisplay = function(id) {
    var num = Math.floor(id / 20);
    for (var i = 0; i < 5; i++) {
        if (i == num) {
            $('tab_' + i).style.fontWeight = 'bold';
            $('list_' + i).style.display = 'block';
        } else {
            $('tab_' + i).style.fontWeight = '';
            $('list_' + i).style.display = 'none';
        }
    }
}

HOTPEPPER.clickObserver = function(event) {
    event = event || window.event;
    var target = event.target || event.srcElement;
    if (target.id.match(/^(shop|shopimage)_([0-9]+)$/)) {
        var pre = RegExp.$1;
        var num = RegExp.$2;
        if (pre == "shop") {
            HOTPEPPER.openInfoWindow(num, target);
        }
        else if (pre == "shopimage") {
            HOTPEPPER.openInfoWindow(num, $("shop_" + num));
        }
    }
    else if (target.className == 'close') {
        HOTPEPPER.close();
    }
}

HOTPEPPER.search = function(q) {
    HOTPEPPER.allowGetAddress = true;
    this.geocoder.getLatLng(q, function(point) {
        if (point) {
            HOTPEPPER.map.setCenter(point);
        }
    });
    return false;
}

HOTPEPPER.close = function() {
    HOTPEPPER.map.closeInfoWindow();
    HOTPEPPER.preTarget.style.fontWeight = '';
    HOTPEPPER.preTarget = undefined;
}

HOTPEPPER.keyHandler = function(type, args, obj) {
    var keycode = args[0];
    // 38 ↑
    // 40 ↓
    // 37 ←
    // 39 →
    if (keycode == 38) {
        HOTPEPPER.openInfoWindowUp();
    }
    if (keycode == 40) {
        HOTPEPPER.openInfoWindowDown();
    }
}

window.onload = function() {
    document.getElementsByTagName("html")[0].onclick = HOTPEPPER.clickObserver;
    HOTPEPPER.onload();
    var yKey = new YAHOO.util.KeyListener(document, {keys: [38, 40]}, {fn: HOTPEPPER.keyHandler});
    yKey.enable();
}


