// 20050927 - Copyright (C) 2005-2006 Simone Manca <simone.manca@gmail.com>
// http://datacrossing.crs4.it/en_Documentation_mscross.html
// v1.1.9 20070218
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Old code
//Object.prototype.objRef = null;

var browser = new Browser();
var dragObj = new Object();
dragObj.zIndex = 0;
var langResDict={

  'licenseerror_pl':'B\u0142\u0105d licencji',
  'licenseerror_en':'License error',
  'licenseerror_de':'License error',

  'licensereload_pl':'Za\u0142adowa\u0107 stronê ponownie?',
  'licensereload_en':'Reload page?',
  'licensereload_de':'Reload page?',

  'ticketerror_pl':'Bilet niewa\u017Cny',
  'ticketerror_en':'Ticket expired',
  'ticketerror_de':'Ticket expired',

  'info_pl':'Informacja i wsp\u00F3\u0142rz\u0119dne',
  'info_en':'Information and coordinates',
  'info_de':'Angabe und Koordinaten',
  
  'fullview_pl':'Pe\u0142ny widok mapy',
  'fullview_en':'Full view',
  'fullview_de':'Gef\u00FCllt Ansicht',
  
  'move_pl':'Przesu\u0144',
  'move_en':'Pan',
  'move_de':'Verschieben',
  
  'zoomin_pl':'Przybli\u017C',
  'zoomin_en':'Zoom in',
  'zoomin_de':'Hineinzoomen',
  
  'zoomout_pl':'Oddal',
  'zoomout_en':'Zoom out',
  'zoomout_de':'Herauszoomen',

  'geturl_pl':'Pobierz link do mapy',
  'geturl_en':'Get url',
  'geturl_de':'Get url',

  'preview_pl':'Podgl\u0105d wydruku',
  'preview_en':'Print preview',
  'preview_de':'Print preview',
  
  'togglefullview_pl':'Pe\u0142ny ekran',
  'togglefullview_en':'Full screen',
  'togglefullview_de':'Full screen',
  
  'nodata_pl':'Brak danych',
  'nodata_en':'No results',
  'nodata_de':'No results',
  
  'connectionerror_pl':'Problem z dost\u0119pem do serwera',
  'connectionerror_en':'Connection error',
  'connectionerror_de':'Connection error',

  'xmlhttpiniterror_pl':'Problem z zainicjowaniem obiektu XMLHttp',
  'xmlhttpiniterror_en':'Error initializing XMLHttp',
  'xmlhttpiniterror_de':'Error initializing XMLHttp',

  'getposition_pl':'Oznacz pozycj\u0119 na mapie',
  'getposition_en':'Set position on the map',
  'getposition_de':'Set position on the map'

}

