var centerLatitude = 40.6897;
var centerLongitude = -95.0446;
var startZoom = 2;

var map;
var bounds;
var points;

/* Set up custom pins */
var MoodVB;

var pin_names = ['mood_vb', 'mood_b', 'mood_g', 'mood_vg'];
var pins = [];

function initPins() {
  for(i=0; i< pin_names.length; i++) {
    name = pin_names[i];
    pins[name] = new GIcon();
    pins[name].image = '/images/pins/'+name+'.png';
	  pins[name].shadow = '/images/pins/pin_shadow.png';
    pins[name].iconSize = new GSize(18, 30);
    pins[name].shadowSize = new GSize(25, 30);
    pins[name].iconAnchor = new GPoint(9, 30);
    pins[name].infoWindowAnchor = new GPoint(24, 24);
  }
}

function addMarker(latitude, longitude, patient_id, pin) {
  if(!pin) { pin = 'mood_g'; };
  latlng = new GLatLng(latitude, longitude);
  var marker = new GMarker(latlng, pins[pin]);
  bounds.extend(latlng);
  GEvent.addListener(marker, 'click',
    function() {
		GDownloadUrl('/patients/geo_nugget?id='+patient_id, function(data, responseCode) {
		  // To ensure against HTTP errors that result in null or bad data,
		  // always check status code is equal to 200 before processing the data
		  if(responseCode == 200) {
			marker.openInfoWindowHtml(data);
		  } else if(responseCode == -1) {
		    alert("Data request timed out. Please try later.");
		  } else { 
			alert(responseCode);
		    alert("Request resulted in error. Check XML file is retrievable.");
		  }
		});
    }
  );
  
  map.addOverlay(marker);
}

function addPoly(stateCode, opacity, color, patients, interest_patients) {
   var polygon = new GPolygon(stateBorders[stateCode], color, opacity, opacity, color, opacity);
   GEvent.addListener(polygon, "click", function(latlng) {
	 $('state-info').update("<h3>"+stateCode+"</h3><b>ALS Patients: </b> "+patients+"<br /> <b>On Drug: </b>"+interest_patients);
   });
   map.addOverlay(polygon);
}

function initMap(isLocationSearch, zoom) {
  if(zoom) {
    startZoom = zoom;
  }
  initPins();
  bounds = new GLatLngBounds();
  map = new GMap2(document.getElementById("map-container"));
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  map.addControl(new GScaleControl());
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
    
  // loop through and add each store to the map
  updatePoints();

  if(isLocationSearch == 'true') {
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
  }
}

function initColoredMap(zoom) {
  if(zoom) {
    startZoom = zoom;
  }
  bounds = new GLatLngBounds();
  map = new GMap2(document.getElementById("map"));
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  map.addControl(new GScaleControl());
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
    
  // loop through and add each store to the map
  updateStates();
}

function updatePoints() {
  for(i=0; i < points.length; i++) {
    addMarker(points[i].lat , points[i].lng, points[i].id, points[i].pin);
  };	
}

function updateStates() {
  for(i=0; i < points.length; i++) {
	if(points[i].users >= 0) {
	  if(!points[i].opacity) { points[i].opacity = parseFloat(points[i].drug_users)/parseFloat(points[i].users); };
	  if(!points[i].color) { points[i].color = '#0000FF'}
	  // if (opacity > 0.0) {opacity += 0.15;};
      addPoly(points[i].state, points[i].opacity, points[i].color, points[i].users, points[i].drug_users)
	}
  };
}

var nytimeInterval;
var time = 0;
function nextNyTimesUpdate() {
  if (time >= 72) {
	clearInterval(nytimesInterval);
	}
  else {
	time += 1;
  }

  new Ajax.Request('/research_maps/map_nytimes_signups?time='+time, {
    method: 'get',
    onSuccess: function(response) {
	  time_and_points = eval('('+response.responseText+')');
	  points = time_and_points.points;
	  $('time').update(time_and_points.time);
	  //map.clearOverlays();
	  updatePoints();
    }
});
}

function moodUpdate(date, strip_pins) {
  new Ajax.Request('/research_maps/map_national_mood?date='+encodeURIComponent(date), {
    method: 'get',
    onSuccess: function(response) {
	  time_and_points = eval('('+response.responseText+')');
	  points = time_and_points.points;
	  $('date').update(time_and_points.time);
	  //map.clearOverlays();
	  if(strip_pins) { map.clearOverlays(); };
	  updatePoints();
	  date_parts = date.split('-');
	  prev_date_obj = new Date(parseInt(date_parts[0]), parseInt(date_parts[1]), parseInt(date_parts[2])-1);
	  next_date_obj = new Date(parseInt(date_parts[0]), parseInt(date_parts[1]), parseInt(date_parts[2])+1);
	  date_prev = ''+prev_date_obj.getFullYear()+'-'+prev_date_obj.getMonth()+'-'+prev_date_obj.getDate();
	  date_next = ''+next_date_obj.getFullYear()+'-'+next_date_obj.getMonth()+'-'+next_date_obj.getDate();

	  $('prev').onclick = function(){moodUpdate(date_prev, true); return false;};
  	  $('next').onclick = function(){moodUpdate(date_next, true); return false;};
    }
});
}

var timeInterval;
var time_period = 0;
function timedUpdate(url, periods) {
  if (time_period >= periods) {
	clearInterval(timeInterval);
	return false;
	}
  else {
	time_period += 1;
  }

  new Ajax.Request(url+'?time='+time_period, {
    method: 'get',
    onSuccess: function(response) {
	  time_and_points = eval('('+response.responseText+')');
	  points = time_and_points.points;
	  $('date').update(time_and_points.time);
	  //map.clearOverlays();
	  updatePoints();
    }
});
}
