var map, UI_PROJ, OL_PROJ, central_point;
var point_layer, all_points, current_popup;
var $map_placeholder;
var map_highlight_items=false;

function load_data() {
  all_points = parseDataDOM(jQuery);
  prepare_layer(all_points);
}

function map_marker_config($, elemid) {
  var $el = $(elemid);
  var values = $el.attr("alt").split(" ");
  return {
    'url': $el.attr("src"),
    'w': parseInt(values[0], 10),
    'h': parseInt(values[1], 10),
    'hotx': parseInt(values[2], 10),
    'hoty': parseInt(values[3], 10)
  };
}

function parseDataDOM($) {
  var ll, marker_config;
  marker_config = map_marker_config(jQuery, "#map-marker");
  var icon_size = new OpenLayers.Size(marker_config.w, marker_config.h);
  var icon_hot = new OpenLayers.Pixel(marker_config.hotx, marker_config.hoty);
  for (var i=0; i < all_points.length; i++) {
    point = all_points[i];
    ll = new OpenLayers.LonLat(point.lon, point.lat);
    ll.transform(UI_PROJ, OL_PROJ);
    point.ll = ll;
    point.icon = new OpenLayers.Icon(marker_config.url, icon_size, icon_hot);
  }
  return all_points;
}

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


function create_popup(feature, closeBoxCallback) {
  if (feature.lonlat != null) {
    var id = feature.id + "_popup";
    var anchor = (feature.marker) ? feature.marker.icon : null;

    if (!feature.popup) {
      feature.popup = new feature.popupClass(id, 
                                             feature.lonlat,
                                             feature.data.popupSize,
                                             feature.data.popupContentHTML,
                                             anchor,
                                             feature.closeBox,
                                             closeBoxCallback);
    }
    if (feature.data.overflow != null) {
      feature.popup.contentDiv.style.overflow = feature.data.overflow;
    }
    //feature.popup.feature = feature;
  }
  return feature.popup;
}

function toggle_popup(feature) {
  var $thumbnail, call_url, featureid;
  if (feature.popup === null) {
    feature.popup = create_popup(feature,
                                 function(e) {
                                   this.hide();
                                   update_event_items(jQuery);
                                   OpenLayers.Event.stop(e);
                                 });
 
    map.addPopup(feature.popup);
    feature.popup.show();

    $thumbnail = jQuery(feature.popup.contentDiv).find("a.insertThumbnail");
    call_url = $thumbnail.attr('href');

    if (call_url !== undefined) {
      jQuery.ajax({
        url: call_url,
            success: function(response){
            var loadedheader = response.replace(/<script(.|\s)*?\/script>/g, "");
            $thumbnail.replaceWith(loadedheader);
          }
        });
    }


  } else {
    feature.popup.toggle();
  }
  current_popup = feature.popup;
  update_event_items(jQuery);
}

function prepare_layer(all_points) {
  var AutoSizeFramedCloud, padding, minsize, popup_html, feat;
  var marker, feature, markerClick, point;

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

  for(feat=0; feat < all_points.length; feat++) {
    point = all_points[feat];
    feature = new OpenLayers.Feature(point_layer, point.ll); 
    feature.closeBox = true;
    feature.popupClass = AutoSizeFramedCloud;
    popup_html = point.popup_html;
    feature.data.popupContentHTML = popup_html;
    if (!point.scroll) {
       feature.data.overflow = "hidden";
    }
    feature.data.icon = point.icon;

    marker = feature.createMarker();

    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);

    point.feature = feature;
    point.marker = feature.marker;
    point_layer.addMarker(all_points[feat].marker);
  }

  jQuery("div.olLayerDiv > div > img").addClass("map_marker");
  if (all_points.length >= 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 do_init_map() {
    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]);
    }

    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");

    load_data();

    map.addLayer(point_layer);    

}

function map_init() {
  var $show = jQuery("#mapControlShow");
  var $hide = jQuery("#mapControlHide");
  $map_placeholder = jQuery("#map-placeholder");
  do_init_map();
  $hide.click(hide_map);
  $("#assortedevent-list .mapControlShowOnMap").click(open_on_the_map).show();
  if ($map_placeholder.hasClass("map_open")) {
    $show.click(show_map);
    $hide.show();
  } else {
    $show.click(first_show_map);
    $show.show();
  }
}

function show_map(e) {
  $map_placeholder.css("display", "block");
  jQuery("#mapControlShow").hide();
  jQuery("#mapControlHide").show();
  update_event_items(jQuery);
}

function hide_map(e) {
  $map_placeholder.css("display", "none");
  jQuery("#mapControlHide").hide();
  jQuery("#mapControlShow").show();
  unhighlight_items(jQuery);
}

function first_show_map(e) {
  $map_placeholder.css("left", "");
  $map_placeholder.css("position", "");
  jQuery("#mapControlShow").hide();
  jQuery("#mapControlShow").click(show_map);
  jQuery("#mapControlHide").show();
}

function unhighlight_items($) {
  if (map_highlight_items) {
    $("#assortedevent-list li.unhighlightedEvent").removeClass("unhighlightedEvent");
  }
}

function highlight_items($, klass) {
  if (map_highlight_items) {
    $("#assortedevent-list li.unhighlightedEvent").removeClass("unhighlightedEvent");
    $("#assortedevent-list li:not(." + klass + ")").addClass("unhighlightedEvent");
  }
}

function update_event_items($) {
  var featureid;
  if (map_highlight_items) {
    if (current_popup != undefined) {
      if (current_popup.visible()) {
        featureid = $(current_popup.contentDiv).children().attr('id');
        highlight_items($, featureid);
      } else {
        unhighlight_items($);
      }
    }
  }
}

function open_on_the_map(e) {
  var classes = jQuery(this).parent().attr('class');
  var featureid = classes.match(/featureid[0123456789]+/);
  var $show_button = jQuery("#mapControlShow");

  if ($show_button.is(":visible")) {
    $show_button.click();
  }

  if (featureid !== null) {
    featureid = parseInt(featureid[0].substring(9), 10);
    highlight_marker(featureid);
  }

  window.scrollTo(0, 0);
  return false;
}

