var YWSID = "KUce8Lpv05CSyV09X3xzMw"; // common required parameter (api key)

var map = null;
var icon = null;
var mapOverlays = new Array();
var categoryOverlays = new Array();
   
function load() {
	map = new GMap2(document.getElementById("searchResultsMap"));
	GEvent.addListener(map, "load", function() {updateMap();});    
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	if(window.isApartment) {
	  map.setCenter(new GLatLng(window.currentLat, window.currentLong), 15);
	  map.addOverlay(new GMarker(new GLatLng(window.currentLat,window.currentLong)));
	} else if(window.isCity) {
    map.setCenter(new GLatLng(defaultMarkers[0].lat, defaultMarkers[0].lon), 12);
    for(marker in defaultMarkers) {
      addApartmentOverlay(defaultMarkers[marker]);
    }
    
	}
  
}

function addApartmentOverlay(loc) {
  var infoWindowHtml = '<div class="marker">';

  // image and rating
  // infoWindowHtml += '<img class="businessimage" src="'+biz.photo_url+'"/>';

  // div start
  infoWindowHtml += '<div class="businessinfo">';
  // name/url
  infoWindowHtml += '<a href="'+loc.url+'">'+loc.name+'</a><br/>';
  // address
  infoWindowHtml += loc.street + ' ';
  // address2
  if(loc.street2.length) 
      infoWindowHtml += loc.street2+ ' ';
  // city, state and zip
  infoWindowHtml += loc.zip;
  // div end
  infoWindowHtml += '</div></div>';

  var icon = new GIcon(G_DEFAULT_ICON);
  icon.shadow = '';
  icon.infoWindowAnchor = new GPoint(-118,45);
  var marker = new GMarker(new GLatLng(loc.lat, loc.lon), icon);
  GEvent.addListener(marker, 'click', function(){ 
  	marker.openExtInfoWindow(
  		map,
  		"simple_example_window",
  		infoWindowHtml,
  		{beakOffset: 3}
  	); 
  });
  map.addOverlay(marker);
};

/*
 * Construct the URL to call for the API request
 */
function constructYelpURL(category) {
  if(category) {
    var mapBounds = map.getBounds();
  	var URL = "http://api.yelp.com/" +
  		"business_review_search?"+
  		"callback=" + "handleResults" +
  		"&category=" + category.replace('_',' ') + 
  		"&limit=25" + 
  		"&num_biz_requested=10" +
  		"&tl_lat=" + mapBounds.getSouthWest().lat() +
  		"&tl_long=" + mapBounds.getSouthWest().lng() + 
  		"&br_lat=" + mapBounds.getNorthEast().lat() + 
  		"&br_long=" + mapBounds.getNorthEast().lng() +
  		"&ywsid=" + YWSID;
  	return encodeURI(URL);
  }
}

/*
 * Called on the form submission: updates the map by
 * placing markers on it at the appropriate places
 */
function updateMap(categories) {
  for(marker in mapOverlays) {
      map.removeOverlay(mapOverlays[marker]);
  }
  
  for(term in categories) {
    $("li.loader").fadeIn('fast');

     var yelpRequestURL = constructYelpURL(categories[term]);

     /* do the api request */
     var script = document.createElement('script');
     script.src = yelpRequestURL;
     script.type = 'text/javascript';
     var head = document.getElementsByTagName('head').item(0);
     head.appendChild(script);
  }
  return false;
}


/*
 * If a sucessful API response is received, place
 * markers on the map.  If not, display an error.
 */
function handleResults(data) {
	$("li.loader").fadeOut('fast');
	
	if(data.message.text == "OK") {
		if (data.businesses.length == 0) {
			return;
		}
		for(var i=0; i<data.businesses.length; i++) {
			biz = data.businesses[i];
			createMarker(biz, new GLatLng(biz.latitude, biz.longitude), i);
		}
	} else {
	}
}

/*
 * Formats and returns the Info Window HTML 
 * (displayed in a balloon when a marker is clicked)
 */
function generateInfoWindowHtml(biz) {
    var text = '<div class="marker">';

    // image and rating
    // text += '<img class="businessimage" src="'+biz.photo_url+'"/>';

    // div start
    text += '<div class="businessinfo">';
    // name/url
    text += '<a href="'+biz.url+'" target="_blank">'+biz.name+'</a><br/>';
    // stars
    text += '<img class="ratingsimage" src="'+biz.rating_img_url_small+'"/>&nbsp;based&nbsp;on&nbsp;';
    // reviews
    text += biz.review_count + '&nbsp;reviews<br/><br />';
    // categories
    text += formatCategories(biz.categories);
    // neighborhoods
    if(biz.neighborhoods.length)
        text += formatNeighborhoods(biz.neighborhoods);
    // address
    text += biz.address1 + '<br/>';
    // address2
    if(biz.address2.length) 
        text += biz.address2+ '<br/>';
    // city, state and zip
    text += biz.city + ',&nbsp;' + biz.state + '&nbsp;' + biz.zip + '<br/>';
    // phone number
    if(biz.phone.length)
        text += formatPhoneNumber(biz.phone);
    // Read the reviews
    text += '<br/><a href="'+biz.url+'" target="_blank">Read the reviews »</a><br/>';
    // div end
    text += '</div></div>'
    return text;
}

/*
 * Formats the categories HTML
 */
function formatCategories(cats) {
	var s = 'Categories: ';
	for(var i=0; i<cats.length; i++) {
		s+= cats[i].name;
		if(i != cats.length-1) s += ', ';
	}
	s += '<br/>';
	return s;
}

/*
 * Formats the neighborhoods HTML
 */
function formatNeighborhoods(neighborhoods) {
	s = 'Neighborhoods: ';
	for(var i=0; i<neighborhoods.length; i++) {
		s += '<a href="' + neighborhoods[i].url + '" target="_blank">' + neighborhoods[i].name + '</a>';
		if (i != neighborhoods.length-1) s += ', ';
	}
	s += '<br/>';
	return s;
}

/*
 * Formats the phone number HTML
 */
function formatPhoneNumber(num) {
	if(num.length != 10) return '';
	return '(' + num.slice(0,3) + ') ' + num.slice(3,6) + '-' + num.slice(6,10) + '<br/>';
}

/*
 * Creates a marker for the given business and point
 */
function createMarker(biz, point, markerNum) {
	var infoWindowHtml = generateInfoWindowHtml(biz)
	var icon = new GIcon(G_DEFAULT_ICON);
	icon.image = '/images/mm_20_red.png';
	icon.shadow = '';
	icon.infoWindowAnchor = new GPoint(-118,45);
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, 'click', function(){ 
		marker.openExtInfoWindow(
			map,
			"simple_example_window",
			infoWindowHtml,
			{beakOffset: 3}
		); 
	});
	map.addOverlay(marker);
	mapOverlays.push(marker);
}

$(document).ready(function() {
	
	$('input[name=yelpSearch]').bind('change', function() {
	  var categories = new Array();
    $('input[name=yelpSearch]:checked').each(function() {
      categories.push($(this).val());
    });
    updateMap(categories);
	});
	
});
