function alphanumlots(a, b) {
  function chunkify(t) {
    var tz = [], x = 0, y = -1, n = 0, i, j;

    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        tz[++y] = "";
        n = m;
      }
      tz[y] += j;
    }
    return tz;
  }

  var aa = chunkify(a.name);
  var bb = chunkify(b.name);

  for (x = 0; aa[x] && bb[x]; x++) {
    if (aa[x] !== bb[x]) {
      var c = Number(aa[x]), d = Number(bb[x]);
      if (c == aa[x] && d == bb[x]) {
        return c - d;
      } else return (aa[x] > bb[x]) ? 1 : -1;
    }
  }
  return aa.length - bb.length;
}

function CustomGetTileUrl(a,b){
        var base = iconbaseurl + 'tile/';
		if ( b == 14 && a.x >= 2624 && a.x <= 2626 && a.y >= 5718 && a.y <= 5719 ){
				return base + b + "_" + a.x + "_" + a.y + ".png"; // replace that with a "real" URL
		}
		if ( b == 15 && a.x >= 5249 && a.x <= 5252 && a.y >= 11436 && a.y <= 11438 ){
				return base + b + "_" + a.x + "_" + a.y + ".png"; // replace that with a "real" URL
		}
		if ( b == 16 && a.x >= 10499 && a.x <= 10505 && a.y >= 22872 && a.y <= 22877 ){
				return base + b + "_" + a.x + "_" + a.y + ".png"; // replace that with a "real" URL
		}
		if ( b == 17 && a.x >= 20999 && a.x <= 21011 && a.y >= 45745 && a.y <= 45754 ){
				return base + b + "_" + a.x + "_" + a.y + ".png"; // replace that with a "real" URL
		}
		return G_SATELLITE_MAP.getTileLayers()[0].getTileUrl(a,b);
}

var map;
var side_bar_html = "";
var bluemarker;
var locs;
var iconbaseurl;

var attribs = ["ID_NUMBER", "LAT", "LONG", "COVER", "PERCENT_UTILIZATION_08", "CAPACITY", "BUILDING", "RACK_TYPE", "NUM_RACKS", "ACTUAL_CAPACITY_PER_RACK_AT_SITE", "ACTUAL_CAPACITY_AT_SITE", "NUM_BIKES_AT_SITE", "NOTES", "CAMPUS_AREA", "PG", "SURFACE"];
var columns = ["id", "lat", "lng", "cover", "percent_utilization_08", "capacity", "building", "rack_type", "num_racks", "actual_capacity", "actual_capacity_total", "num_bikes_at_site", "notes", "campus_area", "pg", "surface"];
var publicAttribs = ["COVER", "PERCENT_UTILIZATION_08", "CAPACITY", "BUILDING", "RACK_TYPE", "NUM_RACKS", "ACTUAL_CAPACITY_AT_SITE", "CAMPUS_AREA", "SURFACE"];
var publicAttribValues = ["Covered", "Percentage usage in 2008", "Rack Capacity", "Building", "Rack Type", "Number of Racks", "Total Capacity", "Campus Area", "Surface"];

$(document).ready(function() {

    var center = new GLatLng(47.653825382654695, -122.30782985687256);
    iconbaseurl = Drupal.settings.rackModulePath + '/images/';

    if (GBrowserIsCompatible()) {
        var preload_image = new Image();
        preload_image.src = iconbaseurl + "lding.gif";
        var GMapTypeOptions = {
            minResolution: 14,
            maxResolution: 17,
            errorMessage: "No map data available"
        };
        map = new GMap2(document.getElementById("map"), GMapTypeOptions);
        var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(47.646516, -122.322673), new GLatLng(47.663623, -122.289883)), 4, "Commuter Services");
        var copyCollection = new GCopyrightCollection('UW');
        copyCollection.addCopyright(copyright);
        
        // Setup the tile layers
        var tilelayers = new Array();
        tilelayers[0] = G_SATELLITE_MAP.getTileLayers()[0];
        tilelayers[1] = new GTileLayer(copyCollection, 14, 17);
        tilelayers[1].getTileUrl = CustomGetTileUrl;
        tilelayers[1].isPng = function() {return true;};
        tilelayers[1].getOpacity = function () {return 0.9;};//of the non transparent part

        // Create our custom map layer
 //       var custommap = new GMapType(tilelayers, new GMercatorProjection(20), "Campus", GMapTypeOptions);
 //       custommap.getTextColor = function() {return "#000000";};
    
 //       map.addMapType(custommap);
 //       map.setMapType(custommap);
        map.setCenter(new GLatLng(47.654230094973265, -122.30604158172607), 15);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.enableScrollWheelZoom();
        loadxml();
    }
});

var lotArray;

function loadxml() {
    var gatehouses = new GGeoXml("http://www.washington.edu/facilities/transportation/commuterservices/files/gatehouses.kml");
    map.addOverlay(gatehouses);

    lotArray = [];
    var id = 0;

    var selectbox = $('<select></select>').bind('change', function(opt) {
        var lot = lotArray[this.selectedIndex];
        map.openInfoWindow(lot.coords[0], '<h1>'+lot.name+'</h1>'+lot.descr);
    });
    $('#lotlist').append(selectbox);

    $.ajax({
        type: "GET",
        url: Drupal.settings.basePath + 'files/parkinglots.xml',
        dataType: "xml",
        success: function(xml) {
            $(xml).find('Placemark').each(function() {
                var thisId = id;
                var name = $(this).find('name').text();
                var descr = $(this).find('description').text().replace(/\n/g, "<br/>");
                
                var coord_array = $(this).find('coordinates').text().split(' ');
                var coord_array_parsed = [];
                for (var i = 0; i < coord_array.length-1; i++) {
                    var coords = coord_array[i].split(',');
                    coord_array_parsed.push(new GLatLng(coords[1], coords[0]));
                }
                coord_array_parsed.push(coord_array_parsed[0]);
                var polygon = new GPolygon(coord_array_parsed, "#39275B", 2, 1, "#39275B", 0.2);
                map.addOverlay(polygon);

                lotArray.push({ 'id':thisId, 'name':name, 'coords':coord_array_parsed, 'polygon':polygon, 'descr':descr });

                GEvent.addListener(polygon, "click", function(point) {
                    map.openInfoWindow(point, '<h1>'+name+'</h1>'+descr);
                });

                /*var listelement = $('<li><a>'+name+'</a></li>').bind('click', function() {
                    map.openInfoWindow(coord_array_parsed[0], '<h1>'+name+'</h1>'+descr);
                });
                $('#lotlist').append(listelement);*/
                //var option = $('<option value="'+thisId+'">'+name+'</option>');
                //$('#lotlist select').append(option);
                id++;                
            });

            // sort array and add to dropdown box
            lotArray.sort(alphanumlots);

            for (var i = 0; i < lotArray.length; i++) {
                var lot = lotArray[i];
                var option = $('<option value="'+i+'">'+lot.name+'</option>');
                $('#lotlist select').append(option);
            }
        }
        /*error: function (XMLHttpRequest, textStatus, errorThrown) {
            // typically only one of textStatus or errorThrown 
            // will have info
            //this; // the options for this ajax request
        }*/

    }); //close $.ajax(
}

function renderLots() {
}

