﻿//**************************************************************************
//    imapa.js - základní objekt imapy
//--------------------------------------------------------------------------
//    Datum vytvoření   : 16.1.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa.js,v 1.4 2008-01-11 09:20:03 michal Exp $


var browser_MSIE = (navigator.appVersion.match(/\bMSIE\b/) != null);
var browserFF   = (navigator.userAgent.match(/\bFirefox\b/) != null);


if((typeof Prototype=='undefined') ||
   (typeof Element == 'undefined') ||
   (typeof Element.Methods=='undefined') ||
   parseFloat(Prototype.Version.split(".")[0] + "." +
              Prototype.Version.split(".")[1]) != 1.5) 
{
  alert('iMapa requires the Prototype JavaScript framework v. 1.5.0');
  throw('missing Prototype library');
}


//---------------------------------------------------------------------------------------------------

// startup code
jQuery(document).ready(function() {
  jq = jQuery.noConflict();
  imapa = new iMapa();
  imapa.load();
});

//---------------------------------------------------------------------------------------------------


var iMapa = Class.create();
iMapa.prototype = {
  version: 'dynamic-1.5',

  //********************************************************
  // object constructor
  initialize: function()
  {
    this.mapwindow = $('imapa-mapwindow');
    this.indicator = $('indicator');

    // initialize objects
    this.config     = new MapConfig();
    this.analytics  = new MapAnalytics();
    this.projection = new Projection();
    this.mapserver  = new MapServer();
    this.ui         = new UserInterface();
    this.mapcontroller = new MapController();
    this.mapimage   = new MapImage;
    this.sidebar    = new SideBar();

    // install global event listeners
    Event.observe(window, 'unload', this.unload.bindAsEventListener(this));
    Event.observe(window, 'resize', this.resize.bindAsEventListener(this));
  },
  
  
  load: function() {
    // set element sizes
    this.resize();
    // first load user settings
    this.config.loadSettings();
    // call load() methods of member objects
    for (var property in this)
      if (typeof this[property].load == 'function') this[property].load();
  },

  
  unload: function() {
    // call unload() methods of member objects
    for (var property in this)
      if (typeof this[property].unload == 'function') this[property].unload();
    // finally save user settings
    this.config.saveSettings();
  },

  
  resize: function() {
    var newheight = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight) - 
      Element.getHeight('imapa-header') - Element.getHeight('imapa-toolbar') - Element.getHeight('imapa-footer');
    newheight = Math.max(350, newheight);
    $('imapa-mapwindow').style.height = newheight+'px';
    $('sidebar').style.height = newheight+'px';
    // notify components
    for (var property in this)
      if (typeof this[property].onResize == 'function') this[property].onResize();
  }

};

//**************************************************************************
//    imapa-config.js - nastavení imapy (na straně klienta)
//--------------------------------------------------------------------------
//    Datum vytvoření   : 4.5.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-config.js,v 1.3 2008-01-11 09:20:03 michal Exp $


  

var MapConfig = Class.create();
MapConfig.prototype = {
 
	initialize: function() {
    //this.imgdir = 'www/images/'+this.layout+'/'+this.skin+'/';
    this.cookie_name = 'imapa-settings';
  },
  
  loadSettings: function() {
  /*
    var s = document.cookie.indexOf(this.cookie_name+'=');
    if (s>=0) s += this.cookie_name.length + 1;
    var e = document.cookie.indexOf(';', s);
    this.settings = (s>=0) ? eval('('+unescape(document.cookie.substring(s,e))+')') : {};
    */
  },
  
  saveSettings: function() {
  /*
    // save settings data in JSON format to document.cookie
    var date = new Date();
    date.setTime(date.getTime() + 182*24*60*60*1000); // 6 months
    cookieValues = new Array();
    for (var property in this.settings)
      cookieValues.push('"'+property+'"' +':'+ (typeof this.settings[property] == 'string' ? '"'+this.settings[property]+'"' : this.settings[property]));
    document.cookie = 'imapa-settings='+escape('{'+cookieValues.join(',')+'}') + ';' + 
      'expires='+date.toGMTString()
      */
  },
 
  registerValue: function(name, initial_value) {
    if(!this.settings[name]) this.settings[name] = initial_value;
  },
  
  dummy: function() {}
};
//**************************************************************************
//    imapa-projection.js - projekce mapového okna
//--------------------------------------------------------------------------
//    Datum vytvoření   : 16.1.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-projection.js,v 1.3 2008-01-11 09:20:03 michal Exp $



//--------------------------------------------------------------------------
// Projection
//--------------------------------------------------------------------------

var Projection = Class.create();
Projection.prototype = {
  // class constructor
  initialize: function() {
    this.memory = new ProjectionMemory();
    this.notifiers = new Array();
    
    // nastavení projekce v současném mapovém okně
    this.prjWidth   = null;            // reálná šířka pohledu
    this.prjHeight  = null;            // reálná výška pohledu
    this.imgWidth   = null;            // pixelová šířka okna
    this.imgHeight  = null;            // pixelová výška okna
    this.rotation   = null;            // natočení pohledu [rad]
    this.center     = null;            // střed pohledu [TMapCoord]
    this.boundRect  = null;            // vnější nenatočené meze pohledu [TMapRect]
    this.pixSize    = null;            // kolik metrů odpovídá 1 pixelu
    this.scale      = null;            // měřítko výřezu (1:Scale)
    this.kS         = null;            // koeficienty transformace
    this.kC         = null;            // koeficienty transformace
    this.k          = null;            // koeficienty transformace
    this.layers     = null;            // skutečně zobrazené vrstvy projekce
    this.isSynopsis = null;            // zobrazena přehledová mapa
  },
  
  
  load: function() {
    this.layers = imapa.config.layers;
  },
  

  //********************************************************
  // zobrazí informaci o objektu (jako text)
  // základní metoda každého objektu
  // př.: alert(projection);
  toString: function() {
    return "Projection:\n" +
        "prjWidth = " + this.prjWidth + "\n" +
        "prjHeight = " + this.prjHeight + "\n" +
        "imgWidth = " + this.imgWidth + "\n" +
        "imgHeight = " + this.imgHeight + "\n" +
        "rotation = " + this.rotation + "\n" +
        "center = " + this.center + "\n" +
        "boundRect = " + this.boundRect + "\n" +
        "pixSize = " + this.pixSize + "\n" +
        "scale = " + this.scale + "\n" +
        "kS = " + this.kS + "\n" +
        "kC = " + this.kC + "\n" +
        "k = " + this.k + "\n" +
        "layers = " + encodeLayers(this.layers) + "\n";
        "synopsis = " + this.isSynopsis + "\n";
  },

  
  addNotifier: function(notifier) {
    this.notifiers.push(notifier);
  },
  

  //********************************************************
  // nastaví nové parametry projekce
  assign: function(
    $prjwidth, $prjheight, $imgwidth, $imgheight, $rotation,
    $center_y, $center_x,
    $rect_y1, $rect_x1, $rect_y2, $rect_x2,
    $pixsize, $scale, $ks, $kc, $k, $layers, $isSynopsis
  ) {
    this.prjWidth   = $prjwidth;
    this.prjHeight  = $prjheight;
    this.imgWidth   = $imgwidth;
    this.imgHeight  = $imgheight;
    this.rotation   = $rotation;
    this.center     = new MapCoord($center_y, $center_x);
    this.boundRect  = new MapRect($rect_y1, $rect_x1, $rect_y2, $rect_x2, 0.0);
    this.pixSize    = $pixsize;
    this.scale      = $scale;
    this.kS         = $ks;
    this.kC         = $kc;
    this.k          = $k;
    this.layers     = $layers;
    this.isSynopsis = $isSynopsis;
    
    this.layers['REF']     = true;

    this.memory.save(this.center, this.scale, this.rotation);
    for (var i=0; i<this.notifiers.length; i++) this.notifiers[i](this);
  },
  
  assignFromMapServer: function(mapserverobj) {
    this.prjWidth   = mapserverobj.projection.prjWidth,
    this.prjHeight  = mapserverobj.projection.prjHeight,
    this.imgWidth   = mapserverobj.projection.imgWidth,
    this.imgHeight  = mapserverobj.projection.imgHeight,
    this.rotation   = mapserverobj.projection.rotation,
    this.center     = new MapCoord(mapserverobj.projection.centerY, mapserverobj.projection.centerX);
    this.boundRect  = new MapRect(mapserverobj.projection.boundingRect.y1, mapserverobj.projection.boundingRect.x1, mapserverobj.projection.boundingRect.y2, mapserverobj.projection.boundingRect.x2, 0.0);
    this.pixSize    = mapserverobj.projection.pixsizeX,
    this.scale      = mapserverobj.projection.scale,
    this.kS         = mapserverobj.projection.ks,
    this.kC         = mapserverobj.projection.kc,
    this.k          = mapserverobj.projection.kX,
    this.layers     = decodeLayers(mapserverobj.layers.layerSet);
    this.isSynopsis = (mapserverobj.isSynopsis == true);

    this.layers['REF']     = true;

    this.memory.save(this.center, this.scale, this.rotation);
    for (var i=0; i<this.notifiers.length; i++) this.notifiers[i](this);
  },

  //********************************************************
  // make a copy of the projection object
  duplicate: function() {
    var prj = new Projection();
    prj.prjWidth   = this.prjWidth;
    prj.prjHeight  = this.prjHeight;
    prj.imgWidth   = this.imgWidth;
    prj.imgHeight  = this.imgHeight;
    prj.rotation   = this.rotation;
    prj.center     = this.center.duplicate();
    prj.boundRect  = this.boundRect.duplicate();
    prj.pixSize    = this.pixSize;
    prj.scale      = this.scale;
    prj.kS         = this.kS;
    prj.kC         = this.kC;
    prj.k          = this.k;
    prj.layers     = this.layers;
    prj.isSynopsis = this.isSynopsis;
    return prj;
  },

  //********************************************************
  // transformuje souřadnice okna do TMapCoord
  transformW2R: function($wX, $wY) {
    try {
      var mY = this.center.y - this.kS*($wY-this.imgHeight/2)/this.k - this.kC*($wX-this.imgWidth/2)/this.k;
      var mX = this.center.x + this.kC*($wY-this.imgHeight/2)/this.k - this.kS*($wX-this.imgWidth/2)/this.k;
      return new MapCoord(mY, mX);
    } catch (e) {
      return new MapCoord(0, 0);
    }
  },

  //********************************************************
  // transformuje souřadnice TMapCoord do okna
  transformR2W: function($mc) {
    try {
      var wX = - this.kC*($mc.y-this.center.y)*this.k - this.kS*($mc.x-this.center.x)*this.k + this.imgWidth/2;
      var wY = - this.kS*($mc.y-this.center.y)*this.k + this.kC*($mc.x-this.center.x)*this.k + this.imgHeight/2;
      return [wX,wY];
    } catch (e) {
      return [0,0];
    }
  },
  
  //********************************************************
  // transformuje pole souřadnic (MapCoord[]) TMapCoord do okna
  transformR2WArray: function(coord_array) {
    var result = new Array();
    for (var i=0; i<coord_array.length; i++) result.push(this.transformR2W(coord_array[i]));
    return result;
  }
  
};




