var map;
var geocoder;
var json;
var infoWindow;
var markers;


if (window.location.pathname == '/tillman-military-scholars/scholar-map/') {
   $(document).ready(function() {
      $.ajax({
         url : '/php/scholar_list.php',
         success : function(data) {
            json = $.parseJSON(data);
            
            $('.entry-content').prepend('<div id="map_canvas"></div>');
            $('#map_canvas').after(
               '<div id="map_filter">' +
               '<div id="institution_types"><ul></ul></div>' +
               '<div id="scholar_statuses"><ul></ul></div>' +
               '<div id="scholar_years"></div>' +
               '</div>'
            );
            
            for (var i = 0; i < json.institution_types.length; i++) {
               var type = json.institution_types[i];
               $('#institution_types ul').append('<li><input type="checkbox" '
                  + 'id="' + type.replace(' ', '_') + '" checked="checked" '
                  + 'value="' + type + '" /><label for="'
                  + type.replace(' ', '_') + '">' + type + '</label></li>');
               $('#' + type.replace(' ', '_')).change(function() {
                  loadMarkers();
               });
            }
            
            for (var i = 0; i < json.scholar_statuses.length; i++) {
               var status = json.scholar_statuses[i];
               $('#scholar_statuses ul').append('<li><input type="checkbox" id="'
                  + status.replace(' ', '_') + '" checked="checked" value="'
                  + status + '" /><label for="' + status + '">' + status
                  + '</label></li>');
               $('#' + status.replace(' ', '_')).change(function() {
                  loadMarkers();
               });
            }
            
            $('#scholar_years').append('<label for="scholar_year">Scholar Year:'
               + '</label><select id="scholar_year"><option value="" '
               + 'selected="selected">All</option></select>');
            $('#scholar_year').change(function() {
               loadMarkers();
            });
            for (var i = 0; i < json.scholar_years.length; i++) {
               var year = json.scholar_years[i];
               $('#scholar_year').append('<option value="' + year + '">' + year
                  + '</option>');
            }
            
            map = new google.maps.Map(document.getElementById('map_canvas'), {
               zoom: 3,
               center: new google.maps.LatLng(38.25, -97.50),
               mapTypeId: google.maps.MapTypeId.TERRAIN,
               panControl: false,
               mapTypeControl: false,
               streetViewControl: false
            });
            
            infoWindow = new google.maps.InfoWindow();
            
            loadMarkers();
         }
      });
   });
}


function loadMarkers()
{
   var types = [ ];
   $('#institution_types input[type="checkbox"]').each(function() {
      types.push(this);
   });
   
   var statuses = [ ];
   $('#scholar_statuses input[type="checkbox"]').each(function() {
      statuses.push(this);
   });
   
   var year = $('#scholar_year').val();
   
   clearMarkers();
   for (var i = 0; i < json.institutions.length; i++) {
      var institution = json.institutions[i];
      if (institution.scholars.length > 0) {
         if (true == shouldShowInstitution(types, statuses, year, institution)) {
            var icon = '/images/marker1.png';
            var shadow = '/images/marker1-shadow.png';
            
            if (institution.type == 'At-large') {
               icon = icon.replace('1', '2');
               shadow = shadow.replace('1', '2');
            }
            
            var markerIcon = new google.maps.MarkerImage(icon,
               //  Icon size
               new google.maps.Size(30, 30),
               //  Origin point
               new google.maps.Point(0, 0),
               //  Anchor point
               new google.maps.Point(15, 15)
            );
            
            var markerShadow = new google.maps.MarkerImage(shadow,
               //  Icon size
               new google.maps.Size(46, 30),
               //  Origin point
               new google.maps.Point(0, 0),
               //  Anchor point
               new google.maps.Point(15, 15)
            );
               
            marker = new google.maps.Marker({
               map: map,
               icon: markerIcon,
               shadow: markerShadow,
               position: new google.maps.LatLng(institution.lat, institution.lng),
               title: institution.name
            });
            
            var info = '<div style="width:150px;height:100px;">';
            info += '<h5 style="border-bottom:1px #ccc solid;margin-bottom:5px;">';
            if (institution.url.length > 0) {
               info += '<a href="' + institution.url + '" target="_blank">'
                  + institution.name + '</a>';
            } else {
               info += institution.name;
            }
            info += '</h5>';
            info += '<ul>';
            for (var j = 0; j < institution.scholars.length; j++) {
               var scholar = institution.scholars[j];
               if (true == shouldShowScholar(statuses, year, scholar)) {
                  info += '<li style="line-height:120%;margin-bottom:5px;">';
                  if (scholar.profile_path.length > 0) {
                     info += '<a href="' + scholar.profile_path
                        + '" target="_blank">' + scholar.name + '</a>';
                  } else {
                     info += scholar.name;
                  }
                  if (scholar.degree.length > 0) {
                     info += '<span style="font-size:80%"><br />'
                        + scholar.degree + '</span>';
                  }
                  info += '</li>';
               }
            }
            info += '</ul></div>';
            marker.info = info;
            markers.push(marker);
            
            google.maps.event.addListener(marker, 'click', function() {
               infoWindow.setContent(this.info);
               infoWindow.open(map, this);
            });
         }
      }
   }
}


