var map = null;                     // obiekt mapy
var geocoder = null;                // obiekt geokodera
var directions = null;              // obiekt do tworzenia tras
var bounds = new GLatLngBounds();   // obiekt do tworzenia ram mapy
var waypoints = [];

/**
 * Inicjalizacja mapy
 */
function initializeGM(mapDivId, directionDivId) {

    // sprawdzenie kompatybilnosci przegladarki
    if (GBrowserIsCompatible()) {
    
        // zaladowanie mapy do DIV-a
        map = new GMap2(document.getElementById(mapDivId));
        // dodanie obiektu geokodera
        geocoder = new GClientGeocoder();
        
        // dodanie kontrolek sterowania
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        // dodanie pluginu Google Earth
        map.addMapType(G_SATELLITE_3D_MAP);
        map.setMapType(G_SATELLITE_MAP);
        //map.addControl(new GScaleControl());
        scalePosition = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5,35)); 
        scaleControl = new GScaleControl(); 
        map.addControl(scaleControl, scalePosition); 
        
        // ustawienie punktu poczatkowego
        map.setCenter(new GLatLng(0, 0), 0);

        // stworzenie obiektu do tworzenia tras
        directions = new GDirections(map, document.getElementById(directionDivId));
        // utworzenie trasy
        //var arrLocation = new Array(2);
        //arrLocation[0] = sourceLocation;
        //arrLocation[1] = esurfLocation;

        // clear the mapa nd directions of any old information
        //directions.clear();

        // load the map and directions from the specified waypoints
        //directions.loadFromWaypoints(arrLocation);
        bounds = new GLatLngBounds();
    }
}

/**
 * Funkcja pozwalajaca na tworzenie roznych ikonek w zaleznosci od przekazanego
 * parametru.
 */
function createIcon(param)
{
    if (param == 'esurf') {
        icon = new GIcon();
        icon.image = "logo_esurf_100.jpg";
        icon.iconSize = new GSize(40, 28);
        icon.shadowSize = new GSize(36, 34);
        icon.iconAnchor = new GPoint(5, 34);
        icon.infoWindowAnchor = new GPoint(5, 2);
    } else {
	    //icon = new GIcon();
	    //icon.image = "Zachód słońca.jpg";
	    //icon.iconSize = new GSize(40, 28);
	    //icon.shadowSize = new GSize(36, 34);
	    //icon.iconAnchor = new GPoint(5, 34);
	    //icon.infoWindowAnchor = new GPoint(5, 2);
    }
    return icon;
}

/**
 * Funkcja pozwalajaca na zaladowanie punktow przy pomocy AJAX z podanego
 * pliku PHP.
 */
function readMap(param, description)
{
    // ustawienie adresu odwolania AJAX
    var url = "markers.php?qs=" + param + '&desc=' + description;
    var request = GXmlHttp.create();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
	    if (request.readyState == 4) {
	        var xmlDoc = request.responseXML;
	        
	        // pobranie listy elementow do umieszczenia na mapie
	        var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	      
	        // ukrywanie informacji o usuwanych punktach, aby nie byly dalej wyswietlane po usunieciu
	        map.getInfoWindow().hide();
	      
	        map.clearOverlays();
	      
	        // wyczyszczenie tablicy punktow
	        gmarkers = [];
	            
	        for (var i = 0; i < markers.length; i++) {
	            // pobranie atrybutow dla kazdego z punktow
	            var lat = parseFloat(markers[i].getAttribute("lat"));
	            var lng = parseFloat(markers[i].getAttribute("lng"));
	            var point = new GLatLng(lat, lng);
	            var html = markers[i].getAttribute("html");

	            // utworzenie ikonki
	            //icon = createIcon(param);            
	            // utworzenie punktu
	            var marker = createMarker(point, html);//, icon);
	            map.addOverlay(marker);
	            
	            // pobranie lokalizacji punktu
	            latlng = marker.getLatLng();
	            bounds.extend(latlng);
	        }
	    }
	    
	    // wysrodkowanie mapy na dodanych punktach
	    map.setZoom(map.getBoundsZoomLevel(bounds));
        map.setCenter(bounds.getCenter());
        currentZoom = map.getZoom();        
        map.setZoom(currentZoom - 1);
    }
    request.send(null);
}

/**
 * Tworzenie nowego punktu na mapie
 */