//--------------------------------------------------------------------------
// ProjectionMemory
//--------------------------------------------------------------------------

var ProjectionMemory = Class.create();
ProjectionMemory.prototype = {
  initialize: function() {
    this.projections = new Array();
    this.index = this.projections.length-1;
    this.locked = false;
  },

  
  save: function(center, scale, rotation) {
    if (this.locked) {
      this.locked = false;
      return;
    }
    
    this.projections = this.projections.slice(0, this.index+1);
    this.projections.push({
      center: center,
      scale: scale,
      rotation: rotation
    });
    this.index = this.projections.length-1;
  },
  
  
  isNext: function() {
    return (this.index < this.projections.length-1);
  },

  
  isPrev: function() {
    return (this.index > 0);
  },
  
  
  goNext: function() {
    if (!this.isNext()) return null;
    this.locked = true;
    this.index++;
    return this.projections[this.index];
  },
  
  
  goPrev: function() {
    if (!this.isPrev()) return null;
    this.locked = true;
    this.index--;
    return this.projections[this.index];
  }

};



//**************************************************************************
//    imapa-mapimage.js - mapové okno
//--------------------------------------------------------------------------
//    Datum vytvoření   : 14.1.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2001  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-mapimage.js,v 1.3 2008-01-11 09:20:03 michal Exp $


// MapImage - class to handle visual operations upon the 'mapimage' control
var MapImage = Class.create();
MapImage.prototype = {

  // class constructor
  initialize: function() {
    // variable to store pointer to the 'mapimage' component
    this.mapimage = $('mapimage-a');
    this.mapimageOffset = Position.positionedOffset(Position.offsetParent(this.mapimage));

    // variable to store pointer to the 'mapimage-b' component (the backgroud overlay)
    this.mapimage_bg = $('mapimage-b');
    
    this.tmpImage = new Image();
    
    this.groverlay = new GraphicsOverlay($('imapa-mapwindow'));

    // variable to store pointer to the current running effect
    this.current_effect = null;
  },
  

  // returns X page position of the mapimage element
  getPageX: function() {
    return this.mapimageOffset[0];
  },
  

  // returns Y page position of the mapimage element
  getPageY: function() {
    return this.mapimageOffset[1];
  },
  

  // returns width if the mapimage element  
  getWidth: function() {
    return Element.getWidth(this.mapimage);
  },
  

  // returns height if the mapimage element  
  getHeight: function() {
    return Element.getHeight(this.mapimage);
  },
  

  // cancels any running visual effect on 'mapimage'
  cancelEffect: function() {
    if (this.current_effect) this.current_effect.cancel();
    this.current_effect = null;
  },


  // cancels any running visual effect on 'mapimage'
  onEffectFinish: function() {
    this.current_effect = null;
  },


  // simulates left map movement by shifting the 'mapimage' component to the right by 
  // specified percentage of the current viewport width
  effectMoveLeft: function(factor) {
    Element.hide(this.mapimage);
    this.current_effect = new Effect.MoveBy(this.mapimage_bg, 0, +imapa.projection.imgWidth*factor, {afterFinish:this.onEffectFinish.bind(this)});
  },


  // simulates right map movement by shifting the 'mapimage' component to the left by 
  // specified percentage of the current viewport width
  effectMoveRight: function(factor) {
    Element.hide(this.mapimage);
    this.current_effect = new Effect.MoveBy(this.mapimage_bg, 0, -imapa.projection.imgWidth*factor, {afterFinish:this.onEffectFinish.bind(this)});
  },


  // simulates up map movement by shifting the 'mapimage' component to the bottom by 
  // specified percentage of the current viewport width
  effectMoveUp: function(factor) {
    Element.hide(this.mapimage);
    this.current_effect = new Effect.MoveBy(this.mapimage_bg, +imapa.projection.imgHeight*factor, 0, {afterFinish:this.onEffectFinish.bind(this)});
  },


  // simulates down map movement by shifting the 'mapimage' component to the top by 
  // specified percentage of the current viewport width
  effectMoveDown: function(factor) {
    Element.hide(this.mapimage);
    this.current_effect = new Effect.MoveBy(this.mapimage_bg, -imapa.projection.imgHeight*factor, 0, {afterFinish:this.onEffectFinish.bind(this)});
  },


  // simulates map scaling by shrinking/expanding the 'mapimage' component to the specified percentage 
  // of the current viewport; scales from the image centre
  effectScale: function(factor) {
    Element.hide(this.mapimage);
    this.current_effect = new Effect.Scale(this.mapimage_bg, factor, {scaleFromCenter: true, afterFinish:this.onEffectFinish.bind(this)});
  },
  

  // simulates simultaneous map scaling and movement by shrinking/expanding the 'mapimage' 
  // component to the specified percentage of the current viewport and by shifting 
  // the 'mapimage' component by specified pixels of the current viewport relative to the center
  effectScaleAndMove: function(move_dx, move_dy, scale_f) {
    Element.hide(this.mapimage);
    move_dx = -imapa.mapimage.getWidth() /2 * (scale_f/100 - 1.0) + scale_f/100*move_dx;
    move_dy = -imapa.mapimage.getHeight()/2 * (scale_f/100 - 1.0) + scale_f/100*move_dy;
    this.current_effect = new Effect.Parallel(
      [ new Effect.Scale (this.mapimage_bg, scale_f, {sync:true, scaleFromCenter: false}),
        new Effect.MoveBy(this.mapimage_bg, move_dy, move_dx, {sync:true})
      ], { duration:2.0, afterFinish:this.onEffectFinish.bind(this) }
    );
  },


  // loads a new image specified by given URL in the background and once loaded
  // it switches the current content of the 'mapimage' component with the newly loaded  one
  effectSwitchImages: function(new_url) {
    this.tmpImage.onload = (function(){
      this.mapimage.src = this.tmpImage.src;
      //this.cancelEffect(); ??? predcasne ukonceni beziciho efektu zpusobi trhany obraz, melo by se pockat, az se sam dokonci
      setTimeout((function(){
        // show 'mapimage-a' component with a 100ms delay
        this.mapimage.style.left = '0px';
        this.mapimage.style.top  = '0px';
        Element.show(this.mapimage)
      }).bind(this), 100);
      setTimeout((function(){
        // synchronize 'mapimage-b' component with 'mapimage-a' in background 150ms after showing 'mapimage-a'
        var ofs = [0,0];//Position.cumulativeOffset($('imapa-mapwindow'));
        this.mapimage_bg.src = this.tmpImage.src; 
        this.mapimage_bg.style.left = ofs[0]+'px';
        this.mapimage_bg.style.top  = ofs[1]+'px';
        this.mapimage_bg.style.width  = Element.getWidth (this.mapimage)+'px';
        this.mapimage_bg.style.height = Element.getHeight(this.mapimage)+'px';
      }).bind(this),250);
    }).bind(this);
    this.tmpImage.src = new_url;
  }
};


//**************************************************************************
//    imapa-sidebar.js - ovládání postranního panelu
//--------------------------------------------------------------------------
//    Datum vytvoření   : 4.2.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-sidebar.js,v 1.3 2008-01-11 09:20:03 michal Exp $


// SideBar - class to handle visual operations upon the 'side-bar' control
var SideBar = Class.create();
SideBar.prototype = {

  // class constructor
  initialize: function() {
    // variable to store pointer to the 'sidebar' component
    this.sidebar = $('sidebar');
	this.onBeforeContentChange = null;
    this.defaultContents = this.sidebar.innerHTML;
  },
  
  
  scrollToTop: function() {
    this.sidebar.scrollLeft = 0;
    this.sidebar.scrollTop  = 0;
  },

  
  setDefault: function() {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
  	this.onBeforeContentChange = null;
    this.sidebar.innerHTML = this.defaultContents;
  },
  
  
  findRdn: function() {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
  	this.onBeforeContentChange = null;
	
    var options = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this)
    };
    imapa.mapserver.requestFindRdn(options);
  },

