if (typeof(google) != 'undefined') {
google.load('maps' , '2');
google.load('search' , '1');
}
(function($) {
       
    $(document).ready(function() {

        /* Maps */
        if (typeof(google) != 'undefined') {
        
        $('.location-map').each(function() {
            var container = $(this);
            var address = container.find(':input.address').val();
            var key = container.find(':input.key').val();
            var geocoder = new GClientGeocoder();
            geocoder.getLocations(
                address,
                function(response) {
                    var place = response.Placemark[0];
                    var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                    var url = 'http://maps.google.com/staticmap?center=' + place.Point.coordinates[1] + ',' + place.Point.coordinates[0] + 
                        '&markers=' + place.Point.coordinates[1] + ',' + place.Point.coordinates[0] + ',blue&zoom=13&size=500x300&key=' + key;
                    
                    container.find('img')
                        .attr('src', url);
                    
                }
            );
            
        });
       $('.map-container').each(function() {
            var container = $(this);
            var query = container.attr('title');
            var mapElement = container.find('.map')[0];
            
            var map = new GMap2(mapElement);
            map.setCenter(new GLatLng(37.4419, -122.1419), 13);
           // map.setUIToDefault();
            
            var directionsPanel = container.find('.directions');
            var geocoder = new GClientGeocoder();
            geocoder.getLocations(
              query,
              function(response) {
                if (response.Placemark == undefined || response.Placemark.length == 0) {
                    return;
                }
                var place = response.Placemark[0];
                var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                
                map.setCenter(point, 13);
                var blueIcon = new GIcon(G_DEFAULT_ICON);
                blueIcon.image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';
                blueIcon.iconSize = new GSize(32,32);
                var marker = new GMarker(point, {
                    icon: blueIcon 
                });
                map.addOverlay(marker);
                marker.openInfoWindowHtml(place.address);
              });
            
            if (directionsPanel.length == 1) {
                var directions;
                
                var directionsContainer = container.find('.directions-container form').submit(function() {
                    if (directions) {
                        directions.clear();
                    }
                    map.clearOverlays();
                    directions = new GDirections(map, directionsPanel[0]);
                    directions.load('from: ' + $(this).find(':input[name=from]').val() + ' to: ' + query);
                   return false; 
                });
                
                container.find('.directions-container form :input[name=from]').each(function() {
                    if ($(this).val().length > 0) {
                        $(this).closest('form').submit();
                    }
                });
            } else if (container.find('.results').length == 1) {
                  // ...and add a couple of controls.
                map.addControl(new google.maps.SmallMapControl()); // Add a small map control
                map.addControl(new google.maps.MapTypeControl()); // Add the map type control
                
               /*
                $('form.gsc-search-box').hide();
                $('.gsc-resultsHeader tr:first').hide();
                */
                

                 // Set the map's center point and finish!
                 map.setCenter(new google.maps.LatLng(37.443915 , -122.163610), 11);
               
                 // Execute an initial search

                 var q = container.find(':input.keywords').val();
                 //var GoogleMapsApiKey = 'ABQIAAAA_gfPAAqdgsT43Q86_ZXB5BSAJWr1u41h1StZbPhRcS_N17usVBRPLOItdZQHq4cDSGqQN7P3zS_yzg';
                 var url = 'http://ajax.googleapis.com/ajax/services/search/local?callback=?';
                 var params = {
                    v: '1.0',
                    key: GoogleMapsApiKey,
                    rsz: 8,
                    start: 0,
                    hl: 'en',
                    near: query,
                    q: q
                 };
                 
                 var exclusionsString = container.find(':input.eliminations').val();
                 var exclusions = prepareExclusions(exclusionsString);

                 getPlacesFullList(url, params, exclusions, [], function(places, viewport) {
                        addPlacesToList(container, places);
                        addPlacesToMap(map, places);
                        adjustMapPosition(map, viewport);                 
                 });
            }
       });
        }
    });
    
    function prepareExclusions(exclusionsString) {
        var exclusions = []; 
        
        if ($.trim(exclusionsString).length = 0)
            return exclusions;        
        
        $.each(exclusionsString.split(','), function() {
           if ($.trim(this).length > 0)
		exclusions.push(new RegExp($.trim(this), 'i'));
        });
        
        return exclusions;                     
    }
    
    function isPlaceInExclusions(title, exclusions) {
	for(var index = 0; index < exclusions.length; index++) {
            if (exclusions[index].test(title))
		return true;
        };

        return false;
    }
    
    function getPlacesFullList(url, params, exclusions, places, onSuccess) {
         $.getJSON(url, params, function(response) {
            // Process exclusions
            $.each(response.responseData.results, function() {
		if (!isPlaceInExclusions(this.titleNoFormatting, exclusions))
                   places.push(this);    
            });

            /*    
            var ResultsCount = 10;
            if (places.length < ResultsCount && isNextResultsPageExists(params, response)) {
                // Define next page start
                params.start = params.start + params.rsz;
                getPlacesFullList(url, params, exclusions, places, onSuccess); 
            } else {
                // Show top ResultsCount results
                onSuccess(places.length > ResultsCount ? places.slice(0, ResultsCount) : places);
            }
            */
            
            // Show results
            onSuccess(places, response.responseData.viewport);
         });    
    }
    
    function isNextResultsPageExists(params, response) {
        var nextStart = params.start + params.rsz;
        for(var index = 0; index < response.responseData.cursor.pages.length; index++) {
            if (response.responseData.cursor.pages[index].start == nextStart)
                return true;
        }
    
        return false;    
    }
    
    function addPlacesToList(container, places) {
        var $results = container.find('.results');
        $.each(places, function(index, place) {
            var $place = $(
                '<div id="result' + index + '" style="padding:5px 0">' +
                '<div><a href="' + place.url + '">' + place.titleNoFormatting + '</a></div>' +
                '<div>' + place.addressLines[0] + '</div>' +
                '<div>' + place.addressLines[1] + '</div>' +
                '<div>' + place.phoneNumbers[0].number + '</div>' +
                '<div><a href="' + place.ddUrl + '">directions</a></div>' +
                '</div>');
            $results.append($place);
            place.html = $place.clone().get(0);
        });
    }
    
    function adjustMapPosition(map, viewport) {
        // Store where the map should be centered
        var center = viewport.center;

        // Calculate what the zoom level should be
        var ne = new google.maps.LatLng(viewport.ne.lat, viewport.ne.lng);
        var sw = new google.maps.LatLng(viewport.sw.lat, viewport.sw.lng);
        var bounds = new google.maps.LatLngBounds(sw, ne);
        var zoom = map.getBoundsZoomLevel(bounds, new google.maps.Size(350, 350));

        // Set the new center of the map
        // parseFloat converts the lat/lng from a string to a float, which is what
        // the LatLng constructor takes.
        map.setCenter(new google.maps.LatLng(parseFloat(center.lat),
                                            parseFloat(center.lng)),
                                            zoom);    
    }
    
    function addPlacesToMap(map, places) {
        map.clearOverlays();
        // We loop through to get the points
        $.each(places, function(index, place) {
            var markerLatLng = new google.maps.LatLng(parseFloat(place.lat), parseFloat(place.lng));
            var marker = new google.maps.Marker(markerLatLng); // Create the marker
            // Bind information for the infoWindow aka the map marker popup
            marker.bindInfoWindow(place.html.cloneNode(true));
            place.marker = marker; // bind the marker to the result
            map.addOverlay(marker); // add the marker to the map
        });
    }
    
})(jQuery);
