var __map, __X, __Y, __oldX, __oldY;

var zoomlevels = new Array(256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216);

var __ob, __event,__srcElement,__wheelProcess;

function MDC(ev)
{
   if(!ev) ev = window.event;
   var cLeft = parseInt(__map.container.style.left);
   if(!cLeft)cLeft = 0;
   var cTop  = parseInt(__map.container.style.top);
   if(!cTop)cTop = 0;

   var pixel = new GPoint(__map.centerpixel.x - __map.width/2 + ev.clientX , __map.centerpixel.y - __map.height/2 + ev.clientY);

   var nCenter =  MercatorInvers(fromPixelToLatLng(pixel, __map.zoom));

   if(__map.ondblclick) __map.ondblclick(nCenter.lat(), nCenter.lng());
}

function MDC2(ev)
{
   if(!ev) ev = window.event;
   var cLeft = parseInt(__map.container.style.left);
   if(!cLeft)cLeft = 0;
   var cTop  = parseInt(__map.container.style.top);
   if(!cTop)cTop = 0;

   var pixel = new GPoint(__map.centerpixel.x - __map.width/2 + ev.clientX , __map.centerpixel.y - __map.height/2 + ev.clientY);

   var nCenter =  MercatorInvers(fromPixelToLatLng(pixel, __map.zoom));

   if(__map.ondblclick) __map.ondblclick(nCenter.lat(), nCenter.lng());
}

function wheelReset()
{
   __wheelProcess = false;
}

function wheel(event)
{
    // Переменная, в которой будем хранить сдвиг
    if(__wheelProcess == true)return;
    var wheelDelta = 0;    
    if (!event) 
    {
        event = window.event;
    }
    if (event.wheelDelta) 
    {
        // В IE и Safari значения delta всегда строго 120, вне зависимости от настроек пользователя.
        wheelDelta = event.wheelDelta/120;
        
        // В Opera 9, значение delta домножается на 40 и совпадает по знаку со значениями в IE
        if (window.opera)
        {
            wheelDelta = event.wheelDelta/40;
        }
    } 
    else if (event.detail) 
    {
        // В Mozilla, значение wheelDelta отличается по знаку от значения в IE.
        // По модулю wheelDelta строго совпадает со значением в пользовательких настройках
        wheelDelta = -event.detail;
    }
    __wheelProcess = true;
    setTimeout('wheelReset();',500);
    if (wheelDelta<0)
    {
     __map.zoomOut();
    }
    if (wheelDelta>0)
    {
     __map.zoomIn();
    }
    navigation.onEvent('mapZoom'); //устанавливаем бегунок навигатора в нужное место
    // Убиваем событие (чтобы страница не скроллилась)
    //blockEvent(event);
}


function __getParentNodeById(node, parentId)
{
//if(node.parentNode){
   while(node.parentNode)
   {
      node = node.parentNode;
      if(node.id == parentId) return node;
   }
//}
   return false;
}

function MD(ev){
    if(!ev) ev = window.event;

    var key; 
    if(ev.which){key = ev.which;}else{key = ev.button;}
    if(key != 1)
    {
       ev.cancelBubble = true;
       ev.keyCode = 0;
       ev.returnValue = false;
       return false;
    }
    
    var srcElement;

    if(ev.target)
    {
       srcElement = ev.target;
    }
    else
    {
       srcElement = ev.srcElement;
    } 

    __srcElement = srcElement;

    if (srcElement.id != "_infowindow" && !__getParentNodeById(srcElement,'_infowindow')) 
        if (document.getElementById("_infowindow")) {
            document.getElementById("_infowindow").parentNode.removeChild(document.getElementById("_infowindow"));
        }

    if ((srcElement.name == "__scrollimg") || (srcElement.name == "__mapimage") || (srcElement.name == "__line")) {
        __event = srcElement.name;

        if (srcElement.name == "__line" && srcElement.fixed == 'yes')
        {
          __ob = srcElement.parentNode.parentNode.parentNode.style;
          __event = '__mapimage';
        }
        else
        {
          __ob = srcElement.parentNode.style;
        } 

        __oldY = parseInt(__ob.top);
        __oldX = parseInt(__ob.left);

        __X = ev.clientX;
        __Y = ev.clientY;

    }
    else {

    }
    return false;
}

