var maxMarkers = 60;
var currentPage = 1;
var mapState; 
var staticFilter;

function initMap()
{
	MapAPI.disableEvents();

 	MapAPI.init("themap");
	MapAPI.setCenter(59.265881, 14.194336, 7);

    // ====== set up marker mouseover tooltip div ======
    var tooltip = document.createElement("div");
    tooltip.id = "locationlist2";

    MapAPI.theMap.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);

    tooltip.style.display="none";

	var opt = { afterUpdateElement: onLookupSelect,
			    parameters: "template=geolocations",
				indicator: "indicator" };
	var url = ajaxServerURL + "/maps.lookupLocationHTML";
	new Ajax.Autocompleter('location','locationlist2', url, opt );

	restoreMapState();
}

function showInfoLayer(html)
{
  var f = $('infolayer');
  if (f)
    {
    f.innerHTML = html;
    f.show();
    }
}

function hideInfoLayer(html)
{
  var f = $('infolayer');
  if (f)
    f.hide();
}

function onMarkerMouseOver()
{
  var geoposID = this._geopos_ID;

  MapAPI.highlightMarkerForGeoPosition(geoposID);

  showInfoLayer(this._geopos_info);

  var id = "geopos" + geoposID;

  var f = $(id);
  if (f)
    f.addClassName("hover");
}

function onMarkerMouseOut()
{
  var geoposID = this._geopos_ID;

  MapAPI.unhighlightMarkerForGeoPosition(geoposID);

  hideInfoLayer();

  var id = "geopos" + geoposID;

  var f = $(id);
  if (f)
    f.removeClassName("hover");
}

function onListMouseOver(geoposID)
{
  MapAPI.highlightMarkerForGeoPosition(geoposID);

  showInfoLayer(MapAPI.markers[geoposID]._geopos_info);

  var id = "geopos" + geoposID;
  var f = $(id);
  if (f)
    f.addClassName("hover");
}

function onListMouseOut(geoposID)
{
  MapAPI.unhighlightMarkerForGeoPosition(geoposID);
  var id = "geopos" + geoposID;

  hideInfoLayer();

  var f = $(id);
  if (f)
    f.removeClassName("hover");
}

function onFilterChange()
{
  MapAPI.closeInfoWindows();
  loadVisibleMarkers(1);
  storeMapState();
}

function onSortChange()
{
  MapAPI.closeInfoWindows();
  loadVisibleMarkers(1);
  storeMapState();
}

function onCityChange()
{

	var form = $('filterForm');
	var city = form['city'];
	
	var date = form['date'];
	
	$(date).setValue("*");
	
	var val = $(city).getValue();
	
	var zoom = 10;
if(val == "55.6090087890625,13.00059986114502")
  zoom = 12;
	var array=val.split(",");

	if (array[0] == "0")
	  MapAPI.setCenter(59.265881, 14.194336, 5);
	else
	  MapAPI.setCenter(array[0], array[1], zoom);
	
	MapAPI.closeInfoWindows();
  	loadVisibleMarkers(1);
  	storeMapState();
}

function onDateChange(){

var form = $('filterForm');
var city = form['city'];
	
	$(city).setValue("0,0");
	
	MapAPI.setCenter(59.265881, 14.194336, 5);
	
	MapAPI.closeInfoWindows();
  	loadVisibleMarkers(1);
  	storeMapState();
}

function onMapChange(x)
{
  if (!MapAPI.refreshDisabled)
    loadVisibleMarkers(1);
  MapAPI.enableMarkerRefresh();
  storeMapState();
}

