var map, layer;
var eactive_key = '898cfa06a63e5ad7a427a30896cd95c2';
var vector_layer;
var urban_areas, places;
var tc_url = ['http://tilecache.beardedmaps.com/tilecache.py?'];
function init_map(){
    var options = {
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        numZoomLevels: 11,
        maxResolution: 156543.0339,
        maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
                                         20037508, 20037508.34)

    };
    map = new OpenLayers.Map('smap', options);
    
    var osm = new OpenLayers.Layer.TMS(
        "OpenStreetMap ",
        "http://b.tile.cloudmade.com/" + eactive_key + "/2050/256/",{
            type: 'png', getURL: osm_getTileURL,
            attribution: '<a href="http://www.openstreetmap.org/">OpenStreetMap</a>'
            }
        );
        
    urban_areas = new OpenLayers.Layer.WMS(
        "Urban Areas",
            tc_url, {
            map : '/projects/walkscore/mapserver/ws.map',
            layers: "urban_areas", 
            transparent: "true" },
        { isBaseLayer : false, 
          opacity : .75,
          buffer : 0,
          attribution: '<a href="http://www.umbrellaconsulting.com/">Umbrella Consulting</a>'}
        );
        
    cbsa = new OpenLayers.Layer.WMS(
        "CBSA",
        tc_url, {
        map : '/projects/walkscore/mapserver/ws.map',
        layers: "cbsa", 
        transparent: "true" },
    {isBaseLayer : false, opacity : .3, buffer:1}
    );

    places = new OpenLayers.Layer.WMS(
        "Places",
        tc_url, {
        map : '/projects/walkscore/mapserver/ws.map',
        layers: "places", 
        transparent: "true" },
    {isBaseLayer : false, opacity : .7, buffer:1}
    );
           
    //vector_layer = new OpenLayers.Layer.Vector('overlay', {styleMap:get_style()}); 

   vector_layer = new OpenLayers.Layer.Vector("Place Details", {
                    styleMap:get_style(),
                    projection: new OpenLayers.Projection("EPSG:4326")
                     })


    map.addLayers([osm, cbsa, urban_areas,  places, vector_layer]);
    map.addControl(new OpenLayers.Control.MousePosition());
    
    map.setCenter(new OpenLayers.LonLat(-98.0,39.0).transform(map.displayProjection, map.projection),4);

    map.events.register("click", map, get_census_details); 

    jQuery("#urban_areas_slider").slider({
        value: urban_areas.opacity * 100,
        slide: function(e, ui) {urban_areas.setOpacity(ui.value / 100);}
        });
    jQuery("#cbsa_slider").slider({
        value: cbsa.opacity * 100,
        slide: function(e, ui) {cbsa.setOpacity(ui.value / 100);}
        });
    jQuery("#places_slider").slider({
        value: places.opacity * 100,
        slide: function(e, ui) {places.setOpacity(ui.value / 100);}
        });
    jQuery("#urban_areas_slider").slider("moveTo", urban_areas.opacity); 
    jQuery("#cbsa_slider").slider("moveTo", cbsa.opacity); 
    jQuery("#places_slider").slider("moveTo", places.opacity); 
    
    }
    
function get_style(){    
   var style = new OpenLayers.StyleMap({
    "default": new OpenLayers.Style({
        //pointRadius: "${type}", // sized according to type attribute
        fillColor: "#006DCF",
        strokeColor: "#006DCF",
        strokeWidth: 3,
        fillOpacity : .5
        }),
    "select": new OpenLayers.Style({
        fillColor: "#66ccff",
        strokeColor: "#3399ff"
        })
    
    });return style;}
  

function get_census_details(click){
    vector_layer.destroyFeatures();
    jQuery('#sidebar_app').html('running query ... <br> may take a minute');
    ll = map.getLonLatFromPixel(click.xy).transform(map.projection, map.displayProjection);
    var geojson_format = new OpenLayers.Format.GeoJSON({
        'internalProjection': new OpenLayers.Projection("EPSG:900913"),
        'externalProjection': new OpenLayers.Projection("EPSG:4326")
        });
    jQuery.getJSON('/census_details/',
        {'lat': ll.lat, 'lon' : ll.lon},
        function(json){
           var html = ''
           //console.log(json)
              jQuery.each(json, function(i,l) {
               html += '<div class="' + l.type + '"><b>' + l.name + '</b> (' + l.lsad + ')</div><br>';
               //if (l.type == 'UrbanAreas') {vector_layer.addFeatures(geojson_format.read(l.geom));} 
               //else {console.log(i,l)}

              }); 
              jQuery('#sidebar_app').html(html);
        });
           jQuery('#sidebar')[0].style.display = 'block';
     }


function get_style(){    
   var style = new OpenLayers.StyleMap({
    "default": new OpenLayers.Style({
        pointRadius : 8,
        fillColor: "#006DCF",
        strokeColor: "#006DCF",
        strokeWidth: 3,
        fillOpacity : .2
        }),
    "select": new OpenLayers.Style({
        fillColor: "#66ccff",
        strokeColor: "#3399ff"
        })
    
    });return style;}
    
    
function osm_getTileURL(bounds) {
    var res = this.map.getResolution();
    var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
    var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
    var z = this.map.getZoom();
    var limit = Math.pow(2, z);

    if (y < 0 || y >= limit) {
        return OpenLayers.Util.getImagesLocation() + "404.png";
    } else {
        x = ((x % limit) + limit) % limit;
        var u = this.url + z + "/" + x + "/" + y + "." + this.type;
        return u;
    }
}


