
MapReader = {};

MapReader.init = function()
{
  if (GBrowserIsCompatible()) 
  {
    var map = new GMap2(document.getElementById("map"));
	  map.setCenter(new GLatLng(38, -100), 3);
	  map.setMapType(G_NORMAL_MAP);
	  map.addControl(new GLargeMapControl());
	  map.addControl(new GMapTypeControl()); 
	   
	  MapReader.map = map;
	  MapReader.geocoder = new GClientGeocoder();
	  MapReader.newLocations = 0;
	
    if (my_locations != null && my_locations.length > 0)
    {
      MapReader.loadMyLocations(false);
      
      for (i=0; i<my_locations.length; i++)
      {
	  		var baseIcon = new GIcon();
				baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
				baseIcon.iconSize = new GSize(20, 34);
				baseIcon.shadowSize = new GSize(37, 34);
				baseIcon.iconAnchor = new GPoint(9, 34);
				baseIcon.infoWindowAnchor = new GPoint(9, 2);
				baseIcon.infoShadowAnchor = new GPoint(18, 25);
			
				var swirlIcon = new GIcon(baseIcon);
  			swirlIcon.image = "images/marker-red.png";
				marker = new GMarker(new GLatLng(my_locations[i]['location_latitude'], my_locations[i]['location_longitude']), {icon:swirlIcon});
        marker.key = my_locations[i]['location_key'];
    		map.addOverlay(marker);
			
				GEvent.addListener(marker, "click", function() {
    			MapReader.loadLocation(this.key);
    		});
     	}
    }  
    
		if (typeof load_location != "undefined")
    {
      map.setCenter(new GLatLng(load_location['location_latitude'], load_location['location_longitude']), 12);
      MapReader.loadLocation(load_location['location_key']);
      load_location = null;
    }
    else 
    {
      MapReader.searchPrompt();
    }
  }
}

MapReader.newLocation = function()
{
  // shadow, icon dimensions, etc.
	var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);
	
	var swirlIcon = new GIcon(baseIcon);
	swirlIcon.image = "images/marker-lime.png";
	
	if (typeof MapReader.newMarker != 'undefined') 
	{
		MapReader.map.removeOverlay(MapReader.newMarker);
	}

	MapReader.newMarker = new GMarker(MapReader.map.getCenter(), {
		icon: swirlIcon,
		draggable: true,
		icon: swirlIcon
	});
	
	GEvent.addListener(MapReader.newMarker, "dragstart", function(){
		});
		
		GEvent.addListener(MapReader.newMarker, "dragend", function(){
			if (MapReader.newMarker.getLatLng()) 
				MapReader.getZipcode(MapReader.newMarker.getLatLng().lat(), MapReader.newMarker.getLatLng().lng());
		});
		
		MapReader.map.addOverlay(MapReader.newMarker);
        MapReader.setWindowTitle('New Location');
        MapReader.displayLocation('Drag the green marker to the location desired.  Enter a name and description and click "Save"');
}

MapReader.displayLocation = function(weather)
{
  document.getElementById('weather').innerHTML = weather;
}

MapReader.displayForecast = function(weather)
{
  document.getElementById('forecast').innerHTML = weather;
}

MapReader.getZipcode = function(lat, lon)
{
  Ext.Ajax.request({
    url: 'get_zip.php',
		method: 'GET',
		params: {lat: lat, lon: lon, type: 'location'},
		success: function(response)
		{
		  loc = eval(response.responseText);
		  MapReader.current_location = loc;
      MapReader.loadWeather(loc.zip);
    }});
}

MapReader.loadWeather = function(zip, key)
{
  MapReader.showLoading();                    
  Ext.Ajax.request({
		url: 'weather.php',
		method: 'POST',
		params: {zip: zip, id: key, mode: 'map'},
		success: function(response)
		{
     MapReader.displayLocation(response.responseXML.getElementsByTagName('weather')[0].childNodes[0].nodeValue);
     MapReader.displayForecast(response.responseXML.getElementsByTagName('forecast')[0].childNodes[0].nodeValue);
  }});
}

MapReader.saveCustomLocation = function()
{
  //Make sure that zipcodes starting with 0 preserve the leading 0.
  var zip = MapReader.current_location.zip;
  if (zip.length == 4) zip = '0'+zip;
 
  //Bundle location fields in an object.  location_user will be determined from SESSION by add_location.php.
  var location = {
     'location[location_latitude]': MapReader.newMarker.getLatLng().lat(),
     'location[location_longitude]': MapReader.newMarker.getLatLng().lng(),
     'location[location_zip]': zip,
     'location[location_name]': document.getElementById('location_name').value,
     'location[location_description]': document.getElementById('location_desc').value
  }
 
  my_locations.push(location);
 
  Ext.Ajax.request({
    url: 'form/add_location.php',
		  method: 'POST',
		  params: location,
		  success: function(response)
		  {
      Ext.MessageBox.alert('Success','Location saved.',MapReader.init);
      MapReader.loadMyLocations(true);
    }});
    
}

MapReader.loadMyLocations = function(refresh)
{
  MapReader.showLoading();
  if (refresh) {
  Ext.Ajax.request({
    url: 'my_locations.php',
		  method: 'GET',
		  success: function(response)
		  {
      my_locations = eval(response.responseText);
      MapReader.displayLocation(MapReader.displayMyLocations());
    }});
  }
  else MapReader.displayLocation(MapReader.displayMyLocations());
}

