/**
 * The MarkerClusterer object.
 * @type {MarkerCluster}
 */
var mc = null;
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
/**
 * Marker Clusterer display/hide flag.
 * @type {boolean}
 */
var showMarketClusterer = false;

/**
 * Toggles Marker Clusterer visibility.
 */
function toggleMarkerClusterer() {
  showMarketClusterer = !showMarketClusterer;
  if (showMarketClusterer) {
    if (mc) {
      mc.addMarkers(markers.locations);
    } else {
      mc = new MarkerClusterer(map, markers.locations, {maxZoom: 19});
    }
  } else {
    mc.clearMarkers();
  }
}

function nads(lat, lng) {
    doNadsAdd(lat, lng);
    return ''
}
// Client function that calls a server rpc and provides a callback
function doNadsAdd(lat, lng) {
    server.Add(lat, lng, onNadsAddSuccess);
}
// Callback for after a successful doAdd
function onNadsAddSuccess(response) {
    document.getElementById("nadsResponse").innerHTML = ' (' + response + ')';
}
//
// As mentioned at http://en.wikipedia.org/wiki/XMLHttpRequest
//
if (!window.XMLHttpRequest)
    XMLHttpRequest = function() {
    try {
        return new ActiveXObject("Msxml2.XMLHTTP.6.0")
        } catch(e) {}
    try {
        return new ActiveXObject("Msxml2.XMLHTTP.3.0")
        } catch(e) {}
    try {
        return new ActiveXObject("Msxml2.XMLHTTP")
        } catch(e) {}
    try {
        return new ActiveXObject("Microsoft.XMLHTTP")
        } catch(e) {}
    throw new Error("Could not find an XMLHttpRequest alternative.")
    };
//
// Makes an AJAX request to a local server function w/ optional arguments
//
// functionName: the name of the server's AJAX function to call
// opt_argv: an Array of arguments for the AJAX function
//
function Request(function_name, opt_argv) {
    if (!opt_argv)
        opt_argv = new Array();
    // Find if the last arg is a callback function; save it
    var callback = null;
    var len = opt_argv.length;
    if (len > 0 && typeof opt_argv[len - 1] == 'function') {
        callback = opt_argv[len - 1];
        opt_argv.length--;
    }
    var async = (callback != null);
    // Encode the arguments in to a URI
    var query = 'action=' + encodeURIComponent(function_name);
    for (var i = 0; i < opt_argv.length; i++) {
        var key = 'arg' + i;
        var val = JSON.stringify(opt_argv[i]);
        query += '&' + key + '=' + encodeURIComponent(val);
    }
    query += '&time=' + new Date().getTime();
    // IE cache workaround
    // Create an XMLHttpRequest 'GET' request w/ an optional callback handler 
    var req = new XMLHttpRequest();
    req.open('GET', '/rpc?' + query, async);
    if (async) {
        req.onreadystatechange = function() {
            if (req.readyState == 4 && req.status == 200) {
                var response = null;
                try {
                    response = JSON.parse(req.responseText);
                } catch(e) {
                    response = req.responseText;
                }
                callback(response);
            }
        }
    }
    // Make the actual request
    req.send(null);
}
// Adds a stub function that will pass the arguments to the AJAX call 
function InstallFunction(obj, functionName) {
    obj[functionName] = function() {
        Request(functionName, arguments);
    }
}


    // Server object that will contain the callable methods
    var server = {};
    // Insert 'Add' as the name of a callable method
    InstallFunction(server, 'Add');
    // Handy "macro"
    function $(id){
      return document.getElementById(id);
    }
    // Client function that calls a server rpc and provides a callback
    function doAdd() {
      server.Add($('num1').value, $('num2').value, onAddSuccess);
    }
    // Callback for after a successful doAdd
    function onAddSuccess(response) {
      $('result').value = response;
    }

var address;

var initialLocation;
//var siberia = new google.maps.LatLng(60, 105);
//var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
var map;
var infowindow = new google.maps.InfoWindow();
var adUnit;

// Create an object containing LatLng, population.
var citymap = {};
citymap['chicago'] = {
    center: new google.maps.LatLng(41.878113, -87.629798),
    population: 2842518
};
citymap['newyork'] = {
    center: new google.maps.LatLng(40.714352, -74.005973),
    population: 8143197
};
citymap['losangeles'] = {
    center: new google.maps.LatLng(34.052234, -118.243684),
    population: 3844829
}

//var delhi = new google.maps.LatLng((28.6667,77.2167);

var cityCircle;

var geocoder;
var address;

