var _mapsource = "/cgi-bin/gmap.pl";
//var _mapsource = "/map_db/map_gen.php";
//var _mapsource = "http://192.168.0.151/cgi-bin/gde.pl";
var __map, __X, __Y, __oldX, __oldY;

//var zoomlevels = new Array(650000, 3750000, 7500000, 11250000, 15000000, 18750000, 22500000, 26250000);
//var zoomlevels = new Array(25000, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000);
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;

function MDC(ev)
{
   if(!ev) ev = window.event;


//   alert(__map.container.style.left);
   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 - parseInt(__map.container.style.left), __map.centerpixel.y - __map.height /2 - ev.clientY - parseInt(__map.container.style.top));

   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));
//   var nCenter =  MercatorInvers(fromPixelToLatLng(__map.centerpixel, __map.zoom));

//   alert(nCenter.lat() + '  ' + nCenter.lng());
   if(__map.ondblclick) __map.ondblclick(nCenter.lat(), nCenter.lng());
}

function __getParentNodeById(node,parentId)
{
   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;
    } 

//document.title = ev.target.nodeName + '=' + ev.target.name + ' '  + ev.currentTarget.nodeName + '=' + ev.currentTarget.name;
//document.title = __getParentNodeById(srcElement,'_infowindow');

    __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 + srcElement.offsetLeft + __map.container.offsetLeft;
//        __Y = ev.clientY + srcElement.offsetTop + __map.container.offsetTop;

        __X = ev.clientX;
        __Y = ev.clientY;

    }
    else {
//        return false;
    }
    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;

//        __ob.top  = parseInt(ev.clientY - __Y + parseInt(document.body.scrollTop)  - 3) + 'px';
//        __ob.left = parseInt(ev.clientX - __X + parseInt(document.body.scrollLeft) - 3) + 'px';

        if (__event == "__mapimage") {
//            __ob.left = parseInt(ev.clientX - __X + parseInt(document.body.scrollLeft) - 3) + 'px';
            __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 __MercatorInvers(latlng){
    //	alert(latlng.lat());
    var r_major = 6378137.000;
    var r_minor = 6356752.3142;
    var temp = r_minor / r_major;
    var es = 1.0 - (temp * temp);
    var eccent = Math.sqrt(es);
    var ts = Math.exp(-1 * Deg2Rad(latlng.lat()));
    var HALFPI = 1.5707963267948966;
    //    alert(ts);
    var eccnth, Phi, con, dphi;
    eccnth = 0.5 * eccent;
    
    Phi = HALFPI - 2.0 * Math.atan(ts);
    
    var N_ITER = 15;
    var TOL = 1e-7;
    var i = N_ITER;
    dphi = 0.1;
    while ((Math.abs(dphi) > TOL) && (--i > 0)) {
        con = eccent * Math.sin(Phi);
        dphi = HALFPI - 2.0 * Math.atan(ts * Math.pow((1.0 - con) / (1.0 + con), eccnth)) - Phi;
        //        alert(dphi);
        Phi += dphi;
    }
    //	alert(Rad2Deg(Phi));
    return new GLatLng(Rad2Deg(Phi), latlng.lng());
    //	return new GLatLng(latlng.lat(), latlng.lng());
}

function __MercatorForward(latlng){
    //lamdeg - longitude, phideg - latitude
    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 = Math.log(Math.tan(Math.PI / 4 + phi / 2) * Math.pow((1 - e * Math.sin(phi)) / (1 + e * Math.sin(phi)), e / 2));
    //  alert(Rad2Deg(phi));
    return new GLatLng(Rad2Deg(lat), Rad2Deg(long));
    //  return new GLatLng(latlng.lat(), latlng.lng());
}
function MercatorForward(latlng){
    //lamdeg - longitude, phideg - latitude
    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 = Math.log(Math.tan(Math.PI / 4 + phi / 2) * Math.pow((1 - e * Math.sin(phi)) / (1 + e * Math.sin(phi)), e / 2));

//    var lat = Deg2Rad(7915.70447 * lg( Math.tan (Math.PI/4 + phi/2))  /  60);
    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));
    //  return new GLatLng(latlng.lat(), latlng.lng());
}

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));
//    x = ((latlng.lng() + 180) * (256 * n / 180));
    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 __fromLatLngToPixel(latlng, zoom){
    //    alert(zoom);
    x = ((latlng.lng() + 180) * (zoomlevels[zoom - 1] / 180));
    y = (((latlng.lat() * -1) + 90) * (zoomlevels[zoom - 1] / 180));
    //    alert(x);
    return new GPoint(x, y);
}

