if(typeof(Sima)=="undefined") Sima={};
/***********************************
 * Namespace: Sima.Map
 ***********************************/
if(typeof(Sima.Map)=="undefined") Sima.Map = {};
Sima.Map.nextid=1;
Sima.Map.nextscriptid=1;

/***********************************
 * Enumumerations
 ***********************************/
Sima.Map.ActionType={
  None:         0,
  Pan:          1,
  ZoomIn:       2,
  ZoomOut:      3,
  DrawPoint:    4,
  DrawLine:     5,
  DrawRectangle:6,
  DrawCircle:   7,
  DrawPolygon:  8,
  MoveMap:      9,
  ZoomBox:      10,
  ZoomLive:     11};
Sima.Map.BrowseMapState={
  MoveMap:      1,
  ZoomBox:      2,
  ZoomLive:     3,
  DrawLine:     4,
  DrawRectangle:5,
  DrawCircle:   6,
  DrawPolygon:  7};
Sima.Map.SelectionType={
  None:         "",
  Rectangle:    "RECT",
  Polygon:      "POLY",
  Circle:       "CIRC",
  Line:         "LINE",
  Point:        "POIN"};
Sima.Map.SelectionState={
  NoSelection:  0,
  Selecting:    1,
  HasSelection: 2};
Sima.Map.ActionEventType={
  Select:       "SELECT",
  Deselect:     "DESELECT"};
Sima.Map.SelectionEventType={
  Start:        "START",
  End:          "END",
  Clear:        "CLEAR"};
Sima.Map.LayerEventType={
  Loaded:     "Loaded",
  Add:        "Add",
  Remove:     "Remove",
  Hide:       "Hide",
  Show:       "Show",
  Activate:   "Activate",
  Deactivate: "Deactivate"};

/***********************************
 * Classes
 ***********************************/
Sima.Map.ActionEvent=function(eventType, actionType){this.eventType=eventType;this.actionType=actionType;};
Sima.Map.ActionEvent.prototype.toString = function(){return "ActionEvent {eventType="+this.eventType+", this.actionType="+this.actionType+"}";};
Sima.Map.SelectionEvent=function(eventType, selection){this.eventType=eventType;this.selection=selection};
Sima.Map.SelectionEvent.prototype.toString = function(){return "SelectionEvent {eventType="+this.eventType+"}";};
Sima.Map.ZoomlevelEvent=function(zoomlevel){this.zoomlevel=zoomlevel};
Sima.Map.ZoomlevelEvent.prototype.toString = function(){return "ZoomlevelEvent {zoomlevel="+this.zoomlevel+"}";};
Sima.Map.ScaleEvent=function(scale){this.scale=scale};
Sima.Map.ScaleEvent.prototype.toString = function(){return "ScaleEvent {scale="+this.scale+"}";};
Sima.Map.CartographyEvent=function(cartography){this.cartography=cartography};
Sima.Map.CartographyEvent.prototype.toString = function(){return "CartographyEvent {cartography="+this.cartography+"}";};
Sima.Map.CoordinateEvent=function(coordinate){this.coordinate=coordinate};
Sima.Map.CoordinateEvent.prototype.toString = function(){return "CoordinateEvent {coordinate="+this.coordinate+"}";};
Sima.Map.UpdateEvent=function(){};
Sima.Map.UpdateEvent.prototype.toString = function(){return "UpdateEvent {}";};
Sima.Map.LayerEvent=function(eventType, layerName){this.eventType=eventType;this.layerName=layerName;};
Sima.Map.LayerEvent.prototype.toString = function(){return "LayerEvent {eventType="+this.eventType+",layerName="+this.layerName+"}";};

/***********************************
 * Class: Sima.Map.BrowseMap
 ***********************************/
Sima.Map.BrowseMap=function(){
  var scripts = (document.scripts)?document.scripts:document.getElementsByTagName("SCRIPT");
  var regexp = new RegExp("^(.*)/SimaMap.js$","i");
  var match
  this.scriptbase = "http://www.sima.dk/Utils";
  this.tp = this.scriptbase+"/images/1pxtransparent.gif";
  this.width=400;
  this.height=300;
  this.zoomlevel=1;
  this.scale=1;
  this.cartography=2;
  this.border=10;
  this.rendered=false;
  this.id = "SimaMap$" + (Sima.Map.nextid++);
  this.listeners = new Array();
  this.coordinate = new Sima.Geometry.Coordinate();
  
  this.actionType = Sima.Map.ActionType.None;

  this.drawingCanvas=new Sima.Map.DrawingCanvas();
  this.locationLayers=new Sima.Map.LocationLayers();
  this.navigationPanel=new Sima.Map.NavigationPanel();
  this.toolbar=new Sima.Map.Toolbar();
  this.selection=new Sima.Map.Selection();
  this.regionMap=new Sima.Map.RegionMap();
  this.ratio=Array(0.30, 0.92, 2.29, 4.57, 10.9, 46, 170, 385, 978, 3261, 11400);
  
  this.drawingCanvas.map=this;
  this.locationLayers.map=this;
  this.navigationPanel.map=this;
  this.toolbar.map=this;
  this.selection.map=this;
  this.regionMap.map=this;
  
  this.actionEventListeners = new Array();
  this.selectionEventListeners = new Array();
  this.zoomlevelEventListeners = new Array();
  this.scaleEventListeners = new Array();
  this.cartographyEventListeners = new Array();
  this.coordinateEventListeners = new Array();
  this.updateEventListeners = new Array();
  this.layerEventListeners = new Array();
  Sima.Map[this.id]=this;
};
pro = Sima.Map.BrowseMap.prototype;


/*----------------------------------
 Public Methods
 ----------------------------------*/