function initialize() {
    var stylez = [{
        featureType: "road",
        elementType: "geometry",
        stylers: [{
            hue: "#00ff00"
        }, {
            saturation: 100
        }]
    }, {
        featureType: "landscape",
        elementType: "geometry",
        stylers: [{
            hue: "#000000"
        }, {
            saturation: 75
        }, {
            lightness: -100
        }]
    }];
    var darkStyle = [{
        featureType: "administrative.country",
        elementType: "geometry",
        stylers: [{
            hue: "#ffee00"
        }, {
            saturation: 40
        }, ]

    },


    {
        featureType: "landscape",
        elementType: "labels",
        stylers: [{
            invert_lightness: true
        }]

    },

    {
        featureType: "water",
        elementType: "labels",
        stylers: [{
            hue: "#9b95dd"
        }, {
            saturation: 50
        }, {
            lightness: -10
        }, {
            gamma: 0.9
        }]
    },

    {
        featureType: "water",
        elementType: "geometry",
        stylers: [{
            visibility: "on"
        }, {
            saturation: 40
        }, {
            lightness: -92
        }]
    }, {
        featureType: "landscape",
        elementType: "all",
        stylers: [{
            hue: "#6d8f39"
        }, {
            saturation: 50
        }, {
            lightness: -45
        }, {
            gamma: 0.9
        },

        {
            featureType: "administrative.locality",
            elementType: "labels",
            stylers: [{
                hue: "#0022ff"
            }, {
                saturation: 50
            }, {
                lightness: -10
            }, {
                gamma: 0.9
            }]
        }

        ]
    }, {
        featureType: "road",
        elementType: "geometry",
        stylers: [{
            hue: "#00ff00"
        }, {
            saturation: 100
        }]
    }, {
        featureType: "landscape",
        elementType: "geometry",
        stylers: [{
            hue: "#6d8f39"
        }, {
            saturation: 75
        }, {
            lightness: -45
        }]
    }];
    var mapOptions = {
        zoom: 4,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        // center: newyork,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
            mapTypeIds: ['Dark', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN, "relief"]
        },
    };

    var reliefMap = new google.maps.ImageMapType({
        getTileUrl: function (a, b) {
            return "http://maps-for-free.com/layer/relief/z" + b + "/row" + a.y + "/" + b + "_" + a.x + "-" + a.y + ".jpg";
        },
        tileSize: new google.maps.Size(256, 256),
        isPng: false,
        minZoom: 0,
        maxZoom: 11,
        name: "Relief",
        alt: "Relief layer"
    });

    map = new google.maps.Map(document.getElementById("gmap"), mapOptions);

    var adUnitDiv = document.createElement('div');
    var adUnitOptions = {
        format: google.maps.adsense.AdFormat.HALF_BANNER,
        position: google.maps.ControlPosition.TOP,
        map: map,
        visible: true,
        publisherId: 'pub-7211665888260307'
    }
    adUnit = new google.maps.adsense.AdUnit(adUnitDiv, adUnitOptions);

    var styledMapOptions = {
        name: "Dark"
    }

    var darkMapType = new google.maps.StyledMapType(
    darkStyle, styledMapOptions);
    map.mapTypes.set('Dark', darkMapType);
    map.mapTypes.set("relief", reliefMap); 

    var mapdiv = document.getElementById("gmap");
    geocoder = new google.maps.Geocoder();

    var ctaLayer = new google.maps.KmlLayer('http://montaoproject.appspot.com/kmlfile/4468185');

    ctaLayer.setMap(map);
google.maps.event.addListener(map, "click", gAdd);
    // Try W3C Geolocation method (Preferred)
    if (navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function (position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

            var latlng = initialLocation
            geocoder.geocode({
                'latLng': latlng
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        marker = new google.maps.Marker({
                            position: latlng,
                            map: map
                        });
                        infowindow.setContent('<a href="/li?lat=' + latlng.lat() + '&lon=' + latlng.lng() + '">' + results[1].formatted_address + '</a>');
                        infowindow.open(map, marker);
                    } else {
                        alert("No results found");
                    }
                } else {
                    alert("Geocoder failed due to: " + status);
                }
            });

        }, function () {
            handleNoGeolocation(browserSupportFlag);
        });
    } else if (google.gears) {
        // Try Google Gears Geolocation
        browserSupportFlag = true;
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function (position) {
            initialLocation = new google.maps.LatLng(position.latitude, position.longitude);
            //contentString = "Location found using Google Gears";

            var latlng = initialLocation
            geocoder.geocode({
                'latLng': latlng
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        //map.setZoom(11);
                        marker = new google.maps.Marker({
                            position: latlng,
                            map: map
                        });
                        infowindow.setContent('<a href="/li?lat=' + latlng.lat() + '&lon=' + latlng.lng() + '">' + results[1].formatted_address + '</a>');
                        infowindow.open(map, marker);
                    } else {
                        alert("No results found");
                    }
                } else {
                    alert("Geocoder failed due to: " + status);
                }
            });


        }, function () {
            handleNoGeolocation(browserSupportFlag);
        });
    } else {
        // Browser doesn't support Geolocation
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
    }
}

function placeMarker(location) {
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
    map.setCenter(location);
    var latlng = location
    geocoder.geocode({
        'latLng': latlng
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                marker = new google.maps.Marker({
                    position: latlng,
                    map: map
                });
                infowindow.setContent('<a href="/li?lat=' + latlng.lat() + '&lon=' + latlng.lng() + '">' + results[1].formatted_address + '</a>');
                infowindow.open(map, marker);
            } else {
                alert("No results found");
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
}


function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
        initialLocation = newyork;
        contentString = "Error: The Geolocation service failed.";
    } else {
        initialLocation = siberia;
        contentString = "Error: Your browser doesn't support geolocation. Are you in Siberia?";
    }
    map.setCenter(initialLocation);
    infowindow.setContent(contentString);
    infowindow.setPosition(initialLocation);
    infowindow.open(map);
}


function gAdd(ev) {
    marker.setMap(null)
    var latlng = new google.maps.LatLng(ev.latLng.lat(), ev.latLng.lng());

    geocoder.geocode({
        'latLng': latlng
    }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            //document.getElementById("message").innerHTML = results[1].formatted_address;
            //document.upload.place.value = results[5].formatted_address
            //document.upload.lat.value = latlng.lat();
            //document.upload.lng.value = latlng.lng();
            marker = new google.maps.Marker({
                position: latlng,
                //draggable:true,
                //animation: google.maps.Animation.DROP,
                map: map
            });
            //google.maps.event.addListener(marker, 'click', toggleBounce);
            infowindow.setContent('<a href="/li?lat=' + latlng.lat() + '&lon=' + latlng.lng() + '">' + results[1].formatted_address + '</a>');
            infowindow.open(map, marker);

        } else {

        }
    });

}