// msMap class prototype
function msMap(DivTag, ControlType, p_lang, p_jspath, p_license, p_ticket, p_callmethod, p_protocol)
{
  // Private vars
  var i= this;

  var _ilicense=p_license;
  if (_ilicense == null) {_ilicense=''};

  var _iticket=p_ticket;
  if (_iticket == null) {_iticket=''};

  var _tagMain = DivTag;
  
  var _map_w   = parseInt( _tagMain.style.width );
  var _map_h   = parseInt( _tagMain.style.height );

  var _mscross_path=p_jspath;
  if (_mscross_path == null) {_mscross_path = 'inc/mscross/'};
  
  var _protocol = p_protocol; // 'mapservercgi', 'wms'
  if (_protocol == null) {_protocol = 'mapservercgi'};

  var _callmethod = p_callmethod; // 'jsonp', 'ajax'
  if (_callmethod == null) {_callmethod = 'jsonp'};
  
  
  
  // Hidden map border in in pixel. You can set map size highter respect
  // div size (visible map)
  var _map_w_bord = 0; var _map_h_bord = 0;

  var _ref_w_bord = 2; var _ref_h_bord = 2;

  //var _action  = 'pan';  // pan, zoom, none // xxx old
  var _control=ControlType;
  var _cgi='/cgi-bin/mapserv';
  var _tcgi='';
  var _ppreview='';
  var _togglefullview='';
  var _docurl='';
  var _mode='map';
  var _layers='';
  var _otherlayers='';
  var _constlayers='';
  var _lang= p_lang;
  if (_lang == null) {
     _lang='pl';
  }

  var _map_file;
  var _args = '';
  var _attachedMsMap = null;
  var _referenceMap  = null;
  var _report = null;
  var _loading_counter = 0;
  var _read_cookie = false;
  var _SResultOptimalZoom = 300; // $$SK
  var _ext_Xmin_orig; var _ext_Xmax_orig;
  var _ext_Ymin_orig; var _ext_Ymax_orig;
  var _ext_Xmin = null; var _ext_Xmax = null;
  var _ext_Ymin = null; var _ext_Ymax = null;
  
  var _zoombox_x_first; var _zoombox_y_first;
  var _zoombox_x_last;  var _zoombox_y_last;
  var _pixel_w; var _pixel_h;

  // Double buffering
  var _tagMap   = document.createElement('img');
  var _tagMap_B = document.createElement('img');
  this.getTagMap = function(){return _tagMap;}
  this.getTagEvent = function(){return _tagEvents;}

  var _tagLegendImg   = null;  // $$RS
  var _tagLegendDiv = null;
  var _tagQueryDiv = null;
  var _tagExtentDiv = null;
  var _tagLatDiv = null;
  var _tagLonDiv = null;
  var _tagScaleDiv = null;
  var _tagZoomDiv = null;
  var _tagQstring = new Array();
  var _qlayer = new Array();
  var _qitem = new Array();
  var _queryFile = '';
  var _latstqlayer = '';

  var _queryParams = '';  
  
  var _tagZoombox   = document.createElement('div');
  var _tagReference = document.createElement('div');
  var _tagLoading   = document.createElement('img');
  var _tagOverlay   = document.createElement('div'); // Overlay Layer
  var _tagPoints    = document.createElement('div'); // Points Overlay container
  var _tagInfo      = document.createElement('div'); // Report win Overlay container
  var _tagEvents    = document.createElement('div');

  var _referenceMinBoxSize=4;

  var _iconCloseButton = _mscross_path + 'img/buttons/decline.png';

  
//  var _Xclick; var _Yclick;

  var _toolbars = new Array(); // Array of toolbars
  this.getToolbar = function(p){return _toolbars[p];}
  var _iconLoading = _mscross_path + 'img/earth_loader.gif';


  // Disable text/images selection.
  if ( browser.isIE )
  {
    _tagMain.onselectstart = function(){return false;};
    _tagMain.ondrag = function(){return false;};
  } else
  { _tagMain.style.setProperty("-moz-user-select", "none", ""); }

  
  i.show_loading_image = function(p)
  {
    if (p == true)
    {
      _loading_counter++;
      _tagLoading.style.display = '';
    }
    if (p == false)
    {
      _loading_counter--;  if (_loading_counter < 0) { _loading_counter = 0; }
      //xxx errore!!! da risolvere!!!    if (_loading_counter == 0)
      { _tagLoading.style.display = 'none'; }
    }
  }

  // Active Debug mode
  this.debug = function()
  {
    var db = document.createElement('a');
    db.oncontextmenu    = function(){return false;};
    setZindex(db, '110');
    db.style.position   = 'absolute';
    db.style.fontFamily = 'Verdana, Arial, Helvetica, sans-serif';
    db.style.fontSize   = '11px';
    db.style.left       = i.width()-72+'px';
    db.style.top        = i.height()-13+'px';
    db.style.fontWeight = 'normal';
    db.style.textDecoration = 'overline';
    db.appendChild(document.createTextNode("Debug INFO"));
    _tagMain.appendChild(db);
    add_event(db, 'click', function(){ prompt('Debug INFO',i.get_map_url()) } );
  }

  // Check if a box (x, y, width, height) is within a map
  this.isPointInMap = function( p_x, p_y, p_w, p_h )
  {
    if ( (p_x > (_ext_Xmax+i.wPixel2real(_map_w_bord))) ||
         ((p_x+p_w) < (_ext_Xmin-i.wPixel2real(_map_w_bord))) ) return false;
    if ( ((p_y-p_h) > (_ext_Ymax+i.hPixel2real(_map_h_bord))) ||
         ((p_y+p_h-p_h) < (_ext_Ymin-i.hPixel2real(_map_h_bord))) ) return false;
    return true;
  }

  // Imposta il bordo intorno alla mappa.
  this.setBorder = function(p)
  {
    _map_w_bord = p; _map_h_bord = p;

    // First image buffer (double buffer)
    _tagMap.style.width  = (i.width()+_map_w_bord+_map_w_bord)+'px';
    _tagMap.style.height = (i.height()+_map_h_bord+_map_h_bord)+'px';
    _tagMap.style.top    = (- _map_w_bord) +'px';
    _tagMap.style.left   = (- _map_h_bord) +'px';

    // Second image buffer (double buffer)
    _tagMap_B.style.width  = _tagMap.style.width;
    _tagMap_B.style.height = _tagMap.style.height;
    _tagMap_B.style.top    = _tagMap.style.top;
    _tagMap_B.style.left   = _tagMap.style.left;
  }
  this.getBorder = function() {return _map_w_bord;}

  this.addClickTool = function()
  { //xxx
    i.getToolbar(0).addMapTool('Select', i.setActionSelect, _iconSelectButton);
  }

  this.width=function() { return _map_w; }
  this.height=function() { return _map_h; }
//  this.action     = function() { return _action; }
  this.control=function() { return _control; }

  this.lang=function() { return _lang; }
  this.mscrosspath=function() { return _mscross_path; }

  this.setCgi=function(path) { _cgi = path; }
  this.setTCgi=function(path) { _tcgi = path; }
  this.setDocUrl=function(path) { _docurl = path; }
  this.getDocUrl=function() { return _docurl; }
  
  this.setPPreview=function(path) { _ppreview = path; }
  this.getPPreview=function() { return _ppreview; }
  
  this.setTFullView=function(path) { _togglefullview = path; }
  this.getTFullView=function() { return _togglefullview; }
  
  
  
  this.setMapFile=function(p_mapFile) { _map_file = 'map='+p_mapFile; }
  this.setMode=function(p_mode) { _mode = p_mode; }
  this.setLayers=function(p_layers) { _otherlayers=p_layers; _layers = _constlayers + ' ' + _otherlayers; }
  this.getLayers=function() { if (_otherlayers=='') {return '-1';} else {return _otherlayers;}; }
  this.setConstLayers=function(p_layers) { _constlayers = p_layers }  
  this.setArgs=function(p_args) { _args = p_args; }
  this.attachMap=function(myMap) { _attachedMsMap = myMap; }
  this.setReferenceMap=function(myMap) { _referenceMap = myMap; _referenceMap.setReferenceBox(_ext_Xmin, _ext_Xmax, _ext_Ymin, _ext_Ymax);}

//  this.setClickCoords = function(p_x ,p_y) { _Xclick = i.xPixel2Real(p_x); _Yclick = i.yPixel2Real(p_y); }

  this.setReferenceBox = function(p_Xmin, p_Xmax, p_Ymin, p_Ymax)
  {
    //i.fullExtentNoRedraw();  // 20060316
    var Xmin = i.xReal2pixel(p_Xmin); var Ymin = i.yReal2pixel(p_Ymin);
    var Xmax = i.xReal2pixel(p_Xmax); var Ymax = i.yReal2pixel(p_Ymax);
    if ((Xmax - Xmin)<_referenceMinBoxSize) {
       _tagReference.style.left=(Xmin+Xmax)/2 - _referenceMinBoxSize/2 - _map_w_bord -_ref_w_bord +'px';
       _tagReference.style.width=_referenceMinBoxSize +'px';
    } else {
       _tagReference.style.left    = Xmin - _map_w_bord -_ref_w_bord +'px';
       _tagReference.style.width   = Xmax - Xmin +'px';
    }
    if ((Ymin-Ymax)<_referenceMinBoxSize) {
       _tagReference.style.top=(Ymin+Ymax)/2 - _referenceMinBoxSize/2 - _map_h_bord -_ref_h_bord +'px';
       _tagReference.style.height=_referenceMinBoxSize +'px';
    } else {
       _tagReference.style.top= Ymax - _map_h_bord -_ref_h_bord +'px';
       _tagReference.style.height= Ymin - Ymax +'px';
    }
    _tagReference.style.display = '';
   
  };
  
  this.setSResultOptimalZoom = function(sroptimalzoom) {
      if (sroptimalzoom>0) {
        _SResultOptimalZoom = sroptimalzoom;
      }
  }
  this.xReal2pixel = function(p_x)
  { return Math.round( _map_w * (p_x - _ext_Xmin) / (_ext_Xmax - _ext_Xmin) ); }
  this.yReal2pixel = function(p_y)
  { return Math.round( _map_h * (_ext_Ymax - p_y) / (_ext_Ymax - _ext_Ymin) ); }
  this.wPixel2real = function(p_w) { return (p_w * _pixel_w); }
  this.hPixel2real = function(p_h) { return (p_h * _pixel_h); }
  this.wReal2pixel = function(p_w) { return (p_w / _pixel_w); }
  this.hReal2pixel = function(p_h) { return (p_h / _pixel_w); }
  this.xPixel2Real = function(p_x) { return i.wPixel2real(p_x)+_ext_Xmin; }
  this.yPixel2Real = function(p_y) { return i.hPixel2real(_map_h-p_y)+_ext_Ymin; }

  this.setExtent  = function(Xmin, Xmax, Ymin)
  {
    Xmin = parseFloat(Xmin); Xmax = parseFloat(Xmax); Ymin = parseFloat(Ymin);
    _ext_Xmin = Xmin; _ext_Xmax = Xmax; _ext_Ymin = Ymin;
    _ext_Ymax = ((_map_h/_map_w)*(_ext_Xmax-_ext_Xmin)) + _ext_Ymin;
  }

  this.setExtentAll  = function(Xmin, Xmax, Ymin, Ymax)
  {
    Xmin = parseFloat(Xmin); Xmax = parseFloat(Xmax); Ymin = parseFloat(Ymin);
    _ext_Xmin = Xmin; _ext_Xmax = Xmax; _ext_Ymin = Ymin; _ext_Ymax = Ymax;
  }
  
  this.setFullExtent = function(Xmin, Xmax, Ymin, Ymax)
  {
    _ext_Xmin_orig = Xmin; _ext_Xmax_orig = Xmax; _ext_Ymin_orig = Ymin; _ext_Ymax_orig=Ymax;
//    _ext_Ymax_orig = ((_map_h/_map_w)*(_ext_Xmax_orig-_ext_Xmin_orig)) + _ext_Ymin_orig;
    if (_read_cookie == false)
    { i.fullExtentNoRedraw(); }  // 20060316 (IE bugfix)
  }

  this.getFullExtent = function()
  {
      return _ext_Xmin_orig+'+'+_ext_Ymin_orig+'+'+_ext_Xmax_orig+'+'+_ext_Ymax_orig;
  }

  this.getExtent = function() { return _ext_Xmin+','+_ext_Xmax+','+_ext_Ymin;}

  this.getCenterX = function()  {return (_ext_Xmin + _ext_Xmax)/2}

  this.getCenterY = function()  {return (_ext_Ymin + _ext_Ymax)/2}

  this.getCallMethod = function()  {return _callmethod}
  
  this.getSearchParams = function()  {return _tagQstring}
  

  this.setZoomboxFirst = function(x, y)
  { _zoombox_x_first = x; _zoombox_y_first = y; }

  this.setZoomboxWH = function(x, y)
  {
    _zoombox_x_last = x; _zoombox_y_last = y;
    _tagZoombox.style.left   = min(_zoombox_x_first, _zoombox_x_last) + 'px';
    _tagZoombox.style.top    = min(_zoombox_y_first, _zoombox_y_last) + 'px';
    _tagZoombox.style.width  = max(_zoombox_x_last,  _zoombox_x_first) -
                               min(_zoombox_x_last,  _zoombox_x_first) + 'px';
    _tagZoombox.style.height = max(_zoombox_y_last,  _zoombox_y_first) -
                               min(_zoombox_y_last,  _zoombox_y_first) + 'px';
    _tagZoombox.style.display = '';
  }

  this.zoomboxExtent = function()
  {
    _tagZoombox.style.display = 'none';

    var ll = min(_zoombox_x_last, _zoombox_x_first);
    var rr = max(_zoombox_x_last, _zoombox_x_first);
    var bb = max(_zoombox_y_last, _zoombox_y_first);
    var tt = min(_zoombox_y_last, _zoombox_y_first);

    var ext_Xmin =_ext_Xmin + ll * _pixel_w;
    var ext_Xmax =_ext_Xmax - (_map_w - rr) * _pixel_w;
    var ext_Ymax =_ext_Ymax - tt * _pixel_h;
    var ext_Ymin =_ext_Ymin + (_map_h - bb) * _pixel_h;

    if (((rr-ll) < 5) && ((bb-tt) < 5)) {
      var acenterX=(ext_Xmin + ext_Xmax) / 2;
      var acenterY=(ext_Ymin + ext_Ymax) / 2;
      this.setRecenter(acenterX, acenterY);
      i.zoomPerc(1.40);
    } else {
       _ext_Xmin=ext_Xmin;
       _ext_Xmax=ext_Xmax;
       _ext_Ymax=ext_Ymax;
       _ext_Ymin=ext_Ymin;    
    }
    i.setExtentAll(_ext_Xmin,_ext_Xmax,_ext_Ymin,_ext_Ymax);
    i.redraw();
  }

  this.zoomboxExtentOut = function()
  {
    _tagZoombox.style.display = 'none';

    var ll = min(_zoombox_x_last, _zoombox_x_first);
    var rr = max(_zoombox_x_last, _zoombox_x_first);
    var bb = max(_zoombox_y_last, _zoombox_y_first);
    var tt = min(_zoombox_y_last, _zoombox_y_first);

    var ext_Xmin =_ext_Xmin + ll * _pixel_w;
    var ext_Xmax =_ext_Xmax - (_map_w - rr) * _pixel_w;
    var ext_Ymax =_ext_Ymax - tt * _pixel_h;
    var ext_Ymin =_ext_Ymin + (_map_h - bb) * _pixel_h;

    var acenterX=(ext_Xmin + ext_Xmax) / 2.0;
    var acenterY=(ext_Ymin + ext_Ymax) / 2.0;
    this.setRecenter(acenterX, acenterY);

    if (((rr-ll) < 5) && ((bb-tt) < 5)) {
       i.zoomPerc(0.30);
    } else {

       var mw=_map_w/(rr-ll);
       var mh=_map_h/(bb-tt);
       var newW=(ext_Xmax-ext_Xmin)*mw*mw;
       var newH=(ext_Ymax-ext_Ymin)*mh*mh;

       _ext_Xmin=acenterX-(newW/2);
       _ext_Xmax=acenterX+(newW/2);
       _ext_Ymin=acenterY-(newH/2);
       _ext_Ymax=acenterY+(newH/2);
    }
    i.setExtentAll(_ext_Xmin,_ext_Xmax,_ext_Ymin,_ext_Ymax);
    i.redraw();
  }

  this.recalc_pixel_size = function()
  {
    _pixel_w  = (_ext_Xmax - _ext_Xmin) / _map_w;
    _pixel_h  = (_ext_Ymax - _ext_Ymin) / _map_h;
  }
  
  this.getTxtErrHandler = function(amessage) {
      alert(amessage);
      i.show_loading_image(false);    
  }
  
  this.setLegendTag = function(alegenddiv,alegendimg)
  { 
      _tagLegendDiv=alegenddiv;
      if (alegendimg!=null) {
         _tagLegendImg=alegendimg;
      }   
  }

  this.refreshLegend = function(ahtml)
  { 
    if  (ahtml=='LICENSE ERROR') {
      var respConfirmation=confirm(langResDict['licenseerror_'+_lang]+'. '+langResDict['licensereload_'+_lang]);
      if (respConfirmation==true) {
         window.location=i.getMapUrl(1);
      }
    };
    if  (ahtml=='TICKET ERROR') {
      var respConfirmation=confirm(langResDict['ticketerror_'+_lang]+'. '+langResDict['licensereload_'+_lang]);
      if (respConfirmation==true) {
         window.location=i.getMapUrl(1);
      }
    };
    _tagLegendDiv.innerHTML=ahtml.replace(/\[mapcnt\]/g,_tagLegendDiv.getAttribute('mapcnt'));
    var aisallchecked=true;
    jQuery("input",_tagLegendDiv).each(function(){
       if (this.checked==false) {
         aisallchecked=false;
       }
    });
    jQuery(_tagLegendDiv).find('.legTitle').prepend('<input type=\"checkbox\" ' + (aisallchecked == true ? "checked" : String.Empty) + ' onclick=\"chgLayers' + _tagLegendDiv.getAttribute('mapcnt') + '(this)\" />');
  }

  this.refreshBrowseInfo = function(ahtml)
  { 
    if (ahtml!='') {
//       prompt('',ahtml);
       alarray=ahtml.split('|');
       if (_tagScaleDiv!=null) {
          _tagScaleDiv.innerHTML=Math.round(alarray[0]*1);
       }      
    }
  }
  
  this.setQueryTag = function(aquerydiv)
  { 
      _tagQueryDiv=aquerydiv;
  }

  this.setQstringTag = function(aqstringdiv,aqlayer,aqitem)
  {
      _tagQstring.push(aqstringdiv);
      _qlayer.push(aqlayer);
      _qitem.push(aqitem);
  }

  this.setQstringTagById = function(aqstringdiv,aqlayer,aqitem,aindex) 
  {
    _tagQstring[aindex]=aqstringdiv;
    _qlayer[aindex]=aqlayer;
    _qitem[aindex]=aqitem;
  }

  this.setExtentTag = function(aextentdiv)
  { 
      _tagExtentDiv=aextentdiv;
  }

  this.setScaleTag = function(ascalediv)
  { 
      _tagScaleDiv=ascalediv;
  }

  this.setZoomTag = function(azoomdiv)
  { 
      _tagZoomDiv=azoomdiv;
  }

  this.setLatTag = function(alatdiv)
  {
      _tagLatDiv=alatdiv;
  }

  this.setLonTag = function(alondiv)
  {
      _tagLonDiv=alondiv;
  }
  

/**************!!!!!!!!!!!!!!!!!!!!!!!!!*************/
  
  this.getSearchResult=function(afarray) {
     i.show_loading_image(true)
     try {
        _mode='itemnquery';
       var sqlayer='';
       var sqitem='';
       var sqstring='';
       for (var k=0; k<afarray.length; k++) {
          acnt=afarray[k];
          if (sqitem!='') {
             sqitem=sqitem+'|';
          }
          sqitem=sqitem+_qitem[acnt];
          if (sqstring!='') {
             sqstring=sqstring+'|';
          }
          sqstring=sqstring+escape(_tagQstring[acnt].value);
       }
       _queryParams='&qlayer='+_qlayer[acnt]+'&qitem='+sqitem+'&qstring='+sqstring;
       _queryFile='';
       _latstqlayer=_qlayer[acnt];

        _args='&mapext='+i.getFullExtent()+_queryParams;
        var aurl=i.get_map_url();
//        prompt('',aurl);

        getTXT(aurl,i.refreshMapProc1,i.getTxtErrHandler,true,_callmethod);
      } catch(e) {
         _mode='map';
         _args='';
         i.show_loading_image(false)
      }
  }  

  this.refreshMapProc1=function(ahtml) {
     if  ((ahtml.indexOf('Query error')!=-1) || (ahtml.indexOf('Search returned no results')!=-1) || (ahtml=='')) {
         _mode='map';
         _args='';
         i.show_loading_image(false);
         alert(langResDict['nodata_'+_lang]);
         _latstqlayer='';
         return;
     }

     try {
         var aline;
         var imgpath;
         var alinearray;
         var alarray;         
         var shapeextarray;
         var Xmin_bound=null;
         var Xmax_bound=null;
         var Ymin_bound=null;
         var Ymax_bound=null;
         var aresparray=ahtml.split('^');
         for (l=0;l<aresparray.length;l++) {
            aline=aresparray[l];
            if (aline!='') {
               alarray=aline.split('|');
               imgpath=alarray[0];
               shapeextarray=alarray[1].split(' ');
               if (Xmin_bound==null) {
                  Xmin_bound=parseFloat(shapeextarray[0]);
               } else {
                  Xmin_bound=min(Xmin_bound, parseFloat(shapeextarray[0]));
               }
               if (Ymin_bound==null) {
                  Ymin_bound=parseFloat(shapeextarray[1]);
               } else {
                  Ymin_bound=min(Ymin_bound, parseFloat(shapeextarray[1]));
               }
               if (Xmax_bound==null) {
                  Xmax_bound=parseFloat(shapeextarray[2]);
               } else {
                  Xmax_bound= max(Xmax_bound, parseFloat(shapeextarray[2]));
               }
               if (Ymax_bound==null) {
                  Ymax_bound=parseFloat(shapeextarray[3]);
               } else {
                  Ymax_bound= max(Ymax_bound, parseFloat(shapeextarray[3]));
               }
            }
         }

        //10 proc buffer 
        var w_bound=Xmax_bound-Xmin_bound;
        var h_bound=Ymax_bound-Ymin_bound;
        var bufferWidth=w_bound/10;
        var bufferHeight=h_bound/10;
        var optBufferWidth=(_SResultOptimalZoom-w_bound)/2;
        var optBufferHeight=(_SResultOptimalZoom-h_bound)/2;
        
        if (optBufferWidth>bufferWidth) {
            bufferWidth=optBufferWidth;
        }
        if (optBufferHeight>bufferHeight) {
            bufferHeight=optBufferHeight;
        }
        Xmin_bound=Xmin_bound-bufferWidth;
        Ymin_bound=Ymin_bound-bufferHeight;
        Xmax_bound=Xmax_bound+bufferWidth;
        Ymax_bound=Ymax_bound+bufferHeight;

        var ext=(Xmin_bound)+'+'+(Ymin_bound)+'+'+(Xmax_bound)+'+'+(Ymax_bound);                      
        _args='&mapext='+ext+_queryParams;
        var aurl=i.get_map_url();
//        prompt('',aurl);
        getTXT(aurl, i.refreshMapProc2, i.getTxtErrHandler, true,_callmethod);
     } catch(e) {
        _mode='map';     
        _args='';
        alert(langResDict['connectionerror_'+_lang]);
        i.show_loading_image(false);
     }
  }

  this.refreshMapProc2=function(ahtml) {
     try {     
        var imgpath='';
        var mapextarray;
        var xmin,xmax,ymin,xmax;            
        if (ahtml!='') {
            var aresparray=ahtml.split('^');
            var aline=aresparray[0].split('|');
            imgpath=aline[0];
            mapextarray=aline[2].split(' ');
        }
        xmin=parseFloat(mapextarray[0]);
        xmax=parseFloat(mapextarray[2]);
        ymin=parseFloat(mapextarray[1]);
        ymax=parseFloat(mapextarray[3]); 
        _queryFile=aline[3];
        i.setExtent(xmin,xmax,ymin);        
        _mode='map';
        _args='';
        i.redraw(false,imgpath);
     } catch(e) {
         _mode='map';     
         _args='';
         alert(langResDict['connectionerror_'+_lang]);
         i.show_loading_image(false);
     }
     
  }
  
  this.refreshQuery = function(ahtml)
  { 
   if (_tagQueryDiv!=null) {
      if ((ahtml.indexOf('error')==-1) && (ahtml!='') && (ahtml.indexOf('Search returned no results')==-1) ) {
        ahtml=ahtml.replace(/\[mapcnt\]/g,_tagLegendDiv.getAttribute('mapcnt'));
        _tagQueryDiv.innerHTML='<div class="queryTitle">Informacja:</div><img class="queryCloseButton" src="'+ _iconCloseButton +'" align="right" onclick="jQuery(this.parentNode).hide()">';

//this.parent.style.display='none'

        _tagQueryDiv.innerHTML=_tagQueryDiv.innerHTML+ahtml;
        _tagQueryDiv.style.display='';
      } else {
        _tagQueryDiv.innerHTML=''
        _tagQueryDiv.style.display='none';
      }  
    }
    i.show_loading_image(false);
  }

  
  this.getCoords = function(ahtml)
  {
     var alarray;
     alarray=ahtml.split('|');
     if (_tagLatDiv!=null) {
        _tagLatDiv.innerHTML=alarray[0];
     }
     if (_tagLonDiv!=null) {
        _tagLonDiv.innerHTML=alarray[1];
     }
  }
  
  this.redraw = function(redrawAttached, mapUrl)
  {
    i.show_loading_image(true);
    //if ( _ext_Xmax == null ) { i.fullExtentNoRedraw(); }  // 20060316
    i.recalc_map_size();

    // Set second buffer map image (Double buffer)
    if (mapUrl==undefined) {
       mapUrl= i.get_map_url()};
    _tagMap_B.src=mapUrl;
    //prompt('', _tagMap_B.src);

    if ( (_attachedMsMap != null) && (redrawAttached != false) )
    {
      _attachedMsMap.attachMap(i);
      _attachedMsMap.setExtent(_ext_Xmin, _ext_Xmax, _ext_Ymin);
      _attachedMsMap.redraw(false);
    }

    if ( _referenceMap != null ) // Draw zoom box in the reference map
    {
      _referenceMap.setReferenceBox(_ext_Xmin, _ext_Xmax, _ext_Ymin, _ext_Ymax);
    }

    var aoldmode=_mode;    
    if (_tagLegendDiv!=null) {
        _mode='legend';
        var aurl=i.get_map_url();         
        if (_tagLegendImg!=null) {
          _tagLegendImg.src=aurl; 
        } else {
           getTXT(aurl,this.refreshLegend,this.getTxtErrHandler,true,_callmethod);
        }  
    }

     _mode='browse';
     var aurl=i.get_map_url();         
     getTXT(aurl,this.refreshBrowseInfo,this.getTxtErrHandler,true,_callmethod);
    _mode=aoldmode;

    if (_tagExtentDiv!=null) {
       _tagExtentDiv.innerHTML=_ext_Xmin+','+_ext_Ymin+','+_ext_Xmax+','+_ext_Ymax;
    }

    if (_tagZoomDiv!=null) {
       _tagZoomDiv.innerHTML=parseInt(_ext_Xmax-_ext_Xmin);
    }

  }

  this.fullExtentNoRedraw = function()
  {
    _ext_Xmin = _ext_Xmin_orig; _ext_Xmax = _ext_Xmax_orig;
    _ext_Ymin = _ext_Ymin_orig; _ext_Ymax = _ext_Ymax_orig;
  }

  this.fullExtent = function() { i.fullExtentNoRedraw(); i.redraw(); }

  this.getMapUrlParams = function(anoqstring) {
     var aqstring='';
     var afidstr='';
     var afvstr='';
     var jc=0;
     var aretsparams=i.getSearchParams();
     for (var j=0; j<aretsparams.length; j++) {
        if ((aretsparams[j].parentNode.style.display=='') && (aretsparams[j].value!='')) {
           if (jc==0) {
              afidstr=j;
              afvstr=aretsparams[j].value;
           } else {
              afidstr=afidstr+','+j;
              afvstr=afvstr+'|'+aretsparams[j].value;};
           jc++;
        }
     }
     aqstring=aqstring+'aext='+escape(i.getExtent())+'&olayers='+escape(i.getLayers())+'&awidth='+i.width()+'&aheight='+i.height();
     if (afidstr!='' && afvstr!='' && anoqstring!=1) {
        aqstring=aqstring+'&afid='+escape(afidstr)+'&afv='+escape(afvstr);
     }
     return aqstring;
  }
  
  this.getMapUrl = function(aprompt) {
     var ahrefstr = i.getDocUrl();
     if (ahrefstr=='') {
        ahrefstr=window.location.href;
     }
     if (ahrefstr.indexOf("?") > -1 ){
        ahrefstr=ahrefstr.substr(0,ahrefstr.indexOf("?")).toLowerCase();
     }     
     ahrefstr=ahrefstr+'?'+i.getMapUrlParams(aprompt);
//     alert(aprompt);
     if (aprompt==null) {
        prompt('URL: ',ahrefstr);
     } else {
        return ahrefstr;
     }
  }  

  this.previewMap = function() {
     if (_ppreview!='') {
        var newwindow=window.open(_ppreview+'?randid=' + Math.random(),'newwindowpp','toolbar=no, location=no, directories=no, status=yes, menubar=yes, scrollbars=yes, resizable=yes, height=600,width=800,left=50,top=50');
        if (window.focus) {
           newwindow.focus();
        }
     }   
     else {
     }
  }

  this.togglefullview = function() {
     if (_togglefullview!='') {
        var newwindow=window.open(_togglefullview+'?'+i.getMapUrlParams(),'newwindowfv','toolbar=yes, location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, resizable=yes, height=600,width=800,left=50,top=50');
        if (window.focus) {
           newwindow.focus(); 
        }
     }   
     else {
     }  
  }

  
  
  this.clearActionBoxBorder=function() {
    for (var j=0; j<_toolbars.length; j++) {
      var atoolbararray=_toolbars[j].getArrayTags();
      for (var k=0; k<atoolbararray.length; k++) {
         var atag=atoolbararray[k].getTag();
         atag.className="mscross_tool";
      }
    }
  }
  
  this.setActionZoombox = function()
  { //_action = 'zoom';
     _tagMap.style.cursor = "crosshair"; }

  this.setActionZoomboxIn = function(e,amap,atag)
  { //_action = 'zoom';
     i.setActionZoomIn();
     _tagMap.style.cursor = "crosshair"; i.clearActionBoxBorder(); atag.className="mscross_tool_sel";}

  this.setActionZoomboxOut = function(e,amap,atag)
  { //_action = 'zoom';
     i.setActionZoomOut();
     _tagMap.style.cursor = "crosshair"; i.clearActionBoxBorder(); atag.className="mscross_tool_sel";}

  this.setActionPan = function(e,amap,atag)
  { //_action = 'pan';
    _tagMap.style.cursor = "move"; i.clearActionBoxBorder(); atag.className="mscross_tool_sel";}

  this.setActionCoords = function()
  { //_action = 'coords';
    _tagMap.style.cursor = "crosshair";}

  this.setActionNone = function()
  {
    for (var j=0; j<_toolbars.length; j++){_toolbars[j].hide();}
//    _action = 'none';
    _tagMap.style.cursor = "";
  }

  this.setActionZoomIn = function()
  {
    if ( isNaN(_tagLoading.style.display) )
    { i.zoomPerc(1.40); i.redraw(); }
  }

  this.setActionZoomOut = function()
  {
    if ( isNaN(_tagLoading.style.display) )
    { i.zoomPerc(0.30); i.redraw(); }
  }

  this.setActionGetInfo= function(e,amap,atag)
   { //_action = 'info';
     _tagMap.style.cursor = "crosshair"; i.clearActionBoxBorder(); atag.className="mscross_tool_sel";}
     
  this.zoomPerc = function(p_perc)
  {
    var wx     = _ext_Xmax - _ext_Xmin;
    var wx_new = wx * p_perc;
    var kx     = (wx_new - wx) / 2;
    var wy     = _ext_Ymax - _ext_Ymin;
    var wy_new = wy * p_perc;
    var ky     = (wy_new - wy) / 2;
    i.setExtent(_ext_Xmin + kx, _ext_Xmax - kx, _ext_Ymin + ky);
  }

  this.mapLoaded = function()
  {
    // Swap image buffer (double buffering)
    var tmp = _tagMap;
    _tagMap = _tagMap_B;
    _tagMap_B = tmp;

    _tagMap.style.cursor = _tagMap_B.style.cursor;
    _tagMap.style.left = (- _map_w_bord) +'px';
    _tagMap.style.top  = (- _map_h_bord) +'px';
    _tagMap_B.style.display = 'none';
    _tagMap.style.display = '';

    // Hide "loading" image when map is loaded
    i.show_loading_image(false);
  }

  this.get_map_url = function()
  {
    var my_url;
    if (_protocol == 'mapservercgi')
    {
      var size = 'mapsize=' + (_map_w+_map_w_bord+_map_w_bord) + '+'
                            + (_map_h+_map_h_bord+_map_h_bord);
      var amodename='mapext=';
      if ((_mode=='query')||(_mode=='nquery')) {
         amodename='imgext=';
      }
      var ext='';
      
      if (_mode!='itemnquery') {
         ext = amodename + (_ext_Xmin-i.wPixel2real(_map_w_bord)) + '+'
                           + (_ext_Ymin-i.hPixel2real(_map_h_bord)) + '+'
                           + (_ext_Xmax+i.wPixel2real(_map_w_bord)) + '+'
                           + (_ext_Ymax+i.hPixel2real(_map_h_bord)) ;
         ext='&' + ext;
      }
      var qlayer=''
      if ((_latstqlayer!='') && (_mode!='nquery')) {
         qlayer=' '+_latstqlayer;
      }
 
      my_url = _cgi + '?mode=' + _mode + ext +'&queryfile='+_queryFile + '&layers=' + _layers + qlayer + '&' + size + '&ilicense=' + _ilicense + '&iticket=' + _iticket;
      // Opera9 Bug Fix (onload event don't work if image is in cache)
      if (browser.isOP) {my_url = my_url + '&randid=' + Math.random();}
    }
    return my_url + _args;
  }

  this.get_tcgi_url = function()  {
     var my_url='';
     if (_tcgi!='') {
        my_url = _tcgi + '?mode=' + _mode + _args;
        if (browser.isOP) {my_url = my_url + '&randid=' + Math.random();}
     }
     return my_url;
  }
  
  this.setPan = function(x, y)
  {
    i.recalc_pixel_size();
    var x_real = x * _pixel_w; var y_real = y * _pixel_h;
    _ext_Xmin = _ext_Xmin - x_real; _ext_Xmax = _ext_Xmax - x_real;
    _ext_Ymin = _ext_Ymin + y_real; _ext_Ymax = _ext_Ymax + y_real;
    i.redraw();
  }

  this.setRecenter = function(x, y)
  {
    i.recalc_pixel_size();
    var w2 = ((_ext_Xmax - _ext_Xmin) / 2);
    var h2 = ((_ext_Ymax - _ext_Ymin) / 2);
    _ext_Xmin = x-w2; _ext_Xmax = x+w2;
    _ext_Ymin = y-h2; _ext_Ymax = y+h2;
    i.redraw();

  }

  this.recalc_map_size = function()
  {
    i.recalc_pixel_size();

    if ( _pixel_w > _pixel_h )
    { // Modify only Y (box width > height)
      var middle = ((_ext_Ymax - _ext_Ymin) / 2) + _ext_Ymin;
      var new_h = (_map_h / _map_w) * (_ext_Xmax - _ext_Xmin);
      _ext_Ymin = middle - (new_h / 2);
      _ext_Ymax = middle + (new_h / 2);
    } else
    { // Modify only X (box width < height)
      var middle = ((_ext_Xmax - _ext_Xmin) / 2) + _ext_Xmin;
      var new_w = (_map_w / _map_h) * (_ext_Ymax - _ext_Ymin);
      _ext_Xmin = middle - (new_w / 2);
      _ext_Xmax = middle + (new_w / 2);
    }
    i.recalc_pixel_size();
  }

  this.init = function()
  {
    //_tagMain.className = 'mscross';  // css
    _tagMain.oncontextmenu  = function(){return false;};
    _tagMain.style.width    = i.width()+'px';
    _tagMain.style.height   = i.height()+'px';
    _tagMain.style.overflow = 'hidden';
    _tagMain.style.position = 'relative';
    _tagEvents.oncontextmenu = function(){return false;};
    setZindex(_tagEvents, '0');
    _tagEvents.style.position = 'absolute';
    _tagEvents.left           = '0';
    _tagEvents.top            = '0';

    // First buffer (double buffer)
    _tagMap.objRef = i;
    _tagMap.oncontextmenu  = function(){return false;};
    _tagMap.onmousedown = function(){return false;};  // Disable drag'n drop
    add_event(_tagMap, 'load', i.mapLoaded );
    //i.tagMap.setAttribute('style', '-moz-user-select:none;');
    setZindex(_tagMap, '0');
    _tagMap.galleryImg = "no";
    _tagMap.style.width    = (i.width()+_map_w_bord+_map_w_bord)+'px';
    _tagMap.style.height   = (i.height()+_map_h_bord+_map_h_bord)+'px';
    _tagMap.style.border   = '0 none';
    _tagMap.style.margin   = '0'; _tagMap.style.padding  = '0';
    _tagMap.style.position = 'absolute';
    _tagMap.style.top      = (- _map_w_bord) +'px';
    _tagMap.style.left     = (- _map_h_bord) +'px';
    _tagMap.style.display  = 'none';

    // Second buffer (double buffer)
    _tagMap_B.objRef = _tagMap.objRef;
    _tagMap_B.oncontextmenu = _tagMap.oncontextmenu;
    _tagMap_B.onmousedown = _tagMap.onmousedown;
    add_event(_tagMap_B, 'load', i.mapLoaded );
    setZindex(_tagMap_B, '0');
    _tagMap_B.galleryImg = "no";
    _tagMap_B.style.width    = _tagMap.style.width;
    _tagMap_B.style.height   = _tagMap.style.height;
    _tagMap_B.style.border   = _tagMap.style.border;
    _tagMap_B.style.margin   = _tagMap.style.margin;
    _tagMap_B.style.padding  = _tagMap.style.padding;
    _tagMap_B.style.position = _tagMap.style.position;
    _tagMap_B.style.top      = _tagMap.style.top;
    _tagMap_B.style.left     = _tagMap.style.left;
    _tagMap_B.style.display  = 'none';

    _tagReference.className = 'mscross_reference_zoombox';  // css
    _tagReference.oncontextmenu    = function(){return false;};
    setZindex(_tagReference, '100');
    _tagReference.style.display    = 'none';
    _tagReference.style.position   = 'absolute';
    _tagReference.style.margin     = '0'; _tagReference.style.padding = '0';
    _tagReference.style.lineHeight = '0';
//    _tagReference.style.border     = '1px solid #000000';
//    _tagReference.style.background = '#a0a0a0';
    _tagReference.style.opacity    = '0.50';               // Gecko
    _tagReference.style.filter     = 'alpha(opacity=50)';  // Windows
    _tagReference.style.fontSize   = '1'; // 20061012 bugfix by Rodrigo

    _tagZoombox.oncontextmenu    = function(){return false;};
    setZindex(_tagZoombox, '100');
    _tagZoombox.style.position   = 'absolute';
    _tagZoombox.style.display    = 'none';
    _tagZoombox.style.border     = '1px dashed #000000';
    _tagZoombox.style.margin     = '0px'; 
    _tagZoombox.style.padding = '0px';
    _tagZoombox.style.lineHeight = '0';
    _tagZoombox.style.background = '#606060';            //'#f0f0f0';
    _tagZoombox.style.opacity    = '0.18';               // Gecko
    _tagZoombox.style.filter     = 'alpha(opacity=18)';  // Windows
    _tagZoombox.style.fontSize   = '1'; // 20061012 bugfix by Rodrigo

    // Overlay Layer
    _tagOverlay.oncontextmenu    = function(){return false;};
    setZindex(_tagOverlay, '30');
    _tagOverlay.style.position   = 'absolute';

    _tagPoints.oncontextmenu    = function(){return false;};
    setZindex(_tagPoints, '40');
    _tagPoints.style.position   = 'absolute';

    _tagInfo.oncontextmenu   = function(){return false;};
    setZindex(_tagInfo, '50');
    _tagInfo.style.position  = 'absolute';

    // "Loading" image tag
    _tagLoading.oncontextmenu    = function(){return false;};
    _tagLoading.onmousedown = function(){return false;};  // Disable drag'n drop
    setZindex(_tagLoading, '100');
    _tagLoading.style.position   = 'absolute';
    _tagLoading.style.display    = 'none';
    _tagLoading.style.border     = '0';
    _tagLoading.style.margin     = '0'; _tagLoading.style.padding    = '0';
    _tagLoading.style.lineHeight = '0';
    setAlphaPNG(_tagLoading, _iconLoading);
    _tagLoading.style.left = (_map_w - 31) + 'px';
    _tagLoading.style.top  = 0 + 'px';

    // Double buffer
    _tagEvents.appendChild(_tagMap);
    _tagEvents.appendChild(_tagMap_B);

    _tagOverlay.appendChild(_tagPoints);
    _tagOverlay.appendChild(_tagInfo);

    _tagMain.appendChild(_tagEvents);
    _tagMain.appendChild(_tagOverlay);
    _tagMain.appendChild(_tagZoombox);
    _tagMain.appendChild(_tagReference);
    if (ControlType != null)
    {
      adefalult=true;
      if (ControlType=='empty') {
         adefalult=false;
      }
      _toolbars.push(new msToolbar(i, ControlType, adefalult));
      _tagMain.appendChild(_toolbars[0].getTag());
    }
    _tagMain.appendChild(_tagLoading);
  }

  this.getClick_X = function(p_event)
  {
    var my_x;
    if (browser.isNS)
    {
      my_x = p_event.clientX + window.scrollX;
    } else
    {
      my_x = window.event.clientX + document.documentElement.scrollLeft
        + document.body.scrollLeft;
    }
    return my_x - DL_GetElementLeft(i.getTagMap()) - _map_w_bord;
  }
  this.getClick_Y = function(p_event)
  {
    var my_y;
    if (browser.isNS)
    {
      my_y = p_event.clientY + window.scrollY;
    } else
    {
      my_y = window.event.clientY + document.documentElement.scrollTop
        + document.body.scrollTop;
    }
    return my_y - DL_GetElementTop(i.getTagMap()) - _map_w_bord;
  }


  this.zoomStart = function(event)
  {
    var el;
    dragObj.elNode = _tagMap;
    var x = i.getClick_X(event);
    var y = i.getClick_Y(event);
    if ( isNaN(_tagLoading.style.display) )
    {
      if (browser.isNS)
      {
        document.addEventListener("mousemove", i.zoomGo,   true);
        document.addEventListener("mouseup",   i.zoomStop, true);
        event.preventDefault();
      } else
      {
        document.attachEvent("onmousemove", i.zoomGo);
        document.attachEvent("onmouseup",   i.zoomStop);
        window.event.cancelBubble = true;
        window.event.returnValue = false;
      }
      i.setZoomboxFirst(x, y);
    }
  }

  this.zoomOutStart = function(event)
  {
    var el;
    dragObj.elNode = _tagMap;
    var x = i.getClick_X(event);
    var y = i.getClick_Y(event);
    if ( isNaN(_tagLoading.style.display) )
    {
      if (browser.isNS)
      {
        document.addEventListener("mousemove", i.zoomGo,   true);
        document.addEventListener("mouseup",   i.zoomOutStop, true);
        event.preventDefault();
      } else
      {
        document.attachEvent("onmousemove", i.zoomGo);
        document.attachEvent("onmouseup",   i.zoomOutStop);
        window.event.cancelBubble = true;
        window.event.returnValue = false;
      }
      i.setZoomboxFirst(x, y);
    }
  }

  this.zoomGo = function(event)
  {
    var x = i.getClick_X(event);
    var y = i.getClick_Y(event);
    window.status='x='+x+';  y='+y; //$$RS
    i.setZoomboxWH(x, y);

    if (browser.isNS)
    {event.preventDefault();} else
    {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
  }

  this.zoomStop = function(event)
  {
    // Stop capturing mousemove and mouseup events.
    var flag = true; if (browser.isOP){flag=false;}
    i.zoomGo(event);
    del_event(document, "mousemove", i.zoomGo, flag);
    del_event(document, "mouseup", i.zoomStop, flag);
    i.setExtent(_ext_Xmin, _ext_Xmax, _ext_Ymin);            
    i.zoomboxExtent();
  }

  this.zoomOutStop = function(event)
  {
    // Stop capturing mousemove and mouseup events.
    var flag = true; if (browser.isOP){flag=false;}
    i.zoomGo(event);
    del_event(document, "mousemove", i.zoomGo, flag);
    del_event(document, "mouseup", i.zoomOutStop, flag);
    i.setExtent(_ext_Xmin, _ext_Xmax, _ext_Ymin);            
    i.zoomboxExtentOut();
  }

  this.dragStart = function(event)
  {
    var el;
    dragObj.elNode = _tagMap;
    var x = i.getClick_X(event) + DL_GetElementLeft(i.getTagMap());
    var y = i.getClick_Y(event) + DL_GetElementTop(i.getTagMap());
    // Save starting positions of cursor and element.
    dragObj.cursorStartX = x; dragObj.cursorStartY = y;
    dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
    dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);
    if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
    if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;
    // Update element's z-index.
    //dragObj.elNode.style.zIndex = ++dragObj.zIndex;       // Serve???
    // Capture mousemove and mouseup events on the page.
    // xxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyy
    if ( isNaN(_tagLoading.style.display) )
    {
      if (browser.isNS)
      {
        document.addEventListener("mousemove", i.dragGo,   true);
        document.addEventListener("mouseup",   i.dragStop, true);
        event.preventDefault();
      } else
      {
        document.attachEvent("onmousemove", i.dragGo);
        document.attachEvent("onmouseup",   i.dragStop);
        window.event.cancelBubble = true;
        window.event.returnValue = false;
      }
    }
  }

  this.dragGo = function(event)
  {
    var xx = i.getClick_X(event) + DL_GetElementLeft(i.getTagMap());
    var yy = i.getClick_Y(event) + DL_GetElementTop(i.getTagMap());
    // Move map by the same amount the cursor has moved.
    dragObj.elNode.style.left = (dragObj.elStartLeft + xx - dragObj.cursorStartX) + "px";
    dragObj.elNode.style.top  = (dragObj.elStartTop  + yy - dragObj.cursorStartY) + "px";
    // Move Overlay layer
    _tagOverlay.style.left = parseInt(dragObj.elNode.style.left) +_map_w_bord +'px';
    _tagOverlay.style.top  = parseInt(dragObj.elNode.style.top)  +_map_h_bord +'px';
    if (browser.isNS)
    {event.preventDefault();} else
    {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
  }

  this.dragStop = function(event)
  {
    // Clear the drag element global.
    //dragObj.elNode = null;

    // Stop capturing mousemove and mouseup events.
    var flag = true; if (browser.isOP){flag=false;}
    del_event(document, "mousemove", i.dragGo, flag);
    del_event(document, "mouseup", i.dragStop, flag);

    var xx, yy;
    var x = i.getClick_X(event) + DL_GetElementLeft(i.getTagMap());
    var y = i.getClick_Y(event) + DL_GetElementTop(i.getTagMap());
    // Move drag element by the same amount the cursor has moved.
    xx = (dragObj.elStartLeft + x - dragObj.cursorStartX);
    yy = (dragObj.elStartTop  + y - dragObj.cursorStartY);
    // Add buffer size
    xx += _map_w_bord;
    yy += _map_h_bord;
    if ((xx != 0) || (yy != 0)) {i.setPan(xx, yy);}
  }
  i.init();
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Determining Element Page Coordinates, Part 4:
// http://www.webreference.com/dhtml/diner/realpos4/9.html
function DL_GetElementLeft(eElement)
{
   if (!eElement && this)                    // if argument is invalid
   {                                         // (not specified, is null or is 0)
      eElement = this;                       // and function is a method
   }                                         // identify the element as the method owner
   var DL_bIE = document.all ? true : false; // initialize var to identify IE
   var nLeftPos = eElement.offsetLeft;       // initialize var to store calculations
   var eParElement = eElement.offsetParent;  // identify first offset parent element

   while (eParElement != null)
   {                                         // move up through element hierarchy
      if(DL_bIE)                             // if browser is IE, then...
      {
         if( (eParElement.tagName != "TABLE") && (eParElement.tagName != "BODY") )
         {                                   // if parent is not a table or the body, then...
            nLeftPos += eParElement.clientLeft; // append cell border width to calcs
         }
      }
      else                                   // if browser is Gecko, then...
      {
         if(eParElement.tagName == "TABLE")  // if parent is a table, then...
         {                                   // get its border as a number
            var nParBorder = parseInt(eParElement.border);
            if(isNaN(nParBorder))            // if no valid border attribute, then...
            {                                // check the table's frame attribute
               var nParFrame = eParElement.getAttribute('frame');
               if(nParFrame != null)         // if frame has ANY value, then...
               {
                  nLeftPos += 1;             // append one pixel to counter
               }
            }
            else if(nParBorder > 0)          // if a border width is specified, then...
            {
               nLeftPos += nParBorder;       // append the border width to counter
            }
         }
         // sm 20051010
         if(eParElement.tagName == "DIV")
         {
           var bord = parseInt(eParElement.style.border);
           if ( bord > 0 ) { nLeftPos += bord; }
         }
      }
      nLeftPos += eParElement.offsetLeft;    // append left offset of parent
      eParElement = eParElement.offsetParent; // and move up the element hierarchy
   }                                         // until no more offset parents exist
   return nLeftPos;                          // return the number calculated
}

function DL_GetElementTop(eElement)
{
   if (!eElement && this)                    // if argument is invalid
   {                                         // (not specified, is null or is 0)
      eElement = this;                       // and function is a method
   }                                         // identify the element as the method owner
   var DL_bIE = document.all ? true : false; // initialize var to identify IE
   var nTopPos = eElement.offsetTop;         // initialize var to store calculations
   var eParElement = eElement.offsetParent;  // identify first offset parent element
   while (eParElement != null)
   {                                         // move up through element hierarchy
      if(DL_bIE)                             // if browser is IE, then...
      {
         if( (eParElement.tagName != "TABLE") && (eParElement.tagName != "BODY") )
         {                                   // if parent a table cell, then...
            nTopPos += eParElement.clientTop; // append cell border width to calcs
         }
      }
      else                                   // if browser is Gecko, then...
      {
         if(eParElement.tagName == "TABLE")  // if parent is a table, then...
         {                                   // get its border as a number
            var nParBorder = parseInt(eParElement.border);
            if(isNaN(nParBorder))            // if no valid border attribute, then...
            {                                // check the table's frame attribute
               var nParFrame = eParElement.getAttribute('frame');
               if(nParFrame != null)         // if frame has ANY value, then...
               {
                  nTopPos += 1;              // append one pixel to counter
               }
            }
            else if(nParBorder > 0)          // if a border width is specified, then...
            {
               nTopPos += nParBorder;        // append the border width to counter
            }
         }
         // sm 20051010
         if(eParElement.tagName == "DIV")
         {
           var bord = parseInt(eParElement.style.border);
           if ( bord > 0 ) { nTopPos += bord; }
         }
      }
      nTopPos += eParElement.offsetTop;      // append top offset of parent
      eParElement = eParElement.offsetParent; // and move up the element hierarchy
   }                                         // until no more offset parents exist
   return nTopPos;                           // return the number calculated
}

// Determine browser and version
function Browser()
{
  var ua, s, i;
  this.isIE    = false;
  this.isNS    = false;
  this.isOP    = false;
  this.name    = navigator.appName;
  this.version = null;
  ua = navigator.userAgent;
  if ((navigator.userAgent).indexOf("Opera")!=-1)
  {
    this.isOP = true;
  } else
  if (navigator.appName=="Netscape")
  {
    this.isNS = true;
  } else
  if ( (navigator.appName).indexOf("Microsoft") != -1 )
  {
    this.isIE = true;
  }
  return;
}

function min(a, b) { if ( a < b ) { return a; } else { return b; } }
function max(a, b) { if ( a > b ) { return a; } else { return b; } }

// http://www.quirksmode.org/js/events_advanced.html
function add_event(obj, event_id, func)
{
  if (obj.addEventListener)
  {
    obj.addEventListener(event_id, func, false)
  } else if(obj.attachEvent)
  {
    event_id = 'on'+event_id;
    obj.attachEvent(event_id, func)
  } else
  { obj[event_id] = func; }
}
function del_event(obj, event_id, funct, flag)
{
  if (obj.removeEventListener)
  {
    obj.removeEventListener(event_id, funct, flag);
  } else if(obj.detachEvent)
  {
    obj.detachEvent(event_id, funct);
    obj.detachEvent('on'+event_id, funct);
  }
}

function setPos(p_obj, p_x, p_y)
{
  p_obj.style.left    = p_x+'px';
  p_obj.style.top     = p_y+'px';
  p_obj.style.display = '';
}

function setAlphaPNG(p_imgTag, p_src)
{
  p_imgTag.src = p_src;
}

function setZindex(p_tag, p)
{
  if (p_tag.setAttribute)
  { p_tag.setAttribute('style', 'z-index:'+p+';'); } else
  { p_tag.style.zIndex = p; }
}


function htmlDecode(str) {
  var entMap={'quot':34,'amp':38,'apos':39,'lt':60,'gt':62};
  return str.replace(/&([^;]+);/g,function(m,n) {
    var code;
    if (n.substr(0,1)=='#') {
      if (n.substr(1,1)=='x') {
        code=parseInt(n.substr(2),16);
      } else {
        code=parseInt(n.substr(1),10);
      }
    } else {
      code=entMap[n];
    }
    return (code===undefined||code===NaN)?'&'+n+';':String.fromCharCode(code);
  });
}


function getTXT(p_url,p_funct,p_errfunct,amode,acallmethod) {
   if (acallmethod=='jsonp') {
      jQuery.getJSON(p_url+'&callback=?',function(json){
         p_funct(htmlDecode(json.data));
      })
   } 
   else { //ajax
     var http_request2 = false;
     if (window.XMLHttpRequest) // Mozilla, Safari,...
     {
       try {
         netscape.security.PrivilegeManager.enablePrivilege( "UniversalBrowserRead"); 
         netscape.security.PrivilegeManager.enablePrivilege( "UniversalXPConnect"); 
       }  catch(e) {
//      alert(langResDict['xmlhttpiniterror_'+this.lang()]);
       }
       http_request2 = new XMLHttpRequest();
       if (http_request2.overrideMimeType) {
          http_request2.overrideMimeType('text/html; charset=windows-1250');
       }
     } else if (window.ActiveXObject) // IE
     {
       try
       {
          http_request2 = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e)
       {
         try
         {
           http_request2 = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {}
       }
     }
     if (!http_request2)
     {
       alert('Giving up :( Cannot create an XMLHTTP instance');
       return false;
     }

     http_request2.onreadystatechange = function()
     {
       if (http_request2.readyState == 4)
       {
         if (http_request2.status == 200)
         {
            p_funct(http_request2.responseText);
         } else { 
            p_errfunct('Problem z dostêpem do serwera');
          }
       }
     }
     
     http_request2.open('GET', p_url , amode);
     http_request2.send(null);     
   }   
}

function getQuerystring(key, default_) {
  if (default_==null) default_='';
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null) {
    return default_;
  } else {
    return decodeURIComponent(qs[1]);
  }
}

// msTool class prototype
function msTool(p_title, p_event_button, p_icon, p_event_map)
{
  var _tag = document.createElement('img');
  var _map; var _toolbar;

  var _event_button = null;   //p_event_button;
  if (p_event_button != null)
  { _event_button = function(e){p_event_button(e, _map, _tag);} }

  var _event_map = null;
  if (p_event_map != null)
  {
    _event_map = function(e)
    {
      var xx = _map.getClick_X(e); var yy = _map.getClick_Y(e);
      p_event_map(e, _map, xx, yy, _map.xPixel2Real(xx), _map.yPixel2Real(yy));
    }
  }

  this.eventClick = function(e)
    {
      if (_event_map != null)
      {
        _toolbar.removeMapEvents();  // Remove all events
        add_event(_map.getTagEvent(), 'mousedown', _event_map);
      }
      if (_event_button != null) {_event_button();}
    }

  _tag.className = 'mscross_tool';
  _tag.oncontextmenu = function(){return false;};
  _tag.onmousedown = function(){return false;};  // Disable drag'n drop
  add_event(_tag, 'click', this.eventClick);
  setAlphaPNG(_tag, p_icon);
  _tag.title = p_title;
  setZindex(_tag, '200');
  _tag.style.margin = '0'; _tag.style.padding = '0';
  _tag.style.position = 'absolute';
  _tag.style.cursor = 'pointer';
  _tag.style.display = 'none';

  this.getTag = function(){return _tag;}
  this.setMap = function(p){_map=p;}
  this.setToolbar = function(p){_toolbar=p;}
  this.haveMapEvent = function(){if (_event_map == null){return false;} return true;}
  this.removeMapEvent = function()
  {
    if (_event_map != null)
    { del_event(_map.getTagEvent(), "mousedown", _event_map, false); }
  }
}

// msToolbar class prototype
function msToolbar(p_msMap, _control, _default)
{
  var _tagToolbar = document.createElement('div');
  var _toolbarArray = new Array();
  var _msMap = p_msMap;
  var _tagMap = _msMap.getTagMap();
  var _iconSeparator = _msMap.mscrosspath() + 'img/buttons/separator.png';
  var _iconFullExtentButton = _msMap.mscrosspath() + 'img/buttons/world.png';
  var _iconPanButton        = _msMap.mscrosspath() + 'img/buttons/arrow_out.png';
  var _iconZoominButton     = _msMap.mscrosspath() + 'img/buttons/magnifier_zoom_in.png';
  var _iconZoomoutButton    = _msMap.mscrosspath() + 'img/buttons/magnifier_zoom_out.png';
  var _iconInfoButton    = _msMap.mscrosspath() + 'img/buttons/information.png';
  var _iconUrlButton    = _msMap.mscrosspath() + 'img/buttons/world_link.png';
  var _iconPreviewButton    = _msMap.mscrosspath() + 'img/buttons/printer.png';
  var _iconToggleFullViewButton    = _msMap.mscrosspath() + 'img/buttons/image.png';

  this.getTag = function(){return _tagToolbar;}
  this.getArrayTags = function(){return _toolbarArray;}  
  this.hide = function(){_tagToolbar.style.display = 'none';}

  this.removeMapEvents = function()
  { for (i=0; i<_toolbarArray.length; i++){_toolbarArray[i].removeMapEvent();} }

  this.addMapTool = function(p_tool)
  {
    p_tool.setMap(_msMap);
    p_tool.setToolbar(this);
    _toolbarArray.push(p_tool);
    _tagToolbar.appendChild(p_tool.getTag());
    this.redraw();
  }

  this.redraw = function()
  {
    if ( (_control == 'standard')      ||
         (_control == 'standardRight') ||
         (_control == 'standardCornerRight') ||
         (_control == 'empty') )
    {
      box.style.left   = (parseInt(_tagMap.style.width)-(40+_msMap.getBorder()*2)) +'px';
      box.style.top    = '0px';
      box.style.width  = '30px';
      box.style.height = _tagMap.style.height;
      for (i=0; i<_toolbarArray.length; i++)
      { setPos(_toolbarArray[i].getTag(), parseInt(box.style.left)+5, (i*30)+5); }
    }
    if ( (_control == 'standardLeft') || (_control == 'standardCornerLeft') )
    {
      for (i=0; i<_toolbarArray.length; i++){setPos(_toolbarArray[i].getTag(), 3, (i*30)+5 );}
      box.style.left   = '0px';
      box.style.top    = '0px';
      box.style.width  = '30px';
      box.style.height = _tagMap.style.height;
    }
    if (_control == 'standardUp')
    {
      for (i=0; i<_toolbarArray.length; i++){setPos(_toolbarArray[i].getTag(), (i*25)+5, 5 );}
      box.style.left   = '0px';
      box.style.top    = '0px';
      box.style.width  = _tagMap.style.width;
      box.style.height = '30px';
    }
  }

  _tagToolbar.oncontextmenu = function(){return false;};
  setZindex(_tagToolbar, '100');
  _tagToolbar.style.position = 'absolute';

  box = document.createElement('div');
  box.oncontextmenu  = function(){return false;};
  setZindex(box, '100');
  box.style.position = 'absolute';
  box.style.display  = '';
  box.style.border     = '0px';
  box.style.margin     = '0px';
  box.style.padding    = '0px';
  box.style.background = '#C0C0C0';
  box.style.lineHeight = '0';
  box.style.opacity    = '0.80';               // Gecko
  box.style.filter     = 'alpha(opacity=90)';  // Windows
  _tagToolbar.appendChild(box);

  if (_default == true)
  {
    var t_sep=new msTool('', null, _iconSeparator);
    var t_fullext = new msTool(langResDict['fullview_'+_msMap.lang()], _msMap.fullExtent, _iconFullExtentButton);
    var t_pan     = new msTool(langResDict['move_'+_msMap.lang()], _msMap.setActionPan, _iconPanButton, function(e, map, x, y){map.dragStart(e);});
    var t_zoomboxin    = new msTool(langResDict['zoomin_'+_msMap.lang()], _msMap.setActionZoomboxIn, _iconZoominButton, function(e, map, x, y){map.zoomStart(e);});
    var t_zoomboxout    = new msTool(langResDict['zoomout_'+_msMap.lang()], _msMap.setActionZoomboxOut, _iconZoomoutButton, function(e, map, x, y){map.zoomOutStart(e);});
    var t_info = new msTool(langResDict['info_'+_msMap.lang()], _msMap.setActionGetInfo, _iconInfoButton ,function(e, map, x, y, xx, yy){
//        map.setArgs('&mapxy='+xx+'+'+yy+'&imgxy='+x+'+'+y);
        map.setArgs('&imgxy='+x+'+'+y);
        map.setMode('nquery');
        map.show_loading_image(true);
        var aurl;
        aurl=map.get_map_url();
        getTXT(aurl,map.refreshQuery,map.getTxtErrHandler,true,map.getCallMethod());
        map.setMode('getcoords');
        map.setArgs('&x='+xx+'&y='+yy);
        aurl=map.get_tcgi_url();
        if (aurl!='') {
           getTXT(aurl,map.getCoords,map.getTxtErrHandler,true,map.getCallMethod());
        };
        map.setMode('map');
     });     
     
    var t_geturl = new msTool(langResDict['geturl_'+_msMap.lang()], _msMap.getMapUrl, _iconUrlButton);
    var t_preview = new msTool(langResDict['preview_'+_msMap.lang()], _msMap.previewMap, _iconPreviewButton);
    var t_togglefullview = new msTool(langResDict['togglefullview_'+_msMap.lang()], _msMap.togglefullview, _iconToggleFullViewButton);
    
    this.addMapTool(t_fullext);
    this.addMapTool(t_pan);
    this.addMapTool(t_zoomboxin);
    this.addMapTool(t_zoomboxout);
    this.addMapTool(t_info);
    this.addMapTool(t_sep);
    this.addMapTool(t_togglefullview);
    this.addMapTool(t_geturl);
    this.addMapTool(t_preview);

  }

  this.redraw();

  // Activate first button with map function
  for (i=0; i<_toolbarArray.length; i++)
  {
    if (_toolbarArray[i].haveMapEvent() == true)
    {
      _toolbarArray[i].eventClick();
      break;
    }
  }
}