var sorted = [];
var applyTag = function( gMapLocations ) {
    queryString = jQuery.parseQuery();
    if ( queryString.tag ) {
        jQuery('#racecar').val(queryString.tag);
        filterLocations( queryString.tag, gMapLocations );
    }
}

window.addEvent("domready",function(){
    $j = jQuery.noConflict();

    /* This variable is used to store the user's location so that when they
     * update their location we can remove the existing marker and place
     * another.
     */
    var userLocationMarker = null;
    var queryString;

    var plotLocation = function( locationRequest ) {

        /* Try to get a google object for the user location,
         * if we get one, plot it and sort etc.
         */
        var clientGeocoder = new GClientGeocoder();
        clientGeocoder.getLatLng(locationRequest,function( point ) {

            if ( point ) {
                if ( userLocationMarker ) {
                    userLocationMarker.remove();
                }
                
                var gMapIcon = new GIcon(new GIcon(G_DEFAULT_ICON));
                    gMapIcon.iconSize         = new GSize(32, 32);
                    gMapIcon.iconAnchor       = new GPoint(0, 32);
                    gMapIcon.infoWindowAnchor = new GPoint(19, 5);
                    gMapIcon.image            = "http://gMaps.google.com/gMapfiles/ms/micons/blue-pushpin.png";
                var marker  = new GMarker(point, { icon:gMapIcon });
                userLocationMarker = marker;

                GEvent.addListener(marker, "click", function() {
                    marker.openInfoWindowHtml( '<h2>' + locationRequest + '<h2>');
                });

                gMap.addOverlay( marker );
                bounds.extend( point );

				//changed the old way that zoomed as far out as necessary to show all points, to zooming in on the metro area around the user entered zipcode
                //gMap.setZoom( gMap.getBoundsZoomLevel(bounds) );
                //gMap.setCenter( bounds.getCenter() );

				gMap.setZoom( 11 );
				gMap.setCenter( point );

                // calculate distance of all locations to this point
                gMapLocations.each(function(item,i){
                    // miles = 1609.344 meters per mile
                    item.distanceToLocation = Math.round(point.distanceFrom(
                        new GLatLng( item.latitude, item.longitude ) )/1609.344
                    );
                });

                /* Copy the locations to another array so that I can freely
                 * sort and manipulate it. This shouldn't be necessary.
                 */
                var newLocations = gMapLocations.slice();
                newLocations.sort(function(a,b){
                    if ( a.distanceToLocation > b.distanceToLocation ) {
                        return 1;
                    }
                    if ( a.distanceToLocation < b.distanceToLocation ) {
                        return -1;
                    }
                    if ( a.distanceToLocation = b.distanceToLocation ) {
                        return 0;
                    }
                });
                sorted = [];
                // Copy the items that we want
                newLocations.each(function(item, i){
                    sorted.push( $j( '.'+item.filterClass ).clone() );
                });
console.log(sorted.length);
                // empty our container
                /* Unfortunately this is a hard-coded CSS id, it is strongly
                 * coupled to the ID in FIRSTBase and would ideally be
                 * dynamically generated.
                 */
                $j('#locList').empty();

                // add back each item that we copied to the container we emptied.
                sorted.each(function(item, i){console.log(item);
                    $j('#locList').append( item );
                });
				console.log(sorted.length);
            }
            else {
                /* What happens when the location that the user enters does
                 * not correlate to a position in Google's gMap data?
                 */
            }
        });
    } // end plotLocation


    // Change the user with JS using form elements on the page.
    if ( $j("#changeLocation") ) {
        $j('#changeLocation').click(function(){
            plotLocation( $j('#userLocation').attr('value') );
            return false;
        });
    }

    // Requires jquery.parsequery.min.js
    // http://plugins.jquery.com/project/parseQuery
    if ( typeof $j.parseQuery == 'function' ) {
        queryString = $j.parseQuery();

        // Query string locations.
        if ( queryString.loc ) {
            plotLocation( queryString.loc );
        }

        // This is getting called too early, not enough time to implement correctly.
        setTimeout("applyTag( gMapLocations );", 2000);
    }

});