var map, UI_PROJ, OL_PROJ, central_point;
var point_layer, all_points, default_category, selected_categories, current_popup;

function load_json() {
  OpenLayers.loadURL(CONTEXT_ABSOLUTE_URL+"/feed.json" + MAP_EXTRA_OPTIONS.request, "?", null, onJsonLoad);
}

function load_json_qs(qs) {
  OpenLayers.loadURL(CONTEXT_ABSOLUTE_URL+"/feed.json", qs, null, onJsonLoad);
}

function onJsonLoad(req) {
  parseDataJson(req);
  prepare_features(point_layer);
  fill_layer_categories(selected_categories);
  //fill_layer_category(default_category);
}

function parseDataJson(req) {
  var g =  new OpenLayers.Format.JSON();
    
  json_data = g.read(req.responseText);
  features = json_data.features;
  default_category = json_data.default_category;
  selected_categories = json_data.selected_categories;
  all_points = new Array();

  for(var feat in features) {
      var ll = new OpenLayers.LonLat(features[feat].geometry.x, features[feat].geometry.y);
      ll.transform(UI_PROJ, OL_PROJ);
      features[feat].ll = ll;
      features[feat].icon = new OpenLayers.Icon(features[feat].marker_url,
                                 new OpenLayers.Size(features[feat].marker_width, features[feat].marker_height),
                                 new OpenLayers.Pixel(-features[feat].marker_hotspotx, -features[feat].marker_hotspoty));
      all_points.push(features[feat]);
  }
}

function hide_current_popup(feature) {
  if (current_popup != undefined) {
    current_popup.hide();
  }
}

function toggle_popup(feature) {
  if (feature.popup === null) {
    feature.popup = feature.createPopup(feature.closeBox);
    map.addPopup(feature.popup);
    feature.popup.show();
  } else {
    feature.popup.toggle();
  }
  current_popup = feature.popup;
}


function prepare_features(lr) {
  var AutoSizeFramedCloud, padding, minsize;

  AutoSizeFramedCloud = new OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
      'autoSize': true, 'minSize': new OpenLayers.Size(280,200), 'padding': new OpenLayers.Bounds(10, 10, 10, 10)});

  for(var feat in features) {
    var feature = new OpenLayers.Feature(lr, all_points[feat].ll); 
    feature.closeBox = true;
    feature.popupClass = AutoSizeFramedCloud;
    feature.data.popupContentHTML = all_points[feat].popup_html;
    feature.data.overflow = "hidden";
    feature.data.icon = all_points[feat].icon;

    var marker = feature.createMarker();

    var markerClick = function (evt) {
      // this is a OpenLayers.Feature
      hide_current_popup();
      toggle_popup(this);
      // this brings the marker to front
      point_layer.removeMarker(this.marker);
      point_layer.addMarker(this.marker);
      OpenLayers.Event.stop(evt);
    };
    marker.events.register("mousedown", feature, markerClick);

    all_points[feat].feature = feature;
    all_points[feat].marker = feature.marker;
  }
}

function dct(a) {
  var o = {};
  for(var i=0;i<a.length;i++) {o[a[i]]='';}
  return o;
}

function array_intersects_dict(a, d) {
  for(var i=0; i < a.length; i++) {
    if (a[i] in d) {
      return true;
    }
  }
  return false;
}


function fill_layer_categories(categories) {
  var cnt;
  hide_current_popup();
  point_layer.clearMarkers();
  cnt = 0;
  categories_dict = dct(categories);
  for (var feat=0; feat<all_points.length; feat++) {
    if (array_intersects_dict(all_points[feat].subject, categories_dict)) {
      point_layer.addMarker(all_points[feat].marker);
      cnt += 1;
    }
  }
  jQuery("div.olLayerDiv > div > img").addClass("map_marker");
  jQuery("#gallerycategories button").removeClass("selected");
  for(var i=0; i < categories.length; i++) {
    jQuery("#pointcategory" + categories[i]).addClass("selected");
  }

  if (cnt >= 1) {
      map.zoomToExtent(point_layer.getDataExtent());
      if (map.getZoom() > map.getZoomForResolution(RESOLUTION)) {
        map.zoomTo(map.getZoomForResolution(RESOLUTION));
      }
    }
  else {
    map.setCenter(central_point.clone(), map.getZoomForResolution(RESOLUTION));
  }
}

