// server specific settings
var shtmlpath = "/design/libs/google/map.shtml";
var imagepath = "/design/images/gmap/";


// Our todd map controller object
var map;

// Last bounds (prevent requesting overlays twice)
var lastbounds;

// Our XMLHttpRequest communicator
var xhr;

var busyimage, logger, statusDialog;

// Move handler timeout
var movetimeout = null;

function toddEncodeJSON(data)
{
  switch(typeof data)
  {
    case 'boolean':
      return data ? 'true' : 'false';
    case 'object':
      if(data==null)
        return'null';

      if(data instanceof Array)
      {
        var retval='[';
        for (var i=0;i<data.length;++i)
          retval+=(i>0?',':'')+toddEncodeJSON(data[i]);
        return retval+']';
      }

      var retval='{';
      for (cellname in data) //ADDME safari 1.3 fallback for hasownproperty?!
        if(!data.hasOwnProperty || data.hasOwnProperty(cellname))
          retval += (retval.length>1?',':'') + '"' + cellname + '":' + toddEncodeJSON(data[cellname]);
      return retval+'}';
    case 'number':
      return data.toString();
    case 'string':
      if (/["\\\x00-\x1f]/.test(data))
      {
          return '"' + data.replace(/[\x00-\x1f\\"]/g, function (a)
          {
              var c = a.charCodeAt();
              return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
          }) + '"';
      }
      return '"' + data + '"';
    default:
      return alert("toddEncodeJSON: How should I encode " + typeof data + "?");
  }
}

function ShowBusyImage()
{
  busyimage.style.display = 'block';
}


function HideBusyImage()
{
  busyimage.style.display = 'none';
}


function AddSearchBoxBehavior () {
  
  var searchinput = document.getElementById("words");
  if (searchinput) {
    searchinput.value = "Search ECOS...";
    searchinput.style.backgroundColor = "#f5f5f5";
    searchinput.onfocus = function() { 
      this.value = ""; 
      this.style.backgroundColor = "#fff";
    }
  }

}

function toddCreateRequestObject()
{
 var browser = navigator.appName;
 if(browser == "Microsoft Internet Explorer")
 {
   var ro = new ActiveXObject("Microsoft.XMLHTTP");
 }
 else
 {
   var ro = new XMLHttpRequest();
 }
 return ro;
} 

function toddDummyFunction()
{  
  return;
}

function LoadMap()
{
  AddSearchBoxBehavior();

  logger = document.getElementById("gmap_log");
  statusDialog = document.getElementById("gmap_statusdialog");
  busyimage = document.getElementById("toddBusyImage");

  ShowBusyImage();
  
  statusLog("Initializing map...<br/>");

  xhr = toddCreateRequestObject();
  
  xhr.onreadystatechange = XHR_StateChanged;

  map = toddGM_Initialize("gmap_canvas", { maptype: "map"
                                        , center: "11.436955,30.410156"
                                        , zoom: 5
                                        , moveable: true
                                        , iconsize: 48
                                        , icons: [ { name: "report-clustered", icon: imagepath + "report-clustered.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "report-pin", icon: imagepath + "report-pin.png", shadow: imagepath + "pin-shadow.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "newsitem-clustered", icon: imagepath + "newsitem-clustered.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "newsitem-pin", icon: imagepath + "newsitem-pin.png", shadow: imagepath + "pin-shadow.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "analysis-clustered", icon: imagepath + "analysis-clustered.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "analysis-pin", icon: imagepath + "analysis-pin.png", shadow: imagepath + "pin-shadow.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "agreement-clustered", icon: imagepath + "agreement-clustered.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "agreement-pin", icon: imagepath + "agreement-pin.png", shadow: imagepath + "pin-shadow.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "multimedia-clustered", icon: imagepath + "multimedia-clustered.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "multimedia-pin", icon: imagepath + "multimedia-pin.png", shadow: imagepath + "pin-shadow.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 , { name: "singledoc-pin", icon: imagepath + "yellow-pin.png", shadow: imagepath + "pin-shadow.png", anchor_x: 15, anchor_y: 42, label_x: 24, label_y: 8, popup_x: 24, popup_y: 5}
                                                 ]
                                        , OnInitialized: MapInitialized
                                        , OnMoveEnd: XHR_UpdateOverlays
                                        , OnZoomEnd: OnZoomEnd
                                        , OpenInfoWindow: OpenInfoWindow
                                        , CloseInfoWindow: CloseInfoWindow
                                        });
}

function UnloadMap()
{
  toddGM_DeInit(map);
}

function MapInitialized()
{
  map.map.addControl(new vw_ZoomControl());
  map.map.addControl(new vw_FullscreenControl());
  map.map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(130,10)));  

  XHR_UpdateOverlays();

  statusLog("Map is initialized.");
}

var UpdateOverlaysTimeout = null;

function OnZoomEnd()
{
 if (UpdateOverlaysTimeout)
   window.clearTimeout(UpdateOverlaysTimeout);
   UpdateOverlaysTimeout = window.setTimeout('XHR_UpdateOverlays', 100);
} 

function XHR_UpdateOverlays(force)
{

  var bounds = toddGM_BoundsToString(map.GetMapIconBounds());
  if (bounds == lastbounds && !force)
  {
    statusLog("Already requested overlays.");
    return;
  }

  lastbounds = bounds;
  statusLog("Requesting overlays...");
  
  ShowBusyImage();

  var show_concessions = document.getElementById('gmap_show_concessions').checked;
  var show_newsitems = document.getElementById('gmap_show_newsitems').checked;
  var show_reports= document.getElementById('gmap_show_reports').checked;
  var show_agreements = document.getElementById('gmap_show_agreements').checked;
  var show_analyses = document.getElementById('gmap_show_analyses').checked;
  var show_multimedia = document.getElementById('gmap_show_multimedia').checked;
  var theme_selected = document.getElementById('gmap_show_theme').value;

  var url = window.location;
  var re = /(?:specific_doc=)([0-9]+)/;
  var docvar = re.exec(url);
  var specificdoc = (docvar && docvar.length>1)?docvar[1]:'0';

  var request = { type: "updateoverlays"
                , show_concessions:show_concessions
                , show_newsitems:show_newsitems
                , show_reports:show_reports
                , show_agreements:show_agreements
                , show_analyses:show_analyses
                , show_multimedia:show_multimedia
                , theme_selected:theme_selected
                , show_specificdoc:specificdoc
                , bounds: bounds
                , zoom: map.map.getZoom()
                };

  xhr.open("POST", shtmlpath, true);
// reassign onreadystatechange in case corrupted by 'abort'
  xhr.onreadystatechange = XHR_StateChanged; 
  xhr.send(toddEncodeJSON(request));

  //xhr.onreadystatechange = toddDummyFunction; // do nothing until we're back here

}



function XHR_StateChanged()
{
  if(xhr.readyState == 4 && xhr.status == 200)
  {
    var response = eval('(' + xhr.responseText + ')');
    if (response.success)
    {
      map.UpdateAllOverlays(response.overlays);
      statusLog("Received <b>" + response.overlays.length + "</b> overlay" + (response.overlays.length != 1 ? "s" : ""));
    }
    else
      statusLog(response.error);
  
    HideBusyImage();
  }
}


function OpenInfoWindow(overlay)
{
  statusLog("Opening info window");
  if (overlay.infohtml)
  {
    if (overlay.marker)
      map.map.openInfoWindowHtml(new google.maps.LatLng(overlay.lat, overlay.lng), overlay.infohtml, { noCloseOnClick: false, maxWidth:350 });
    else if (overlay.shape && overlay.infolat && overlay.infolng)
      map.map.openInfoWindowHtml(new google.maps.LatLng(overlay.infolat, overlay.infolng), overlay.infohtml, { noCloseOnClick: false, maxWidth:350 });
    else
      statusLog('Opening infowindow failed' );
  }
  else
    alert('No infowindow available');
}


function CloseInfoWindow()
{
  statusLog("Closing info window");
  map.map.closeInfoWindow();
}

function statusLog(text)
{
  if (!logger) return;
  logger.innerHTML = ([ logger.innerHTML, text ]).join('<br>');
  logger.scrollTop = logger.scrollHeight;
  
  statusDialog.innerHTML = text;
}



///////////////////////////////////////////////////////////////////////////////
// Zoom control

function vw_ZoomControl()
{
  this.buttons = new Object;
}
vw_ZoomControl.prototype = new google.maps.Control();

// Called by google.maps.Map2.addControl()
vw_ZoomControl.prototype.initialize = function vw_ZoomControl_initialize(map)
{
  this.map = map;

  // Create a container for our buttons
  this.node = document.createElement("div");
  this.node.style.textAlign = "center";

  var self = this;
  // Create our buttons buttons and add them to the container
  this.buttons.zoomin = this.CreateButton("zoomin", function(e) { self.ZoomIn(e); }, this.node);
  this.buttons.zoomout = this.CreateButton("zoomout", function(e) { self.ZoomOut(e); }, this.node);

  // Insert our button container in the map controls container
  this.map.getContainer().appendChild(this.node);
  return this.node;
}

// Called by google.maps.Map2.addControl()
vw_ZoomControl.prototype.getDefaultPosition = function vw_ZoomControl_getDefaultPosition()
{
  // Position this control at the top left corner, at 8 pixels from the map's edge
  return new google.maps.ControlPosition(G_ANCHOR_TOP_LEFT, new google.maps.Size(8, 6));
}

vw_ZoomControl.prototype.DeInit = function vw_ZoomControl_DeInit()
{
  for (var b in this.buttons)
    if (this.buttons[b])
      google.maps.Event.clearInstanceListeners(this.buttons[b]);
}

vw_ZoomControl.prototype.CreateButton = function vw_ZoomControl_CreateButton(buttonimage, callback, parent)
{
  var button = document.createElement("img");
  button.src = imagepath + buttonimage + ".png";
  button.width = 30;
  button.height = 32;

  button.map = this.map;
  button.style.cursor = "pointer";
  google.maps.Event.addDomListener(button, "click", callback);
  parent.appendChild(button);
  return button;
}

vw_ZoomControl.prototype.ZoomIn = function vw_ZoomControl_ZoomIn()
{
  this.map.zoomIn();
}

vw_ZoomControl.prototype.ZoomOut = function vw_ZoomControl_ZoomOut()
{
  this.map.zoomOut();
}


///////////////////////////////////////////////////////////////////////////////
// Fullscreen control

function vw_FullscreenControl()
{
  this.buttons = new Object;
  this.fullscreen = false;
  this.fullscreencontainer = null;
}
vw_FullscreenControl.prototype = new google.maps.Control();

// Called by google.maps.Map2.addControl()
vw_FullscreenControl.prototype.initialize = function vw_FullscreenControl_initialize(map)
{
  this.map = map;

  // Create a container for the fullscreen view
  this.fullscreencontainer = document.createElement("div");
  this.fullscreencontainer.style.position = "absolute";
  this.fullscreencontainer.style.top = "0";
  this.fullscreencontainer.style.left = "0";
  this.fullscreencontainer.style.display = "none";
  this.fullscreencontainer.style.zIndex = "1000";
  this.fullscreencontainer.style.textAlign = "left";
  document.body.appendChild(this.fullscreencontainer);

  // Create a container for our buttons
  this.node = document.createElement("div");
  this.node.style.textAlign = "center";

  var self = this;
  // Create our buttons buttons and add them to the container
  this.buttons.fullscreen = this.CreateButton("fullscreen", function(e) { self.Fullscreen(e); }, this.node);

  // Insert our button container in the map controls container
  this.map.getContainer().appendChild(this.node);
  return this.node;
}

// Called by google.maps.Map2.addControl()
vw_FullscreenControl.prototype.getDefaultPosition = function vw_FullscreenControl_getDefaultPosition()
{
  // Position this control at the top left corner, at 8 pixels from the map's edge
  return new google.maps.ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(8, 6));
}

vw_FullscreenControl.prototype.DeInit = function vw_FullscreenControl_DeInit()
{
  for (var b in this.buttons)
    if (this.buttons[b])
      google.maps.Event.clearInstanceListeners(this.buttons[b]);
}

vw_FullscreenControl.prototype.CreateButton = function vw_FullscreenControl_CreateButton(buttonimage, callback, parent)
{
  var button = document.createElement("img");
  button.src = imagepath + buttonimage + ".png";
  button.width = 32;
  button.height = 32;

  button.map = this.map;
  button.style.cursor = "pointer";
  google.maps.Event.addDomListener(button, "click", callback);
  parent.appendChild(button);
  return button;
}

vw_FullscreenControl.prototype.Fullscreen = function vw_FullscreenControl_Fullscreen()
{
  var map_canvas = document.getElementById("gmap_canvas");
  var map_container = document.getElementById("gmap_container");

  this.fullscreen = !this.fullscreen;
  if (this.fullscreen)
  {
    this.scrollTop = { bodyTop: document.body.scrollTop
                     , htmlTop: document.documentElement.scrollTop
                     , bodyLeft: document.body.scrollLeft
                     , htmlLeft: document.documentElement.scrollLeft
                     };
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
    document.body.scrollLeft = 0;
    document.documentElement.scrollLeft = 0;

    var latlng = this.map.getCenter();
    this.fullscreencontainer.style.width = (document.documentElement.clientWidth) + "px";
    this.fullscreencontainer.style.height = (document.documentElement.clientHeight) + "px";
    this.fullscreencontainer.style.display = "block";
    this.fullscreencontainer.appendChild(map_canvas);
    this.map.checkResize();
    this.map.setCenter(latlng);
  }
  else
  {
    var latlng = this.map.getCenter();
    map_container.appendChild(map_canvas);
    this.fullscreencontainer.style.display = "none";
    this.map.checkResize();
    this.map.setCenter(latlng);

    document.body.scrollTop = this.scrollTop.bodyTop;
    document.documentElement.scrollTop = this.scrollTop.htmlTop;
    document.body.scrollLeft = this.scrollTop.bodyLeft;
    document.documentElement.scrollLeft = this.scrollTop.htmlLeft;
  }
}
