// global vars
var _map;
var _markerImages;          // images for markers
var _markers = new Array(); // list of all marker objects: it is global to permit events trigger by sideBar
var SIDEBAR_ELEMENT_ID_PREFIX = "sbe_";

// load map reading data from suppied xml (url)
function loadMap( idOfContainerElement, idOfSideBarContainerElement, urlOfXmlDataFile, urlOfImages, mapType, pageType ,ctrlOn)
{

  if (G_NORMAL_MAP==null) return;
  if ( mapType == null )
    mapType = G_NORMAL_MAP;
    
  // get data file
  GDownloadUrl( urlOfXmlDataFile, function(data, responseCode) {
    if ( responseCode != '200' || data == null || data == '' )
    {
      alert( 'Map error:\nresponseCode: ' + responseCode + '\ndata: ' + ( data == null ? 'NULL' : '' ) );
      return;
    }
      
    xmlDataFileDownloadComplete( idOfContainerElement, idOfSideBarContainerElement, data, responseCode, urlOfImages, mapType, pageType, ctrlOn);
  });
}

// xml data dowload completed, start processing
function xmlDataFileDownloadComplete( idOfContainerElement, idOfSideBarContainerElement, data, responseCode, urlOfImages, mapType, pageType, ctrlOn) {
  generateMapByXmlData( idOfContainerElement, idOfSideBarContainerElement, data, urlOfImages, mapType, pageType, ctrlOn);
}

// generate the map basing on xmlData (string format) supplied
function generateMapByXmlData( idOfContainerElement, idOfSideBarContainerElement, xmlData, urlOfImages, mapType, pageType, ctrlOn)
{
  // hides map container while loading
  document.getElementById( idOfContainerElement ).style.visibility = 'hidden';
  
  // get sideBar element
  var sideBar = document.getElementById( idOfSideBarContainerElement );

  // init images array
  _markerImages = [
  G_DEFAULT_ICON.image,
  urlOfImages + "/gMapMarkerHL.png"
  ];
  
  // create bounds
  var bounds = new GLatLngBounds();
  
  // parse xml
  var xml = GXml.parse(xmlData);

  // create map and set properties
  _map = new GMap2(document.getElementById( idOfContainerElement ));
  _map.setCenter(new GLatLng(0, 0), 10);                                 // center map (recentered after markers positioning)
  if (ctrlOn){
      _map.addControl(new GLargeMapControl());                               // controls (zoom, scroll)
      _map.addControl(new GMapTypeControl());                                // _map type control
      _map.addControl(new GScaleControl());                                  // display scale
      new GKeyboardHandler(_map);                                            // bind keys (up, down...pup, pdown...+ -)
      _map.enableContinuousZoom();
      _map.enableDoubleClickZoom();
  }
  _map.setMapType( mapType );
  
  // display markers and generate sidebar
  markerElements = xml.documentElement.getElementsByTagName("MARKER");
  var sideBarContent = "";
  var markerIndex = 0;
  for (var i = 0; i < markerElements.length; i++)
  {
    if (
      markerElements[i].getAttribute("MAP_LAT") == null ||
      markerElements[i].getAttribute("MAP_LONG") == "" ||
      markerElements[i].getAttribute("MAP_LAT") == null ||
      markerElements[i].getAttribute("MAP_LONG") == "" )
    {
      // only sidebar, no map interaction
      sideBarContent += createSideBarElement( markerElements[i] );
    }
    else
    {
      // map marker and sidebar with map interaction
      _markers[markerIndex] = createMarker( markerElements[i], bounds, markerIndex, pageType );
      _map.addOverlay( _markers[markerIndex] );
      sideBarContent += createSideBarElement( markerElements[i], markerIndex );
      markerIndex++;
    }
  }
  
  sideBar.innerHTML = sideBarContent;
  
  // zoom: if specified use it, otherwise get from bounds
  var specifiedZoomLevel = xml.documentElement.getAttribute("MAP_ZOOM");
  if ( specifiedZoomLevel == "" )
    specifiedZoomLevel = null;
  
  var effectiveZoomLevel = parseInt( ( specifiedZoomLevel != null ? specifiedZoomLevel : _map.getBoundsZoomLevel(bounds) ) );
  //Never use max zoom... use at least 13
//  if( effectiveZoomLevel > 12 )
//    effectiveZoomLevel = 12;
  //alert( 'specified: ' + (specifiedZoomLevel == null ? "NULL" : specifiedZoomLevel) + "; effective:"  + effectiveZoomLevel);
  
  //auto center and zoom
  if (xml.documentElement.getAttribute("MAP_LAT")=="" || 
  	xml.documentElement.getAttribute("MAP_LONG")=="")
  	_map.setCenter(bounds.getCenter(), effectiveZoomLevel );
  else
  	_map.setCenter(new GLatLng(xml.documentElement.getAttribute("MAP_LAT"), xml.documentElement.getAttribute("MAP_LONG")), effectiveZoomLevel );
  _map.savePosition(); // this makes the center button useful

  // show/hide controls on mouseover/mouseout
  /*
  map.hideControls();
  GEvent.addListener(map, "mouseover", function(){
    map.showControls();
  });
  GEvent.addListener(map, "mouseout", function(){
    map.hideControls(); 
  });
  */

  // show map container
  document.getElementById( idOfContainerElement ).style.visibility = 'visible';
}