function toggle_category(category) {
  var new_categories = [];
  var removed = false;
  for(var i=0; i < selected_categories.length; i++) {
    if (category === selected_categories[i]) {
      jQuery("#pointcategory" + category).removeClass("selected");
      removed = true;
    } else {
      new_categories.push(selected_categories[i]);
    }
  }
  if (!removed) {
    jQuery("#pointcategory" + category).addClass("selected");
    new_categories.push(category);
  }
  selected_categories = new_categories;
  fill_layer_categories(selected_categories);
}


function fill_layer_category(category) {
  var cnt;
  hide_current_popup();
  point_layer.clearMarkers();

  cnt = 0;
  for (var feat=0; feat<all_points.length; feat++) {
    if (category in dct(all_points[feat].subject)) {
      point_layer.addMarker(all_points[feat].marker);
      cnt += 1;
    }
  }
  jQuery("div.olLayerDiv > div > img").addClass("map_marker");
  jQuery("#gallerycategories button").removeClass("selected");
  jQuery("#pointcategory" + category).addClass("selected");

  if (cnt >= 1) {
      map.zoomToExtent(point_layer.getDataExtent());
      if (map.getZoom() > map.getZoomForResolution(RESOLUTION)) {
        map.zoomTo(map.getZoomForResolution(RESOLUTION));
      }
    }
  else {
    map.setCenter(central_point.clone(), map.getZoomForResolution(RESOLUTION));
  }
}


function highlight_marker(marker_id) {
  var mrk = all_points[marker_id].marker;
  hide_current_popup();
  point_layer.removeMarker(mrk);
  map.setCenter(mrk.lonlat);
  point_layer.addMarker(mrk);
  toggle_popup(all_points[marker_id].feature);
}

function map_init() {
  central_point = new OpenLayers.LonLat(CENTRAL_X, CENTRAL_Y);

  vendor_map_init();

  central_point.transform(UI_PROJ, OL_PROJ);

  if (BASE_LAYER && base_layers[BASE_LAYER]) {
    map.setBaseLayer(base_layers[BASE_LAYER]);
  }

  fix_calendar_view(jQuery);

  navigation = new OpenLayers.Control.Navigation();
  map.addControl(navigation);
  navigation.disableZoomWheel();
  map.addControl(new OpenLayers.Control.MousePosition());
  panzoombar = new OpenLayers.Control.PanZoomBar();
  panzoombar.zoomStopWidth = 18;
  panzoombar.zoomStopHeight = 5;
  map.addControl(panzoombar);

  map.addControl(new OpenLayers.Control.LayerSwitcher());

  point_layer = new OpenLayers.Layer.Markers("Markers");

  map.setCenter(central_point.clone(), map.getZoomForResolution(RESOLUTION));

  load_json();

  map.addLayer(point_layer);

}

function fix_calendar_view($) {
  var old_action = $("dl#portlet-assortedevent form").attr("action");

  if (old_action !== undefined) {
    $("dl#portlet-assortedevent form").attr('action', old_action + "/@@map-aggregated-view");
    $("dl#portlet-assortedevent-calendar .portletItem a[href^=" + old_action + "]").each(function(index) {
        var new_href = $(this).attr("href").replace(old_action, old_action + "/@@map-aggregated-view");
        $(this).attr("href", new_href);
      });

    $("dl#portlet-assortedevent form").attr('method', "get");
    $("div.content p.documentDescription").after('<div id="aggregated-map-back-link"><a href="' + old_action + '">' + BACK_TO_CALENDAR + '</a></div>');
  }
}
