Ext.BLANK_IMAGE_URL = '/images/default/s.gif';

window.onunload = GUnload;
var map;
var directionsPanel;
var directions;
function $(id) {
    return document.getElementById(id);
}

var newMarkers = [];
var latLngs = [];
var icons = [];
function onGDirectionsAddOverlay(){ 
    for (var i=0; i<newMarkers.length; i++){
        map.removeOverlay(newMarkers[i]);
    }
    for (var i=0; i<=directions.getNumRoutes(); i++){
        var originalMarker = directions.getMarker(i);
        latLngs[i] = originalMarker.getLatLng();
        icons[i] = originalMarker.getIcon();
        newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
        map.addOverlay(newMarkers[i]);
        GEvent.addListener(newMarkers[i], "dragend", function(){
            var points = [];
            for (var i=0; i<newMarkers.length; i++){
                points[i]= newMarkers[i].getLatLng();
            }
            directions.loadFromWaypoints(points);
        });
        copyClick(newMarkers[i],originalMarker);
        map.removeOverlay(originalMarker);
    }
    function copyClick(newMarker,oldMarker){
        GEvent.addListener(newMarker, 'click', function(){
            GEvent.trigger(oldMarker,'click');
        });
    }
}

Ext.onReady(function(){
    map = new GMap2($("map"));
    map.setCenter(new GLatLng(34.75162, 135.39308), 13);
    map.setUIToDefault();
    directionsPanel = $('route');
    directions = new GDirections(map, directionsPanel);
    GEvent.addListener(directions, 'error', function () {
        var code = directions.getStatus().code;
        if (code == G_GEO_UNKNOWN_ADDRESS)
            alert("不明な住所です。\nError code: " + code);
        else if (code == G_GEO_SERVER_ERROR)
            alert("サーバーエラーです。\n Error code: " + code);
        else if (code == G_GEO_MISSING_QUERY)
            alert("検索条件が不正です。\n Error code: " + code);
        else if (code == G_GEO_BAD_KEY)
            alert("APIキーが不正です。 \n Error code: " + code);
        else if (code == G_GEO_BAD_REQUEST)
            alert("リクエストが不正です。\n Error code: " + code);
        else alert("予期せぬエラーが発生しました。");
    });
    GEvent.addListener(directions, "addoverlay", onGDirectionsAddOverlay);

    var ds = new Ext.data.Store({
        baseParams: {
            output: 'json',
            oe: 'utf-8',
            key: 'ABQIAAAAiMcQwe74xAWj6l8Np5WFkhSX2ALbfL2Vt6Nxmuo0Kyv4WYxKrBRQoWzuBZDbbf0qzyFGQAklf3ryGQ'
        },
        proxy: new Ext.data.ScriptTagProxy({
            url: 'http://maps.google.co.jp/maps/geo'
        }),
        reader: new Ext.data.JsonReader({
            root: 'Placemark',
            id: 'id'
        }, [
            {name: 'id', mapping: 'id'},
            {name: 'address', mapping: 'address'},
            {name: 'AddressDetails', mapping: 'AddressDetails'},
            {name: 'Point', mapping: 'Point'},
            {name: 'lat', mapping: 'Point.coordinates[1]'},
            {name: 'lng', mapping: 'Point.coordinates[0]'}
        ])
    });

    var dsStation = new Ext.data.Store({
        baseParams: {
            output: 'json'
        },
        proxy: new Ext.data.ScriptTagProxy({
            url: 'http://map.simpleapi.net/stationapi'
        }),
        reader: new Ext.data.JsonReader({
            id: 'name'
        }, [
            {name: 'name', mapping: 'name'},
            {name: 'line', mapping: 'line'},
            {name: 'distanceKm', mapping: 'distanceKm'},
            {name: 'traveltime', mapping: 'traveltime'}
        ])
    });

    var grid = new Ext.grid.GridPanel({
        store: dsStation,
        title:'最寄り駅（駅を選択するとルート案内を表示します）',
        columns: [{
            id:'name',
            dataIndex: 'name',
            header: "駅名"
        },{
            id:'line',
            dataIndex: 'line',
            header: "路線"
        },{
            id:'distanceKm',
            dataIndex: 'distanceKm',
            header: "直線距離"
        },{
            id:'traveltime',
            dataIndex: 'traveltime',
            header: "直線徒歩時間"
        }],
        autoExpandColumn: 'line',
        width : 470,
        height: 200,
        stripeRows: true
    });

    grid.render("grid");

    var resultTpl = new Ext.XTemplate(
        '<tpl for="."><div class="search-item">',
            '<h3>ID:{id} 住所:{address}</h3>',
            '経度:{lng} 緯度:{lat}',
        '</div></tpl>'
    );

    var search = new Ext.form.ComboBox({
        store: ds,
        displayField:'title',
        typeAhead: false,
        loadingText: '検索中...',
        emptyText: '住所を入力してください',
        width: 470,
        hideTrigger: true,
        tpl: resultTpl,
        applyTo: 'search',
        itemSelector: 'div.search-item',
        queryParam: 'q',
        minChars: 2,
        onSelect: function(record){
            var point = new GLatLng(record.data.Point.coordinates[1],
                        record.data.Point.coordinates[0]);
            map.setCenter(point);
            map.clearOverlays();
            map.addOverlay(new GMarker(point));
            search.setValue(record.data.address);
            dsStation.load({params:{
                x:record.data.Point.coordinates[0],
                y:record.data.Point.coordinates[1]}
            });
            this.collapse();
        },
        onKeyUp : function(e){
            if(this.editable !== false && !e.isSpecialKey()){
                this.lastKey = e.getKey();
             }
        }
    });

    var timeout;
    var comboValue = '';
    
    var focusCombo = function() {
        if (comboValue != search.el.dom.value) {
            if (search.isExpanded()) {
                search.collapse();
            }
            search.onTriggerClick();
            comboValue = search.getValue();
        }
        timeout = setTimeout(focusCombo, 500);
    }

    var blurCombo = function() {
        clearTimeout(timeout);
    }

    search.on({
        'focus': focusCombo,
        'blur': blurCombo
    });

    grid.on('rowclick', function(g, i, e) {
        directions.load(
            'from: '
                + g.getStore().getAt(i).get('name')
                + ' to: '
                + search.getValue(),
            {
                locale: 'ja_JP',
                travelMode: G_TRAVEL_MODE_WALKING
            }
        );
    });

});