pro.getPixelPrMeter=function(){return this.scale/this.ratio[this.zoomlevel];};
pro.getMeterPrPixel=function(){return 1/this.getPixelPrMeter();};
pro.meter2pixel=function(value){return value*this.getPixelPrMeter();};
pro.pixel2meter=function(value){return value*this.getMeterPrPixel();};
pro.coordinateX2pixelX=function(value){return Math.round(0.5*this.width-this.meter2pixel(this.coordinate.x-value));};
pro.coordinateY2pixelY=function(value){return Math.round(0.5*this.height+this.meter2pixel(this.coordinate.y-value));};
pro.coordinate2pixel=function(coordinate){return new Sima.Graphics.Point(this.coordinateX2pixelX(coordinate.x), this.coordinateY2pixelY(coordinate.y));};
pro.pixelX2coordinateX=function(value){return this.coordinate.x+this.pixel2meter(value-0.5*this.width);};
pro.pixelY2coordinateY=function(value){return this.coordinate.y+this.pixel2meter(0.5*this.height-value);};
pro.pixel2coordinate=function(point){return new Sima.Geometry.Coordinate(this.pixelX2coordinateX(point.x), this.pixelY2coordinateY(point.y));};
pro.getExtentXmin=function(){return Math.round(this.pixelX2coordinateX(0));};
pro.getExtentXmax=function(){return Math.round(this.pixelX2coordinateX(this.width)-1);};
pro.getExtentYmin=function(){return Math.round(this.pixelY2coordinateY(this.height)-1);};
pro.getExtentYmax=function(){return Math.round(this.pixelY2coordinateY(0));};
pro.setCoordinateX=function(coordinateX,refresh){this.coordinate.x=coordinateX;if(refresh!=false)this.refresh();this.fireCoordinateEvent(new Sima.Map.CoordinateEvent(this.coordinate));};
pro.setCoordinateY=function(coordinateY,refresh){this.coordinate.y=coordinateY;if(refresh!=false)this.refresh();this.fireCoordinateEvent(new Sima.Map.CoordinateEvent(this.coordinate));};
pro.setCoordinate=function(coordinate,refresh){this.coordinate=coordinate;if(refresh!=false)this.refresh();this.fireCoordinateEvent(new Sima.Map.CoordinateEvent(this.coordinate));};
pro.setExtent=function(extentXmin,extentYmin,extentXmax,extentYmax,refresh) {
  var width = extentXmax - extentXmin;
  var height = extentYmax - extentYmin;
  this.setZoomlevel(this.findBestZoomlevel(width, height),false);
  this.setCoordinate(new Sima.Geometry.Coordinate((extentXmax+extentXmin)/2,(extentYmax+extentYmin)/2),false);
  var scale = ((width/height)>this.getAspectRatio())?
    this.width*this.ratio[this.zoomlevel]/width:
    this.height*this.ratio[this.zoomlevel]/height;
  if(this.getZoomlevel()==0) scale=1;
  if(scale>100) scale=100;
  this.setScale(scale,false);
  if(refresh!=false)this.refresh();
};
pro.getZoomlevel=function() {return this.zoomlevel;};
pro.setZoomlevel=function(zoomlevel,refresh) {
  if(zoomlevel>this.ratio.length-2) zoomlevel=this.ratio.length-2;
  if(zoomlevel<0) zoomlevel=0;
  if(this.zoomlevel!=zoomlevel||this.getScale()!=1) {
    if(this.maxZoom && 1/this.ratio[zoomlevel]>this.maxZoom){
      while(1/this.ratio[zoomlevel]>this.maxZoom) zoomlevel++;
      this.zoomlevel=zoomlevel;
      this.scale=this.ratio[this.zoomlevel]*this.maxZoom;
    }else{
      this.zoomlevel=zoomlevel;
      if(this.getScale()!=1) this.setScale(1,false);
    }
    this.fireZoomlevelEvent(new Sima.Map.ZoomlevelEvent(this.zoomlevel));
    if(refresh!=false)this.refresh();
  }
};
pro.zoomIn = function(coordinate,refresh) {
  this.setCoordinate(coordinate,false);
  this.setZoomlevel(this.getZoomlevel()-1,false);
  if(refresh!=false)this.refresh();
};
pro.zoomOut = function(coordinate) {
  this.setCoordinate(coordinate,false);
  if(this.scale!=1) {
    this.setScale(1,false);
  } else {
    this.setZoomlevel(this.getZoomlevel()+1,false);
  }
  if(refresh!=false)this.refresh();
};
pro.setMaxZoom = function(maxZoom){if(!this.maxZoom)this.maxZoom=maxZoom;};
pro.setScale = function(scale,refresh) {if(this.maxZoom && scale/this.ratio[this.zoomlevel]>this.maxZoom){scale=this.ratio[this.zoomlevel]*this.maxZoom}if(this.scale!=scale) {this.scale=scale;this.fireScaleEvent(new Sima.Map.ScaleEvent(this.scale));if(refresh!=false)this.refresh();}};
pro.getScale=function() {return this.scale;};
pro.setCartography = function(cartography,refresh) {if(this.cartography!=cartography) {this.cartography=cartography;this.fireCartographyEvent(new Sima.Map.CartographyEvent(this.cartography));if(refresh!=false)this.refresh();}};
pro.getCartography = function() {return this.cartography;};
pro.setDimension = function(width, height,refresh) {this.width=width;this.height=height;if(refresh!=false)this.refresh();};
pro.setHeight = function(height,refresh) {this.height=height;if(refresh!=false)this.refresh()};
pro.setWidth = function(width,refresh) {this.width=width;if(refresh!=false)this.refresh()};
pro.getAspectRatio = function() {return this.width/this.height;};
pro.getImageSRC = function() {return this.browseMapImageSRC;};
pro.getRegionImageSRC = function() {return this.regionMapImageSRC;};
pro.getPrintImageSRC = function() {
  var src=this.printMapImageSRC;
  var k=0;
  for(var i=0;i<this.locationLayers.layers.length;i++) {
    var layer = this.locationLayers.layers[i];
    for(var j=0;j<layer.locations.length;j++) src+="&mtwM"+(++k)+"=1,"+layer.locations[j].x+","+layer.locations[j].y;
  }
  return src;
};
pro.addLocationLayer = function(name, layer) {this.locationLayers.addLayer(name, layer);};
pro.hideLocationLayer = function(name) {this.locationLayers.hideLayer(name);};
pro.showLocationLayer = function(name) {this.locationLayers.showLayer(name);};
pro.deactivateLocationLayer = function(name) {this.locationLayers.deactivateLayer(name);};
pro.activateLocationLayer = function(name) {this.locationLayers.activateLayer(name);};
pro.deactivateLocations=function() {this.locationLayers.deactivate();};
pro.activateLocations=function() {this.locationLayers.activate();};
pro.setNearestZoomlevel = function(xmin, ymin, xmax, ymax) {
  var zoomlevel = this.findBestZoomlevel(xmax-xmin, ymax-ymin);
  zoomlevel = (zoomlevel>1)?zoomlevel:1;
  this.setZoomlevel(zoomlevel);
  this.setCoordinate(new Sima.Geometry.Coordinate(Math.round((xmax+xmin)/2),Math.round((ymax+ymin)/2)));
};
pro.zoomToAddress = function(url, street, houseno, postalid, city, country, onafterzoom) {
  url+="?Street="+escape(street)+
       "&HouseNo="+escape(houseno)+
       "&PostalID="+escape(postalid)+
       "&City="+escape(city)+
       "&Country="+escape(country);
  var obj = this;
  Sima.Remote.call(url, 
                   function(e) {
                     if(e) {
                       if(e.ExtentXmin!=0 && e.ExtentYmin!=0 && e.ExtentXmax!=0 && e.ExtentYmax!=0) {
                         obj.setNearestZoomlevel(e.ExtentXmin, e.ExtentYmin, e.ExtentXmax, e.ExtentYmax);
                       } else {
                         obj.setNearestZoomlevel(e.GisX, e.GisY, e.GisX, e.GisY);
                       }
                     }
                     if(onafterzoom) onafterzoom(e);
                   },
                   6000);
}
pro.print = function() {
  w = window.open();
  d = w.document;
  d.write("<html><head></head><body><div style='position:relative'><img src='"+this.getPrintImageSRC()+"'/></div></body></html>");
  d.close();
  //w.print();
  //w.close();
  return false;
};
pro.pan = function(direction) {
  switch(direction) {
    case "East":
    case "SouthEast":
    case "NorthEast":
      this.coordinate.x = this.getExtentXmax();
      break;
    case "West":
    case "SouthWest":
    case "NorthWest":
      this.coordinate.x = this.getExtentXmin();
      break;
  }
  switch(direction) {
    case "North":
    case "NorthWest":
    case "NorthEast":
      this.coordinate.y = this.getExtentYmax();
      break;
    case "South":
    case "SouthWest":
    case "SouthEast":
      this.coordinate.y = this.getExtentYmin();
      break;
  }
  this.refresh();
  this.fireCoordinateEvent(new Sima.Map.CoordinateEvent(this.coordinate));
};
pro.setAction = function(actionType) {
  this.fireActionEvent(new Sima.Map.ActionEvent(Sima.Map.ActionEventType.Deselect, this.actionType));
  this.actionType = actionType;
  this.fireActionEvent(new Sima.Map.ActionEvent(Sima.Map.ActionEventType.Select, this.actionType));
};
pro.getAction=function(){return this.actionType;};
pro.setToolbarDesign=function(toolbarDesign){
  this.toolbar.design = toolbarDesign;
}
// - adding event listeners
pro.addListener=function(listeners,listener){for(var i=0;i<listeners.length;i++) {if(listeners[i]==listener) return;}listeners.push(listener);};
pro.addActionEventListener=function(listener){this.addListener(this.actionEventListeners,listener);};
pro.addSelectionEventListener=function(listener){this.addListener(this.selectionEventListeners,listener);};
pro.addZoomlevelEventListener=function(listener){this.addListener(this.zoomlevelEventListeners,listener);};
pro.addScaleEventListener=function(listener){this.addListener(this.scaleEventListeners,listener);};
pro.addCartographyEventListener=function(listener){this.addListener(this.cartographyEventListeners,listener);};
pro.addCoordinateEventListener=function(listener){this.addListener(this.coordinateEventListeners,listener);};
pro.addUpdateEventListener=function(listener){this.addListener(this.updateEventListeners,listener);};
pro.addLayerEventListener=function(listener){this.addListener(this.layerEventListeners,listener);};
// - removing event listeners
pro.removeListener=function(listeners, listener){for(var i=0;i<listeners.length;i++) {if(listeners[i]==listener) {listeners.splice(i, 1);return;}}};
pro.removeActionEventListener=function(listener){this.removeListener(this.actionEventListeners,listener);};
pro.removeSelectionEventListener=function(listener){this.removeListener(this.selectionEventListeners,listener);};
pro.removeZoomlevelEventListener=function(listener){this.removeListener(this.zoomlevelEventListeners,listener);};
pro.removeScaleEventListener=function(listener){this.removeListener(this.scaleEventListeners,listener);};
pro.removeCartographyEventListener=function(listener){this.removeListener(this.cartographyEventListeners,listener);};
pro.removeCoordinateEventListener=function(listener){this.removeListener(this.coordinateEventListeners,listener);};
pro.removeUpdateEventListener=function(listener){this.removeListener(this.updateEventListeners,listener);};
pro.removeLayerEventListener=function(listener){this.removeListener(this.layerEventListeners,listener);};
// - firering events
pro.fireEvent=function(listeners,e){setTimeout(function() {for(var i=0;i<listeners.length;i++)listeners[i](e);},5);};
pro.fireActionEvent=function(e){this.fireEvent(this.actionEventListeners,e);};
pro.fireSelectionEvent=function(e){this.fireEvent(this.selectionEventListeners,e);};
pro.fireZoomlevelEvent=function(e){this.fireEvent(this.zoomlevelEventListeners,e);};
pro.fireScaleEvent=function(e){this.fireEvent(this.scaleEventListeners,e);};
pro.fireCartographyEvent=function(e){this.fireEvent(this.cartographyEventListeners,e);};
pro.fireCoordinateEvent=function(e){this.fireEvent(this.coordinateEventListeners,e);};
pro.fireUpdateEvent=function(e){this.fireEvent(this.updateEventListeners,e);};
pro.fireLayerEvent=function(e){this.fireEvent(this.layerEventListeners,e);};
pro.setSelection=function(selection){
  var regex = new RegExp("^(\\w{4,4})(\\d+(,\\d+)*)$");
  var match = regex.exec(selection);
  var selectiontype = match[1];
  var selectioncoords = match[2];
  switch(selectiontype.toUpperCase()) {
  case "POIN": selectiontype = Sima.Map.SelectionType.Point; break;
  case "CIRC": selectiontype = Sima.Map.SelectionType.Circle; break;
  case "RECT": selectiontype = Sima.Map.SelectionType.Rectangle; break;
  case "POLY": selectiontype = Sima.Map.SelectionType.Polygon; break;
  }
  var coords = selectioncoords.split(",");
  this.selection.start(selectiontype);
  switch(selectiontype.toUpperCase()) {
  case "CIRC":
    if(coords.length==4) {
      this.selection.polygon.push(new Sima.Geometry.Coordinate(Math.round((parseInt(coords[0])+parseInt(coords[2]))/2), Math.round((parseInt(coords[1])+parseInt(coords[3]))/2)));
      this.selection.polygon.push(new Sima.Geometry.Coordinate(Math.round(parseInt(coords[2])), Math.round((parseInt(coords[1])+parseInt(coords[3]))/2)));
    }
    break;
  default:
    for(var i=1;i<coords.length;i+=2) {
      this.selection.polygon.push(new Sima.Geometry.Coordinate(coords[i-1], coords[i]));
    }
    break;
  }
  this.selection.end();
};
pro.showRegionMap=function(bool) {this.displayRegionMap=bool;};
/*----------------------------------
 Private Methods
 ----------------------------------*/
 
/*
 * Rendering
 */