function MM(ev){
    if(!ev) ev = window.event;
    if (__ob) {

        __ob.top  = parseInt(ev.clientY - __Y + parseInt(__ob.top)) + 'px';
        __ob.left = parseInt(ev.clientX - __X + parseInt(__ob.left)) + 'px';

        __X = ev.clientX;
        __Y = ev.clientY;

        if (__event == "__mapimage") {

            __map.moveMapImages(__ob);
        }

        if (__event == "__scrollimg") {
            if (parseInt(__ob.top) > 190) 
                __ob.top = 190 + 'px';
            if (parseInt(__ob.top) < 70) 
                __ob.top = 70 + 'px';
        }

        return false;
    }
}

function MU(){
    if (__event == "__scrollimg") 
        if (__ob != null) 
            if (__oldY != parseInt(__ob.top)) {
                __map.setZoom(17 - Math.round((__ob.pixelTop - 70) / 17.15));
            }

     if (__event == "__line") {
        __srcElement.object.move();
     }


    if (__event == "__mapimage") 
        if (__ob != null) 
            if ((__oldY != parseInt(__ob.top)) || ((__oldX != parseInt(__ob.left) ))) {
                offsetY = parseInt(__ob.top) - __oldY;
                offsetX = parseInt(__ob.left) - __oldX;
                __map.calcCenter(offsetX, offsetY);
            }
    __ob = null;
    return false;
}


//document.onmousedown = MD;
//document.onmousemove = MM;
//document.onmouseup = MU;

function GBrowserIsCompatible(){
    return true;
}

function GLatLng(lat, lng){
    this.latitude = lat;
    this.longitude = lng;
    this.lat = function(){
        return this.latitude;
    }
    this.lng = function(){
        return this.longitude;
    }
}

function GPoint(x, y){
    this.x = x;
    this.y = y;
}

function GSize(width, height){
    this.width = width;
    this.height = height;
}

function Deg2Rad(deg){
    return deg / 180 * Math.PI;
}

function Rad2Deg(rad){
    return rad / Math.PI * 180;
}

function MercatorForward(latlng){

    var wgs84_a = 6378137.0;
    var wgs84_rf = 298.257223563;
    var lam = Deg2Rad(latlng.lng());
    var phi = Deg2Rad(latlng.lat());
    var es = 1 / wgs84_rf;
    var es = es * (2 - es);
    var e = Math.sqrt(es);
    var long = lam;
    var lat = Deg2Rad( (7915.70447 / Math.log(10)) * Math.log( Math.tan (Math.PI/4 + phi/2))  /  60);
    return new GLatLng(Rad2Deg(lat), Rad2Deg(long));
}

function MercatorInvers(latlng)
{
   var lng = latlng.lng();
   var D = latlng.lat();
   var C = 7915.70447 /( Math.log(10) * 60 );
   var lat = 2 * Math.atan( Math.pow(Math.E, D/C) ) - Math.PI/2;
   return new GLatLng(Rad2Deg(lat),lng);
}

function fromLatLngToPixel(latlng, zoom){
    var n = Math.pow(2,zoom);
    x = ((latlng.lng() + 180) * (256 * n / 360));
    y = ((256 * n/2) - (latlng.lat() * (256 * n / 360)));
    return new GPoint(x, y);
} 

function fromPixelToLatLng(pixel,zoom)
{
    var n = Math.pow(2,zoom);
    var lng = 360 * pixel.x/(256 * n) - 180;
    var lat = 360 * (256 * n/2 - pixel.y)/(256 * n);
    return new GLatLng(lat,lng);
}