function __fromPixelToLatLng(pixel, zoom){
    //    alert(zoom);
    lng = pixel.x * 180 / zoomlevels[zoom - 1] - 180;
    lat = (pixel.y * 180 / zoomlevels[zoom - 1] - 90) * -1;
    //    alert(zoomlevels[zoom-1]);
    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 = 'http://192.168.0.151/cgi-bin/line.pl?height='+size.height+'&width='+size.width+'&path='+size.path;
        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+'&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) + '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);
         }


//alert(infoWindowDispaly.innerHTML);
//          infoWindowDispaly.innerHTML = html; 


        this.infoWindow.style.left = this.left  + 'px';
/*
        this.infoWindow.style.width = 200 + 'px';
        this.infoWindow.style.height = 200 + 'px';
        this.infoWindow.style.background = "lemonchiffon";
        this.infoWindow.style.border = "1px solid black";
//        this.infoWindow.style.padding = "4px 4px 4px 4px";
        //    this.infoWindow.style.paddingLeft = "3";
*/

//        this.infoWindow.style.borderLeft = "2px solid black";


        __map.overlayContainer.appendChild(this.infoWindow);
//        this.infoWindow.addEventListener('click', testListener, true);
//        this.infoWindow.onclick = function(){alert('click infoWindow')};
//        this.infoWindow.innerHTML = html;
        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.removeChild(infoWindow);      

    }
}

function testListener(ev)
{
//   alert('testListener');
   ev.stopPropagation();
}


function GMapTypeControl(){
    this.type = "maptypecontrol"
    this.position = new GPoint(0, 0);
    this.drawControl = function(){
        return 0;
    }
}