pro.renderContent = function() {
  document.write("<div class='SimaMapContent'"+
                     " id='"+this.id+"$Content'>");
  this.locationLayers.render();
  this.selection.render();
  this.renderBrowseMap();
  this.drawingCanvas.render();
  document.write("</div>");
  this.elementContent = Sima.Tools.getElement(this.id+"$Content");
};
pro.render = function() {
  document.write(
    "<div class='SimaMapMap'"+
        " style='width:"+(this.width+2*this.border)+"px;"+
                "height:"+(this.height+2*this.border+this.toolbar.height)+"px;'"+
        " id='"+this.id+"'>");
  this.navigationPanel.render();
  this.regionMap.render();
  this.toolbar.render();
  this.renderBackground();

  
  document.write("</div>");
  this.element = Sima.Tools.getElement(this.id);
  this.rendered=true;
  this.elementHead = document.getElementsByTagName("head").item(0);
  this.refresh();
};
pro.renderBackground = function() {
  var id=this.id+"$Background";
  document.write(
    "<div class='SimaMapMapArea'"+
        " style='left:"+this.border+"px;"+
                "top:"+(this.border+this.toolbar.height)+"px;"+
                "width:"+this.width+"px;"+
                "height:"+this.height+"px;'>"+
    "<div class='SimaMapBackground'"+
        " style='width:100%;"+
                "height:100%;'"+
        " id='"+id+"'>");
  document.write(
    "<div class='SimaMapInfo'"+
        " id='"+id+"$Info'></div>");
  if(this.toolbar.height==0) {
    this.navigationPanel.renderInnerBorder("NorthWest");
    this.navigationPanel.renderInnerBorder("NorthEast");
  }
  this.navigationPanel.renderInnerBorder("SouthWest");
  this.navigationPanel.renderInnerBorder("SouthEast");
  this.locationLayers.renderMap();
  this.renderContent(); 
  document.write("</div></div>");
  this.elementBackground = Sima.Tools.getElement(id);
  this.elementInfo = Sima.Tools.getElement(id+"$Info");
  var oMap = this;
  this.elementBackground.onmousedown=function(e) {return oMap.mousedown.call(oMap,e);};
  this.addZoomlevelEventListener(function(){oMap.showinfo(oMap);});
  this.addCartographyEventListener(function(){oMap.showinfo(oMap);});
};
pro.showinfo = function(oMap) {
  if(oMap.getZoomlevel()>3 && (oMap.getCartography()==40 || oMap.getCartography()==50)) {
    oMap.elementInfo.innerHTML = Sima.Map.Text.InfoAirphoto;
    oMap.elementInfo.style.display="block";
   } else {
    oMap.elementInfo.innerHTML = "";
    oMap.elementInfo.style.display="none";
   }
};
pro.renderBrowseMap = function() {
  var id = this.id+"$BrowseMap";
  document.write("<div class='SimaMapBrowseMap'"+
                 " id='"+id+"'>"+
                 "<div class='SimaMapBrowseMapCopyright' id='"+id+"$Copyright'></div>");
  this.renderImage();
  document.write("</div>");
  this.elementBackground = Sima.Tools.getElement(id);
  this.elementCopyright = Sima.Tools.getElement(id+"$Copyright");
};
pro.setCopyright=function(){
  var text
  if(this.getZoomlevel()>4 || this.getCartography()==10) {
    text = Sima.Map.Text.CopyrightMap;
  } else {
    text = Sima.Map.Text.CopyrightCombined;
  }
  this.elementCopyright.innerHTML = text;
};
pro.renderImage = function() {
  var id = this.id+"$BrowseImage";
  document.write("<img id='"+id+"'"+
                     " style='z-index:102;position:absolute;'"+
                     " src='"+this.tp+"'"+
                 "/>");
  this.elementBrowseImage = Sima.Tools.getElement(id);
};

pro.fireBrowseMapEvent = function(e) {
  for(var i=0;i<this.listeners.length;i++) {
    this.listeners[i](e);
  }
}
/*
 * Misc
 */
pro.findBestZoomlevel = function(widthMeter, heightMeter) {
  var i = 0;
  while(i<this.ratio.length && (widthMeter>this.width*this.ratio[i] || heightMeter>this.height*this.ratio[i])) i++;
  return i;
}

/*
 * Event handling
 */
pro.mousedown = function(e) {
  if (!e) var e = window.event;
  var targ = this.getEventTarget(e);
  this.mousemoved=false;
  if(targ.tagName.toLowerCase()=="area") return false;
  this.startPosition = this.getPosition(e);
  var oMap = this;
  
  document.onmousemove=function(e) {return oMap.mousemove.call(oMap,e);};
  document.onmouseup=function(e) {return oMap.mouseup.call(oMap,e);};
  switch(this.actionType) {
    case Sima.Map.ActionType.MoveMap: this.onMouseDownMoveMap(e);break;
    case Sima.Map.ActionType.ZoomBox: this.onMouseDownZoomBox(e);break;
    case Sima.Map.ActionType.ZoomLive: break;
  }
  return false;
};
pro.mousemove = function(e) {
  if (!e) var e = window.event;
  var targ = this.getEventTarget(e);
  if(targ.tagName.toLowerCase()=="area") return false;
  var position = this.getPosition(e);
  var oMap = this;

  this.mousemoved=true;
  switch(this.actionType) {
    case Sima.Map.ActionType.MoveMap: this.onMouseMoveMoveMap(e);break;
    case Sima.Map.ActionType.ZoomBox: this.onMouseMoveZoomBox(e);break;
    case Sima.Map.ActionType.ZoomLive: break;
  }
  
  if(e.preventDefault) e.preventDefault();
  return false;
};
pro.mouseup = function(e) {
  if (!e) var e = window.event;
  var targ = this.getEventTarget(e);
  if(targ.tagName.toLowerCase()=="area") return false;
  var oMap = this;
  document.onmousemove=null;
  document.onmouseup=null;

  switch(this.actionType) {
    case Sima.Map.ActionType.MoveMap: this.onMouseUpMoveMap(e);break;
    case Sima.Map.ActionType.ZoomBox: this.onMouseUpZoomBox(e);break;
    case Sima.Map.ActionType.ZoomLive: break;
    case Sima.Map.ActionType.Pan: this.onClickPan(e);break;
    case Sima.Map.ActionType.ZoomIn: this.onClickPanZoomIn(e);break;
    case Sima.Map.ActionType.ZoomOut: this.onClickPanZoomOut(e);break;
    case Sima.Map.ActionType.DrawPoint: this.onClickDrawPoint(e);break;
    case Sima.Map.ActionType.DrawPolygon: this.onClickDrawPolygon(e);break;
    case Sima.Map.ActionType.DrawRectangle: this.onClickDrawRectangle(e);break;
    case Sima.Map.ActionType.DrawCircle: this.onClickDrawCircle(e);break;
    case Sima.Map.ActionType.DrawLine: break;
  }

  
  if(e.preventDefault) e.preventDefault();
  return false;
};
pro.keydown = function(e) {
  if (!e) var e = window.event
  var position = this.getPosition(e);

  if(e.preventDefault) e.preventDefault();
  return false;
};


pro.onClickPan = function(e) {
  var position = this.getPosition(e);
  var coordinate = this.pixel2coordinate(position);
  this.setCoordinate(coordinate);
};
pro.onClickPanZoomIn = function(e) {
  var position = this.getPosition(e);
  var coordinate = this.pixel2coordinate(position);
  this.zoomIn(coordinate);
};
pro.onClickPanZoomOut = function(e) {
  var position = this.getPosition(e);
  var coordinate = this.pixel2coordinate(position);
  this.zoomOut(coordinate);
};
pro.onClickDrawPoint = function(e) {
  var position = this.getPosition(e);
  this.selection.start(Sima.Map.SelectionType.Point,position);
  this.selection.end();
};
pro.onClickDrawCircle = function(e) {
  var position = this.getPosition(e);
  var coordinate = this.pixel2coordinate(position).round();
  var oMap = this;
  if(this.selection.state==Sima.Map.SelectionState.Selecting) {
    this.selection.polygon.push(coordinate);
    this.selection.end();
    document.onmousemove=null;
  } else {
    this.selection.start(Sima.Map.SelectionType.Circle,position);
  }
  document.onmousemove=function(e) {return oMap.onMouseMoveDrawPolygon.call(oMap,e);};
};  
pro.onClickDrawRectangle = function(e) {
  var position = this.getPosition(e);
  var coordinate = this.pixel2coordinate(position).round();
  var oMap = this;
  if(this.selection.state==Sima.Map.SelectionState.Selecting) {
    this.selection.polygon.push(coordinate);
    this.endSelection();
    document.onmousemove=null;
  } else {
    this.selection.start(Sima.Map.SelectionType.Rectangle, position);
  }
  document.onmousemove=function(e) {return oMap.onMouseMoveDrawPolygon.call(oMap,e);};
};  
pro.onClickDrawLine = function(e) {};
pro.onClickDrawPolygon = function(e) {
  var position = this.getPosition(e);
  var coordinate = this.pixel2coordinate(position).round();
  var oMap = this;
  if(this.selection.state==Sima.Map.SelectionState.Selecting) {
    this.selection.polygon.push(coordinate);
    this.selection.drawArea();   
  } else {
    this.startSelection(Sima.Map.SelectionType.Polygon, position);

    this.selection.startPoint.onclick = function(e) {
      if (!e) var e = window.event;
      window.clearInterval(oMap.timer);
      oMap.selection.polygon.push(coordinate);
      oMap.selection.end();
      document.onmousemove=null;
      if(e.preventDefault) e.preventDefault();
      return false;
    };


  }
  document.onmousemove=function(e) {return oMap.onMouseMoveDrawPolygon.call(oMap,e);};
};  
  
pro.onMouseMoveDrawPolygon = function(e) {
if (!e) var e = window.event;
this.currentPosition = this.getPosition(e);
if(e.preventDefault) e.preventDefault();
return false;
};


pro.endSelection=function() {
  this.selection.end();
}

pro.clearSelection = function() {
  this.selection.clear();
}
pro.startSelection=function(selectionType, position) {
  this.selection.start(selectionType, position);
}


pro.onMouseDownMoveMap = function(e) {}
pro.onMouseMoveMoveMap = function(e) {
  var point = this.getPosition(e).sub(this.startPosition);
  var imagestyle = this.elementContent.style;
  imagestyle.left = point.x+'px';
  imagestyle.top = point.y+'px';
};
pro.onMouseUpMoveMap = function(e) {
  if(this.mousemoved) {
    this.setCoordinate(this.coordinate.sub(this.pixel2coordinate(this.getPosition(e)).sub(this.pixel2coordinate(this.startPosition))))
  } else {
  //  this.setCoordinate(this.pixel2coordinate(this.getPosition(e)));
  }
;}


