var prog;
var done;
function KiwamiMap(myvar) {
    prog = new Image();
    prog.src = 'images/progress.gif';
    done = new Image();
    done.src = 'images/done.gif';
    this.myvar = myvar;
    this.mapInstance = null;
    this.markerMgr = null;
    this.placemarks = null;
    this.route = null;
    this.kanko = null;
    this.accordion = null;
    this.glyph = null;
    this.message = null;
    this.markCount = 0;
}

KiwamiMap.prototype.prepare = function() {
    this.glyph = document.getElementById('glyph');
    this.message = document.getElementById('message');
    if (GBrowserIsCompatible()) {
        this.mapInstance = new GMap2(document.getElementById('canvas'));
        this.mapInstance.addControl(new GLargeMapControl());
        this.mapInstance.addControl(new GOverviewMapControl());
        this.mapInstance.setCenter(new GLatLng(37.65, 138.8), 8); //新潟県中心
        this.mapInstance.savePosition();

        GEvent.addListener(this.mapInstance, 'zoomend', this.zoomend.bind(this));

        areaLists = document.getElementById('regionlist').getElementsByTagName('ul');
        region = new Array;
        region['niigata'] = "37.916373,139.036617,11";
        region['shibata-murakami'] = "38.107547,139.522247,10";
        region['sanjo-aga'] = "37.667516,139.226990,10";
        region['nagaoka-mitsuke'] = "37.436541,138.838917,11";
        region['kashiwazaki'] = "37.376160,138.563004,11";
        region['tokamachi-yuzawa'] = "37.044217,138.912506,10";
        region['joetsu-itoigawa'] = "37.023388,138.073425,10";
        region['sado'] = "38.058905,138.383789,10";
        this.kanko = new GGeoXml(kiwamiRoot + 'map/niigatakankou.kml?' + (new Date()).getTime(), this.kankoload.bind(this));
        new Ajax.Request(kiwamiRoot + 'map/markers.php', {
            method: "get",
            onSuccess: this.onSuccess.bind(this),
            onFailure: this.onFailure.bind(this)
        });
    }
    else {
        this.progress('ご使用の環境では残念ながら地図機能をご利用頂けません。', false);
    }
}

KiwamiMap.prototype.progress = function(message, busy) {
    if (busy) {
        this.glyph.src = 'images/progress.gif';
    }
    else {
        this.glyph.src = 'images/done.gif';
    }
    if (message) this.message.innerHTML = message;
}

KiwamiMap.prototype.kankoload = function() {
    if (this.kanko.loadedCorrectly()) {
        this.mapInstance.addOverlay(this.kanko);
    }
}

KiwamiMap.prototype.zoomend = function(oldLevel, newLevel) {
    if (oldLevel >= 8 && newLevel < 8) {
        if (this.markerMgr) {
            for (var i = 0; i < this.markerMgr.gmarkers.length; i++) {
                var m = this.markerMgr.gmarkers[i];
                this.mapInstance.removeOverlay(m);
            }
        }
        if (this.kanko.loadedCorrectly()) {
            this.mapInstance.removeOverlay(this.kanko);
        }
    }
    else if (oldLevel < 8 && newLevel >= 8) {
        if (this.markerMgr) {
            for (var i = 0; i < this.markerMgr.gmarkers.length; i++) {
                var m = this.markerMgr.gmarkers[i];
                this.mapInstance.addOverlay(m);
            }
        }
        if (this.kanko.loadedCorrectly()) {
            this.mapInstance.addOverlay(this.kanko);
        }
    }
}

KiwamiMap.prototype.onSuccess = function(httpObj) {
    this.placemarks = GXml.parse(httpObj.responseText).documentElement.getElementsByTagName('Placemark');
    this.markCount = 0;
    baseicon = kiwamiCreateIcon();
    this.markerMgr = new EGeoXml(this.myvar + '.markerMgr', this.mapInstance, null, {
        sortbyname: false,
        baseicon: baseicon,
        titlestyle: 'id="iwtitle"',
        descstyle: 'id="iwdesc"',
        createmarker: this.createmarker.bind(this)
    });
    GEvent.addListener(this.markerMgr, 'parsed', this.parsed.bind(this));
    this.markerMgr.parseString(httpObj.responseText);
}

