var map;
var mapPoints = [];
var aStartupCoords = [43.6485936834387, -79.3853352889556];
var thisListing;
var listingTypes = [];
var listingsCache = {}; // cache ajax queries for listings. Indexed by querystring.
var aRows, iPage, iListingsPerPage = 10;

$j(function(){
	try{
		$j.getJSON(
			"http://api.blogto.com/listings.json/" + iListingID + "?k=d4UKy3LrxPXA",
			function(r){
				thisListing = r;
				if(thisListing){
					initMap();
					plotListing(thisListing, true);
					zoomMapToFit();
				}
			}
		);
	}
	catch(e){}
	$j(window).unload( function(){GUnload();});
});

function initMap(){
	if(!GBrowserIsCompatible()) return;
	try {
	  var objPoint = new GLatLng(thisListing.latitude, thisListing.longitude);
	  geocoder = new GClientGeocoder();				
	  map = new GMap2($j("#sidebar .map")[0]);
	  map.setCenter(objPoint, 16);      
	  map.addControl(new GSmallMapControl());
	  map.setMapType(G_DEFAULT_MAP_TYPES);
	}
	catch(e){
	  warn(e);
	}				
}

function clearMap(){
	try {
	  map.clearOverlays();
	  mapPoints = [];
	}
	catch (e) { warn(e); } 
}

function zoomMapToFit(){
	map.setCenter(new GLatLng(aStartupCoords),0);
	var bounds = new GLatLngBounds();
	$j.each(mapPoints, function(i, point){
	      bounds.extend(point);
	});
	var zoom = map.getBoundsZoomLevel(bounds);
	if (zoom > 16 ) zoom = 16;
	if(map.getZoom() == zoom){
		map.panTo(bounds.getCenter());
	}
	else{
		map.setCenter(bounds.getCenter(), zoom);
	}  	
}

function plotListingSet(listingSet) {
	clearMap();        
	$j.each(listingSet, function(key, val){
	  plotListing(val);  
	});
	plotListing(thisListing, true);
	zoomMapToFit();
}

function plotListing(listing, active) {
	if (listing.latitude === 0 || listing.longitude === 0) return;
	var point = new GLatLng(listing.latitude, listing.longitude);
	var markerIcon = new GIcon(G_DEFAULT_ICON);
	markerIcon.image = (active) ? '/images/gmaps/'+listing.type_shorthand+'_active.png' : '/images/gmaps/'+listing.type_shorthand+'.png';
	marker = new GMarker(point, {icon:markerIcon});
	marker.listing = listing;
	map.addOverlay(marker);
	GEvent.addListener(marker, "click", listingMarkerClick);
	mapPoints.push(point);
}

function listingMarkerClick(){
	var listing = this.listing;
	var html = 
	  '<div class="infowindow">'+
	    '<h3><a href="'+listing.url+'" >'+listing.name+'</a></h3>'+
	    '<p>'+listing.address+'<br/>'+
	    listing.phone+'</p>'+
	    '<p>'+
	    '<a href="'+listing.url+'">View Review</a> | '+
	    '<a href="/listings/facebook-faves.php?entryid='+listing.entry_id+'" >Add to Faves</a>'+
	    '</p>'+
    '</div>';  	      
	this.openInfoWindowHtml(html);
}

function log(){
	if (console) console.debug(arguments);
}

function warn(){
	if (console) console.warn(arguments);
}

function SearchListings(objForm){
  var aFilter = new Array();
  var sNeighborhoodID = objForm.Neighbourhood.value;
  var sCustom = "";
  if(objForm.Custom) sCustom = objForm.Custom.value;
  if(sNeighborhoodID == "" && sCustom == "") return;
  if(sNeighborhoodID != "") aFilter.push("Neighborhood = " + sNeighborhoodID);
  if(sCustom != ""){
    aFilter.push("Custom = '" + sCustom.replace(/'/g, "\\'") + "'");
  }
  if(objForm.Reviewed.checked) aFilter.push("Reviewed = 1");
  if(aFilter.length == 0) return;
  
  var sFilter = aFilter.join(" AND ");
  var sData = "cmd=search&type=" + iListingsType + "&filter=" + escape(sFilter);
  
  $listingfinder_instructions = $j("#listingfinder .instructions");
  $listingfinder_results = $j("#listingfinder .results");
  $listingfinder_pages = $j("#listingfinder .pages");
  
  $listingfinder_instructions.html("Loading...");
  $listingfinder_results.hide();
  $listingfinder_pages.hide();

  $j.get(location.pathname, sData, function(sResponse){
	if(sResponse.length == 0){
	  $listingfinder_instructions.html("Sorry, no results found.").show();
	  return;
	}
	
	aRows = sResponse.split("\n");
	var sHTML = "";
	
	for(i=0; i<iListingsPerPage; i++){
	  if(i == aRows.length) break;
	  aFields = aRows[i].split("|");
	  sHTML += "<li><a href=\"" + aFields[2] + "\">" + Replace(aFields[1], "\\'", "'") + "</li>";
	}
	
	$listingfinder_instructions.hide();
	$listingfinder_results.html("<ul>" + sHTML +  "</ul>").show();
	
	if(aRows.length > iListingsPerPage){
	  $listingfinder_pages.html("<a class=\"right\" href=\"javascript: SwitchPage(1);\"><img src=\"/images/buttons/next.gif\" align=\"absmiddle\" /></a>").show();
	}
  });

  iPage = 1;
}

function SwitchPage(iDirection){
  iPage+=iDirection;
  if(iPage > iPages) iPage = iPages;
  if(iPage < 1) iPage = 1;

  var sHTML = "";
  var iPages = Math.ceil(aRows.length / iListingsPerPage);
  var iStart = ((iPage - 1) * iListingsPerPage);

  for(i=iStart; i<(iStart + iListingsPerPage); i++){
    if(i == aRows.length) break;
    aFields = aRows[i].split("|");
    sHTML += "<li><a href=\"" + aFields[2] + "\">" + Replace(aFields[1], "\\'", "'") + "</a></li>";
  }
 $listingfinder_results.html("<ul>" + sHTML + "</ul>");

  if(iPage > 1 && iPage < iPages){
    sHTML = "<a class=\"left\" href=\"javascript: SwitchPage(-1);\"><img src=\"/images/buttons/previous.gif\" align=\"absmiddle\" /></a><a class=\"right\" href=\"javascript: SwitchPage(1);\"><img src=\"/images/buttons/next.gif\" align=\"absmiddle\" /></a>";
  }
  else if(iPage == iPages){
    sHTML = "<a class=\"left\" href=\"javascript: SwitchPage(-1);\"><img src=\"/images/buttons/previous.gif\" align=\"absmiddle\" />";
  }
  else if(iPage == 1){
    sHTML = "<a class=\"right\" href=\"javascript: SwitchPage(1);\"><img src=\"/images/buttons/next.gif\" align=\"absmiddle\" />";
  }
  $listingfinder_pages.html(sHTML);
}

function Replace(sText, sReplace, sWith){
  var objRegExp = new RegExp(sReplace);
  return sText.replace(objRegExp, sWith);
}

