
//<![CDATA[
var cm_map;
var cm_mapMarkers = [];
var cm_mapHTMLS = [];

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var cm_baseIcon = new GIcon();
cm_baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
cm_baseIcon.iconSize = new GSize(20, 34);
cm_baseIcon.shadowSize = new GSize(37, 34);
cm_baseIcon.iconAnchor = new GPoint(9, 34);
cm_baseIcon.infoWindowAnchor = new GPoint(9, 2);
cm_baseIcon.infoShadowAnchor = new GPoint(18, 25);

// Icon for Luncher
var cm_lunchIcon = new GIcon();
cm_lunchIcon.shadow = "/i/map/luncher_icon_shadow.png";
cm_lunchIcon.iconSize = new GSize(20, 39);
cm_lunchIcon.shadowSize = new GSize(40, 39);
cm_lunchIcon.iconAnchor = new GPoint(9, 34);
cm_lunchIcon.infoWindowAnchor = new GPoint(9, 2);
cm_lunchIcon.infoShadowAnchor = new GPoint(18, 25);


// Change these parameters to customize map
var param_wsId = "default";
//var param_ssKey = "pp3LMci9UjS4MwJEjJFO_Ww";
var param_useSidebar = true;
var param_titleColumn = "title";
var param_descriptionColumn = "description";
var param_xstreet = "xstreet";
var param_address = "address";
var param_zipcode = "zipcode";
var param_phone = "phone";
var param_link = "link";
var param_closed = "closed";
var param_latColumn = "latitude";
var param_lngColumn = "longitude";
var param_category = "category";
var param_iconType = "green";
var param_iconOverType = "orange";

var categories = new Array();
var categoryTitles = new Array();
var markers = new Array();

/**
 * Loads map and calls function to load in worksheet data.
 */
function cm_load() {  
  if (GBrowserIsCompatible()) {
    // create the map
    cm_map = new GMap2(document.getElementById("cm_map"));
    cm_map.addControl(new GLargeMapControl());
    cm_map.addControl(new GMapTypeControl());
    cm_map.setCenter(new GLatLng());
    cm_map.setZoom(14);
    cm_getJSON();
  } else {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  } 
}

/**
 * Function called when marker on the map is clicked.
 * Opens an info window (bubble) above the marker.
 * @param {Number} markerNum Number of marker in global array
 */
function cm_markerClicked(markerNum) {
  cm_mapMarkers[markerNum].openInfoWindowHtml(cm_mapHTMLS[markerNum]);
}

/**
 * Function that sorts 2 worksheet rows from JSON feed
 * based on their rank column. Only called if column is defined.
 * @param {rowA} Object Represents row in JSON feed
 * @param {rowB} Object Represents row in JSON feed
 * @return {Number} Difference between row values
 */