/*  
  findCadOrDst: function() {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
  	this.onBeforeContentChange = null;
	
    var options = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this)
    };
    imapa.mapserver.requestFindCadOrDst(options);
  },
*/
  
  findCad: function() {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
  	this.onBeforeContentChange = null;
	
    var options = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this)
    };
    imapa.mapserver.requestFindCad(options);
  },

  
  findDst: function() {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
  	this.onBeforeContentChange = null;
	
    var options = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this)
    };
    imapa.mapserver.requestFindDst(options);
  },


  findStn: function() {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
  	this.onBeforeContentChange = null;
	
    var options = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this)
    };
    imapa.mapserver.requestFindStn(options);
  },

  
  layers: function() {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
	  this.onBeforeContentChange = null;
	
    var options = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this)
    };
    imapa.mapserver.requestLayers(options);
  },

  
  info: function(coord) {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
	  this.onBeforeContentChange = null;
	
    var options = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this),
      onError: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this)
    };
    imapa.mapserver.requestInfo(coord, options);
  },


  markPoint: function() {
  	if (this.onBeforeContentChange)	this.onBeforeContentChange();
	  this.onBeforeContentChange = null;
	
    var options = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this),
      onError: (function(html) {
          Element.update(this.sidebar, html);
      }).bind(this)
    };
    imapa.mapserver.requestMarkPoint(options);
  },


  dummy: function() {}
};

//**************************************************************************
//    imapa-control.js - ovládání imapy (základní operace mapy)
//--------------------------------------------------------------------------
//    Datum vytvoření   : 14.1.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-control.js,v 1.3 2008-01-11 09:20:03 michal Exp $


  

var MapController = Class.create();
MapController.prototype = {
	initialize: function() {
	},
  
  
  load: function() {
    this.loadSynopsis();
  },
  
  
  setMapProjection: function(projection, effect) {
    this.setMap(projection.center, projection.scale, projection.rotation, effect);
  },
  

  setMap: function(position, scale, rotation, effect) {
    var options = {
      indicator: imapa.indicator,
      onBefore: (function(){
        imapa.ui.disable();
        imapa.mapimage.groverlay.disable();
      }),//.bind(this),
      onAfter: (function(obj){
        imapa.projection.assignFromMapServer(obj);
        imapa.mapimage.effectSwitchImages('imapa.aspx?rid=tmpres&ID='+obj.image.resId);
        imapa.ui.enable();
        imapa.mapimage.groverlay.enable(imapa.projection);
      })//.bind(this)
    };
    
    if (effect) effect();

    if (scale <= mapMaxScale)
      imapa.mapserver.requestMap(position, scale, rotation, options)
    else
      imapa.mapserver.requestSynopsis(options);
  },

  
  repaint: function() {
    this.setMapProjection(imapa.projection, null);
  },
  

  loadSynopsis: function() {
    var options = {
      indicator: imapa.indicator,
      onBefore: (function(){
        imapa.ui.disable();
        imapa.mapimage.groverlay.disable();
      }),//.bind(this),
      onAfter: (function(obj){
        imapa.projection.assignFromMapServer(obj);
        imapa.mapimage.effectSwitchImages('imapa.aspx?rid=tmpres&ID='+obj.image.resId);
        imapa.sidebar.setDefault();
        imapa.ui.enable();
        imapa.mapimage.groverlay.enable(imapa.projection);
      })//.bind(this)
    };
    imapa.mapserver.requestSynopsis(options);
  },

  
  // zvětší mapu tak aby obsahovala výřez
  // $x1,$y1,$x2,$y2 ... pixelové souřadnice relativně k mapovému oknu
  zoomRect: function(maprect) {
    var options = {
      indicator: imapa.indicator,
      onBefore: (function(){
        imapa.ui.disable();
        imapa.mapimage.groverlay.disable();
      }),//.bind(this),
      onAfter: (function(obj){
        imapa.projection.assignFromMapServer(obj);
        imapa.mapimage.effectSwitchImages('imapa.aspx?rid=tmpres&ID='+obj.image.resId);
        imapa.ui.enable();
        imapa.mapimage.groverlay.enable(imapa.projection);
      })//.bind(this)
    };
    imapa.mapserver.requestMapRect(maprect, options);
  },


  locateRdn: function(ID) {
    var options = {
      indicator: imapa.indicator,
      onBefore: (function(){
        imapa.ui.disable();
        imapa.mapimage.groverlay.disable();
      }),//.bind(this),
      onAfter: (function(obj){
        imapa.projection.assignFromMapServer(obj);
        imapa.mapimage.effectSwitchImages('imapa.aspx?rid=tmpres&ID='+obj.image.resId);
        imapa.ui.enable();
        imapa.mapimage.groverlay.enable(imapa.projection);
      })//.bind(this)
    };
    imapa.mapserver.requestLocateRdn(ID, options);
  },

  locateStn: function(ID) {
    var options = {
      indicator: imapa.indicator,
      onBefore: (function(){
        imapa.ui.disable();
        imapa.mapimage.groverlay.disable();
      }),//.bind(this),
      onAfter: (function(obj){
        imapa.projection.assignFromMapServer(obj);
        imapa.mapimage.effectSwitchImages('imapa.aspx?rid=tmpres&ID='+obj.image.resId);
        imapa.ui.enable();
        imapa.mapimage.groverlay.enable(imapa.projection);
      })//.bind(this)
    };
    imapa.mapserver.requestLocateStn(ID, options);
  },

  
  locateCad: function(ID) {
    var options = {
      indicator: imapa.indicator,
      onBefore: (function(){
        imapa.ui.disable();
        imapa.mapimage.groverlay.disable();
      }),//.bind(this),
      onAfter: (function(obj){
        imapa.projection.assignFromMapServer(obj);
        imapa.mapimage.effectSwitchImages('imapa.aspx?rid=tmpres&ID='+obj.image.resId);
        imapa.ui.enable();
        imapa.mapimage.groverlay.enable(imapa.projection);
      })//.bind(this)
    };
    imapa.mapserver.requestLocateCad(ID, options);
  },

  
  locateDst: function(ID) {
    var options = {
      indicator: imapa.indicator,
      onBefore: (function(){
        imapa.ui.disable();
        imapa.mapimage.groverlay.disable();
      }),//.bind(this),
      onAfter: (function(obj){
        imapa.projection.assignFromMapServer(obj);
        imapa.mapimage.effectSwitchImages('imapa.aspx?rid=tmpres&ID='+obj.image.resId);
        imapa.ui.enable();
        imapa.mapimage.groverlay.enable(imapa.projection);
      })//.bind(this)
    };
    imapa.mapserver.requestLocateDst(ID, options);
  },

  
  dummy: function() {}
  
};
//**************************************************************************
//    imapa-ui.js - uživatelské rozhraní ovládání mapy
//--------------------------------------------------------------------------
//    Datum vytvoření   : 4.7.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-ui.js,v 1.3 2008-01-11 09:20:03 michal Exp $

 
// UserInterface - class to handle visual operations upon the 'side-bar' control
var UserInterface = Class.create();
UserInterface.prototype = {

  initialize: function() {
    // install global event handlers
    Event.observe(document, 'keypress', this.onKeyPress.bindAsEventListener(this));
    this.activeMode = null;
  },
  
  
  load: function() {
    this.navigation = new UI.Navigation();
    this.activeMode = new UI.Mode.Info();
  },
  

  enable: function() {
    this.navigation.enable();
    this.activeMode.enable();
  },
  
  
  disable: function() {
    this.navigation.disable();
    this.activeMode.disable();
  },
  

  onKeyPress: function(event) {
    this.navigation.onKeyPress(event);
  },

  

  /*
  //ui.setMode('navigation', 'opmenu-navigation', 'imapa-opmenu-controls');
  
  setMode: function(mode, caller) {
    // uninstall previous controller
    if (this.activeMode) {
      if (this.activeMode.mode == mode) return;
      this.activeMode.uninstall();
      Element.removeClassName(this.activeMode.caller, 'tbl-item-active');
    }
    // install new controller
    this.activeMode = new MapControl.Modes[mode](caller);
    Element.addClassName(this.activeMode.caller, 'tbl-item-active');
  }
  */

  dummy: function() {}

};



//--------------------------------------------------------------------------------
// UI & UI.Mode classes
//--------------------------------------------------------------------------------

var UI = {};
UI.Mode = {};



//--------------------------------------------------------------------------------
// UI.Mode.Base prototype
//--------------------------------------------------------------------------------

UI.Mode.Base = function() {};
UI.Mode.Base.prototype = {

  initialize: function() {
    // noop
  }
  
  // in addition, each user-interface mode object MUST implement at minimum these methods:
  // - enable()
  // - disable()
  // - onMouseClick(mapcoord)
};




/*
var MapControl = {};

MapControl.Base = function() {};
MapControl.Base.prototype = {
	initialize: function(caller) {
	},

	uninstall: function() {
	}

};

// array of registered modes
MapControl.Modes = [];

//MapControl.Navigation = Class.create();
//MapControl.Modes['navigation'] = MapControl.Navigation;
//Object.extend(Object.extend(MapControl.Navigation.prototype, MapControl.Base.prototype), {

*///**************************************************************************
//    imapa-ui-navigation.js - ovládání režimu 'navigace'
//--------------------------------------------------------------------------
//    Datum vytvoření   : 14.1.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-ui-navigation.js,v 1.3 2008-01-11 09:20:03 michal Exp $



//-----------------------------------------------------------------------------------
// MapControl.Navigation
//-----------------------------------------------------------------------------------

