	// ====================
	// = LOCATION ACTIONS =
	// ====================
	var map_context = map_context || "bucket"
	
	var def_rad = .5;
	
	var cur_addr = "";
	curLat = 40.70283;
	curLng = -73.986697;
	var map = null;
	var geocoder = null;
	
	// chooses between loading the location.drop.io GMap 
	// or the mini map widget on the regular drop pages
	function initLocation() {
	  if( $('map_canvas') ) {
	    loadGMap();
	    setupLocStuff();
	  }
	}
	Event.observe(window, 'load', initLocation);
	
	function loadGMap() {
		if (GBrowserIsCompatible()) {
	    map = new GMap2(document.getElementById("map_canvas"));
	    map.setCenter(new GLatLng(curLat, curLng), 13);

	    map.addControl(new GSmallMapControl());
			
			geocoder = new GClientGeocoder();
			GEvent.addListener(map, 'click', mapClick);
			// Display current location
			if (window.saved_location !== undefined && window.saved_location) {
				loc = new GLatLng(saved_location.lat, saved_location.lon);
				map.setCenter(loc);
				mapClick("", loc);
			}
	  }
	}
	
	function setupLocStuff() {
  		$('bucket_location').onfocus = function() {
  		  Form.Element.select(this);
  		  this.select();
  		}
	}

	/** Utility Functions **/
	
	// byte2hex - Takes number n from 0-255 and converts to hexadecimal string e.g. 'AA'
	// Courtesy Jim Bumgardner of krazydad.com
	function byte2Hex(n) {
		var nybHexString = "0123456789ABCDEF";
		return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
	}
	
	// RGB2Color - Takes 3 hexadecimal string color components and concatenates into standard HTML format
	// Courtesy Jim Bumgardner of krazydad.com
	function RGB2Color(r,g,b) {
		return '#' + byte2Hex(r) + byte2Hex(g) + byte2Hex(b);
	}
	
  function enableSaveButton(){
    if ($("save_btn"))
      $("save_btn").className = "save";
  }
        

	// mapClick - Handles the event of a user clicking anywhere on the map
	// Draws circle with clicked point as center.
	function mapClick(overlay, clickedPoint) {
		clearShapes();
		var polyPoints = Array();
		
		var mapNormalProj = G_NORMAL_MAP.getProjection();
		var mapZoom = map.getZoom(); // 0 (all out) - 17 (all in)
	    var clickedPixel = mapNormalProj.fromLatLngToPixel(clickedPoint, mapZoom);
		
		//var polySmallRadius = 20; // dependant on zoom level... at level 13, rad = 20
		var polySmallRadius = mapZoom*1.2;
		//	alert(polySmallRadius);
		var polyColor = RGB2Color(201,36,36);
		
		// circle mode
	    polyNumSides = 20;
	    polySideLength = 18;
		
	 	for (var a = 0; a<(polyNumSides+1); a++) {
			var aRad = polySideLength*a*(Math.PI/180);
	    	var polyRadius = polySmallRadius; 
	   	    var pixelX = clickedPixel.x + polyRadius * Math.cos(aRad);
	    	var pixelY = clickedPixel.y + polyRadius * Math.sin(aRad);
	    	var polyPixel = new GPoint(pixelX,pixelY);
	    	var polyPoint = mapNormalProj.fromPixelToLatLng(polyPixel,mapZoom);
	    	polyPoints.push(polyPoint);
		}
			if (window.saved_location !== undefined && window.saved_location && clickedPoint.lat() == saved_location.lat && clickedPoint.lng() == saved_location.lon) {
				if ($("reset_btn"))
					$("reset_btn").className = "reset_inactive";
				if ($("save_btn"))
					$("save_btn").className = "save_inactive";
			}
			else {
				if ($("reset_btn"))
					$("reset_btn").className = "reset";
				if ($("save_btn"))
					$("save_btn").className = "save";
			}
	   	drawCircle(clickedPoint, def_rad, 400, "#000000",1,.5,polyColor,.5);
			$("bucket_longitude").value = clickedPoint.lng();
			$("bucket_latitude").value = clickedPoint.lat();
			if (map_context == "lookup") {
	  		lookup();
		  }
	}
	
	function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa, clickedPoint) {
		bounds = new GLatLngBounds();
		revGeo(center.lat(),center.lng());
	    var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	    var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;
	    var points = [];
	    var step = parseInt(360/nodes)||10;
	    for(var i=0; i<=360; i+=step) {
	    	var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
	        points.push(pint);
	        bounds.extend(pint); //this is for fit function
	    }
	    fillColor = fillColor||liColor||"#0055ff";
	    liWidth = liWidth||2;
	    var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
	    if (map_context == "lookup") {
	  		map.addOverlay(new GMarker(center));
		  }
		  else {
		  	map.addOverlay(poly);
		  }
	}
	
	function clearShapes() {
		map.clearOverlays();
	}
	
	function resetLocation() {
		if (window.saved_location !== undefined && window.saved_location) {
			loc = new GLatLng(saved_location.lat, saved_location.lon);
			mapClick("", loc);
			map.setCenter(loc);
		}
		else {
			removeLocation();
		}
	}
	
	function removeLocation() {
		clearShapes();
		$('bucket_location').value = null;
		$('bucket_latitude').value = null;
		$('bucket_longitude').value = null;
		$('actual_form').submit();
	}
	function showAddress() {
		var address = $('bucket_location').value;
		if (geocoder) {
			geocoder.getLatLng(
				address,
				function(point) {
					if (!point) {
						alert(address + " not found");
					} else {
						map.setCenter(point, 13);
						mapClick("overlay", point);
						$('bucket_latitude').value = point.lat();
						$('bucket_longitude').value = point.lng();
					}
				}
			);
		}
		return false;
	}

	function loadLoki() {
	  $('find_me_btn').disabled = true
	  $('find_me_btn').value ="finding your location...";
	  var loki = LokiAPI();
	  if (loki) {
	    loki.onSuccess = function(location) {
			curLat = location.latitude;
			curLng = location.longitude;
			cur_addr = location.house_number+" "+location.street+" "+location.city+" "+location.postal_code;
			$("bucket_location").value = trimZip(cur_addr);
			mapClick("overlay", new GLatLng(curLat, curLng));
			map.setCenter(new GLatLng(curLat, curLng), 13);
			$('find_me_btn').disabled = false
	    $('find_me_btn').value ="Find me with Loki";
			$('bucket_latitude').value = curLat;
			$('bucket_longitude').value = curLng;
		}
	    loki.onFailure = function(error) {
	      $('find_me_btn').disabled = false
  	    $('find_me_btn').value ="Find me with Loki";
	      alert("Could not determine your location. Please try again.");
	    } 
	    loki.setKey('drop.io');
	    loki.requestLocation(true, loki.FULL_STREET_ADDRESS_LOOKUP); 
	  }
	}
	
	function lookup() {
		lat = $("bucket_latitude").value;
		lng = $("bucket_longitude").value;
		if (lat != "" && lng != "") {
  		new Ajax.Request("/v05/drops.json", {
	  		method: "get",
	  		parameters: "lat=" + lat + "&long=" + lng,
				onCreate: function(){
			  	$("results").update("<div style='padding-top:130px;'><center><img src='/images/box_spinner.gif'></center></div>");
			  },
	  		onComplete: function(transport){
	  			response = eval(transport.responseText);
	  			draw_lookup_results(response);
	  		}
	  	})
	  }
		else {
			alert("please choose a location first");
		}
	}
	
	function create_drop_at_location() {
	  lat = $("bucket_latitude").value;
		lng = $("bucket_longitude").value;
		dname = $("drop_name").value;
    $('dropbtn').hide()
    $('dropping').show()
	  new Ajax.Request("/v05/new_drop.json", {
	  		method: "post",
	  		parameters: "url=" + dname + "&latitude=" + lat + "&longitude=" + lng,
	  		onSuccess: function(transport){
	  			url = transport.responseJSON.url;
	  			top.location = "/"+url;
	  		},
	  		onFailure: function(transport) {
	  		  alert("Sorry, drop creation failed. Please try again.");
	  		  $('dropbtn').show()
          $('dropping').hide()
	  		}
	  	})
			return false;
	}
	
	function trimZip(address) {
		zip = reverseString( parseInt(reverseString(address)).toString() );
		if (zip != "NaN") {
			return address.substring(0, address.indexOf(zip));
		}
		else {
			return address;
		}
	}
	
	function reverseString(string) {
		var reversed = ""; 
    var counter = string.length; 
    for (counter; counter > 0; counter-- ) { 
       reversed += string.substring(counter-1, counter); 
    }
		return reversed;
	}
	
	
	function draw_lookup_results(response) {
		$("results").hide();
		$("results").update("");
		new Insertion.Bottom("results", "<b>There " + (response.length == 1 ? "is" : "are") + " " +response.length + " " + (response.length == 1 ? "drop" : "drops") + " at this location:</b><div id='results_list' style='overflow:auto; height:230px;'></div>");
		var count = 1;
		response.each(function(drop){
			new Insertion.Bottom("results_list", count + ". <a class='loc_drop_name' href='" + drop.url + "'>" + drop.url.split("/")[3] + "</a><br>");
			count += 1;
		});
		to_insert =  "<div class='new_drop_at_loc'>";
		to_insert += "<p'><b>Create a new drop at this location</b></p>";
		to_insert += "<form action='' onsubmit='return create_drop_at_location()'>";
		to_insert += "<label for='drop_name'>Drop name: </label>";
		to_insert += "<input type='text' class='invisible_text' value='"+randomString(8)+"' size='10' id='drop_name' onclick='this.value=\"\"' /> ";
		to_insert += "<img id='dropbtn' src='/images/btn_go_normal.gif' style='cursor:pointer; margin-left: 10px;' onmouseover='this.src=\"/images/btn_go_highlight.gif\"' onmouseout='this.src=\"/images/btn_go_normal.gif\"' onclick='create_drop_at_location(); return false;'/>";
		to_insert += "<label id='dropping' style='display:none; font-size:9px'>dropping...</label>"
		to_insert += "</form>";
		new Insertion.Bottom("results", to_insert);
		new Effect.Appear("results", {duration:.2});
	}
	
	function revGeo(lat,lon,j) {
		var gLat = new GLatLng(lat,lon);
		var geo = new GClientGeocoder();
		geo.getLocations(gLat,getLocation)
	}
  
  function getLocation(jData) {
		if (jData == null || jData.Placemark == null || jData.Placemark.length < 0) {
			return;
		}
		address = jData.Placemark[0];
		var clicked_addr = address.address;
	    $('bucket_location').value = trimZip(clicked_addr);
	}
	
	
