// JavaScript Document

    var map;
    var rect;
    var mgr;
    var icons = {};
	var marker;



    function load() {
      if (GBrowserIsCompatible()) {
	  
//	    window.moveTo(0,0);
//		window.resizeTo(screen.width,screen.height);
		
	
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GOverviewMapControl());
		    map.addControl(new GMapTypeControl());
		
   		  map.enableContinuousZoom();
		    map.enableScrollWheelZoom();
        map.enableDoubleClickZoom();
				map.setMapType(G_HYBRID_MAP );


        map.setCenter(new GLatLng(-22.59888, -47.878081), 14);



		GEvent.addListener(map, 'infowindowclose', mapIWClose);

        window.setTimeout(setupOfficeMarkers, 0);


      }
    }

    function getIcon(images) {
      var icon = null;
      if (images) {
        if (icons[images[0]]) {
          icon = icons[images[0]];
        } else {
          icon = new GIcon();
          icon.image = "images/icones/" 
              + images[0] + ".png";
          var size = iconData[images[0]];
          icon.iconSize = new GSize(size.width, size.height);
          icon.iconAnchor = new GPoint(size.width >> 1, size.height >> 1);
          icon.shadow = "images/" 
              + images[1] + ".png";
          size = iconData[images[1]];
          icon.shadowSize = new GSize(size.width, size.height);
		  icon.infoWindowAnchor = new GPoint(13, 1);
          icon.infoShadowAnchor = new GPoint(26, 13);
          icons[images[0]] = icon;
        }
      }
      return icon;
    }

    function createZoomMarker(detailMap) {
      for (var i in officeLayer) {
        var layer = officeLayer[i];
        var markersZoomArray = [];
        for (var j in layer["places"]) {
          var place = layer["places"][j];
          var icon = getIcon(place["icon"]);
          var id = place["id"];
          var title = place["name"];
          var labels = place["labels"];
          var html = null;
          var posn = new GLatLng(place["posn"][0], place["posn"][1]);
	      var markerZoom = createMarker(posn, title, icon, html);
          markersZoomArray.push(markerZoom);
        }
		
	    var icon_Cluster = getIcon(["zoom","zoom-shadow"]);		  
        mgr = new MarkerManager(detailMap, {trackMarkers:true});
        mgr.addMarkers(markersZoomArray, 0, 17);

      }
    mgr.refresh();
//       ZoomCluster.refresh(true);
    }
	
	
    function setupOfficeMarkers() {
      for (var i in officeLayer) {
        var layer = officeLayer[i];
        var markersArray = [];
        for (var j in layer["places"]) {
          var place = layer["places"][j];
          var icon = getIcon(place["icon"]);
          var id = place["id"];
          var title = place["name"];
          var html = place["html"];
          var labels = place["labels"];
          var posn = new GLatLng(place["posn"][0], place["posn"][1]);
	        var marker = createTabbedMarker(posn, title, icon, html, labels, id);
/*	
		  var listItem = document.createElement('li');
			  listItem.innerHTML = '<div class="label">&nbsp;'+id+'&nbsp;</div><a href="' + title + '">' + title + '</a>';
			  document.getElementById('sidebar-list').appendChild(listItem);
			  
*/			  
              markersArray.push(marker);
        }
				


		  
		
	    var icon_Cluster = getIcon(["zoom","zoom-shadow"]);
		  
		var myCluster = new ClusterMarker(map, { markers:markersArray , clusterMarkerTitle:"Clique para ampliar e ver %count empresas", clusterMarkerIcon:icon_Cluster, fitMapMaxZoom:layer["zoom"][16], borderPadding: 512} );
//		myCluster.clusterMarkerClick=function(args) { args.clusterMarker.openInfoWindowHtml( args.clusteredMarkers.length + ' markers clustered here.');
		  myCluster.fitMapToMarkers();
//        mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
      }
  //    mgr.refresh();
       myCluster.refresh(true);
    }
		

  
    function createMarker(posn, title, icon, html) {

		opts = {
					 "icon": icon,
					 "clickable": true,
					 "title": title,
					 "labelText": "",
					 "labelOffset": new GSize(-6, -10)
				};

	  var marker = new LabeledMarker(posn, opts);
	  if (html){
	  var markerHtml = "<h4>"+title+"</h4>"+html;
	    GEvent.addListener(marker, "click", function(){ 
			marker.openInfoWindowHtml(markerHtml);
		});	  
	  }
      
      return marker;
    }

    function deleteMarker() {
//      var markerNum = parseInt(document.getElementById("markerNum").value);
//      mgr.removeMarker(allmarkers[markerNum]);
		myCluster.removeMarkers();
    }
   
    function clearMarkers() {
      mgr.clearMarkers();
    }
   
    function reloadMarkers() {
      setupOfficeMarkers();
    }
	
	

  function createTabbedMarker(point, title, icon, htmls, labels, id) {


	opts = {
	       "icon": icon,
	       "clickable": true,
		     "title": title,
		     "labelText": "",
		     "labelOffset": new GSize(-6, -10)
		  };

	  var marker = new LabeledMarker(point, opts);
        GEvent.addListener(marker, "click", function() {
		
		var maxContentDiv = document.createElement('div');
			maxContentDiv.id='maxContent';
//			maxContentDiv.style.textAlign = 'center';
// 	    maxContentDiv.style.width = '500px';
//	    maxContentDiv.style.height = '300px';
			maxContentDiv.innerHTML = 'Carregando...';
			
		var zoomDiv = document.createElement('div');
			zoomDiv.id='zoom';
//		zoomDiv.style.textAlign = 'center';
 	    zoomDiv.style.width = '470px';
   		zoomDiv.style.height = '260px';
   		zoomDiv.style.border = '1px solid #000';
			zoomDiv.innerHTML = 'Carregando...';
			
		var zoom_maxDiv = document.createElement('div');
			zoom_maxDiv.id='zoom_max';
 	  	    zoom_maxDiv.style.width = '100%';
  	   		zoom_maxDiv.style.height = '100%';
			zoom_maxDiv.innerHTML = 'Carregando...';
  
          // adjust the width so that the info window is large enough for this many tabs
//          if (htmls.length > 2) {
//            htmls[0] = '<div style="width:'+htmls.length*120+'px">' + htmls[0] + '</div>';
              htmls[0] = '<div style="width:500px; height:260px;">' + htmls[0] + '</div>';
//          }
          var tabs = [];
          for (var i=0; i<htmls.length; i++) {
            tabs.push(new GInfoWindowTab(labels[i],htmls[i]));
          }
          tabs.push(new GInfoWindowTab('Zoom',zoomDiv));

        marker.openInfoWindowTabsHtml(tabs);
		  
//          marker.openInfoWindowTabsHtml(tabs,{maxContent: maxContentDiv, maxTitle: "Mais Informações"});

          var iw = map.getInfoWindow();
		  
          GEvent.addListener(iw, "maximizeclick", function() {

		  var id_table = iw.getSelectedTab();
		  
	  
// 	      alert(htmls.length +" = "+ id_table);
		  

	  		  var icon_Zoom = getIcon(["headquarters","headquarters-shadow"]);

			  marker_zoom_opts = {
					"icon": icon_Zoom,
					"title": title	
		      };			  

	          GDownloadUrl("ajax_content.php?id="+id+"&id_table="+id_table, function(data) {
           	  		maxContentDiv.innerHTML = data;					
 
	           });		  
   
      });



  		  var icon_Zoom = getIcon(["headquarters","headquarters-shadow"]);

		  marker_zoom_opts = {
			   "icon": icon_Zoom,
			   "title": title
		  };
		
		var dMapDiv = document.getElementById("zoom");
		var detailMap = new GMap2(dMapDiv);
		var getZoom = map.getZoom();
		var ZoomLevel = 16;



		
		detailMap.addControl(new GSmallMapControl());
		detailMap.setCenter(point , ZoomLevel);
		GEvent.addListener(detailMap, "zoomend", miniMapZoomEnd);
		GEvent.addListener(detailMap, "moveend", miniMapMoveEnd);

		var CopyrightDiv = dMapDiv.firstChild.nextSibling;
		var CopyrightImg = dMapDiv.firstChild.nextSibling.nextSibling;
		CopyrightDiv.style.display = "none"; 
		CopyrightImg.style.display = "none";
		showMinimapRect(detailMap);
		createZoomMarker(detailMap);
//	    var marker_zoom = new LabeledMarker(point, icon_Zoom);
//		    detailMap.addOverlay(marker_zoom);		  
		
/*		
		  mapp = new GMap2(document.getElementById("zoom"));
		  mapp.addControl(new GSmallMapControl());
		  mapp.enableDoubleClickZoom();
		  
		  mapp.setCenter(point, 15);


*/

        });

/*		
        GEvent.addListener(marker, "mouseover", function() {
			marker.setImage('http://gmaps-samples.googlecode.com/svn/trunk/markers/circular/yellowcirclemarker.png');
  });

        GEvent.addListener(marker, "mouseout", function() {
        	marker.setImage('http://gmaps-samples.googlecode.com/svn/trunk/markers/circular/greencirclemarker.png');
  });

        GEvent.addListener(marker, "infowindowclose", function() {        	                
			marker.setImage('http://gmaps-samples.googlecode.com/svn/trunk/markers/circular/greencirclemarker.png');
  });

*/		
		
        return marker;
      }
	  