// the navigation mode user interface
UI.Navigation = Class.create();
UI.Navigation.prototype = {
    
	initialize: function() {
    this.enabled = true;
            
    this.map_image_offset = [0,0];//Position.cumulativeOffset($('mapimage-a'));

    // prepare the helperControl variable
    this.helperControl = null;
    $('mapimage-a').ondragstart = discardEvent;
    
    this.synopsis = new UI.Navigation.Synopsis();

    var zoomerTrack  = document.createElement("div");
    var zoomerHandle = document.createElement("div");
    zoomerTrack.id = 'navigation-zoomer-track';
    zoomerHandle.id = 'navigation-zoomer-handle';
    $('imapa-mapwindow').appendChild(zoomerTrack);
    zoomerTrack.appendChild(zoomerHandle);
    zoomerTrack.className = 'ui-control';
    zoomerHandle.className = 'ui-control';

    this.zoomer = new Control.ZoomSlider(zoomerHandle, zoomerTrack, {
        range:$R(Math.log(imapa.config.minScale)/Math.log(10), Math.log(imapa.config.maxScale)/Math.log(10)),
        axis: 'vertical',
        sliderValue: Math.log(imapa.config.maxScale)/Math.log(10),
        onChange:function(v){imapa.mapcontroller.setMap(imapa.projection.center, Math.pow(10,v), imapa.projection.rotation);}
    });
    
    var node = document.createElement("img");
    node.id = 'navigation-zoom-out';
    node.src = 'www/images/dynamic/nav-unzoom.png';
    //node.width = '28';
    //node.height = '26';
    node.alt = '';
    node.title = 'Oddálit mapu';
    node.className = 'ui-control'
    node.style.cursor = 'pointer';
    //node.onmouseover="this.src=img_zoomout_on.src"
    //node.onmouseout="this.src=img_zoomout.src"
    node.onclick = (function() {if (this.enabled) this.doZoomOut();}).bind(this);
    $('imapa-mapwindow').appendChild(node);
  
    var node = document.createElement("img");
    node.id = 'navigation-zoom-in';
    node.src = 'www/images/dynamic/nav-zoom.png';
    //node.width = '28';
    //node.height = '26';
    node.alt = '';
    node.title = 'Přiblížit mapu';
    node.className = 'ui-control'
    node.style.cursor = 'pointer';
    //node.onmouseover="this.src=img_zoomout_on.src"
    //node.onmouseout="this.src=img_zoomout.src"
    node.onclick = (function() {if (this.enabled) this.doZoomIn();}).bind(this);
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-left';
    node.src = 'www/images/dynamic/nav-left.png';
    node.className = 'ui-control'
    node.title = 'Posunout mapu vlevo';
    node.style.cursor = 'pointer';
    node.onclick = (function() {if (this.enabled) this.doMoveLeft();}).bind(this);
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-right';
    node.src = 'www/images/dynamic/nav-right.png';
    node.className = 'ui-control'
    node.title = 'Posunout mapu vpravo';
    node.style.cursor = 'pointer';
    node.onclick = (function() {if (this.enabled) this.doMoveRight();}).bind(this);
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-up';
    node.src = 'www/images/dynamic/nav-up.png';
    node.className = 'ui-control'
    node.title = 'Posunout mapu nahoru';
    node.style.cursor = 'pointer';
    node.onclick = (function() {if (this.enabled) this.doMoveUp();}).bind(this);
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-down';
    node.src = 'www/images/dynamic/nav-down.png';
    node.className = 'ui-control'
    node.title = 'Posunout mapu dolů';
    node.style.cursor = 'pointer';
    node.onclick = (function() {if (this.enabled) this.doMoveDown();}).bind(this);
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-synopsis';
    node.src = 'www/images/dynamic/nav-synopsis.png';
    node.className = 'ui-control'
    node.title = 'Přehledová mapa';
    node.style.cursor = 'pointer';
    node.onclick = (function() {if (this.enabled) imapa.mapcontroller.loadSynopsis();}).bind(this);
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-proj-prev';
    node.src = 'www/images/dynamic/nav-proj-prev-disabled.png';
    //node.width = '28';
    //node.height = '26';
    node.alt = '';
    node.title = 'Předchozí výřez';
    node.className = 'ui-control'
    node.style.cursor = 'pointer';
    //node.onmouseover="this.src=img_zoomout_on.src"
    //node.onmouseout="this.src=img_zoomout.src"
    node.onclick = (function() {if (this.enabled) this.doProjectionPrev();}).bind(this);
    $('imapa-mapwindow').appendChild(node);
  
    var node = document.createElement("img");
    node.id = 'navigation-proj-next';
    node.src = 'www/images/dynamic/nav-proj-next-disabled.png';
    //node.width = '28';
    //node.height = '26';
    node.alt = '';
    node.title = 'Následující výřez';
    node.className = 'ui-control'
    node.style.cursor = 'pointer';
    //node.onmouseover="this.src=img_zoomout_on.src"
    //node.onmouseout="this.src=img_zoomout.src"
    node.onclick = (function() {if (this.enabled) this.doProjectionNext();}).bind(this);
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-map-basic';
    node.src = 'www/images/dynamic/nav-map-basic.png';
    node.className = 'ui-control'
    node.title = 'Základní mapa';
    node.style.cursor = 'pointer';
    node.onclick = function() { imapa.analytics.tracker('navigation/map-block'); imapa.projection.layers=imapa.config.layers; imapa.mapcontroller.repaint(); };
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-map-foto';
    node.src = 'www/images/dynamic/nav-map-foto.png';
    node.className = 'ui-control'
    node.title = 'Letecká mapa';
    node.style.cursor = 'pointer';
    node.onclick = function() { imapa.analytics.tracker('navigation/map-aerial'); imapa.projection.layers=decodeLayers('RAS,GRF'); imapa.mapcontroller.repaint(); };
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-synopsis-btn';
    node.src = 'www/images/dynamic/synopsis-openbtn.png';
    node.width = '18';
    node.height = '18';
    node.alt = '';
    node.title = 'Přehledová mapa';
    node.className = 'ui-control'
    node.style.cursor = 'pointer';
    node.onclick = (function() {imapa.analytics.tracker('navigation/synopsis-show');  this.synopsis.show();}).bind(this);
    $('imapa-mapwindow').appendChild(node);

    /*
    var node = document.createElement("img");
    node.id = 'navigation-turn-left';
    node.src = 'www/images/dynamic/nav-rot-ccw.png';
    node.className = 'ui-control'
    node.title = 'Natočit mapu po směru h.r.';
    node.style.cursor = 'pointer';
    node.onclick = function() { imapa.ui.navigation.doZoomIn(); };
    $('imapa-mapwindow').appendChild(node);

    var node = document.createElement("img");
    node.id = 'navigation-turn-right';
    node.src = 'www/images/dynamic/nav-rot-cw.png';
    node.className = 'ui-control'
    node.title = 'Natočit mapu proti směru h.r.';
    node.style.cursor = 'pointer';
    node.onclick = function() { imapa.ui.navigation.doZoomIn(); };
    $('imapa-mapwindow').appendChild(node);
    */

    // install navagation event handlers
    Event.observe('mapcanvas', "mousedown", this.onMouseDown.bindAsEventListener(this));
    Event.observe(document,    "mouseup",   this.onMouseUp.bindAsEventListener(this));
  },
  
  
  enable: function() {
    this.zoomer.setScale(imapa.projection.scale);
    this.enabled = true;
    $('navigation-proj-prev').src = 'www/images/dynamic/' + (imapa.projection.memory.isPrev() ? 'nav-proj-prev.png' : 'nav-proj-prev-disabled.png');
    $('navigation-proj-next').src = 'www/images/dynamic/' + (imapa.projection.memory.isNext() ? 'nav-proj-next.png' : 'nav-proj-next-disabled.png');
    $('navigation-proj-prev').style.cursor = imapa.projection.memory.isPrev() ? 'pointer' : 'default';
    $('navigation-proj-next').style.cursor = imapa.projection.memory.isNext() ? 'pointer' : 'default';
    //$('imapa-mapwindow').getElementsByClassName('ui-control').map(function(e){ Element.show(e) });
  },
  
  
  disable: function() {
    this.enabled = false;
    //$('imapa-mapwindow').getElementsByClassName('ui-control').map(function(e){ Element.hide(e) });
  },

  
  // method handler for key-press events
  onKeyPress: function(event) {
    if (!this.enabled) return;
    if (Event.element(event).nodeName == 'INPUT') return;
    switch (getEventKeyCode(event)) {
      case Event.KEY_ESC:
        if (this.helperControl) this.helperControl.cancel();
        this.helperControl = null;
        break;
      case 43:  // KEY_NUMERIC_ADD (firefox)
      case 107: // KEY_NUMERIC_ADD (iexplorer)
        if (this.doZoomIn()) Event.stop(event);
        break;
      case 45:  // KEY_NUMERIC_SUB (firefox)
      case 109: // KEY_NUMERIC_SUB (iexplorer)
        if (this.doZoomOut()) Event.stop(event);
        break;
      case Event.KEY_RIGHT:
        if (this.doMoveRight()) Event.stop(event);
        break;
      case Event.KEY_LEFT:
        if (this.doMoveLeft()) Event.stop(event);
        break;
      case Event.KEY_UP:
        if (this.doMoveUp()) Event.stop(event);
        break;
      case Event.KEY_DOWN:
        if (this.doMoveDown()) Event.stop(event);
        break;
    }
  },


  // method handler for mouse-down events
	onMouseDown: function(event) {
    if (!this.enabled) return false;
    // we are interested in left mouse button only
    if (!Event.isLeftClick(event)) return false;
    // create a helperControl component to track mouse movements
    if ((event.ctrlKey))
      this.helperControl = new ZoomControl(event);
    else if ((!event.shiftKey) && (!event.ctrlKey) && (!imapa.projection.isSynopsis))
      this.helperControl = new MoveControl(event);
    else
      return true;
    // stop event propagation to avoid dragging
    Event.stop(event);
	},


  // method handler for mouse-up events
	onMouseUp: function(event) {
    if (!this.enabled) return;
    // instruct the current helper control to finish
    if (this.helperControl) {
      if (!this.helperControl.takeAction(event))
        imapa.ui.activeMode.onMouseClick(this.helperControl.coord().click);
    }
    // free the helper control
    this.helperControl = null;
	},

  
  // performs a map projection shift to the left
  doMoveLeft: function() {
    if (imapa.projection.isSynopsis) return false;
    imapa.analytics.tracker('navigation/move-left');  
    var pxNewCY = imapa.projection.imgWidth /2 - imapa.projection.imgWidth *0.8;
    var pxNewCX = imapa.projection.imgHeight/2;
    imapa.mapcontroller.setMap(
      imapa.projection.transformW2R(pxNewCY, pxNewCX), 
      imapa.projection.scale, 
      imapa.projection.rotation, 
      function(){ imapa.mapimage.effectMoveLeft(0.8); }
    );
    return true;
  },
  

  // performs a map projection shift to the right with a visual effect
  doMoveRight: function() {
    if (imapa.projection.isSynopsis) return false;
    imapa.analytics.tracker('navigation/move-right');  
    var pxNewCY = imapa.projection.imgWidth /2 + imapa.projection.imgWidth *0.8;
    var pxNewCX = imapa.projection.imgHeight/2;
    imapa.mapcontroller.setMap(
      imapa.projection.transformW2R(pxNewCY, pxNewCX), 
      imapa.projection.scale, 
      imapa.projection.rotation, 
      function(){ imapa.mapimage.effectMoveRight(0.8); }
    );
    return true;
  },
  

  // performs a map projection shift to the bottom with a visual effect
  doMoveDown: function() {
    if (imapa.projection.isSynopsis) return false;
    imapa.analytics.tracker('navigation/move-down');  
    var pxNewCY = imapa.projection.imgWidth /2;
    var pxNewCX = imapa.projection.imgHeight/2 + imapa.projection.imgHeight *0.8;
    imapa.mapcontroller.setMap(
      imapa.projection.transformW2R(pxNewCY, pxNewCX), 
      imapa.projection.scale, 
      imapa.projection.rotation, 
      function(){ imapa.mapimage.effectMoveDown(0.8); }
    );
    return true;
  },
  

  // performs a map projection shift to the top with a visual effect
  doMoveUp: function() {
    if (imapa.projection.isSynopsis) return false;
    imapa.analytics.tracker('navigation/move-up');  
    var pxNewCY = imapa.projection.imgWidth /2;
    var pxNewCX = imapa.projection.imgHeight/2 - imapa.projection.imgHeight *0.8;
    imapa.mapcontroller.setMap(
      imapa.projection.transformW2R(pxNewCY, pxNewCX), 
      imapa.projection.scale, 
      imapa.projection.rotation, 
      function(){ imapa.mapimage.effectMoveUp(0.8); }
    );
    return true;
  },
  

  // performs a map projection zoom-in with a visual effect
  doZoomIn: function() {
    imapa.analytics.tracker('navigation/zoom-in');  
    imapa.mapcontroller.setMap(
      imapa.projection.center, 
      imapa.projection.isSynopsis ? imapa.config.maxScale/2 : imapa.projection.scale/2, 
      imapa.projection.rotation,
      function(){ imapa.mapimage.effectScale(200); }
    );
    return true;
  },
  

  // performs a map projection zoom-out with a visual effect
  doZoomOut: function() {
    if (imapa.projection.isSynopsis) return true;
    imapa.analytics.tracker('navigation/zoom-out');  
    imapa.mapcontroller.setMap(
      imapa.projection.center, 
      imapa.projection.scale*2, 
      imapa.projection.rotation,
      function(){ imapa.mapimage.effectScale(50); }
    );
    return true;
  },
  

  // sets a previous map projection
  doProjectionPrev: function() {
    var prj = imapa.projection.memory.goPrev();
    if (!prj) return false;
    imapa.analytics.tracker('navigation/projection-prev');  
    imapa.mapcontroller.setMap(prj.center, prj.scale, prj.rotation, null);
    return true;
  },
  
  
  // sets a next map projection
  doProjectionNext: function() {
    var prj = imapa.projection.memory.goNext();
    if (!prj) return false;
    imapa.analytics.tracker('navigation/projection-next');  
    imapa.mapcontroller.setMap(prj.center, prj.scale, prj.rotation, null);
    return true;
  }

};