//********************************************************
// Functions for the mini map on drop pages 
// (assumes presence of saved_location.lat, saved_location.lon
// cur_bucket_url, and HOST
//********************************************************

// the base icon to be use to build icons for the drop_page context
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = document.location.protocol + "//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);

var dropMarker = null;   // the marker where the user clicks

// load the gmap and add markers for this and nearby drops
function loadMiniGMap() {
	if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("mini_map_canvas"));
    map.addControl(new GSmallZoomControl());                        // only zoom controls
		GEvent.addListener(map, 'click', miniMapClick); 

	  my_loc = new GLatLng(saved_location.lat, saved_location.lon);
		map.setCenter(my_loc,14);
	  
	  map.addOverlay(dropioMarker(my_loc,window.cur_bucket_url,true));

    // get nearby drops and put markers there
		new Ajax.Request("/v05/drops.json", {
  		method: "get",
  		parameters: "lat=" + saved_location.lat + "&long=" + saved_location.lon,
  		onComplete: function(transport){
  			response = eval(transport.responseText);
  			response.each(function(drop){
			    the_loc = new GLatLng(drop.lat, drop.lon);
			    if( drop.display_url != cur_bucket_url &&  my_loc.lat() != the_loc.lat() && my_loc.lng() != the_loc.lng())
  			    map.addOverlay(dropioMarker(the_loc,drop.display_url,false));
		    });
  		}
  	})
  }
}