function markerDragEnd() {
	GEvent.trigger(this,'click');
}

function miniMapZoomEnd(oldZ,newZ) {
	showMinimapRect(this);
}

function miniMapMoveEnd() {
	showMinimapRect(this);
}


function showMinimapRect(detailMap) {
	if (rect) {
		map.removeOverlay(rect);
	}
	var bounds = detailMap.getBounds();
	var polyPoints = [	bounds.getSouthWest(),
						new GLatLng(bounds.getSouthWest().lat(),bounds.getNorthEast().lng()),
						bounds.getNorthEast(),
						new GLatLng(bounds.getNorthEast().lat(),bounds.getSouthWest().lng()),
						bounds.getSouthWest()
					]

	rect = new GPolygon(polyPoints, '#000000', 1, 1, '#999999', 0.5);
	map.addOverlay(rect);

}


function mapIWClose() {
	if (rect) {
		map.removeOverlay(rect);
	}
}


    function toggleGroup(type) {
      for (var i = 0; i < markerGroups[type].length; i++) {
        var marker = markerGroups[type][i];
        if (marker.isHidden()) {
          marker.show();
        } else {
          marker.hide();
        }
      } 
    }

    function toggleLabels() {
      var showLabels = document.getElementById("labelsCheckbox").checked;
      for (groupName in markerGroups) {
        for (var i = 0; i < markerGroups[groupName].length; i++) {
          var marker = markerGroups[groupName][i];
          marker.setLabelVisibility(showLabels);
        }
      }
    }
	

