
var shapeMgrInitialized = false;
var shapeMgrLoadedAgency = null;
var geocoder = new GClientGeocoder();
var waypoints = new Array();

Ext.onReady(function () {



function loadShapeMgr(init) {
    waypoints = new Array();
    Map.gmap.checkResize();
    if (! init) {
        Map.gmap.clearOverlays();
    }

    if (agency && agency.data.lat && agency.data.lng) {
        Map.setMapCenter(defaultLat + ',' +  defaultLng);
    } else if (agency && agency.data.city) {
        Ext.MessageBox.alert('GeoCoding Info', 'The default map location was geocoded from "' + agency.data.city + '".  You can set the default map location in the agency manager.');
        Map.setMapCenter(agency.data.city);
    } else {
        Ext.MessageBox.alert('Warning', 'The default map location and city name are not set..');
        Map.setMapCenter('USA');
    }
    //ads = new GAdsManager(Map.gmap, 'ca-pub-7897815954291269', { channel: '0833443484', maxAdsOnMap: 10 } );
    //ads.enable();
    Map.gmap.enableGoogleBar()


    if (! init && shapeMgrLoadedAgency != yai) {
        return;
    }


    GEvent.addListener(Map.gmap, 'click', MapClickHandler); 
    GEvent.addListener(Map.gmap, 'singlerightclick', MapRightClickHandler); 
}

function countarray(a) {
    var count=0;
    for (var blah in a) {
        count++;
    }
    return(count);
}

function insertWaypoint(before, lat, lng, hidden) {
    Map.gmap.removeOverlay(waypoints[before].polyline);
    var markeropts = {
        draggable: true,
        bouncy: true,
        hide: false,
        icon: defaultIcon
    };
    if (hidden) markeropts.hide = true;
    marker = new GMarker(new GLatLng(lat, lng), markeropts);
    marker.sequence=before;
    var line = new Array(
            marker.getLatLng(),
            new GLatLng(lat, lng)
            );
    marker.polyline = new GPolyline();
    var first = waypoints.slice(0, before);
    var last = waypoints.slice(before);
    first.push(marker);
    waypoints = first.concat(last);
    waypoints = resequence(waypoints);
    waypoints[before].polyline = drawLine(waypoints[before]);
    waypoints[before+1].polyline = drawLine(waypoints[before+1]);
    GEvent.addListener(waypoints[before], 'dragend', MarkerDragHandler); 
    Map.gmap.addOverlay(waypoints[before]);
    return(marker);
}

function resequence(newwp) {
    //waypoints = new Array();
    for (ctr = 0; ctr < newwp.length; ctr++) {
        newwp[ctr] = setMarkerSequence(newwp[ctr], ctr);
    }
    return(newwp);
}

function setMarkerSequence(marker, seq) {
    marker.sequence = seq;
    if (marker.polyline) {
        marker.polyline.belongsTo = seq;
    }
    return(marker);
}

function addWaypoint(lat, lng, hidden) {
    var markeropts = {
        draggable: true,
        bouncy: true,
        hide: false,
        icon: defaultIcon
    }
    if (hidden) markeropts.hide = true;
    marker = new GMarker(new GLatLng(lat, lng), markeropts);
    marker.sequence=waypoints.length;
    marker.polyline=drawLine(marker);
    waypoints[waypoints.length] = marker;
    GEvent.addListener(waypoints[waypoints.length-1], 'dragend', MarkerDragHandler); 
    Map.gmap.addOverlay(marker);
    return(marker);
}

function removeWaypoint(marker) {
    // the last waypoint is a special case
    if (marker.sequence == waypoints.length-1) {
        Map.gmap.removeOverlay(marker);
        Map.gmap.removeOverlay(marker.polyline);
        waypoints = waypoints.slice(0, marker.sequence);
        return;
    }
    var seq = marker.sequence;
    var len = waypoints.length;
    Map.gmap.removeOverlay(marker);
    Map.gmap.removeOverlay(marker.polyline);
    Map.gmap.removeOverlay(waypoints[marker.sequence+1].polyline);
    var first = waypoints.slice(0, seq);
    var last = waypoints.slice(seq+1);
    waypoints = new Array();
    waypoints = first.concat(last);
    resequence(waypoints);
    waypoints[seq].polyline = drawLine(waypoints[seq]);
}

function drawLine(marker) {
    if (marker.sequence > 0) {
        //alert('drawing line from ' + (marker.sequence-1) + ' to ' + marker.sequence);
        line = new Array(
                waypoints[marker.sequence-1].getLatLng(),
                marker.getLatLng()
                );
        polyline = new GPolyline(line);
        polyline.belongsTo=marker.sequence;
        Map.gmap.addOverlay(polyline);
        return(polyline);
    }
    return null;
}

function moveWaypointLine(marker) {
    // can't move the previous line for the first marker
    if (marker.sequence != 0) {
        Map.gmap.removeOverlay(waypoints[marker.sequence].polyline);
        marker.polyline = drawLine(marker);
    }
    // can't move the next line for the last marker
    if (marker.sequence != waypoints.length-1) {
        Map.gmap.removeOverlay(waypoints[marker.sequence+1].polyline);
        waypoints[marker.sequence+1].polyline = drawLine(waypoints[marker.sequence+1]);
    }
}

function duplicateMarker(marker) {
    var lat = marker.getLatLng().lat();
    var lng = marker.getLatLng().lng();
    addWaypoint(lat, lng, true);
}

function MapClickHandler(overlay, latlng, overlaylatlng) { 
    if (overlay) { 
        if (overlay.belongsTo) {
            // user clicked on a line
            insertWaypoint(overlay.belongsTo, overlaylatlng.lat(), overlaylatlng.lng(), false);
        } else {
            // user clicked on a marker
            if (overlay.getLatLng) {
                duplicateMarker(overlay);
            }
        }
    } else if (latlng) {
        // user clicked on the map
        waypoint = addWaypoint(latlng.lat(), latlng.lng(), false);
    }
}

function MapRightClickHandler(xy, element, overlay) { 
    if (overlay) { 
        if (overlay.sequence == 0) {
            Ext.MessageBox.alert('Error', "Cannot remove first waypoint");
        } else if (overlay.sequence == 1 && waypoints.length == 2) {
            Ext.MessageBox.alert('Error', "Cannot remove waypoint 2 when there are only 2 waypoints");
        } else if (overlay.polyline) {
            removeWaypoint(overlay);
        }
    }
}

function MarkerDragHandler(latlng) {
    var movedIndex=-1;
    // check to see if marker 0 moved (marker 0 is special)
    latlng_marker = waypoints[0].getLatLng();
    latlng_line = waypoints[1].polyline.getVertex(0);
    if (latlng_marker.lat() != latlng_line.lat() || latlng_marker.lng() != latlng_line.lng()) {
        movedIndex=0;
    } else {
        // figure out which marker moved
        for (ctr = 1; ctr < waypoints.length; ctr++) {
            latlng_marker = waypoints[ctr].getLatLng();
            latlng_line = waypoints[ctr].polyline.getVertex(1);
            if (latlng_marker.lat() != latlng_line.lat() || latlng_marker.lng() != latlng_line.lng()) {
                movedIndex=ctr;
            }
        }
    }
    if (movedIndex != -1) {
        moveWaypointLine(waypoints[movedIndex]);
    }
}

function showMarkers() {
    for (ctr = 0; ctr < waypoints.length; ctr++) {
        waypoints[ctr].show();
    }
}

function hideMarkers() {
    for (ctr = 0; ctr < waypoints.length; ctr++) {
        waypoints[ctr].hide();
    }
}

function gotoLoc(btn, name) {
    if (name.indexOf(',') == -1) {
        name = name + ', ' + agency.data.city
    }
    Map.zoomLevel = Map.gmap.getZoom();
    var loclatlng = Map.setMapCenter(name);
    return false;
}

function clearAllMarkers(btn, blah) {
    Ext.MessageBox.confirm('Clear Markers', "You will lose any unsaved work.  Are you sure?", function(btnId) {
        if (btnId == 'yes') {
            Map.gmap.clearOverlays();
            waypoints = new Array();
        }
    });
}

function panMap(latlng) {
    if (latlng == null) {
        Ext.MessageBox.alert('Error', "Could not find any location matching " + document.getElementById("go_to_loc").value);
        return;
    }
    Map.gmap.setCenter(latlng, 16);
}

function loadRoute() {
    if (confirm("You will lose all unsaved progress if you load a route")) {
        document.loadroute.submit();
        return true;
    }
    return false;
}

function saveRoute() {
    var routename = document.getElementById("save_route_id").value;
    document.getElementById("routebox").value = "";
    var routetext = new String();
    for (ctr = 0; ctr < waypoints.length; ctr++) {
        routetext = routetext.concat(routename + "," + waypoints[ctr].getLatLng().lat() + "," + waypoints[ctr].getLatLng().lng() + "," + (ctr+1) + ",\n");
    }
    document.getElementById("routebox").value = routetext;
}

function shapeMgrInit(shapeMgrPanel) {
    if (! shapeMgrInitialized) {
        loadShapeMgr(true);
        shapeMgrInitialized = true;
    } else if (shapeMgrLoadedAgency != yai) {
        loadShapeMgr();
    }
    shapeMgrLoadedAgency = yai;
}

function getLocationBox() {
    Ext.MessageBox.prompt('Go To Location', 'Location:', gotoLoc );
}

var Map = new Ext.ux.GMapPanel({
	xtype: 'gmappanel',
	region: 'center',
	zoomLevel: 14,
	gmapType: 'map',
	mapConfOpts: [
	    'enableScrollWheelZoom',
	    'enableDoubleClickZoom',
	    'enableDragging'
	],
	mapControls: ['GLargeMapControl3D', 'GMapTypeControl'],
	mapTypes: [G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP,G_PHYSICAL_MAP],
	setCenter: {
	    geoCodeAddr: 'USA',
	    marker: {title: 'USA'}
	},
	markers: []
});

var shapeMgr = new Ext.Panel({
    layout: 'border',
    id: 'shapeMgr',
    title: 'Shape Manager',

    defaults: {
        collapsible: true,
        split: true,
        animFloat: false,
        autoHide: false,
        useSplitTips: true
    },
    items: [{
        title: 'Shape Information',
        id: 'shapeMgrStopinfo',
        region: 'south',
        floatable: false,
        height: 150,
        minSize: 75,
        maxSize: 250,
        margins: '0 0 0 0',
        cmargins: '5 0 0 0',
        html: '<div style="font-family: arial;"><p><b>Instructions:</b> <ul><li>Click the map to set a new marker.</li><li>Right click a marker to delete the waypoint.</li><li>Drag a marker to reposition</li><li>Click on a line to insert a waypoint on the line</li><li>Use the buttons above the map to clear, hide, or show markers</ul></p></div>'
    },{
        title: 'Shapes',
        id: 'shapeMgrShapelist',
        region:'west',
        floatable: false,
        margins: '0 0 0 0',
        cmargins: '5 5 0 0',
        layout: 'fit',
        width: 175,
        minSize: 100,
        maxSize: 250,
	html: 'blah west'
    },{
        id: 'shapeMgrMap',
        collapsible: false,
        tbar: new Ext.Toolbar({
                    items: [
                        { text: 'Clear Markers', handler: clearAllMarkers },
                        { xtype: 'tbseparator' },
                        { text: 'Go To Location', handler: getLocationBox },
                        { xtype: 'tbseparator' },
                        { text: 'Hide Markers', handler: hideMarkers },
                        { xtype: 'tbseparator' },
                        { text: 'Show Markers', handler: showMarkers }
                    ]
                }),
        layout: 'fit',
        region:'center',
        margins: '0 0 0 0',
        items: [Map]

    }]
});


main.tabs.add(shapeMgr);
main.tabs.shapeMgr = main.tabs.add(shapeMgr);
main.tabs.shapeMgr.on('activate', shapeMgrInit);

});
// vim: et sts=4 cindent sw=4