/***
 * Removes all markers from the map.
 ***/ 
function clearMarkers()
{
   if (null != markers) {
      infoWindow.close();
      for (var i = 0; i < markers.length; i++) {
         markers[i].setMap(null);
         markers[i] = null;
      }
   }
   
   markers = [ ];
}


/***
 * shouldShowInstitution
 *    Determines if the institution should be displayed in the map or not.
 ***/ 
function shouldShowInstitution(types, statuses, year, institution)
{
   var showInstitution = true;
   
   if (true == showInstitution) {
      for (var i = 0; i < types.length; i++) {
         if (types[i].value == institution.type) {
            showInstitution = types[i].checked;
         }
      }
   }
   
   if (true == showInstitution) {
      var scholars = [ ];
      for (var i = 0; i < statuses.length; i++) {
         if (statuses[i].checked) {
            for (var j = 0; j < institution.scholars.length; j++) {
               if (statuses[i].value == institution.scholars[j].scholar_status) {
                  if (year == ''
                   || year == institution.scholars[j].scholar_year) {
                     scholars.push(institution.scholars[j]);
                  }
               }
            }
         }
      }
      
      if (scholars.length == 0) {
         showInstitution = false;
      }
   }
   
   return showInstitution;
}


/***
 * shouldShowScholar
 *    Determines if the scholar should be displayed in the institution's scholar
 *    list or not.
 ***/ 
function shouldShowScholar(statuses, year, scholar)
{
   var showScholar = true;
   
   if (true == showScholar) {
      if (year != ''
       && year != scholar.scholar_year) {
         showScholar = false;
      }
   }
   
   if (true == showScholar) {
      for (var i = 0; i < statuses.length; i++) {
         if (statuses[i].value == scholar.scholar_status) {
            showScholar = statuses[i].checked;
         }
      }
   }
   
   return showScholar;
}


/***
 * loadMap
 *    Loads the Google map for a single location.
 ***/
function loadMap(name, city, state, type, latlng)
{
   var canvas = document.getElementById('map_canvas');
   canvas.style.display = 'block';
   
   map = new google.maps.Map(canvas, {
         center: latlng,
         disableDefaultUI: true,
         mapTypeId: google.maps.MapTypeId.TERRAIN,
         navigationControl: true,
         navigationControlOptions: {
               style: google.maps.NavigationControlStyle.SMALL
            },
         zoom: 14
      });

   var icon = '/images/marker' + type + '.png';
   var shadow = '/images/marker' + type + '-shadow.png';

   var marker = new google.maps.Marker({
         map: map,
         position: latlng,
         icon: icon,
         shadow: shadow
      });
      
   var infoWindow = new google.maps.InfoWindow({
         content: '<p><strong>' + name + '</strong><br />' + city + ', ' + state
            + '</p>'
      });
      
   google.maps.event.addListener(marker, 'click', function() {
         infoWindow.open(map, marker);
      });
} // end loadMap


/***
 * getLatLng
 *    Geocodes the specified location.
 ***/     
function getLatLng(name, city, state, type, elemLat, elemLng)
{
   var geocoder = new google.maps.Geocoder();
   geocoder.geocode({
         address: name + ', ' + city + ', ' + state
      },
      function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
            var location = results[0].geometry.location;
            loadMap(name, city, state, type, location);
            
            elemLat.value = location.lat();
            elemLng.value = location.lng();
         }
      });
}

/***
 * updateMap
 *    Updates the map on the institution SAM page.
 ***/  
function updateMap()
{
   var name = document.getElementById('institution_name');
   var city = document.getElementById('city');
   var state = document.getElementById('state_id');
   var type = document.getElementById('institution_type_id');
   
   if (name.text != '' && city.text != ''
    && state.selectedIndex > 0 && type.selectedIndex > 0) {
      getLatLng(name.value, city.value,
         state.options[state.selectedIndex].text,
         type.selectedIndex,
         document.getElementById('latitude'),
         document.getElementById('longitude')
      );
   } else {
      msg = 'Please complete the following fields and try again:\n';
      if (name.value == '') {
         msg += '- Name\n';
      }
      if (city.value == '') {
         msg += '- City\n';
      }
      if (state.selectedIndex == 0) {
         msg += '- State\n';
      }
      
      alert(msg);
   }
}

