/**
 * google mapa 
 * vojtech.sir@perus.cz  
 */ 
function gmap(lat, lng, zoom, map_type, name, c_zoom, c_search, c_overview, c_switch, map_drag, markers_drag, add_markers, add_polys, sidebar, select_name) {
   
   this.map = null;
   this.name = name;
   this.lat = lat;
   this.lng = lng;
   this.zoom = zoom;
   this.map_type = map_type; 
   this.map_types = {0: G_NORMAL_MAP, 1: G_SATELLITE_MAP, 2: G_PHYSICAL_MAP, 3: G_HYBRID_MAP};
   this.markers = {};
   this.polys = {};
   this.polys_show = {};
   this.poly_size = {};
   this.poly_color = {};
   this.poly_fill = {};
   this.poly_name = {};
   this.poly_center = {};
   this.poly_zoom = {};
   this.control_zoom = c_zoom;
   this.control_search = c_search;
   this.control_overview = c_overview;
   this.control_switch = c_switch;
   this.map_drag = map_drag;
   this.markers_drag = markers_drag;
   this.markers_count = 0;
   this.markers_cats = {};
   this.polys_count = 0;
   this.add_markers = add_markers;
   this.add_polys = add_polys;
   this.sidebar = sidebar;
   this.select_name = select_name;
   this.edit_poly = null;
   this.show_poly = null;
   this.bounds = null;
   this.show_all = false;
   this.poly_selected = null;
   this.poly_selected_obj = null;
   this.bounds = new GLatLngBounds(new GLatLng(49.93, 14.16), new GLatLng(50.222, 14.848));   
   this.scroll_down = null;
   this.scroll_up = null;

   this.initialize = function() {
      if (GBrowserIsCompatible()) {     
         this.map = new GMap2(getEl('g' + this.name), {backgroundColor: '#ffefb6', googleBarOptions: {showOnLoad: true, suppressInitialResultSelection: true}});
         this.map.addMapType(G_PHYSICAL_MAP);
         this.map.setMapType(this.map_types[this.map_type]);
         this.map.setCenter(new GLatLng(this.lat, this.lng), this.zoom);
         this.map.enableContinuousZoom();
         if (!this.map_drag) {
            this.map.disableDragging();
         }

         if (this.control_zoom) this.map.addControl(new GLargeMapControl());
         //if (this.control_switch) this.map.addControl(new GMapTypeControl());
         if (this.control_search) this.map.enableGoogleBar();
         if (this.control_overview) {
            var ov = new GOverviewMapControl(new GSize(120, 120));
            //ov.setMapType(this.map_types[this.ov_type]);
            this.map.addControl(ov);
         }

         this.sidebar = document.createElement('div');
         this.sidebar.id = '__sidebar';
         //this.sidebar.style.padding = '8px';
         this.sidebar.style.backgroundColor = '#ffffc6';
         this.sidebar.style.border = '1px solid #f8ca60';
         //this.sidebar.style.overflow = (navigator.appName == 'Microsoft Internet Explorer') ? 'auto' : '-moz-scrollbars-vertical';
         this.sidebar.style.overflow = 'hidden';
         this.sidebar.style.height= '790px';  
         this.sidebar.style.width = '200px';       
         //this.sidebar.style.paddingLeft = '5px';
         //this.sidebar.innerHTML = '<a class="mapside" href="index.php">Celá Praha</a>';               

         this.indexlink = document.createElement('div');
         this.indexlink.style.backgroundColor = '#ffffc6';
         this.indexlink.style.border = '1px solid #f8ca60';
         this.indexlink.style.height= '35px';  
         this.indexlink.style.width = '200px';       
         this.indexlink.innerHTML = '<a class="mapside" href="index.php">Celá Praha</a>';               

         this.zoomdiv = document.createElement('div');
         this.zoomdiv.style.backgroundColor = 'transparent';
         //this.zoomdiv.style.border = '1px solid #f8ca60';
         this.zoomdiv.style.height= '130px';  
         this.zoomdiv.style.width = '130px';       
         this.zoomdiv.innerHTML = '<a href="javascript:mapa.zoomIn()"><img src="design/l1/d1/images/plus.gif" /></a>&nbsp;&nbsp;<a href="javascript:mapa.zoomOut()"><img src="design/l1/d1/images/minus.gif" /></a>';               

         this.switcher = document.createElement('div');
         this.switcher.style.backgroundColor = 'transparent';
         //this.switcher.style.border = '1px solid #f8ca60';
         this.switcher.style.height= '190px';  
         this.switcher.style.width = '197px';       
         this.switcher.innerHTML = '<a href="javascript:mapa.mapType(0)"><img id="_map0" class="block" src="design/l1/d1/images/map0.gif" /></a><br>';
         this.switcher.innerHTML += '<a href="javascript:mapa.mapType(1)"><img id="_map1" class="block" src="design/l1/d1/images/map1.gif" /></a><br>';               
         this.switcher.innerHTML += '<a href="javascript:mapa.mapType(2)"><img id="_map2" class="block" src="design/l1/d1/images/map2.gif" /></a><br>';               
         this.switcher.innerHTML += '<a href="javascript:mapa.mapType(3)"><img id="_map3" class="block" src="design/l1/d1/images/map3_over.gif" /></a><br>';               

         this.locbar = document.createElement('div');
         this.locbar.id = 'locbar';
         this.locbar.style.padding = '8px';
         this.locbar.style.paddingTop = '5px';
         this.locbar.style.backgroundColor = '#fff2c7';
         this.locbar.style.border = '1px solid #f8ca60';
         this.locbar.style.height= '50px';  
         this.locbar.style.width = '250px';       
         this.locbar.style.fontWeight = 'bold';
         this.locbar.innerHTML = 'Zobrazeno:<h1 class="mapa">Celá Praha</h1>';               

         this.bottom = document.createElement('div');   
         this.bottom.style.width = '100%';
         this.bottom.style.height = '35px'; 
         this.bottom.style.backgroundColor = 'transparent';                  

         this.up = document.createElement('div');   
         this.up.style.width = '57px';
         this.up.style.height = '57px'; 
         this.up.innerHTML = '<a onclick="goUp()"><img class="block" src="design/l1/d1/images/up.gif" /></a>';
         //this.up.innerHTML = '<a onmouseover="mapa.scroll_up = setInterval(scrollUp, 10);" onmouseout="clearInterval(mapa.scroll_up);"><img class="block" src="design/l1/d1/images/up.gif" /></a>';
         this.down = document.createElement('div');   
         this.down.style.width = '57px';
         this.down.style.height = '57px'; 
         this.down.innerHTML = '<a onclick="goDown()"><img class="block" src="design/l1/d1/images/down.gif" /></a>';
         //this.down.innerHTML = '<a onmouseover="mapa.scroll_down = setInterval(scrollDown, 10);" onmouseout="clearInterval(mapa.scroll_down);"><img class="block" src="design/l1/d1/images/down.gif" /></a>';

         if (this.add_markers) this.addMarkers(this.add_markers);
         if (this.add_polys) this.addPolys(this.add_polys);

         var mt = this.map.getMapTypes();
         for (var i=0; i < mt.length; i++) {
           mt[i].getMinimumResolution = function() {return 13;}
           mt[i].getMaximumResolution = function() {return 17;}
         }

         this.map.addControl(new this.addBottom(this.name));

         var mapa = this;
         GEvent.addListener(this.map, 'move', function() {mapa.checkBounds();});
         GEvent.addListener(this.map, 'zoomend', function() {mapa.zoomEnd();});
         if (this.show_poly) this.triggerPoly(this.show_poly);

         if (!this.show_all) this.map.addControl(new this.addSidebar(this.name));
         if (!this.show_all) this.map.addControl(new this.addLocbar(this.name));
         if (!this.show_all) this.map.addControl(new this.addIndexLink(this.name));
         if (!this.show_all) this.map.addControl(new this.addZoom(this.name));
         if (!this.show_all) this.map.addControl(new this.addSwitch(this.name));
         this.map.addControl(new this.addUp(this.name));
         this.map.addControl(new this.addDown(this.name));
      }
   }


   this.checkBounds = function() {
     if (this.bounds.contains(this.map.getCenter())) {
       return;
     }
     var C = this.map.getCenter();
     var X = C.lng();
     var Y = C.lat();

     var AmaxX = this.bounds.getNorthEast().lng();
     var AmaxY = this.bounds.getNorthEast().lat();
     var AminX = this.bounds.getSouthWest().lng();
     var AminY = this.bounds.getSouthWest().lat();

     if (X < AminX) {X = AminX;}
     if (X > AmaxX) {X = AmaxX;}
     if (Y < AminY) {Y = AminY;}
     if (Y > AmaxY) {Y = AmaxY;}
     this.map.setCenter(new GLatLng(Y,X));
   }

   this.zoomIn = function() {
      this.map.zoomIn();
   }
   this.zoomOut = function() {
      this.map.zoomOut();
   }

   this.mapType = function(type) {
      var path = 'design/l1/d1/images/';
      for(var i = 0; i < 4; i++) {
         document.getElementById('_map' + i).src = (i == type) ? path + 'map' + i + '_over.gif' : path + 'map' + i + '.gif';
      }
      this.map.setMapType(this.map_types[type]);
   }

   // pridej polygony
   this.addPolys = function(polys) {
      var i = 0;
      //var opacity = 10;

      this.sidebar.innerHTML += '<ul>';
      for (var key in polys) {
         //if (this.markers_cats[key]) {
            var pole = polys[key];
            var body = pole[0];
            this.sidebar.innerHTML += '<a class="mapside" href="index.php?kat=' + key + '">' + pole[6] + '</a>';

            if (typeof body == 'object') {
               var obj = null;
               if (!this.show_poly || this.show_poly == key) {
                  var points = new Array();
                  for (var y = 0; y < body.length; y += 2) {
                     points.push(new GLatLng(body[y], body[y+1]));
                  }
                  obj = new GPolygon(points, pole[1], pole[3], 1, pole[2], (pole[4]/10));         
                  this.map.addOverlay(obj);
                  this.polys_show[key] = true;
               }
            }
            else {
               var levels = new Array(pole[5]+1).join('P');
               var obj = new GPolygon.fromEncoded({
                           polylines: [{points: body,
                                        levels: levels,
                                        color: pole[1],
                                        opacity: 1,
                                        weight: pole[3],
                                        numLevels: 0,
                                        zoomFactor: 0}],
                          fill: true,
                          color: pole[2],
                          opacity: (pole[4]/10),
                          outline: true
                        });           
               this.map.addOverlay(obj);
            }
            if (obj) {
               this.polyListener(obj, key);
               this.polys[key] = obj;
               this.poly_size[key] = pole[3];
               this.poly_color[key] = pole[1];
               this.poly_fill[key] = pole[2];
               this.poly_name[key] = pole[6];
               this.poly_center[key] = new GLatLng(pole[7][0], pole[7][1]);
               this.poly_zoom[key] = pole[8];
            }
         //}
      }
      this.sidebar.innerHTML += '</ul>';
   }

   this.polyListener = function(obj, id) {
      var t = this;
      GEvent.addListener(obj, 'mouseover', function() {
            t.setPolyOver(obj, id);
         });      
      GEvent.addListener(obj, 'mouseout', function() {
            t.setPolyOut(obj, id);
         });      
      GEvent.addListener(obj, 'click', function() {
            t.zoomToPoly(obj, id);
         });      

   }

   this.addMarker = function() {
      
      if (!this.markers_count) {
         var marker_icon = new GIcon(G_DEFAULT_ICON);
         var center = this.map.getCenter();
         var pos = new GLatLng(center.lat(), center.lng());
         this.createMarker(this.markers_count, pos, marker_icon);
         this.markers_count++;
      }
      else {
         var center = this.map.getCenter();
         this.markers[0].setLatLng(new GLatLng(center.lat(), center.lng()));
      }
      GEvent.trigger(this.markers[0], 'dragend');
   }

   this.createMarker = function(num, cat, pos, marker_icon) {
      var marker = new GMarker(pos, {draggable: this.markers_drag, icon: marker_icon});         
      var map = this.map;
      this.map.addOverlay(marker);         
      if (!this.show_all) marker.hide();
      this.markers_cats[cat].push(marker);
      this.markers[num] = marker;
   }


   this.addMarkers = function(markers) {
      var i = 0;
      for (var key in markers) {
         if (key == this.show_poly) {
            var m = markers[key];
            this.markers_cats[key] = new Array();
            for(var y = 0; y < m.length; y++) {
               var cat = parseInt(key);
               var pole = m[y];
               var pos = new GLatLng(pole[0], pole[1]);
               var marker_icon = new GIcon(G_DEFAULT_ICON);
               //if (!this.show_all) {
                  marker_icon.iconSize = new GSize(36, 53);
                  marker_icon.shadow = '';
                  marker_icon.shadowSize = new GSize(36, 53);
                  marker_icon.iconAnchor = new GPoint((36/2), 0);
                  marker_icon.infoWindowAnchor = new GPoint((36/2), 0);
                  marker_icon.image = 'design/l1/d1/cz/images/ikona.gif';	
                  marker_icon.transparent = '';	
               //}
            
               this.createMarker(i, cat, pos, marker_icon);
               if (pole[2] && pole[3].length) {
                  this.setMarkerWindow(i, pole[2], pole[3]);
               }
               i++;
            }
         }
         else {
            this.markers_cats[key] = new Array();                
         }
      }
   }

   this.setMarkerWindow = function(num, id, text) {
      var marker = this.markers[num];
      var map = this.map;
      if (text && text.length) {
         var html = '<h1 style="margin: 0;margin-bottom:15px;">' + text + '</h1>';
         html += '<h2><a href="index.php?sec=adv_redaction&s_cat=' + id +'">Detail naleziště</a></h2>';
         GEvent.addListener(marker, "mouseover", function() {
            marker.openInfoWindowHtml(html);
         });
      }
      GEvent.addListener(marker, "click", function() {
         //alert('aaaa');
         location.href = 'index.php?sec=adv_redaction&s_cat=' + id;
      });
   }

   this.triggerClick = function(num) {
      if (num != 'select') {
         GEvent.trigger(this.markers[num], 'click');
      }
   }

   this.triggerPoly = function(id) {
      if (!this.polys_show[id]) {
         //this.show_poly = id;
         this.map.addOverlay(this.polys[id]);
      }
      GEvent.trigger(this.polys[id], 'click');
   }

   this.triggerPolyOver = function(id) {
      if (this.polys[id]) {
         GEvent.trigger(this.polys[id], 'mouseover');
      }
   }

   this.triggerPolyOut = function(id) {
      if (this.polys[id]) {
         GEvent.trigger(this.polys[id], 'mouseout');
      }
   }

   this.hideAllMarkers = function() {
      for(key in this.markers) {
         this.markers[key].hide();
      }      
   }
   
   this.showMarkersCat = function(id) {
      this.hideAllMarkers();      
      if (this.markers_cats[id]) {
         for(var i = 0; i < this.markers_cats[id].length; i++) {
            this.markers_cats[id][i].show();
         }      
      }
   }

   this.zoomToPoly = function(poly, id) {
      this.polys_show[id] = true;
      this.resetPoly();
      this.allHide(id);
      poly.setStrokeStyle({color: "#EECF07"});
      poly.setFillStyle({color: "#FCCC79"});
      //var bounds = poly.getBounds();
      //var zoom = this.map.getBoundsZoomLevel(bounds);
      this.map.setCenter(this.poly_center[id], this.poly_zoom[id]);
      this.map.closeInfoWindow();
      //this.map.setZoom(zoom);
      this.showMarkersCat(id);
      this.setLocbar(id);
      this.setPolyOver(poly, id);
      this.poly_selected = id;
      this.poly_selected_obj = poly;
   }
   
   this.allHide = function(id) {
      for(key in this.polys) {
         if (key != id) {
            this.polys[key].hide();
         }
         else {
            this.polys[key].show();               
         }
      }            
   }

   this.allShow = function() {
      for(key in this.polys) {
        this.polys[key].show();               
      }            
   }

   this.setPolyOver = function(poly, id) {
      if (!this.poly_selected) {
         var size = this.poly_size[id] + 4;
         poly.setStrokeStyle({weight: size, color: "#EECF07"});
         if (this.map.getZoom() > 14) {
            this.showMarkersCat(id);
         }
         if (this.map.getZoom() < 13) {
            //var latlng = poly.getBounds().getCenter();
            this.map.openInfoWindowHtml(this.poly_center[id], '<h1>' + this.poly_name[id] + '</h1>');
         }
         //getEl('g' + this.name).style.cursor = 'pointer';
      }
   }

   this.setPolyOut = function(poly, id) {
      //this.hideAllMarkers();      
      if (!this.poly_selected) {
         poly.setStrokeStyle({weight: this.poly_size[id], color: this.poly_color[id]});
         this.map.closeInfoWindow();
      }
      //document.body.style.cursor = '';
   }

   this.setLocbar = function(id) {
      this.locbar.innerHTML = 'Zobrazeno:<h1 class="mapa">' + this.poly_name[id] + '</h1>';
   }

   this.showFull = function() {
      if (this.show_poly) {
         for ( var key in this.polys) {
            if (!this.polys_show[key]) {
               this.map.addOverlay(this.polys[key]);    
            }
         }
         this.show_poly = null;
      }
      this.resetPoly();
      this.map.setCenter(new GLatLng(this.lat, this.lng), this.zoom);  
      this.allShow();
      this.hideAllMarkers();
      this.map.closeInfoWindow();
      this.locbar.innerHTML = 'Zobrazeno:<h1 class="mapa">Celá Praha</h1>';       
   }

   this.resetPoly = function() {
      if (this.poly_selected) {
         var id = this.poly_selected;
         var poly = this.poly_selected_obj;
         poly.setStrokeStyle({weight: this.poly_size[id], color: this.poly_color[id]});
         poly.setFillStyle({color: this.poly_fill[id]});                  
         this.poly_selected = null;
         this.poly_selected_obj = null;
      }
   }

   this.zoomEnd = function() {
      if (this.map.getZoom() < 14) {
         //this.hideAllMarkers();
      }      
   }

   this.addSidebar = function(name) {
      this.objname = name;
   }
   this.addSidebar.prototype = new GControl(false, false);
   this.addSidebar.prototype.initialize = function(map) {
      map.getContainer().appendChild(window[this.objname].sidebar);
      return window[this.objname].sidebar;
   }
   this.addSidebar.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(90, 85));
   }

   this.addSwitch = function(name) {
      this.objname = name;
   }
   this.addSwitch.prototype = new GControl(false, false);
   this.addSwitch.prototype.initialize = function(map) {
      map.getContainer().appendChild(window[this.objname].switcher);
      return window[this.objname].switcher;
   }
   this.addSwitch.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20, 105));
   }

   this.addIndexLink = function(name) {
      this.objname = name;
   }
   this.addIndexLink.prototype = new GControl(false, false);
   this.addIndexLink.prototype.initialize = function(map) {
      map.getContainer().appendChild(window[this.objname].indexlink);
      return window[this.objname].indexlink;
   }
   this.addIndexLink.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(90, 33));
   }

   this.addZoom = function(name) {
      this.objname = name;
   }
   this.addZoom.prototype = new GControl(false, false);
   this.addZoom.prototype.initialize = function(map) {
      map.getContainer().appendChild(window[this.objname].zoomdiv);
      return window[this.objname].zoomdiv;
   }
   this.addZoom.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20, 330));
   }


   this.addLocbar = function(name) {
      this.objname = name;
   }
   this.addLocbar.prototype = new GControl(false, false);
   this.addLocbar.prototype.initialize = function(map) {
      map.getContainer().appendChild(window[this.objname].locbar);
      return window[this.objname].locbar;
   }
   this.addLocbar.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20, 15));
   }

   this.addBottom = function(name) {
      this.objname = name;
   }
   this.addBottom.prototype = new GControl(false, false);
   this.addBottom.prototype.initialize = function(map) {
      map.getContainer().appendChild(window[this.objname].bottom);
      return window[this.objname].bottom;
   }
   this.addBottom.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0, 0));
   }

   this.addUp = function(name) {
      this.objname = name;
   }
   this.addUp.prototype = new GControl(false, false);
   this.addUp.prototype.initialize = function(map) {
      map.getContainer().appendChild(window[this.objname].up);
      return window[this.objname].up;
   }
   this.addUp.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 400));
   }
   this.addDown = function(name) {
      this.objname = name;
   }
   this.addDown.prototype = new GControl(false, false);
   this.addDown.prototype.initialize = function(map) {
      map.getContainer().appendChild(window[this.objname].down);
      return window[this.objname].down;
   }
   this.addDown.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 480));
   }

   window[this.name] = this;
   var map = this.name;
   window.attachEvent ? window.attachEvent('onload', function() {window[map].initialize();}) : window.addEventListener('load',  function() {window[map].initialize();}, false);
}