//-----------------------------------------------------------------------------------
// Synopsis
//-----------------------------------------------------------------------------------

// Synopsis - class to handle floating tool-window with synoptic map
UI.Navigation.Synopsis = Class.create();
UI.Navigation.Synopsis.prototype = {

  // class constructor
  initialize: function() {
    // projection object for synopsis window
    this.projection = new Projection();

    // create the floating window (container + handle + content-box)
    this.object = document.createElement('div');
    this.object.id = 'synopsis';
    //this.object.className = 'tool-window';
    this.object.innerHTML = 
      '<img id="synopsis-closebtn" src="" width="12" height="12" title="Zavřít okno" />' +
      '<div id="synopsis-contents">' +
      '<img id="synopsis-image" src="www/images/dynamic/null.gif" alt="" />' +
      '<span id="synopsis-rect" style="display:none"></span>' +
      '</div>';
    imapa.mapwindow.appendChild(this.object);
    this.imageDimensions = Element.getDimensions('synopsis-contents');

    // set visibility
//    Element.hide('synopsis');           pavel
//    Element.hide('synopsis-rect');      pavel
    Element.show('synopsis');
    Element.show('synopsis-rect'); 
    
    // finish tool-window
    $('synopsis-closebtn').src = 'www/images/dynamic/synopsis-closebtn.gif';
    $('synopsis-closebtn').onclick = (function(){this.hide()}).bind(this);

    // register notify function on map-window projection change events
    imapa.projection.addNotifier(this.update.bind(this));

    // draw synopsis image to the window
    var options = {
      indicator: null,
      onAfter: (function(obj){
        this.projection.assignFromMapServer(obj);
        $('synopsis-image').src = 'imapa.aspx?rid=tmpres&ID='+obj.image.resId;
        this.update(imapa.projection);
      }).bind(this)
    };
    imapa.mapserver.requestSynopsis(options, this.imageDimensions.width, this.imageDimensions.height);
    
    // position & show window
    //$('synopsis').style.left = '0px';
    //$('synopsis').style.top  = Element.getDimensions(imapa.mapwindow).height - this.imageDimensions.height + 'px';
    //if (imapa.config.settings.synopsisLeft) $('synopsis').style.left = imapa.config.settings.synopsisLeft+'px';
    //if (imapa.config.settings.synopsisTop)  $('synopsis').style.top  = imapa.config.settings.synopsisTop+'px';
    //Element[imapa.config.settings.synopsisVisible ? 'show' : 'hide']('synopsis');
  },

  
  show: function() {
    //Element.show('synopsis');
    Effect.Grow('synopsis', {direction:'bottom-left', duration:0.4});
  },

  
  hide: function() {
    if (!Element.visible('synopsis')) return;
    // save window properties to user settings & hide it
    //imapa.config.settings['synopsisLeft'] = GetAbsOffsetLeft('synopsis');
    //imapa.config.settings['synopsisTop']  = GetAbsOffsetTop('synopsis');
    //imapa.config.settings['synopsisVisible'] = false;
    //Element.hide('synopsis');
    Effect.Fade('synopsis', {duration:0.4});
  },

  
  update: function(new_projection) {
    // set window possition
    $('synopsis').style.left = '0px';
    $('synopsis').style.top  = Element.getDimensions(imapa.mapwindow).height - this.imageDimensions.height + 'px';
    // on map-window projection change, update the viewport rectangle
    if ((!this.projection.center)||(!new_projection.center)) return;
    var p1 = this.projection.transformR2W(new_projection.boundRect.P1());
    var p2 = this.projection.transformR2W(new_projection.boundRect.P2());
    var L = Math.min(p1[0], p2[0]);  //L = Math.max(L, 0);
    var T = Math.min(p1[1], p2[1]);  //T = Math.max(T, 0);
    var W = Math.abs(p1[0] - p2[0]); //W = Math.min(W, this.imageDimensions.width-L);
    var H = Math.abs(p1[1] - p2[1]); //H = Math.min(H, this.imageDimensions.height-T);
    $('synopsis-rect').style.left   = L+'px';
    $('synopsis-rect').style.top    = T+'px';
    $('synopsis-rect').style.width  = W+'px';
    $('synopsis-rect').style.height = H+'px';
    // set synopsis-rect visibility
    Element[imapa.projection.isSynopsis ? 'hide' : 'show']('synopsis-rect');
    Element.setOpacity('synopsis-rect', (0.6-Math.min(Math.min(W,H)/50,1.0)*0.6)+0.4);
  },
  
  dummy: function() {}
};




//-----------------------------------------------------------------------------------
// ZoomControl
//-----------------------------------------------------------------------------------

// helper class to MapControl.Navigation, which takes care of zooming map by mouse