function GPolyline(points, color, weight){
    this.type = 'polyline';
    this.points = new Array;
    if(points)this.points = points;
    this.color = color;
    this.weight = weight;

    this.image;
    this.latlng;
    this.top = 0;
    this.left = 0;
    this.pixel = new GPoint;

    var div = document.createElement('div');
    div.style.position = 'absolute';
    div.name = '__linediv';  
    this.div = div;

    this.events = new Array();

    this.move = function()
    {
       var size = sizeOfImage(this.points);
       var oldLL = MercatorInvers(fromPixelToLatLng(new GPoint(size.left + __map.min_s.x, size.top + __map.min_s.y),__map.zoom));
       var newLL = MercatorInvers(fromPixelToLatLng(new GPoint(parseInt(this.div.style.left) + __map.min_s.x, parseInt(this.div.style.top) + __map.min_s.y),__map.zoom));
        var dLat = newLL.lat()-oldLL.lat();
        var dLng = newLL.lng()-oldLL.lng();
        for (var i = 0; i < this.points.length; i++)
        {
           this.points[i].latitude  = parseFloat(parseFloat(this.points[i].latitude)  + dLat);
           this.points[i].longitude = parseFloat(parseFloat(this.points[i].longitude) + dLng);
        }
    }

    this.getPoint = function(){
        return this.latlng;
    }

    this.setPoint = function(){
        var size = sizeOfImage(this.points);
//        var url = '/ingeoweb/line.pl?height='+size.height+'&width='+size.width+'&color='+color+'&weight='+weight+'&path='+size.path;
        var url = '/cgi-bin/line.pl?height='+size.height+'&width='+size.width+'&color='+color+'&weight='+weight+'&path='+size.path;
        this.setImage();
        this.setImage(url);
        this.div.style.top  = size.top + 'px';
        this.div.style.left = size.left + 'px';
    }

    this.setImage = function(url)
    {
       if(this.image)
       {
          if(!url)
          {
             if(this.div)
             { 
                this.div.removeChild(this.image);
             }
             this.image = false;
             
          }
          else
          {
             this.image.src = url;
          }
       }
       else
       {
          var img = document.createElement('img');
          this.image = img;
          img.style.display = 'none';
          img.onload = function(){this.style.display = '';}
          img.style.position = 'absolute';
          img.name = '__line';
          img.fixed = 'yes'; 
          img.object = this; 
          img.src = url;
          this.div.appendChild(img);
       }
}

    function sizeOfImage(points)
    {
       if(!points) return new GImageSize(0,0,0,0);
       var maxLat = -90;
       var minLat =  90;
       var maxLng = -180;
       var minLng =  180;
       var path = 0;
       var temp = '';
       for (var i = 0; i < points.length; i++)
       {
          if(points[i].lat() > maxLat) maxLat = points[i].lat();
          if(points[i].lat() < minLat) minLat = points[i].lat();
          if(points[i].lng() > maxLng) maxLng = points[i].lng();
          if(points[i].lng() < minLng) minLng = points[i].lng();
       }   
       var minPixel  = fromLatLngToPixel(MercatorForward(new GLatLng(maxLat,minLng)), __map.zoom);
       var maxPixel  = fromLatLngToPixel(MercatorForward(new GLatLng(minLat,maxLng)), __map.zoom);

       var topPixel  = fromLatLngToPixel(MercatorForward(new GLatLng(maxLat,minLng)), __map.zoom);
       var top  = parseInt(topPixel.y - __map.min_s.y);
       var left = parseInt(topPixel.x - __map.min_s.x);
       var width = Math.abs(parseInt(maxPixel.y - minPixel.y));
       var height= Math.abs(parseInt(maxPixel.x - minPixel.x));

       for (var i = 0; i < points.length; i++)
       {
          var pixel = fromLatLngToPixel(MercatorForward(points[i]), __map.zoom);
          pixel.y = parseInt(pixel.y - __map.min_s.y - top);
          pixel.x = parseInt(pixel.x - __map.min_s.x - left);
//          temp = temp << 8;
          temp = temp + pixel.x + 'a';
//          temp = temp << 8;
          temp = temp + pixel.y + 'b';
       }

       return new GImageSize(height,width,top,left,temp);
    }


}

function GImageSize(height,width,top,left,path)
{
   this.height = height;
   this.width  = width;
   this.top    = top;
   this.left   = left;
   this.path   = path;
}


function __GIcon(){
    this.image = "default.ico";
    this.iconSize = new GSize(32, 32);
}

        function GIcon(url,width,height)
        {
           var img = document.createElement('img');
           img.src = url;
           img.style.position = 'absolute';
           img.alt = 'test';
           if(width)
           {
              img.style.width  = width+'px';
           }
           if(height)
           {
              img.style.height = height+'px';
           }
           return img;
        }