MapReader.displayMyLocations = function()
{
 if (GustHut.session.user_key > 0)
 {
  var html = '<table class="locations" cellpadding="0" cellspacing="0"><tr><th>Location</th><th>Subscribers</th></tr>';

  for (i=0; i<my_locations.length; i++)
  {
    html += '<tr><td><a style="cursor:pointer" onclick="MapReader.loadLocation('+my_locations[i].location_key+')">'+my_locations[i].location_name+'</a></td>';
    html += '<td>'+my_locations[i].subscribers+'</td></tr>';
  }
  html += '</table>';
  return html;
 }
 else return '<a href="signup.php">Sign Up</a> for GustHut to save locations!';
}

MapReader.showLoading = function()
{
  MapReader.displayLocation('<img src="images/loader.gif"/>');
}

MapReader.setCenter = function(lat, lon, zoom)
{
 MapReader.map.setCenter(new GLatLng(lat, lon), zoom);
}

MapReader.loadLocation = function(loc_key)
{
  var found = false;
  if (my_locations)
  {
	  for (i=0; i<my_locations.length; i++)
	  {
	    if (my_locations[i].location_key == loc_key)
	    {
	      var loc = my_locations[i];
	      MapReader.loadWeather(loc.location_zip, loc_key);
	      Ext.get('ajax_window').dom.innerHTML = loc.location_name;
	      MapReader.setCenter(loc.location_latitude, loc.location_longitude, 12);
	      found = true;
	    }
	  }
  }
  
  if (typeof search_locations != "undefined" && found == false)
  {

  for (i=0; i<search_locations.length; i++)
  {
    if (search_locations[i].location_key == loc_key)
    {
      var loc = search_locations[i];
      MapReader.loadWeather(loc.location_zip, loc_key);
      Ext.get('ajax_window').dom.innerHTML = loc.location_name;
      MapReader.setCenter(loc.location_latitude, loc.location_longitude, 12);
      found = true;
    }
  }
  }
  
  else
  {
      MapReader.loadWeather(load_location.location_zip, loc_key);
      Ext.get('ajax_window').dom.innerHTML = load_location.location_name;
      MapReader.setCenter(load_location.location_latitude, load_location.location_longitude, 12);
  }
}

MapReader.postComment = function(loc)
{
  MapReader.comment_loc = loc;
  var message = {message_content: document.getElementById('message').value};
  Ext.Ajax.request({
    url: 'post.php',
		  method: 'POST',
		  params: {message: document.getElementById('message').value, type: 'location', key: loc},
		  success: function(response)
		  {
      Ext.MessageBox.alert('Success','Comment saved.',MapReader.loadLocation(MapReader.comment_loc));
    }});
    
}

MapReader.moveMap = function(text)
{
			MapReader.geocoder.getLatLng(
    		text,
    		function(point) {
      			if (!point) {
        		alert(text + " not found");
      			} else {
			MapReader.getLocations(point.lat(), point.lng());
        		MapReader.map.setCenter(point, 10);
 				}
    		}
  			);
}

MapReader.searchPrompt = function()
{
	Ext.MessageBox.prompt('Where to?', 'City, State or Zip', MapReader.processSearch);
	Ext.MessageBox.minWidth = 350;
}

MapReader.processSearch = function(btn, text)
{
  if (btn == 'ok') {
			MapReader.moveMap(text);
			
		}
}

MapReader.setWindowTitle = function(title)
{
 Ext.get('ajax_window').dom.innerHTML = title;
}

MapReader.getLocations = function(lat, lon)
{
  Ext.Ajax.request({
  url: 'search_locations.php',
		method: 'GET',
		params: {lat: lat, lon: lon},
		success: function(response)
		{
		  search_locations = eval(response.responseText);
		  MapReader.displayLocation(MapReader.displaySearchLocations());
		  MapReader.createSearchMarkers();
		  
  }});
}

MapReader.displaySearchLocations = function()
{
  var html = '<table class="locations" cellpadding="0" cellspacing="0"><tr><th>Location</th><th>Started By</th><th>Subscribers</th></tr>';

  for (i=0; i<search_locations.length; i++)
  {
    html += '<tr><td><a style="cursor:pointer" href="javascript: MapReader.loadLocation('+search_locations[i].location_key+')">'+search_locations[i].location_name+'</a></td>';
    html += '<td><a href="home.php?id='+search_locations[i].location_user+'" >'+search_locations[i].user_username+'</a></td>';
    html += '<td>'+search_locations[i].subscribers+'</td></tr>';
  }
  html += '</table>';
  return html;
}

MapReader.createSearchMarkers = function()
{
  for (i=0; i<search_locations.length; i++)
  {
    var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);
    var swirlIcon = new GIcon(baseIcon);
    swirlIcon.image = "images/marker-shine.png";
    marker = new GMarker(new GLatLng(search_locations[i]['location_latitude'], search_locations[i]['location_longitude']), {icon:swirlIcon});
    marker.key = search_locations[i]['location_key'];
    MapReader.map.addOverlay(marker);
    
    GEvent.addListener(marker, "click", function() {
      MapReader.loadLocation(this.key);
    });
  }
}

window.onload = MapReader.init;
