function main ()
{
	initialize();
}

function initialize() {
     geocoder = new google.maps.Geocoder();
     infowindow = new google.maps.InfoWindow();
}

var map = null;
var geocoder = null;
var infowindow;


function centerMap_(map, lat, lon)
{
        var coords = new google.maps.LatLng(lat,lon);
        map.setCenter(coords);
}

function createMap(el, lat, lon, zoom)
{
        if (zoom == null) zoom = 10;

        var coords = new google.maps.LatLng(lat,lon);
        var myOptions = {
          zoomControl: true,
          zoomControlOptions: {
             style: google.maps.ZoomControlStyle.SMALL
          },
          
          zoom: zoom,
          center: coords,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        return new google.maps.Map(el, myOptions);
}

// Plot a normal pointer on the map
function plotPoint(map, lat, lon, title, info, markerSrc)
{
        var coords = new google.maps.LatLng(lat,lon);

        var image;
        if (markerSrc == undefined)
            image = '../images/icons/marker.png';
        else
            image = '../' + markerSrc;
        
        var marker = new google.maps.Marker({
            position: coords,
            map: map,
            title: title,
            icon: image
        });
        
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setOptions({content: info, position: coords});
          infowindow.open(map,marker);
        });

        return marker;
}

// Plot a small pointer on the map (for maps with many gyms)
function plotDot(map, lat, lon, title, hasMorePage)
{
       var coords = new google.maps.LatLng(lat,lon);
       var img = hasMorePage ? "../images/small_marker_special.png" : "../images/small_marker.png";

       var marker = new google.maps.Marker({
           position: coords,
           map: map,
           title: title,
           icon: img
       });
       
       return marker;
}


function getCoordsFromAddress() {

    var address = $("input_address").value;
    city = address.split(", ")[1];
    if (!city && $("input_city").value) { 
        address += ", " + $("input_city").value;
        $("input_address").value = address;
    }
    geocoder.geocode( {'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var loc = results[0].geometry.location;
        $("input_coordinates").value = loc.lat() + ", " + loc.lng();
      } else {
        // alert("Koordinater hittades inte.");
      }
    });
}
	  
function functionExists(functionName)
{
    if(typeof functionName == 'function')
        return true;
    else
        return false;

}

// Not used/completed:
var locationOutputElement;
function locate(outputElementId) {
    //Check if browser supports W3C Geolocation API

    locationOutputElement = $(outputElementId);
    if (!locationOutputElement) return;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(successFunctionW3C, errorFunctionW3C);
    } else {
        locateFromAjax();
    }
}

function locateFromAjax()
{
    var req = new Request({
		method: 'get',
		url: 'ajax/localize.php',
		data: {'rnd' : Math.random()},
		onRequest: function() {},
		onComplete: function(response)
			{
                if (response == "error") localizationError();
                coords = response.split(", ");
                localizationSuccess(coords[0], coords[1]);
			}

	});

	req.send();
}

function successFunctionW3C(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    localizationSuccess(lat, lon);
}

function errorFunctionW3C(position) {
    locateFromAjax();
}

function localizationSuccess(lat, lon)
{
    locationOutputElement.setAttribute("value",lat + ", " + lon);
}

function localizationError()
{
    locationOutputElement.setAttribute("value","Error");
}

// Get entries (for the current state) for a specific area
function getEntriesForBounds(bounds){
    var ne = bounds.getNorthEast();
    var sw = bounds.getSouthWest();
    var req = new Request({
		method: 'get',
		url: '../ajax/json.php',
		data: {'state' : 'ggMain','neLat' : ne.lat(), 'neLon' : ne.lng(), 'swLat' : sw.lat(), 'swLon' : sw.lng(), 'rand': Math.random()},
		onRequest: function() { },
		onComplete: function(response) { receiveEntries(response, false)}
	});
	req.send();
    //alert('localhost/gg/ajax/json.php?state=ggMain'+'&neLat=' + ne.lat() + '&neLon=' + ne.lng() + '&swLat=' + sw.lat() + '&swLon=' + sw.lng() + '&rand='+ Math.random())
}

// Get all entries for the current state, and centers the map on the result
function getEntries() {
    var req = new Request({
		method: 'get',
		url: '../ajax/json.php',
		data: {'state' : 'ggMain'},
		onRequest: function() { },
		onComplete: function(response) { receiveEntries(response, true)}
	});
	req.send();
}

function receiveEntries(response, centerAtResults) {
    var o = (JSON.parse(response));
    //alert("Number of queries: " + el.numberOfQueries); // (Debugging)
    var count = 0;
    for( var i in o.entries ) {
        count++;
    }
    //alert (count);
    plotEntries(o.entries, o.renderAsDots);
    parent.document.getElementById("visible_on_map").innerHTML = "<br />(" + count + ")";
    if (centerAtResults) {
        if (o.showLocation) {
            setCenter(o.showLat, o.showLon, 11);
        } else {
            if (o.neLat && o.neLon && o.swLat && o.swLon)
                setCenterBound(o.neLat, o.neLon, o.swLat, o.swLon);
        }
        
    }
    
    
}

function updateMap() {
    top.frames['mapFrame'].updateMap(true);
}


function FullScreenControl(map) {
    this.map = map;
    
    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map

    // Set CSS for the control border
    var controlUI = document.createElement('DIV');
    controlUI.style.margin = '15px';
    controlUI.style.backgroundColor = 'white';
    controlUI.style.borderStyle = 'solid';
    controlUI.style.borderWidth = '2px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    //controlDiv.appendChild(controlUI);

    // Set CSS for the control interior
    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    controlText.style.paddingLeft = '4px';
    controlText.style.paddingRight = '4px';
    controlText.innerHTML = '<b>Fullskärm</b>';
    controlUI.appendChild(controlText);
      
      
    this.draggableState = 0;
    this.fullScreenMode = false;

    // Setup the click event listeners: simply set the map to
    google.maps.event.addDomListener(controlUI, 'click', function() {
        mapContainer = parent.document.getElementById("mapFrame");
        searchField = parent.document.getElementById("searchWords");
        filterContainer = parent.document.getElementById("filters");
        if (this.fullScreenMode) {
            filterContainer.setAttribute("class","");
            searchField.removeClass("fullScreen");
            mapContainer.setAttribute("class","");
            //mapContainer.removeClass("fullScreen");   Doesn't work in msie
            this.fullScreenMode = false;
        } else {
            filterContainer.setAttribute("class","fullScreen");
            searchField.addClass("fullScreen");
            mapContainer.setAttribute("class","fullScreen");
            //mapContainer.addClass("fullScreen");      Doesn't work in msie
            this.fullScreenMode = true;
        }

        
    });
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlUI);
}

main();