pro.onMouseDownZoomBox = function(e) {
  this.deactivateLocations();
}
pro.onMouseMoveZoomBox = function(e) {
  var position = this.getPosition(e);
  var rect = this.getZoomBox(this.startPosition, position,this.getAspectRatio());
  this.zoombox = this.drawingCanvas.drawRectangle("SimaMapZoomBox", rect, this.zoombox);
};
pro.onMouseUpZoomBox = function(e) {
  this.activateLocations();
  var position = this.getPosition(e);
  this.drawingCanvas.removeDrawing(this.zoombox);
  this.zoombox = null;
  var rect = this.getZoomBox(this.startPosition, position, this.getAspectRatio());
  if(this.mousemoved&&(rect.xmax-rect.xmin)>8&&(rect.ymax-rect.ymin)>8) {
    this.setExtent(this.pixelX2coordinateX(rect.xmin), this.pixelY2coordinateY(rect.ymax), this.pixelX2coordinateX(rect.xmax), this.pixelY2coordinateY(rect.ymin));
  } else {
  //  this.setCoordinate(this.pixel2coordinate(position));
  }
};
pro.getZoomBox = function(startPosition, position, ratio) {
  var width = position.x-startPosition.x;
  var height = position.y-startPosition.y;
  if(Math.abs(width/height)>ratio) {
    position.y = startPosition.y + (((height>0)?1:-1) * Math.abs(Math.round(width/ratio)));
  } else {
    position.x = startPosition.x + (((width>0)?1:-1 )* Math.abs(Math.round(height*ratio)));
  }
  return new Sima.Graphics.Rect(startPosition.x, startPosition.y, position.x, position.y);
};

pro.getAbsolutePosition = function(e) {
  var clickposx = 0;
  var clickposy = 0;
  if (e.pageX || e.pageY)
  {
    clickposx = e.pageX;
    clickposy = e.pageY;
  }
  else if (e.clientX || e.clientY)
  {
    clickposx = e.clientX + document.body.scrollLeft;
    clickposy = e.clientY + document.body.scrollTop;
  }
  return new Sima.Graphics.Point(clickposx, clickposy);
};

pro.getPosition = function(e, targ) {
  if(typeof(targ)!="object") targ = this.elementBackground;
  var position = this.getAbsolutePosition(e);
  return new Sima.Graphics.Point(
    position.x-Sima.Tools.findPosX(targ),
    position.y-Sima.Tools.findPosY(targ));
};

pro.getEventTarget=function(e){
  var targ;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;
  if (targ.nodeType == 3) // defeat Safari bug
    targ = targ.parentNode;
  return targ;
};

pro.refresh = function() {
  if(!this.rendered) return;
  var url = this.scriptbase + "/SimaMap.asp?CoordinateX="+this.coordinate.x+
                                          "&CoordinateY="+this.coordinate.y+
                                          "&Zoomlevel="+this.zoomlevel+
                                          "&Scale="+this.scale+
                                          "&Cartography="+this.cartography+
                                          "&Width="+this.width+
                                          "&Height="+this.height+
                                          "&RegionMapWidth="+this.regionMap.width+
                                          "&RegionMapHeight="+this.regionMap.height;/*+
                                          "&Callback=Sima.Map['"+this.id+"'].update&"+
                                          (new Date()).getTime()
  var scriptID = 'SimaMapScript$' + Sima.Map.nextscriptid++;
  var scriptObj = document.createElement("script");
  scriptObj.setAttribute("type", "text/javascript");
  scriptObj.setAttribute("charset", "utf-8");
  scriptObj.setAttribute("src", url);
  scriptObj.setAttribute("id", scriptID);
  this.elementScript = scriptObj;
  this.elementHead.appendChild(scriptObj);*/
  var obj = this;
  Sima.Remote.call(url, function(e) {obj.update(e);}, 2000);
};

pro.update=function(e) {
  if(!e) return;
  this.browseMapImageSRC = e.BrowseMapImage;
  this.printMapImageSRC = e.PrintMapImage;
  this.regionMapImageSRC = e.RegionMapImage;
  var BrowseImage = this.elementBrowseImage;
  var obj = this;
  obj.locationLayers.getLayers();
  this.setCopyright();
  BrowseImage.onload = function() {
    obj.elementContent.style.top="0px";
    obj.elementContent.style.left="0px";
    obj.locationLayers.showLayers();
    obj.selection.drawArea();
  };
  this.fireUpdateEvent(new Sima.Map.UpdateEvent());
  BrowseImage.src = this.getImageSRC();
  //this.elementHead.removeChild(this.elementScript);
  this.regionMap.refresh();
}

pro.createTooltip=function(tooltip) {
  var box;
  box = document.createElement("div");
  box.className = "SimaMapToolbarTooltip";
  box.style.top = this.border+this.toolbar.height+2+"px";
  box.style.left = this.border+2+"px";
  var text=
    "<table cellspacing='0' cellpadding='0' width='100%' height='100%'>"+
     "<tr>"+
      "<td class='SimaMapToolbarTooltipCorner SimaMapToolbarTooltipCornerNW'></td>"+
      "<td class='SimaMapToolbarTooltipBorder SimaMapToolbarTooltipBorderN'>&nbsp;</td>"+
      "<td class='SimaMapToolbarTooltipCorner SimaMapToolbarTooltipCornerNE'></td>"+
     "</tr>"+
     "<tr>"+
      "<td class='SimaMapToolbarTooltipBorder SimaMapToolbarTooltipBorderW'>&nbsp;</td>"+
      "<td class='SimaMapToolbarTooltipContent'>"+tooltip+"</td>"+
      "<td class='SimaMapToolbarTooltipBorder SimaMapToolbarTooltipBorderE'>&nbsp;</td>"+
     "</tr>"+
     "<tr>"+
      "<td class='SimaMapToolbarTooltipCorner SimaMapToolbarTooltipCornerSW'></td>"+
      "<td class='SimaMapToolbarTooltipBorder SimaMapToolbarTooltipBorderS'>&nbsp;</td>"+
      "<td class='SimaMapToolbarTooltipCorner SimaMapToolbarTooltipCornerSE'></td>"+
     "</tr>"+
    "</table>"
  box.innerHTML=text;
  return box;
}
/***********************************
 * Class: Sima.Map.LocationLayer
 ***********************************/
Sima.Map.LocationLayer=function(name, layer) {this.name=name;this.layer=layer;this.locations=new Array();this.active=true;this.hidden=false;this.elementLayer=null;};
pro=Sima.Map.LocationLayer.prototype;
pro.show=function() {this.hidden=false;this.update();this.layers.map.fireLayerEvent(new Sima.Map.LayerEvent(Sima.Map.LayerEventType.Show, this.name));};
pro.hide=function() {this.hidden=true;this.update();this.layers.map.fireLayerEvent(new Sima.Map.LayerEvent(Sima.Map.LayerEventType.Hide, this.name));};
pro.activate=function() {this.active=true;this.update();this.layers.map.fireLayerEvent(new Sima.Map.LayerEvent(Sima.Map.LayerEventType.Activate, this.name));};
pro.deactivate=function() {this.active=false;this.update();this.layers.map.fireLayerEvent(new Sima.Map.LayerEvent(Sima.Map.LayerEventType.Deactivate, this.name));};
pro.update=function() {
  for(var i=0;i<this.locations.length;i++) {
    var location = this.locations[i];
    if(this.hidden) {
      location.hide();
      location.deactivate();
    } else if(this.active) {
      location.show();
      location.activate();
    } else {
      location.show();
      location.deactivate();
    }
    if(this.active) location.activate();
  }; 
};
pro.showLocations = function() {
  var elementMap = this.layers.elementMap;
  var element = document.createElement("div");
  if(!this.hidden) {
    for(var i=0;i<this.locations.length;i++) {
      var location = this.locations[i];
      element.appendChild(location.elementImage);
      location.show();
      if(this.active) location.activate();
    };
  };
  
  if(this.elementLayer) {
    this.layers.element.replaceChild(element,this.elementLayer);
  } else {
    this.layers.element.appendChild(element);
  }
  this.elementLayer = element;
};
pro.getLocations = function() {
  while(this.locations.length>0) {
    var location = this.locations.pop();
    location.deactivate();
  }
  var map = this.layers.map;
  if(typeof(this.layer) == "function") {
    var locations = this.layer(
      'RECT'+map.getExtentXmin()+','+map.getExtentYmin()+','+map.getExtentXmax()+','+map.getExtentYmax(),
      map.selection.getSelection());
    for(var i=0;i<locations.length;i++) {
          this.locations.push(new Sima.Map.Location(
            locations[i].x,
            locations[i].y,
            locations[i].doturl,
            locations[i].infourl,
            locations[i].linkurl,
            infowidth,
            infoheight,
            this,
            locations[i].width,
            locations[i].height,
            locations[i].onrender));
    }  
  } else {
    if(!this.layer) return;
    var url = this.layer+((this.layer.indexOf('?')==-1)?'?':'&');
    var selection = map.selection.getSelection();
    if(selection!='') url+=('selection='+selection+'&');
    url+='extent=RECT'+map.getExtentXmin()+','+map.getExtentYmin()+','+map.getExtentXmax()+','+map.getExtentYmax();
    var xml = LoadXML(url);
    if(xml.status==200) {
      var l = xml.responseXML.selectSingleNode("locations");
      var infoheight = l.getAttribute("infoheight");
      var infowidth = l.getAttribute("infowidth");
      if(l) {
        var locations = l.selectNodes("location");
        for(var i=0;i<locations.length;i++) {
          this.locations.push(new Sima.Map.Location(
            locations[i].getAttribute("x"),
            locations[i].getAttribute("y"),
            locations[i].getAttribute("doturl"),
            locations[i].getAttribute("infourl"),
            locations[i].getAttribute("linkurl"),
            infowidth,
            infoheight,
            this,
            locations[i].getAttribute("width"),
            locations[i].getAttribute("height"),
            locations[i].getAttribute("onrender")));
        }
      }
    }
  }
  map.fireLayerEvent(new Sima.Map.LayerEvent(Sima.Map.LayerEventType.Loaded, this.name));
};

/***********************************
 * Class: Sima.Map.Location
 ***********************************/