KiwamiMap.prototype.onFailure = function(httpObj) {
    this.progress('極み参加店舗一覧の取得に失敗しました。', false);
}

KiwamiMap.prototype.createmarker = function(point, name, desc, style) {
    var lid = 0;
    var areaCode = 0;
    var parlarLatitude = 0;
    var parlarLongitude = 0;
    var icLatitude = 0;
    var icLongitude = 0;
    var placemark = this.placemarks[this.markCount];
    var extendedData = placemark.getElementsByTagName("ExtendedData");
    if (extendedData.length > 0) {
        var datas = extendedData[0].getElementsByTagName("Data");
        for (var i = 0; i < datas.length; i++) {
            var data = datas[i];
            var dataName = data.getAttribute('name');
            var dataValue = data.getElementsByTagName("value")[0].firstChild.nodeValue;
            if (dataName == 'areaCode') {
                areaCode = dataValue;
            }
            else if (dataName == 'lid') {
                lid = dataValue;
            }
        }
    }
    if (areaCode > 0) {
        areaLists[areaCode - 1].innerHTML += '<li>' + '<a href="javascript:GEvent.trigger(' + this.myvar + '.markerMgr.gmarkers[' + this.markCount + '], \'click\');/*' + this.myvar + '.mapInstance.setZoom(14);*/">' + name + '</a></li>';
    }
    if (lid > 0) {
        desc += '<div><a href="javascript:' + this.myvar + '.routeSearch(' + lid + ');">付近ICからのルートを表示</a></div>';
    }
    this.markerMgr.createMarker(point, name, desc, style);
    this.markCount++;
}

KiwamiMap.prototype.parsed = function() {
    for (i = 0; i < areaLists.length; i++) {
        if (areaLists[i].innerHTML.length == 0) {
            areaLists[i].innerHTML = '<li>（該当店舗無し）</li>';
        }
    }
    this.accordion = new KiwamiAccordion('regionlist', {
        activatefn: this.activatefn.bind(this)
    });
    if (location.search.length > 1) {
        activeTab = document.getElementById(location.search.substring(1));
        if (activeTab) this.accordion.activate(activeTab);
    }
    this.progress('極み寿司マップ初期化完了.', false);
}

KiwamiMap.prototype.activatefn = function(tab) {
    this.routeClear();
    var center = region[tab.id].split(',');
    var lat = center[0];
    var lng = center[1];
    var zoom = parseInt(center[2], 10);
    this.mapInstance.setCenter(new GLatLng(lat, lng), zoom);
    this.mapInstance.savePosition();
}

KiwamiMap.prototype.routeSearch = function(lid) {
    if (this.route) this.mapInstance.removeOverlay(this.route);
    this.route = null;
    this.progress('ルート探索中...', true);
    this.route = new GGeoXml(kiwamiRoot + 'map/route.php?lid=' + lid + '&' + (new Date()).getTime(), this.routeFound.bind(this));
}

KiwamiMap.prototype.routeFound = function() {
    if(this.route.loadedCorrectly()) {
        this.mapInstance.addOverlay(this.route);
        this.progress('ルート探索を終了しました。（<a href="javascript:void(0);" onClick="' + this.myvar + '.routeClear();">ルート消去</a>）', false);
    }
    else {
        this.route = null;
        this.progress('ルート探索に失敗しました。', false);
    }
}

KiwamiMap.prototype.routeClear = function() {
    if (this.route) {
        this.mapInstance.removeOverlay(this.route);
        this.route = null;
        this.progress('ルートを消去しました。', false);
    }
}