// create sidebar HTML element
function createSideBarElement( xmlDataMarkerElement, markerIndex )
{
  var id          = SIDEBAR_ELEMENT_ID_PREFIX + markerIndex;
  var text        = xmlDataMarkerElement.getAttribute("NAME") == '' ? "(...)" : xmlDataMarkerElement.getAttribute("NAME");
  var href        = xmlDataMarkerElement.getAttribute("SEO");
  
  // intercat with map
  if ( markerIndex != null )
  {
    var onMouseOver = "GEvent.trigger(_markers[" + markerIndex + "], 'mouseover')";
    var onMouseOut  = "GEvent.trigger(_markers[" + markerIndex + "], 'mouseout')";

    return '<a id="' + id + '" href="' + href + '" onmouseover="' + onMouseOver + '" onmouseout="' + onMouseOut + '">' + text + '</a>';
  }
  // do not interact with map
  else
  {
    return '<a id="' + id + '" href="' + href + '">' + text + '</a>';
  }
  
  
}

// create GMarker
function createMarker( xmlDataMarkerElement, mapBounds, markerIndex, pageType )
{
  var point = new GLatLng(parseFloat(xmlDataMarkerElement.getAttribute("MAP_LAT")), parseFloat(xmlDataMarkerElement.getAttribute("MAP_LONG")));
  var marker = new GMarker(point, {title:xmlDataMarkerElement.getAttribute("NAME")});
  var infoWin = xmlDataMarkerElement.getAttribute("INFO_TEXT");
  
  GEvent.addListener(marker, "click", function()
    {
//      if( pageType == 'LOCALITION' )
        marker.openInfoWindowHtml(infoWin,{maxWidth:150});//300
//      else // other values may be "touristiczone" "region"
//        window.location.href = xmlDataMarkerElement.getAttribute("SEO");
    }
  );
  
  GEvent.addListener(marker,'mouseover', function()
    {
      //marker.openInfoWindowHtml(infoWin,{maxWidth:300});
      marker.visited = true;
      marker.setImage(_markerImages[1]);
      hlSideBarElement( markerIndex, true );
    }
  );
  
  GEvent.addListener(marker,'mouseout', function()
    {
      marker.setImage(_markerImages[0]);
      hlSideBarElement( markerIndex, false );
    }
  );
  
  mapBounds.extend( point );
  
  return marker;
}

// highlight a sidebar element
function hlSideBarElement( markerIndex, hl )
{
  var hlElement = document.getElementById( SIDEBAR_ELEMENT_ID_PREFIX + markerIndex );
  if ( hlElement == null )
    return;
  
  hlElement.className = hl ? 'hl' : '';
}