function GSmallMapControl(){
    this.type = "smallcontrol"
    this.position = new GPoint(0, 0);
    this.drawControl = function(container){
        this.downArrow = document.createElement("div");
        this.downArrow.innerHTML = '<img src="down.gif" onclick="__map.scrollDown()"></img>';
        this.downArrow.style.position = "absolute";
        this.downArrow.style.left = 20;
        this.downArrow.style.top = 37;
        container.appendChild(this.downArrow);
        this.upArrow = document.createElement("div");
        this.upArrow.innerHTML = '<img src="up.gif" onclick="__map.scrollUp()"></img>';
        this.upArrow.style.position = "absolute";
        this.upArrow.style.left = 20;
        this.upArrow.style.top = 3;
        container.appendChild(this.upArrow);
        this.leftArrow = document.createElement("div");
        this.leftArrow.innerHTML = '<img src="left.gif" onclick="__map.scrollLeft()"></img>';
        this.leftArrow.style.position = "absolute";
        this.leftArrow.style.left = 3;
        this.leftArrow.style.top = 20;
        container.appendChild(this.leftArrow);
        this.rightArrow = document.createElement("div");
        this.rightArrow.innerHTML = '<img src="right.gif" onclick="__map.scrollRight()"></img>';
        this.rightArrow.style.position = "absolute";
        this.rightArrow.style.left = 37;
        this.rightArrow.style.top = 20;
        container.appendChild(this.rightArrow);
        this.zoomIn = document.createElement("div");
        this.zoomIn.innerHTML = '<img src="plus.gif" onclick="__map.zoomIn()"></img>';
        this.zoomIn.style.position = "absolute";
        this.zoomIn.style.left = 20;
        this.zoomIn.style.top = 53;
        container.appendChild(this.zoomIn);
        this.zoomOut = document.createElement("div");
        this.zoomOut.innerHTML = '<img src="minus.gif" onclick="__map.zoomOut()"></img>';
        this.zoomOut.style.position = "absolute";
        this.zoomOut.style.left = 20;
        this.zoomOut.style.top = 202;
        container.appendChild(this.zoomOut);
        this.scrollback = document.createElement("div");
        this.scrollback.id = "_scrollbackground";
        this.scrollback.innerHTML = '<img name="__scrollbackimg" src="slider_back.gif"></img>';
        this.scrollback.style.position = "absolute";
        this.scrollback.style.left = 20;
        this.scrollback.style.top = 73;
        container.appendChild(this.scrollback);
        this.scroll = document.createElement("div");
        this.scroll.id = "_scroll";
        this.scroll.innerHTML = '<img name="__scrollimg" src="slider.gif"></img>';
        this.scroll.style.position = "absolute";
        this.scroll.style.left = 20;
        this.scroll.style.top = (17 - __map.zoom) * 17.15 + 70;
        container.appendChild(this.scroll);
    }
}

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.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.overlayContainer.innerHTML = '';
        for (i = 0; i < this.overlays.length; i++) {
            this.overlays[i].drawOverlay(this.min_s);
            this.overlayContainer.innerHTML += '<div id="_overlay' + i + '" style="position:absolute;' +
            'top:' +
            parseInt(parseInt(this.overlays[i].top)  - 16) + 'px' +
            ';left:' +
            parseInt(parseInt(this.overlays[i].left) - 16) + 'px' +
            ';">' +
            '<img src="' +
            this.overlays[i].icon.image +
            '"' +
            'on' +
            this.overlays[i].events[0][0] +
            '=GEvent.callHandler(' +
            this.overlays[i].events[0][1] +
            ')></img>' +
            '</div>';
            //      alert(this.overlays[i].top);
        }
    }
    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].oncontextmenu = contextMenu;
            }
        }
        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;

//        document.title = container.offsetLeft; 

        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';
            }
//                        document.title = "j=" + j + "|coloffset=" + coloffset + "|imgoffsetx=" + imgOffsetX + "|colcount=" + this.mapImgColCount+"|containerOffSet="+container.offsetLeft;
            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';
            }
            //            document.title = "i=" + i + "|rowoffset=" + rowoffset + "|imgoffsety=" + imgOffsetY + "|rowcount=" + this.mapImgRowCount;
            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><div id="__copyright" style="position:absolute;left:15;top:' +
        (this.height - 50) +
        ';"><a href="http://www.vi-tel.ru"><img src="/img/vilogo.gif" border="0"></a></div> ';
        this.mapImagesContainer = document.getElementById("__mapimg");
        this.mapImagesContainer.onmousedown = MD;
        this.mapImagesContainer.onmouseup   = MU;
        this.mapImagesContainer.onmousemove = MM;
        this.mapImagesContainer.ondblclick  = MDC;
//        this.mapImagesContainer.oncontextmenu = contextMenu;

        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.setMapImagesURLs = function(){
        for (i = 0; i < this.mapImgRowCount; i++) {
            for (j = 0; j < this.mapImgColCount; 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 = _mapsource +
                    '?scale=' +
                    this.zoom +
                    '&scale_level=' +
                    zoomlevels[this.zoom - 1] +
                    '&lat=' +
                    imgCenter.lat() +
                    '&long=' +
                    imgCenter.lng() +
                    '&width=256&height=256';
                    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;
//					if (this.mapimages[i + "," + j].offsetTop == 0) {
//						document.title = "i=" + i +"|j=" + j + "|imgCenter.lng()=" + imgCenter.lng() + "|imgCenter.lat()=" + imgCenter.lat() + "|offsettop=" + this.initCenterPixel.y ;
//					}
                }
            }
        }
    }

	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();