Sima.Map.Location=function(x, y, doturl, infourl, linkurl, infoboxwidth, infoboxheight,layer, width, height, onrender) {this.x=x;this.y=y;this.linkurl=linkurl;this.infourl=infourl;this.doturl=doturl;this.infoboxwidth=infoboxwidth;this.infoboxheight=infoboxheight;this.width=(width)?width:0;this.height=(height)?height:0;this.onrender=(onrender)?onrender:null;this.active=false;this.elementInfoBox=null;this.elementImage=null;this.elementArea=null;this.layer=layer;this.createImage();};
pro=Sima.Map.Location.prototype;
pro.hide=function() {this.elementImage.style.visibility = "hidden";};
pro.show=function() {this.elementImage.style.visibility = "visible";};
pro.activate=function() {if(this.active||!this.elementArea) return;this.active=true;this.layer.layers.elementMap.appendChild(this.elementArea);};
pro.deactivate=function() {if(!this.active||!this.elementArea) return;this.active=false;this.layer.layers.elementMap.removeChild(this.elementArea);};
pro.createImage=function() {
  if(this.elementImage) return
  var map = this.layer.layers.map;
  var location = this;
  var width = map.meter2pixel(this.width);
  var height = map.meter2pixel(this.height)
  this.exact = (height==0&&width==0);
  if((width<=10 && height<=10)) {
    var image = document.createElement("img");
    image.className = "SimaMapLocation";
    image.style.visibility = "hidden";
    location.xCenter = map.coordinateX2pixelX(this.x);
    location.yCenter = map.coordinateY2pixelY(this.y);
    image.onload = function(e) {
      location.xMin = location.xCenter-(this.width/2);
      location.yMin = location.yCenter-(this.height/2);
      location.xMax = location.xCenter+(this.width/2);
      location.yMax = location.yCenter+(this.height/2);
      this.style.left = location.xMin + 'px';
      this.style.top = location.yMin + 'px';
      location.createArea();
      if(location.onrender) location.onrender(location);
    };
    this.type = "point";
    image.src = this.doturl;
    this.elementImage = image;
  } else {
    var image = document.createElement("div");
    image.className = "SimaMapLocationArea";
    image.style.visibility = "hidden";
    location.xCenter = map.coordinateX2pixelX(this.x);
    location.yCenter = map.coordinateY2pixelY(this.y);
    location.xMin = location.xCenter-(width/2);
    location.yMin = location.yCenter-(height/2);
    location.xMax = location.xCenter+(width/2);
    location.yMax = location.yCenter+(height/2);
    image.style.left = location.xMin + 'px';
    image.style.top = location.yMin + 'px';
    image.style.width = width + 'px';
    image.style.height = height + 'px';
    this.elementImage = image;
    this.type = "area";
    if(location.onrender) location.onrender(location);
  } 
};
pro.getInfoBox=function() {
  if(!this.elementInfoBox) {
    var map = this.layer.layers.map;
    var infobox = document.createElement("iframe");
    infobox.className = "SimaMapInfoBox";
    infobox.allowTransparency="true";
    infobox.style.height = (this.infoboxheight)?(this.infoboxheight+"px"):"200px";
    infobox.style.width = (this.infoboxwidth)?(this.infoboxwidth+"px"):"200px";
    infobox.style.top = map.border+map.toolbar.height+2+"px";
    if(this.xMin<(map.width/2)) {
      infobox.style.right = map.border+2+"px";
    } else {
      infobox.style.left = map.border+2+"px";
    }
    infobox.frameBorder = 0;
    infobox.border=0;
    infobox.scrolling = "no";
    infobox.src = this.infourl;
    this.elementInfoBox = infobox;
  }
  return this.elementInfoBox;
};
pro.createArea=function() {
  if(this.elementArea||this.width!=0||this.height!=0) return;
  var map=this.layer.layers.map;
  var location=this;
  var area = document.createElement("area");
  area.shape="rect";
  if(this.linkurl) {
    area.href=this.linkurl;
  }
  area.border=0;
  area.alt="";
  var infobox=null;
  if(this.infourl) {
    area.onmouseover=function(e) {
      if (!e) var e = window.event
      var targ;
      if (e.target) targ = e.target;
      else if (e.srcElement) targ = e.srcElement;
      if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
      if (targ.tagName.toLowerCase()!="area") return false;
      infobox = location.getInfoBox()
      map.element.appendChild(infobox);
    };
    area.onmouseout=function(e) {
      if(infobox) {
        map.element.removeChild(infobox);
        infobox = null;
      }
    };
    area.onclick=area.onmouseout;
  }
  this.elementArea = area;
  this.elementArea.coords=this.xMin+","+this.yMin+","+this.xMax+","+this.yMax;
};


/***********************************
 * Class: Sima.Map.LocationLayers
 ***********************************/
Sima.Map.LocationLayers=function() {this.layers=new Array();};
pro = Sima.Map.LocationLayers.prototype;
pro.render = function() {
  this.id = this.map.id+"$LocationLayers";
  document.write("<div class='SimaMapLocationLayers'"+
                     " id='"+this.id+"'>"+
                 "</div>");
  this.element = Sima.Tools.getElement(this.id);
};
pro.renderMap = function() {
  this.id = this.map.id+"$LocationLayers";
  document.write(
  "<img class='SimaMapLocationsMapImage'"+
   " id='"+this.id+"$MapImage'"+
   " width='100%'"+
   " height='100%'"+
   " alt=''"+
   " src='"+this.map.tp+"'"+
   " usemap='#"+this.id+"$Map'"+
   " border='0'/>"+
  "<map name='"+this.id+"$Map'"+
   " id='"+this.id+"$Map'>"+
  "</map>");
  this.elementMap = Sima.Tools.getElement(this.id+"$Map");
  this.elementMapImage = Sima.Tools.getElement(this.id+"$MapImage");
};
pro.addLayer=function(name, layer) {var olayer = new Sima.Map.LocationLayer(name, layer);olayer.layers = this;this.layers.push(olayer);}; 
pro.activate=function() {this.elementMapImage.useMap="#"+this.elementMap.name;};
pro.deactivate=function(){this.elementMapImage.useMap=null;};
pro.getLayers=function(){for(var i=0;i<this.layers.length;i++) this.layers[i].getLocations();};
pro.showLayers=function(){for(var i=0;i<this.layers.length;i++) this.layers[i].showLocations();};
pro.findLayer=function(name) {for(var i=0;i<this.layers.length;i++) if(this.layers[i].name==name) return this.layers[i];return null;}
pro.hideLayer=function(name) {var layer=this.findLayer(name);if(layer) layer.hide();};
pro.showLayer=function(name) {var layer=this.findLayer(name);if(layer) layer.show();};
pro.activateLayer=function(name) {var layer=this.findLayer(name);if(layer) layer.activate();};
pro.deactivateLayer=function(name) {var layer=this.findLayer(name);if(layer) layer.deactivate();};

/***********************************
 * Class: Sima.Map.Selection
 ***********************************/
Sima.Map.Selection = function() {
  this.selectionType=Sima.Map.SelectionType.None;
  this.lastPosition=new Sima.Graphics.Point(0,0);
  this.startPoint=null;
  this.tempSelectionTimer=null;
  this.selectionBoundary=null;
  this.selectionArea=null;
  this.state=Sima.Map.SelectionState.NoSelection;
};
pro = Sima.Map.Selection.prototype;

/****
 * Method: getSelectionCanvas
 ****/
pro.render = function() {
  var id = this.map.id+"$SelectionCanvas";
  document.write("<div class='SimaMapSelectionCanvas'"+
                    " id='"+id+"'>"+
                    "</div>");
  this.element = Sima.Tools.getElement(id);
  
  var selection = this;
  this.map.addActionEventListener(function(e) {if(selection.state==Sima.Map.SelectionState.Selecting) selection.clear();});
};

/****
 * Method: drawArea
 ****/
pro.drawArea = function() {
  if(this.state!=Sima.Map.SelectionState.HasSelection&&this.selectionArea) {
    this.map.drawingCanvas.removeDrawing(this.selectionArea);
    this.selectionArea=null;
  }
  if(this.state==Sima.Map.SelectionState.NoSelection&&this.selectionBoundary) {
    this.map.drawingCanvas.removeDrawing(this.selectionBoundary);
    this.selectionBoundary=null;
  }
  if(!this.polygon) return;
  switch(this.selectionType) {
  case Sima.Map.SelectionType.Polygon:
    var vertices = new Array();
    for(var i=0;i<this.polygon.length;i++) {
       var point = this.map.coordinate2pixel(this.polygon[i]);
       vertices.push(point);
    }
    if(this.state==Sima.Map.SelectionState.HasSelection) 
      this.selectionArea = this.map.drawingCanvas.drawPolygon("SimaMapDrawingArea", vertices, this.selectionArea);
    if(this.state!=Sima.Map.SelectionState.NoSelection)
      this.selectionBoundary = this.map.drawingCanvas.drawPolyLine("SimaMapDrawingLine", vertices, this.selectionBoundary);
    break;
  case Sima.Map.SelectionType.Rectangle:
    if(this.polygon.length<2) return;
    var p1 = this.map.coordinate2pixel(this.polygon[0]);
    var p2 = this.map.coordinate2pixel(this.polygon[1]);
    var rect =  new Sima.Graphics.Rect(p1.x, p1.y, p2.x, p2.y);
    if(this.state==Sima.Map.SelectionState.HasSelection)
      this.selectionArea = this.map.drawingCanvas.drawRectangle("SimaMapDrawingArea", rect, this.selectionArea);
    if(this.state!=Sima.Map.SelectionState.NoSelection)
      this.selectionBoundary = this.map.drawingCanvas.drawRectangle("SimaMapDrawingRect", rect, this.selectionBoundary);
    break;
  case Sima.Map.SelectionType.Circle:
    if(this.polygon.length<2) return;
    var p1 = this.map.coordinate2pixel(this.polygon[0]);
    var p2 = this.map.coordinate2pixel(this.polygon[1]);
    var radius = Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
    if(this.state==Sima.Map.SelectionState.HasSelection)
      this.selectionArea = this.map.drawingCanvas.drawDisc("SimaMapDrawingArea", p1, radius, this.selectionArea);
    if(this.state!=Sima.Map.SelectionState.NoSelection)
      this.selectionBoundary = this.map.drawingCanvas.drawCircle("SimaMapDrawingLine", p1, radius, this.selectionBoundary);
    break;
  case Sima.Map.SelectionType.Point:
    if(this.polygon.length<1) return;
    var p1 = this.map.coordinate2pixel(this.polygon[0]);
    if(this.state==Sima.Map.SelectionState.HasSelection)
      this.selectionArea = this.map.drawingCanvas.drawDisc("SimaMapDrawingPoint", p1, 6, this.selectionArea);
    if(this.state!=Sima.Map.SelectionState.NoSelection)
      this.selectionBoundary = this.map.drawingCanvas.drawCircle("SimaMapDrawingLine", p1, 6, this.selectionBoundary);
    break; 
  }
}

