var $_ = jQuery;
$_(document).ready(function(){ 
  var map, gmap, texas, select, control;
  OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
  Proj4js.defs["EPSG:3081"] = "+proj=lcc +lat_1=27.41666666666667 +lat_2=34.91666666666666 +lat_0=31.16666666666667 +lon_0=-100 +x_0=1000000 +y_0=1000000 +ellps=GRS80 +datum=NAD83 +units=m +no_defs";
  Proj4js.defs["EPSG:4269"] = "+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs";
  var options = {
      projection: new OpenLayers.Projection("EPSG:900913"),
      displayProjection: new OpenLayers.Projection("EPSG:4326"),
      units: "m",
      numZoomLevels: 18,
      maxResolution: 156543.0339,
      maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508.34),
      restrictedExtent: new OpenLayers.Bounds(-11900000,2970000,-10400000,4380000)
  };
  map = new OpenLayers.Map('map', options);
  // create Google Mercator layers
  gmap   = new OpenLayers.Layer.Google("Google Streets",{'sphericalMercator': true});
  texas  = new OpenLayers.Layer.WMS("Texas",
         "geo",
         {'layers': 'gis:county', 'format':'image/png', 'sld':'http://www.medinafortexas.com/regional.sld','transparent':'true'},
         {'opacity': 0.4, visibility: true,'isBaseLayer': false,'wrapDateLine': true}
  );
  select = new OpenLayers.Layer.Vector("Selection", {
         styleMap: new OpenLayers.Style(OpenLayers.Feature.Vector.style["select"])
  });
  var vector = new OpenLayers.Layer.Vector("Editable Vectors");

  control = new OpenLayers.Control.GetFeature({
    protocol: new OpenLayers.Protocol.WFS.fromWMSLayer(texas,{url:'wfs', srsName:'EPSG:900913'}),
    box: true,
    multipleKey: "shiftKey",
    toggleKey: "ctrlKey"
  });
  control.events.register("featureselected", this, 
    function(e) {
      select.addFeatures([e.feature]);
      $_.ajax({
        type:"GET",
        url: "jsonHelper",
        data: {'call': 'getCountyInfo', 'fips': e.feature.attributes.countyfp},
        dataType: 'json',
        success: 
          function(dat){
            $_('#countyInfo').html('<h2>'+e.feature.attributes.name+' County</h2><p>Regional Coordinator: '+dat.REGION_COORD_NAME +' </p><p>Regional Email: '+dat.REGION_COORD_EMAIL +' </p><p>Regional Phone: '+dat.REGION_COORD_PHONE +' </p><p>County Email: '+e.feature.attributes.name.toLowerCase().replace(' ', '')+'county@wetexans.com</p>');
          }
      });
    }
  );
  control.events.register("featureunselected", this, function(e) {select.removeFeatures([e.feature]);});
    map.addControl(control);
    control.activate();

  map.addLayers([gmap, texas, select]);
  map.addControl(new OpenLayers.Control.LayerSwitcher());
  map.addControl(new OpenLayers.Control.Permalink());
  map.addControl(new OpenLayers.Control.MousePosition());
  if (!map.getCenter()) {map.zoomToMaxExtent()}
});