function cm_sortRows(rowA, rowB) {
    var x = rowA["gsx$" + param_titleColumn].$t.toLowerCase();
    var y = rowB["gsx$" + param_titleColumn].$t.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

/** 
 * Called when JSON is loaded. Creates sidebar if param_sideBar is true.
 * Sorts rows if param_rankColumn is valid column. Iterates through worksheet rows, 
 * creating marker and sidebar entries for each row.
 * @param {JSON} json Worksheet feed
 */       
function cm_loadMapJSON(json) {

  if (param_useSidebar == true) {
    var sidebarDIV = document.createElement("div");
    sidebarDIV.id = "cm_sidebarDIV";
    //sidebarDIV.style.overflow = "auto";
    //sidebarDIV.style.height = "200px";
    sidebarDIV.style.width = "515px";
    sidebarDIV.style.fontSize = "11px";
    sidebarDIV.style.color = "#000000";
    document.getElementById("categoryDIV").appendChild(sidebarDIV);
  }

  var bounds = new GLatLngBounds();

  json.feed.entry.sort(cm_sortRows);
      
   for (var i = 0; i < json.feed.entry.length; i++) {
    var entry = json.feed.entry[i];
    //test += entry["gsx$" + param_category].$t;
	if ((entry["gsx$" + param_latColumn].$t != "") && (entry["gsx$" + param_lngColumn].$t != "") && (entry["gsx$" + param_titleColumn].$t != "title")) {
		if (entry["gsx$" + param_closed].$t != "TRUE") {
			if (entry["gsx$" + param_category].$t != "Luncher") {
			  var lat = parseFloat(entry["gsx$" + param_latColumn].$t);
			  var lng = parseFloat(entry["gsx$" + param_lngColumn].$t);
			  var point = new GLatLng(lat,lng);
			  var label = entry["gsx$"+param_titleColumn].$t;
			  var html = "";
			  html += "<b style='font-size:1.3em;'>" + entry["gsx$"+param_titleColumn].$t + "</b><br/>";
			  if (entry["gsx$" + param_closed].$t == "TRUE") {
				html += "*** NOW CLOSED ***<br/>";
			  }
			  if (entry["gsx$" + param_address].$t != "") {
				html += "<br/>" + entry["gsx$"+param_address].$t;
			  }
			  if (entry["gsx$" + param_xstreet].$t != "") {
				html += "<br/>(" + entry["gsx$"+param_xstreet].$t + ")";
			  }
			  if (entry["gsx$" + param_phone].$t != "") {
				html += "<br/>" + entry["gsx$"+param_phone].$t;
			  }
			  if (entry["gsx$" + param_descriptionColumn].$t != "") {
				html += "<br/><br/>" + entry["gsx$"+param_descriptionColumn].$t;
			  }
			  if (entry["gsx$" + param_link].$t != "") {
				html += "<br/><br/><a href='" + entry["gsx$"+param_link].$t + "'>Read more...</a>";
			  } else {
				html += "<br/><br/>Review Coming Soon";
			  }
			  html += "<br/><br/><br/>";
			  
			  // create the marker
			  var marker = cm_createMarker(point,label,html);
			  cm_map.addOverlay(marker);
			  cm_mapMarkers.push(marker);
			  cm_mapHTMLS.push(html);
			  bounds.extend(point);
			  
			  //marker.hide();
			  
			  // add to categories array
			  var cat = entry["gsx$" + param_category].$t.split(",");
			  marker.whichCats = cat;
			  
			  for (j=0; j < cat.length; j++) {
				  if (typeof categories[cat[j]] == "undefined") {
					categories[cat[j]] = [];
					if (cat[j]) {
						categoryTitles[categoryTitles.length] = cat[j];
					}
				  }
				  categories[cat[j]].push(marker);
			  }
			} else {
			  var lat = parseFloat(entry["gsx$" + param_latColumn].$t);
			  var lng = parseFloat(entry["gsx$" + param_lngColumn].$t);
			  var point = new GLatLng(lat,lng);
			  var label = entry["gsx$"+param_titleColumn].$t;
			  var html = "";
			  html += "<b style='font-size:1.3em;'>Profiled Luncher</b><br/>";
			  if (entry["gsx$"+param_titleColumn].$t != "") {
				html += "<br/>Name: " + entry["gsx$"+param_titleColumn].$t;
			  }
			  if (entry["gsx$" + param_address].$t != "") {
				html += "<br/>Age: " + entry["gsx$"+param_address].$t;
			  }
			  if (entry["gsx$" + param_zipcode].$t != "") {
				html += "<br/>Workplace: " + entry["gsx$"+param_zipcode].$t;
			  }
			  if (entry["gsx$" + param_link].$t != "") {
				html += "<br/><br/><a href='" + entry["gsx$"+param_link].$t + "'>View profile</a>";
			  }
			  html += "<br/>";
			  
			  // create the marker
			  var marker = cm_createMarker(point,label,html,true);
			  cm_map.addOverlay(marker);
			  cm_mapMarkers.push(marker);
			  cm_mapHTMLS.push(html);
			  bounds.extend(point);
			  
			  if (param_city == "MNYC") {
			    marker.hide();
			  }
			  
			  // add to categories array
			  var cat = entry["gsx$" + param_category].$t.split(",");
			  marker.whichCats = cat;
			  
			  for (j=0; j < cat.length; j++) {
				  if (typeof categories[cat[j]] == "undefined") {
					categories[cat[j]] = [];
					if (cat[j]) {
						categoryTitles[categoryTitles.length] = cat[j];
					}
				  }
				  categories[cat[j]].push(marker);
			  }
			}
		}
	}
  }
			  
  cm_map.setZoom(cm_map.getBoundsZoomLevel(bounds));
  cm_map.setCenter(bounds.getCenter());
  
  
/* creates checkboxes by category */
	categoryTitles.sort();
	var checkboxes = "<form id='catForm'><br>&nbsp;<a href='javascript:checkAll(false);' style='color:#000; font-size: 1.3em;'>Uncheck All</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:checkAll(true);' style='color:#000; font-size: 1.3em;'>Check All</a><br><br>";
	checkboxes += "<div class='checkboxCol'>";
	var checkboxes2 = "";
	
	var subtractCategories = 0; //hack to pull out Luncher and Happy_Hour categories from the main checkbox section
	for(i=0; i < categoryTitles.length; i++) {
		if ((categoryTitles[i] == "Luncher") || (categoryTitles[i] == "Happy_Hour")) {
			subtractCategories++;
		}
	}
	
	var numCatsForColumns = categoryTitles.length - subtractCategories;
	var perColumn = Math.floor(numCatsForColumns / 3);
	var numLgColumns = numCatsForColumns % 3;
	var numCols = 1;
	var counter;
	var numInCurCol = 1;
	for(i=0; i < categoryTitles.length; i++) {
		if  ((categoryTitles[i] != "Luncher") && (categoryTitles[i] != "Happy_Hour")) {
			if (numCols <= numLgColumns) {
				counter = perColumn + 1;
			} else {
				counter = perColumn;
			}
			if (categoryTitles[i] && (categoryTitles[i] != "category")) {
				var newTit = "";
				for (j=0; j<categoryTitles[i].length; j++) {
					if (categoryTitles[i].charAt(j) == "_") {
						newTit += " ";
					} else {
						newTit += categoryTitles[i].charAt(j);
					}
				}
				checkboxes += "<input type='checkbox' onclick='toggleMarkers(\"" + categoryTitles[i] + "\");' id='" + categoryTitles[i] + "' name='" + categoryTitles[i] + "' checked style='vertical-align:middle;'><label for='" + categoryTitles[i] + "' class='checkLabel'>&nbsp;" + newTit + "</label><br>";
			}
			if (((numInCurCol % counter) == 0) && (numInCurCol>0)) {
				checkboxes += "</div>";
				if (numCols < 3) {
					checkboxes += "<div class='checkboxCol checkboxMar'>";
				}
				numCols++;
				numInCurCol = 1;
			} else {
				numInCurCol++;
			}
		} else {
			var newTit = "";
			var isChecked = "checked";
			if (categoryTitles[i] == "Luncher") {
				newTit = "Profiled Luncher";
			} else {
				for (j=0; j<categoryTitles[i].length; j++) {
					if (categoryTitles[i].charAt(j) == "_") {
						newTit += " ";
					} else {
						newTit += categoryTitles[i].charAt(j);
					}
				}
			}
			if ((param_city == "MNYC") && ((categoryTitles[i] == "Luncher") || (categoryTitles[i] == "Happy_Hour"))) {
				isChecked = "";
			}
			checkboxes2 += "<div class='checkboxCol checkboxMar'>&nbsp;</div><div class='checkboxCol'><input type='checkbox' onclick='toggleMarkers(\"" + categoryTitles[i] + "\");' id='" + categoryTitles[i] + "' name='" + categoryTitles[i] + "' " + isChecked + " style='vertical-align:middle;'><label for='" + categoryTitles[i] + "' class='checkLabel'>&nbsp;" + newTit + "</label><br></div>";
		}
	}
	checkboxes += "<div class='clear'></div><br/>" +  checkboxes2 + "</form>";
	sidebarDIV.innerHTML = checkboxes + "<div class='clear'></div><br/><br/>";
}

function toggleMarkers(which) {
	//alert(document.forms["catForm"].elements.length);
	for (i=0; i < categories[which].length; i++) {
		var toShow = false;
		var marker = categories[which][i];
		for (j=0; j < marker.whichCats.length; j++) {
			if (document.forms["catForm"].elements[marker.whichCats[j]].checked) {
				toShow = true;
			}
		}
		if (toShow) {
			marker.show();
		} else {
			marker.hide();
		}
	}
}

function checkAll(which) {
	for (i=0; i < document.forms["catForm"].elements.length; i++) {
		document.forms["catForm"][i].checked = which;
	}
	for (j=0; j < categoryTitles.length; j++) {
		for (k=0; k < categories[categoryTitles[j]].length; k++) {
			var marker = categories[categoryTitles[j]][k];
			if (which) {
				marker.show();
			} else {
				marker.hide();
			}
		}
	}
}


/**
 * Creates marker with ranked Icon or blank icon,
 * depending if rank is defined. Assigns onclick function.
 * @param {GLatLng} point Point to create marker at
 * @param {String} title Tooltip title to display for marker
 * @param {String} html HTML to display in InfoWindow
 * @param {Number} rank Number rank of marker, used in creating icon
 * @return {GMarker} Marker created
 */
function cm_createMarker(point, title, html, luncher) {
  var markerOpts = {};
  if (!luncher) {
  	var nIcon = new GIcon(cm_baseIcon);
    nIcon.imageOut = "http://gmaps-samples.googlecode.com/svn/trunk/" +
        "markers/" + param_iconType + "/blank.png";
    nIcon.imageOver = "http://gmaps-samples.googlecode.com/svn/trunk/" +
        "markers/" + param_iconOverType + "/blank.png";
    nIcon.image = nIcon.imageOut;
  } else {
	var nIcon = new GIcon(cm_lunchIcon);
    nIcon.imageOut = "/i/map/luncher_icon.png";
    nIcon.imageOver = "/i/map/luncher_icon.png";
    nIcon.image = nIcon.imageOut;
  }
  markerOpts.icon = nIcon;
  markerOpts.title = title;
 
  var marker = new GMarker(point, markerOpts);
	
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html, {maxWidth:250});
  });
  GEvent.addListener(marker, "mouseover", function() {
    marker.setImage(marker.getIcon().imageOver);
  });
  GEvent.addListener(marker, "mouseout", function() {
    marker.setImage(marker.getIcon().imageOut);
  });
  GEvent.addListener(marker, "infowindowopen", function() {
    marker.setImage(marker.getIcon().imageOver);
  });
  GEvent.addListener(marker, "infowindowclose", function() {
    marker.setImage(marker.getIcon().imageOut);
  });
  return marker;
}

/**
 * Creates a script tag in the page that loads in the 
 * JSON feed for the specified key/ID. 
 * Once loaded, it calls cm_loadMapJSON.
 */
function cm_getJSON() {

  // Retrieve the JSON feed.
  var script = document.createElement('script');

  script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list'
                         + '/' + param_ssKey + '/' + param_wsId + '/public/values' +
                        '?alt=json-in-script&callback=cm_loadMapJSON');
  script.setAttribute('id', 'jsonScript');
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
}

setTimeout('cm_load()', 500);

//]]>