/****
 * Method: drawTempLine
 ****/
pro.drawTempLine = function() {
  var div = this.element.cloneNode(false);
  var parent = this.element.parentElement;
  if(!parent) parent = this.element.parentNode;
  while(!this.lastPosition.equals(this.map.currentPosition) && this.polygon) {
    this.lastPosition = this.map.currentPosition;
    Sima.Graphics.drawLine(div, "SimaMapSelectionLine", new Sima.Graphics.Line(this.map.coordinate2pixel(this.polygon[this.polygon.length-1]), this.map.currentPosition));
    parent.replaceChild(div, this.element);
    this.element = div;
  }
}

/****
 * Method: drawTempRect
 ****/
pro.drawTempRect = function() {
  var div = this.element.cloneNode(false);
  var parent = this.element.parentElement;
  if(!parent) parent = this.element.parentNode;
  while(!this.lastPosition.equals(this.map.currentPosition) && this.polygon) {
    this.lastPosition = this.map.currentPosition;
    var p1 = this.map.coordinate2pixel(this.polygon[this.polygon.length-1]);
    var p2 = this.map.currentPosition;
    Sima.Graphics.drawRectangle(div, "SimaMapSelectionRect", new Sima.Graphics.Rect(p1.x, p1.y, p2.x, p2.y));
    parent.replaceChild(div, this.element);
    this.element = div;
  }
}

/****
 * Method: drawTempRect
 ****/
pro.drawTempCirc = function() {
  var div = this.element.cloneNode(false);
  var parent = this.element.parentElement;
  if(!parent) parent = this.element.parentNode;
  while(!this.lastPosition.equals(this.map.currentPosition) && this.polygon) {
    this.lastPosition = this.map.currentPosition;
    var p1 = this.map.coordinate2pixel(this.polygon[this.polygon.length-1]);
    var p2 = this.map.currentPosition;
    var radius = Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
    Sima.Graphics.drawOval(div, "SimaMapSelectionLine", Math.round(p1.x-radius), Math.round(p1.y-radius), Math.round(2*radius), Math.round(2*radius));
    parent.replaceChild(div, this.element);
    this.element = div;
  }
}

pro.removeTempSelection = function() {
  if(this.tempSelectionTimer) window.clearInterval(this.tempSelectionTimer);
  this.tempSelectionTimer=null;
  
  var div = this.element.cloneNode(false);
  var parent = this.element.parentElement;
  if(!parent) parent = this.element.parentNode;
  parent.replaceChild(div, this.element);
  this.element = div;
  
  if(this.startPoint) {
    var startPoint = this.startPoint;
    this.startPoint = null;
    parent = startPoint.parentElement;
    if(!parent) parent = startPoint.parentNode;
    parent.removeChild(startPoint);
  }
}
pro.end = function() {
  this.removeTempSelection();
  this.state=Sima.Map.SelectionState.HasSelection;
  this.map.activateLocations();
  this.map.fireSelectionEvent(new Sima.Map.SelectionEvent(Sima.Map.SelectionEventType.End, this.getSelection()));
  this.drawArea();
}
pro.start = function(selectionType,position) {
  var map = this.map;
  map.deactivateLocations();
  this.clear();
  this.map.fireSelectionEvent(new Sima.Map.SelectionEvent(Sima.Map.SelectionEventType.Start, this.getSelection()));
  this.selectionType = selectionType;
  this.state=Sima.Map.SelectionState.Selecting;
  this.polygon = new Array();
  if(typeof(position)!="undefined") {
    var coordinate = map.pixel2coordinate(position).round();
    this.currentPosition = position;
    this.polygon.push(coordinate);
    this.showStartPoint(coordinate);
  }
  var selection = this;
  if(!this.tempSelectionTimer) this.tempSelectionTimer = window.setInterval(function() {selection.drawTemp.call(selection);}, 50);
  this.drawArea();
};
pro.drawTemp=function() {
  this.showStartPoint();
  switch(this.selectionType) {
    case Sima.Map.SelectionType.Polygon:    this.drawTempLine(); break;
    case Sima.Map.SelectionType.Rectangle:  this.drawTempRect(); break;
    case Sima.Map.SelectionType.Circle:     this.drawTempCirc(); break;
  }
}

pro.clear = function() {
  this.removeTempSelection();
  this.polygon=null;
  this.state=Sima.Map.SelectionState.NoSelection;
  this.drawArea();
  this.map.fireSelectionEvent(new Sima.Map.SelectionEvent(Sima.Map.SelectionEventType.Clear, this.getSelection()));
};

pro.showStartPoint = function() {
  if(!this.polygon) return;
  var map = this.map;
  var position = map.coordinate2pixel(this.polygon[0]);
  var startPoint
  if(!this.startPoint) {
    startPoint = document.createElement("img");
    startPoint.src = map.tp;
    startPoint.className="SimaMapStartPoint";
    this.startPoint = startPoint;
    map.element.appendChild(startPoint);
  } else {
    startPoint = this.startPoint;
  }
  startPoint.style.left = position.x - 5 + map.border + "px";
  startPoint.style.top = position.y - 5 + map.border+map.toolbar.height + "px";
}
/****
 * Method: getSelection
 ****/
pro.getSelection = function() {
  var selection = '';
  if(this.polygon) {
    switch(this.selectionType) {
    case Sima.Map.SelectionType.Polygon:
      if(this.polygon.length<4) break;
      selection+=this.selectionType+this.polygon[0].x+','+this.polygon[0].y;
      for(var i=1;i<this.polygon.length;i++) {
        selection+=','+this.polygon[i].x+','+this.polygon[i].y;
      }
      break;
    case Sima.Map.SelectionType.Rectangle:
      if(this.polygon.length!=2) break;
      selection+=this.selectionType+
        ((this.polygon[0].x<this.polygon[1].x)?this.polygon[0].x:this.polygon[1].x)+','+
        ((this.polygon[0].y<this.polygon[1].y)?this.polygon[0].y:this.polygon[1].y)+','+
        ((this.polygon[0].x>this.polygon[1].x)?this.polygon[0].x:this.polygon[1].x)+','+
        ((this.polygon[0].y>this.polygon[1].y)?this.polygon[0].y:this.polygon[1].y);
      break;
    case Sima.Map.SelectionType.Circle:
      if(this.polygon.length!=2) break;
      var r=Math.round(Math.sqrt((this.polygon[0].x-this.polygon[1].x)*(this.polygon[0].x-this.polygon[1].x)+(this.polygon[0].y-this.polygon[1].y)*(this.polygon[0].y-this.polygon[1].y)));
      selection+=this.selectionType+
        (this.polygon[0].x-r)+','+
        (this.polygon[0].y-r)+','+
        (this.polygon[0].x+r)+','+
        (this.polygon[0].y+r);
      break;
    case Sima.Map.SelectionType.Point:
      if(this.polygon.length!=1) break;
      selection+=this.selectionType+this.polygon[0].x+','+this.polygon[0].y;
      break;
    }
  }
  return selection;
}

/****
 * Method getSelectionType
 ****/
pro.getSelectionType = function() {return this.selectionType;};

/***********************************
 * Class: Sima.Map.NavigationPanel
 ***********************************/
Sima.Map.NavigationPanel = function() {};
pro = Sima.Map.NavigationPanel.prototype;

/****
 * Method: getInnerBorder
 ****/
pro.renderInnerBorder = function(name) {
  document.write("<div class='SimaMapInnerBorder SimaMapInnerBorder" + name + "'>"+
                 "</div>");
};

/****
 * Method: getInnerBorders
 ****/
pro.renderInnerBorders = function() {
  this.renderInnerBorder("NorthWest");
  this.renderInnerBorder("NorthEast");
  this.renderInnerBorder("SouthWest");
  this.renderInnerBorder("SouthEast");
};

/****
 * Method: getNavigationCell
 ****/
pro.getNavigationCell = function(direction) {
  var map = this.map;
  document.write(
  "<td class='SimaMapNavigationBorder SimaMapNavigationBorder" + direction + "'" +
     " id='"+map.id+"$Navigation$"+direction+"'" +
     " style='cursor:pointer;cursor:hand;'>" +
    "<div class='SimaMapOuterBorder SimaMapOuterBorder" + direction + "'>&nbsp;</div>" +
  "</td>");
  Sima.Tools.getElement(map.id+"$Navigation$"+direction).onclick=function(e) {return map.pan(direction);};
};

/****
 * Method: getNavigationPanel
 ****/
pro.render = function() {                           
  document.write("<table id='Navigation' cellspacing='0' cellpadding='0' height='100%' width='100%'>");
  document.write("<tr>");
  this.getNavigationCell("NorthWest");
  this.getNavigationCell("North");
  this.getNavigationCell("NorthEast");
  document.write("</tr><tr>");
  this.getNavigationCell("West");
  document.write("<td></td>");
  this.getNavigationCell("East");
  document.write("</tr><tr>");
  this.getNavigationCell("SouthWest");
  this.getNavigationCell("South");
  this.getNavigationCell("SouthEast");
  document.write("</tr>");
  document.write("</table>");
};

/***********************************
 * Class: Sima.Map.RegionMap
 ***********************************/
Sima.Map.RegionMap = function() {};
pro = Sima.Map.RegionMap.prototype;

/****
 * Method: getImageSRC
 ****/
pro.getImageSRC = function() {
  return this.map.getRegionImageSRC();
  return "Http://80.63.32.218/fms_om/Map_region.aspx?mtwBBOX="+Math.round(this.map.pixelX2coordinateX(0))+","+Math.round(this.map.pixelY2coordinateY(this.map.height))+","+Math.round(this.map.pixelX2coordinateX(this.map.width))+","+Math.round(this.map.pixelY2coordinateY(0))+"&WIDTH=100&HEIGHT=80&mtwAREA=45&BBOX=430000,6045000,905000,6425000&mtwSTYLE=20&u=sima";
};

/****
 * Method: getRegionMap
 ****/