function createMarker(point, html, icon) {
	var defaultIcon = new GIcon(G_DEFAULT_ICON);
	
	defaultIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
	
	if(icon == 'spot') {
		//defaultIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png";
		defaultIcon.image = "http://www.surfing-guide.com/images/googlemaps/spotmiejscowosc.png";
		defaultIcon.iconSize = new GSize(25, 25);
		defaultIcon.shadow = "";
		defaultIcon.iconAnchor = new GPoint(10, 15);
    } else if(icon == 'airport') {        
        defaultIcon.image = "http://www.surfing-guide.com/images/googlemaps/lotnisko.png";
        defaultIcon.iconSize = new GSize(25, 25);
        defaultIcon.shadow = "";
        defaultIcon.iconAnchor = new GPoint(10, 15);
    } else if(icon == 'place_of_interest') {        
        defaultIcon.image = "http://www.surfing-guide.com/images/googlemaps/ciekawemiejsce.png";
        defaultIcon.iconSize = new GSize(25, 25);
        defaultIcon.shadow = "";
        defaultIcon.iconAnchor = new GPoint(10, 15);
    } else if(icon == 'surfing_place') {        
        defaultIcon.image = "http://www.surfing-guide.com/images/googlemaps/spotsurf.png";
        defaultIcon.iconSize = new GSize(25, 25);
        defaultIcon.shadow = "";
        defaultIcon.iconAnchor = new GPoint(10, 15);
	} else if(icon == 'orange') {
		defaultIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/orange-dot.png";
	} else if(icon == 'hotel') {
		//defaultIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png";
		defaultIcon.image = "http://www.surfing-guide.com/images/googlemaps/hotel.png";
        defaultIcon.iconSize = new GSize(25, 25);
        defaultIcon.shadow = "";
        defaultIcon.iconAnchor = new GPoint(10, 15);
    } else if(icon == 'bazawind') {
        //defaultIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png";
        defaultIcon.image = "http://www.surfing-guide.com/images/googlemaps/bazawindsurfing.png";
        defaultIcon.iconSize = new GSize(25, 25);
        defaultIcon.shadow = "";
        defaultIcon.iconAnchor = new GPoint(10, 15);
    } else if(icon == 'bazakite') {
        //defaultIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png";
        defaultIcon.image = "http://www.surfing-guide.com/images/googlemaps/bazakite.png";
        defaultIcon.iconSize = new GSize(25, 25);
        defaultIcon.shadow = "";
        defaultIcon.iconAnchor = new GPoint(10, 15);
    } else if(icon == 'bazawindkite') {
        defaultIcon.image = "http://www.surfing-guide.com/images/googlemaps/bazawindkite.png";
        defaultIcon.iconSize = new GSize(49, 25);
        defaultIcon.shadow = "";
        defaultIcon.iconAnchor = new GPoint(10, 15);
	} else if(icon == 'green') {
		defaultIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png";
	}

    //defaultIcon.iconSize = new GSize(20, 32);
    //defaultIcon.shadowSize = new GSize(32, 32);  
	markerOptions = { icon:defaultIcon };


    var marker = new GMarker(point, markerOptions);
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(html);
      
      if($("#google_route").attr("checked"))
      {
	      waypoints.splice(waypoints.length, 0, this);
	      if(waypoints.length > 1)
	      	directions.loadFromWaypoints([waypoints[waypoints.length-2].getPoint(), waypoints[waypoints.length-1].getPoint()], {getPolyline:true});
	  }
      //alert(this.getLatLng().lat());
    });
    return marker;
  }



/**
 * Wyszukiwanie punktu na mapie po adresie
 */
function showAddress(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          map.setCenter(point, 13);
          //var marker = new GMarker(point);
          //map.addOverlay(marker);
          //marker.openInfoWindowHtml('<p class="gmap_popup">' + address + '</p>');
          
          // stworzenie obiektu do tworzenia tras
        var directions = new GDirections(map, document.getElementById("directions_canvas"));
        // utworzenie trasy
        var arrLocation = new Array(2);
        esurfLocation = new GLatLng(52.41017, 16.910642);
        arrLocation[0] = point;
        arrLocation[1] = esurfLocation;

        // clear the mapa nd directions of any old information
        directions.clear();

        // load the map and directions from the specified waypoints
        directions.loadFromWaypoints(arrLocation);
        }
      }
    );
  }
}

/**
 * Tworzenie trasy
 */
function createRoute(sourceAddress) {
    var sourceLocation = '';
    var esurfLocation = new GLatLng(52.41017, 16.910642);
    if (geocoder) {
        // pobranie lokalizacji zrodla
        geocoder.getLatLng(
            sourceAddress,
            function(point) {
                if (!point) {
                    alert(sourceAddress + " - nie znaleziono!");
                } else {
                    map.setCenter(point, 13);
                    sourceLocation = point;
                    var marker = new GMarker(sourceLocation);
                    map.addOverlay(marker);
                }
            }
        );
    }
}