var ZoomControl = Class.create();
ZoomControl.prototype = {

	initialize: function(event) {
    // initialize html element for zoom rectangle
    this.zoomRect = $('zoom-rect');
    this.canvas   = $('mapcanvas');
    Element.hide(this.zoomRect);
    this.zoomRect.style.left = '0px';
    this.zoomRect.style.top  = '0px';
    // save its screen offset position
    this.zoomRectOffset = Position.positionedOffset(Position.offsetParent(this.zoomRect));

    this.hasMoved = false;
    this.P1 = this.P2 = this.getMousePointerPosition(event);
    
    // mouse-move handler binding
    this.onMouseMoveHandler = this.onMouseMove.bindAsEventListener(this);
    Event.observe(this.zoomRect, "mousemove", this.onMouseMoveHandler);
    Event.observe(this.canvas,   "mousemove", this.onMouseMoveHandler);
    this.canvas.style.cursor = 'crosshair';
	},


	// [private] stop: show element and install observers for mousemove events
	finish: function(event) {
    // hide element
    setTimeout((function(){Element.hide(this.zoomRect);}).bind(this), 500);
    this.canvas.style.cursor = 'default';
    // uninstall event handlers
    Event.stopObserving(this.zoomRect, "mousemove", this.onMouseMoveHandler);
    Event.stopObserving(this.canvas,   "mousemove", this.onMouseMoveHandler);
    // record the latest mouse position
    if (event) this.P2 = this.getMousePointerPosition(event);
	},


	// cancel
	cancel: function() {
    this.finish(null);
    Element.hide(this.zoomRect);
	},


  // [public] get click coordinates
  coord: function(event) {
    return {
      down:  imapa.projection.transformW2R(this.P1[0],this.P1[1]),
      up:    imapa.projection.transformW2R(this.P2[0],this.P2[1]),
      click: ((!this.hasMoved) && samePointers(this.P1,this.P2)) ? imapa.projection.transformW2R(this.P2[0],this.P2[1]) : null
    };
  },


	// [private] get the mouse pointer position relative to the parent object
  // (i.e. map-window container)
  getMousePointerPosition: function(event) {
    return [
      Event.pointerX(event) - this.zoomRectOffset[0], 
      Event.pointerY(event) - this.zoomRectOffset[1]
    ];
  },


	// [private] mousemove event handler
	onMouseMove: function(event) {
    if (!this.hasMoved) {
      Element.show(this.zoomRect);
      this.hasMoved = true;
    };
    var pointer = this.getMousePointerPosition(event);
    if (samePointers(this.P2, pointer)) return;
    this.P2 = pointer;
    this.zoomRect.style.left   = Math.min(this.P1[0],  this.P2[0])+'px';
    this.zoomRect.style.top    = Math.min(this.P1[1],  this.P2[1])+'px';
    this.zoomRect.style.width  = Math.max(Math.abs(this.P1[0]-this.P2[0])+(browser_MSIE?-4:1), 0)+'px';
    this.zoomRect.style.height = Math.max(Math.abs(this.P1[1]-this.P2[1])+(browser_MSIE?-4:1), 0)+'px';
	},


  // performs an action assigned to MoveControl
	takeAction: function(event) {
    this.finish(event);

    // if that was a mouse-click
    if ((!this.hasMoved) && samePointers(this.P1,this.P2)) {
      var new_center   = imapa.projection.transformW2R(this.P2[0],this.P2[1]);
      var new_scale    = (imapa.projection.isSynopsis) ? imapa.config.maxScale/100 : imapa.projection.scale/2;
      var new_rotation = (imapa.projection.isSynopsis) ?  0.0  : imapa.projection.rotation;
      var effect = (function() {
        imapa.mapimage.effectScaleAndMove(-this.P2[0]+imapa.mapimage.getWidth()/2, -this.P2[1]+imapa.mapimage.getHeight()/2, imapa.projection.scale/new_scale*100);
      }).bind(this);
      imapa.analytics.tracker('navigation/zoom-point');  
      imapa.mapcontroller.setMap(new_center, new_scale, new_rotation, effect);
      return true;
    }
    
    var x1 = Math.min(this.P1[0], this.P2[0]);
	  var y1 = Math.min(this.P1[1], this.P2[1]);
  	var x2 = Math.max(this.P1[0], this.P2[0]);
  	var y2 = Math.max(this.P1[1], this.P2[1]);
	  var c1 = imapa.projection.transformW2R(x2, y1);
  	var c2 = imapa.projection.transformW2R(x1, y2);

   	var maprect = new MapRect(c1.y, c1.x, c2.y, c2.x, imapa.projection.rotation);
    imapa.analytics.tracker('navigation/zoom-rect');  
    imapa.mapcontroller.zoomRect(maprect);
    return true;
	}
};



//-----------------------------------------------------------------------------------
// MoveControl
//-----------------------------------------------------------------------------------

// helper class to MapControl.Navigation, which takes care of moving map by mouse

var MoveControl = Class.create();
MoveControl.prototype = {

  initialize: function(event) {
    // mouse-move handler binding
    this.onMouseMoveHandler = this.onMouseMove.bindAsEventListener(this);
    
    this.mapImage = $('mapimage-b');
    this.P1 = this.P2 = this.getMousePointerPosition(event);

    // hide overlay graphics
    imapa.mapimage.groverlay.disable();

    // start observing
    this.hasMoved = false;
    Event.observe(document, "mousemove", this.onMouseMoveHandler);
	},


	// [private] finish: show element and install observers for mousemove events
	finish: function(event) {
    this.mapImage.style.cursor = 'default';
    // uninstall event handlers
    Event.stopObserving(document, "mousemove", this.onMouseMoveHandler);
    // record the latest mouse position
    if (event) this.P2 = this.getMousePointerPosition(event);

    var p = imapa.projection.duplicate();
    p.center.y += +(this.P2[0]-this.P1[0])*p.pixSize;
    p.center.x += -(this.P2[1]-this.P1[1])*p.pixSize;
    imapa.mapimage.groverlay.enable(p);
	},


	// cancel
	cancel: function() {
    this.P2 = this.P1;
    this.finish(null);
    Element.show('mapimage-a');
    this.mapImage.style.left = '0px';
    this.mapImage.style.top  = '0px';
  },


  // [public] get click coordinates
  coord: function(event) {
    return {
      down:  imapa.projection.transformW2R(this.P1[0],this.P1[1]),
      up:    imapa.projection.transformW2R(this.P2[0],this.P2[1]),
      click: ((!this.hasMoved) && samePointers(this.P1,this.P2)) ? imapa.projection.transformW2R(this.P2[0],this.P2[1]) : null
    }; 
  },


	// [private] get the mouse pointer position relative to the parent object
  // (i.e. map-window container)
  getMousePointerPosition: function(event) {
    return [
      Event.pointerX(event) - imapa.mapimage.mapimageOffset[0], 
      Event.pointerY(event) - imapa.mapimage.mapimageOffset[1]
    ];
  },


	// [private] mousemove event handler
  onMouseMove: function(event) {
    if (!this.hasMoved) {
      this.mapImage.style.cursor = 'move';
      Element.hide('mapimage-a');
      this.hasMoved = true;
    }
    var pointer = this.getMousePointerPosition(event);
    if (samePointers(this.P2, pointer)) return;
    this.P2 = pointer;
    this.mapImage.style.left = (this.P2[0]-this.P1[0])+'px';
    this.mapImage.style.top  = (this.P2[1]-this.P1[1])+'px';
  },


  // performs an action assigned to MoveControl
  takeAction: function(event) {
    this.finish(event);

    // if that was a mouse-click
    if ((!this.hasMoved) && samePointers(this.P1,this.P2)) {
      var mapcoord = imapa.projection.transformW2R(this.P2[0],this.P2[1]);
      if (imapa.projection.isSynopsis) {
        var new_scale = imapa.config.maxScale/100;
        imapa.analytics.tracker('navigation/zoom-point-synopsis'); 
        imapa.mapcontroller.setMap(mapcoord, new_scale, 0.0, (function() {imapa.mapimage.effectScaleAndMove(-this.P2[0]+imapa.mapimage.getWidth()/2, -this.P2[1]+imapa.mapimage.getHeight()/2, imapa.projection.scale/new_scale*100);}).bind(this))
      } else {
        // pass control to active user-interface mode
        return false;
      }
      return true;
     }
    
    // if not, move the new projection center
	  var c1 = imapa.projection.transformW2R(this.P1[0], this.P1[1]);
  	var c2 = imapa.projection.transformW2R(this.P2[0], this.P2[1]);

    var newCenter = new MapCoord(
      imapa.projection.center.y - (c2.y-c1.y),
      imapa.projection.center.x - (c2.x-c1.x)
    );
    
    imapa.analytics.tracker('navigation/move'); 
    imapa.mapcontroller.setMap(newCenter, imapa.projection.scale, imapa.projection.rotation, null);
    return true;
  }
};



//-----------------------------------------------------------------------------------
// Control.ZoomSlider
//-----------------------------------------------------------------------------------

// component of the zoom slider for the navigation mode

Control.ZoomSlider = Class.create();
Object.extend(Object.extend(Control.ZoomSlider.prototype, Control.Slider.prototype), {
  setScale: function(scale) {
    this.initialized = false;
    this.setValue(Math.log(scale)/Math.log(10));
    this.initialized = true;
  },
  
  getScale: function() {
    return Math.pow(10,this.value);
  }
});


  

//**************************************************************************
//    imapa-ui-mode-info.js - uživatelské rozhraní ovládání mapy
//--------------------------------------------------------------------------
//    Datum vytvoření   : 4.7.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-ui.js,v 1.2 2007-06-19 09:08:01 michal Exp $