function getSearchDefinition(page)
{
  var def = new Object;

var classes = ["CalendarItem"];

  var x = $("filter") ? $F("filter") : null;
  if (!x)
    {
    x = Form.getInputs("filterForm", "", "filter");
    for (var i = 0; i < x.length; i++)
      {
        if (x[i].checked)
          classes.push(x[i].value);
      }
    }
  else
    classes = [x];

  var filter;

  if (staticFilter)
     {
     filter = staticFilter;
     filter.refclass = classes.join("|");
     }
  else	 
     {
     filter = { refclass: classes.join("|") };
     }

  def.filter = filter;

  var x = $("sort") ? $F("sort") : null;
  if (!x)
    {
	x = Form.getInputs("filterForm", "", "sort");
    for (var i = 0; i < x.length; i++)
	  {
	    if (x[i].checked)
		  def.sort = x[i].value;
	  }
    }
  else
    def.sort = x;


	var form = $('filterForm');
	var date = form['date'];	
	var val = $(date).getValue();
	
	//alert(val);

     def.date = val;
     
  def.adapter  = "mapsfairtradefokus";
  def.listTemplate = "fflist";
  def.markerTemplate = "ffmapinfowindow";
  def.maxRows  = maxMarkers;
  def.skipRows = page ? ((page-1) * def.maxRows) : 0;

  def.bounds = MapAPI.getBounds();
  def.center = MapAPI.getCenter();

  return def;   
}

function lookupLocation()
{
  var location = $F('location');

  var callb = function (data,x)
    {
      if (!data)
        {
        alert("Ingen träff.");
        return;
        }

      if (!data.length)
      {
        var x = data.position.latitude;
        var y = data.position.longitude;
        onLocationSelectLatLon(x,y, buildLocationName(data));
        return;
      }

      var html = formatLocationList(data);

      $("locationlist").style.display = "block";
      $("locationlist").innerHTML = html;
    }

  asyncRpcCall("maps.lookupLocation", location, callb);
}

function onLocationSelectLatLon(x,y,name)
{
  $("locationlist").style.display = "none";

  $("location").value = "";

  //if (name)
  //  $("location").value = name;

  MapAPI.setCenter(x,y);
  storeMapState();
}

function formatLocationList(set)
{
  var html = "";

  var regions = [];
  var cities  = [];
  var streets = [];
  var other = [];

  for (var i=0; i < set.length; i++)
    {
    r = set[i];

    if (r.streetName)
      streets.push(r);
    else if (r.city)
      cities.push(r);
    else if (r.region)
      regions.push(r);
    else
      other.push(r);
    }

  if (regions.length > 0)
    {
    html += "<b>Kommuner:</b>";
    html += buildLocationList(regions);
    }

  if (cities.length > 0)
    {
    html += "<b>Städer/orter:</b>";
    html += buildLocationList(cities);
    }

  if (streets.length > 0)
    {
    html += "<b>Gator:</b>";
    html += buildLocationList(streets);
    }

  if (other.length > 0)
    {
    html += "<b>Annat:</b>";
    html += buildLocationList(other);
    }

  return html;
}


function buildLocationList(set)
{
  var html = "<ul>";

  for (var i=0; i < set.length; i++)
    {
      var y = set[i].position.longitude;
      var x = set[i].position.latitude;

      html += "<li>";
      html += "<a href='javascript:void(0)' onclick='onLocationSelectLatLon(" + x + "," + y + ",this.innerHTML)'>";
      html += buildLocationName(set[i]);
      html += "</a>";
      html += "</li>";
    }

  html += "</ul>";
  return html;
}


function buildLocationName(data)
{
  var html = [];

  if (data.streetName && data.streetNumber)
    html.push(data.streetName + " " + data.streetNumber);
  else if (data.streetName)
    html.push(data.streetName);

  if (data.city)
    html.push(data.city);

  if (data.region && data.region != data.city)
    html.push(data.region);

  if (data.location)
    html.push(data.location);

  return html.join(", ");
}


function onLookupSelect(el, li)
{
  MapAPI.setCenter(li.getAttribute("geo:lat"), li.getAttribute("geo:long"));
  storeMapState();
}

function showNext()
{
  MapAPI.closeInfoWindows();
  if (currentPage + 1 <= totalPages)
	{
	  currentPage++;
	  loadVisibleMarkers(currentPage);
	  storeMapState();
	}
}

