
/**
* get source of json object 
*
* @param  json object
* @return string
*/
function getJsonSource(obj) {

    var output = [], temp;
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            temp = i + ":";
            switch (typeof obj[i]) {
                case "object" :
                    temp += getJsonSource(obj[i]);
                    break;
                case "string" :
                    temp += "\"" + obj[i] + "\"";    // add in some code to escape quotes
                    break;
                default :
                    temp += obj[i];
            }
            output.push(temp);
        }
    }
    return "{" + output.join() + "}";
}

/**
* setDistanceFilter() is called when the geocoder returns an answer.
* It changes values of some form elements.
*
* @param  json object
* @return string
*/ 
function setDistanceFilter(response) {
        
    if (!response || response.Status.code != 200) {

        // use deafult values for where filter
        $('address_filter').value = whereDefaultParam;
        $('search_distance_filter').value = '3';
      
    } else {
        
        // Address details
        place = response.Placemark[0];

        switch(place.AddressDetails.Accuracy) {
            case 9:
            case 8:
            case 7:
            case 6:
            case 5:
              if (place.AddressDetails.Country.CountryNameCode == 'CH' || place.AddressDetails.Country.CountryNameCode == 'DE') {
                  $('search_distance_filter').value = '1';
              } else {
                  $('search_distance_filter').value = '5';
              }
              
              break;
            
            case 4:
              if (place.AddressDetails.Country.CountryNameCode == 'CH' || place.AddressDetails.Country.CountryNameCode == 'DE') {
                  $('search_distance_filter').value = '2';
              } else {
                  $('search_distance_filter').value = '5';
              }
              break;
            
            case 3:
              if (place.AddressDetails.Country.CountryNameCode == 'CH' || place.AddressDetails.Country.CountryNameCode == 'DE') {
                  $('search_distance_filter').value = '3';
              } else {
                  $('search_distance_filter').value = '5';
              }

              break;
            case 2:
              if (place.AddressDetails.Country.CountryNameCode == 'CH' || place.AddressDetails.Country.CountryNameCode == 'DE') {
                  $('search_distance_filter').value = '4';
              } else {
                  $('search_distance_filter').value = '5';
              }
              break;
            default:
              $('search_distance_filter').value = '5';
        }
           
        $('address_filter').value = response.name;
        
        // This parameter is used to search users on class functin usersData()
        var jsonSource = getJsonSource(response);
        $('placemark').value = jsonSource;

    }
}

/**
* It geocodes the address entered into the form
* and set center of the map at that location.
*
* @param  string address
* @param  string whereDefault
*/ 
function findLocation(address, whereDefault) {
    whereDefaultParam = whereDefault;
    
    var geocoder = new GClientGeocoder();
    
    // This part is not included in the stable google version  
    var sw = new GLatLng(34.88, -14.52); // south-west
    var ne = new GLatLng(62.43, 42.71);  // north-east
      
    geocoder.setViewport(new GLatLngBounds(sw, ne));      
    geocoder.setBaseCountryCode('ch');

    geocoder.getLocations(address, setDistanceFilter);
}


/**
* draw circle on center of map
*
*/ 
function drawCircle(center, radius, color, thickness, opacity) {

	  var circleQuality = 1;			//1 is best but more points, 5 looks pretty good, too
	  var M = Math.PI / 180;			//Create Radian conversion constant
	  var L = map.getBounds();		//Holds copy of map bounds for use below
	  var sw = L.getSouthWest();
	  var ne = L.getNorthEast();

	  // The map is not completely square so this calculates the lat/lon ratio
  	// this works because we create a square map
	  var circleSquish = (ne.lng() - sw.lng()) / (ne.lat() - sw.lat());

	  var points = [];//Init Point Array
	  
    // Loop through all degrees from 0 to 360
	  for(var i=0; i<360; i+=circleQuality){
		    var P = new GLatLng(
		  	    center.lat() + (radius * Math.sin(i * M)),
			      center.lng() + (radius * Math.cos(i * M)) * circleSquish
			  );
		    points.push(P);
	  }
	  
    // close the circle
    points.push(points[0]);
    
    if (circle) {
        map.removeOverlay(circle);
    }	
	  circle = new GPolyline(points, color, thickness, opacity);
  
  	map.addOverlay(circle);
  	oldPoly.push(circle);
}
    

/**
* add markers to the map
*
*/ 
function setupProfileMarkers() {
  
    var mgr = new MarkerManager(map); 
    
    if (json == null) return;
    
    mgr.addMarkers(getProfileMarkers(), 0);
  
    mgr.refresh();
} 

/**
* add markers to the map
*
* @return array
*/
function getProfileMarkers() {
    var batch = [];

		for (var i=0; i<json.length; i++) {

        marker = createMarker(i);

			  batch.push(marker);
		}

    return batch;
}

/**
* Creates a marker whose info window displays user data corresponding
* to the given index.
*
* @param  int i
* @return marker
*/
function createMarker(i) {

    var flagicon = new GIcon(G_DEFAULT_ICON);
    if (json[i].icon != null) {
        flagicon.image = 'http://maps.google.com/mapfiles/ms/micons/' + json[i].icon;
    } else {
        flagicon.image = 'http://maps.google.com/mapfiles/ms/micons/' + markerIcon;
    }
    flagicon.iconSize = new GSize(35, 35);
    flagicon.iconAnchor = new GPoint(6, 20);
    flagicon.infoWindowAnchor = new GPoint(5, 1);
    
    // Set up our GMarkerOptions object
    markerOptions = { icon:flagicon };

    var marker = new GMarker(new GLatLng(json[i].lat, json[i].lon), markerOptions);
                             // info window
                             GEvent.addListener(marker, "mouseover", function() {   
                               marker.openInfoWindowHtml(jsonProfileInfoWindowHtml[i].html); 
                             }); 
    return marker;
}


/**
* Display center of map to the given address and draw a circle
*
* @param  string address
* @return int zoom (map zoom level)
*/
function showAddress(address, zoom) {
    if (geocoder) {
        geocoder.getLatLng(address, function(point) {
                                      map.setCenter(point, zoom);
                                      drawCircle(map.getCenter(), (16 / Math.pow(2, zoom)), '#C72A26', 2, 0.8);
                                    });
    }
}

