/**
 * @author Michal Cap
 */

  var map;
  var markers = [];
  var collaborativeMode = false;
  
  function Marker(flabel, lat, lng, citylat, citylng, fvenueId, fteamId, logoUrl, shadowUrl, logoSize, clickTarget)
  {
     this.label = flabel;
     this.pos = null;
     this.teamId = fteamId;
     this.venueId = fvenueId;
     this.approximate = true;
     this.icon = null;       
     this.clickTarget = clickTarget;
     
     var marker = this;       
       
     if (lat != null && lng != null) {
         this.pos = new GLatLng(lat, lng);
         this.approximate = false;
     }
     else if(citylat != null && citylng != null) {
     	   this.pos = new GLatLng(citylat, citylng);
     	   this.approximate = true;      	
     }
     
     // Get the icon image     
     this.icon = new GIcon(G_DEFAULT_ICON);
     
     if (logoUrl !== null) {
       this.icon.image = logoUrl;
        this.icon.shadow	=  shadowUrl;      

        this.icon.iconSize = new GSize(logoSize, logoSize);
        this.icon.shadowSize = new GSize(logoSize*2, logoSize);
        this.icon.iconAnchor = new GPoint(0, logoSize);
     }
  }   
    
  function mapsLoad() {
    if (GBrowserIsCompatible()) {  
      if (document.getElementById("map") != null) {
  			// There is a map container on the page
  			map = new GMap2(document.getElementById("map"));
  			
  			map.addControl(new GSmallMapControl());
  			map.addControl(new GMapTypeControl());
  			map.enableDoubleClickZoom();
  			//map.enableScrollWheelZoom();
  			map.setCenter(new GLatLng(50, 0), 2);			
  			
  			// Get the markers to display - defined on the respective team, match or competition page
  			loadMarkers(markers);
  			resetView();
	    }
    }
  }
    	
  function mapsUnload()
  {
  	GUnload();
  }	    
    
  /* Places markers on the map, assigns viewport */
  function resetView()
  {
  	map.clearOverlays()    	
  	
    // Place the markers on the map
    if (!collaborativeMode)
        setTimeout('addMarkersToMapOnBackground(0)', 500);
    
    // Adjust viewport
    if (markers.length == 1) {
    	if (!markers[0].approximate) {
    		// Single stadium view, exact coordinates, showing whole stadium on the satellite view 
    		map.setCenter(markers[0].pos, 16);
    		map.setMapType(G_SATELLITE_MAP);		
    	} else {      		
    		if (!collaborativeMode) {
          // only approximate city view
          map.setCenter(markers[0].pos, 6);
        }
        else {
          // In the collaborative mode show whole city
          map.setMapType(G_HYBRID_MAP);
          map.setCenter(markers[0].pos, 11);                                      
        }
    	}
    }
    
    if (markers.length >= 2) {            
    	// Compute the viewport that includes all the markers
    	var bounds = new GLatLngBounds();
    	for(var i = 0; i < markers.length; i++) {
    		if (markers[i].pos != null)
    			bounds.extend(markers[i].pos);
    	}
    	
      // Extend the viewport by 10% to be sure that all logos fit into the viewport
      bounds.extend(
          new GLatLng(
                  bounds.getSouthWest().lat() - bounds.toSpan().lat()*0.1,
                  bounds.getSouthWest().lng() - bounds.toSpan().lng()*0.1
              ));
      
      bounds.extend(
          new GLatLng(
                  bounds.getNorthEast().lat() + bounds.toSpan().lat()*0.1,
                  bounds.getNorthEast().lng() + bounds.toSpan().lng()*0.1
              ));        

    	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    	map.setMapType(G_HYBRID_MAP);
    }
    
    // Show the aiming cross in the collaborative mode
    if (collaborativeMode) {
      document.getElementById("map-aiming-cross").style.zIndex = 1000;
    } 	 	
  }
    
  function addMarkerToMap(marker)
  {    	
  	if (marker.pos != null) {
  		// Add to the map
  		// alert(document.getElementById("info-" + marker.venueId + "-general"));
  		var gMarker = new GMarker(marker.pos, {icon:marker.icon})
  		map.addOverlay(gMarker);
  		
  		if (marker.clickTarget != null) {
         GEvent.addListener(gMarker, 'click', function() {
           window.location.href = marker.clickTarget;
         });
       }
  		
    	// Set onClick action	    	   
        /*
          GEvent.addListener(gMarker, "click", function() {
          gMarker.openInfoWindowTabs(
          	[ 
          	  new GInfoWindowTab('General', document.getElementById("info-" + marker.venueId + "-general").cloneNode(true)) ,
          	  new GInfoWindowTab('Results', document.getElementById("info-" + marker.venueId + "-results").cloneNode(true)) ,
          	  new GInfoWindowTab('Fixtures', document.getElementById("info-" + marker.venueId + "-fixtures").cloneNode(true))
          	]	          
          );
        });
        */ 
          
      // Show the aiming cross in the collaborative mode
      if (collaborativeMode) {
        document.getElementById("map-aiming-cross").style.zIndex = 1000;
      }   		 
  	}	     	
  }  
    
  /**
   * Recursively calls itself resulting in slow adding of Markers. 
   * Waits 100ms between adding two markers.
   * 
   * @param int currentIndex
   */
  
  function addMarkersToMapOnBackground(currentIndex)
  {    	
    // If the marker image is not defined, do not display the marker
    if (markers[currentIndex].icon.image != null)
      addMarkerToMap(markers[currentIndex]);
    
    // Schedule adding of the next one
    if (currentIndex+1 < markers.length)
      setTimeout('addMarkersToMapOnBackground(' + (parseInt(currentIndex) + 1) + ')',100);
  } 
  
  
  function submitReportedLocation(venueName, block_id, lat, lng){
    var url = location.href + 'reportStadium/.' + venueName + '/' + lat + '/' + lng + '/';
    alert(url);
    
    new Ajax.Request(url, {
      method: 'post',
      parameters: {block_id: block_id},
      onSuccess: function(transport) {
                 alert('Thank you for your help!\nYour contribution will be processed and added to the database in the next few days.');            
      }
    });               
  }
      