function showPrev()
{
  MapAPI.closeInfoWindows();
  if (currentPage > 1)
	{
	  currentPage--;
	  loadVisibleMarkers(currentPage);
	  storeMapState();
	}
}

function loadVisibleMarkers(page)
{
  if (page)
	currentPage = page; 

  asyncRpcCall("maps.getPositions", getSearchDefinition(currentPage),
			   function(data) { MapAPI.log("getPositions"); showMarkers(data); MapAPI.enableEvents(); });
}

function restoreMapState(state,ts)
{
  if (!state)
	{
	  asyncRpcCall("maps.getMapState",
				   function(ms) { if (ms) restoreMapState(ms); });
    }
  else
	{
	  var myData; 

	  mapState = state;

	  MapAPI.setType(mapState.type);
	  MapAPI.setCenter(mapState.center[0], mapState.center[1], mapState.zoom);

	  if (mapState.adapter && mapState.adapter["mapsindex"])
		myData = mapState.adapter["mapsindex"];
	  else
		myData = { };

	  var page = myData.page;
	  var def  = myData.searchDef;
	  
	  if (!def)
		def = { filter: "" };

	  var refclass = def.filter.refclass;
	  if (!refclass || refclass == "" )
	    refclass = "Member";

	  var sort = def.sort;
	  if (!sort || sort == "")
	    sort = "ctime desc";

      var f = $("filter");
	  if (f && f.type == "select-one")
	    {
	    $A($("filter").options).each( function (e) { e.selected = (e.value == refclass); });
        }
	  else
        {
   	    var arr = Form.getInputs("filterForm", "", "filter");
	    arr.each( function(e) { if (e.value == refclass) e.checked = true; });
        }	

      var f = $("sort");
	  if (f && f.type == "select-one")
	    {
	    $A($("sort").options).each( function (e) { e.selected = (e.value == sort); });
        }
	  else
        {
   	    var arr = Form.getInputs("filterForm", "", "sort");
	    arr.each( function(e) { if (e.value == sort) e.checked = true; });
        }	

	  loadVisibleMarkers(page ? page : 1);
	}
}

function storeMapState(reload)
{
  if (!mapState)
	mapState = new Object;	

  if (!mapState.adapter)
	mapState.adapter = new Object;

  if (!mapState.adapter["mapsindex"])
	mapState.adapter["mapsindex"] = new Object;

  mapState.adapter["mapsindex"].searchDef = getSearchDefinition();
  mapState.adapter["mapsindex"].page = currentPage;

  mapState.center = MapAPI.getCenter();
  mapState.zoom = MapAPI.getZoom();

  mapState.type = MapAPI.getType();

  MapAPI.log("storing map state");

  if (reload)	
    asyncRpcCall("maps.storeMapState", mapState, function() { reloadPage() });
  else
    asyncRpcCall("maps.storeMapState", mapState);  
}

function showMarkers(arr)
{
  var newMarkers = new Object();
  var positions = arr.positions;
  var totalrows = arr.totalrows;
  var rows = arr.rows;
  var overflow = arr.overflow;

  totalPages = Math.ceil(totalrows / maxMarkers);

  var info;

  if (overflow)
	  {
	  info = totalrows + " st hittade<br>";

	  info += "<a href='javascript:void(0)' onclick='showPrev()' class='pagectl'>&laquo;</a>";
      info += "&nbsp;&nbsp;";		
	  info += "Sida " + currentPage + " av " + totalPages;
      info += "&nbsp;&nbsp;";		
	  info += "<a href='javascript:void(0)' onclick='showNext()' class='pagectl'>&raquo;</a>";
	  }
  else
      info = "";

  $("mapinfo").innerHTML = info;
  $("list").innerHTML = arr.list;

  var cbs = { mouseover: onMarkerMouseOver, mouseout: onMarkerMouseOut };

  MapAPI.replaceGeoPositionMarkers(positions, cbs);
}


