var map = null;
var geocoder = null;

function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.setCenter(new GLatLng(37.4419, -122.1419), 2);
    geocoder = new GClientGeocoder();
    
    GEvent.addListener(map, "dblclick", function() {
      fetchBuzz(map.getCenter(), $('address').value);
    });

  }
}

function showTwits(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          map.setCenter(point, 9);
          var marker = new GMarker(point);
          map.addOverlay(marker);
          fetchBuzz(point, address);
        }
      }
    );
  }
}


function fetchBuzz(point, address) {
  if(address.blank()) {address = "";}
  
  req = false;
  req = new window.XMLHttpRequest();

  // branch for native XMLHttpRequest object
   if(window.XMLHttpRequest && !(window.ActiveXObject)) {
     try {
       req = new XMLHttpRequest();
     } catch(e) {
       req = false;
     }
   // branch for IE/Windows ActiveX version
   } else if(window.ActiveXObject) {
     try {
       req = new ActiveXObject("Msxml2.XMLHTTP");
     } catch(e) {
     try {
       req = new ActiveXObject("Microsoft.XMLHTTP");
     } catch(e) {
       req = false;
     }
   }
   
   }
   
  if(req) {
    req.onreadystatechange = function() {
      if (req.readyState==4) {
        fillBuzz(req.responseText, address);
      }
    };
    
    req_str = point.y + "," + point.x + ",50km";
    req_url = "/remote?geocode=" + req_str;
    if(address) {
      req_url += "&q=" + address;
    }
    req.open("GET", req_url , true);
    req.send("");
  }

}

function fillBuzz(str, address) {
  if(!address.blank() && address == "Type in your location here...") {
    address = address.gsub(/\+/," ");
    document.title = "What's that buzzing sound in " + address + "?";
  } else {
    document.title = "What's that buzzing sound?";
  }
  
  document.getElementById("twuzzers").innerHTML = str;
	$("twuzzers").scrollTo();
}

function forwardTo(address) {
	if (address.blank()) {
		alert ("You need to type a location")
	} else {
    window.location = "/" + address.escapeHTML().gsub(" ", "+");
	}
}

function setupTwitterRefresh(params) {
	if (params.blank()) {
		//we might need a different set of behaviours if params are empty, unless you can populate this with 
		//a proper keyword automatically based on lat/lng
	} else {
		
		showTwits(params);
		
		new PeriodicalExecuter(function() {
			showTwits(params);
		}, 120);
		
	}
}