var map;
var mapdiv;
var gcoder;
var mgr;
var config;
var data;
var initScript;
// Open the linktool dialog. Use this function to open the dialog from your own code.
function OpenLinkToolDialog(dialogURL, dialogArguments) {
  dialogURL += (dialogURL.indexOf('?') >= 0 ? '&' : '?') + 'caller=dhtmleditor';

  return OpenDialog(dialogURL, dialogArguments);
}

function OpenDialog(dialogURL, dialogArguments, width, height) {
  width = (!width) ? 560 : parseInt(width);
  height = (!height) ? 465 : parseInt(height);

  var dialogParameters = 'dialogWidth:' + width + 'px;dialogHeight:' + height + 'px;help=no;resizable:no;scroll:no;status:no;';

  return OpenDialogWithParameters(dialogURL, dialogArguments, dialogParameters);
}

function OpenDialogWithParameters(dialogURL, dialogArguments, dialogParameters) {
  var returnedObject;
  var ex;

  // The following flag is used by the editor to track if focus is lost because of a dialog is being opened.
  // When the flag is true, the caret position is not lost in the editor when the focusout event is triggered.
  window.OpeningDialog = true;

  try {
    returnedObject = window.showModalDialog(dialogURL, dialogArguments, dialogParameters);
  }
  catch (ex) {
    ShowMsg("Popups are blocked for this site, you need to enable popups to access this function.");
    returnedObject = "";
  }

  window.OpeningDialog = false;

  return returnedObject;
}

function load() {
  if (GBrowserIsCompatible()) {

    mapdiv = document.getElementById("map");

    if (mapdiv) {
      map = new GMap2(mapdiv);

      map.enableDoubleClickZoom();

      gcoder = new GClientGeocoder();

      GDownloadUrl(config, 
        function(vdata, responseCode) {
          var fail = '';
          if (responseCode == 200) {
            var xml = GXml.parse(vdata);
            if (xml) {
              //alert(vdata);     //uncomment line to debug xml created         
              config = xml.documentElement.getElementsByTagName('config')[0];
              data = xml.documentElement.getElementsByTagName('data')[0];
              initScript = xml.documentElement.getElementsByTagName('initscript')[0];
              fail = GmapInit();
            } else {
              fail = 'error on xml';
            }
          } else {
            fail = 'error on get configuration';
          }
          if ((fail) && (fail != ''))
            alert(fail);
        }
      );
    }
  }
}
function Initialize() {
  if (initScript.firstChild) {
    if (initScript.firstChild.data) {
      eval(initScript.firstChild.data);
    }
  }
}


function GmapInit() {
  //size part
  var size = config.getElementsByTagName('size')[0];
  var width = size.getElementsByTagName('width')[0].firstChild.data;
  var height = size.getElementsByTagName('height')[0].firstChild.data;
  setMapSize(width, height);

  //map center
  var center = config.getElementsByTagName('center')[0];
  center = center.getElementsByTagName('poi')[0];

  //add zoom control
  map.addControl(new GLargeMapControl());

  var gcenter = new gAddress(center);
  var zoom = config.getElementsByTagName('zoom')[0].firstChild.data;
  zoom = parseInt(zoom);
  findCenter(gcenter, zoom);

  setTimeout(GmapPutData, 500);
  if (initScript)
    setTimeout(Initialize, 500);

}
function GmapPutData() {
  var pois = data.getElementsByTagName('poi');

  for (var i = 0; i < pois.length; i++) {
    var poi = new gAddress(pois[i]);
    updateMarker(poi, null);
  }
}

function centerIt(ll, zoom) {
  map.setCenter(ll, zoom);
}
function findCenter(address, zoom) {
  var ll = null;

  if ((address.lat) && (address.lng)) {
    ll = new GLatLng(address.lat, address.lng);
    centerIt(ll, zoom);

  } else {
    var where = address.city + ',' + address.country;
    gcoder.getLatLng(where, function(point) {
      if (point) {
        centerIt(point, zoom);
      } else {
        gcoder.getLatLng(address.country, function(point) {
          if (point)
            centerIt(point, zoom);
        });
      }
    }
       );

  }
}

//creates a custom icon with onclick text
function createMarker(point, html, icon) {
  var marker;
  if (icon)
    marker = new GMarker(point, icon);
  else
    marker = new GMarker(point);
  if (html) {
    GEvent.addListener(marker, "click",
                function() {
                  marker.openInfoWindowHtml(html);
                });
  }
  return marker;
}

function updateMarker(address, marker) {
  var ll = null;

  if ((address.lat) && (address.lng)) {
    ll = new GLatLng(address.lat, address.lng);
    var theIcon = null;

    if ((address.icon) && (address.icon.indexOf(".") > 0)) {
      var baseIcon = new GIcon();
      baseIcon.iconSize = new GSize(30, 30);
      baseIcon.shadowSize = new GSize(56, 32);
      baseIcon.iconAnchor = new GPoint(16, 32);
      baseIcon.infoWindowAnchor = new GPoint(16, 0);
      baseIcon.shadow = address.iconshadow;
      //creating custom icon
      theIcon = new GIcon(baseIcon, address.icon);
    }

    var marker = createMarker(11, address.info, theIcon)
    //add marker to map     
    marker.setPoint(ll);
    map.addOverlay(marker);

  } else {
    var where = address.city + ',' + address.country;
    gcoder.getLatLng(where, function(point) {
      if (point) {
        uMarker(point, marker, address.info);
      } else {
        gcoder.getLatLng(address.country, function(point) {
          if (point)
            uMarker(point, marker, address.info);
        });
      }
    }
       );

  }
}



function setMapSize(width, height) {
  mapdiv.style.width = width + 'px';
  mapdiv.style.height = height + 'px';
  map.checkResize();
}

//build data object based on config xml
function gAddress(xnode) {
  if (xnode.getElementsByTagName('city')[0].firstChild)
    this.city = xnode.getElementsByTagName('city')[0].firstChild.data;
  else
    this.city = '';

  this.info = '';
  if (xnode.getElementsByTagName('info')[0]) {
    if (xnode.getElementsByTagName('info')[0].firstChild)
      this.info = xnode.getElementsByTagName('info')[0].firstChild.data;
  }

  if (xnode.getElementsByTagName('country')[0].firstChild)
    this.country = xnode.getElementsByTagName('country')[0].firstChild.data;
  else
    this.country = '';
  var gpoint = xnode.getElementsByTagName('gpoint')[0];
  if (gpoint.getElementsByTagName('lat')[0].firstChild)
    this.lat = parseFloat(gpoint.getElementsByTagName('lat')[0].firstChild.data);
  else
    this.lat = null;
  if (gpoint.getElementsByTagName('lng')[0].firstChild)
    this.lng = parseFloat(gpoint.getElementsByTagName('lng')[0].firstChild.data);
  else
    this.lng = null;

  this.icon = null;
  if (xnode.getElementsByTagName('icon')[0]) {
    if (xnode.getElementsByTagName('icon')[0].firstChild)
      this.icon = xnode.getElementsByTagName('icon')[0].firstChild.data;
  }

  this.iconshadow = null;
  if (xnode.getElementsByTagName('iconshadow')[0]) {
    if (xnode.getElementsByTagName('iconshadow')[0].firstChild)
      this.iconshadow = xnode.getElementsByTagName('iconshadow')[0].firstChild.data;
  }


}