// UserInterface - class to handle visual operations upon the 'side-bar' control
UI.Mode.Info = Class.create();
Object.extend(Object.extend(UI.Mode.Info.prototype, UI.Mode.Base.prototype), {

  initialize: function() {
    this.enabled = true;
  },
  
  
  enable: function() {
    this.enabled = true;
  },
  
  
  disable: function() {
    this.enabled = false;
  },
  
  
  onMouseClick: function(mapcoord) {
    if (!this.enabled) return;
    imapa.analytics.tracker('navigation/info'); 
    imapa.sidebar.info(mapcoord);
  },
  
  
  dummy: function() {}
  
});
//**************************************************************************
//    imapa-mapserver.js - rozhraní pro komunikacis GisServerem
//--------------------------------------------------------------------------
//    Datum vytvoření   : 20.1.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-mapserver.js,v 1.3 2008-01-11 09:20:03 michal Exp $


var MapServer = Class.create();
MapServer.prototype = {
  initialize: function() {
  },
    

  execRequest: function(request_id, params, options, json) {
    Object.extend(params, {rid: request_id});
    var request_options = {
      method: 'get',
      parameters: params,
      asynchronous: (options.async && options.async==false) ? false : true,
      onSuccess: function(transport){
          var response = json ? eval('('+transport.responseText+')') : transport.responseText;
          if (options.onAfter) options.onAfter(response);
      },
      onFailure: function(transport){
          if (options.onError) options.onError(transport.responseText); else alert('mapserver request failed ('+request_id+'): '+transport.responseText);;
      },
      onComplete: (function(){
          if (options.indicator) Element.hide(options.indicator);
      }).bind(this)
    };

    if (options.indicator) Element.show(options.indicator);
    if (options.onBefore) options.onBefore();
    new Ajax.Request('imapa.aspx', request_options);

    // support for Google Analytics
    // - logs requests to mapserver as a separate page hits
    imapa.analytics.tracker('map-server/'+request_id);  
  },


  requestSynopsis: function(options, width, height, layers) {
    var params = {
      WN: width  ? width  : imapa.mapwindow.clientWidth,
      HN: height ? height : imapa.mapwindow.clientHeight,
      LY: layers ? encodeLayers(layers) : encodeLayers(imapa.projection.layers),
      JSON: 1
    };
    this.execRequest('synopsis', params, options, true);
  },
  
  
  requestMap: function(center, scale, rotation, options) {
    var params = {
      CY: center.y,
      CX: center.x,
      SC: scale,
      AN: rotation,
      WN: imapa.mapwindow.clientWidth,
      HN: imapa.mapwindow.clientHeight,
      LY: encodeLayers(imapa.projection.layers),
      JSON: 1
    };
    this.execRequest('map', params, options, true);
  },
  
  
  requestMapRect: function(maprect, options) {
  //--------------------------------
    var params = {
      P1Y: maprect.y1,
      P1X: maprect.x1,
      P2Y: maprect.y2,
      P2X: maprect.x2,
      AN: imapa.projection.rotation,
      WN: imapa.mapwindow.clientWidth,
      HN: imapa.mapwindow.clientHeight,
      LY: encodeLayers(imapa.projection.layers),
      JSON: 1
    };
    this.execRequest('map-rect', params, options, true);
  },

  
  requestFindRdn: function(options) {
  //--------------------------------
    var params = {}
    this.execRequest('find-rdn', params, options, false);
  },
  
  
  requestLocateRdn: function(rdn_id, options) {
  //--------------------------------
    var params = {
      ID: rdn_id,
      AN: imapa.projection.rotation,
      WN: imapa.mapwindow.clientWidth,
      HN: imapa.mapwindow.clientHeight,
      LY: encodeLayers(imapa.projection.layers),
      JSON: 1
    };
    this.execRequest('locate-rdn', params, options, true);
  },

  
  requestInfoRdn: function(rdn_id, options) {
  //--------------------------------
    var params = {
      ID: rdn_id
    };
    this.execRequest('info-rdn', params, options, false);
  },


  requestFindStn: function(options) {
  //--------------------------------
    var params = {}
    this.execRequest('find-stn', params, options, false);
  },

/*
  requestFindCadOrDst: function(options) {
  //--------------------------------
    var params = {}
    this.execRequest('find-caddst', params, options, false);
  },
*/

  requestFindCad: function(options) {
  //--------------------------------
    var params = {}
    this.execRequest('find-cad', params, options, false);
  },


  requestInfoCad: function(cad_id, options) {
  //--------------------------------
    var params = {
      ID: cad_id
    };
    this.execRequest('info-cad', params, options, false);
  },


  requestInfoDst: function(dst_id, options) {
  //--------------------------------
    var params = {
      ID: dst_id
    };
    this.execRequest('info-dst', params, options, false);
  },


  requestLocateCad: function(cad_id, options) {
  //--------------------------------
    var params = {
      ID: cad_id,
      AN: imapa.projection.rotation,
      WN: imapa.mapwindow.clientWidth,
      HN: imapa.mapwindow.clientHeight,
      LY: encodeLayers(imapa.projection.layers),
      JSON: 1
    };
    this.execRequest('locate-cad', params, options, true);
  },


  requestFindDst: function(options) {
  //--------------------------------
    var params = {}
    this.execRequest('find-dst', params, options, false);
  },


  requestLocateDst: function(dst_id, options) {
  //--------------------------------
    var params = {
      ID: dst_id,
      AN: imapa.projection.rotation,
      WN: imapa.mapwindow.clientWidth,
      HN: imapa.mapwindow.clientHeight,
      LY: encodeLayers(imapa.projection.layers),
      JSON: 1
    };
    this.execRequest('locate-dst', params, options, true);
  },
  

  requestLocateStn: function(stn_id, options) {
  //--------------------------------
    var params = {
      ID: stn_id,
      AN: imapa.projection.rotation,
      WN: imapa.mapwindow.clientWidth,
      HN: imapa.mapwindow.clientHeight,
      LY: encodeLayers(imapa.projection.layers),
      JSON: 1
    };
    this.execRequest('locate-stn', params, options, true);
  },


  requestLayers: function(options) {
  //--------------------------------
    var params = {};
    this.execRequest('layers', params, options, false);
  },

  requestInfo: function(coord, options) {
  //--------------------------------
    var params = {
      CY: coord.y,
      CX: coord.x,
      SC: imapa.projection.scale,
      AN: imapa.projection.rotation,
      LY: encodeLayers(imapa.projection.layers),
      dialog: 0
    };
    this.execRequest('info', params, options, false);
  },

  requestInfoStn: function(stn_id, options) {
  //--------------------------------
    var params = {
      ID: stn_id
    };
    this.execRequest('info-stn', params, options, false);
  },


  requestMarkPoint: function(options) {
  //--------------------------------
    var params = {
    };
    this.execRequest('mark-point', params, options, false);
  },


  dummy: function() {}

  };




//**************************************************************************
//    imapa-groverlay.js - kresba vrstvy vektorové grafiky v prohlížeči
//--------------------------------------------------------------------------
//    Datum vytvoření   : 9.6.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-groverlay.js,v 1.1 2007-06-19 09:08:01 michal Exp $


var GraphicsOverlay = Class.create();
GraphicsOverlay.prototype = {

  // class constructor
  initialize: function(parent) {
    // store parent element for graphic objects
    this.parent = $(parent);
    this.objects = new Array();
  },
  
  
  enable: function(projection) {
    if (projection) this.update(projection);
    for (var i=0; i<this.objects.length; i++) this.objects[i].show(true);
  },

  
  disable: function() {
    for (var i=0; i<this.objects.length; i++) this.objects[i].hide(true);
  },

  
  showAll: function(projection) {
    if (projection) this.onProjectionChange(projection);
    for (var i=0; i<this.objects.length; i++) this.objects[i].show();
  },

  
  hideAll: function() {
    for (var i=0; i<this.objects.length; i++) this.objects[i].hide();
  },

  
  clearAll: function() {
    for (var i=0; i<this.objects.length; i++) this.objects[i].finalize();
    this.objects = new Array();
  },

  
  update: function(new_projection) {
    for (var i=0; i<this.objects.length; i++) this.objects[i].update(new_projection);
  },
  
  
  drawLine: function(coords) {
    var object = new ObjLine(this.parent, coords);
    this.objects.push(object);
    return object;
  },
  
  
  drawPoint: function(center, size) {
    var object = new ObjPoint(this.parent, center, size);
    this.objects.push(object);
    return object;
  },
  
  
  dummy: function() {}
};



//----------------------------------------------------------------------------
// ObjLine
//----------------------------------------------------------------------------

