/* MWS national map support script
 *
 * Support script for adding the red box around national maps
 * and for driving the map navigation by province.
 */
 
 
 
// Add a handler to the gmaps to box out the country and zoom the map
Drupal.gmap.addHandler('gmap', function(elem) {
    var obj = this;
    obj.bind('init', function() {       
        var points = [];

        if (Drupal.countrybox) {
           // Draw the box around the country   
            points.push(new GLatLng(Drupal.countrybox.bboxnorth, Drupal.countrybox.bboxwest));
            points.push(new GLatLng(Drupal.countrybox.bboxsouth, Drupal.countrybox.bboxwest));
            points.push(new GLatLng(Drupal.countrybox.bboxsouth, Drupal.countrybox.bboxeast));
            points.push(new GLatLng(Drupal.countrybox.bboxnorth, Drupal.countrybox.bboxeast));
            points.push(new GLatLng(Drupal.countrybox.bboxnorth, Drupal.countrybox.bboxwest));
       
            obj.map.addOverlay(new GPolyline(points, "#b32317", 2));
            
            // Center and zoom the map
            Drupal.mws_national_map_adjust_view(obj.map);
        }
    });
});

// Sets the view to the full country
Drupal.mws_national_map_adjust_view = function(map) {
            // Center and zoom the map
            var national_center = new GLatLng(Drupal.countrybox.center_lat,Drupal.countrybox.center_lon);
            var bnds = new GLatLngBounds(new GLatLng(Drupal.countrybox.bboxnorth, Drupal.countrybox.bboxwest), new GLatLng(Drupal.countrybox.bboxsouth, Drupal.countrybox.bboxeast));
            var zoom = map.getBoundsZoomLevel(bnds);
            map.setCenter(national_center, zoom);
}

// Respond to a zoom-to-province request
Drupal.mws_national_view_zoom_to_box = function(latlonstr) {
    if(Drupal.gmap) {
       var map = Drupal.gmap.getMap("nationalmap").map;
       
       if(latlonstr == "full") {
          Drupal.mws_national_map_adjust_view(map);
       } else {
          var latlon = latlonstr.split("/");
          var bboxnorth = parseFloat(latlon[0]);
          var bboxwest = parseFloat(latlon[1]);
          var bboxsouth = parseFloat(latlon[2]);
          var bboxeast = parseFloat(latlon[3]); 
          var datapoints = parseInt(latlon[4]);
          var lat_center = (bboxnorth + bboxsouth)/2.0;
          var lon_center = (bboxwest + bboxeast)/2.0;
          var box_center = new GLatLng(lat_center,lon_center);
          var bnds = new GLatLngBounds(new GLatLng(bboxnorth, bboxwest), new GLatLng(bboxsouth, bboxeast));
          var zoom = Math.min(9, map.getBoundsZoomLevel(bnds));
          map.setCenter(box_center, zoom);
       }
    }
}