// gets the GMarker object
function dropioMarker(point,url,special) {
  var dropioIcon = new GIcon(baseIcon);
  if(special)
    dropioIcon.image = HOST + "/images/dropio_gmap_icon_special.png";
  else
    dropioIcon.image = HOST + "/images/dropio_gmap_icon.png";

  // Set up GMarkerOptions object
  markerOptions = { icon:dropioIcon, title:url };
  var marker = new GMarker(point, markerOptions);
  
  if( url != "Your New Drop" ) {
    GEvent.addListener(marker, "click", function() {
      window.location = marker.getTitle()
    });
  }
  
  return marker;
}

// moves the dropMarker to where the user clicked
// and updates lat/lng info
function miniMapClick(overlay, clickedPoint) {
  if( dropMarker != null ) 
    map.removeOverlay(dropMarker);

  dropMarker = dropioMarker(clickedPoint,"Your New Drop",true) 
  map.addOverlay(dropMarker);
  
  // store lat/lon so create_drop_at_location can access it later
  $("bucket_latitude").value = clickedPoint.lat();
	$("bucket_longitude").value = clickedPoint.lng();
	
	// show spinner
	$('results_list').innerHTML = "<br /><br /><center><img src='/images/box_spinner.gif'></center>"
	
	// get nearby drops and create the list
	new Ajax.Request("/v05/drops.json", {
  		method: "get",
  		parameters: "lat=" + clickedPoint.lat() + "&long=" + clickedPoint.lng(),
  		onComplete: function(transport){
  			response = eval(transport.responseText);
		    $('results_list_summary').innerHTML = "<b>There " + (response.length == 1 ? "is" : "are") + " " +response.length + " " + (response.length == 1 ? "drop" : "drops") + " at this location:</b>";
		    var count = 1;
		    var links = "";
    		response.each(function(drop){
    			links += "<span style='color:white'>" + count + ".</span> <a class='loc_drop_name' href='" + drop.url + "'>" + drop.url.split("/")[3] + "</a><br>"
    			count += 1;
    		});
    		$('results_list').innerHTML = links;
      }
  });
	
  $('drop_name').value = randomString(7)
  if( $('new_drop_at_loc').style.display == "none" )
    Effect.toggle('new_drop_at_loc', 'blind', {duration: 0.3});
}
