
var map = null;
var mapZoomLevel = 14;
var polylineData = new Array();
var polyline = null;
var StopMapWin = null;
var routeViewerInitialized = false;
var curRoute = false;

Ext.onReady(function () {

function routeViewerInit(routeViewerPanel) {
    if (! routeViewerInitialized) {
        RouteStore.load({ params: { yai: yai } });
        routeViewerInitialized = true;
    }
}

//--------------------------------------------------------------
//  Route Grid/Reader Config
//--------------------------------------------------------------
Route = Ext.data.Record.create([
	{ name: 'id',                   mapping: 'g_route_id' },
	{ name: 'agency_id',            mapping: 'g_agency_id' },
	{ name: 'short_name',           mapping: 'g_route_short_name' },
	{ name: 'long_name',            mapping: 'g_route_long_name' },
	{ name: 'desc',                 mapping: 'g_route_desc' },
	{ name: 'type',                 mapping: 'g_route_type' },
	{ name: 'url',                  mapping: 'g_route_url' },
	{ name: 'color',                mapping: 'g_route_color' },
	{ name: 'text_color',           mapping: 'g_route_text_color' }
    ]);

var RouteReader = new Ext.data.JsonReader({ root: 'rows' }, Route);
var RouteProxy = new Ext.data.HttpProxy({ url: 'json.php', method: 'GET' });
RouteStore = new Ext.data.Store({
    proxy: RouteProxy,
    reader: RouteReader,
    baseParams: {
	task: 'getRoutes'
    }
});

var RouteGrid = new Ext.grid.GridPanel({
    store: RouteStore,
    id: 'routeGrid',
    layout: 'fit',
    columns: [
        { id: 'color', width: 25, resizable: false, sortable: false, dataIndex: 'color',
            // set the cell background color
            renderer: function(v, meta){
                meta.attr = 'style=background-color:#' + v + ';';
                return '';
            }
        },
	{ header: 'ID',        width: 50, sortable: true, dataIndex: 'id'         },
	{ header: 'Name',      width: 50, sortable: true, dataIndex: 'short_name' },
	{ header: 'Long Name', width: 75, sortable: true, dataIndex: 'long_name'  },
	{ header: 'Type',      width: 75, sortable: true, dataIndex: 'type'       }
    ],
    autoExpandColumn: 3,
    viewConfig: { autoFill: true },
    stripeRows: true,
    tbar: [{
            text:'Add',
            tooltip:'Add a new route',
            iconCls:'add'
        },'-',{
            text:'Remove',
            tooltip:'Remove the selected item',
            iconCls:'remove'
        }],
    title: 'Routes',
    height: 255,
    frame: true
});

RouteGrid.on('cellclick', function(grid, rowIndex, colIndex, e) {
        curRoute = rowIndex;
	rowRecord = grid.getStore().getAt(rowIndex).data.id;
	TripStore.reload({params: { g_route_id: rowRecord, yai: yai } });
	if (StopMapWin) {
	    StopMapWin.destroy();
	    StopMapWin = null;
	}
    });
RouteStore.on('load', function(grid, rowIndex, colIndex, e) {
    TripStore.removeAll();
    TripStopStore.removeAll();
});

//--------------------------------------------------------------
// Trip Grid/Reader Config
//--------------------------------------------------------------
var Trip = Ext.data.Record.create([
	{ name: 'route_id',         mapping: 'g_route_id' },
	{ name: 'service_id',       mapping: 'g_service_id' },
	{ name: 'id',               mapping: 'g_trip_id' },
	{ name: 'headsign',         mapping: 'g_trip_headsign' },
	{ name: 'direction',        mapping: 'g_direction_id' },
	{ name: 'block_id',         mapping: 'g_block_id' },
	{ name: 'shape_id',         mapping: 'g_shape_id' },
	{ name: 'start_time',       mapping: 'route_start_time' },
	{ name: 'end_time',         mapping: 'route_end_time' },
	{ name: 'first_stop',       mapping: 'first_stop' },
	{ name: 'stop_count',       mapping: 'stop_count' },
    ]);

var TripProxy = new Ext.data.HttpProxy({ url: 'json.php', method: 'GET' });
var TripReader  = new Ext.data.JsonReader({ root: 'rows' }, Trip);
var TripStore = new Ext.data.Store({
    proxy: TripProxy,
    reader: TripReader,
    baseParams: {
	task: 'getTripsForRoute'
    }
});


var TripGrid = new Ext.grid.GridPanel({
    layout: 'fit',
    store: TripStore,
    columns: [
	{header: 'Schedule', width: 75, sortable: true, dataIndex: 'service_id'},
	{header: 'Trip', width: 75, sortable: true, dataIndex: 'id'},
	{header: 'Stops', width: 50, sortable: true, dataIndex: 'stop_count'},
	{header: 'From', width: 150, sortable: true, dataIndex: 'headsign'},
	{header: 'Start', width: 75, sortable: true, dataIndex: 'start_time'},
	{header: 'End', width: 75, sortable: true, dataIndex: 'end_time'},
	{header: 'Direction', width: 90, sortable: true, dataIndex: 'direction'}
    ],
    autoExpandColumn: 3,
    viewConfig: { autoFill: true },
    stripeRows: true,
    loadMask: true,
    title: 'Trips',
    height: 255,
    frame: true
});
TripGrid.on('cellclick', function(grid, rowIndex, colIndex, e) {
	rowRecord = grid.getStore().getAt(rowIndex).data.id;
	TripStopStore.reload({params: { g_trip_id: rowRecord, yai: yai } });
	if (StopMapWin) {
	    StopMapWin.destroy();
	    StopMapWin = null;
	}
    });

//--------------------------------------------------------------
// Shape Reader Config
//--------------------------------------------------------------
var Shape = Ext.data.Record.create([
	{ name: 'id',                   mapping: 'g_shape_id' },
	{ name: 'trip_id',              mapping: 'g_trip_id' },
	{ name: 'lat',                  mapping: 'g_shape_pt_lat' },
	{ name: 'lng',                  mapping: 'g_shape_pt_lon' },
	{ name: 'dist_traveled',        mapping: 'g_shape_pt_sequence' },
    ]);

var ShapeProxy = new Ext.data.HttpProxy({ url: 'json.php', method: 'GET' });
var ShapeReader  = new Ext.data.JsonReader({ root: 'rows' }, Shape);
var ShapeStore = new Ext.data.Store({
    proxy: ShapeProxy,
    reader: ShapeReader,
    baseParams: {
	task: 'getShapeForTrip'
    }
});

//--------------------------------------------------------------
// Stop Grid/Reader Config
//--------------------------------------------------------------
var TripStop = Ext.data.Record.create([
	{ name: 'trip_id',              mapping: 'g_trip_id' },
	{ name: 'arrival_time',         mapping: 'g_arrival_time' },
	{ name: 'departure_time',       mapping: 'g_departure_time' },
	{ name: 'id',                   mapping: 'g_stop_id' },
	{ name: 'sequence',             sortType: 'asInt', mapping: 'g_stop_sequence' },
	{ name: 'headsign',             mapping: 'g_stop_headsign' },
	{ name: 'pickup_type',          mapping: 'g_pickup_type' },
	{ name: 'drop_off_type',        mapping: 'g_drop_off_type' },
	{ name: 'shap_dist_traveled',   mapping: 'g_shape_dist_traveled' },
	{ name: 'code',                 mapping: 'g_stop_code' },
	{ name: 'name',                 mapping: 'g_stop_name' },
	{ name: 'desc',                 mapping: 'g_stop_desc' },
	{ name: 'lat',                  mapping: 'g_stop_lat' },
	{ name: 'lng',                  mapping: 'g_stop_lon' },
	{ name: 'zone_id',              mapping: 'g_zone_id' },
	{ name: 'url',                  mapping: 'g_stop_url' },
	{ name: 'location_type',        mapping: 'g_location_type' },
	{ name: 'parent_station',       mapping: 'g_parent_station' },
    ]);

var TripStopProxy = new Ext.data.HttpProxy({ url: 'json.php', method: 'GET' });
var TripStopReader  = new Ext.data.JsonReader({ root: 'rows' }, TripStop);
var TripStopStore = new Ext.data.Store({
    proxy: TripStopProxy,
    reader: TripStopReader,
    baseParams: {
	task: 'getStopsForTrip'
    }
});

var TripStopGrid = new Ext.grid.GridPanel({
    store: TripStopStore,
    columns: [
	{header: '#', width: 50, sortable: false, dataIndex: 'sequence'},
	{header: 'ID', width: 50, sortable: false, dataIndex: 'id'},
	{header: 'Time', width: 75, sortable: false, dataIndex: 'departure_time'},
	{header: 'Name', width: 50, sortable: false, dataIndex: 'name'},
	{header: 'Lat', width: 75, sortable: false, dataIndex: 'lat'},
	{header: 'Lng', width: 75, sortable: false, dataIndex: 'lng'},
	{header: 'Station', width: 50, sortable: false, dataIndex: 'g_location_type'}
    ],
    title: 'Trip Stops',
    viewConfig: { autoFill: true },
    loadMask: true,
    autoExpandColumn: 3,
    height: 200,
    frame: true
});
TripStopGrid.on('cellclick', function(grid, rowIndex, colIndex, e) {
	var lat = grid.getStore().getAt(rowIndex).data.lat;
	var lng = grid.getStore().getAt(rowIndex).data.lng;
	var trip_id = grid.getStore().getAt(rowIndex).data.trip_id;
	if (! StopMapWin) {
	    StopMapWin = new Ext.ux.GMapWindow({
		maximizable: false,
		title: 'Stop Locator',
		mapConfOpts: [
		    'enableScrollWheelZoom',
		    'enableDoubleClickZoom',
		    'enableDragging'
		],
		mapControls: ['GLargeMapControl']
	    });
	    StopMapWin.on('close', function(win) {
		StopMapWin = null;
		});
	    StopMapWin.show();
	    map = StopMapWin.mapPanel.getMap();
	    GEvent.addListener(map, 'zoomend', function (old_zoom, new_zoom) {
		mapZoomLevel = new_zoom;
	    });
	    map.setCenter(new GLatLng(lat, lng), mapZoomLevel);
	} else {
	    map = StopMapWin.mapPanel.getMap();
	}
	// Figure out if this is a new shape
	var reloadShape = true;
	if (ShapeStore.getCount()) {
	    if (ShapeStore.data.items[0].data.trip_id == trip_id) {
		reloadShape = false;
	    }
	}
	if (reloadShape) {
	    ShapeStore.removeAll();
	    ShapeStore.reload({params: { g_trip_id: trip_id, yai: yai } });
	    ShapeStore.on('load', function(store, recs, opts) {
		    if (polyline) {
			map.removeOverlay(polyline);
		    }
		    polylineData = new Array();
		    polyline = null;
		    for (var ctr = 0; ctr < recs.length; ctr++) {
			polylineData[ctr] = new GLatLng(parseFloat(recs[ctr].data.lat), parseFloat(recs[ctr].data.lng));
                    }
                    // don't plot white lines
                    var color;
                    if (RouteStore.getAt(curRoute).data.color.toLowerCase() == 'ffffff') {
                        color = '0000cc';
                    } else {
                        color = RouteStore.getAt(curRoute).data.color;
                    }
		    polyline = new GPolyline(polylineData, '#' + color, 5, 0.75);
		    map.addOverlay(polyline);
		    });
	}
	map.clearOverlays();
	map.panTo(new GLatLng(lat, lng), mapZoomLevel);
        grid.getStore().data.each(function (stoprec) {
            var iconOptions = {};
            if (stoprec.data.lat == lat && stoprec.data.lng == lng) {
                iconOptions.width = 32;
                iconOptions.height = 32;
                iconOptions.primaryColor = "#FF0000";
            } else {
                iconOptions.width = 16;
                iconOptions.height = 16;
                iconOptions.primaryColor = "#0000FF";
            }
            iconOptions.cornerColor = "#FFFFFF";
            iconOptions.strokeColor = "#000000";
            var icon = MapIconMaker.createMarkerIcon(iconOptions);
            marker = new GMarker(new GLatLng(stoprec.data.lat, stoprec.data.lng), icon);
            map.addOverlay(marker);
        }, this);
	if (polyline) {
	    map.addOverlay(polyline);
	}
});

function routeViewerResizeHandler(com, newWidth, newHeight, rawWidth, rawHeight) {
    // Set the grid width's and location
    RouteGrid.setWidth(parseInt(main.getSize().width * 0.33)-10);
    TripGrid.setWidth(parseInt(main.getSize().width * 0.66)-10);
    TripStopGrid.setWidth(parseInt(main.getSize().width * 0.66)-10);
}


        // create a DOM element build the HTML Table for this tab pane
        //Ext.DomHelper.append(document.body, { id: 'tablePane', tag: 'div', class: 'x-hide-display' });
        //var tablePaneDom = Ext.DomHelper.append('tablePane', '<table cellspacing="10">' + '   <tr>' + '       <td>' + '           <div id="routegrid-div"></div>' + '       </td>' + '       <td>' + '           <div id="tripgrid-div"></div>' + '       </td>' + '   </tr>' + '   <tr>' + '       <td colspan=2>' + '           <div id="tripstopgrid-div"></div>' + '       </td>' + '   </tr>' + '</table>');
        // Add our tab to the main tab panel
        main.tabs.routeViewer = main.tabs.add({ id: 'routeViewer', title: 'Route Viewer', contentEl: 'tablePane' });

        // render the grids to their appropriate location
        RouteGrid.render('routegrid-div');
        TripGrid.render('tripgrid-div');
        TripStopGrid.render('tripstopgrid-div');

        // set the initial width and create a listener to resize the grids
        routeViewerResizeHandler();
        main.tabs.routeViewer.on('bodyresize', routeViewerResizeHandler);

        // initial the records
        main.tabs.routeViewer.on('activate', routeViewerInit);

});

// vim: et sts=4 cindent sw=4