pro.render = function() {
  var id = this.map.id+"$RegionMap";
  var imageid = this.map.id+"$RegionImage";
  document.write("<div class='SimaMapRegionMap'"+
                     " style='width:100px;"+
                             "height:80px;'"+
                     " id='"+id+"'>"+
                   "<img class='SimaMapRegionImage' id='"+imageid+"' width='100%' height='100%' src='" + /*this.getImageSRC()*/ this.map.tp + "' alt=''/>"+
                 "</div>");
  this.element = Sima.Tools.getElement(id);
  this.elementImage = Sima.Tools.getElement(imageid);
};

/****
 * Method: refresh
 ****/
pro.refresh = function() {
  this.elementImage.src = this.getImageSRC();
  if(this.map.getZoomlevel()>7||this.map.displayRegionMap==false) {
    this.element.style.display="none";
  } else {
    this.element.style.display="block";
  }
}

/***********************************
 * Class: Sima.Map.DrawingCanvas
 ***********************************/
Sima.Map.DrawingCanvas=function(){};
pro = Sima.Map.DrawingCanvas.prototype;
 
/****
 * Method: getDrawingCanvas
 ****/
pro.render = function() {
  this.id = this.map.id+"$DrawingCanvas";
  document.write("<div class='SimaMapDrawingCanvas'"+
                     " id='"+this.id+"'>"+
                 "</div>");
  this.element = Sima.Tools.getElement(this.id);
};

pro.drawRectangle = function(className, rect, element) {
  var div = document.createElement("div");
  Sima.Graphics.drawRectangle(div, className, rect, new Sima.Graphics.ClipRect(new Sima.Graphics.Rect(0, 0, this.map.width, this.map.height)));
  if(element && typeof(element)=="object") {
    this.element.replaceChild(div, element);
  } else {
    this.element.appendChild(div);
  }
  return div;
}
  
pro.drawPolygon = function(className, vertices, element) {
  var div = document.createElement("div");
  Sima.Graphics.drawPolygon(div, className, vertices, new Sima.Graphics.ClipRect(new Sima.Graphics.Rect(0, 0, this.map.width, this.map.height)));
  if(typeof(element)=="object"&&element) {
    this.element.replaceChild(div, element);
  } else {
    this.element.appendChild(div);
  }
  return div;
}

pro.drawCircle = function(className, point, radius, element) {
  var div = document.createElement("div");
  Sima.Graphics.drawOval(div, className, Math.round(point.x-radius),Math.round(point.y-radius), Math.round(2*radius), Math.round(2*radius), new Sima.Graphics.ClipRect(new Sima.Graphics.Rect(0, 0, this.map.width, this.map.height)));
  if(typeof(element)=="object"&&element) {
    this.element.replaceChild(div, element);
  } else {
    this.element.appendChild(div);
  }
  return div;
}

pro.drawDisc = function(className, point, radius, element) {
  var div = document.createElement("div");
  Sima.Graphics.drawDisc(div, className, Math.round(point.x-radius),Math.round(point.y-radius), Math.round(2*radius), Math.round(2*radius), new Sima.Graphics.ClipRect(new Sima.Graphics.Rect(0, 0, this.map.width, this.map.height)));
  if(typeof(element)=="object"&&element) {
    this.element.replaceChild(div, element);
  } else {
    this.element.appendChild(div);
  }
  return div;
}

pro.drawPolyLine = function(className, vertices, element) {
  var div = document.createElement("div");
  Sima.Graphics.drawPolyLine(div, className, vertices, new Sima.Graphics.ClipRect(new Sima.Graphics.Rect(0, 0, this.map.width, this.map.height)));
  if(typeof(element)=="object"&&element) {
    this.element.replaceChild(div, element);
  } else {
    this.element.appendChild(div);
  }
  return div;
}

pro.removeDrawing = function(element) {
  if(element) this.element.removeChild(element);
}

/***********************************
 * Class: Sima.Map.Toolbar
 ***********************************/
Sima.Map.Toolbar=function(){this.height=30;this.toolbarGroups=new Array();this.design="{MoveMap}|{ZoomBox}|{DrawRectangle,DrawCircle,DrawPolygon}|ZoomPanel|Cartography"};
pro = Sima.Map.Toolbar.prototype;
pro.addToolbarGroup=function(toolbarGroup) {
  toolbarGroup.toolbar = this;
  this.toolbarGroups.push(toolbarGroup);
};

pro.render=function() {
  this.id=this.map.id+"$Toolbar";
  document.write(
  "<div class='SimaMapToolbarArea'"+
      " style='left:"+this.map.border+"px;"+
              "top:"+this.map.border+"px;"+
              "width:"+this.map.width+"px;"+
              "height:"+this.height+"px;'>"+
  "<div class='SimaMapToolbar'"+
      " id='"+this.id+"'>");
  this.map.navigationPanel.renderInnerBorder("NorthWest");
  this.map.navigationPanel.renderInnerBorder("NorthEast");
  document.write("<div class='SimaMapToolbarGroupSeparator'>&nbsp;</div>");
  var tokens = this.design.match(/(\{|\}|\||[^\{\}\|]+)/g);
  var toolbarGroup;
  for(var i=0;i<tokens.length;i++) {
    switch(tokens[i]) {
      case "{":
        toolbarGroup = new Sima.Map.ToolbarGroup("");
        break;
      case "}":
        this.addToolbarGroup(toolbarGroup);
        toolbarGroup.render();
        toolbarGroup = null;
        break;
      case "|":
        document.write("<div class='SimaMapToolbarGroupSeparator'>&nbsp;</div>");
        break;
      default:
        var items = tokens[i].split(/,/);
        for(var j=0;j<items.length;j++) {
          switch(items[j].toLowerCase()) {
            case "movemap":       toolbarGroup.addToolbarIcon(new Sima.Map.ToolbarIcon("MoveMap", Sima.Map.ActionType.MoveMap, Sima.Map.Text.MoveMap));break;
            case "zoombox":       toolbarGroup.addToolbarIcon(new Sima.Map.ToolbarIcon("ZoomBox", Sima.Map.ActionType.ZoomBox, Sima.Map.Text.ZoomBox));break;
            case "pan":           toolbarGroup.addToolbarIcon(new Sima.Map.ToolbarIcon("Pan", Sima.Map.ActionType.Pan, Sima.Map.Text.Pan));break;
            case "drawrectangle": toolbarGroup.addToolbarIcon(new Sima.Map.ToolbarIcon("DrawRectangle", Sima.Map.ActionType.DrawRectangle, Sima.Map.Text.DrawRectangle));break;
            case "drawcircle":    toolbarGroup.addToolbarIcon(new Sima.Map.ToolbarIcon("DrawCircle", Sima.Map.ActionType.DrawCircle, Sima.Map.Text.DrawCircle));break;
            case "drawpolygon":   toolbarGroup.addToolbarIcon(new Sima.Map.ToolbarIcon("DrawPolygon", Sima.Map.ActionType.DrawPolygon, Sima.Map.Text.DrawPolygon));break;
            case "drawpoint":     toolbarGroup.addToolbarIcon(new Sima.Map.ToolbarIcon("DrawPoint", Sima.Map.ActionType.DrawPoint, Sima.Map.Text.DrawPoint));break;
            case "zoompanel":     this.zoompanel=new Sima.Map.ToolbarZoomPanel();this.zoompanel.toolbar=this;this.zoompanel.render();break;
            case "cartography":   this.cartography=new Sima.Map.Cartography();this.cartography.toolbar=this;this.cartography.render();break;
          }
        }
        break;
    }
  }
  document.write("</div></div>");
};

Sima.Map.ToolbarGroup=function(name) {
  this.name=name;
  this.toolbarIcons=new Array();
};
pro=Sima.Map.ToolbarGroup.prototype;
pro.renderCorner=function(name) {
  document.write("<div class='SimaMapToolbarGroupCorner SimaMapToolbarGroupCorner"+name+"'></div>");
}
pro.render=function() {
  document.write("<div class='SimaMapToolbarGroup'>");
  this.renderCorner("NW");
  this.renderCorner("NE");
  this.renderCorner("SW");
  this.renderCorner("SE");
  for(var i=0;i<this.toolbarIcons.length;i++) this.toolbarIcons[i].render();
  document.write("</div>");
}
pro.addToolbarIcon=function(toolbarIcon) {
  toolbarIcon.toolbarGroup=this;
  this.toolbarIcons.push(toolbarIcon);
};
Sima.Map.ToolbarIcon=function(name, actionType, tooltip) {
  this.name=name;
  this.actionType=actionType;
  this.tooltip=tooltip;
};
pro=Sima.Map.ToolbarIcon.prototype;
pro.render=function() {
  this.id=this.toolbarGroup.toolbar.id+"$"+this.name;
  document.write(
    "<div id='"+this.id+"$Background'"+
         " class='SimaMapToolbarIconBackground'>"+
     "<div  id='"+this.id+"$Icon'"+
          " class='SimaMapToolbarIcon SimaMapToolbarIcon"+this.name+"'></div>"+
    "</div>");
  this.elementBackground=Sima.Tools.getElement(this.id+"$Background");
  this.elementIcon=Sima.Tools.getElement(this.id+"$Icon");
  
  var map = this.toolbarGroup.toolbar.map;
  var toolbarIcon=this;
  this.elementIcon.onclick=function(e) {map.setAction(toolbarIcon.actionType);};
  var box
  this.elementIcon.onmouseover=function(e) {box = map.createTooltip(toolbarIcon.tooltip);var background = map.element;background.appendChild(box);};
  this.elementIcon.onmouseout=function(e) {var background = map.element;if(background.lastChild==box) background.removeChild(box);};
  
  map.addActionEventListener(
    function(e) {
      if(e.actionType==toolbarIcon.actionType) {
        if(e.eventType==Sima.Map.ActionEventType.Select) {
          toolbarIcon.elementBackground.className="SimaMapToolbarIconBackground SimaMapToolbarIconBackgroundActive";
        } else if(e.eventType==Sima.Map.ActionEventType.Deselect)  {
          toolbarIcon.elementBackground.className="SimaMapToolbarIconBackground";
        }
      }
    });
};