var ObjLine = Class.create();
ObjLine.prototype = {

  initialize: function(parent, coords) {
    this.data = {coords: null, lengths: null, points: null};
    this.data.coords  = makeCoordArray(coords);
    this.data.lengths = makeSegmentLengths(this.data.coords);

    this.visible = false;
    this.object = document.createElement('v:polyline');
    this.object.fillcolor='yellow';
    this.object.filled=false;
    this.object.strokecolor='red';
    this.object.strokeweight='5px';
    this.object.style.zIndex='100';
    this.object.style.position='absolute';
    this.object.style.top='0px';
    this.object.style.left='0px';
    this.object.style.display = (this.visible) ? '' : 'none';
    parent.appendChild(this.object);
    this.update(imapa.projection);
  },
  
  
  finalize: function() {
    Element.remove(this.object);
    this.object = null;
  },
  
  
  show: function(temporarily) {
    if (!temporarily) this.visible = true;
    if (this.visible) Element.show(this.object);
  },
 
 
  hide: function(temporarily) {
    if (!temporarily) this.visible = false;
    Element.hide(this.object);
  },

  
  update: function(new_projection) {
    this.data.points = new_projection.transformR2WArray(this.data.coords);
    var s = '';
    for (var i=0; i<this.data.points.length; i++) s += this.data.points[i][0] + 'px,' + this.data.points[i][1] + 'px,';
    this.object.points.value = s.substr(0,s.length-1);
  },
  

  getCoordAlongLine: function(t) {
  // gets a coordinate of a point along the line pointed to by an affine parameter t (t in [0,1])
    // find boundary coordinates
    var i = 0;
    while ((this.data.lengths[i+1] < t) && (i < this.data.lengths.length-2)) i++;
    var p1 = this.data.coords[i];
    var p2 = this.data.coords[i+1];
    // calculate position
    var s = (t-this.data.lengths[i])/(this.data.lengths[i+1]-this.data.lengths[i]);
    return new MapCoord( p1.y*(1.0-s) + p2.y*s,  p1.x*(1.0-s) + p2.x*s);
  },
  
  getAffineParam: function(coord) {
  // inverse function to getCoordAlongLine - having a coordinate point 
  // returns the affine parameter along the line
    // for each segment of line calculate the weighted distance of the point from the abscisa
    var distances = new Array();
    for (var i=0; i<this.data.coords.length-1; i++) {
      var a = coordDistance(coord, this.data.coords[i]);
      var b = coordDistance(coord, this.data.coords[i+1]);
      var c = coordDistance(this.data.coords[i], this.data.coords[i+1]);
      distances.push(a/c + b/c);
    }
    // find a point of miminal distance
    var index = 0;
    for (var i=1; i<distances.length; i++) if (distances[i] < distances[index]) index = i;
    // get the two boudary vertices
    var p1 = this.data.coords[index];
    var p2 = this.data.coords[index+1];
    var s  = coordDistance(coord,p1)/(coordDistance(coord,p1) + coordDistance(coord,p2));
    // get the line lengths at boundary points
    var L1 = this.data.lengths[index];
    var L2 = this.data.lengths[index+1];
    // calculate the affine parameter
    return (L1*(1.0-s) + L2*s) / this.data.lengths[this.data.lengths.length-1];
  }

};



//----------------------------------------------------------------------------
// ObjPoint
//----------------------------------------------------------------------------

var ObjPoint = Class.create();
ObjPoint.prototype = {

  initialize: function(parent, center, size) {
    this.data = {center: center, position: null, size: (size%2==0)?size:size+1};
    this.visible = false;
    this.object = document.createElement('v:oval');
    this.object.fillcolor='yellow';
    this.object.style.zIndex='100';
    this.object.style.position='absolute';
    this.object.style.width  = this.data.size+'px';
    this.object.style.height = this.data.size+'px';
    this.object.style.display = (this.visible) ? '' : 'none';
    parent.appendChild(this.object);
    this.update(imapa.projection);
  },
  
  
  finalize: function() {
    Element.remove(this.object);
    this.object = null;
  },
  
  
  show: function(temporarily) {
    if (!temporarily) this.visible = true;
    if (this.visible) Element.show(this.object);
  },
 
 
  hide: function(temporarily) {
    if (!temporarily) this.visible = false;
    Element.hide(this.object);
  },

  
  update: function(new_projection) {
    this.data.position = new_projection.transformR2W(this.data.center);
    this.object.style.left = (this.data.position[0]-this.data.size/2)+'px';
    this.object.style.top  = (this.data.position[1]-this.data.size/2)+'px';
  }
  
};



//**************************************************************************
//    imapa-search.js - průběžné dohledávání objeků podle jména
//--------------------------------------------------------------------------
//    Datum vytvoření   : 16.1.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-search.js,v 1.1 2007-06-19 09:08:01 michal Exp $


var SearchAutocompleter = Class.create();
SearchAutocompleter.prototype = {
  initialize: function(element, update, url, options, rid) {
    this.element     = $(element); 
    this.update      = $(update);  
    this.url         = url;
    this.changed     = false; 
    this.active      = false; 
    this.options     = options;
    this.rid         = rid;
    
    this.options.asynchronous  = true;
    this.options.defaultParams = options.parameters || null;
    this.options.paramName     = options.paramName || this.element.name;
    this.options.frequency     = options.frequency || 0.4;
    this.options.minChars      = options.minChars || 1;

    this.observer = null;
   
    this.element.setAttribute('autocomplete','off');

    Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
  },


  onKeyPress: function(event) {
    if((event.keyCode==Event.KEY_TAB) || (event.keyCode==Event.KEY_RETURN) || 
      ((navigator.appVersion.indexOf('AppleWebKit') > 0) && (event.keyCode == 0))) return;

    this.changed = true;

    if (this.observer) clearTimeout(this.observer);
    this.observer =  setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },


  onObserverEvent: function() {
    this.changed = false;   
    if(this.element.value.length>=this.options.minChars) {
      this.updatedChoices();
    } else {
      Element.update(this.update, '');
    }
  },


  updatedChoices: function() {
    //this.options.parameters = 
    //  encodeURIComponent(this.options.paramName) + '=' + encodeURIComponent(this.element.value);

    //if(this.options.defaultParams) 
    //  this.options.parameters += '&' + this.options.defaultParams;

    var xparams = {
      name: this.element.value, //encodeURIComponent(this.element.value),
      hint: 1,
      max: 0
    };
    var xoptions = {
      indicator: imapa.indicator,
      onAfter: (function(html) {
          Element.update(this.update, html);
      }).bind(this)
    };

    imapa.mapserver.execRequest(this.rid, xparams, xoptions, false);
  },
  
  dummy: function() {}
  
};

//**************************************************************************
//    imapa-menu.js - jednoduché drop-down menu
//--------------------------------------------------------------------------
//    Datum vytvoření   : 14.1.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-menu.js,v 1.2 2008-01-11 09:20:03 michal Exp $

var current_menu = null;

var Menu = Class.create();
Menu.prototype = {
	initialize: function(control_element) {
    this.control_element = $(control_element);

    this.main_element = document.createElement("div");
    this.main_element.className = 'popup-menu-main'
    Element.hide(this.main_element);
    document.body.appendChild(this.main_element);
    
    this.hide_timeout = null;
    
    Event.observe(this.control_element, "click",     this.onClick.bindAsEventListener(this));
    Event.observe(this.control_element, "mouseout",  this.onMouseOut.bindAsEventListener(this));
    Event.observe(this.control_element, "mouseover", this.onMouseOver.bindAsEventListener(this));
    Event.observe(this.main_element,    "mouseout",  this.onMouseOut.bindAsEventListener(this));
    Event.observe(this.main_element,    "mouseover", this.onMouseOver.bindAsEventListener(this));
	},
  
  addNode: function(text, onclick) {
    var node = document.createElement("div");
    node.className = 'popup-menu-item'
    node.innerHTML = text;
    this.main_element.appendChild(node);
    Event.observe(node, "click", (function(){this.menuHide();onclick();}).bind(this));
  },

  onClick: function() {
    if (!Element.visible(this.main_element)) this.menuShow(); else this.menuHide();
  },
  
  onMouseOut: function() {
    this.hide_timeout = setTimeout(this.menuHide.bind(this), 250);
  },
  
  onMouseOver: function() {
    if (this.hide_timeout) clearTimeout(this.hide_timeout);
    this.hide_timeout = null;
    this.menuShow();
  },
  
  menuShow: function() {
    if ((current_menu) && (current_menu != this)) current_menu.menuHide();
    var pos = Position.cumulativeOffset(this.control_element);
    pos[1] += Element.getHeight(this.control_element) + 3;
    this.main_element.style.left = pos[0]+'px';
    this.main_element.style.top  = pos[1]+'px';
    Element.show(this.main_element);
    current_menu = this;
  },
  
  menuHide: function() {
    if (this.hide_timeout) clearTimeout(this.hide_timeout);
    this.hide_timeout = null;
    current_menu = null;
    Element.hide(this.main_element);
  },
  
  dummy: function() {}
};

//**************************************************************************
//    imapa-analytics.js - statistiky
//--------------------------------------------------------------------------
//    Datum vytvoření   : 3.7.2007
//    Správce           : Michal Bursa
//    Součást projektu  : iMapa
//--------------------------------------------------------------------------
//    Copyright (c) 2007  CDSw - City Data Software s.r.o.
//**************************************************************************
//    $Id: imapa-config.js,v 1.2 2007-06-19 09:08:01 michal Exp $



var MapAnalytics = Class.create();
MapAnalytics.prototype = {
 
  initialize: function() {
    this.google = ((typeof pageTracker != 'undefined') && (pageTracker));

  },
  
  tracker: function(page) {
    if (this.google) pageTracker._trackPageview(page);
  },
    
  dummy: function() {}
};
Object.extend(iMapa.prototype, {

  resize: function() {
    var newheight =
      (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight) -
      Element.getHeight('imapa-header') - Element.getHeight('imapa-toolbar') - Element.getHeight('imapa-footer') -
      5 /* container.padding-top */ - 5 /* container.padding-bottom */;
    newheight = Math.max(350,newheight);
    $('imapa-mapwindow').style.height = newheight+'px';
    $('sidebar').style.height = newheight+'px';
  }

});

//-----------------------------------------------------------------------------------

Object.extend(MapServer.prototype, {

  redirectTSK: function() {
    var params = {
      AN: imapa.projection.rotation,
      WN: imapa.mapwindow.clientWidth,
      HN: imapa.mapwindow.clientHeight,
      LY: encodeLayers(imapa.projection.layers),
      JSON: 1
    };

    this.execRequest('locate-redirect', params, {}, true);
  }

});

//-----------------------------------------------------------------------------------