function scrollDown() {
   var div = document.getElementById('__sidebar');
   if (parseInt(div.scrollTop) < parseInt(div.scrollHeight)) {
      div.scrollTop += 15;            
   }
}
function scrollUp() {
   var div = document.getElementById('__sidebar');
   if (div.scrollTop > 0) {
      div.scrollTop -= 15;            
   }
}

function goUp(i) {
   var div = document.getElementById('__sidebar');
   if (!i) i = 0;
   if (i < 20 && div.scrollTop > 0) {
      div.scrollTop -= 20;            
      setTimeout('goUp(' + (i+1) + ')', 1);
   }      
}

function goDown(i) {
   var div = document.getElementById('__sidebar');
   if (!i) i = 0;
   if (i < 20 && parseInt(div.scrollTop) < parseInt(div.scrollHeight)) {
      div.scrollTop += 20;            
      setTimeout('goDown(' + (i+1) + ')', 1);
   }      
}

function _goUp() {
   var div = document.getElementById('__sidebar');
   if (div.scrollTop > 0) {
      div.scrollTop -= 400;            
   }   
}
function _goDown() {
   var div = document.getElementById('__sidebar');
   if (parseInt(div.scrollTop) < parseInt(div.scrollHeight)) {
      div.scrollTop += 400;            
   }
}
