/**
 * Snepo map JS
 *
 * Here we provide an AJAX implementation for the google maps API
 */
$(function() {
  
  // Get all the gMaps elements
  $( '.snepo_map' ).each( function( index, element ){
    
    //  Get the location and type
    var location = $( this ).siblings( 'input[type="hidden"]:first' ).remove().val();
    var type = $( this ).siblings( 'input[type="hidden"]:first' ).remove().val();
    
    // Map type
    var map_type;
    switch( type )
    {
      case 'TERRAIN' :
        map_type = google.maps.MapTypeId.TERRAIN;
      break;
      case 'HYBRID' :
        map_type = google.maps.MapTypeId.HYBRID;
      break;
      case 'SATELLITE' :
        map_type = google.maps.MapTypeId.SATELLITE;
      break;
      case 'ROADMAP' :
        map_type = google.maps.MapTypeId.ROADMAP;
      break;
    }
    
    // Fix scope
    var map_element = this;
    
    // Get coordinates
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({address: location, region: 'AU'}, function (results, status) {
      // If we get a result
      if (status == google.maps.GeocoderStatus.OK)
      {
        // Get element ID
        var id = $( map_element ).get(0);
        
        // Remove map info, but save it and make visible
        //check the height of the div and set in css
       var content_height= $('#snepo_map_info_snepo').height();
       $('#snepo_map_info_snepo').css('height',content_height);
        var mapinfo = $( map_element ).siblings( '.snepo_map_info' ).css('display', 'block').remove().get(0);
       
        // Set options
        var myOptions = {
          zoom: 16,
          center: results[0].geometry.location,
          mapTypeId: map_type,
          backgroundColor: '#ffffff'
        };
        
        // Create map
        var map = new google.maps.Map(id, myOptions);

        // Create marker
        
        var marker = new google.maps.Marker({
          position: results[0].geometry.location,
          map: map
        });

        // Create info window
        var infowindow = new google.maps.InfoWindow({
          content:mapinfo,
          maxWidth:260
        });

        // Load window straight away
        infowindow.open(map, marker);

        // Add load window to click event too
        google.maps.event.addListener(marker, 'click', function () {
          infowindow.open(map, marker);
        });
      }
    });
  });
  
});