function GMarker(latlng, icon){
    this.type = 'marker';
    this.latlng = latlng;
    this.icon = icon;
    this.image; 
    this.top = 0;
    this.left = 0;
    this.events = new Array();
    this.onclick;

    var div = document.createElement('div');
    div.style.position = 'absolute';
    div.style.zIndex   = '99';
    div.appendChild(this.icon);
    this.div = div;

    
    this.addListener = function(evt,handler)
    {
       this.div.onclick = handler;
    }

    this.getPoint = function(){
        return this.latlng;
    }

    this.setPoint = function(latlng){
        this.latlng = latlng;
        this.pixel  = fromLatLngToPixel(MercatorForward(latlng), __map.zoom);
        this.top  = this.pixel.y - __map.min_s.y;
        this.left = this.pixel.x - __map.min_s.x;
        this.div.style.top  = parseInt(this.top - parseInt(this.icon.style.height)/2) + 'px';
        this.div.style.left = parseInt(this.left - parseInt(this.icon.style.width)/2) + 'px';
    }

    this.setImage = function(url)
    {
       if(this.image)
       {
          if(!url)
          {
             this.div.removeChild(this.image);
             this.image = false;
          }
          else
          {
             this.image.src = url;
          }
       }
       else
       {
          var img = document.createElement('img');
          img.src = url;
          img.style.position = 'absolute';
          img.style.width = this.icon.style.width;
          img.style.height= this.icon.style.height;
          if(this.icon){img.style.cursor = this.icon.style.cursor;}
          this.div.appendChild(img);
          this.image = img;
       }
    }


    this.pixel = fromLatLngToPixel(MercatorForward(latlng), __map.zoom);
    this.drawOverlay = function(min_s){
        this.pixel = fromLatLngToPixel(MercatorForward(latlng), __map.zoom);
        this.top = this.pixel.y - min_s.y;
        this.left = this.pixel.x - min_s.x;
        //    alert(this.left);
        //    alert(min_s.x);
    }
    this.openInfoWindow = function(html){
        if(!this.infoWindow)
        {
           this.infoWindow = document.createElement("div");
           this.infoWindow.style.zIndex = "500";
           this.infoWindow.id = "_infowindow";
           this.infoWindow.name = "_infowindowname";
           this.infoWindow.style.position = "absolute";
           this.infoWindow.style.top  = this.top   + 'px';

   this.infoWindow.innerHTML = '<table class="infowindow" sellpadding="0" cellspacing="0" ><tr><td NOWRAP style="border-color:#000000;border-style:solid;border-width:1;border-bottom-width:0;">&nbsp;</td></tr><tr><td NOWRAP id="markerInfoWindowDispaly" style="background-color:lemonchiffon;border-color:#000000;border-style:solid;border-width:1;">&nbsp;</td></tr><tr><td style="border-color:#000000;border-style:solid;border-width:1;border-top-width:0px;border-bottom-width:0px;border-right-width:0px;">&nbsp;</td></tr></table>';
          
             this.infoWindowCaption = this.infoWindow.getElementsByTagName('td').item(0);
             this.infoWindowDispaly = this.infoWindow.getElementsByTagName('td').item(1);
         }

        this.infoWindow.style.left = this.left  + 'px';

        __map.overlayContainer.appendChild(this.infoWindow);

        this.infoWindowCaption.onclick = this.removeInfoWindow;
        this.infoWindowDispaly.innerHTML = html; 

        this.infoWindow.style.top = parseInt(this.top - parseInt(this.infoWindow.clientHeight)) + 'px';
    }
    this.removeInfoWindow = function(ev)
    {
       if(!ev)ev = window.event;
       var target;
       var infoWindow;

       if(ev)
       {

          if(ev.target)
          {
             target = ev.target;
          }
          else
          {
             target = ev.srcElement;
          } 
          infoWindow = __getParentNodeById(target,'_infowindow');
       }
       else
       {
          infoWindow = this.infoWindow;
       }
       if(infoWindow && infoWindow.parentNode)infoWindow.parentNode.removeChild(infoWindow);      

    }
}

function testListener(ev)
{
   ev.stopPropagation();
}


function GMapTypeControl(){
    this.type = "maptypecontrol"
    this.position = new GPoint(0, 0);
    this.drawControl = function(){
        return 0;
    }
}

function _GEvent(){
    this.handlers = new Array;
    this.addListener = function(source, event, handler){
        this.handlers[this.handlers.length] = handler;
        source.events[source.events.length] = new Array(event, this.handlers.length - 1);
    }
    this.callHandler = function(handlerId){
        this.handlers[handlerId]();
    }
}

function ABounds()
{
   this.Top    = new GLatLng();
   this.Bottom = new GLatLng();
   this.contains = function(LatLng)
   {
      if(this.Top.lat() > LatLng.lat() && this.Top.lng() < LatLng.lng() && this.Bottom.lat() < LatLng.lat() && this.Bottom.lng() > LatLng.lng())
      {
         return true;
      }
      else
      {
         return false;
      }
   }
}