Sima.Map.ToolbarZoomPanel=function() {};
pro=Sima.Map.ToolbarZoomPanel.prototype;
pro.render=function() {
  var map = this.toolbar.map;
  document.write(
    "<div id='"+map.id+"$ZoomPanel' class='SimaMapZoomPanelBackground'>"+
     "<div class='SimaMapZoomPanelContent'>"+
      "<div id='"+map.id+"$ZoomPanel$ZoomOut' class='SimaMapZoomPanelZoomOut'></div>"+
      "<div class='SimaMapZoomPanelSlider'>"+
       "<div id='"+map.id+"$ZoomPanel$SliderContent' class='SimaMapZoomPanelSliderContent'>"+
        "<div id='"+map.id+"$ZoomPanel$Slider' class='SimaMapZoomPanelSliderMark'></div>"+
       "</div>"+
      "</div>"+
      "<div id='"+map.id+"$ZoomPanel$ZoomIn' class='SimaMapZoomPanelZoomIn'></div>"+
     "</div>"+
    "</div>");
  Sima.Tools.getElement(map.id+"$ZoomPanel").onmouseover=function(e) {box = map.createTooltip(Sima.Map.Text.ZoomPanel);var background = map.element;background.appendChild(box);};
  Sima.Tools.getElement(map.id+"$ZoomPanel").onmouseout=function(e) {var background = map.element;if(background.lastChild==box) background.removeChild(box);};
  Sima.Tools.getElement(map.id+"$ZoomPanel$ZoomOut").onclick=function(e) {map.setZoomlevel((map.getZoomlevel()<8)?map.getZoomlevel()+1:8);if (!e) var e = window.event;if(e.preventDefault) e.preventDefault();return false};
  Sima.Tools.getElement(map.id+"$ZoomPanel$ZoomIn").onclick=function(e) {map.setZoomlevel(map.getZoomlevel()-1);if (!e) var e = window.event;if(e.preventDefault) e.preventDefault();return false};
  var slider = Sima.Tools.getElement(map.id+"$ZoomPanel$Slider");
  var slidercontent = Sima.Tools.getElement(map.id+"$ZoomPanel$SliderContent");
  slider.style.left=(8-map.getZoomlevel())*6+"px";
  slidercontent.onclick=function(e) {
    if (!e) var e = window.event;
    var p = map.getPosition(e, slidercontent);
    var zoomlevel = 8-Math.floor(p.x/6);
    map.setZoomlevel(zoomlevel);
  }
  map.addZoomlevelEventListener(function(e) {slider.style.left=(8-e.zoomlevel)*6+"px";});
  slider.onmousedown=function(e) {
    if (!e) var e = window.event;
    slidercontent.startX = Sima.Tools.findPosX(slidercontent);
    document.onmousemove=function(e) {
      if (!e) var e = window.event;
      var p = map.getAbsolutePosition(e);
      var x = p.x-slidercontent.startX;
      if(x<-10) {
        slider.style.left=(8-map.getZoomlevel())*6+"px";
      } else if(x<0) {
        slider.style.left=0+"px";
      } else if(x>58) {
        slider.style.left=(8-map.getZoomlevel())*6+"px";
      } else if(x>48) {
        slider.style.left=48+"px";
      } else {
        slider.style.left=x-2+"px";
      }
      if(e.preventDefault) e.preventDefault();
      return false;
    };
    document.onmouseup=function(e) {
      if (!e) var e = window.event;
      var p = map.getAbsolutePosition(e);
      var x = p.x-slidercontent.startX;
      if(x<-10 || x>58) {
        slider.style.left=(8-map.getZoomlevel())*6+"px";
      } else {
        if(x<0) x=0;
        if(x>48) x=48;
        var zoomlevel = 8-Math.floor(x/6);
        map.setZoomlevel(zoomlevel);
      }
      slidercontent.startPoint = null;
      document.onmousemove=null;
      document.onmouseup=null;
      if(e.preventDefault) e.preventDefault();
      return false;
    };
    if(e.preventDefault) e.preventDefault();
    return false;
  };
};
Sima.Map.Cartography=function() {
  var cart=this;
  this.dropdown=new Sima.DropDown("SimaMapCartography");
  this.dropdown.setTitle(Sima.Map.Text.CartographyMapType);
  this.dropdown.showTitle(true);
  this.dropdown.addDropDownItem(new Sima.DropDownItem(Sima.Map.Text.CartographyMap, 10));
  this.dropdown.addDropDownItem(new Sima.DropDownItem(Sima.Map.Text.CartographyAirPhoto, 50));
  this.dropdown.addDropDownItem(new Sima.DropDownItem(Sima.Map.Text.CartographyCombined, 40));
  this.dropdown.addChangeListener(function(e) {cart.toolbar.map.setCartography(cart.dropdown.items[cart.dropdown.selectedIndex].value)});
};
pro=Sima.Map.Cartography.prototype;
pro.render=function() {
  var map = this.toolbar.map;
  switch(map.getCartography()) {
  case 10:this.dropdown.selectedIndex=0;break;
  case 50:this.dropdown.selectedIndex=1;break;
  case 40:this.dropdown.selectedIndex=2;break;
  }
  this.dropdown.id = this.toolbar.map.id+"$Cartography";
  this.dropdown.render();
  this.dropdown.element.onmouseover=function(e) {box = map.createTooltip(Sima.Map.Text.Cartography);var background = map.element;background.appendChild(box);};
  this.dropdown.element.onmouseout=function(e) {var background = map.element;if(background.lastChild==box) background.removeChild(box);};
}

Sima.DropDown=function(className, id) {this.id=id;this.showtitle=false;this.className=className;this.listbox=null;this.selectedIndex=0;this.items=new Array();this.listeners=new Array();};
pro=Sima.DropDown.prototype;
pro.renderCorner=function(name) {
  document.write("<div class='"+this.className+"DropDownCorner"+name+" "+this.className+"DropDownCorner'></div>");
}
pro.addChangeListener=function(listener) {
  this.listeners.push(listener);
}
pro.setTitle=function(title){this.title=title;};
pro.showTitle=function(showtitle){this.showtitle=showtitle;};
pro.render=function() {
  var dropdown = this;
  document.write("<div id='"+this.id+"$DropDown' class='"+this.className+"DropDown'>");
  this.renderCorner("NW");
  this.renderCorner("NE");
  this.renderCorner("SW");
  this.renderCorner("SE");
  document.write(
    "<div id='"+this.id+"$DropDownSelection' class='"+this.className+"DropDownSelection'>"+
    "<div id='"+this.id+"$DropDownSelectionText' class='"+this.className+"DropDownSelectionText'>"+((dropdown.showtitle)?dropdown.title:dropdown.items[dropdown.selectedIndex].name)+"</div>"+
    "</div>"+
    "<div class='"+this.className+"DropDownSeparator'>&nbsp;</div>"+
    "<div id='"+this.id+"$DropDownTarget' class='"+this.className+"DropDownTarget'></div>"+
   "</div>");
  this.elementSelectionText = Sima.Tools.getElement(this.id+"$DropDownSelectionText");
  this.elementSelection = Sima.Tools.getElement(this.id+"$DropDownSelection");
  this.element = Sima.Tools.getElement(this.id+"$DropDown");
  this.elementTarget = Sima.Tools.getElement(this.id+"$DropDownTarget");
  var onclick=function(e) {
    if (!e) var e = window.event;
    if(dropdown.listbox) {
      document.body.removeChild(dropdown.listbox);
      document.onmousedown=null;
      dropdown.listbox = null;
    } else {
      var ele = document.createElement("div");
      for(var i=0;i<dropdown.items.length;i++) if(i!=dropdown.selectedIndex||dropdown.showtitle==true) {ele.appendChild(dropdown.items[i].getElement());dropdown.items[i].setSelected(i==dropdown.selectedIndex);}
      ele.className = dropdown.className+"DropDownList";
      ele.style.top = Sima.Tools.findPosY(dropdown.element)+17+"px";
      ele.style.left = Sima.Tools.findPosX(dropdown.element)+"px";
      dropdown.listbox = ele;
      document.body.appendChild(ele);
      document.onmousedown=function(e) {
        if (!e) var e = window.event;
        var targ;
	      if (e.target) targ = e.target;
	      else if (e.srcElement) targ = e.srcElement;
	      if (targ.nodeType == 3) // defeat Safari bug
		      targ = targ.parentNode;
		    if(targ.id==dropdown.elementTarget.id||targ.id==dropdown.elementSelectionText.id||targ.id==dropdown.elementSelection.id) return false;
        document.body.removeChild(dropdown.listbox);
        document.onmousedown=null;
        dropdown.listbox = null;
      };
    }
    return false;
  }
  this.elementTarget.onmousedown=onclick;
  this.elementSelection.onmousedown=onclick;
};
pro.update=function(){
  if(this.showtitle) {
    this.elementSelectionText.replaceChild(document.createTextNode(this.title),this.elementSelectionText.firstChild);
  } else {
    this.elementSelectionText.replaceChild(document.createTextNode(this.items[this.selectedIndex].name),this.elementSelectionText.firstChild);
  }
  for(var i=0;i<this.listeners.length;i++) this.listeners[i]();
};
pro.addDropDownItem=function(item) {
  item.index = this.items.length;
  item.className = this.className;
  item.dropdown = this;
  this.items.push(item);
};

Sima.DropDownItem=function(name, value) {this.name=name;this.value=value;this.element=null;this.selectionClass="";};
pro=Sima.DropDownItem.prototype;
pro.getElement=function(){
  var item = this;
  if(!this.element) {
    var ele = document.createElement("div");
    var tele = document.createElement("span");
    ele.className = this.className+"DropDownListItem";
    tele.className = this.className+"DropDownListItemText";
    tele.appendChild(document.createTextNode(this.name));
    ele.appendChild(tele);
    ele.onmousedown=function(e) {
      item.dropdown.selectedIndex=item.index;
      item.dropdown.update();
      return false;
    };
    ele.onmouseover=function(e) {
      item.element.className = item.selectionClass+item.className+"DropDownListItem "+item.className+"DropDownListItemActive";
      return false;
    };
    ele.onmouseout=function(e) {
      item.element.className = item.selectionClass+item.className+"DropDownListItem";
      return false;
    };
    this.element = ele;
  }
  item.element.className = item.selectionClass+item.className+"DropDownListItem";
  return this.element;
};
pro.setSelected=function(b) {
  this.selectionClass = b?this.className+"DropDownListItemSelected ":"";
  this.element.className = this.selectionClass+this.className+"DropDownListItem";
}