function GMap2(container){
    __map = this;
    this.container = container;
    this.center = new GLatLng(0, 0);
    this.initCenter = new GLatLng(0, 0);
    this.centerOffsetX = 0;
    this.centerOffsetY = 0;
    this.zoom = 5;
    this.width = container.offsetWidth;
    this.height = container.offsetHeight;
    this.imgOffsetX = 0;
    this.imgOffsetY = 0;
    this.container.style.overflow = "hidden";
    this.container.style.background = "lightgrey";
    this.container.style.border = "1px solid";
    this.overlays = new Array();
    this.mapImgRowCount = 0;
    this.mapImgColCount = 0;
    this.mapimages = new Array();
    this.centerpixel = fromLatLngToPixel(MercatorForward(this.center), this.zoom);
    this.initCenterPixel = new GPoint(this.centerpixel.x,this.centerpixel.y);
    this.min_s = new GPoint(this.centerpixel.x - this.width / 2, this.centerpixel.y - this.height / 2);
    this.ondblclick;
    this.pictures = '/gmap';

    this.getBounds = function()
    {
       var min_s = new GPoint(this.centerpixel.x - this.width / 2, this.centerpixel.y - this.height / 2);
       var max_s = new GPoint(this.centerpixel.x + this.width / 2, this.centerpixel.y + this.height / 2);
       var bounds = new ABounds;

       bounds.Top    = MercatorInvers(fromPixelToLatLng(min_s, this.zoom));
       bounds.Bottom = MercatorInvers(fromPixelToLatLng(max_s, this.zoom));
       return bounds;
    }

    this.overlayPaint = function(){
        this.overlayContainer.innerHTML = '';
        for (var i = 0; i < this.overlays.length; i++) {
          if(!this.overlays[i].hasChildNodes)
	           {
               if(this.overlays[i].icon)this.overlays[i].div.appendChild(this.overlays[i].icon);
               if(this.overlays[i].image)this.overlays[i].div.appendChild(this.overlays[i].image);
	           }
            this.overlays[i].setPoint(this.overlays[i].getPoint());
            this.overlayContainer.appendChild(this.overlays[i].div);
        }
      return;
    }
    this.createMapImages = function(container){
        this.mapImgColCount = Math.round(this.width / 256) + 4;
        this.mapImgRowCount = Math.round(this.height / 256) + 4;
        for (i = 0; i < this.mapImgRowCount; i++) {
            for (j = 0; j < this.mapImgColCount; j++) {
                this.mapimages[i + "," + j] = document.createElement("img");
                container.appendChild(this.mapimages[i + "," + j]);
                this.mapimages[i + "," + j].style.position = "absolute";
                this.mapimages[i + "," + j].style.left = (j - 2) * 256;
                this.mapimages[i + "," + j].style.top = (i - 2) * 256;
                this.mapimages[i + "," + j].style.height = 256;
                this.mapimages[i + "," + j].style.width = 256;
                this.mapimages[i + "," + j].loadedLeft = (j - 2) * 256;
                this.mapimages[i + "," + j].loadedTop = (i - 2) * 256;
                this.mapimages[i + "," + j].loaded = false;
                this.mapimages[i + "," + j].posX = j;
                this.mapimages[i + "," + j].posY = i;
                this.mapimages[i + "," + j].id = "_mapimage";
                this.mapimages[i + "," + j].name = "__mapimage";
                this.mapimages[i + "," + j].onerror=function () {this.src='/gmap/noimg.png';}
                this.mapimages[i + "," + j].onload =function () {this.style.display='';};
//		this.mapimages[i + "," + j].onclick = function () {statusText(this.src);};
            }
            
        }
        this.overlayContainer = document.createElement("div");
        this.overlayContainer.style.position = "absolute";
        this.overlayContainer.id = "__mapoverlay";
        container.appendChild(this.overlayContainer);
        this.mapImagesContainer.style.left = this.centerOffsetX;
        this.mapImagesContainer.style.top = this.centerOffsetY;
	this.overlayContainer.style.left =  - this.centerOffsetX;
	this.overlayContainer.style.top =  - this.centerOffsetY;
	this.setMapImagesURLs();
    }
    
    this.moveMapImages = function(){
        container = this.mapImagesContainer;

        imgOffsetX = Math.round(container.offsetLeft / 256);
        imgOffsetY = Math.round(container.offsetTop / 256);
        if (this.imgOffsetX != imgOffsetX) {
            if (this.imgOffsetX < imgOffsetX) {
                coloffset = 0 - imgOffsetX;
                j = Math.abs(imgOffsetX) % this.mapImgColCount;
            }
            else {
                coloffset = this.mapImgColCount - imgOffsetX - 1;
                j = Math.abs(imgOffsetX + 1) % this.mapImgColCount;
            }
            if ((this.imgOffsetX > imgOffsetX) && (imgOffsetX == 0)) {
                coloffset = this.mapImgColCount - imgOffsetX - 1;
                j = this.mapImgColCount - 1;
            }
            if (imgOffsetX > 0) 
                j = this.mapImgColCount - j;
            if (j == this.mapImgColCount) 
                j = 0;
            for (i = 0; i < this.mapImgRowCount; i++) {
                this.mapimages[i + "," + j].style.left = parseInt((coloffset - 2) * 256) + 'px';
            }

            this.imgOffsetX = imgOffsetX;
        }
        if (this.imgOffsetY != imgOffsetY) {
            if (this.imgOffsetY < imgOffsetY) {
                rowoffset = 0 - imgOffsetY;
                i = Math.abs(imgOffsetY) % this.mapImgRowCount;
            }
            else {
                rowoffset = this.mapImgRowCount - imgOffsetY - 1;
                i = Math.abs(imgOffsetY + 1) % this.mapImgRowCount;
            }
            if ((this.imgOffsetY > imgOffsetY) && (imgOffsetY == 0)) {
                rowoffset = this.mapImgRowCount - imgOffsetY - 1;
                i = this.mapImgRowCount - 1;
            }
            if (imgOffsetY > 0) 
                i = this.mapImgRowCount - i;
            if (i == this.mapImgRowCount) 
                i = 0;
            for (j = 0; j < this.mapImgColCount; j++) {
                this.mapimages[i + "," + j].style.top = parseInt((rowoffset - 2) * 256) + 'px';
            }

            this.imgOffsetY = imgOffsetY;
        }
        this.setMapImagesURLs();
    }
    
    this.paint = function(){
        //   alert(this.center.lat());
        this.container.innerHTML = '<div id="__mapimg" style="position:absolute;left:0;top:0;"></div><div id="__controloverlay" style="position:absolute;left:0;top:0;"></div><img src="" id="__cache" style="position:absolute;left:-1000;top:-1000;" this.src="/gmap/noimg.png";/>';

        this.mapImagesContainer = document.getElementById("__mapimg");
        this.mapImagesContainer.onmousedown = MD;
        this.mapImagesContainer.onmouseup   = MU;
        this.mapImagesContainer.onmousemove = MM;
        this.mapImagesContainer.ondblclick  = MDC;
	if (window.addEventListener) {
           this.mapImagesContainer.addEventListener('DOMMouseScroll',wheel,false);
	}else{
           this.mapImagesContainer.onmousewheel = wheel;
	}
        this.createMapImages(this.mapImagesContainer);
        this.overlayContainer = document.getElementById("__mapoverlay");
        this.controlContainer = document.getElementById("__controloverlay");
        this.overlayPaint();
        document.getElementById("_mapimage").onload = function(){
        }
    }
  
    this.isMapImageVisible = function(image){
        imageScreenLeft = this.mapImagesContainer.offsetLeft + image.offsetLeft;
        imageScreenTop = this.mapImagesContainer.offsetTop + image.offsetTop;
        if ((imageScreenLeft > -256) && (imageScreenLeft < this.container.offsetWidth)) {
            if ((imageScreenTop > -256) && (imageScreenTop < this.container.offsetHeight)) {
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    }
    
    this.MapImageNotLoaded = function(image){
        if (this.isMapImageVisible(image)) {
            if (!image.loaded || (image.loadedLeft != image.offsetLeft) || (image.loadedTop != image.offsetTop)) {
                image.loaded = false;
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    }
    
	this.resetLoaded = function(){
        for (i = 0; i < this.mapImgRowCount; i++) {
			for (j = 0; j < this.mapImgColCount; j++) {
				this.mapimages[i + "," + j].loaded = false;
			}
		}
	}
	

		this.getMapPicture=function(lat, lng, zoom){				
				var point   = fromLatLngToPixel(MercatorForward(new GLatLng(lat,lng)), zoom);
    var z = 17 - zoom;
    var x = Math.floor(point.x/256);
    var y = Math.floor(point.y/256);
    var picture = this.pictures+'/'+z+'/x'+x+'y'+y+'z'+z+'.png';
				return picture;
				} 

 		this.setMapImageURL  = function(i,j){
			if (this.MapImageNotLoaded(this.mapimages[i + "," + j])) {
				imgCenterPixel = new GPoint(this.initCenterPixel.x + this.mapimages[i + "," + j].offsetLeft - this.imgCountOffsetLeft * 256, this.initCenterPixel.y + this.mapimages[i + "," + j].offsetTop - this.imgCountOffsetTop * 256);
				imgCenter = MercatorInvers(fromPixelToLatLng(imgCenterPixel, this.zoom));
				this.mapimages[i + "," + j].src  = this.getMapPicture(imgCenter.lat(),imgCenter.lng(),this.zoom);	
				this.mapimages[i + "," + j].loaded = true;
				this.mapimages[i + "," + j].loadedLeft = this.mapimages[i + "," + j].offsetLeft;
				this.mapimages[i + "," + j].loadedTop = this.mapimages[i + "," + j].offsetTop;
    }
			}

    this.setMapImagesURLs = function(){
     for (i = 0; i < this.mapImgRowCount; i++) {
            for (j = 0; j < this.mapImgColCount; j++) {
                  this.setMapImageURL(i,j);
            }
        }
//alert(this.mapImgRowCount);
//alert(this.mapImgColCount);
/*var t2=this.mapImgRowCount;
var t1= this.mapImgColCount; 
var xy='';
if(t1<t2){ 
			var c2=t1*t1;
		}else{
			var c2=t2*t2;	
		}
var x=Math.floor(t1/2);
var y=Math.floor(t2/2);
var count=2;
var countStep=0;
var n='up';
var minX=x;
var maxX=x;
var minY=y;
var maxY=y;
this.setMapImageURL(x,y);
for (var i=1; i<c2; i++){
 countStep++;
 	if(count==countStep){
			switch (n) {
			case 'up':
					n='left';
		 break;
			case 'left':
					n='down';
					count++;
		 break;
			case 'down':
					n='right';
		 break;
			case 'right':
					n='up';
					count++;
		 break;		
		countStep=1;
		}
	}
if(n=='up'){y--;}
if(n=='left'){x--;}
if(n=='down'){y++;}
if(n=='right'){x++;}
if(x<minX){minX=x;}
if(y<minY){minY=y;}
if(x>maxX){maxX=x;}
if(y>maxY){maxY=y;}
this.setMapImageURL(x,y);
}
if(minX>0){
 for(var i=minX-1; i>0; i--) {
 	for(var j=0; j<t2;j++){
	  this.setMapImageURL(i,j);
		}
	}
}

if(minY>0){
 for(var j=minY-1; j>=0; j--) {
 	for(var i=0; i<t1;i++){
	  this.setMapImageURL(i,j);
		}
	}
}

if(maxX<t1){
 for(var i=maxX+1; i<t1; i++) {
 	for(var j=0; j<t2;j++){
				this.setMapImageURL(i,j);
		}
	}
}

if(maxY<t2){
 for(var j=maxY+1; j<t2; j++) {
 	for(var i=0; i<t1;i++){
				this.setMapImageURL(i,j);
		}
	}
}*/


     }

	this.calcCenter = function(offsetX, offsetY){
        this.centerpixel.x -= offsetX;
        this.centerpixel.y -= offsetY;
        this.center = MercatorInvers(fromPixelToLatLng(this.centerpixel, this.zoom));
    }
    
    //do no scroll grather then 255 pixels at once
	this.scrollOffset = function(offsetX, offsetY){
        this.centerpixel.x -= offsetX;
        this.centerpixel.y -= offsetY;
        this.center = MercatorInvers(fromPixelToLatLng(this.centerpixel, this.zoom));
	this.mapImagesContainer.style.left = this.mapImagesContainer.offsetLeft + offsetX;
	this.mapImagesContainer.style.top = this.mapImagesContainer.offsetTop + offsetY;
        this.moveMapImages();
	this.setMapImagesURLs();
    }


    this.setZoom = function(zoom){
        this.zoom = zoom;
        if (this.zoom < 1) {
            this.zoom = 1;
        }
        if (this.zoom > 17) {
            this.zoom = 17;
        }
//        this.control.scroll.style.top = (17 - __map.zoom) * 17.5 + 70;
        //    alert(zoom);
								this.calcMapCoords();
        this.mapImagesContainer.style.left = this.centerOffsetX;
        this.mapImagesContainer.style.top = this.centerOffsetY;
								this.overlayContainer.style.left =  - this.centerOffsetX;
								this.overlayContainer.style.top =  - this.centerOffsetY;
								this.imgOffsetX = 0;
								this.imgOffsetY = 0;
       	for (i = 0; i < this.mapImgRowCount; i++) {
										for (j = 0; j < this.mapImgColCount; j++) {
												this.mapimages[i + "," + j].style.left = (j - 2) * 256;
												this.mapimages[i + "," + j].style.top = (i - 2) * 256;
									}
								}
							 this.resetLoaded(); 
        this.setMapImagesURLs();
        this.overlayPaint();
    }

    this.scrollUp = function(){
		this.scrollOffset(0, -128);
    }


    this.scrollDown = function(){
		this.scrollOffset(0, 128);
    }

    this.scrollLeft = function(){
		this.scrollOffset(128, 0);
    }

    this.scrollRight = function(){
		this.scrollOffset(-128, 0);
    }
    
    this.zoomIn = function(){
        this.zoom++;
        if (this.zoom > 17) {
            this.zoom = 17;
        }
       // this.control.scroll.style.top = (17 - __map.zoom) * 17.15 + 70;
		this.setZoom(this.zoom);
    }
    
    this.zoomOut = function(){
        this.zoom--;
        if (this.zoom < 1) {
            this.zoom = 1;
        }
       // this.control.scroll.style.top = (17 - __map.zoom) * 17.15 + 70;
		this.setZoom(this.zoom);
    }
    
	this.calcMapCoords = function(){
           this.initCenter = new GLatLng(this.center.lat(), this.center.lng());
           this.centerLinear = MercatorForward(this.center);
           this.centerpixel = fromLatLngToPixel(MercatorForward(this.center), this.zoom);
           this.initCenterPixel = new GPoint(this.centerpixel.x, this.centerpixel.y);
           this.min_s = new GPoint(this.centerpixel.x - this.width / 2, this.centerpixel.y - this.height / 2);
           this.offsetCenterPixel = new GPoint(this.centerpixel.x + 256, this.centerpixel.y + 256);
           this.offsetCenter = fromPixelToLatLng(this.offsetCenterPixel, this.zoom);
           this.gridSizeLatLng = new GLatLng(this.offsetCenter.lat() - this.centerLinear.lat(), this.offsetCenter.lng() - this.centerLinear.lng());
//		document.title = "sizelat=" + this.gridSizeLatLng.lat() + "|sizelng=" + this.gridSizeLatLng.lng();
           this.gridLeftTopCoord = fromLatLngToPixel(new GLatLng(Math.floor(this.centerLinear.lat() / this.gridSizeLatLng.lat()) * this.gridSizeLatLng.lat(), (Math.floor(this.centerLinear.lng() / this.gridSizeLatLng.lng())* this.gridSizeLatLng.lng())),this.zoom);
           this.centerOffsetX = this.initCenterPixel.x - this.gridLeftTopCoord.x;
           this.centerOffsetY = this.initCenterPixel.y - this.gridLeftTopCoord.y;
           this.imgCountOffsetLeft = Math.floor((this.width / 2 - this.centerOffsetX) / 256);
           this.imgCountOffsetTop = Math.floor((this.height / 2 - this.centerOffsetY) / 256);
           this.centerOffsetX = (this.width / 2 - this.centerOffsetX) % 256;
           this.centerOffsetY = (this.height / 2 - this.centerOffsetY) % 256;
	}
	
    this.setCenter = function(center, zoom){
        this.center = center;
        this.zoom = zoom;
	this.calcMapCoords();
//		document.title = "|centeroffsetx=" + this.centerOffsetX + "|centeroffsety=" + this.centerOffsetY;
        this.paint();
    }
    
    this.addControl = function(control){
        if (control.type == "smallcontrol") {
            this.control = control;
            this.control.drawControl(this.controlContainer, new Array(this.scrollUp));
        }
    }
    
    this.addOverlay = function(overlay){
        this.overlays[this.overlays.length] = overlay;
        this.overlayContainer.appendChild(overlay.div);
//        this.overlayPaint();
    }

    this.removeOverlay = function(overlay){     
        if(!overlay)return;
//        if(!this.overlayContainer)return;
        if(overlay.div) 
        {
           try{   
              this.overlayContainer.removeChild(overlay.div);
           }catch(e){}         
        }
        var temp = new Array;
        for(var i = 0; i < this.overlays.length; i++)
        {
           if(overlay != this.overlays[i]) temp[temp.length] = this.overlays[i];
        }
        this.overlays = temp;
//        this.overlayPaint();
    }
}

var GEvent;
GEvent = new _GEvent();

